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.
77 * - When putting IO read operations on top of the queue, do this only if
78 * the already-on-top operation is not a save or if it is a save that
79 * is scheduled for later execution. If there is a save that is ready to
80 * fire, let's insert the load operation just before the first save that
81 * is scheduled for later exection for instance.
83 * - Support MULTI/EXEC transactions via a journal file, that is played on
84 * startup to check if there is cleanup to do. This way we can implement
85 * transactions with our simple file based KV store.
88 /* Virtual Memory is composed mainly of two subsystems:
89 * - Blocking Virutal Memory
90 * - Threaded Virtual Memory I/O
91 * The two parts are not fully decoupled, but functions are split among two
92 * different sections of the source code (delimited by comments) in order to
93 * make more clear what functionality is about the blocking VM and what about
94 * the threaded (not blocking) VM.
98 * Redis VM is a blocking VM (one that blocks reading swapped values from
99 * disk into memory when a value swapped out is needed in memory) that is made
100 * unblocking by trying to examine the command argument vector in order to
101 * load in background values that will likely be needed in order to exec
102 * the command. The command is executed only once all the relevant keys
103 * are loaded into memory.
105 * This basically is almost as simple of a blocking VM, but almost as parallel
106 * as a fully non-blocking VM.
109 void spawnIOThread(void);
110 int cacheScheduleIOPushJobs(int flags
);
111 int processActiveIOJobs(int max
);
113 /* =================== Virtual Memory - Blocking Side ====================== */
119 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
121 redisLog(REDIS_NOTICE
,"Opening Disk Store: %s", server
.ds_path
);
122 /* Open Disk Store */
123 if (dsOpen() != REDIS_OK
) {
124 redisLog(REDIS_WARNING
,"Fatal error opening disk store. Exiting.");
128 /* Initialize threaded I/O for Object Cache */
129 server
.io_newjobs
= listCreate();
130 server
.io_processing
= listCreate();
131 server
.io_processed
= listCreate();
132 server
.io_ready_clients
= listCreate();
133 pthread_mutex_init(&server
.io_mutex
,NULL
);
134 pthread_cond_init(&server
.io_condvar
,NULL
);
135 server
.io_active_threads
= 0;
136 if (pipe(pipefds
) == -1) {
137 redisLog(REDIS_WARNING
,"Unable to intialized DS: pipe(2): %s. Exiting."
141 server
.io_ready_pipe_read
= pipefds
[0];
142 server
.io_ready_pipe_write
= pipefds
[1];
143 redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
);
144 /* LZF requires a lot of stack */
145 pthread_attr_init(&server
.io_threads_attr
);
146 pthread_attr_getstacksize(&server
.io_threads_attr
, &stacksize
);
148 /* Solaris may report a stacksize of 0, let's set it to 1 otherwise
149 * multiplying it by 2 in the while loop later will not really help ;) */
150 if (!stacksize
) stacksize
= 1;
152 while (stacksize
< REDIS_THREAD_STACK_SIZE
) stacksize
*= 2;
153 pthread_attr_setstacksize(&server
.io_threads_attr
, stacksize
);
154 /* Listen for events in the threaded I/O pipe */
155 if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
,
156 vmThreadedIOCompletedJob
, NULL
) == AE_ERR
)
157 oom("creating file event");
159 /* Spawn our I/O thread */
163 /* Compute how good candidate the specified object is for eviction.
164 * An higher number means a better candidate. */
165 double computeObjectSwappability(robj
*o
) {
166 /* actual age can be >= minage, but not < minage. As we use wrapping
167 * 21 bit clocks with minutes resolution for the LRU. */
168 return (double) estimateObjectIdleTime(o
);
171 /* Try to free one entry from the diskstore object cache */
172 int cacheFreeOneEntry(void) {
174 struct dictEntry
*best
= NULL
;
175 double best_swappability
= 0;
176 redisDb
*best_db
= NULL
;
180 for (j
= 0; j
< server
.dbnum
; j
++) {
181 redisDb
*db
= server
.db
+j
;
182 /* Why maxtries is set to 100?
183 * Because this way (usually) we'll find 1 object even if just 1% - 2%
184 * are swappable objects */
187 if (dictSize(db
->dict
) == 0) continue;
188 for (i
= 0; i
< 5; i
++) {
194 if (maxtries
) maxtries
--;
195 de
= dictGetRandomKey(db
->dict
);
196 keystr
= dictGetEntryKey(de
);
197 val
= dictGetEntryVal(de
);
198 initStaticStringObject(keyobj
,keystr
);
200 /* Don't remove objects that are currently target of a
201 * read or write operation. */
202 if (cacheScheduleIOGetFlags(db
,&keyobj
) != 0) {
203 if (maxtries
) i
--; /* don't count this try */
206 swappability
= computeObjectSwappability(val
);
207 if (!best
|| swappability
> best_swappability
) {
209 best_swappability
= swappability
;
215 /* Was not able to fix a single object... we should check if our
216 * IO queues have stuff in queue, and try to consume the queue
217 * otherwise we'll use an infinite amount of memory if changes to
218 * the dataset are faster than I/O */
219 if (listLength(server
.cache_io_queue
) > 0) {
220 redisLog(REDIS_DEBUG
,"--- Busy waiting IO to reclaim memory");
221 cacheScheduleIOPushJobs(REDIS_IO_ASAP
);
222 processActiveIOJobs(1);
225 /* Nothing to free at all... */
228 key
= dictGetEntryKey(best
);
229 val
= dictGetEntryVal(best
);
231 redisLog(REDIS_DEBUG
,"Key selected for cache eviction: %s swappability:%f",
232 key
, best_swappability
);
234 /* Delete this key from memory */
236 robj
*kobj
= createStringObject(key
,sdslen(key
));
237 dbDelete(best_db
,kobj
);
243 /* Return true if it's safe to swap out objects in a given moment.
244 * Basically we don't want to swap objects out while there is a BGSAVE
245 * or a BGAEOREWRITE running in backgroud. */
246 int dsCanTouchDiskStore(void) {
247 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
250 /* ==================== Disk store negative caching ========================
252 * When disk store is enabled, we need negative caching, that is, to remember
253 * keys that are for sure *not* on the disk key-value store.
255 * This is usefuls because without negative caching cache misses will cost us
256 * a disk lookup, even if the same non existing key is accessed again and again.
258 * With negative caching we remember that the key is not on disk, so if it's
259 * not in memory and we have a negative cache entry, we don't try a disk
263 /* Returns true if the specified key may exists on disk, that is, we don't
264 * have an entry in our negative cache for this key */
265 int cacheKeyMayExist(redisDb
*db
, robj
*key
) {
266 return dictFind(db
->io_negcache
,key
) == NULL
;
269 /* Set the specified key as an entry that may possibily exist on disk, that is,
270 * remove the negative cache entry for this key if any. */
271 void cacheSetKeyMayExist(redisDb
*db
, robj
*key
) {
272 dictDelete(db
->io_negcache
,key
);
275 /* Set the specified key as non existing on disk, that is, create a negative
276 * cache entry for this key. */
277 void cacheSetKeyDoesNotExist(redisDb
*db
, robj
*key
) {
278 if (dictReplace(db
->io_negcache
,key
,(void*)time(NULL
))) {
283 /* Remove one entry from negative cache using approximated LRU. */
284 int negativeCacheEvictOneEntry(void) {
285 struct dictEntry
*de
;
287 redisDb
*best_db
= NULL
;
288 time_t time
, best_time
= 0;
291 for (j
= 0; j
< server
.dbnum
; j
++) {
292 redisDb
*db
= server
.db
+j
;
295 if (dictSize(db
->io_negcache
) == 0) continue;
296 for (i
= 0; i
< 3; i
++) {
297 de
= dictGetRandomKey(db
->io_negcache
);
298 time
= (time_t) dictGetEntryVal(de
);
300 if (best
== NULL
|| time
< best_time
) {
301 best
= dictGetEntryKey(de
);
308 dictDelete(best_db
->io_negcache
,best
);
315 /* ================== Disk store cache - Threaded I/O ====================== */
317 void freeIOJob(iojob
*j
) {
318 decrRefCount(j
->key
);
319 /* j->val can be NULL if the job is about deleting the key from disk. */
320 if (j
->val
) decrRefCount(j
->val
);
324 /* Every time a thread finished a Job, it writes a byte into the write side
325 * of an unix pipe in order to "awake" the main thread, and this function
327 void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
,
331 int retval
, processed
= 0, toprocess
= -1;
334 REDIS_NOTUSED(privdata
);
336 /* For every byte we read in the read side of the pipe, there is one
337 * I/O job completed to process. */
338 while((retval
= read(fd
,buf
,1)) == 1) {
342 redisLog(REDIS_DEBUG
,"Processing I/O completed job");
344 /* Get the processed element (the oldest one) */
346 redisAssert(listLength(server
.io_processed
) != 0);
347 if (toprocess
== -1) {
348 toprocess
= (listLength(server
.io_processed
)*REDIS_MAX_COMPLETED_JOBS_PROCESSED
)/100;
349 if (toprocess
<= 0) toprocess
= 1;
351 ln
= listFirst(server
.io_processed
);
353 listDelNode(server
.io_processed
,ln
);
356 /* Post process it in the main thread, as there are things we
357 * can do just here to avoid race conditions and/or invasive locks */
358 redisLog(REDIS_DEBUG
,"COMPLETED Job type %s, key: %s",
359 (j
->type
== REDIS_IOJOB_LOAD
) ? "load" : "save",
360 (unsigned char*)j
->key
->ptr
);
361 if (j
->type
== REDIS_IOJOB_LOAD
) {
362 /* Create the key-value pair in the in-memory database */
363 if (j
->val
!= NULL
) {
364 /* Note: it's possible that the key is already in memory
365 * due to a blocking load operation. */
366 if (dbAdd(j
->db
,j
->key
,j
->val
) == REDIS_OK
) {
367 incrRefCount(j
->val
);
368 if (j
->expire
!= -1) setExpire(j
->db
,j
->key
,j
->expire
);
371 /* Key not found on disk. If it is also not in memory
372 * as a cached object, nor there is a job writing it
373 * in background, we are sure the key does not exist
376 * So we set a negative cache entry avoiding that the
377 * resumed client will block load what does not exist... */
378 if (dictFind(j
->db
->dict
,j
->key
->ptr
) == NULL
&&
379 (cacheScheduleIOGetFlags(j
->db
,j
->key
) &
380 (REDIS_IO_SAVE
|REDIS_IO_SAVEINPROG
)) == 0)
382 cacheSetKeyDoesNotExist(j
->db
,j
->key
);
385 cacheScheduleIODelFlag(j
->db
,j
->key
,REDIS_IO_LOADINPROG
);
386 handleClientsBlockedOnSwappedKey(j
->db
,j
->key
);
388 } else if (j
->type
== REDIS_IOJOB_SAVE
) {
389 cacheScheduleIODelFlag(j
->db
,j
->key
,REDIS_IO_SAVEINPROG
);
393 if (processed
== toprocess
) return;
395 if (retval
< 0 && errno
!= EAGAIN
) {
396 redisLog(REDIS_WARNING
,
397 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
402 void lockThreadedIO(void) {
403 pthread_mutex_lock(&server
.io_mutex
);
406 void unlockThreadedIO(void) {
407 pthread_mutex_unlock(&server
.io_mutex
);
410 void *IOThreadEntryPoint(void *arg
) {
415 pthread_detach(pthread_self());
418 /* Get a new job to process */
419 if (listLength(server
.io_newjobs
) == 0) {
420 /* Wait for more work to do */
421 pthread_cond_wait(&server
.io_condvar
,&server
.io_mutex
);
424 redisLog(REDIS_DEBUG
,"%ld IO jobs to process",
425 listLength(server
.io_newjobs
));
426 ln
= listFirst(server
.io_newjobs
);
428 listDelNode(server
.io_newjobs
,ln
);
429 /* Add the job in the processing queue */
430 listAddNodeTail(server
.io_processing
,j
);
431 ln
= listLast(server
.io_processing
); /* We use ln later to remove it */
434 redisLog(REDIS_DEBUG
,"Thread %ld: new job type %s: %p about key '%s'",
435 (long) pthread_self(),
436 (j
->type
== REDIS_IOJOB_LOAD
) ? "load" : "save",
437 (void*)j
, (char*)j
->key
->ptr
);
439 /* Process the Job */
440 if (j
->type
== REDIS_IOJOB_LOAD
) {
443 j
->val
= dsGet(j
->db
,j
->key
,&expire
);
444 if (j
->val
) j
->expire
= expire
;
445 } else if (j
->type
== REDIS_IOJOB_SAVE
) {
447 dsSet(j
->db
,j
->key
,j
->val
);
453 /* Done: insert the job into the processed queue */
454 redisLog(REDIS_DEBUG
,"Thread %ld completed the job: %p (key %s)",
455 (long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
);
458 listDelNode(server
.io_processing
,ln
);
459 listAddNodeTail(server
.io_processed
,j
);
461 /* Signal the main thread there is new stuff to process */
462 redisAssert(write(server
.io_ready_pipe_write
,"x",1) == 1);
464 /* never reached, but that's the full pattern... */
469 void spawnIOThread(void) {
471 sigset_t mask
, omask
;
475 sigaddset(&mask
,SIGCHLD
);
476 sigaddset(&mask
,SIGHUP
);
477 sigaddset(&mask
,SIGPIPE
);
478 pthread_sigmask(SIG_SETMASK
, &mask
, &omask
);
479 while ((err
= pthread_create(&thread
,&server
.io_threads_attr
,IOThreadEntryPoint
,NULL
)) != 0) {
480 redisLog(REDIS_WARNING
,"Unable to spawn an I/O thread: %s",
484 pthread_sigmask(SIG_SETMASK
, &omask
, NULL
);
485 server
.io_active_threads
++;
488 /* Wait that up to 'max' pending IO Jobs are processed by the I/O thread.
489 * From our point of view an IO job processed means that the count of
490 * server.io_processed must increase by one.
492 * If max is -1, all the pending IO jobs will be processed.
494 * Returns the number of IO jobs processed.
496 * NOTE: while this may appear like a busy loop, we are actually blocked
497 * by IO since we continuously acquire/release the IO lock. */
498 int processActiveIOJobs(int max
) {
501 while(max
== -1 || max
> 0) {
502 int io_processed_len
;
505 if (listLength(server
.io_newjobs
) == 0 &&
506 listLength(server
.io_processing
) == 0)
508 /* There is nothing more to process */
514 /* If there are new jobs we need to signal the thread to
515 * process the next one. FIXME: drop this if useless. */
516 redisLog(REDIS_DEBUG
,"waitEmptyIOJobsQueue: new %d, processing %d",
517 listLength(server
.io_newjobs
),
518 listLength(server
.io_processing
));
520 if (listLength(server
.io_newjobs
)) {
521 pthread_cond_signal(&server
.io_condvar
);
525 /* Check if we can process some finished job */
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);
532 if (max
!= -1) max
--;
538 void waitEmptyIOJobsQueue(void) {
539 processActiveIOJobs(-1);
542 /* Process up to 'max' IO Jobs already completed by threads but still waiting
543 * processing from the main thread.
545 * If max == -1 all the pending jobs are processed.
547 * The number of processed jobs is returned. */
548 int processPendingIOJobs(int max
) {
551 while(max
== -1 || max
> 0) {
552 int io_processed_len
;
555 io_processed_len
= listLength(server
.io_processed
);
557 if (io_processed_len
== 0) break;
558 vmThreadedIOCompletedJob(NULL
,server
.io_ready_pipe_read
,
559 (void*)0xdeadbeef,0);
560 if (max
!= -1) max
--;
566 void processAllPendingIOJobs(void) {
567 processPendingIOJobs(-1);
570 /* This function must be called while with threaded IO locked */
571 void queueIOJob(iojob
*j
) {
572 redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n",
573 (void*)j
, j
->type
, (char*)j
->key
->ptr
);
574 listAddNodeTail(server
.io_newjobs
,j
);
575 if (server
.io_active_threads
< server
.vm_max_threads
)
579 /* Consume all the IO scheduled operations, and all the thread IO jobs
580 * so that eventually the state of diskstore is a point-in-time snapshot.
582 * This is useful when we need to BGSAVE with diskstore enabled. */
583 void cacheForcePointInTime(void) {
584 redisLog(REDIS_NOTICE
,"Diskstore: synching on disk to reach point-in-time state.");
585 while (listLength(server
.cache_io_queue
) != 0) {
586 cacheScheduleIOPushJobs(REDIS_IO_ASAP
);
587 processActiveIOJobs(1);
589 waitEmptyIOJobsQueue();
590 processAllPendingIOJobs();
593 void cacheCreateIOJob(int type
, redisDb
*db
, robj
*key
, robj
*val
) {
596 j
= zmalloc(sizeof(*j
));
602 if (val
) incrRefCount(val
);
606 pthread_cond_signal(&server
.io_condvar
);
610 /* ============= Disk store cache - Scheduling of IO operations =============
612 * We use a queue and an hash table to hold the state of IO operations
613 * so that's fast to lookup if there is already an IO operation in queue
616 * There are two types of IO operations for a given key:
617 * REDIS_IO_LOAD and REDIS_IO_SAVE.
619 * The function cacheScheduleIO() function pushes the specified IO operation
620 * in the queue, but avoid adding the same key for the same operation
621 * multiple times, thanks to the associated hash table.
623 * We take a set of flags per every key, so when the scheduled IO operation
624 * gets moved from the scheduled queue to the actual IO Jobs queue that
625 * is processed by the IO thread, we flag it as IO_LOADINPROG or
628 * So for every given key we always know if there is some IO operation
629 * scheduled, or in progress, for this key.
631 * NOTE: all this is very important in order to guarantee correctness of
632 * the Disk Store Cache. Jobs are always queued here. Load jobs are
633 * queued at the head for faster execution only in the case there is not
634 * already a write operation of some kind for this job.
636 * So we have ordering, but can do exceptions when there are no already
637 * operations for a given key. Also when we need to block load a given
638 * key, for an immediate lookup operation, we can check if the key can
639 * be accessed synchronously without race conditions (no IN PROGRESS
640 * operations for this key), otherwise we blocking wait for completion. */
642 #define REDIS_IO_LOAD 1
643 #define REDIS_IO_SAVE 2
644 #define REDIS_IO_LOADINPROG 4
645 #define REDIS_IO_SAVEINPROG 8
647 void cacheScheduleIOAddFlag(redisDb
*db
, robj
*key
, long flag
) {
648 struct dictEntry
*de
= dictFind(db
->io_queued
,key
);
651 dictAdd(db
->io_queued
,key
,(void*)flag
);
655 long flags
= (long) dictGetEntryVal(de
);
658 redisLog(REDIS_WARNING
,"Adding the same flag again: was: %ld, addede: %ld",flags
,flag
);
659 redisAssert(!(flags
& flag
));
662 dictGetEntryVal(de
) = (void*) flags
;
666 void cacheScheduleIODelFlag(redisDb
*db
, robj
*key
, long flag
) {
667 struct dictEntry
*de
= dictFind(db
->io_queued
,key
);
670 redisAssert(de
!= NULL
);
671 flags
= (long) dictGetEntryVal(de
);
672 redisAssert(flags
& flag
);
675 dictDelete(db
->io_queued
,key
);
677 dictGetEntryVal(de
) = (void*) flags
;
681 int cacheScheduleIOGetFlags(redisDb
*db
, robj
*key
) {
682 struct dictEntry
*de
= dictFind(db
->io_queued
,key
);
684 return (de
== NULL
) ? 0 : ((long) dictGetEntryVal(de
));
687 void cacheScheduleIO(redisDb
*db
, robj
*key
, int type
) {
691 if ((flags
= cacheScheduleIOGetFlags(db
,key
)) & type
) return;
693 redisLog(REDIS_DEBUG
,"Scheduling key %s for %s",
694 key
->ptr
, type
== REDIS_IO_LOAD
? "loading" : "saving");
695 cacheScheduleIOAddFlag(db
,key
,type
);
696 op
= zmalloc(sizeof(*op
));
701 op
->ctime
= time(NULL
);
703 /* Give priority to load operations if there are no save already
704 * in queue for the same key. */
705 if (type
== REDIS_IO_LOAD
&& !(flags
& REDIS_IO_SAVE
)) {
706 listAddNodeHead(server
.cache_io_queue
, op
);
707 cacheScheduleIOPushJobs(REDIS_IO_ONLYLOADS
);
709 /* FIXME: probably when this happens we want to at least move
710 * the write job about this queue on top, and set the creation time
711 * to a value that will force processing ASAP. */
712 listAddNodeTail(server
.cache_io_queue
, op
);
716 /* Push scheduled IO operations into IO Jobs that the IO thread can process.
718 * If flags include REDIS_IO_ONLYLOADS only load jobs are processed:this is
719 * useful since it's safe to push LOAD IO jobs from any place of the code, while
720 * SAVE io jobs should never be pushed while we are processing a command
721 * (not protected by lookupKey() that will block on keys in IO_SAVEINPROG
724 * The REDIS_IO_ASAP flag tells the function to don't wait for the IO job
725 * scheduled completion time, but just do the operation ASAP. This is useful
726 * when we need to reclaim memory from the IO queue.
728 #define MAX_IO_JOBS_QUEUE 100
729 int cacheScheduleIOPushJobs(int flags
) {
730 time_t now
= time(NULL
);
732 int jobs
, topush
= 0, pushed
= 0;
734 /* Sync stuff on disk, but only if we have less
735 * than MAX_IO_JOBS_QUEUE IO jobs. */
737 jobs
= listLength(server
.io_newjobs
);
740 topush
= MAX_IO_JOBS_QUEUE
-jobs
;
741 if (topush
< 0) topush
= 0;
742 if (topush
> (signed)listLength(server
.cache_io_queue
))
743 topush
= listLength(server
.cache_io_queue
);
745 while((ln
= listFirst(server
.cache_io_queue
)) != NULL
) {
746 ioop
*op
= ln
->value
;
747 struct dictEntry
*de
;
753 if (op
->type
!= REDIS_IO_LOAD
&& flags
& REDIS_IO_ONLYLOADS
) break;
755 if (!(flags
& REDIS_IO_ASAP
) &&
756 (now
- op
->ctime
) < server
.cache_flush_delay
) break;
758 /* Don't add a SAVE job in the IO thread queue if there is already
759 * a save in progress for the same key. */
760 if (op
->type
== REDIS_IO_SAVE
&&
761 cacheScheduleIOGetFlags(op
->db
,op
->key
) & REDIS_IO_SAVEINPROG
)
763 /* Move the operation at the end of the list if there
764 * are other operations, so we can try to process the next one.
765 * Otherwise break, nothing to do here. */
766 if (listLength(server
.cache_io_queue
) > 1) {
767 listDelNode(server
.cache_io_queue
,ln
);
768 listAddNodeTail(server
.cache_io_queue
,op
);
775 redisLog(REDIS_DEBUG
,"Creating IO %s Job for key %s",
776 op
->type
== REDIS_IO_LOAD
? "load" : "save", op
->key
->ptr
);
778 if (op
->type
== REDIS_IO_LOAD
) {
779 cacheCreateIOJob(REDIS_IOJOB_LOAD
,op
->db
,op
->key
,NULL
);
781 /* Lookup the key, in order to put the current value in the IO
782 * Job. Otherwise if the key does not exists we schedule a disk
783 * store delete operation, setting the value to NULL. */
784 de
= dictFind(op
->db
->dict
,op
->key
->ptr
);
786 val
= dictGetEntryVal(de
);
788 /* Setting the value to NULL tells the IO thread to delete
789 * the key on disk. */
792 cacheCreateIOJob(REDIS_IOJOB_SAVE
,op
->db
,op
->key
,val
);
794 /* Mark the operation as in progress. */
795 cacheScheduleIODelFlag(op
->db
,op
->key
,op
->type
);
796 cacheScheduleIOAddFlag(op
->db
,op
->key
,
797 (op
->type
== REDIS_IO_LOAD
) ? REDIS_IO_LOADINPROG
:
798 REDIS_IO_SAVEINPROG
);
799 /* Finally remove the operation from the queue.
800 * But we'll have trace of it in the hash table. */
801 listDelNode(server
.cache_io_queue
,ln
);
802 decrRefCount(op
->key
);
809 void cacheCron(void) {
811 cacheScheduleIOPushJobs(0);
813 /* Reclaim memory from the object cache */
814 while (server
.ds_enabled
&& zmalloc_used_memory() >
815 server
.cache_max_memory
)
819 if (cacheFreeOneEntry() == REDIS_OK
) done
++;
820 if (negativeCacheEvictOneEntry() == REDIS_OK
) done
++;
821 if (done
== 0) break; /* nothing more to free */
825 /* ========== Disk store cache - Blocking clients on missing keys =========== */
827 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
828 * If the key is already in memory we don't need to block.
830 * FIXME: we should try if it's actually better to suspend the client
831 * accessing an object that is being saved, and awake it only when
832 * the saving was completed.
834 * Otherwise if the key is not in memory, we block the client and start
835 * an IO Job to load it:
837 * the key is added to the io_keys list in the client structure, and also
838 * in the hash table mapping swapped keys to waiting clients, that is,
839 * server.io_waited_keys. */
840 int waitForSwappedKey(redisClient
*c
, robj
*key
) {
841 struct dictEntry
*de
;
844 /* Return ASAP if the key is in memory */
845 de
= dictFind(c
->db
->dict
,key
->ptr
);
846 if (de
!= NULL
) return 0;
848 /* Don't wait for keys we are sure are not on disk either */
849 if (!cacheKeyMayExist(c
->db
,key
)) return 0;
851 /* Add the key to the list of keys this client is waiting for.
852 * This maps clients to keys they are waiting for. */
853 listAddNodeTail(c
->io_keys
,key
);
856 /* Add the client to the swapped keys => clients waiting map. */
857 de
= dictFind(c
->db
->io_keys
,key
);
861 /* For every key we take a list of clients blocked for it */
863 retval
= dictAdd(c
->db
->io_keys
,key
,l
);
865 redisAssert(retval
== DICT_OK
);
867 l
= dictGetEntryVal(de
);
869 listAddNodeTail(l
,c
);
871 /* Are we already loading the key from disk? If not create a job */
873 cacheScheduleIO(c
->db
,key
,REDIS_IO_LOAD
);
877 /* Preload keys for any command with first, last and step values for
878 * the command keys prototype, as defined in the command table. */
879 void waitForMultipleSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
881 if (cmd
->vm_firstkey
== 0) return;
882 last
= cmd
->vm_lastkey
;
883 if (last
< 0) last
= argc
+last
;
884 for (j
= cmd
->vm_firstkey
; j
<= last
; j
+= cmd
->vm_keystep
) {
885 redisAssert(j
< argc
);
886 waitForSwappedKey(c
,argv
[j
]);
890 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
891 * Note that the number of keys to preload is user-defined, so we need to
892 * apply a sanity check against argc. */
893 void zunionInterBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
897 num
= atoi(argv
[2]->ptr
);
898 if (num
> (argc
-3)) return;
899 for (i
= 0; i
< num
; i
++) {
900 waitForSwappedKey(c
,argv
[3+i
]);
904 /* Preload keys needed to execute the entire MULTI/EXEC block.
906 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
907 * and will block the client when any command requires a swapped out value. */
908 void execBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
910 struct redisCommand
*mcmd
;
916 if (!(c
->flags
& REDIS_MULTI
)) return;
917 for (i
= 0; i
< c
->mstate
.count
; i
++) {
918 mcmd
= c
->mstate
.commands
[i
].cmd
;
919 margc
= c
->mstate
.commands
[i
].argc
;
920 margv
= c
->mstate
.commands
[i
].argv
;
922 if (mcmd
->vm_preload_proc
!= NULL
) {
923 mcmd
->vm_preload_proc(c
,mcmd
,margc
,margv
);
925 waitForMultipleSwappedKeys(c
,mcmd
,margc
,margv
);
930 /* Is this client attempting to run a command against swapped keys?
931 * If so, block it ASAP, load the keys in background, then resume it.
933 * The important idea about this function is that it can fail! If keys will
934 * still be swapped when the client is resumed, this key lookups will
935 * just block loading keys from disk. In practical terms this should only
936 * happen with SORT BY command or if there is a bug in this function.
938 * Return 1 if the client is marked as blocked, 0 if the client can
939 * continue as the keys it is going to access appear to be in memory. */
940 int blockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
) {
941 if (cmd
->vm_preload_proc
!= NULL
) {
942 cmd
->vm_preload_proc(c
,cmd
,c
->argc
,c
->argv
);
944 waitForMultipleSwappedKeys(c
,cmd
,c
->argc
,c
->argv
);
947 /* If the client was blocked for at least one key, mark it as blocked. */
948 if (listLength(c
->io_keys
)) {
949 c
->flags
|= REDIS_IO_WAIT
;
950 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
951 server
.cache_blocked_clients
++;
958 /* Remove the 'key' from the list of blocked keys for a given client.
960 * The function returns 1 when there are no longer blocking keys after
961 * the current one was removed (and the client can be unblocked). */
962 int dontWaitForSwappedKey(redisClient
*c
, robj
*key
) {
966 struct dictEntry
*de
;
968 /* The key object might be destroyed when deleted from the c->io_keys
969 * list (and the "key" argument is physically the same object as the
970 * object inside the list), so we need to protect it. */
973 /* Remove the key from the list of keys this client is waiting for. */
974 listRewind(c
->io_keys
,&li
);
975 while ((ln
= listNext(&li
)) != NULL
) {
976 if (equalStringObjects(ln
->value
,key
)) {
977 listDelNode(c
->io_keys
,ln
);
981 redisAssert(ln
!= NULL
);
983 /* Remove the client form the key => waiting clients map. */
984 de
= dictFind(c
->db
->io_keys
,key
);
985 redisAssert(de
!= NULL
);
986 l
= dictGetEntryVal(de
);
987 ln
= listSearchKey(l
,c
);
988 redisAssert(ln
!= NULL
);
990 if (listLength(l
) == 0)
991 dictDelete(c
->db
->io_keys
,key
);
994 return listLength(c
->io_keys
) == 0;
997 /* Every time we now a key was loaded back in memory, we handle clients
998 * waiting for this key if any. */
999 void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
) {
1000 struct dictEntry
*de
;
1005 de
= dictFind(db
->io_keys
,key
);
1008 l
= dictGetEntryVal(de
);
1009 len
= listLength(l
);
1010 /* Note: we can't use something like while(listLength(l)) as the list
1011 * can be freed by the calling function when we remove the last element. */
1014 redisClient
*c
= ln
->value
;
1016 if (dontWaitForSwappedKey(c
,key
)) {
1017 /* Put the client in the list of clients ready to go as we
1018 * loaded all the keys about it. */
1019 listAddNodeTail(server
.io_ready_clients
,c
);