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 * - What happens when an object is destroyed?
28 * If the object is destroyed since semantically it was deleted or
29 * replaced with something new, we don't care if there was a SAVE
30 * job pending for it. Anyway when the IO JOb will be created we'll get
31 * the pointer of the current value.
33 * If the object is already a REDIS_IO_SAVEINPROG object, then it is
34 * impossible that we get a decrRefCount() that will reach refcount of zero
35 * since the object is both in the dataset and in the io job entry.
37 * - What happens with MULTI/EXEC?
39 * Good question. Without some kind of versioning with a global counter
40 * it is not possible to have trasactions on disk, but they are still
41 * useful since from the point of view of memory and client bugs it is
42 * a protection anyway. Also it's useful for WATCH.
44 * Btw there is to check what happens when WATCH gets combined to keys
45 * that gets removed from the object cache. Should be save but better
48 * - Check if/why INCR will not update the LRU info for the object.
50 * - Fix/Check the following race condition: a key gets a DEL so there is
51 * a write operation scheduled against this key. Later the same key will
52 * be the argument of a GET, but the write operation was still not
53 * completed (to delete the file). If the GET will be for some reason
54 * a blocking loading (via lookup) we can load the old value on memory.
56 * This problems can be fixed with negative caching. We can use it
57 * to optimize the system, but also when a key is deleted we mark
58 * it as non existing on disk as well (in a way that this cache
59 * entry can't be evicted, setting time to 0), then we avoid looking at
60 * the disk at all if the key can't be there. When an IO Job complete
61 * a deletion, we set the time of the negative caching to a non zero
62 * value so it will be evicted later.
64 * Are there other patterns like this where we load stale data?
66 * Also, make sure that key preloading is ONLY done for keys that are
67 * not marked as cacheKeyDoesNotExist(), otherwise, again, we can load
68 * data from disk that should instead be deleted.
70 * - dsSet() should use rename(2) in order to avoid corruptions.
72 * - Don't add a LOAD if there is already a LOADINPROGRESS, or is this
73 * impossible since anyway the io_keys stuff will work as lock?
75 * - Serialize special encoded things in a raw form.
78 /* Virtual Memory is composed mainly of two subsystems:
79 * - Blocking Virutal Memory
80 * - Threaded Virtual Memory I/O
81 * The two parts are not fully decoupled, but functions are split among two
82 * different sections of the source code (delimited by comments) in order to
83 * make more clear what functionality is about the blocking VM and what about
84 * the threaded (not blocking) VM.
88 * Redis VM is a blocking VM (one that blocks reading swapped values from
89 * disk into memory when a value swapped out is needed in memory) that is made
90 * unblocking by trying to examine the command argument vector in order to
91 * load in background values that will likely be needed in order to exec
92 * the command. The command is executed only once all the relevant keys
93 * are loaded into memory.
95 * This basically is almost as simple of a blocking VM, but almost as parallel
96 * as a fully non-blocking VM.
99 void spawnIOThread(void);
101 /* =================== Virtual Memory - Blocking Side ====================== */
107 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
109 redisLog(REDIS_NOTICE
,"Opening Disk Store: %s", server
.ds_path
);
110 /* Open Disk Store */
111 if (dsOpen() != REDIS_OK
) {
112 redisLog(REDIS_WARNING
,"Fatal error opening disk store. Exiting.");
116 /* Initialize threaded I/O for Object Cache */
117 server
.io_newjobs
= listCreate();
118 server
.io_processing
= listCreate();
119 server
.io_processed
= listCreate();
120 server
.io_ready_clients
= listCreate();
121 pthread_mutex_init(&server
.io_mutex
,NULL
);
122 pthread_cond_init(&server
.io_condvar
,NULL
);
123 server
.io_active_threads
= 0;
124 if (pipe(pipefds
) == -1) {
125 redisLog(REDIS_WARNING
,"Unable to intialized DS: pipe(2): %s. Exiting."
129 server
.io_ready_pipe_read
= pipefds
[0];
130 server
.io_ready_pipe_write
= pipefds
[1];
131 redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
);
132 /* LZF requires a lot of stack */
133 pthread_attr_init(&server
.io_threads_attr
);
134 pthread_attr_getstacksize(&server
.io_threads_attr
, &stacksize
);
136 /* Solaris may report a stacksize of 0, let's set it to 1 otherwise
137 * multiplying it by 2 in the while loop later will not really help ;) */
138 if (!stacksize
) stacksize
= 1;
140 while (stacksize
< REDIS_THREAD_STACK_SIZE
) stacksize
*= 2;
141 pthread_attr_setstacksize(&server
.io_threads_attr
, stacksize
);
142 /* Listen for events in the threaded I/O pipe */
143 if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
,
144 vmThreadedIOCompletedJob
, NULL
) == AE_ERR
)
145 oom("creating file event");
147 /* Spawn our I/O thread */
151 /* Compute how good candidate the specified object is for eviction.
152 * An higher number means a better candidate. */
153 double computeObjectSwappability(robj
*o
) {
154 /* actual age can be >= minage, but not < minage. As we use wrapping
155 * 21 bit clocks with minutes resolution for the LRU. */
156 return (double) estimateObjectIdleTime(o
);
159 /* Try to free one entry from the diskstore object cache */
160 int cacheFreeOneEntry(void) {
162 struct dictEntry
*best
= NULL
;
163 double best_swappability
= 0;
164 redisDb
*best_db
= NULL
;
168 for (j
= 0; j
< server
.dbnum
; j
++) {
169 redisDb
*db
= server
.db
+j
;
170 /* Why maxtries is set to 100?
171 * Because this way (usually) we'll find 1 object even if just 1% - 2%
172 * are swappable objects */
175 if (dictSize(db
->dict
) == 0) continue;
176 for (i
= 0; i
< 5; i
++) {
182 if (maxtries
) maxtries
--;
183 de
= dictGetRandomKey(db
->dict
);
184 keystr
= dictGetEntryKey(de
);
185 val
= dictGetEntryVal(de
);
186 initStaticStringObject(keyobj
,keystr
);
188 /* Don't remove objects that are currently target of a
189 * read or write operation. */
190 if (cacheScheduleIOGetFlags(db
,&keyobj
) != 0) {
191 if (maxtries
) i
--; /* don't count this try */
194 swappability
= computeObjectSwappability(val
);
195 if (!best
|| swappability
> best_swappability
) {
197 best_swappability
= swappability
;
203 /* FIXME: If there are objects that are in the write queue
204 * so we can't delete them we should block here, at the cost of
205 * slowness as the object cache memory limit is considered
209 key
= dictGetEntryKey(best
);
210 val
= dictGetEntryVal(best
);
212 redisLog(REDIS_DEBUG
,"Key selected for cache eviction: %s swappability:%f",
213 key
, best_swappability
);
215 /* Delete this key from memory */
217 robj
*kobj
= createStringObject(key
,sdslen(key
));
218 dbDelete(best_db
,kobj
);
224 /* Return true if it's safe to swap out objects in a given moment.
225 * Basically we don't want to swap objects out while there is a BGSAVE
226 * or a BGAEOREWRITE running in backgroud. */
227 int dsCanTouchDiskStore(void) {
228 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
231 /* ==================== Disk store negative caching ========================
233 * When disk store is enabled, we need negative caching, that is, to remember
234 * keys that are for sure *not* on the disk key-value store.
236 * This is usefuls because without negative caching cache misses will cost us
237 * a disk lookup, even if the same non existing key is accessed again and again.
239 * With negative caching we remember that the key is not on disk, so if it's
240 * not in memory and we have a negative cache entry, we don't try a disk
244 /* Returns true if the specified key may exists on disk, that is, we don't
245 * have an entry in our negative cache for this key */
246 int cacheKeyMayExist(redisDb
*db
, robj
*key
) {
247 return dictFind(db
->io_negcache
,key
) == NULL
;
250 /* Set the specified key as an entry that may possibily exist on disk, that is,
251 * remove the negative cache entry for this key if any. */
252 void cacheSetKeyMayExist(redisDb
*db
, robj
*key
) {
253 dictDelete(db
->io_negcache
,key
);
256 /* Set the specified key as non existing on disk, that is, create a negative
257 * cache entry for this key. */
258 void cacheSetKeyDoesNotExist(redisDb
*db
, robj
*key
) {
259 if (dictReplace(db
->io_negcache
,key
,(void*)time(NULL
))) {
264 /* Remove one entry from negative cache using approximated LRU. */
265 int negativeCacheEvictOneEntry(void) {
266 struct dictEntry
*de
;
268 redisDb
*best_db
= NULL
;
269 time_t time
, best_time
= 0;
272 for (j
= 0; j
< server
.dbnum
; j
++) {
273 redisDb
*db
= server
.db
+j
;
276 if (dictSize(db
->io_negcache
) == 0) continue;
277 for (i
= 0; i
< 3; i
++) {
278 de
= dictGetRandomKey(db
->io_negcache
);
279 time
= (time_t) dictGetEntryVal(de
);
281 if (best
== NULL
|| time
< best_time
) {
282 best
= dictGetEntryKey(de
);
289 dictDelete(best_db
->io_negcache
,best
);
296 /* ================== Disk store cache - Threaded I/O ====================== */
298 void freeIOJob(iojob
*j
) {
299 decrRefCount(j
->key
);
300 /* j->val can be NULL if the job is about deleting the key from disk. */
301 if (j
->val
) decrRefCount(j
->val
);
305 /* Every time a thread finished a Job, it writes a byte into the write side
306 * of an unix pipe in order to "awake" the main thread, and this function
308 void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
,
312 int retval
, processed
= 0, toprocess
= -1;
315 REDIS_NOTUSED(privdata
);
317 /* For every byte we read in the read side of the pipe, there is one
318 * I/O job completed to process. */
319 while((retval
= read(fd
,buf
,1)) == 1) {
323 redisLog(REDIS_DEBUG
,"Processing I/O completed job");
325 /* Get the processed element (the oldest one) */
327 redisAssert(listLength(server
.io_processed
) != 0);
328 if (toprocess
== -1) {
329 toprocess
= (listLength(server
.io_processed
)*REDIS_MAX_COMPLETED_JOBS_PROCESSED
)/100;
330 if (toprocess
<= 0) toprocess
= 1;
332 ln
= listFirst(server
.io_processed
);
334 listDelNode(server
.io_processed
,ln
);
337 /* Post process it in the main thread, as there are things we
338 * can do just here to avoid race conditions and/or invasive locks */
339 redisLog(REDIS_DEBUG
,"COMPLETED Job type %s, key: %s",
340 (j
->type
== REDIS_IOJOB_LOAD
) ? "load" : "save",
341 (unsigned char*)j
->key
->ptr
);
342 if (j
->type
== REDIS_IOJOB_LOAD
) {
343 /* Create the key-value pair in the in-memory database */
344 if (j
->val
!= NULL
) {
345 /* Note: it's possible that the key is already in memory
346 * due to a blocking load operation. */
347 if (dbAdd(j
->db
,j
->key
,j
->val
) == REDIS_OK
) {
348 incrRefCount(j
->val
);
349 if (j
->expire
!= -1) setExpire(j
->db
,j
->key
,j
->expire
);
352 /* Key not found on disk. If it is also not in memory
353 * as a cached object, nor there is a job writing it
354 * in background, we are sure the key does not exist
357 * So we set a negative cache entry avoiding that the
358 * resumed client will block load what does not exist... */
359 if (dictFind(j
->db
->dict
,j
->key
->ptr
) == NULL
&&
360 (cacheScheduleIOGetFlags(j
->db
,j
->key
) &
361 (REDIS_IO_SAVE
|REDIS_IO_SAVEINPROG
)) == 0)
363 cacheSetKeyDoesNotExist(j
->db
,j
->key
);
366 cacheScheduleIODelFlag(j
->db
,j
->key
,REDIS_IO_LOADINPROG
);
367 handleClientsBlockedOnSwappedKey(j
->db
,j
->key
);
369 } else if (j
->type
== REDIS_IOJOB_SAVE
) {
370 cacheScheduleIODelFlag(j
->db
,j
->key
,REDIS_IO_SAVEINPROG
);
374 if (processed
== toprocess
) return;
376 if (retval
< 0 && errno
!= EAGAIN
) {
377 redisLog(REDIS_WARNING
,
378 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
383 void lockThreadedIO(void) {
384 pthread_mutex_lock(&server
.io_mutex
);
387 void unlockThreadedIO(void) {
388 pthread_mutex_unlock(&server
.io_mutex
);
391 void *IOThreadEntryPoint(void *arg
) {
396 pthread_detach(pthread_self());
399 /* Get a new job to process */
400 if (listLength(server
.io_newjobs
) == 0) {
401 /* Wait for more work to do */
402 pthread_cond_wait(&server
.io_condvar
,&server
.io_mutex
);
405 redisLog(REDIS_DEBUG
,"%ld IO jobs to process",
406 listLength(server
.io_newjobs
));
407 ln
= listFirst(server
.io_newjobs
);
409 listDelNode(server
.io_newjobs
,ln
);
410 /* Add the job in the processing queue */
411 listAddNodeTail(server
.io_processing
,j
);
412 ln
= listLast(server
.io_processing
); /* We use ln later to remove it */
415 redisLog(REDIS_DEBUG
,"Thread %ld: new job type %s: %p about key '%s'",
416 (long) pthread_self(),
417 (j
->type
== REDIS_IOJOB_LOAD
) ? "load" : "save",
418 (void*)j
, (char*)j
->key
->ptr
);
420 /* Process the Job */
421 if (j
->type
== REDIS_IOJOB_LOAD
) {
424 j
->val
= dsGet(j
->db
,j
->key
,&expire
);
425 if (j
->val
) j
->expire
= expire
;
426 } else if (j
->type
== REDIS_IOJOB_SAVE
) {
428 dsSet(j
->db
,j
->key
,j
->val
);
434 /* Done: insert the job into the processed queue */
435 redisLog(REDIS_DEBUG
,"Thread %ld completed the job: %p (key %s)",
436 (long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
);
439 listDelNode(server
.io_processing
,ln
);
440 listAddNodeTail(server
.io_processed
,j
);
442 /* Signal the main thread there is new stuff to process */
443 redisAssert(write(server
.io_ready_pipe_write
,"x",1) == 1);
445 /* never reached, but that's the full pattern... */
450 void spawnIOThread(void) {
452 sigset_t mask
, omask
;
456 sigaddset(&mask
,SIGCHLD
);
457 sigaddset(&mask
,SIGHUP
);
458 sigaddset(&mask
,SIGPIPE
);
459 pthread_sigmask(SIG_SETMASK
, &mask
, &omask
);
460 while ((err
= pthread_create(&thread
,&server
.io_threads_attr
,IOThreadEntryPoint
,NULL
)) != 0) {
461 redisLog(REDIS_WARNING
,"Unable to spawn an I/O thread: %s",
465 pthread_sigmask(SIG_SETMASK
, &omask
, NULL
);
466 server
.io_active_threads
++;
469 /* Wait that all the pending IO Jobs are processed */
470 void waitEmptyIOJobsQueue(void) {
472 int io_processed_len
;
475 if (listLength(server
.io_newjobs
) == 0 &&
476 listLength(server
.io_processing
) == 0)
481 /* If there are new jobs we need to signal the thread to
482 * process the next one. */
483 redisLog(REDIS_DEBUG
,"waitEmptyIOJobsQueue: new %d, processing %d",
484 listLength(server
.io_newjobs
),
485 listLength(server
.io_processing
));
487 /* FIXME: signal or not?
488 if (listLength(server.io_newjobs)) {
489 pthread_cond_signal(&server.io_condvar);
492 /* While waiting for empty jobs queue condition we post-process some
493 * finshed job, as I/O threads may be hanging trying to write against
494 * the io_ready_pipe_write FD but there are so much pending jobs that
496 io_processed_len
= listLength(server
.io_processed
);
498 if (io_processed_len
) {
499 vmThreadedIOCompletedJob(NULL
,server
.io_ready_pipe_read
,
500 (void*)0xdeadbeef,0);
501 /* FIXME: probably wiser to drop this sleeps. Anyway
502 * the contention on the IO thread will avoid we to loop
504 usleep(1000); /* 1 millisecond */
506 /* FIXME: same as fixme above. */
507 usleep(10000); /* 10 milliseconds */
512 /* Process all the IO Jobs already completed by threads but still waiting
513 * processing from the main thread. */
514 void processAllPendingIOJobs(void) {
516 int io_processed_len
;
519 io_processed_len
= listLength(server
.io_processed
);
521 if (io_processed_len
== 0) return;
522 vmThreadedIOCompletedJob(NULL
,server
.io_ready_pipe_read
,
523 (void*)0xdeadbeef,0);
527 /* This function must be called while with threaded IO locked */
528 void queueIOJob(iojob
*j
) {
529 redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n",
530 (void*)j
, j
->type
, (char*)j
->key
->ptr
);
531 listAddNodeTail(server
.io_newjobs
,j
);
532 if (server
.io_active_threads
< server
.vm_max_threads
)
536 void dsCreateIOJob(int type
, redisDb
*db
, robj
*key
, robj
*val
) {
539 j
= zmalloc(sizeof(*j
));
545 if (val
) incrRefCount(val
);
549 pthread_cond_signal(&server
.io_condvar
);
553 /* ============= Disk store cache - Scheduling of IO operations =============
555 * We use a queue and an hash table to hold the state of IO operations
556 * so that's fast to lookup if there is already an IO operation in queue
559 * There are two types of IO operations for a given key:
560 * REDIS_IO_LOAD and REDIS_IO_SAVE.
562 * The function cacheScheduleIO() function pushes the specified IO operation
563 * in the queue, but avoid adding the same key for the same operation
564 * multiple times, thanks to the associated hash table.
566 * We take a set of flags per every key, so when the scheduled IO operation
567 * gets moved from the scheduled queue to the actual IO Jobs queue that
568 * is processed by the IO thread, we flag it as IO_LOADINPROG or
571 * So for every given key we always know if there is some IO operation
572 * scheduled, or in progress, for this key.
574 * NOTE: all this is very important in order to guarantee correctness of
575 * the Disk Store Cache. Jobs are always queued here. Load jobs are
576 * queued at the head for faster execution only in the case there is not
577 * already a write operation of some kind for this job.
579 * So we have ordering, but can do exceptions when there are no already
580 * operations for a given key. Also when we need to block load a given
581 * key, for an immediate lookup operation, we can check if the key can
582 * be accessed synchronously without race conditions (no IN PROGRESS
583 * operations for this key), otherwise we blocking wait for completion. */
585 #define REDIS_IO_LOAD 1
586 #define REDIS_IO_SAVE 2
587 #define REDIS_IO_LOADINPROG 4
588 #define REDIS_IO_SAVEINPROG 8
590 void cacheScheduleIOPushJobs(int onlyloads
);
592 void cacheScheduleIOAddFlag(redisDb
*db
, robj
*key
, long flag
) {
593 struct dictEntry
*de
= dictFind(db
->io_queued
,key
);
596 dictAdd(db
->io_queued
,key
,(void*)flag
);
600 long flags
= (long) dictGetEntryVal(de
);
603 redisLog(REDIS_WARNING
,"Adding the same flag again: was: %ld, addede: %ld",flags
,flag
);
604 redisAssert(!(flags
& flag
));
607 dictGetEntryVal(de
) = (void*) flags
;
611 void cacheScheduleIODelFlag(redisDb
*db
, robj
*key
, long flag
) {
612 struct dictEntry
*de
= dictFind(db
->io_queued
,key
);
615 redisAssert(de
!= NULL
);
616 flags
= (long) dictGetEntryVal(de
);
617 redisAssert(flags
& flag
);
620 dictDelete(db
->io_queued
,key
);
622 dictGetEntryVal(de
) = (void*) flags
;
626 int cacheScheduleIOGetFlags(redisDb
*db
, robj
*key
) {
627 struct dictEntry
*de
= dictFind(db
->io_queued
,key
);
629 return (de
== NULL
) ? 0 : ((long) dictGetEntryVal(de
));
632 void cacheScheduleIO(redisDb
*db
, robj
*key
, int type
) {
636 if ((flags
= cacheScheduleIOGetFlags(db
,key
)) & type
) return;
638 redisLog(REDIS_DEBUG
,"Scheduling key %s for %s",
639 key
->ptr
, type
== REDIS_IO_LOAD
? "loading" : "saving");
640 cacheScheduleIOAddFlag(db
,key
,type
);
641 op
= zmalloc(sizeof(*op
));
646 op
->ctime
= time(NULL
);
648 /* Give priority to load operations if there are no save already
649 * in queue for the same key. */
650 if (type
== REDIS_IO_LOAD
&& !(flags
& REDIS_IO_SAVE
)) {
651 listAddNodeHead(server
.cache_io_queue
, op
);
652 cacheScheduleIOPushJobs(1);
654 /* FIXME: probably when this happens we want to at least move
655 * the write job about this queue on top, and set the creation time
656 * to a value that will force processing ASAP. */
657 listAddNodeTail(server
.cache_io_queue
, op
);
661 /* Push scheduled IO operations into IO Jobs that the IO thread can process.
662 * If 'onlyloads' is true only IO_LOAD jobs are processed: this is useful
663 * since it's save to push LOAD IO jobs from any place of the code, while
664 * SAVE io jobs should never be pushed while we are processing a command
665 * (not protected by lookupKey() that will block on keys in IO_SAVEINPROG
667 #define MAX_IO_JOBS_QUEUE 100
668 void cacheScheduleIOPushJobs(int onlyloads
) {
669 time_t now
= time(NULL
);
671 int jobs
, topush
= 0;
673 /* Sync stuff on disk, but only if we have less
674 * than MAX_IO_JOBS_QUEUE IO jobs. */
676 jobs
= listLength(server
.io_newjobs
);
679 topush
= MAX_IO_JOBS_QUEUE
-jobs
;
680 if (topush
< 0) topush
= 0;
681 if (topush
> (signed)listLength(server
.cache_io_queue
))
682 topush
= listLength(server
.cache_io_queue
);
684 while((ln
= listFirst(server
.cache_io_queue
)) != NULL
) {
685 ioop
*op
= ln
->value
;
690 if (op
->type
== REDIS_IO_LOAD
||
691 (!onlyloads
&& (now
- op
->ctime
) >= server
.cache_flush_delay
))
693 struct dictEntry
*de
;
696 /* Don't add a SAVE job in queue if there is already
697 * a save in progress for the same key. */
698 if (op
->type
== REDIS_IO_SAVE
&&
699 cacheScheduleIOGetFlags(op
->db
,op
->key
) & REDIS_IO_SAVEINPROG
)
701 /* Move the operation at the end of the list of there
702 * are other operations. Otherwise break, nothing to do
704 if (listLength(server
.cache_io_queue
) > 1) {
705 listDelNode(server
.cache_io_queue
,ln
);
706 listAddNodeTail(server
.cache_io_queue
,op
);
713 redisLog(REDIS_DEBUG
,"Creating IO %s Job for key %s",
714 op
->type
== REDIS_IO_LOAD
? "load" : "save", op
->key
->ptr
);
716 if (op
->type
== REDIS_IO_LOAD
) {
717 dsCreateIOJob(REDIS_IOJOB_LOAD
,op
->db
,op
->key
,NULL
);
719 /* Lookup the key, in order to put the current value in the IO
720 * Job. Otherwise if the key does not exists we schedule a disk
721 * store delete operation, setting the value to NULL. */
722 de
= dictFind(op
->db
->dict
,op
->key
->ptr
);
724 val
= dictGetEntryVal(de
);
726 /* Setting the value to NULL tells the IO thread to delete
727 * the key on disk. */
730 dsCreateIOJob(REDIS_IOJOB_SAVE
,op
->db
,op
->key
,val
);
732 /* Mark the operation as in progress. */
733 cacheScheduleIODelFlag(op
->db
,op
->key
,op
->type
);
734 cacheScheduleIOAddFlag(op
->db
,op
->key
,
735 (op
->type
== REDIS_IO_LOAD
) ? REDIS_IO_LOADINPROG
:
736 REDIS_IO_SAVEINPROG
);
737 /* Finally remove the operation from the queue.
738 * But we'll have trace of it in the hash table. */
739 listDelNode(server
.cache_io_queue
,ln
);
740 decrRefCount(op
->key
);
743 break; /* too early */
748 void cacheCron(void) {
750 cacheScheduleIOPushJobs(0);
752 /* Reclaim memory from the object cache */
753 while (server
.ds_enabled
&& zmalloc_used_memory() >
754 server
.cache_max_memory
)
758 if (cacheFreeOneEntry() == REDIS_OK
) done
++;
759 if (negativeCacheEvictOneEntry() == REDIS_OK
) done
++;
760 if (done
== 0) break; /* nothing more to free */
764 /* ========== Disk store cache - Blocking clients on missing keys =========== */
766 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
767 * If the key is already in memory we don't need to block.
769 * FIXME: we should try if it's actually better to suspend the client
770 * accessing an object that is being saved, and awake it only when
771 * the saving was completed.
773 * Otherwise if the key is not in memory, we block the client and start
774 * an IO Job to load it:
776 * the key is added to the io_keys list in the client structure, and also
777 * in the hash table mapping swapped keys to waiting clients, that is,
778 * server.io_waited_keys. */
779 int waitForSwappedKey(redisClient
*c
, robj
*key
) {
780 struct dictEntry
*de
;
783 /* Return ASAP if the key is in memory */
784 de
= dictFind(c
->db
->dict
,key
->ptr
);
785 if (de
!= NULL
) return 0;
787 /* Don't wait for keys we are sure are not on disk either */
788 if (!cacheKeyMayExist(c
->db
,key
)) return 0;
790 /* Add the key to the list of keys this client is waiting for.
791 * This maps clients to keys they are waiting for. */
792 listAddNodeTail(c
->io_keys
,key
);
795 /* Add the client to the swapped keys => clients waiting map. */
796 de
= dictFind(c
->db
->io_keys
,key
);
800 /* For every key we take a list of clients blocked for it */
802 retval
= dictAdd(c
->db
->io_keys
,key
,l
);
804 redisAssert(retval
== DICT_OK
);
806 l
= dictGetEntryVal(de
);
808 listAddNodeTail(l
,c
);
810 /* Are we already loading the key from disk? If not create a job */
812 cacheScheduleIO(c
->db
,key
,REDIS_IO_LOAD
);
816 /* Preload keys for any command with first, last and step values for
817 * the command keys prototype, as defined in the command table. */
818 void waitForMultipleSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
820 if (cmd
->vm_firstkey
== 0) return;
821 last
= cmd
->vm_lastkey
;
822 if (last
< 0) last
= argc
+last
;
823 for (j
= cmd
->vm_firstkey
; j
<= last
; j
+= cmd
->vm_keystep
) {
824 redisAssert(j
< argc
);
825 waitForSwappedKey(c
,argv
[j
]);
829 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
830 * Note that the number of keys to preload is user-defined, so we need to
831 * apply a sanity check against argc. */
832 void zunionInterBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
836 num
= atoi(argv
[2]->ptr
);
837 if (num
> (argc
-3)) return;
838 for (i
= 0; i
< num
; i
++) {
839 waitForSwappedKey(c
,argv
[3+i
]);
843 /* Preload keys needed to execute the entire MULTI/EXEC block.
845 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
846 * and will block the client when any command requires a swapped out value. */
847 void execBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
849 struct redisCommand
*mcmd
;
855 if (!(c
->flags
& REDIS_MULTI
)) return;
856 for (i
= 0; i
< c
->mstate
.count
; i
++) {
857 mcmd
= c
->mstate
.commands
[i
].cmd
;
858 margc
= c
->mstate
.commands
[i
].argc
;
859 margv
= c
->mstate
.commands
[i
].argv
;
861 if (mcmd
->vm_preload_proc
!= NULL
) {
862 mcmd
->vm_preload_proc(c
,mcmd
,margc
,margv
);
864 waitForMultipleSwappedKeys(c
,mcmd
,margc
,margv
);
869 /* Is this client attempting to run a command against swapped keys?
870 * If so, block it ASAP, load the keys in background, then resume it.
872 * The important idea about this function is that it can fail! If keys will
873 * still be swapped when the client is resumed, this key lookups will
874 * just block loading keys from disk. In practical terms this should only
875 * happen with SORT BY command or if there is a bug in this function.
877 * Return 1 if the client is marked as blocked, 0 if the client can
878 * continue as the keys it is going to access appear to be in memory. */
879 int blockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
) {
880 if (cmd
->vm_preload_proc
!= NULL
) {
881 cmd
->vm_preload_proc(c
,cmd
,c
->argc
,c
->argv
);
883 waitForMultipleSwappedKeys(c
,cmd
,c
->argc
,c
->argv
);
886 /* If the client was blocked for at least one key, mark it as blocked. */
887 if (listLength(c
->io_keys
)) {
888 c
->flags
|= REDIS_IO_WAIT
;
889 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
890 server
.cache_blocked_clients
++;
897 /* Remove the 'key' from the list of blocked keys for a given client.
899 * The function returns 1 when there are no longer blocking keys after
900 * the current one was removed (and the client can be unblocked). */
901 int dontWaitForSwappedKey(redisClient
*c
, robj
*key
) {
905 struct dictEntry
*de
;
907 /* The key object might be destroyed when deleted from the c->io_keys
908 * list (and the "key" argument is physically the same object as the
909 * object inside the list), so we need to protect it. */
912 /* Remove the key from the list of keys this client is waiting for. */
913 listRewind(c
->io_keys
,&li
);
914 while ((ln
= listNext(&li
)) != NULL
) {
915 if (equalStringObjects(ln
->value
,key
)) {
916 listDelNode(c
->io_keys
,ln
);
920 redisAssert(ln
!= NULL
);
922 /* Remove the client form the key => waiting clients map. */
923 de
= dictFind(c
->db
->io_keys
,key
);
924 redisAssert(de
!= NULL
);
925 l
= dictGetEntryVal(de
);
926 ln
= listSearchKey(l
,c
);
927 redisAssert(ln
!= NULL
);
929 if (listLength(l
) == 0)
930 dictDelete(c
->db
->io_keys
,key
);
933 return listLength(c
->io_keys
) == 0;
936 /* Every time we now a key was loaded back in memory, we handle clients
937 * waiting for this key if any. */
938 void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
) {
939 struct dictEntry
*de
;
944 de
= dictFind(db
->io_keys
,key
);
947 l
= dictGetEntryVal(de
);
949 /* Note: we can't use something like while(listLength(l)) as the list
950 * can be freed by the calling function when we remove the last element. */
953 redisClient
*c
= ln
->value
;
955 if (dontWaitForSwappedKey(c
,key
)) {
956 /* Put the client in the list of clients ready to go as we
957 * loaded all the keys about it. */
958 listAddNodeTail(server
.io_ready_clients
,c
);