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?
89 /* Virtual Memory is composed mainly of two subsystems:
90 * - Blocking Virutal Memory
91 * - Threaded Virtual Memory I/O
92 * The two parts are not fully decoupled, but functions are split among two
93 * different sections of the source code (delimited by comments) in order to
94 * make more clear what functionality is about the blocking VM and what about
95 * the threaded (not blocking) VM.
99 * Redis VM is a blocking VM (one that blocks reading swapped values from
100 * disk into memory when a value swapped out is needed in memory) that is made
101 * unblocking by trying to examine the command argument vector in order to
102 * load in background values that will likely be needed in order to exec
103 * the command. The command is executed only once all the relevant keys
104 * are loaded into memory.
106 * This basically is almost as simple of a blocking VM, but almost as parallel
107 * as a fully non-blocking VM.
110 /* =================== Virtual Memory - Blocking Side ====================== */
118 if (server
.vm_max_threads
!= 0)
119 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
121 redisLog(REDIS_NOTICE
,"Using '%s' as swap file",server
.vm_swap_file
);
122 /* Try to open the old swap file, otherwise create it */
123 if ((server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b")) == NULL
) {
124 server
.vm_fp
= fopen(server
.vm_swap_file
,"w+b");
126 if (server
.vm_fp
== NULL
) {
127 redisLog(REDIS_WARNING
,
128 "Can't open the swap file: %s. Exiting.",
132 server
.vm_fd
= fileno(server
.vm_fp
);
133 /* Lock the swap file for writing, this is useful in order to avoid
134 * another instance to use the same swap file for a config error. */
136 fl
.l_whence
= SEEK_SET
;
137 fl
.l_start
= fl
.l_len
= 0;
138 if (fcntl(server
.vm_fd
,F_SETLK
,&fl
) == -1) {
139 redisLog(REDIS_WARNING
,
140 "Can't lock the swap file at '%s': %s. Make sure it is not used by another Redis instance.", server
.vm_swap_file
, strerror(errno
));
144 server
.vm_next_page
= 0;
145 server
.vm_near_pages
= 0;
146 server
.vm_stats_used_pages
= 0;
147 server
.vm_stats_swapped_objects
= 0;
148 server
.vm_stats_swapouts
= 0;
149 server
.vm_stats_swapins
= 0;
150 totsize
= server
.vm_pages
*server
.vm_page_size
;
151 redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
);
152 if (ftruncate(server
.vm_fd
,totsize
) == -1) {
153 redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.",
157 redisLog(REDIS_NOTICE
,"Swap file allocated with success");
159 server
.vm_bitmap
= zcalloc((server
.vm_pages
+7)/8);
160 redisLog(REDIS_VERBOSE
,"Allocated %lld bytes page table for %lld pages",
161 (long long) (server
.vm_pages
+7)/8, server
.vm_pages
);
163 /* Initialize threaded I/O (used by Virtual Memory) */
164 server
.io_newjobs
= listCreate();
165 server
.io_processing
= listCreate();
166 server
.io_processed
= listCreate();
167 server
.io_ready_clients
= listCreate();
168 pthread_mutex_init(&server
.io_mutex
,NULL
);
169 pthread_mutex_init(&server
.io_swapfile_mutex
,NULL
);
170 server
.io_active_threads
= 0;
171 if (pipe(pipefds
) == -1) {
172 redisLog(REDIS_WARNING
,"Unable to intialized VM: pipe(2): %s. Exiting."
176 server
.io_ready_pipe_read
= pipefds
[0];
177 server
.io_ready_pipe_write
= pipefds
[1];
178 redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
);
179 /* LZF requires a lot of stack */
180 pthread_attr_init(&server
.io_threads_attr
);
181 pthread_attr_getstacksize(&server
.io_threads_attr
, &stacksize
);
183 /* Solaris may report a stacksize of 0, let's set it to 1 otherwise
184 * multiplying it by 2 in the while loop later will not really help ;) */
185 if (!stacksize
) stacksize
= 1;
187 while (stacksize
< REDIS_THREAD_STACK_SIZE
) stacksize
*= 2;
188 pthread_attr_setstacksize(&server
.io_threads_attr
, stacksize
);
189 /* Listen for events in the threaded I/O pipe */
190 if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
,
191 vmThreadedIOCompletedJob
, NULL
) == AE_ERR
)
192 oom("creating file event");
195 /* Write the specified object at the specified page of the swap file */
196 int vmWriteObjectOnSwap(robj
*o
, off_t page
) {
197 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
198 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
199 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
200 redisLog(REDIS_WARNING
,
201 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
205 rdbSaveObject(server
.vm_fp
,o
);
206 fflush(server
.vm_fp
);
207 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
211 /* Transfers the 'val' object to disk. Store all the information
212 * a 'vmpointer' object containing all the information needed to load the
213 * object back later is returned.
215 * If we can't find enough contiguous empty pages to swap the object on disk
216 * NULL is returned. */
217 vmpointer
*vmSwapObjectBlocking(robj
*val
) {
218 off_t pages
= rdbSavedObjectPages(val
);
222 redisAssert(val
->storage
== REDIS_VM_MEMORY
);
223 redisAssert(val
->refcount
== 1);
224 if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return NULL
;
225 if (vmWriteObjectOnSwap(val
,page
) == REDIS_ERR
) return NULL
;
227 vp
= createVmPointer(val
->type
);
229 vp
->usedpages
= pages
;
230 decrRefCount(val
); /* Deallocate the object from memory. */
231 vmMarkPagesUsed(page
,pages
);
232 redisLog(REDIS_DEBUG
,"VM: object %p swapped out at %lld (%lld pages)",
234 (unsigned long long) page
, (unsigned long long) pages
);
235 server
.vm_stats_swapped_objects
++;
236 server
.vm_stats_swapouts
++;
240 robj
*vmReadObjectFromSwap(off_t page
, int type
) {
243 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
244 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
245 redisLog(REDIS_WARNING
,
246 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
250 o
= rdbLoadObject(type
,server
.vm_fp
);
252 redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno
));
255 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
259 /* Load the specified object from swap to memory.
260 * The newly allocated object is returned.
262 * If preview is true the unserialized object is returned to the caller but
263 * the pages are not marked as freed, nor the vp object is freed. */
264 robj
*vmGenericLoadObject(vmpointer
*vp
, int preview
) {
267 redisAssert(vp
->type
== REDIS_VMPOINTER
&&
268 (vp
->storage
== REDIS_VM_SWAPPED
|| vp
->storage
== REDIS_VM_LOADING
));
269 val
= vmReadObjectFromSwap(vp
->page
,vp
->vtype
);
271 redisLog(REDIS_DEBUG
, "VM: object %p loaded from disk", (void*)vp
);
272 vmMarkPagesFree(vp
->page
,vp
->usedpages
);
274 server
.vm_stats_swapped_objects
--;
276 redisLog(REDIS_DEBUG
, "VM: object %p previewed from disk", (void*)vp
);
278 server
.vm_stats_swapins
++;
282 /* Plain object loading, from swap to memory.
284 * 'o' is actually a redisVmPointer structure that will be freed by the call.
285 * The return value is the loaded object. */
286 robj
*vmLoadObject(robj
*o
) {
287 /* If we are loading the object in background, stop it, we
288 * need to load this object synchronously ASAP. */
289 if (o
->storage
== REDIS_VM_LOADING
)
290 vmCancelThreadedIOJob(o
);
291 return vmGenericLoadObject((vmpointer
*)o
,0);
294 /* Just load the value on disk, without to modify the key.
295 * This is useful when we want to perform some operation on the value
296 * without to really bring it from swap to memory, like while saving the
297 * dataset or rewriting the append only log. */
298 robj
*vmPreviewObject(robj
*o
) {
299 return vmGenericLoadObject((vmpointer
*)o
,1);
302 /* How a good candidate is this object for swapping?
303 * The better candidate it is, the greater the returned value.
305 * Currently we try to perform a fast estimation of the object size in
306 * memory, and combine it with aging informations.
308 * Basically swappability = idle-time * log(estimated size)
310 * Bigger objects are preferred over smaller objects, but not
311 * proportionally, this is why we use the logarithm. This algorithm is
312 * just a first try and will probably be tuned later. */
313 double computeObjectSwappability(robj
*o
) {
314 /* actual age can be >= minage, but not < minage. As we use wrapping
315 * 21 bit clocks with minutes resolution for the LRU. */
316 return (double) estimateObjectIdleTime(o
);
319 /* Try to swap an object that's a good candidate for swapping.
320 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
321 * to swap any object at all.
323 * If 'usethreaded' is true, Redis will try to swap the object in background
324 * using I/O threads. */
325 int vmSwapOneObject(int usethreads
) {
327 struct dictEntry
*best
= NULL
;
328 double best_swappability
= 0;
329 redisDb
*best_db
= NULL
;
333 for (j
= 0; j
< server
.dbnum
; j
++) {
334 redisDb
*db
= server
.db
+j
;
335 /* Why maxtries is set to 100?
336 * Because this way (usually) we'll find 1 object even if just 1% - 2%
337 * are swappable objects */
340 if (dictSize(db
->dict
) == 0) continue;
341 for (i
= 0; i
< 5; i
++) {
345 if (maxtries
) maxtries
--;
346 de
= dictGetRandomKey(db
->dict
);
347 val
= dictGetEntryVal(de
);
348 /* Only swap objects that are currently in memory.
350 * Also don't swap shared objects: not a good idea in general and
351 * we need to ensure that the main thread does not touch the
352 * object while the I/O thread is using it, but we can't
353 * control other keys without adding additional mutex. */
354 if (val
->storage
!= REDIS_VM_MEMORY
|| val
->refcount
!= 1) {
355 if (maxtries
) i
--; /* don't count this try */
358 swappability
= computeObjectSwappability(val
);
359 if (!best
|| swappability
> best_swappability
) {
361 best_swappability
= swappability
;
366 if (best
== NULL
) return REDIS_ERR
;
367 key
= dictGetEntryKey(best
);
368 val
= dictGetEntryVal(best
);
370 redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f",
371 key
, best_swappability
);
375 robj
*keyobj
= createStringObject(key
,sdslen(key
));
376 vmSwapObjectThreaded(keyobj
,val
,best_db
);
377 decrRefCount(keyobj
);
382 if ((vp
= vmSwapObjectBlocking(val
)) != NULL
) {
383 dictGetEntryVal(best
) = vp
;
391 int vmSwapOneObjectBlocking() {
392 return vmSwapOneObject(0);
395 int vmSwapOneObjectThreaded() {
396 return vmSwapOneObject(1);
399 /* Return true if it's safe to swap out objects in a given moment.
400 * Basically we don't want to swap objects out while there is a BGSAVE
401 * or a BGAEOREWRITE running in backgroud. */
402 int vmCanSwapOut(void) {
403 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
406 /* =================== Virtual Memory - Threaded I/O ======================= */
408 void freeIOJob(iojob
*j
) {
409 if ((j
->type
== REDIS_IOJOB_PREPARE_SWAP
||
410 j
->type
== REDIS_IOJOB_DO_SWAP
||
411 j
->type
== REDIS_IOJOB_LOAD
) && j
->val
!= NULL
)
413 /* we fix the storage type, otherwise decrRefCount() will try to
414 * kill the I/O thread Job (that does no longer exists). */
415 if (j
->val
->storage
== REDIS_VM_SWAPPING
)
416 j
->val
->storage
= REDIS_VM_MEMORY
;
417 decrRefCount(j
->val
);
419 decrRefCount(j
->key
);
423 /* Every time a thread finished a Job, it writes a byte into the write side
424 * of an unix pipe in order to "awake" the main thread, and this function
427 * Note that this is called both by the event loop, when a I/O thread
428 * sends a byte in the notification pipe, and is also directly called from
429 * waitEmptyIOJobsQueue().
431 * In the latter case we don't want to swap more, so we use the
432 * "privdata" argument setting it to a not NULL value to signal this
434 void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
,
438 int retval
, processed
= 0, toprocess
= -1, trytoswap
= 1;
441 REDIS_NOTUSED(privdata
);
443 if (privdata
!= NULL
) trytoswap
= 0; /* check the comments above... */
445 /* For every byte we read in the read side of the pipe, there is one
446 * I/O job completed to process. */
447 while((retval
= read(fd
,buf
,1)) == 1) {
450 struct dictEntry
*de
;
452 redisLog(REDIS_DEBUG
,"Processing I/O completed job");
454 /* Get the processed element (the oldest one) */
456 redisAssert(listLength(server
.io_processed
) != 0);
457 if (toprocess
== -1) {
458 toprocess
= (listLength(server
.io_processed
)*REDIS_MAX_COMPLETED_JOBS_PROCESSED
)/100;
459 if (toprocess
<= 0) toprocess
= 1;
461 ln
= listFirst(server
.io_processed
);
463 listDelNode(server
.io_processed
,ln
);
465 /* If this job is marked as canceled, just ignore it */
470 /* Post process it in the main thread, as there are things we
471 * can do just here to avoid race conditions and/or invasive locks */
472 redisLog(REDIS_DEBUG
,"COMPLETED Job type: %d, ID %p, key: %s", j
->type
, (void*)j
->id
, (unsigned char*)j
->key
->ptr
);
473 de
= dictFind(j
->db
->dict
,j
->key
->ptr
);
474 redisAssert(de
!= NULL
);
475 if (j
->type
== REDIS_IOJOB_LOAD
) {
477 vmpointer
*vp
= dictGetEntryVal(de
);
479 /* Key loaded, bring it at home */
480 vmMarkPagesFree(vp
->page
,vp
->usedpages
);
481 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk (threaded)",
482 (unsigned char*) j
->key
->ptr
);
483 server
.vm_stats_swapped_objects
--;
484 server
.vm_stats_swapins
++;
485 dictGetEntryVal(de
) = j
->val
;
486 incrRefCount(j
->val
);
488 /* Handle clients waiting for this key to be loaded. */
489 handleClientsBlockedOnSwappedKey(db
,j
->key
);
492 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
493 /* Now we know the amount of pages required to swap this object.
494 * Let's find some space for it, and queue this task again
495 * rebranded as REDIS_IOJOB_DO_SWAP. */
496 if (!vmCanSwapOut() ||
497 vmFindContiguousPages(&j
->page
,j
->pages
) == REDIS_ERR
)
499 /* Ooops... no space or we can't swap as there is
500 * a fork()ed Redis trying to save stuff on disk. */
501 j
->val
->storage
= REDIS_VM_MEMORY
; /* undo operation */
504 /* Note that we need to mark this pages as used now,
505 * if the job will be canceled, we'll mark them as freed
507 vmMarkPagesUsed(j
->page
,j
->pages
);
508 j
->type
= REDIS_IOJOB_DO_SWAP
;
513 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
516 /* Key swapped. We can finally free some memory. */
517 if (j
->val
->storage
!= REDIS_VM_SWAPPING
) {
518 vmpointer
*vp
= (vmpointer
*) j
->id
;
519 printf("storage: %d\n",vp
->storage
);
520 printf("key->name: %s\n",(char*)j
->key
->ptr
);
521 printf("val: %p\n",(void*)j
->val
);
522 printf("val->type: %d\n",j
->val
->type
);
523 printf("val->ptr: %s\n",(char*)j
->val
->ptr
);
525 redisAssert(j
->val
->storage
== REDIS_VM_SWAPPING
);
526 vp
= createVmPointer(j
->val
->type
);
528 vp
->usedpages
= j
->pages
;
529 dictGetEntryVal(de
) = vp
;
530 /* Fix the storage otherwise decrRefCount will attempt to
531 * remove the associated I/O job */
532 j
->val
->storage
= REDIS_VM_MEMORY
;
533 decrRefCount(j
->val
);
534 redisLog(REDIS_DEBUG
,
535 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
536 (unsigned char*) j
->key
->ptr
,
537 (unsigned long long) j
->page
, (unsigned long long) j
->pages
);
538 server
.vm_stats_swapped_objects
++;
539 server
.vm_stats_swapouts
++;
541 /* Put a few more swap requests in queue if we are still
543 if (trytoswap
&& vmCanSwapOut() &&
544 zmalloc_used_memory() > server
.vm_max_memory
)
549 more
= listLength(server
.io_newjobs
) <
550 (unsigned) server
.vm_max_threads
;
552 /* Don't waste CPU time if swappable objects are rare. */
553 if (vmSwapOneObjectThreaded() == REDIS_ERR
) {
561 if (processed
== toprocess
) return;
563 if (retval
< 0 && errno
!= EAGAIN
) {
564 redisLog(REDIS_WARNING
,
565 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
570 void lockThreadedIO(void) {
571 pthread_mutex_lock(&server
.io_mutex
);
574 void unlockThreadedIO(void) {
575 pthread_mutex_unlock(&server
.io_mutex
);
578 void *IOThreadEntryPoint(void *arg
) {
583 pthread_detach(pthread_self());
585 /* Get a new job to process */
587 if (listLength(server
.io_newjobs
) == 0) {
588 /* No new jobs in queue, exit. */
589 redisLog(REDIS_DEBUG
,"Thread %ld exiting, nothing to do",
590 (long) pthread_self());
591 server
.io_active_threads
--;
595 ln
= listFirst(server
.io_newjobs
);
597 listDelNode(server
.io_newjobs
,ln
);
598 /* Add the job in the processing queue */
599 j
->thread
= pthread_self();
600 listAddNodeTail(server
.io_processing
,j
);
601 ln
= listLast(server
.io_processing
); /* We use ln later to remove it */
603 redisLog(REDIS_DEBUG
,"Thread %ld got a new job (type %d): %p about key '%s'",
604 (long) pthread_self(), j
->type
, (void*)j
, (char*)j
->key
->ptr
);
606 /* Process the Job */
607 if (j
->type
== REDIS_IOJOB_LOAD
) {
608 vmpointer
*vp
= (vmpointer
*)j
->id
;
609 j
->val
= vmReadObjectFromSwap(j
->page
,vp
->vtype
);
610 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
611 j
->pages
= rdbSavedObjectPages(j
->val
);
612 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
613 if (vmWriteObjectOnSwap(j
->val
,j
->page
) == REDIS_ERR
)
617 /* Done: insert the job into the processed queue */
618 redisLog(REDIS_DEBUG
,"Thread %ld completed the job: %p (key %s)",
619 (long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
);
621 listDelNode(server
.io_processing
,ln
);
622 listAddNodeTail(server
.io_processed
,j
);
625 /* Signal the main thread there is new stuff to process */
626 redisAssert(write(server
.io_ready_pipe_write
,"x",1) == 1);
628 return NULL
; /* never reached */
631 void spawnIOThread(void) {
633 sigset_t mask
, omask
;
637 sigaddset(&mask
,SIGCHLD
);
638 sigaddset(&mask
,SIGHUP
);
639 sigaddset(&mask
,SIGPIPE
);
640 pthread_sigmask(SIG_SETMASK
, &mask
, &omask
);
641 while ((err
= pthread_create(&thread
,&server
.io_threads_attr
,IOThreadEntryPoint
,NULL
)) != 0) {
642 redisLog(REDIS_WARNING
,"Unable to spawn an I/O thread: %s",
646 pthread_sigmask(SIG_SETMASK
, &omask
, NULL
);
647 server
.io_active_threads
++;
650 /* We need to wait for the last thread to exit before we are able to
651 * fork() in order to BGSAVE or BGREWRITEAOF. */
652 void waitEmptyIOJobsQueue(void) {
654 int io_processed_len
;
657 if (listLength(server
.io_newjobs
) == 0 &&
658 listLength(server
.io_processing
) == 0 &&
659 server
.io_active_threads
== 0)
664 /* While waiting for empty jobs queue condition we post-process some
665 * finshed job, as I/O threads may be hanging trying to write against
666 * the io_ready_pipe_write FD but there are so much pending jobs that
668 io_processed_len
= listLength(server
.io_processed
);
670 if (io_processed_len
) {
671 vmThreadedIOCompletedJob(NULL
,server
.io_ready_pipe_read
,
672 (void*)0xdeadbeef,0);
673 usleep(1000); /* 1 millisecond */
675 usleep(10000); /* 10 milliseconds */
680 /* This function must be called while with threaded IO locked */
681 void queueIOJob(iojob
*j
) {
682 redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n",
683 (void*)j
, j
->type
, (char*)j
->key
->ptr
);
684 listAddNodeTail(server
.io_newjobs
,j
);
685 if (server
.io_active_threads
< server
.vm_max_threads
)
689 int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
) {
692 j
= zmalloc(sizeof(*j
));
693 j
->type
= REDIS_IOJOB_PREPARE_SWAP
;
697 j
->id
= j
->val
= val
;
700 j
->thread
= (pthread_t
) -1;
701 val
->storage
= REDIS_VM_SWAPPING
;
709 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
711 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
712 * If there is not already a job loading the key, it is craeted.
713 * The key is added to the io_keys list in the client structure, and also
714 * in the hash table mapping swapped keys to waiting clients, that is,
715 * server.io_waited_keys. */
716 int waitForSwappedKey(redisClient
*c
, robj
*key
) {
717 struct dictEntry
*de
;
721 /* If the key does not exist or is already in RAM we don't need to
722 * block the client at all. */
723 de
= dictFind(c
->db
->dict
,key
->ptr
);
724 if (de
== NULL
) return 0;
725 o
= dictGetEntryVal(de
);
726 if (o
->storage
== REDIS_VM_MEMORY
) {
728 } else if (o
->storage
== REDIS_VM_SWAPPING
) {
729 /* We were swapping the key, undo it! */
730 vmCancelThreadedIOJob(o
);
734 /* OK: the key is either swapped, or being loaded just now. */
736 /* Add the key to the list of keys this client is waiting for.
737 * This maps clients to keys they are waiting for. */
738 listAddNodeTail(c
->io_keys
,key
);
741 /* Add the client to the swapped keys => clients waiting map. */
742 de
= dictFind(c
->db
->io_keys
,key
);
746 /* For every key we take a list of clients blocked for it */
748 retval
= dictAdd(c
->db
->io_keys
,key
,l
);
750 redisAssert(retval
== DICT_OK
);
752 l
= dictGetEntryVal(de
);
754 listAddNodeTail(l
,c
);
756 /* Are we already loading the key from disk? If not create a job */
757 if (o
->storage
== REDIS_VM_SWAPPED
) {
759 vmpointer
*vp
= (vmpointer
*)o
;
761 o
->storage
= REDIS_VM_LOADING
;
762 j
= zmalloc(sizeof(*j
));
763 j
->type
= REDIS_IOJOB_LOAD
;
771 j
->thread
= (pthread_t
) -1;
779 /* Preload keys for any command with first, last and step values for
780 * the command keys prototype, as defined in the command table. */
781 void waitForMultipleSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
783 if (cmd
->vm_firstkey
== 0) return;
784 last
= cmd
->vm_lastkey
;
785 if (last
< 0) last
= argc
+last
;
786 for (j
= cmd
->vm_firstkey
; j
<= last
; j
+= cmd
->vm_keystep
) {
787 redisAssert(j
< argc
);
788 waitForSwappedKey(c
,argv
[j
]);
792 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
793 * Note that the number of keys to preload is user-defined, so we need to
794 * apply a sanity check against argc. */
795 void zunionInterBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
799 num
= atoi(argv
[2]->ptr
);
800 if (num
> (argc
-3)) return;
801 for (i
= 0; i
< num
; i
++) {
802 waitForSwappedKey(c
,argv
[3+i
]);
806 /* Preload keys needed to execute the entire MULTI/EXEC block.
808 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
809 * and will block the client when any command requires a swapped out value. */
810 void execBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
812 struct redisCommand
*mcmd
;
818 if (!(c
->flags
& REDIS_MULTI
)) return;
819 for (i
= 0; i
< c
->mstate
.count
; i
++) {
820 mcmd
= c
->mstate
.commands
[i
].cmd
;
821 margc
= c
->mstate
.commands
[i
].argc
;
822 margv
= c
->mstate
.commands
[i
].argv
;
824 if (mcmd
->vm_preload_proc
!= NULL
) {
825 mcmd
->vm_preload_proc(c
,mcmd
,margc
,margv
);
827 waitForMultipleSwappedKeys(c
,mcmd
,margc
,margv
);
832 /* Is this client attempting to run a command against swapped keys?
833 * If so, block it ASAP, load the keys in background, then resume it.
835 * The important idea about this function is that it can fail! If keys will
836 * still be swapped when the client is resumed, this key lookups will
837 * just block loading keys from disk. In practical terms this should only
838 * happen with SORT BY command or if there is a bug in this function.
840 * Return 1 if the client is marked as blocked, 0 if the client can
841 * continue as the keys it is going to access appear to be in memory. */
842 int blockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
) {
843 if (cmd
->vm_preload_proc
!= NULL
) {
844 cmd
->vm_preload_proc(c
,cmd
,c
->argc
,c
->argv
);
846 waitForMultipleSwappedKeys(c
,cmd
,c
->argc
,c
->argv
);
849 /* If the client was blocked for at least one key, mark it as blocked. */
850 if (listLength(c
->io_keys
)) {
851 c
->flags
|= REDIS_IO_WAIT
;
852 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
853 server
.vm_blocked_clients
++;
860 /* Remove the 'key' from the list of blocked keys for a given client.
862 * The function returns 1 when there are no longer blocking keys after
863 * the current one was removed (and the client can be unblocked). */
864 int dontWaitForSwappedKey(redisClient
*c
, robj
*key
) {
868 struct dictEntry
*de
;
870 /* The key object might be destroyed when deleted from the c->io_keys
871 * list (and the "key" argument is physically the same object as the
872 * object inside the list), so we need to protect it. */
875 /* Remove the key from the list of keys this client is waiting for. */
876 listRewind(c
->io_keys
,&li
);
877 while ((ln
= listNext(&li
)) != NULL
) {
878 if (equalStringObjects(ln
->value
,key
)) {
879 listDelNode(c
->io_keys
,ln
);
883 redisAssert(ln
!= NULL
);
885 /* Remove the client form the key => waiting clients map. */
886 de
= dictFind(c
->db
->io_keys
,key
);
887 redisAssert(de
!= NULL
);
888 l
= dictGetEntryVal(de
);
889 ln
= listSearchKey(l
,c
);
890 redisAssert(ln
!= NULL
);
892 if (listLength(l
) == 0)
893 dictDelete(c
->db
->io_keys
,key
);
896 return listLength(c
->io_keys
) == 0;
899 /* Every time we now a key was loaded back in memory, we handle clients
900 * waiting for this key if any. */
901 void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
) {
902 struct dictEntry
*de
;
907 de
= dictFind(db
->io_keys
,key
);
910 l
= dictGetEntryVal(de
);
912 /* Note: we can't use something like while(listLength(l)) as the list
913 * can be freed by the calling function when we remove the last element. */
916 redisClient
*c
= ln
->value
;
918 if (dontWaitForSwappedKey(c
,key
)) {
919 /* Put the client in the list of clients ready to go as we
920 * loaded all the keys about it. */
921 listAddNodeTail(server
.io_ready_clients
,c
);