8 /* dscache.c - Disk store cache for disk store backend. 
  10  * When Redis is configured for using disk as backend instead of memory, the 
  11  * memory is used as a cache, so that recently accessed keys are taken in 
  12  * memory for fast read and write operations. 
  14  * Modified keys are marked to be flushed on disk, and will be flushed 
  15  * as long as the maxium configured flush time elapsed. 
  17  * This file implements the whole caching subsystem and contains further 
  22  * - The WATCH helper will be used to signal the cache system 
  23  *   we need to flush a given key/dbid into disk, adding this key/dbid 
  24  *   pair into a server.ds_cache_dirty linked list AND hash table (so that we 
  25  *   don't add the same thing multiple times). 
  27  * - cron() checks if there are elements on this list. When there are things 
  28  *   to flush, we create an IO Job for the I/O thread. 
  29  *   NOTE: We disalbe object sharing when server.ds_enabled == 1 so objects 
  30  *   that are referenced an IO job for flushing on disk are marked as 
  31  *   o->storage == REDIS_DS_SAVING. 
  33  * - This is what we do on key lookup: 
  34  *   1) The key already exists in memory. object->storage == REDIS_DS_MEMORY 
  35  *      or it is object->storage == REDIS_DS_DIRTY: 
  36  *      We don't do nothing special, lookup, return value object pointer. 
  37  *   2) The key is in memory but object->storage == REDIS_DS_SAVING. 
  38  *      When this happens we block waiting for the I/O thread to process 
  39  *      this object. Then continue. 
  40  *   3) The key is not in memory. We block to load the key from disk. 
  41  *      Of course the key may not be present at all on the disk store as well, 
  42  *      in such case we just detect this condition and continue, returning 
  45  * - Preloading of needed keys: 
  46  *   1) As it was done with VM, also with this new system we try preloading 
  47  *      keys a client is going to use. We block the client, load keys 
  48  *      using the I/O thread, unblock the client. Same code as VM more or less. 
  50  * - Reclaiming memory. 
  51  *   In cron() we detect our memory limit was reached. What we 
  52  *   do is deleting keys that are REDIS_DS_MEMORY, using LRU. 
  54  *   If this is not enough to return again under the memory limits we also 
  55  *   start to flush keys that need to be synched on disk synchronously, 
  56  *   removing it from the memory. We do this blocking as memory limit is a 
  57  *   much "harder" barrirer in the new design. 
  59  * - IO thread operations are no longer stopped for sync loading/saving of 
  60  *   things. When a key is found to be in the process of being saved 
  61  *   we simply wait for the IO thread to end its work. 
  63  *   Otherwise if there is to load a key without any IO thread operation 
  64  *   just started it is blocking-loaded in the lookup function. 
  66  * - What happens when an object is destroyed? 
  68  *   If o->storage == REDIS_DS_MEMORY then we simply destory the object. 
  69  *   If o->storage == REDIS_DS_DIRTY we can still remove the object. It had 
  70  *                    changes not flushed on disk, but is being removed so 
  72  *   if o->storage == REDIS_DS_SAVING then the object is being saved so 
  73  *                    it is impossible that its refcount == 1, must be at 
  74  *                    least two. When the object is saved the storage will 
  75  *                    be set back to DS_MEMORY. 
  77  * - What happens when keys are deleted? 
  79  *   We simply schedule a key flush operation as usually, but when the 
  80  *   IO thread will be created the object pointer will be set to NULL 
  81  *   so the IO thread will know that the work to do is to delete the key 
  82  *   from the disk store. 
  84  * - What happens with MULTI/EXEC? 
  88  * - If dsSet() fails on the write thread log the error and reschedule the 
  91  * - Check why INCR will not update the LRU info for the object. 
  93  * - Fix/Check the following race condition: a key gets a DEL so there is 
  94  *   a write operation scheduled against this key. Later the same key will 
  95  *   be the argument of a GET, but the write operation was still not 
  96  *   completed (to delete the file). If the GET will be for some reason 
  97  *   a blocking loading (via lookup) we can load the old value on memory. 
  99  *   This problems can be fixed with negative caching. We can use it 
 100  *   to optimize the system, but also when a key is deleted we mark 
 101  *   it as non existing on disk as well (in a way that this cache 
 102  *   entry can't be evicted, setting time to 0), then we avoid looking at 
 103  *   the disk at all if the key can't be there. When an IO Job complete 
 104  *   a deletion, we set the time of the negative caching to a non zero 
 105  *   value so it will be evicted later. 
 107  *   Are there other patterns like this where we load stale data? 
 109  *   Also, make sure that key preloading is ONLY done for keys that are 
 110  *   not marked as cacheKeyDoesNotExist(), otherwise, again, we can load 
 111  *   data from disk that should instead be deleted. 
 113  * - dsSet() use rename(2) in order to avoid corruptions. 
 116 /* Virtual Memory is composed mainly of two subsystems: 
 117  * - Blocking Virutal Memory 
 118  * - Threaded Virtual Memory I/O 
 119  * The two parts are not fully decoupled, but functions are split among two 
 120  * different sections of the source code (delimited by comments) in order to 
 121  * make more clear what functionality is about the blocking VM and what about 
 122  * the threaded (not blocking) VM. 
 126  * Redis VM is a blocking VM (one that blocks reading swapped values from 
 127  * disk into memory when a value swapped out is needed in memory) that is made 
 128  * unblocking by trying to examine the command argument vector in order to 
 129  * load in background values that will likely be needed in order to exec 
 130  * the command. The command is executed only once all the relevant keys 
 131  * are loaded into memory. 
 133  * This basically is almost as simple of a blocking VM, but almost as parallel 
 134  * as a fully non-blocking VM. 
 137 void spawnIOThread(void); 
 139 /* =================== Virtual Memory - Blocking Side  ====================== */ 
 145     zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */ 
 147     redisLog(REDIS_NOTICE
,"Opening Disk Store: %s", server
.ds_path
); 
 148     /* Open Disk Store */ 
 149     if (dsOpen() != REDIS_OK
) { 
 150         redisLog(REDIS_WARNING
,"Fatal error opening disk store. Exiting."); 
 154     /* Initialize threaded I/O for Object Cache */ 
 155     server
.io_newjobs 
= listCreate(); 
 156     server
.io_processing 
= listCreate(); 
 157     server
.io_processed 
= listCreate(); 
 158     server
.io_ready_clients 
= listCreate(); 
 159     pthread_mutex_init(&server
.io_mutex
,NULL
); 
 160     pthread_cond_init(&server
.io_condvar
,NULL
); 
 161     server
.io_active_threads 
= 0; 
 162     if (pipe(pipefds
) == -1) { 
 163         redisLog(REDIS_WARNING
,"Unable to intialized DS: pipe(2): %s. Exiting." 
 167     server
.io_ready_pipe_read 
= pipefds
[0]; 
 168     server
.io_ready_pipe_write 
= pipefds
[1]; 
 169     redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
); 
 170     /* LZF requires a lot of stack */ 
 171     pthread_attr_init(&server
.io_threads_attr
); 
 172     pthread_attr_getstacksize(&server
.io_threads_attr
, &stacksize
); 
 174     /* Solaris may report a stacksize of 0, let's set it to 1 otherwise 
 175      * multiplying it by 2 in the while loop later will not really help ;) */ 
 176     if (!stacksize
) stacksize 
= 1; 
 178     while (stacksize 
< REDIS_THREAD_STACK_SIZE
) stacksize 
*= 2; 
 179     pthread_attr_setstacksize(&server
.io_threads_attr
, stacksize
); 
 180     /* Listen for events in the threaded I/O pipe */ 
 181     if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
, 
 182         vmThreadedIOCompletedJob
, NULL
) == AE_ERR
) 
 183         oom("creating file event"); 
 185     /* Spawn our I/O thread */ 
 189 /* Compute how good candidate the specified object is for eviction. 
 190  * An higher number means a better candidate. */ 
 191 double computeObjectSwappability(robj 
*o
) { 
 192     /* actual age can be >= minage, but not < minage. As we use wrapping 
 193      * 21 bit clocks with minutes resolution for the LRU. */ 
 194     return (double) estimateObjectIdleTime(o
); 
 197 /* Try to free one entry from the diskstore object cache */ 
 198 int cacheFreeOneEntry(void) { 
 200     struct dictEntry 
*best 
= NULL
; 
 201     double best_swappability 
= 0; 
 202     redisDb 
*best_db 
= NULL
; 
 206     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 207         redisDb 
*db 
= server
.db
+j
; 
 208         /* Why maxtries is set to 100? 
 209          * Because this way (usually) we'll find 1 object even if just 1% - 2% 
 210          * are swappable objects */ 
 213         if (dictSize(db
->dict
) == 0) continue; 
 214         for (i 
= 0; i 
< 5; i
++) { 
 218             if (maxtries
) maxtries
--; 
 219             de 
= dictGetRandomKey(db
->dict
); 
 220             val 
= dictGetEntryVal(de
); 
 221             /* Only swap objects that are currently in memory. 
 223              * Also don't swap shared objects: not a good idea in general and 
 224              * we need to ensure that the main thread does not touch the 
 225              * object while the I/O thread is using it, but we can't 
 226              * control other keys without adding additional mutex. */ 
 227             if (val
->storage 
!= REDIS_DS_MEMORY
) { 
 228                 if (maxtries
) i
--; /* don't count this try */ 
 231             swappability 
= computeObjectSwappability(val
); 
 232             if (!best 
|| swappability 
> best_swappability
) { 
 234                 best_swappability 
= swappability
; 
 240         /* FIXME: If there are objects marked as DS_DIRTY or DS_SAVING 
 241          * let's wait for this objects to be clear and retry... 
 243          * Object cache vm limit is considered an hard limit. */ 
 246     key 
= dictGetEntryKey(best
); 
 247     val 
= dictGetEntryVal(best
); 
 249     redisLog(REDIS_DEBUG
,"Key selected for cache eviction: %s swappability:%f", 
 250         key
, best_swappability
); 
 252     /* Delete this key from memory */ 
 254         robj 
*kobj 
= createStringObject(key
,sdslen(key
)); 
 255         dbDelete(best_db
,kobj
); 
 261 /* Return true if it's safe to swap out objects in a given moment. 
 262  * Basically we don't want to swap objects out while there is a BGSAVE 
 263  * or a BGAEOREWRITE running in backgroud. */ 
 264 int dsCanTouchDiskStore(void) { 
 265     return (server
.bgsavechildpid 
== -1 && server
.bgrewritechildpid 
== -1); 
 268 /* ==================== Disk store negative caching  ======================== 
 270  * When disk store is enabled, we need negative caching, that is, to remember 
 271  * keys that are for sure *not* on the disk key-value store. 
 273  * This is useful for two reasons: 
 275  * 1) Without negative caching cache misses will cost us a disk lookup, even 
 276  *    if the same non existing key is accessed again and again. We negative 
 277  *    caching we remember that the key is not on disk, so if it's not in memory 
 278  *    and we have a negative cache entry, we don't try a disk access at all. 
 280  * 2) Negative caching is the way to fix a specific race condition. For instance 
 281  *    think at the following sequence of commands: 
 287  *    After the SET, we'll mark the value as dirty, so it will be flushed 
 288  *    on disk at some time. Later the key is deleted, so will be removed 
 289  *    from memory. Another job will be created to remove the key from the disk 
 290  *    store, but the removal is not synchronous, so may happen later in time. 
 292  *    Finally we have a GET foo operation. This operation may result in 
 293  *    reading back a value from disk that is not updated data, as the deletion 
 294  *    operaiton against the disk KV store was still not completed, so we 
 297  * Remembering that the given key is deleted is important. We can discard this 
 298  * information once the key was really removed from the disk. 
 300  * So actually there are two kind of negative caching entries: entries that 
 301  * can be evicted when we need to reclaim memory, and entries that will 
 302  * not be evicted, for all the time we need this information to be available. 
 304  * The API allows to create both kind of negative caching. */ 
 306 int cacheKeyMayExist(redisDb 
*db
, robj 
*key
) { 
 307     return dictFind(db
->io_negcache
,key
) == NULL
; 
 310 void cacheSetKeyMayExist(redisDb 
*db
, robj 
*key
) { 
 311     dictDelete(db
->io_negcache
,key
); 
 314 void cacheSetKeyDoesNotExist(redisDb 
*db
, robj 
*key
) { 
 315     struct dictEntry 
*de
; 
 317     /* Don't overwrite negative cached entries with val set to 0, as this 
 318      * entries were created with cacheSetKeyDoesNotExistRemember(). */ 
 319     de 
= dictFind(db
->io_negcache
,key
); 
 320     if (de 
!= NULL 
&& dictGetEntryVal(de
) == NULL
) return; 
 322     if (dictReplace(db
->io_negcache
,key
,(void*)time(NULL
))) { 
 327 void cacheSetKeyDoesNotExistRemember(redisDb 
*db
, robj 
*key
) { 
 328     if (dictReplace(db
->io_negcache
,key
,NULL
)) { 
 333 /* ================== Disk store cache - Threaded I/O  ====================== */ 
 335 void freeIOJob(iojob 
*j
) { 
 336     decrRefCount(j
->key
); 
 337     /* j->val can be NULL if the job is about deleting the key from disk. */ 
 338     if (j
->val
) decrRefCount(j
->val
); 
 342 /* Every time a thread finished a Job, it writes a byte into the write side 
 343  * of an unix pipe in order to "awake" the main thread, and this function 
 345 void vmThreadedIOCompletedJob(aeEventLoop 
*el
, int fd
, void *privdata
, 
 349     int retval
, processed 
= 0, toprocess 
= -1; 
 352     REDIS_NOTUSED(privdata
); 
 354     /* For every byte we read in the read side of the pipe, there is one 
 355      * I/O job completed to process. */ 
 356     while((retval 
= read(fd
,buf
,1)) == 1) { 
 360         redisLog(REDIS_DEBUG
,"Processing I/O completed job"); 
 362         /* Get the processed element (the oldest one) */ 
 364         redisAssert(listLength(server
.io_processed
) != 0); 
 365         if (toprocess 
== -1) { 
 366             toprocess 
= (listLength(server
.io_processed
)*REDIS_MAX_COMPLETED_JOBS_PROCESSED
)/100; 
 367             if (toprocess 
<= 0) toprocess 
= 1; 
 369         ln 
= listFirst(server
.io_processed
); 
 371         listDelNode(server
.io_processed
,ln
); 
 374         /* Post process it in the main thread, as there are things we 
 375          * can do just here to avoid race conditions and/or invasive locks */ 
 376         redisLog(REDIS_DEBUG
,"COMPLETED Job type %s, key: %s", 
 377             (j
->type 
== REDIS_IOJOB_LOAD
) ? "load" : "save", 
 378             (unsigned char*)j
->key
->ptr
); 
 379         if (j
->type 
== REDIS_IOJOB_LOAD
) { 
 380             /* Create the key-value pair in the in-memory database */ 
 381             if (j
->val 
!= NULL
) { 
 382                 /* Note: the key may already be here if between the time 
 383                  * this key loading was scheduled and now there was the 
 384                  * need to blocking load the key for a key lookup. 
 386                  * Also we don't add a key that was deleted in the 
 387                  * meantime and should not be on disk either. */ 
 388                 if (cacheKeyMayExist(j
->db
,j
->key
) && 
 389                     dbAdd(j
->db
,j
->key
,j
->val
) == REDIS_OK
) 
 391                     incrRefCount(j
->val
); 
 392                     if (j
->expire 
!= -1) setExpire(j
->db
,j
->key
,j
->expire
); 
 395                 /* The key does not exist. Create a negative cache entry 
 397                 cacheSetKeyDoesNotExist(j
->db
,j
->key
); 
 399             /* Handle clients waiting for this key to be loaded. */ 
 400             handleClientsBlockedOnSwappedKey(j
->db
,j
->key
); 
 402         } else if (j
->type 
== REDIS_IOJOB_SAVE
) { 
 404                 redisAssert(j
->val
->storage 
== REDIS_DS_SAVING
); 
 405                 j
->val
->storage 
= REDIS_DS_MEMORY
; 
 406                 cacheSetKeyMayExist(j
->db
,j
->key
); 
 408                 /* Key deleted. Probably we have this key marked as 
 409                  * non existing, and impossible to evict, in our negative 
 410                  * cache entry. Add it as a normal negative cache entry. */ 
 411                 cacheSetKeyMayExist(j
->db
,j
->key
); 
 416         if (processed 
== toprocess
) return; 
 418     if (retval 
< 0 && errno 
!= EAGAIN
) { 
 419         redisLog(REDIS_WARNING
, 
 420             "WARNING: read(2) error in vmThreadedIOCompletedJob() %s", 
 425 void lockThreadedIO(void) { 
 426     pthread_mutex_lock(&server
.io_mutex
); 
 429 void unlockThreadedIO(void) { 
 430     pthread_mutex_unlock(&server
.io_mutex
); 
 433 void *IOThreadEntryPoint(void *arg
) { 
 438     pthread_detach(pthread_self()); 
 441         /* Get a new job to process */ 
 442         if (listLength(server
.io_newjobs
) == 0) { 
 443             /* Wait for more work to do */ 
 444             pthread_cond_wait(&server
.io_condvar
,&server
.io_mutex
); 
 447         redisLog(REDIS_DEBUG
,"%ld IO jobs to process", 
 448             listLength(server
.io_newjobs
)); 
 449         ln 
= listFirst(server
.io_newjobs
); 
 451         listDelNode(server
.io_newjobs
,ln
); 
 452         /* Add the job in the processing queue */ 
 453         listAddNodeTail(server
.io_processing
,j
); 
 454         ln 
= listLast(server
.io_processing
); /* We use ln later to remove it */ 
 457         redisLog(REDIS_DEBUG
,"Thread %ld: new job type %s: %p about key '%s'", 
 458             (long) pthread_self(), 
 459             (j
->type 
== REDIS_IOJOB_LOAD
) ? "load" : "save", 
 460             (void*)j
, (char*)j
->key
->ptr
); 
 462         /* Process the Job */ 
 463         if (j
->type 
== REDIS_IOJOB_LOAD
) { 
 466             j
->val 
= dsGet(j
->db
,j
->key
,&expire
); 
 467             if (j
->val
) j
->expire 
= expire
; 
 468         } else if (j
->type 
== REDIS_IOJOB_SAVE
) { 
 470                 redisAssert(j
->val
->storage 
== REDIS_DS_SAVING
); 
 471                 dsSet(j
->db
,j
->key
,j
->val
); 
 477         /* Done: insert the job into the processed queue */ 
 478         redisLog(REDIS_DEBUG
,"Thread %ld completed the job: %p (key %s)", 
 479             (long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
); 
 482         listDelNode(server
.io_processing
,ln
); 
 483         listAddNodeTail(server
.io_processed
,j
); 
 485         /* Signal the main thread there is new stuff to process */ 
 486         redisAssert(write(server
.io_ready_pipe_write
,"x",1) == 1); 
 488     /* never reached, but that's the full pattern... */ 
 493 void spawnIOThread(void) { 
 495     sigset_t mask
, omask
; 
 499     sigaddset(&mask
,SIGCHLD
); 
 500     sigaddset(&mask
,SIGHUP
); 
 501     sigaddset(&mask
,SIGPIPE
); 
 502     pthread_sigmask(SIG_SETMASK
, &mask
, &omask
); 
 503     while ((err 
= pthread_create(&thread
,&server
.io_threads_attr
,IOThreadEntryPoint
,NULL
)) != 0) { 
 504         redisLog(REDIS_WARNING
,"Unable to spawn an I/O thread: %s", 
 508     pthread_sigmask(SIG_SETMASK
, &omask
, NULL
); 
 509     server
.io_active_threads
++; 
 512 /* Wait that all the pending IO Jobs are processed */ 
 513 void waitEmptyIOJobsQueue(void) { 
 515         int io_processed_len
; 
 518         if (listLength(server
.io_newjobs
) == 0 && 
 519             listLength(server
.io_processing
) == 0) 
 524         /* If there are new jobs we need to signal the thread to 
 525          * process the next one. */ 
 526         redisLog(REDIS_DEBUG
,"waitEmptyIOJobsQueue: new %d, processing %d", 
 527             listLength(server
.io_newjobs
), 
 528             listLength(server
.io_processing
)); 
 530         if (listLength(server.io_newjobs)) { 
 531             pthread_cond_signal(&server.io_condvar); 
 534         /* While waiting for empty jobs queue condition we post-process some 
 535          * finshed job, as I/O threads may be hanging trying to write against 
 536          * the io_ready_pipe_write FD but there are so much pending jobs that 
 538         io_processed_len 
= listLength(server
.io_processed
); 
 540         if (io_processed_len
) { 
 541             vmThreadedIOCompletedJob(NULL
,server
.io_ready_pipe_read
, 
 542                                                         (void*)0xdeadbeef,0); 
 543             usleep(1000); /* 1 millisecond */ 
 545             usleep(10000); /* 10 milliseconds */ 
 550 /* Process all the IO Jobs already completed by threads but still waiting 
 551  * processing from the main thread. */ 
 552 void processAllPendingIOJobs(void) { 
 554         int io_processed_len
; 
 557         io_processed_len 
= listLength(server
.io_processed
); 
 559         if (io_processed_len 
== 0) return; 
 560         vmThreadedIOCompletedJob(NULL
,server
.io_ready_pipe_read
, 
 561                                                     (void*)0xdeadbeef,0); 
 565 /* This function must be called while with threaded IO locked */ 
 566 void queueIOJob(iojob 
*j
) { 
 567     redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n", 
 568         (void*)j
, j
->type
, (char*)j
->key
->ptr
); 
 569     listAddNodeTail(server
.io_newjobs
,j
); 
 570     if (server
.io_active_threads 
< server
.vm_max_threads
) 
 574 void dsCreateIOJob(int type
, redisDb 
*db
, robj 
*key
, robj 
*val
) { 
 577     j 
= zmalloc(sizeof(*j
)); 
 583     if (val
) incrRefCount(val
); 
 587     pthread_cond_signal(&server
.io_condvar
); 
 591 void cacheScheduleForFlush(redisDb 
*db
, robj 
*key
) { 
 595     de 
= dictFind(db
->dict
,key
->ptr
); 
 597         robj 
*val 
= dictGetEntryVal(de
); 
 598         if (val
->storage 
== REDIS_DS_DIRTY
) 
 601             val
->storage 
= REDIS_DS_DIRTY
; 
 604     redisLog(REDIS_DEBUG
,"Scheduling key %s for saving (%s)",key
->ptr
, 
 605         de 
? "key exists" : "key does not exist"); 
 606     dk 
= zmalloc(sizeof(*dk
)); 
 610     dk
->ctime 
= time(NULL
); 
 611     listAddNodeTail(server
.cache_flush_queue
, dk
); 
 614 void cacheCron(void) { 
 615     time_t now 
= time(NULL
); 
 617     int jobs
, topush 
= 0; 
 619     /* Sync stuff on disk, but only if we have less than 100 IO jobs */ 
 621     jobs 
= listLength(server
.io_newjobs
); 
 625     if (topush 
< 0) topush 
= 0; 
 627     while((ln 
= listFirst(server
.cache_flush_queue
)) != NULL
) { 
 628         dirtykey 
*dk 
= ln
->value
; 
 633         if ((now 
- dk
->ctime
) >= server
.cache_flush_delay
) { 
 634             struct dictEntry 
*de
; 
 637             redisLog(REDIS_DEBUG
,"Creating IO Job to save key %s",dk
->key
->ptr
); 
 639             /* Lookup the key, in order to put the current value in the IO 
 640              * Job and mark it as DS_SAVING. 
 641              * Otherwise if the key does not exists we schedule a disk store 
 642              * delete operation, setting the value to NULL. */ 
 643             de 
= dictFind(dk
->db
->dict
,dk
->key
->ptr
); 
 645                 val 
= dictGetEntryVal(de
); 
 646                 redisAssert(val
->storage 
== REDIS_DS_DIRTY
); 
 647                 val
->storage 
= REDIS_DS_SAVING
; 
 649                 /* Setting the value to NULL tells the IO thread to delete 
 650                  * the key on disk. */ 
 653             dsCreateIOJob(REDIS_IOJOB_SAVE
,dk
->db
,dk
->key
,val
); 
 654             listDelNode(server
.cache_flush_queue
,ln
); 
 655             decrRefCount(dk
->key
); 
 658             break; /* too early */ 
 662     /* Reclaim memory from the object cache */ 
 663     while (server
.ds_enabled 
&& zmalloc_used_memory() > 
 664             server
.cache_max_memory
) 
 666         if (cacheFreeOneEntry() == REDIS_ERR
) break; 
 670 /* ============ Virtual Memory - Blocking clients on missing keys =========== */ 
 672 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded. 
 673  * If the key is already in memory we don't need to block, regardless 
 674  * of the storage of the value object for this key: 
 676  * - If it's REDIS_DS_MEMORY we have the key in memory. 
 677  * - If it's REDIS_DS_DIRTY they key was modified, but still in memory. 
 678  * - if it's REDIS_DS_SAVING the key is being saved by an IO Job. When 
 679  *   the client will lookup the key it will block if the key is still 
 680  *   in this stage but it's more or less the best we can do. 
 682  *   FIXME: we should try if it's actually better to suspend the client 
 683  *   accessing an object that is being saved, and awake it only when 
 684  *   the saving was completed. 
 686  * Otherwise if the key is not in memory, we block the client and start 
 687  * an IO Job to load it: 
 689  * the key is added to the io_keys list in the client structure, and also 
 690  * in the hash table mapping swapped keys to waiting clients, that is, 
 691  * server.io_waited_keys. */ 
 692 int waitForSwappedKey(redisClient 
*c
, robj 
*key
) { 
 693     struct dictEntry 
*de
; 
 696     /* Return ASAP if the key is in memory */ 
 697     de 
= dictFind(c
->db
->dict
,key
->ptr
); 
 698     if (de 
!= NULL
) return 0; 
 700     /* Don't wait for keys we are sure are not on disk either */ 
 701     if (!cacheKeyMayExist(c
->db
,key
)) return 0; 
 703     /* Add the key to the list of keys this client is waiting for. 
 704      * This maps clients to keys they are waiting for. */ 
 705     listAddNodeTail(c
->io_keys
,key
); 
 708     /* Add the client to the swapped keys => clients waiting map. */ 
 709     de 
= dictFind(c
->db
->io_keys
,key
); 
 713         /* For every key we take a list of clients blocked for it */ 
 715         retval 
= dictAdd(c
->db
->io_keys
,key
,l
); 
 717         redisAssert(retval 
== DICT_OK
); 
 719         l 
= dictGetEntryVal(de
); 
 721     listAddNodeTail(l
,c
); 
 723     /* Are we already loading the key from disk? If not create a job */ 
 725         dsCreateIOJob(REDIS_IOJOB_LOAD
,c
->db
,key
,NULL
); 
 729 /* Preload keys for any command with first, last and step values for 
 730  * the command keys prototype, as defined in the command table. */ 
 731 void waitForMultipleSwappedKeys(redisClient 
*c
, struct redisCommand 
*cmd
, int argc
, robj 
**argv
) { 
 733     if (cmd
->vm_firstkey 
== 0) return; 
 734     last 
= cmd
->vm_lastkey
; 
 735     if (last 
< 0) last 
= argc
+last
; 
 736     for (j 
= cmd
->vm_firstkey
; j 
<= last
; j 
+= cmd
->vm_keystep
) { 
 737         redisAssert(j 
< argc
); 
 738         waitForSwappedKey(c
,argv
[j
]); 
 742 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands. 
 743  * Note that the number of keys to preload is user-defined, so we need to 
 744  * apply a sanity check against argc. */ 
 745 void zunionInterBlockClientOnSwappedKeys(redisClient 
*c
, struct redisCommand 
*cmd
, int argc
, robj 
**argv
) { 
 749     num 
= atoi(argv
[2]->ptr
); 
 750     if (num 
> (argc
-3)) return; 
 751     for (i 
= 0; i 
< num
; i
++) { 
 752         waitForSwappedKey(c
,argv
[3+i
]); 
 756 /* Preload keys needed to execute the entire MULTI/EXEC block. 
 758  * This function is called by blockClientOnSwappedKeys when EXEC is issued, 
 759  * and will block the client when any command requires a swapped out value. */ 
 760 void execBlockClientOnSwappedKeys(redisClient 
*c
, struct redisCommand 
*cmd
, int argc
, robj 
**argv
) { 
 762     struct redisCommand 
*mcmd
; 
 768     if (!(c
->flags 
& REDIS_MULTI
)) return; 
 769     for (i 
= 0; i 
< c
->mstate
.count
; i
++) { 
 770         mcmd 
= c
->mstate
.commands
[i
].cmd
; 
 771         margc 
= c
->mstate
.commands
[i
].argc
; 
 772         margv 
= c
->mstate
.commands
[i
].argv
; 
 774         if (mcmd
->vm_preload_proc 
!= NULL
) { 
 775             mcmd
->vm_preload_proc(c
,mcmd
,margc
,margv
); 
 777             waitForMultipleSwappedKeys(c
,mcmd
,margc
,margv
); 
 782 /* Is this client attempting to run a command against swapped keys? 
 783  * If so, block it ASAP, load the keys in background, then resume it. 
 785  * The important idea about this function is that it can fail! If keys will 
 786  * still be swapped when the client is resumed, this key lookups will 
 787  * just block loading keys from disk. In practical terms this should only 
 788  * happen with SORT BY command or if there is a bug in this function. 
 790  * Return 1 if the client is marked as blocked, 0 if the client can 
 791  * continue as the keys it is going to access appear to be in memory. */ 
 792 int blockClientOnSwappedKeys(redisClient 
*c
, struct redisCommand 
*cmd
) { 
 793     if (cmd
->vm_preload_proc 
!= NULL
) { 
 794         cmd
->vm_preload_proc(c
,cmd
,c
->argc
,c
->argv
); 
 796         waitForMultipleSwappedKeys(c
,cmd
,c
->argc
,c
->argv
); 
 799     /* If the client was blocked for at least one key, mark it as blocked. */ 
 800     if (listLength(c
->io_keys
)) { 
 801         c
->flags 
|= REDIS_IO_WAIT
; 
 802         aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
); 
 803         server
.cache_blocked_clients
++; 
 810 /* Remove the 'key' from the list of blocked keys for a given client. 
 812  * The function returns 1 when there are no longer blocking keys after 
 813  * the current one was removed (and the client can be unblocked). */ 
 814 int dontWaitForSwappedKey(redisClient 
*c
, robj 
*key
) { 
 818     struct dictEntry 
*de
; 
 820     /* The key object might be destroyed when deleted from the c->io_keys 
 821      * list (and the "key" argument is physically the same object as the 
 822      * object inside the list), so we need to protect it. */ 
 825     /* Remove the key from the list of keys this client is waiting for. */ 
 826     listRewind(c
->io_keys
,&li
); 
 827     while ((ln 
= listNext(&li
)) != NULL
) { 
 828         if (equalStringObjects(ln
->value
,key
)) { 
 829             listDelNode(c
->io_keys
,ln
); 
 833     redisAssert(ln 
!= NULL
); 
 835     /* Remove the client form the key => waiting clients map. */ 
 836     de 
= dictFind(c
->db
->io_keys
,key
); 
 837     redisAssert(de 
!= NULL
); 
 838     l 
= dictGetEntryVal(de
); 
 839     ln 
= listSearchKey(l
,c
); 
 840     redisAssert(ln 
!= NULL
); 
 842     if (listLength(l
) == 0) 
 843         dictDelete(c
->db
->io_keys
,key
); 
 846     return listLength(c
->io_keys
) == 0; 
 849 /* Every time we now a key was loaded back in memory, we handle clients 
 850  * waiting for this key if any. */ 
 851 void handleClientsBlockedOnSwappedKey(redisDb 
*db
, robj 
*key
) { 
 852     struct dictEntry 
*de
; 
 857     de 
= dictFind(db
->io_keys
,key
); 
 860     l 
= dictGetEntryVal(de
); 
 862     /* Note: we can't use something like while(listLength(l)) as the list 
 863      * can be freed by the calling function when we remove the last element. */ 
 866         redisClient 
*c 
= ln
->value
; 
 868         if (dontWaitForSwappedKey(c
,key
)) { 
 869             /* Put the client in the list of clients ready to go as we 
 870              * loaded all the keys about it. */ 
 871             listAddNodeTail(server
.io_ready_clients
,c
);