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 * WARNING: most of the following todo items and design issues are no
23 * longer relevant with the new design. Here as a checklist to see if
24 * some old ideas still apply.
26 * - The WATCH helper will be used to signal the cache system
27 * we need to flush a given key/dbid into disk, adding this key/dbid
28 * pair into a server.ds_cache_dirty linked list AND hash table (so that we
29 * don't add the same thing multiple times).
31 * - cron() checks if there are elements on this list. When there are things
32 * to flush, we create an IO Job for the I/O thread.
33 * NOTE: We disalbe object sharing when server.ds_enabled == 1 so objects
34 * that are referenced an IO job for flushing on disk are marked as
35 * o->storage == REDIS_DS_SAVING.
37 * - This is what we do on key lookup:
38 * 1) The key already exists in memory. object->storage == REDIS_DS_MEMORY
39 * or it is object->storage == REDIS_DS_DIRTY:
40 * We don't do nothing special, lookup, return value object pointer.
41 * 2) The key is in memory but object->storage == REDIS_DS_SAVING.
42 * When this happens we block waiting for the I/O thread to process
43 * this object. Then continue.
44 * 3) The key is not in memory. We block to load the key from disk.
45 * Of course the key may not be present at all on the disk store as well,
46 * in such case we just detect this condition and continue, returning
49 * - Preloading of needed keys:
50 * 1) As it was done with VM, also with this new system we try preloading
51 * keys a client is going to use. We block the client, load keys
52 * using the I/O thread, unblock the client. Same code as VM more or less.
54 * - Reclaiming memory.
55 * In cron() we detect our memory limit was reached. What we
56 * do is deleting keys that are REDIS_DS_MEMORY, using LRU.
58 * If this is not enough to return again under the memory limits we also
59 * start to flush keys that need to be synched on disk synchronously,
60 * removing it from the memory. We do this blocking as memory limit is a
61 * much "harder" barrirer in the new design.
63 * - IO thread operations are no longer stopped for sync loading/saving of
64 * things. When a key is found to be in the process of being saved
65 * we simply wait for the IO thread to end its work.
67 * Otherwise if there is to load a key without any IO thread operation
68 * just started it is blocking-loaded in the lookup function.
70 * - What happens when an object is destroyed?
72 * If o->storage == REDIS_DS_MEMORY then we simply destory the object.
73 * If o->storage == REDIS_DS_DIRTY we can still remove the object. It had
74 * changes not flushed on disk, but is being removed so
76 * if o->storage == REDIS_DS_SAVING then the object is being saved so
77 * it is impossible that its refcount == 1, must be at
78 * least two. When the object is saved the storage will
79 * be set back to DS_MEMORY.
81 * - What happens when keys are deleted?
83 * We simply schedule a key flush operation as usually, but when the
84 * IO thread will be created the object pointer will be set to NULL
85 * so the IO thread will know that the work to do is to delete the key
86 * from the disk store.
88 * - What happens with MULTI/EXEC?
92 * - If dsSet() fails on the write thread log the error and reschedule the
95 * - Check why INCR will not update the LRU info for the object.
97 * - Fix/Check the following race condition: a key gets a DEL so there is
98 * a write operation scheduled against this key. Later the same key will
99 * be the argument of a GET, but the write operation was still not
100 * completed (to delete the file). If the GET will be for some reason
101 * a blocking loading (via lookup) we can load the old value on memory.
103 * This problems can be fixed with negative caching. We can use it
104 * to optimize the system, but also when a key is deleted we mark
105 * it as non existing on disk as well (in a way that this cache
106 * entry can't be evicted, setting time to 0), then we avoid looking at
107 * the disk at all if the key can't be there. When an IO Job complete
108 * a deletion, we set the time of the negative caching to a non zero
109 * value so it will be evicted later.
111 * Are there other patterns like this where we load stale data?
113 * Also, make sure that key preloading is ONLY done for keys that are
114 * not marked as cacheKeyDoesNotExist(), otherwise, again, we can load
115 * data from disk that should instead be deleted.
117 * - dsSet() use rename(2) in order to avoid corruptions.
119 * - Don't add a LOAD if there is already a LOADINPROGRESS, or is this
120 * impossible since anyway the io_keys stuff will work as lock?
123 /* Virtual Memory is composed mainly of two subsystems:
124 * - Blocking Virutal Memory
125 * - Threaded Virtual Memory I/O
126 * The two parts are not fully decoupled, but functions are split among two
127 * different sections of the source code (delimited by comments) in order to
128 * make more clear what functionality is about the blocking VM and what about
129 * the threaded (not blocking) VM.
133 * Redis VM is a blocking VM (one that blocks reading swapped values from
134 * disk into memory when a value swapped out is needed in memory) that is made
135 * unblocking by trying to examine the command argument vector in order to
136 * load in background values that will likely be needed in order to exec
137 * the command. The command is executed only once all the relevant keys
138 * are loaded into memory.
140 * This basically is almost as simple of a blocking VM, but almost as parallel
141 * as a fully non-blocking VM.
144 void spawnIOThread(void);
146 /* =================== Virtual Memory - Blocking Side ====================== */
152 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
154 redisLog(REDIS_NOTICE
,"Opening Disk Store: %s", server
.ds_path
);
155 /* Open Disk Store */
156 if (dsOpen() != REDIS_OK
) {
157 redisLog(REDIS_WARNING
,"Fatal error opening disk store. Exiting.");
161 /* Initialize threaded I/O for Object Cache */
162 server
.io_newjobs
= listCreate();
163 server
.io_processing
= listCreate();
164 server
.io_processed
= listCreate();
165 server
.io_ready_clients
= listCreate();
166 pthread_mutex_init(&server
.io_mutex
,NULL
);
167 pthread_cond_init(&server
.io_condvar
,NULL
);
168 server
.io_active_threads
= 0;
169 if (pipe(pipefds
) == -1) {
170 redisLog(REDIS_WARNING
,"Unable to intialized DS: pipe(2): %s. Exiting."
174 server
.io_ready_pipe_read
= pipefds
[0];
175 server
.io_ready_pipe_write
= pipefds
[1];
176 redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
);
177 /* LZF requires a lot of stack */
178 pthread_attr_init(&server
.io_threads_attr
);
179 pthread_attr_getstacksize(&server
.io_threads_attr
, &stacksize
);
181 /* Solaris may report a stacksize of 0, let's set it to 1 otherwise
182 * multiplying it by 2 in the while loop later will not really help ;) */
183 if (!stacksize
) stacksize
= 1;
185 while (stacksize
< REDIS_THREAD_STACK_SIZE
) stacksize
*= 2;
186 pthread_attr_setstacksize(&server
.io_threads_attr
, stacksize
);
187 /* Listen for events in the threaded I/O pipe */
188 if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
,
189 vmThreadedIOCompletedJob
, NULL
) == AE_ERR
)
190 oom("creating file event");
192 /* Spawn our I/O thread */
196 /* Compute how good candidate the specified object is for eviction.
197 * An higher number means a better candidate. */
198 double computeObjectSwappability(robj
*o
) {
199 /* actual age can be >= minage, but not < minage. As we use wrapping
200 * 21 bit clocks with minutes resolution for the LRU. */
201 return (double) estimateObjectIdleTime(o
);
204 /* Try to free one entry from the diskstore object cache */
205 int cacheFreeOneEntry(void) {
207 struct dictEntry
*best
= NULL
;
208 double best_swappability
= 0;
209 redisDb
*best_db
= NULL
;
213 for (j
= 0; j
< server
.dbnum
; j
++) {
214 redisDb
*db
= server
.db
+j
;
215 /* Why maxtries is set to 100?
216 * Because this way (usually) we'll find 1 object even if just 1% - 2%
217 * are swappable objects */
220 if (dictSize(db
->dict
) == 0) continue;
221 for (i
= 0; i
< 5; i
++) {
227 if (maxtries
) maxtries
--;
228 de
= dictGetRandomKey(db
->dict
);
229 keystr
= dictGetEntryKey(de
);
230 val
= dictGetEntryVal(de
);
231 initStaticStringObject(keyobj
,keystr
);
233 /* Don't remove objects that are currently target of a
234 * read or write operation. */
235 if (cacheScheduleIOGetFlags(db
,&keyobj
) != 0) {
236 if (maxtries
) i
--; /* don't count this try */
239 swappability
= computeObjectSwappability(val
);
240 if (!best
|| swappability
> best_swappability
) {
242 best_swappability
= swappability
;
248 /* FIXME: If there are objects that are in the write queue
249 * so we can't delete them we should block here, at the cost of
250 * slowness as the object cache memory limit is considered
254 key
= dictGetEntryKey(best
);
255 val
= dictGetEntryVal(best
);
257 redisLog(REDIS_DEBUG
,"Key selected for cache eviction: %s swappability:%f",
258 key
, best_swappability
);
260 /* Delete this key from memory */
262 robj
*kobj
= createStringObject(key
,sdslen(key
));
263 dbDelete(best_db
,kobj
);
269 /* Return true if it's safe to swap out objects in a given moment.
270 * Basically we don't want to swap objects out while there is a BGSAVE
271 * or a BGAEOREWRITE running in backgroud. */
272 int dsCanTouchDiskStore(void) {
273 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
276 /* ==================== Disk store negative caching ========================
278 * When disk store is enabled, we need negative caching, that is, to remember
279 * keys that are for sure *not* on the disk key-value store.
281 * This is usefuls because without negative caching cache misses will cost us
282 * a disk lookup, even if the same non existing key is accessed again and again.
284 * With negative caching we remember that the key is not on disk, so if it's
285 * not in memory and we have a negative cache entry, we don't try a disk
289 /* Returns true if the specified key may exists on disk, that is, we don't
290 * have an entry in our negative cache for this key */
291 int cacheKeyMayExist(redisDb
*db
, robj
*key
) {
292 return dictFind(db
->io_negcache
,key
) == NULL
;
295 /* Set the specified key as an entry that may possibily exist on disk, that is,
296 * remove the negative cache entry for this key if any. */
297 void cacheSetKeyMayExist(redisDb
*db
, robj
*key
) {
298 dictDelete(db
->io_negcache
,key
);
301 /* Set the specified key as non existing on disk, that is, create a negative
302 * cache entry for this key. */
303 void cacheSetKeyDoesNotExist(redisDb
*db
, robj
*key
) {
304 if (dictReplace(db
->io_negcache
,key
,(void*)time(NULL
))) {
309 /* Remove one entry from negative cache using approximated LRU. */
310 int negativeCacheEvictOneEntry(void) {
311 struct dictEntry
*de
;
313 redisDb
*best_db
= NULL
;
314 time_t time
, best_time
= 0;
317 for (j
= 0; j
< server
.dbnum
; j
++) {
318 redisDb
*db
= server
.db
+j
;
321 if (dictSize(db
->io_negcache
) == 0) continue;
322 for (i
= 0; i
< 3; i
++) {
323 de
= dictGetRandomKey(db
->io_negcache
);
324 time
= (time_t) dictGetEntryVal(de
);
326 if (best
== NULL
|| time
< best_time
) {
327 best
= dictGetEntryKey(de
);
334 dictDelete(best_db
->io_negcache
,best
);
341 /* ================== Disk store cache - Threaded I/O ====================== */
343 void freeIOJob(iojob
*j
) {
344 decrRefCount(j
->key
);
345 /* j->val can be NULL if the job is about deleting the key from disk. */
346 if (j
->val
) decrRefCount(j
->val
);
350 /* Every time a thread finished a Job, it writes a byte into the write side
351 * of an unix pipe in order to "awake" the main thread, and this function
353 void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
,
357 int retval
, processed
= 0, toprocess
= -1;
360 REDIS_NOTUSED(privdata
);
362 /* For every byte we read in the read side of the pipe, there is one
363 * I/O job completed to process. */
364 while((retval
= read(fd
,buf
,1)) == 1) {
368 redisLog(REDIS_DEBUG
,"Processing I/O completed job");
370 /* Get the processed element (the oldest one) */
372 redisAssert(listLength(server
.io_processed
) != 0);
373 if (toprocess
== -1) {
374 toprocess
= (listLength(server
.io_processed
)*REDIS_MAX_COMPLETED_JOBS_PROCESSED
)/100;
375 if (toprocess
<= 0) toprocess
= 1;
377 ln
= listFirst(server
.io_processed
);
379 listDelNode(server
.io_processed
,ln
);
382 /* Post process it in the main thread, as there are things we
383 * can do just here to avoid race conditions and/or invasive locks */
384 redisLog(REDIS_DEBUG
,"COMPLETED Job type %s, key: %s",
385 (j
->type
== REDIS_IOJOB_LOAD
) ? "load" : "save",
386 (unsigned char*)j
->key
->ptr
);
387 if (j
->type
== REDIS_IOJOB_LOAD
) {
388 /* Create the key-value pair in the in-memory database */
389 if (j
->val
!= NULL
) {
390 /* Note: it's possible that the key is already in memory
391 * due to a blocking load operation. */
392 if (dbAdd(j
->db
,j
->key
,j
->val
) == REDIS_OK
) {
393 incrRefCount(j
->val
);
394 if (j
->expire
!= -1) setExpire(j
->db
,j
->key
,j
->expire
);
397 cacheScheduleIODelFlag(j
->db
,j
->key
,REDIS_IO_LOADINPROG
);
398 handleClientsBlockedOnSwappedKey(j
->db
,j
->key
);
400 } else if (j
->type
== REDIS_IOJOB_SAVE
) {
401 cacheScheduleIODelFlag(j
->db
,j
->key
,REDIS_IO_SAVEINPROG
);
405 if (processed
== toprocess
) return;
407 if (retval
< 0 && errno
!= EAGAIN
) {
408 redisLog(REDIS_WARNING
,
409 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
414 void lockThreadedIO(void) {
415 pthread_mutex_lock(&server
.io_mutex
);
418 void unlockThreadedIO(void) {
419 pthread_mutex_unlock(&server
.io_mutex
);
422 void *IOThreadEntryPoint(void *arg
) {
427 pthread_detach(pthread_self());
430 /* Get a new job to process */
431 if (listLength(server
.io_newjobs
) == 0) {
432 /* Wait for more work to do */
433 pthread_cond_wait(&server
.io_condvar
,&server
.io_mutex
);
436 redisLog(REDIS_DEBUG
,"%ld IO jobs to process",
437 listLength(server
.io_newjobs
));
438 ln
= listFirst(server
.io_newjobs
);
440 listDelNode(server
.io_newjobs
,ln
);
441 /* Add the job in the processing queue */
442 listAddNodeTail(server
.io_processing
,j
);
443 ln
= listLast(server
.io_processing
); /* We use ln later to remove it */
446 redisLog(REDIS_DEBUG
,"Thread %ld: new job type %s: %p about key '%s'",
447 (long) pthread_self(),
448 (j
->type
== REDIS_IOJOB_LOAD
) ? "load" : "save",
449 (void*)j
, (char*)j
->key
->ptr
);
451 /* Process the Job */
452 if (j
->type
== REDIS_IOJOB_LOAD
) {
455 j
->val
= dsGet(j
->db
,j
->key
,&expire
);
456 if (j
->val
) j
->expire
= expire
;
457 } else if (j
->type
== REDIS_IOJOB_SAVE
) {
459 dsSet(j
->db
,j
->key
,j
->val
);
465 /* Done: insert the job into the processed queue */
466 redisLog(REDIS_DEBUG
,"Thread %ld completed the job: %p (key %s)",
467 (long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
);
470 listDelNode(server
.io_processing
,ln
);
471 listAddNodeTail(server
.io_processed
,j
);
473 /* Signal the main thread there is new stuff to process */
474 redisAssert(write(server
.io_ready_pipe_write
,"x",1) == 1);
476 /* never reached, but that's the full pattern... */
481 void spawnIOThread(void) {
483 sigset_t mask
, omask
;
487 sigaddset(&mask
,SIGCHLD
);
488 sigaddset(&mask
,SIGHUP
);
489 sigaddset(&mask
,SIGPIPE
);
490 pthread_sigmask(SIG_SETMASK
, &mask
, &omask
);
491 while ((err
= pthread_create(&thread
,&server
.io_threads_attr
,IOThreadEntryPoint
,NULL
)) != 0) {
492 redisLog(REDIS_WARNING
,"Unable to spawn an I/O thread: %s",
496 pthread_sigmask(SIG_SETMASK
, &omask
, NULL
);
497 server
.io_active_threads
++;
500 /* Wait that all the pending IO Jobs are processed */
501 void waitEmptyIOJobsQueue(void) {
503 int io_processed_len
;
506 if (listLength(server
.io_newjobs
) == 0 &&
507 listLength(server
.io_processing
) == 0)
512 /* If there are new jobs we need to signal the thread to
513 * process the next one. */
514 redisLog(REDIS_DEBUG
,"waitEmptyIOJobsQueue: new %d, processing %d",
515 listLength(server
.io_newjobs
),
516 listLength(server
.io_processing
));
518 if (listLength(server.io_newjobs)) {
519 pthread_cond_signal(&server.io_condvar);
522 /* While waiting for empty jobs queue condition we post-process some
523 * finshed job, as I/O threads may be hanging trying to write against
524 * the io_ready_pipe_write FD but there are so much pending jobs that
526 io_processed_len
= listLength(server
.io_processed
);
528 if (io_processed_len
) {
529 vmThreadedIOCompletedJob(NULL
,server
.io_ready_pipe_read
,
530 (void*)0xdeadbeef,0);
531 usleep(1000); /* 1 millisecond */
533 usleep(10000); /* 10 milliseconds */
538 /* Process all the IO Jobs already completed by threads but still waiting
539 * processing from the main thread. */
540 void processAllPendingIOJobs(void) {
542 int io_processed_len
;
545 io_processed_len
= listLength(server
.io_processed
);
547 if (io_processed_len
== 0) return;
548 vmThreadedIOCompletedJob(NULL
,server
.io_ready_pipe_read
,
549 (void*)0xdeadbeef,0);
553 /* This function must be called while with threaded IO locked */
554 void queueIOJob(iojob
*j
) {
555 redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n",
556 (void*)j
, j
->type
, (char*)j
->key
->ptr
);
557 listAddNodeTail(server
.io_newjobs
,j
);
558 if (server
.io_active_threads
< server
.vm_max_threads
)
562 void dsCreateIOJob(int type
, redisDb
*db
, robj
*key
, robj
*val
) {
565 j
= zmalloc(sizeof(*j
));
571 if (val
) incrRefCount(val
);
575 pthread_cond_signal(&server
.io_condvar
);
579 /* ============= Disk store cache - Scheduling of IO operations =============
581 * We use a queue and an hash table to hold the state of IO operations
582 * so that's fast to lookup if there is already an IO operation in queue
585 * There are two types of IO operations for a given key:
586 * REDIS_IO_LOAD and REDIS_IO_SAVE.
588 * The function cacheScheduleIO() function pushes the specified IO operation
589 * in the queue, but avoid adding the same key for the same operation
590 * multiple times, thanks to the associated hash table.
592 * We take a set of flags per every key, so when the scheduled IO operation
593 * gets moved from the scheduled queue to the actual IO Jobs queue that
594 * is processed by the IO thread, we flag it as IO_LOADINPROG or
597 * So for every given key we always know if there is some IO operation
598 * scheduled, or in progress, for this key.
600 * NOTE: all this is very important in order to guarantee correctness of
601 * the Disk Store Cache. Jobs are always queued here. Load jobs are
602 * queued at the head for faster execution only in the case there is not
603 * already a write operation of some kind for this job.
605 * So we have ordering, but can do exceptions when there are no already
606 * operations for a given key. Also when we need to block load a given
607 * key, for an immediate lookup operation, we can check if the key can
608 * be accessed synchronously without race conditions (no IN PROGRESS
609 * operations for this key), otherwise we blocking wait for completion. */
611 #define REDIS_IO_LOAD 1
612 #define REDIS_IO_SAVE 2
613 #define REDIS_IO_LOADINPROG 4
614 #define REDIS_IO_SAVEINPROG 8
616 void cacheScheduleIOAddFlag(redisDb
*db
, robj
*key
, long flag
) {
617 struct dictEntry
*de
= dictFind(db
->io_queued
,key
);
620 dictAdd(db
->io_queued
,key
,(void*)flag
);
624 long flags
= (long) dictGetEntryVal(de
);
627 redisLog(REDIS_WARNING
,"Adding the same flag again: was: %ld, addede: %ld",flags
,flag
);
628 redisAssert(!(flags
& flag
));
631 dictGetEntryVal(de
) = (void*) flags
;
635 void cacheScheduleIODelFlag(redisDb
*db
, robj
*key
, long flag
) {
636 struct dictEntry
*de
= dictFind(db
->io_queued
,key
);
639 redisAssert(de
!= NULL
);
640 flags
= (long) dictGetEntryVal(de
);
641 redisAssert(flags
& flag
);
644 dictDelete(db
->io_queued
,key
);
646 dictGetEntryVal(de
) = (void*) flags
;
650 int cacheScheduleIOGetFlags(redisDb
*db
, robj
*key
) {
651 struct dictEntry
*de
= dictFind(db
->io_queued
,key
);
653 return (de
== NULL
) ? 0 : ((long) dictGetEntryVal(de
));
656 void cacheScheduleIO(redisDb
*db
, robj
*key
, int type
) {
660 if ((flags
= cacheScheduleIOGetFlags(db
,key
)) & type
) return;
662 redisLog(REDIS_DEBUG
,"Scheduling key %s for %s",
663 key
->ptr
, type
== REDIS_IO_LOAD
? "loading" : "saving");
664 cacheScheduleIOAddFlag(db
,key
,type
);
665 op
= zmalloc(sizeof(*op
));
670 op
->ctime
= time(NULL
);
672 /* Give priority to load operations if there are no save already
673 * in queue for the same key. */
674 if (type
== REDIS_IO_LOAD
&& !(flags
& REDIS_IO_SAVE
)) {
675 listAddNodeHead(server
.cache_io_queue
, op
);
677 /* FIXME: probably when this happens we want to at least move
678 * the write job about this queue on top, and set the creation time
679 * to a value that will force processing ASAP. */
680 listAddNodeTail(server
.cache_io_queue
, op
);
684 void cacheCron(void) {
685 time_t now
= time(NULL
);
687 int jobs
, topush
= 0;
689 /* Sync stuff on disk, but only if we have less than 100 IO jobs */
691 jobs
= listLength(server
.io_newjobs
);
695 if (topush
< 0) topush
= 0;
696 if (topush
> (signed)listLength(server
.cache_io_queue
))
697 topush
= listLength(server
.cache_io_queue
);
699 while((ln
= listFirst(server
.cache_io_queue
)) != NULL
) {
700 ioop
*op
= ln
->value
;
705 if (op
->type
== REDIS_IO_LOAD
||
706 (now
- op
->ctime
) >= server
.cache_flush_delay
)
708 struct dictEntry
*de
;
711 /* Don't add a SAVE job in queue if there is already
712 * a save in progress for the same key. */
713 if (op
->type
== REDIS_IO_SAVE
&&
714 cacheScheduleIOGetFlags(op
->db
,op
->key
) & REDIS_IO_SAVEINPROG
)
716 /* Move the operation at the end of the list of there
717 * are other operations. Otherwise break, nothing to do
719 if (listLength(server
.cache_io_queue
) > 1) {
720 listDelNode(server
.cache_io_queue
,ln
);
721 listAddNodeTail(server
.cache_io_queue
,op
);
728 redisLog(REDIS_DEBUG
,"Creating IO %s Job for key %s",
729 op
->type
== REDIS_IO_LOAD
? "load" : "save", op
->key
->ptr
);
731 if (op
->type
== REDIS_IO_LOAD
) {
732 dsCreateIOJob(REDIS_IOJOB_LOAD
,op
->db
,op
->key
,NULL
);
734 /* Lookup the key, in order to put the current value in the IO
735 * Job. Otherwise if the key does not exists we schedule a disk
736 * store delete operation, setting the value to NULL. */
737 de
= dictFind(op
->db
->dict
,op
->key
->ptr
);
739 val
= dictGetEntryVal(de
);
741 /* Setting the value to NULL tells the IO thread to delete
742 * the key on disk. */
745 dsCreateIOJob(REDIS_IOJOB_SAVE
,op
->db
,op
->key
,val
);
747 /* Mark the operation as in progress. */
748 cacheScheduleIODelFlag(op
->db
,op
->key
,op
->type
);
749 cacheScheduleIOAddFlag(op
->db
,op
->key
,
750 (op
->type
== REDIS_IO_LOAD
) ? REDIS_IO_LOADINPROG
:
751 REDIS_IO_SAVEINPROG
);
752 /* Finally remove the operation from the queue.
753 * But we'll have trace of it in the hash table. */
754 listDelNode(server
.cache_io_queue
,ln
);
755 decrRefCount(op
->key
);
758 break; /* too early */
762 /* Reclaim memory from the object cache */
763 while (server
.ds_enabled
&& zmalloc_used_memory() >
764 server
.cache_max_memory
)
768 if (cacheFreeOneEntry() == REDIS_OK
) done
++;
769 if (negativeCacheEvictOneEntry() == REDIS_OK
) done
++;
770 if (done
== 0) break; /* nothing more to free */
774 /* ========== Disk store cache - Blocking clients on missing keys =========== */
776 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
777 * If the key is already in memory we don't need to block.
779 * FIXME: we should try if it's actually better to suspend the client
780 * accessing an object that is being saved, and awake it only when
781 * the saving was completed.
783 * Otherwise if the key is not in memory, we block the client and start
784 * an IO Job to load it:
786 * the key is added to the io_keys list in the client structure, and also
787 * in the hash table mapping swapped keys to waiting clients, that is,
788 * server.io_waited_keys. */
789 int waitForSwappedKey(redisClient
*c
, robj
*key
) {
790 struct dictEntry
*de
;
793 /* Return ASAP if the key is in memory */
794 de
= dictFind(c
->db
->dict
,key
->ptr
);
795 if (de
!= NULL
) return 0;
797 /* Don't wait for keys we are sure are not on disk either */
798 if (!cacheKeyMayExist(c
->db
,key
)) return 0;
800 /* Add the key to the list of keys this client is waiting for.
801 * This maps clients to keys they are waiting for. */
802 listAddNodeTail(c
->io_keys
,key
);
805 /* Add the client to the swapped keys => clients waiting map. */
806 de
= dictFind(c
->db
->io_keys
,key
);
810 /* For every key we take a list of clients blocked for it */
812 retval
= dictAdd(c
->db
->io_keys
,key
,l
);
814 redisAssert(retval
== DICT_OK
);
816 l
= dictGetEntryVal(de
);
818 listAddNodeTail(l
,c
);
820 /* Are we already loading the key from disk? If not create a job */
822 cacheScheduleIO(c
->db
,key
,REDIS_IO_LOAD
);
826 /* Preload keys for any command with first, last and step values for
827 * the command keys prototype, as defined in the command table. */
828 void waitForMultipleSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
830 if (cmd
->vm_firstkey
== 0) return;
831 last
= cmd
->vm_lastkey
;
832 if (last
< 0) last
= argc
+last
;
833 for (j
= cmd
->vm_firstkey
; j
<= last
; j
+= cmd
->vm_keystep
) {
834 redisAssert(j
< argc
);
835 waitForSwappedKey(c
,argv
[j
]);
839 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
840 * Note that the number of keys to preload is user-defined, so we need to
841 * apply a sanity check against argc. */
842 void zunionInterBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
846 num
= atoi(argv
[2]->ptr
);
847 if (num
> (argc
-3)) return;
848 for (i
= 0; i
< num
; i
++) {
849 waitForSwappedKey(c
,argv
[3+i
]);
853 /* Preload keys needed to execute the entire MULTI/EXEC block.
855 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
856 * and will block the client when any command requires a swapped out value. */
857 void execBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
859 struct redisCommand
*mcmd
;
865 if (!(c
->flags
& REDIS_MULTI
)) return;
866 for (i
= 0; i
< c
->mstate
.count
; i
++) {
867 mcmd
= c
->mstate
.commands
[i
].cmd
;
868 margc
= c
->mstate
.commands
[i
].argc
;
869 margv
= c
->mstate
.commands
[i
].argv
;
871 if (mcmd
->vm_preload_proc
!= NULL
) {
872 mcmd
->vm_preload_proc(c
,mcmd
,margc
,margv
);
874 waitForMultipleSwappedKeys(c
,mcmd
,margc
,margv
);
879 /* Is this client attempting to run a command against swapped keys?
880 * If so, block it ASAP, load the keys in background, then resume it.
882 * The important idea about this function is that it can fail! If keys will
883 * still be swapped when the client is resumed, this key lookups will
884 * just block loading keys from disk. In practical terms this should only
885 * happen with SORT BY command or if there is a bug in this function.
887 * Return 1 if the client is marked as blocked, 0 if the client can
888 * continue as the keys it is going to access appear to be in memory. */
889 int blockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
) {
890 if (cmd
->vm_preload_proc
!= NULL
) {
891 cmd
->vm_preload_proc(c
,cmd
,c
->argc
,c
->argv
);
893 waitForMultipleSwappedKeys(c
,cmd
,c
->argc
,c
->argv
);
896 /* If the client was blocked for at least one key, mark it as blocked. */
897 if (listLength(c
->io_keys
)) {
898 c
->flags
|= REDIS_IO_WAIT
;
899 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
900 server
.cache_blocked_clients
++;
907 /* Remove the 'key' from the list of blocked keys for a given client.
909 * The function returns 1 when there are no longer blocking keys after
910 * the current one was removed (and the client can be unblocked). */
911 int dontWaitForSwappedKey(redisClient
*c
, robj
*key
) {
915 struct dictEntry
*de
;
917 /* The key object might be destroyed when deleted from the c->io_keys
918 * list (and the "key" argument is physically the same object as the
919 * object inside the list), so we need to protect it. */
922 /* Remove the key from the list of keys this client is waiting for. */
923 listRewind(c
->io_keys
,&li
);
924 while ((ln
= listNext(&li
)) != NULL
) {
925 if (equalStringObjects(ln
->value
,key
)) {
926 listDelNode(c
->io_keys
,ln
);
930 redisAssert(ln
!= NULL
);
932 /* Remove the client form the key => waiting clients map. */
933 de
= dictFind(c
->db
->io_keys
,key
);
934 redisAssert(de
!= NULL
);
935 l
= dictGetEntryVal(de
);
936 ln
= listSearchKey(l
,c
);
937 redisAssert(ln
!= NULL
);
939 if (listLength(l
) == 0)
940 dictDelete(c
->db
->io_keys
,key
);
943 return listLength(c
->io_keys
) == 0;
946 /* Every time we now a key was loaded back in memory, we handle clients
947 * waiting for this key if any. */
948 void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
) {
949 struct dictEntry
*de
;
954 de
= dictFind(db
->io_keys
,key
);
957 l
= dictGetEntryVal(de
);
959 /* Note: we can't use something like while(listLength(l)) as the list
960 * can be freed by the calling function when we remove the last element. */
963 redisClient
*c
= ln
->value
;
965 if (dontWaitForSwappedKey(c
,key
)) {
966 /* Put the client in the list of clients ready to go as we
967 * loaded all the keys about it. */
968 listAddNodeTail(server
.io_ready_clients
,c
);