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 * FIXME: how to mark this key as "busy"? With VM we used to change the
30 * object->storage field, but this time we need this to work with every
31 * kind of object, including shared ones. One possibility is just killing
32 * object sharing at all. So let's assume this will be our solution.
34 * So we set keys that are in the process of being saved as
35 * object->storage = REDIS_STORAGE_SAVING;
37 * - This is what we do on key lookup:
38 * 1) The key already exists in memory. object->storage == REDIS_DS_MEMORY.
39 * We don't do nothing special, lookup, return value object pointer.
40 * 2) The key is in memory but object->storage == REDIS_DS_SAVING.
41 * This is an explicit lookup so we have to abort the saving operation.
42 * We kill the IO Job, set the storage to == REDIS_DB_MEMORY but
43 * re-queue the object in the server.ds_cache_dirty list.
45 * Btw here we need some protection against the problem of continuously
46 * writing against a value having the effect of this value to be never
47 * saved on disk. That is, at some point we need to block and write it
48 * if there is too much delay.
49 * 3) The key is not in memory. We block to load the key from disk.
50 * Of course the key may not be present at all on the disk store as well,
51 * in such case we just detect this condition and continue, returning
54 * - Preloading of needed keys:
55 * 1) As it was done with VM, also with this new system we try preloading
56 * keys a client is going to use. We block the client, load keys
57 * using the I/O thread, unblock the client. Same code as VM more or less.
59 * - Transfering keys from memory to disk.
60 * Again while in cron() we detect our memory limit was reached. What we
61 * do is transfering random keys that are not set as dirty on disk, using
62 * LRU to select the key.
63 * If this is not enough to return again under the memory limits we also
64 * start to flush keys that need to be synched on disk synchronously,
65 * removing it from the memory.
67 * - IO thread operations are no longer stopped for sync loading/saving of
68 * things. When a key is found to be in the process of being saved or
69 * loaded we simply wait for the IO thread to end its work.
71 * Otherwise if there is to load a key without any IO thread operation
72 * just started it is blocking-loaded in the lookup function.
75 /* Virtual Memory is composed mainly of two subsystems:
76 * - Blocking Virutal Memory
77 * - Threaded Virtual Memory I/O
78 * The two parts are not fully decoupled, but functions are split among two
79 * different sections of the source code (delimited by comments) in order to
80 * make more clear what functionality is about the blocking VM and what about
81 * the threaded (not blocking) VM.
85 * Redis VM is a blocking VM (one that blocks reading swapped values from
86 * disk into memory when a value swapped out is needed in memory) that is made
87 * unblocking by trying to examine the command argument vector in order to
88 * load in background values that will likely be needed in order to exec
89 * the command. The command is executed only once all the relevant keys
90 * are loaded into memory.
92 * This basically is almost as simple of a blocking VM, but almost as parallel
93 * as a fully non-blocking VM.
96 /* =================== Virtual Memory - Blocking Side ====================== */
98 /* Create a VM pointer object. This kind of objects are used in place of
99 * values in the key -> value hash table, for swapped out objects. */
100 vmpointer
*createVmPointer(int vtype
) {
101 vmpointer
*vp
= zmalloc(sizeof(vmpointer
));
103 vp
->type
= REDIS_VMPOINTER
;
104 vp
->storage
= REDIS_VM_SWAPPED
;
115 if (server
.vm_max_threads
!= 0)
116 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
118 redisLog(REDIS_NOTICE
,"Using '%s' as swap file",server
.vm_swap_file
);
119 /* Try to open the old swap file, otherwise create it */
120 if ((server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b")) == NULL
) {
121 server
.vm_fp
= fopen(server
.vm_swap_file
,"w+b");
123 if (server
.vm_fp
== NULL
) {
124 redisLog(REDIS_WARNING
,
125 "Can't open the swap file: %s. Exiting.",
129 server
.vm_fd
= fileno(server
.vm_fp
);
130 /* Lock the swap file for writing, this is useful in order to avoid
131 * another instance to use the same swap file for a config error. */
133 fl
.l_whence
= SEEK_SET
;
134 fl
.l_start
= fl
.l_len
= 0;
135 if (fcntl(server
.vm_fd
,F_SETLK
,&fl
) == -1) {
136 redisLog(REDIS_WARNING
,
137 "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
));
141 server
.vm_next_page
= 0;
142 server
.vm_near_pages
= 0;
143 server
.vm_stats_used_pages
= 0;
144 server
.vm_stats_swapped_objects
= 0;
145 server
.vm_stats_swapouts
= 0;
146 server
.vm_stats_swapins
= 0;
147 totsize
= server
.vm_pages
*server
.vm_page_size
;
148 redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
);
149 if (ftruncate(server
.vm_fd
,totsize
) == -1) {
150 redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.",
154 redisLog(REDIS_NOTICE
,"Swap file allocated with success");
156 server
.vm_bitmap
= zcalloc((server
.vm_pages
+7)/8);
157 redisLog(REDIS_VERBOSE
,"Allocated %lld bytes page table for %lld pages",
158 (long long) (server
.vm_pages
+7)/8, server
.vm_pages
);
160 /* Initialize threaded I/O (used by Virtual Memory) */
161 server
.io_newjobs
= listCreate();
162 server
.io_processing
= listCreate();
163 server
.io_processed
= listCreate();
164 server
.io_ready_clients
= listCreate();
165 pthread_mutex_init(&server
.io_mutex
,NULL
);
166 pthread_mutex_init(&server
.io_swapfile_mutex
,NULL
);
167 server
.io_active_threads
= 0;
168 if (pipe(pipefds
) == -1) {
169 redisLog(REDIS_WARNING
,"Unable to intialized VM: pipe(2): %s. Exiting."
173 server
.io_ready_pipe_read
= pipefds
[0];
174 server
.io_ready_pipe_write
= pipefds
[1];
175 redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
);
176 /* LZF requires a lot of stack */
177 pthread_attr_init(&server
.io_threads_attr
);
178 pthread_attr_getstacksize(&server
.io_threads_attr
, &stacksize
);
180 /* Solaris may report a stacksize of 0, let's set it to 1 otherwise
181 * multiplying it by 2 in the while loop later will not really help ;) */
182 if (!stacksize
) stacksize
= 1;
184 while (stacksize
< REDIS_THREAD_STACK_SIZE
) stacksize
*= 2;
185 pthread_attr_setstacksize(&server
.io_threads_attr
, stacksize
);
186 /* Listen for events in the threaded I/O pipe */
187 if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
,
188 vmThreadedIOCompletedJob
, NULL
) == AE_ERR
)
189 oom("creating file event");
192 /* Mark the page as used */
193 void vmMarkPageUsed(off_t page
) {
196 redisAssert(vmFreePage(page
) == 1);
197 server
.vm_bitmap
[byte
] |= 1<<bit
;
200 /* Mark N contiguous pages as used, with 'page' being the first. */
201 void vmMarkPagesUsed(off_t page
, off_t count
) {
204 for (j
= 0; j
< count
; j
++)
205 vmMarkPageUsed(page
+j
);
206 server
.vm_stats_used_pages
+= count
;
207 redisLog(REDIS_DEBUG
,"Mark USED pages: %lld pages at %lld\n",
208 (long long)count
, (long long)page
);
211 /* Mark the page as free */
212 void vmMarkPageFree(off_t page
) {
215 redisAssert(vmFreePage(page
) == 0);
216 server
.vm_bitmap
[byte
] &= ~(1<<bit
);
219 /* Mark N contiguous pages as free, with 'page' being the first. */
220 void vmMarkPagesFree(off_t page
, off_t count
) {
223 for (j
= 0; j
< count
; j
++)
224 vmMarkPageFree(page
+j
);
225 server
.vm_stats_used_pages
-= count
;
226 redisLog(REDIS_DEBUG
,"Mark FREE pages: %lld pages at %lld\n",
227 (long long)count
, (long long)page
);
230 /* Test if the page is free */
231 int vmFreePage(off_t page
) {
234 return (server
.vm_bitmap
[byte
] & (1<<bit
)) == 0;
237 /* Find N contiguous free pages storing the first page of the cluster in *first.
238 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
239 * REDIS_ERR is returned.
241 * This function uses a simple algorithm: we try to allocate
242 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
243 * again from the start of the swap file searching for free spaces.
245 * If it looks pretty clear that there are no free pages near our offset
246 * we try to find less populated places doing a forward jump of
247 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
248 * without hurry, and then we jump again and so forth...
250 * This function can be improved using a free list to avoid to guess
251 * too much, since we could collect data about freed pages.
253 * note: I implemented this function just after watching an episode of
254 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
256 int vmFindContiguousPages(off_t
*first
, off_t n
) {
257 off_t base
, offset
= 0, since_jump
= 0, numfree
= 0;
259 if (server
.vm_near_pages
== REDIS_VM_MAX_NEAR_PAGES
) {
260 server
.vm_near_pages
= 0;
261 server
.vm_next_page
= 0;
263 server
.vm_near_pages
++; /* Yet another try for pages near to the old ones */
264 base
= server
.vm_next_page
;
266 while(offset
< server
.vm_pages
) {
267 off_t
this = base
+offset
;
269 /* If we overflow, restart from page zero */
270 if (this >= server
.vm_pages
) {
271 this -= server
.vm_pages
;
273 /* Just overflowed, what we found on tail is no longer
274 * interesting, as it's no longer contiguous. */
278 if (vmFreePage(this)) {
279 /* This is a free page */
281 /* Already got N free pages? Return to the caller, with success */
284 server
.vm_next_page
= this+1;
285 redisLog(REDIS_DEBUG
, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n
, (long long) *first
);
289 /* The current one is not a free page */
293 /* Fast-forward if the current page is not free and we already
294 * searched enough near this place. */
296 if (!numfree
&& since_jump
>= REDIS_VM_MAX_RANDOM_JUMP
/4) {
297 offset
+= random() % REDIS_VM_MAX_RANDOM_JUMP
;
299 /* Note that even if we rewind after the jump, we are don't need
300 * to make sure numfree is set to zero as we only jump *if* it
303 /* Otherwise just check the next page */
310 /* Write the specified object at the specified page of the swap file */
311 int vmWriteObjectOnSwap(robj
*o
, off_t page
) {
312 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
313 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
314 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
315 redisLog(REDIS_WARNING
,
316 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
320 rdbSaveObject(server
.vm_fp
,o
);
321 fflush(server
.vm_fp
);
322 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
326 /* Transfers the 'val' object to disk. Store all the information
327 * a 'vmpointer' object containing all the information needed to load the
328 * object back later is returned.
330 * If we can't find enough contiguous empty pages to swap the object on disk
331 * NULL is returned. */
332 vmpointer
*vmSwapObjectBlocking(robj
*val
) {
333 off_t pages
= rdbSavedObjectPages(val
);
337 redisAssert(val
->storage
== REDIS_VM_MEMORY
);
338 redisAssert(val
->refcount
== 1);
339 if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return NULL
;
340 if (vmWriteObjectOnSwap(val
,page
) == REDIS_ERR
) return NULL
;
342 vp
= createVmPointer(val
->type
);
344 vp
->usedpages
= pages
;
345 decrRefCount(val
); /* Deallocate the object from memory. */
346 vmMarkPagesUsed(page
,pages
);
347 redisLog(REDIS_DEBUG
,"VM: object %p swapped out at %lld (%lld pages)",
349 (unsigned long long) page
, (unsigned long long) pages
);
350 server
.vm_stats_swapped_objects
++;
351 server
.vm_stats_swapouts
++;
355 robj
*vmReadObjectFromSwap(off_t page
, int type
) {
358 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
359 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
360 redisLog(REDIS_WARNING
,
361 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
365 o
= rdbLoadObject(type
,server
.vm_fp
);
367 redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno
));
370 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
374 /* Load the specified object from swap to memory.
375 * The newly allocated object is returned.
377 * If preview is true the unserialized object is returned to the caller but
378 * the pages are not marked as freed, nor the vp object is freed. */
379 robj
*vmGenericLoadObject(vmpointer
*vp
, int preview
) {
382 redisAssert(vp
->type
== REDIS_VMPOINTER
&&
383 (vp
->storage
== REDIS_VM_SWAPPED
|| vp
->storage
== REDIS_VM_LOADING
));
384 val
= vmReadObjectFromSwap(vp
->page
,vp
->vtype
);
386 redisLog(REDIS_DEBUG
, "VM: object %p loaded from disk", (void*)vp
);
387 vmMarkPagesFree(vp
->page
,vp
->usedpages
);
389 server
.vm_stats_swapped_objects
--;
391 redisLog(REDIS_DEBUG
, "VM: object %p previewed from disk", (void*)vp
);
393 server
.vm_stats_swapins
++;
397 /* Plain object loading, from swap to memory.
399 * 'o' is actually a redisVmPointer structure that will be freed by the call.
400 * The return value is the loaded object. */
401 robj
*vmLoadObject(robj
*o
) {
402 /* If we are loading the object in background, stop it, we
403 * need to load this object synchronously ASAP. */
404 if (o
->storage
== REDIS_VM_LOADING
)
405 vmCancelThreadedIOJob(o
);
406 return vmGenericLoadObject((vmpointer
*)o
,0);
409 /* Just load the value on disk, without to modify the key.
410 * This is useful when we want to perform some operation on the value
411 * without to really bring it from swap to memory, like while saving the
412 * dataset or rewriting the append only log. */
413 robj
*vmPreviewObject(robj
*o
) {
414 return vmGenericLoadObject((vmpointer
*)o
,1);
417 /* How a good candidate is this object for swapping?
418 * The better candidate it is, the greater the returned value.
420 * Currently we try to perform a fast estimation of the object size in
421 * memory, and combine it with aging informations.
423 * Basically swappability = idle-time * log(estimated size)
425 * Bigger objects are preferred over smaller objects, but not
426 * proportionally, this is why we use the logarithm. This algorithm is
427 * just a first try and will probably be tuned later. */
428 double computeObjectSwappability(robj
*o
) {
429 /* actual age can be >= minage, but not < minage. As we use wrapping
430 * 21 bit clocks with minutes resolution for the LRU. */
431 time_t minage
= estimateObjectIdleTime(o
);
432 long asize
= 0, elesize
;
437 struct dictEntry
*de
;
440 if (minage
<= 0) return 0;
443 if (o
->encoding
!= REDIS_ENCODING_RAW
) {
446 asize
= sdslen(o
->ptr
)+sizeof(*o
)+sizeof(long)*2;
450 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
451 asize
= sizeof(*o
)+ziplistSize(o
->ptr
);
455 asize
= sizeof(list
);
458 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
459 (sizeof(*o
)+sdslen(ele
->ptr
)) : sizeof(*o
);
460 asize
+= (sizeof(listNode
)+elesize
)*listLength(l
);
466 z
= (o
->type
== REDIS_ZSET
);
467 d
= z
? ((zset
*)o
->ptr
)->dict
: o
->ptr
;
469 if (!z
&& o
->encoding
== REDIS_ENCODING_INTSET
) {
471 asize
= sizeof(*is
)+is
->encoding
*is
->length
;
473 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
474 if (z
) asize
+= sizeof(zset
)-sizeof(dict
);
476 de
= dictGetRandomKey(d
);
477 ele
= dictGetEntryKey(de
);
478 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
479 (sizeof(*o
)+sdslen(ele
->ptr
)) : sizeof(*o
);
480 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
481 if (z
) asize
+= sizeof(zskiplistNode
)*dictSize(d
);
486 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
487 unsigned char *p
= zipmapRewind((unsigned char*)o
->ptr
);
488 unsigned int len
= zipmapLen((unsigned char*)o
->ptr
);
489 unsigned int klen
, vlen
;
490 unsigned char *key
, *val
;
492 if ((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) == NULL
) {
496 asize
= len
*(klen
+vlen
+3);
497 } else if (o
->encoding
== REDIS_ENCODING_HT
) {
499 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
501 de
= dictGetRandomKey(d
);
502 ele
= dictGetEntryKey(de
);
503 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
504 (sizeof(*o
)+sdslen(ele
->ptr
)) : sizeof(*o
);
505 ele
= dictGetEntryVal(de
);
506 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
507 (sizeof(*o
)+sdslen(ele
->ptr
)) : sizeof(*o
);
508 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
513 return (double)minage
*log(1+asize
);
516 /* Try to swap an object that's a good candidate for swapping.
517 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
518 * to swap any object at all.
520 * If 'usethreaded' is true, Redis will try to swap the object in background
521 * using I/O threads. */
522 int vmSwapOneObject(int usethreads
) {
524 struct dictEntry
*best
= NULL
;
525 double best_swappability
= 0;
526 redisDb
*best_db
= NULL
;
530 for (j
= 0; j
< server
.dbnum
; j
++) {
531 redisDb
*db
= server
.db
+j
;
532 /* Why maxtries is set to 100?
533 * Because this way (usually) we'll find 1 object even if just 1% - 2%
534 * are swappable objects */
537 if (dictSize(db
->dict
) == 0) continue;
538 for (i
= 0; i
< 5; i
++) {
542 if (maxtries
) maxtries
--;
543 de
= dictGetRandomKey(db
->dict
);
544 val
= dictGetEntryVal(de
);
545 /* Only swap objects that are currently in memory.
547 * Also don't swap shared objects: not a good idea in general and
548 * we need to ensure that the main thread does not touch the
549 * object while the I/O thread is using it, but we can't
550 * control other keys without adding additional mutex. */
551 if (val
->storage
!= REDIS_VM_MEMORY
|| val
->refcount
!= 1) {
552 if (maxtries
) i
--; /* don't count this try */
555 swappability
= computeObjectSwappability(val
);
556 if (!best
|| swappability
> best_swappability
) {
558 best_swappability
= swappability
;
563 if (best
== NULL
) return REDIS_ERR
;
564 key
= dictGetEntryKey(best
);
565 val
= dictGetEntryVal(best
);
567 redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f",
568 key
, best_swappability
);
572 robj
*keyobj
= createStringObject(key
,sdslen(key
));
573 vmSwapObjectThreaded(keyobj
,val
,best_db
);
574 decrRefCount(keyobj
);
579 if ((vp
= vmSwapObjectBlocking(val
)) != NULL
) {
580 dictGetEntryVal(best
) = vp
;
588 int vmSwapOneObjectBlocking() {
589 return vmSwapOneObject(0);
592 int vmSwapOneObjectThreaded() {
593 return vmSwapOneObject(1);
596 /* Return true if it's safe to swap out objects in a given moment.
597 * Basically we don't want to swap objects out while there is a BGSAVE
598 * or a BGAEOREWRITE running in backgroud. */
599 int vmCanSwapOut(void) {
600 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
603 /* =================== Virtual Memory - Threaded I/O ======================= */
605 void freeIOJob(iojob
*j
) {
606 if ((j
->type
== REDIS_IOJOB_PREPARE_SWAP
||
607 j
->type
== REDIS_IOJOB_DO_SWAP
||
608 j
->type
== REDIS_IOJOB_LOAD
) && j
->val
!= NULL
)
610 /* we fix the storage type, otherwise decrRefCount() will try to
611 * kill the I/O thread Job (that does no longer exists). */
612 if (j
->val
->storage
== REDIS_VM_SWAPPING
)
613 j
->val
->storage
= REDIS_VM_MEMORY
;
614 decrRefCount(j
->val
);
616 decrRefCount(j
->key
);
620 /* Every time a thread finished a Job, it writes a byte into the write side
621 * of an unix pipe in order to "awake" the main thread, and this function
624 * Note that this is called both by the event loop, when a I/O thread
625 * sends a byte in the notification pipe, and is also directly called from
626 * waitEmptyIOJobsQueue().
628 * In the latter case we don't want to swap more, so we use the
629 * "privdata" argument setting it to a not NULL value to signal this
631 void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
,
635 int retval
, processed
= 0, toprocess
= -1, trytoswap
= 1;
638 REDIS_NOTUSED(privdata
);
640 if (privdata
!= NULL
) trytoswap
= 0; /* check the comments above... */
642 /* For every byte we read in the read side of the pipe, there is one
643 * I/O job completed to process. */
644 while((retval
= read(fd
,buf
,1)) == 1) {
647 struct dictEntry
*de
;
649 redisLog(REDIS_DEBUG
,"Processing I/O completed job");
651 /* Get the processed element (the oldest one) */
653 redisAssert(listLength(server
.io_processed
) != 0);
654 if (toprocess
== -1) {
655 toprocess
= (listLength(server
.io_processed
)*REDIS_MAX_COMPLETED_JOBS_PROCESSED
)/100;
656 if (toprocess
<= 0) toprocess
= 1;
658 ln
= listFirst(server
.io_processed
);
660 listDelNode(server
.io_processed
,ln
);
662 /* If this job is marked as canceled, just ignore it */
667 /* Post process it in the main thread, as there are things we
668 * can do just here to avoid race conditions and/or invasive locks */
669 redisLog(REDIS_DEBUG
,"COMPLETED Job type: %d, ID %p, key: %s", j
->type
, (void*)j
->id
, (unsigned char*)j
->key
->ptr
);
670 de
= dictFind(j
->db
->dict
,j
->key
->ptr
);
671 redisAssert(de
!= NULL
);
672 if (j
->type
== REDIS_IOJOB_LOAD
) {
674 vmpointer
*vp
= dictGetEntryVal(de
);
676 /* Key loaded, bring it at home */
677 vmMarkPagesFree(vp
->page
,vp
->usedpages
);
678 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk (threaded)",
679 (unsigned char*) j
->key
->ptr
);
680 server
.vm_stats_swapped_objects
--;
681 server
.vm_stats_swapins
++;
682 dictGetEntryVal(de
) = j
->val
;
683 incrRefCount(j
->val
);
685 /* Handle clients waiting for this key to be loaded. */
686 handleClientsBlockedOnSwappedKey(db
,j
->key
);
689 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
690 /* Now we know the amount of pages required to swap this object.
691 * Let's find some space for it, and queue this task again
692 * rebranded as REDIS_IOJOB_DO_SWAP. */
693 if (!vmCanSwapOut() ||
694 vmFindContiguousPages(&j
->page
,j
->pages
) == REDIS_ERR
)
696 /* Ooops... no space or we can't swap as there is
697 * a fork()ed Redis trying to save stuff on disk. */
698 j
->val
->storage
= REDIS_VM_MEMORY
; /* undo operation */
701 /* Note that we need to mark this pages as used now,
702 * if the job will be canceled, we'll mark them as freed
704 vmMarkPagesUsed(j
->page
,j
->pages
);
705 j
->type
= REDIS_IOJOB_DO_SWAP
;
710 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
713 /* Key swapped. We can finally free some memory. */
714 if (j
->val
->storage
!= REDIS_VM_SWAPPING
) {
715 vmpointer
*vp
= (vmpointer
*) j
->id
;
716 printf("storage: %d\n",vp
->storage
);
717 printf("key->name: %s\n",(char*)j
->key
->ptr
);
718 printf("val: %p\n",(void*)j
->val
);
719 printf("val->type: %d\n",j
->val
->type
);
720 printf("val->ptr: %s\n",(char*)j
->val
->ptr
);
722 redisAssert(j
->val
->storage
== REDIS_VM_SWAPPING
);
723 vp
= createVmPointer(j
->val
->type
);
725 vp
->usedpages
= j
->pages
;
726 dictGetEntryVal(de
) = vp
;
727 /* Fix the storage otherwise decrRefCount will attempt to
728 * remove the associated I/O job */
729 j
->val
->storage
= REDIS_VM_MEMORY
;
730 decrRefCount(j
->val
);
731 redisLog(REDIS_DEBUG
,
732 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
733 (unsigned char*) j
->key
->ptr
,
734 (unsigned long long) j
->page
, (unsigned long long) j
->pages
);
735 server
.vm_stats_swapped_objects
++;
736 server
.vm_stats_swapouts
++;
738 /* Put a few more swap requests in queue if we are still
740 if (trytoswap
&& vmCanSwapOut() &&
741 zmalloc_used_memory() > server
.vm_max_memory
)
746 more
= listLength(server
.io_newjobs
) <
747 (unsigned) server
.vm_max_threads
;
749 /* Don't waste CPU time if swappable objects are rare. */
750 if (vmSwapOneObjectThreaded() == REDIS_ERR
) {
758 if (processed
== toprocess
) return;
760 if (retval
< 0 && errno
!= EAGAIN
) {
761 redisLog(REDIS_WARNING
,
762 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
767 void lockThreadedIO(void) {
768 pthread_mutex_lock(&server
.io_mutex
);
771 void unlockThreadedIO(void) {
772 pthread_mutex_unlock(&server
.io_mutex
);
775 /* Remove the specified object from the threaded I/O queue if still not
776 * processed, otherwise make sure to flag it as canceled. */
777 void vmCancelThreadedIOJob(robj
*o
) {
779 server
.io_newjobs
, /* 0 */
780 server
.io_processing
, /* 1 */
781 server
.io_processed
/* 2 */
785 redisAssert(o
->storage
== REDIS_VM_LOADING
|| o
->storage
== REDIS_VM_SWAPPING
);
788 /* Search for a matching object in one of the queues */
789 for (i
= 0; i
< 3; i
++) {
793 listRewind(lists
[i
],&li
);
794 while ((ln
= listNext(&li
)) != NULL
) {
795 iojob
*job
= ln
->value
;
797 if (job
->canceled
) continue; /* Skip this, already canceled. */
799 redisLog(REDIS_DEBUG
,"*** CANCELED %p (key %s) (type %d) (LIST ID %d)\n",
800 (void*)job
, (char*)job
->key
->ptr
, job
->type
, i
);
801 /* Mark the pages as free since the swap didn't happened
802 * or happened but is now discarded. */
803 if (i
!= 1 && job
->type
== REDIS_IOJOB_DO_SWAP
)
804 vmMarkPagesFree(job
->page
,job
->pages
);
805 /* Cancel the job. It depends on the list the job is
808 case 0: /* io_newjobs */
809 /* If the job was yet not processed the best thing to do
810 * is to remove it from the queue at all */
812 listDelNode(lists
[i
],ln
);
814 case 1: /* io_processing */
815 /* Oh Shi- the thread is messing with the Job:
817 * Probably it's accessing the object if this is a
818 * PREPARE_SWAP or DO_SWAP job.
819 * If it's a LOAD job it may be reading from disk and
820 * if we don't wait for the job to terminate before to
821 * cancel it, maybe in a few microseconds data can be
822 * corrupted in this pages. So the short story is:
824 * Better to wait for the job to move into the
825 * next queue (processed)... */
827 /* We try again and again until the job is completed. */
829 /* But let's wait some time for the I/O thread
830 * to finish with this job. After all this condition
831 * should be very rare. */
834 case 2: /* io_processed */
835 /* The job was already processed, that's easy...
836 * just mark it as canceled so that we'll ignore it
837 * when processing completed jobs. */
841 /* Finally we have to adjust the storage type of the object
842 * in order to "UNDO" the operaiton. */
843 if (o
->storage
== REDIS_VM_LOADING
)
844 o
->storage
= REDIS_VM_SWAPPED
;
845 else if (o
->storage
== REDIS_VM_SWAPPING
)
846 o
->storage
= REDIS_VM_MEMORY
;
848 redisLog(REDIS_DEBUG
,"*** DONE");
854 printf("Not found: %p\n", (void*)o
);
855 redisAssert(1 != 1); /* We should never reach this */
858 void *IOThreadEntryPoint(void *arg
) {
863 pthread_detach(pthread_self());
865 /* Get a new job to process */
867 if (listLength(server
.io_newjobs
) == 0) {
868 /* No new jobs in queue, exit. */
869 redisLog(REDIS_DEBUG
,"Thread %ld exiting, nothing to do",
870 (long) pthread_self());
871 server
.io_active_threads
--;
875 ln
= listFirst(server
.io_newjobs
);
877 listDelNode(server
.io_newjobs
,ln
);
878 /* Add the job in the processing queue */
879 j
->thread
= pthread_self();
880 listAddNodeTail(server
.io_processing
,j
);
881 ln
= listLast(server
.io_processing
); /* We use ln later to remove it */
883 redisLog(REDIS_DEBUG
,"Thread %ld got a new job (type %d): %p about key '%s'",
884 (long) pthread_self(), j
->type
, (void*)j
, (char*)j
->key
->ptr
);
886 /* Process the Job */
887 if (j
->type
== REDIS_IOJOB_LOAD
) {
888 vmpointer
*vp
= (vmpointer
*)j
->id
;
889 j
->val
= vmReadObjectFromSwap(j
->page
,vp
->vtype
);
890 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
891 j
->pages
= rdbSavedObjectPages(j
->val
);
892 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
893 if (vmWriteObjectOnSwap(j
->val
,j
->page
) == REDIS_ERR
)
897 /* Done: insert the job into the processed queue */
898 redisLog(REDIS_DEBUG
,"Thread %ld completed the job: %p (key %s)",
899 (long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
);
901 listDelNode(server
.io_processing
,ln
);
902 listAddNodeTail(server
.io_processed
,j
);
905 /* Signal the main thread there is new stuff to process */
906 redisAssert(write(server
.io_ready_pipe_write
,"x",1) == 1);
908 return NULL
; /* never reached */
911 void spawnIOThread(void) {
913 sigset_t mask
, omask
;
917 sigaddset(&mask
,SIGCHLD
);
918 sigaddset(&mask
,SIGHUP
);
919 sigaddset(&mask
,SIGPIPE
);
920 pthread_sigmask(SIG_SETMASK
, &mask
, &omask
);
921 while ((err
= pthread_create(&thread
,&server
.io_threads_attr
,IOThreadEntryPoint
,NULL
)) != 0) {
922 redisLog(REDIS_WARNING
,"Unable to spawn an I/O thread: %s",
926 pthread_sigmask(SIG_SETMASK
, &omask
, NULL
);
927 server
.io_active_threads
++;
930 /* We need to wait for the last thread to exit before we are able to
931 * fork() in order to BGSAVE or BGREWRITEAOF. */
932 void waitEmptyIOJobsQueue(void) {
934 int io_processed_len
;
937 if (listLength(server
.io_newjobs
) == 0 &&
938 listLength(server
.io_processing
) == 0 &&
939 server
.io_active_threads
== 0)
944 /* While waiting for empty jobs queue condition we post-process some
945 * finshed job, as I/O threads may be hanging trying to write against
946 * the io_ready_pipe_write FD but there are so much pending jobs that
948 io_processed_len
= listLength(server
.io_processed
);
950 if (io_processed_len
) {
951 vmThreadedIOCompletedJob(NULL
,server
.io_ready_pipe_read
,
952 (void*)0xdeadbeef,0);
953 usleep(1000); /* 1 millisecond */
955 usleep(10000); /* 10 milliseconds */
960 void vmReopenSwapFile(void) {
961 /* Note: we don't close the old one as we are in the child process
962 * and don't want to mess at all with the original file object. */
963 server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b");
964 if (server
.vm_fp
== NULL
) {
965 redisLog(REDIS_WARNING
,"Can't re-open the VM swap file: %s. Exiting.",
966 server
.vm_swap_file
);
969 server
.vm_fd
= fileno(server
.vm_fp
);
972 /* This function must be called while with threaded IO locked */
973 void queueIOJob(iojob
*j
) {
974 redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n",
975 (void*)j
, j
->type
, (char*)j
->key
->ptr
);
976 listAddNodeTail(server
.io_newjobs
,j
);
977 if (server
.io_active_threads
< server
.vm_max_threads
)
981 int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
) {
984 j
= zmalloc(sizeof(*j
));
985 j
->type
= REDIS_IOJOB_PREPARE_SWAP
;
989 j
->id
= j
->val
= val
;
992 j
->thread
= (pthread_t
) -1;
993 val
->storage
= REDIS_VM_SWAPPING
;
1001 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
1003 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
1004 * If there is not already a job loading the key, it is craeted.
1005 * The key is added to the io_keys list in the client structure, and also
1006 * in the hash table mapping swapped keys to waiting clients, that is,
1007 * server.io_waited_keys. */
1008 int waitForSwappedKey(redisClient
*c
, robj
*key
) {
1009 struct dictEntry
*de
;
1013 /* If the key does not exist or is already in RAM we don't need to
1014 * block the client at all. */
1015 de
= dictFind(c
->db
->dict
,key
->ptr
);
1016 if (de
== NULL
) return 0;
1017 o
= dictGetEntryVal(de
);
1018 if (o
->storage
== REDIS_VM_MEMORY
) {
1020 } else if (o
->storage
== REDIS_VM_SWAPPING
) {
1021 /* We were swapping the key, undo it! */
1022 vmCancelThreadedIOJob(o
);
1026 /* OK: the key is either swapped, or being loaded just now. */
1028 /* Add the key to the list of keys this client is waiting for.
1029 * This maps clients to keys they are waiting for. */
1030 listAddNodeTail(c
->io_keys
,key
);
1033 /* Add the client to the swapped keys => clients waiting map. */
1034 de
= dictFind(c
->db
->io_keys
,key
);
1038 /* For every key we take a list of clients blocked for it */
1040 retval
= dictAdd(c
->db
->io_keys
,key
,l
);
1042 redisAssert(retval
== DICT_OK
);
1044 l
= dictGetEntryVal(de
);
1046 listAddNodeTail(l
,c
);
1048 /* Are we already loading the key from disk? If not create a job */
1049 if (o
->storage
== REDIS_VM_SWAPPED
) {
1051 vmpointer
*vp
= (vmpointer
*)o
;
1053 o
->storage
= REDIS_VM_LOADING
;
1054 j
= zmalloc(sizeof(*j
));
1055 j
->type
= REDIS_IOJOB_LOAD
;
1063 j
->thread
= (pthread_t
) -1;
1071 /* Preload keys for any command with first, last and step values for
1072 * the command keys prototype, as defined in the command table. */
1073 void waitForMultipleSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
1075 if (cmd
->vm_firstkey
== 0) return;
1076 last
= cmd
->vm_lastkey
;
1077 if (last
< 0) last
= argc
+last
;
1078 for (j
= cmd
->vm_firstkey
; j
<= last
; j
+= cmd
->vm_keystep
) {
1079 redisAssert(j
< argc
);
1080 waitForSwappedKey(c
,argv
[j
]);
1084 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
1085 * Note that the number of keys to preload is user-defined, so we need to
1086 * apply a sanity check against argc. */
1087 void zunionInterBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
1091 num
= atoi(argv
[2]->ptr
);
1092 if (num
> (argc
-3)) return;
1093 for (i
= 0; i
< num
; i
++) {
1094 waitForSwappedKey(c
,argv
[3+i
]);
1098 /* Preload keys needed to execute the entire MULTI/EXEC block.
1100 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
1101 * and will block the client when any command requires a swapped out value. */
1102 void execBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
1104 struct redisCommand
*mcmd
;
1107 REDIS_NOTUSED(argc
);
1108 REDIS_NOTUSED(argv
);
1110 if (!(c
->flags
& REDIS_MULTI
)) return;
1111 for (i
= 0; i
< c
->mstate
.count
; i
++) {
1112 mcmd
= c
->mstate
.commands
[i
].cmd
;
1113 margc
= c
->mstate
.commands
[i
].argc
;
1114 margv
= c
->mstate
.commands
[i
].argv
;
1116 if (mcmd
->vm_preload_proc
!= NULL
) {
1117 mcmd
->vm_preload_proc(c
,mcmd
,margc
,margv
);
1119 waitForMultipleSwappedKeys(c
,mcmd
,margc
,margv
);
1124 /* Is this client attempting to run a command against swapped keys?
1125 * If so, block it ASAP, load the keys in background, then resume it.
1127 * The important idea about this function is that it can fail! If keys will
1128 * still be swapped when the client is resumed, this key lookups will
1129 * just block loading keys from disk. In practical terms this should only
1130 * happen with SORT BY command or if there is a bug in this function.
1132 * Return 1 if the client is marked as blocked, 0 if the client can
1133 * continue as the keys it is going to access appear to be in memory. */
1134 int blockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
) {
1135 if (cmd
->vm_preload_proc
!= NULL
) {
1136 cmd
->vm_preload_proc(c
,cmd
,c
->argc
,c
->argv
);
1138 waitForMultipleSwappedKeys(c
,cmd
,c
->argc
,c
->argv
);
1141 /* If the client was blocked for at least one key, mark it as blocked. */
1142 if (listLength(c
->io_keys
)) {
1143 c
->flags
|= REDIS_IO_WAIT
;
1144 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
1145 server
.vm_blocked_clients
++;
1152 /* Remove the 'key' from the list of blocked keys for a given client.
1154 * The function returns 1 when there are no longer blocking keys after
1155 * the current one was removed (and the client can be unblocked). */
1156 int dontWaitForSwappedKey(redisClient
*c
, robj
*key
) {
1160 struct dictEntry
*de
;
1162 /* The key object might be destroyed when deleted from the c->io_keys
1163 * list (and the "key" argument is physically the same object as the
1164 * object inside the list), so we need to protect it. */
1167 /* Remove the key from the list of keys this client is waiting for. */
1168 listRewind(c
->io_keys
,&li
);
1169 while ((ln
= listNext(&li
)) != NULL
) {
1170 if (equalStringObjects(ln
->value
,key
)) {
1171 listDelNode(c
->io_keys
,ln
);
1175 redisAssert(ln
!= NULL
);
1177 /* Remove the client form the key => waiting clients map. */
1178 de
= dictFind(c
->db
->io_keys
,key
);
1179 redisAssert(de
!= NULL
);
1180 l
= dictGetEntryVal(de
);
1181 ln
= listSearchKey(l
,c
);
1182 redisAssert(ln
!= NULL
);
1184 if (listLength(l
) == 0)
1185 dictDelete(c
->db
->io_keys
,key
);
1188 return listLength(c
->io_keys
) == 0;
1191 /* Every time we now a key was loaded back in memory, we handle clients
1192 * waiting for this key if any. */
1193 void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
) {
1194 struct dictEntry
*de
;
1199 de
= dictFind(db
->io_keys
,key
);
1202 l
= dictGetEntryVal(de
);
1203 len
= listLength(l
);
1204 /* Note: we can't use something like while(listLength(l)) as the list
1205 * can be freed by the calling function when we remove the last element. */
1208 redisClient
*c
= ln
->value
;
1210 if (dontWaitForSwappedKey(c
,key
)) {
1211 /* Put the client in the list of clients ready to go as we
1212 * loaded all the keys about it. */
1213 listAddNodeTail(server
.io_ready_clients
,c
);