8 /* Virtual Memory is composed mainly of two subsystems:
9 * - Blocking Virutal Memory
10 * - Threaded Virtual Memory I/O
11 * The two parts are not fully decoupled, but functions are split among two
12 * different sections of the source code (delimited by comments) in order to
13 * make more clear what functionality is about the blocking VM and what about
14 * the threaded (not blocking) VM.
18 * Redis VM is a blocking VM (one that blocks reading swapped values from
19 * disk into memory when a value swapped out is needed in memory) that is made
20 * unblocking by trying to examine the command argument vector in order to
21 * load in background values that will likely be needed in order to exec
22 * the command. The command is executed only once all the relevant keys
23 * are loaded into memory.
25 * This basically is almost as simple of a blocking VM, but almost as parallel
26 * as a fully non-blocking VM.
29 /* =================== Virtual Memory - Blocking Side ====================== */
31 /* Create a VM pointer object. This kind of objects are used in place of
32 * values in the key -> value hash table, for swapped out objects. */
33 vmpointer
*createVmPointer(int vtype
) {
34 vmpointer
*vp
= zmalloc(sizeof(vmpointer
));
36 vp
->type
= REDIS_VMPOINTER
;
37 vp
->storage
= REDIS_VM_SWAPPED
;
48 if (server
.vm_max_threads
!= 0)
49 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
51 redisLog(REDIS_NOTICE
,"Using '%s' as swap file",server
.vm_swap_file
);
52 /* Try to open the old swap file, otherwise create it */
53 if ((server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b")) == NULL
) {
54 server
.vm_fp
= fopen(server
.vm_swap_file
,"w+b");
56 if (server
.vm_fp
== NULL
) {
57 redisLog(REDIS_WARNING
,
58 "Can't open the swap file: %s. Exiting.",
62 server
.vm_fd
= fileno(server
.vm_fp
);
63 /* Lock the swap file for writing, this is useful in order to avoid
64 * another instance to use the same swap file for a config error. */
66 fl
.l_whence
= SEEK_SET
;
67 fl
.l_start
= fl
.l_len
= 0;
68 if (fcntl(server
.vm_fd
,F_SETLK
,&fl
) == -1) {
69 redisLog(REDIS_WARNING
,
70 "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
));
74 server
.vm_next_page
= 0;
75 server
.vm_near_pages
= 0;
76 server
.vm_stats_used_pages
= 0;
77 server
.vm_stats_swapped_objects
= 0;
78 server
.vm_stats_swapouts
= 0;
79 server
.vm_stats_swapins
= 0;
80 totsize
= server
.vm_pages
*server
.vm_page_size
;
81 redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
);
82 if (ftruncate(server
.vm_fd
,totsize
) == -1) {
83 redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.",
87 redisLog(REDIS_NOTICE
,"Swap file allocated with success");
89 server
.vm_bitmap
= zcalloc((server
.vm_pages
+7)/8);
90 redisLog(REDIS_VERBOSE
,"Allocated %lld bytes page table for %lld pages",
91 (long long) (server
.vm_pages
+7)/8, server
.vm_pages
);
93 /* Initialize threaded I/O (used by Virtual Memory) */
94 server
.io_newjobs
= listCreate();
95 server
.io_processing
= listCreate();
96 server
.io_processed
= listCreate();
97 server
.io_ready_clients
= listCreate();
98 pthread_mutex_init(&server
.io_mutex
,NULL
);
99 pthread_mutex_init(&server
.io_swapfile_mutex
,NULL
);
100 server
.io_active_threads
= 0;
101 if (pipe(pipefds
) == -1) {
102 redisLog(REDIS_WARNING
,"Unable to intialized VM: pipe(2): %s. Exiting."
106 server
.io_ready_pipe_read
= pipefds
[0];
107 server
.io_ready_pipe_write
= pipefds
[1];
108 redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
);
109 /* LZF requires a lot of stack */
110 pthread_attr_init(&server
.io_threads_attr
);
111 pthread_attr_getstacksize(&server
.io_threads_attr
, &stacksize
);
113 /* Solaris may report a stacksize of 0, let's set it to 1 otherwise
114 * multiplying it by 2 in the while loop later will not really help ;) */
115 if (!stacksize
) stacksize
= 1;
117 while (stacksize
< REDIS_THREAD_STACK_SIZE
) stacksize
*= 2;
118 pthread_attr_setstacksize(&server
.io_threads_attr
, stacksize
);
119 /* Listen for events in the threaded I/O pipe */
120 if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
,
121 vmThreadedIOCompletedJob
, NULL
) == AE_ERR
)
122 oom("creating file event");
125 /* Mark the page as used */
126 void vmMarkPageUsed(off_t page
) {
129 redisAssert(vmFreePage(page
) == 1);
130 server
.vm_bitmap
[byte
] |= 1<<bit
;
133 /* Mark N contiguous pages as used, with 'page' being the first. */
134 void vmMarkPagesUsed(off_t page
, off_t count
) {
137 for (j
= 0; j
< count
; j
++)
138 vmMarkPageUsed(page
+j
);
139 server
.vm_stats_used_pages
+= count
;
140 redisLog(REDIS_DEBUG
,"Mark USED pages: %lld pages at %lld\n",
141 (long long)count
, (long long)page
);
144 /* Mark the page as free */
145 void vmMarkPageFree(off_t page
) {
148 redisAssert(vmFreePage(page
) == 0);
149 server
.vm_bitmap
[byte
] &= ~(1<<bit
);
152 /* Mark N contiguous pages as free, with 'page' being the first. */
153 void vmMarkPagesFree(off_t page
, off_t count
) {
156 for (j
= 0; j
< count
; j
++)
157 vmMarkPageFree(page
+j
);
158 server
.vm_stats_used_pages
-= count
;
159 redisLog(REDIS_DEBUG
,"Mark FREE pages: %lld pages at %lld\n",
160 (long long)count
, (long long)page
);
163 /* Test if the page is free */
164 int vmFreePage(off_t page
) {
167 return (server
.vm_bitmap
[byte
] & (1<<bit
)) == 0;
170 /* Find N contiguous free pages storing the first page of the cluster in *first.
171 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
172 * REDIS_ERR is returned.
174 * This function uses a simple algorithm: we try to allocate
175 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
176 * again from the start of the swap file searching for free spaces.
178 * If it looks pretty clear that there are no free pages near our offset
179 * we try to find less populated places doing a forward jump of
180 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
181 * without hurry, and then we jump again and so forth...
183 * This function can be improved using a free list to avoid to guess
184 * too much, since we could collect data about freed pages.
186 * note: I implemented this function just after watching an episode of
187 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
189 int vmFindContiguousPages(off_t
*first
, off_t n
) {
190 off_t base
, offset
= 0, since_jump
= 0, numfree
= 0;
192 if (server
.vm_near_pages
== REDIS_VM_MAX_NEAR_PAGES
) {
193 server
.vm_near_pages
= 0;
194 server
.vm_next_page
= 0;
196 server
.vm_near_pages
++; /* Yet another try for pages near to the old ones */
197 base
= server
.vm_next_page
;
199 while(offset
< server
.vm_pages
) {
200 off_t
this = base
+offset
;
202 /* If we overflow, restart from page zero */
203 if (this >= server
.vm_pages
) {
204 this -= server
.vm_pages
;
206 /* Just overflowed, what we found on tail is no longer
207 * interesting, as it's no longer contiguous. */
211 if (vmFreePage(this)) {
212 /* This is a free page */
214 /* Already got N free pages? Return to the caller, with success */
217 server
.vm_next_page
= this+1;
218 redisLog(REDIS_DEBUG
, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n
, (long long) *first
);
222 /* The current one is not a free page */
226 /* Fast-forward if the current page is not free and we already
227 * searched enough near this place. */
229 if (!numfree
&& since_jump
>= REDIS_VM_MAX_RANDOM_JUMP
/4) {
230 offset
+= random() % REDIS_VM_MAX_RANDOM_JUMP
;
232 /* Note that even if we rewind after the jump, we are don't need
233 * to make sure numfree is set to zero as we only jump *if* it
236 /* Otherwise just check the next page */
243 /* Write the specified object at the specified page of the swap file */
244 int vmWriteObjectOnSwap(robj
*o
, off_t page
) {
245 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
246 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
247 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
248 redisLog(REDIS_WARNING
,
249 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
253 rdbSaveObject(server
.vm_fp
,o
);
254 fflush(server
.vm_fp
);
255 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
259 /* Transfers the 'val' object to disk. Store all the information
260 * a 'vmpointer' object containing all the information needed to load the
261 * object back later is returned.
263 * If we can't find enough contiguous empty pages to swap the object on disk
264 * NULL is returned. */
265 vmpointer
*vmSwapObjectBlocking(robj
*val
) {
266 off_t pages
= rdbSavedObjectPages(val
,NULL
);
270 redisAssert(val
->storage
== REDIS_VM_MEMORY
);
271 redisAssert(val
->refcount
== 1);
272 if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return NULL
;
273 if (vmWriteObjectOnSwap(val
,page
) == REDIS_ERR
) return NULL
;
275 vp
= createVmPointer(val
->type
);
277 vp
->usedpages
= pages
;
278 decrRefCount(val
); /* Deallocate the object from memory. */
279 vmMarkPagesUsed(page
,pages
);
280 redisLog(REDIS_DEBUG
,"VM: object %p swapped out at %lld (%lld pages)",
282 (unsigned long long) page
, (unsigned long long) pages
);
283 server
.vm_stats_swapped_objects
++;
284 server
.vm_stats_swapouts
++;
288 robj
*vmReadObjectFromSwap(off_t page
, int type
) {
291 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
292 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
293 redisLog(REDIS_WARNING
,
294 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
298 o
= rdbLoadObject(type
,server
.vm_fp
);
300 redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno
));
303 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
307 /* Load the specified object from swap to memory.
308 * The newly allocated object is returned.
310 * If preview is true the unserialized object is returned to the caller but
311 * the pages are not marked as freed, nor the vp object is freed. */
312 robj
*vmGenericLoadObject(vmpointer
*vp
, int preview
) {
315 redisAssert(vp
->type
== REDIS_VMPOINTER
&&
316 (vp
->storage
== REDIS_VM_SWAPPED
|| vp
->storage
== REDIS_VM_LOADING
));
317 val
= vmReadObjectFromSwap(vp
->page
,vp
->vtype
);
319 redisLog(REDIS_DEBUG
, "VM: object %p loaded from disk", (void*)vp
);
320 vmMarkPagesFree(vp
->page
,vp
->usedpages
);
322 server
.vm_stats_swapped_objects
--;
324 redisLog(REDIS_DEBUG
, "VM: object %p previewed from disk", (void*)vp
);
326 server
.vm_stats_swapins
++;
330 /* Plain object loading, from swap to memory.
332 * 'o' is actually a redisVmPointer structure that will be freed by the call.
333 * The return value is the loaded object. */
334 robj
*vmLoadObject(robj
*o
) {
335 /* If we are loading the object in background, stop it, we
336 * need to load this object synchronously ASAP. */
337 if (o
->storage
== REDIS_VM_LOADING
)
338 vmCancelThreadedIOJob(o
);
339 return vmGenericLoadObject((vmpointer
*)o
,0);
342 /* Just load the value on disk, without to modify the key.
343 * This is useful when we want to perform some operation on the value
344 * without to really bring it from swap to memory, like while saving the
345 * dataset or rewriting the append only log. */
346 robj
*vmPreviewObject(robj
*o
) {
347 return vmGenericLoadObject((vmpointer
*)o
,1);
350 /* How a good candidate is this object for swapping?
351 * The better candidate it is, the greater the returned value.
353 * Currently we try to perform a fast estimation of the object size in
354 * memory, and combine it with aging informations.
356 * Basically swappability = idle-time * log(estimated size)
358 * Bigger objects are preferred over smaller objects, but not
359 * proportionally, this is why we use the logarithm. This algorithm is
360 * just a first try and will probably be tuned later. */
361 double computeObjectSwappability(robj
*o
) {
362 /* actual age can be >= minage, but not < minage. As we use wrapping
363 * 21 bit clocks with minutes resolution for the LRU. */
364 time_t minage
= estimateObjectIdleTime(o
);
365 long asize
= 0, elesize
;
370 struct dictEntry
*de
;
373 if (minage
<= 0) return 0;
376 if (o
->encoding
!= REDIS_ENCODING_RAW
) {
379 asize
= sdslen(o
->ptr
)+sizeof(*o
)+sizeof(long)*2;
383 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
384 asize
= sizeof(*o
)+ziplistSize(o
->ptr
);
388 asize
= sizeof(list
);
391 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
392 (sizeof(*o
)+sdslen(ele
->ptr
)) : sizeof(*o
);
393 asize
+= (sizeof(listNode
)+elesize
)*listLength(l
);
399 z
= (o
->type
== REDIS_ZSET
);
400 d
= z
? ((zset
*)o
->ptr
)->dict
: o
->ptr
;
402 if (!z
&& o
->encoding
== REDIS_ENCODING_INTSET
) {
404 asize
= sizeof(*is
)+is
->encoding
*is
->length
;
406 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
407 if (z
) asize
+= sizeof(zset
)-sizeof(dict
);
409 de
= dictGetRandomKey(d
);
410 ele
= dictGetEntryKey(de
);
411 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
412 (sizeof(*o
)+sdslen(ele
->ptr
)) : sizeof(*o
);
413 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
414 if (z
) asize
+= sizeof(zskiplistNode
)*dictSize(d
);
419 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
420 unsigned char *p
= zipmapRewind((unsigned char*)o
->ptr
);
421 unsigned int len
= zipmapLen((unsigned char*)o
->ptr
);
422 unsigned int klen
, vlen
;
423 unsigned char *key
, *val
;
425 if ((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) == NULL
) {
429 asize
= len
*(klen
+vlen
+3);
430 } else if (o
->encoding
== REDIS_ENCODING_HT
) {
432 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
434 de
= dictGetRandomKey(d
);
435 ele
= dictGetEntryKey(de
);
436 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
437 (sizeof(*o
)+sdslen(ele
->ptr
)) : sizeof(*o
);
438 ele
= dictGetEntryVal(de
);
439 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
440 (sizeof(*o
)+sdslen(ele
->ptr
)) : sizeof(*o
);
441 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
446 return (double)minage
*log(1+asize
);
449 /* Try to swap an object that's a good candidate for swapping.
450 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
451 * to swap any object at all.
453 * If 'usethreaded' is true, Redis will try to swap the object in background
454 * using I/O threads. */
455 int vmSwapOneObject(int usethreads
) {
457 struct dictEntry
*best
= NULL
;
458 double best_swappability
= 0;
459 redisDb
*best_db
= NULL
;
463 for (j
= 0; j
< server
.dbnum
; j
++) {
464 redisDb
*db
= server
.db
+j
;
465 /* Why maxtries is set to 100?
466 * Because this way (usually) we'll find 1 object even if just 1% - 2%
467 * are swappable objects */
470 if (dictSize(db
->dict
) == 0) continue;
471 for (i
= 0; i
< 5; i
++) {
475 if (maxtries
) maxtries
--;
476 de
= dictGetRandomKey(db
->dict
);
477 val
= dictGetEntryVal(de
);
478 /* Only swap objects that are currently in memory.
480 * Also don't swap shared objects: not a good idea in general and
481 * we need to ensure that the main thread does not touch the
482 * object while the I/O thread is using it, but we can't
483 * control other keys without adding additional mutex. */
484 if (val
->storage
!= REDIS_VM_MEMORY
|| val
->refcount
!= 1) {
485 if (maxtries
) i
--; /* don't count this try */
488 swappability
= computeObjectSwappability(val
);
489 if (!best
|| swappability
> best_swappability
) {
491 best_swappability
= swappability
;
496 if (best
== NULL
) return REDIS_ERR
;
497 key
= dictGetEntryKey(best
);
498 val
= dictGetEntryVal(best
);
500 redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f",
501 key
, best_swappability
);
505 robj
*keyobj
= createStringObject(key
,sdslen(key
));
506 vmSwapObjectThreaded(keyobj
,val
,best_db
);
507 decrRefCount(keyobj
);
512 if ((vp
= vmSwapObjectBlocking(val
)) != NULL
) {
513 dictGetEntryVal(best
) = vp
;
521 int vmSwapOneObjectBlocking() {
522 return vmSwapOneObject(0);
525 int vmSwapOneObjectThreaded() {
526 return vmSwapOneObject(1);
529 /* Return true if it's safe to swap out objects in a given moment.
530 * Basically we don't want to swap objects out while there is a BGSAVE
531 * or a BGAEOREWRITE running in backgroud. */
532 int vmCanSwapOut(void) {
533 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
536 /* =================== Virtual Memory - Threaded I/O ======================= */
538 void freeIOJob(iojob
*j
) {
539 if ((j
->type
== REDIS_IOJOB_PREPARE_SWAP
||
540 j
->type
== REDIS_IOJOB_DO_SWAP
||
541 j
->type
== REDIS_IOJOB_LOAD
) && j
->val
!= NULL
)
543 /* we fix the storage type, otherwise decrRefCount() will try to
544 * kill the I/O thread Job (that does no longer exists). */
545 if (j
->val
->storage
== REDIS_VM_SWAPPING
)
546 j
->val
->storage
= REDIS_VM_MEMORY
;
547 decrRefCount(j
->val
);
549 decrRefCount(j
->key
);
553 /* Every time a thread finished a Job, it writes a byte into the write side
554 * of an unix pipe in order to "awake" the main thread, and this function
557 * Note that this is called both by the event loop, when a I/O thread
558 * sends a byte in the notification pipe, and is also directly called from
559 * waitEmptyIOJobsQueue().
561 * In the latter case we don't want to swap more, so we use the
562 * "privdata" argument setting it to a not NULL value to signal this
564 void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
,
568 int retval
, processed
= 0, toprocess
= -1, trytoswap
= 1;
571 REDIS_NOTUSED(privdata
);
573 if (privdata
!= NULL
) trytoswap
= 0; /* check the comments above... */
575 /* For every byte we read in the read side of the pipe, there is one
576 * I/O job completed to process. */
577 while((retval
= read(fd
,buf
,1)) == 1) {
580 struct dictEntry
*de
;
582 redisLog(REDIS_DEBUG
,"Processing I/O completed job");
584 /* Get the processed element (the oldest one) */
586 redisAssert(listLength(server
.io_processed
) != 0);
587 if (toprocess
== -1) {
588 toprocess
= (listLength(server
.io_processed
)*REDIS_MAX_COMPLETED_JOBS_PROCESSED
)/100;
589 if (toprocess
<= 0) toprocess
= 1;
591 ln
= listFirst(server
.io_processed
);
593 listDelNode(server
.io_processed
,ln
);
595 /* If this job is marked as canceled, just ignore it */
600 /* Post process it in the main thread, as there are things we
601 * can do just here to avoid race conditions and/or invasive locks */
602 redisLog(REDIS_DEBUG
,"COMPLETED Job type: %d, ID %p, key: %s", j
->type
, (void*)j
->id
, (unsigned char*)j
->key
->ptr
);
603 de
= dictFind(j
->db
->dict
,j
->key
->ptr
);
604 redisAssert(de
!= NULL
);
605 if (j
->type
== REDIS_IOJOB_LOAD
) {
607 vmpointer
*vp
= dictGetEntryVal(de
);
609 /* Key loaded, bring it at home */
610 vmMarkPagesFree(vp
->page
,vp
->usedpages
);
611 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk (threaded)",
612 (unsigned char*) j
->key
->ptr
);
613 server
.vm_stats_swapped_objects
--;
614 server
.vm_stats_swapins
++;
615 dictGetEntryVal(de
) = j
->val
;
616 incrRefCount(j
->val
);
618 /* Handle clients waiting for this key to be loaded. */
619 handleClientsBlockedOnSwappedKey(db
,j
->key
);
622 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
623 /* Now we know the amount of pages required to swap this object.
624 * Let's find some space for it, and queue this task again
625 * rebranded as REDIS_IOJOB_DO_SWAP. */
626 if (!vmCanSwapOut() ||
627 vmFindContiguousPages(&j
->page
,j
->pages
) == REDIS_ERR
)
629 /* Ooops... no space or we can't swap as there is
630 * a fork()ed Redis trying to save stuff on disk. */
631 j
->val
->storage
= REDIS_VM_MEMORY
; /* undo operation */
634 /* Note that we need to mark this pages as used now,
635 * if the job will be canceled, we'll mark them as freed
637 vmMarkPagesUsed(j
->page
,j
->pages
);
638 j
->type
= REDIS_IOJOB_DO_SWAP
;
643 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
646 /* Key swapped. We can finally free some memory. */
647 if (j
->val
->storage
!= REDIS_VM_SWAPPING
) {
648 vmpointer
*vp
= (vmpointer
*) j
->id
;
649 printf("storage: %d\n",vp
->storage
);
650 printf("key->name: %s\n",(char*)j
->key
->ptr
);
651 printf("val: %p\n",(void*)j
->val
);
652 printf("val->type: %d\n",j
->val
->type
);
653 printf("val->ptr: %s\n",(char*)j
->val
->ptr
);
655 redisAssert(j
->val
->storage
== REDIS_VM_SWAPPING
);
656 vp
= createVmPointer(j
->val
->type
);
658 vp
->usedpages
= j
->pages
;
659 dictGetEntryVal(de
) = vp
;
660 /* Fix the storage otherwise decrRefCount will attempt to
661 * remove the associated I/O job */
662 j
->val
->storage
= REDIS_VM_MEMORY
;
663 decrRefCount(j
->val
);
664 redisLog(REDIS_DEBUG
,
665 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
666 (unsigned char*) j
->key
->ptr
,
667 (unsigned long long) j
->page
, (unsigned long long) j
->pages
);
668 server
.vm_stats_swapped_objects
++;
669 server
.vm_stats_swapouts
++;
671 /* Put a few more swap requests in queue if we are still
673 if (trytoswap
&& vmCanSwapOut() &&
674 zmalloc_used_memory() > server
.vm_max_memory
)
679 more
= listLength(server
.io_newjobs
) <
680 (unsigned) server
.vm_max_threads
;
682 /* Don't waste CPU time if swappable objects are rare. */
683 if (vmSwapOneObjectThreaded() == REDIS_ERR
) {
691 if (processed
== toprocess
) return;
693 if (retval
< 0 && errno
!= EAGAIN
) {
694 redisLog(REDIS_WARNING
,
695 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
700 void lockThreadedIO(void) {
701 pthread_mutex_lock(&server
.io_mutex
);
704 void unlockThreadedIO(void) {
705 pthread_mutex_unlock(&server
.io_mutex
);
708 /* Remove the specified object from the threaded I/O queue if still not
709 * processed, otherwise make sure to flag it as canceled. */
710 void vmCancelThreadedIOJob(robj
*o
) {
712 server
.io_newjobs
, /* 0 */
713 server
.io_processing
, /* 1 */
714 server
.io_processed
/* 2 */
718 redisAssert(o
->storage
== REDIS_VM_LOADING
|| o
->storage
== REDIS_VM_SWAPPING
);
721 /* Search for a matching object in one of the queues */
722 for (i
= 0; i
< 3; i
++) {
726 listRewind(lists
[i
],&li
);
727 while ((ln
= listNext(&li
)) != NULL
) {
728 iojob
*job
= ln
->value
;
730 if (job
->canceled
) continue; /* Skip this, already canceled. */
732 redisLog(REDIS_DEBUG
,"*** CANCELED %p (key %s) (type %d) (LIST ID %d)\n",
733 (void*)job
, (char*)job
->key
->ptr
, job
->type
, i
);
734 /* Mark the pages as free since the swap didn't happened
735 * or happened but is now discarded. */
736 if (i
!= 1 && job
->type
== REDIS_IOJOB_DO_SWAP
)
737 vmMarkPagesFree(job
->page
,job
->pages
);
738 /* Cancel the job. It depends on the list the job is
741 case 0: /* io_newjobs */
742 /* If the job was yet not processed the best thing to do
743 * is to remove it from the queue at all */
745 listDelNode(lists
[i
],ln
);
747 case 1: /* io_processing */
748 /* Oh Shi- the thread is messing with the Job:
750 * Probably it's accessing the object if this is a
751 * PREPARE_SWAP or DO_SWAP job.
752 * If it's a LOAD job it may be reading from disk and
753 * if we don't wait for the job to terminate before to
754 * cancel it, maybe in a few microseconds data can be
755 * corrupted in this pages. So the short story is:
757 * Better to wait for the job to move into the
758 * next queue (processed)... */
760 /* We try again and again until the job is completed. */
762 /* But let's wait some time for the I/O thread
763 * to finish with this job. After all this condition
764 * should be very rare. */
767 case 2: /* io_processed */
768 /* The job was already processed, that's easy...
769 * just mark it as canceled so that we'll ignore it
770 * when processing completed jobs. */
774 /* Finally we have to adjust the storage type of the object
775 * in order to "UNDO" the operaiton. */
776 if (o
->storage
== REDIS_VM_LOADING
)
777 o
->storage
= REDIS_VM_SWAPPED
;
778 else if (o
->storage
== REDIS_VM_SWAPPING
)
779 o
->storage
= REDIS_VM_MEMORY
;
781 redisLog(REDIS_DEBUG
,"*** DONE");
787 printf("Not found: %p\n", (void*)o
);
788 redisAssert(1 != 1); /* We should never reach this */
791 void *IOThreadEntryPoint(void *arg
) {
796 pthread_detach(pthread_self());
798 /* Get a new job to process */
800 if (listLength(server
.io_newjobs
) == 0) {
801 /* No new jobs in queue, exit. */
802 redisLog(REDIS_DEBUG
,"Thread %ld exiting, nothing to do",
803 (long) pthread_self());
804 server
.io_active_threads
--;
808 ln
= listFirst(server
.io_newjobs
);
810 listDelNode(server
.io_newjobs
,ln
);
811 /* Add the job in the processing queue */
812 j
->thread
= pthread_self();
813 listAddNodeTail(server
.io_processing
,j
);
814 ln
= listLast(server
.io_processing
); /* We use ln later to remove it */
816 redisLog(REDIS_DEBUG
,"Thread %ld got a new job (type %d): %p about key '%s'",
817 (long) pthread_self(), j
->type
, (void*)j
, (char*)j
->key
->ptr
);
819 /* Process the Job */
820 if (j
->type
== REDIS_IOJOB_LOAD
) {
821 vmpointer
*vp
= (vmpointer
*)j
->id
;
822 j
->val
= vmReadObjectFromSwap(j
->page
,vp
->vtype
);
823 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
824 FILE *fp
= fopen("/dev/null","w+");
825 j
->pages
= rdbSavedObjectPages(j
->val
,fp
);
827 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
828 if (vmWriteObjectOnSwap(j
->val
,j
->page
) == REDIS_ERR
)
832 /* Done: insert the job into the processed queue */
833 redisLog(REDIS_DEBUG
,"Thread %ld completed the job: %p (key %s)",
834 (long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
);
836 listDelNode(server
.io_processing
,ln
);
837 listAddNodeTail(server
.io_processed
,j
);
840 /* Signal the main thread there is new stuff to process */
841 redisAssert(write(server
.io_ready_pipe_write
,"x",1) == 1);
843 return NULL
; /* never reached */
846 void spawnIOThread(void) {
848 sigset_t mask
, omask
;
852 sigaddset(&mask
,SIGCHLD
);
853 sigaddset(&mask
,SIGHUP
);
854 sigaddset(&mask
,SIGPIPE
);
855 pthread_sigmask(SIG_SETMASK
, &mask
, &omask
);
856 while ((err
= pthread_create(&thread
,&server
.io_threads_attr
,IOThreadEntryPoint
,NULL
)) != 0) {
857 redisLog(REDIS_WARNING
,"Unable to spawn an I/O thread: %s",
861 pthread_sigmask(SIG_SETMASK
, &omask
, NULL
);
862 server
.io_active_threads
++;
865 /* We need to wait for the last thread to exit before we are able to
866 * fork() in order to BGSAVE or BGREWRITEAOF. */
867 void waitEmptyIOJobsQueue(void) {
869 int io_processed_len
;
872 if (listLength(server
.io_newjobs
) == 0 &&
873 listLength(server
.io_processing
) == 0 &&
874 server
.io_active_threads
== 0)
879 /* While waiting for empty jobs queue condition we post-process some
880 * finshed job, as I/O threads may be hanging trying to write against
881 * the io_ready_pipe_write FD but there are so much pending jobs that
883 io_processed_len
= listLength(server
.io_processed
);
885 if (io_processed_len
) {
886 vmThreadedIOCompletedJob(NULL
,server
.io_ready_pipe_read
,
887 (void*)0xdeadbeef,0);
888 usleep(1000); /* 1 millisecond */
890 usleep(10000); /* 10 milliseconds */
895 void vmReopenSwapFile(void) {
896 /* Note: we don't close the old one as we are in the child process
897 * and don't want to mess at all with the original file object. */
898 server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b");
899 if (server
.vm_fp
== NULL
) {
900 redisLog(REDIS_WARNING
,"Can't re-open the VM swap file: %s. Exiting.",
901 server
.vm_swap_file
);
904 server
.vm_fd
= fileno(server
.vm_fp
);
907 /* This function must be called while with threaded IO locked */
908 void queueIOJob(iojob
*j
) {
909 redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n",
910 (void*)j
, j
->type
, (char*)j
->key
->ptr
);
911 listAddNodeTail(server
.io_newjobs
,j
);
912 if (server
.io_active_threads
< server
.vm_max_threads
)
916 int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
) {
919 j
= zmalloc(sizeof(*j
));
920 j
->type
= REDIS_IOJOB_PREPARE_SWAP
;
924 j
->id
= j
->val
= val
;
927 j
->thread
= (pthread_t
) -1;
928 val
->storage
= REDIS_VM_SWAPPING
;
936 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
938 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
939 * If there is not already a job loading the key, it is craeted.
940 * The key is added to the io_keys list in the client structure, and also
941 * in the hash table mapping swapped keys to waiting clients, that is,
942 * server.io_waited_keys. */
943 int waitForSwappedKey(redisClient
*c
, robj
*key
) {
944 struct dictEntry
*de
;
948 /* If the key does not exist or is already in RAM we don't need to
949 * block the client at all. */
950 de
= dictFind(c
->db
->dict
,key
->ptr
);
951 if (de
== NULL
) return 0;
952 o
= dictGetEntryVal(de
);
953 if (o
->storage
== REDIS_VM_MEMORY
) {
955 } else if (o
->storage
== REDIS_VM_SWAPPING
) {
956 /* We were swapping the key, undo it! */
957 vmCancelThreadedIOJob(o
);
961 /* OK: the key is either swapped, or being loaded just now. */
963 /* Add the key to the list of keys this client is waiting for.
964 * This maps clients to keys they are waiting for. */
965 listAddNodeTail(c
->io_keys
,key
);
968 /* Add the client to the swapped keys => clients waiting map. */
969 de
= dictFind(c
->db
->io_keys
,key
);
973 /* For every key we take a list of clients blocked for it */
975 retval
= dictAdd(c
->db
->io_keys
,key
,l
);
977 redisAssert(retval
== DICT_OK
);
979 l
= dictGetEntryVal(de
);
981 listAddNodeTail(l
,c
);
983 /* Are we already loading the key from disk? If not create a job */
984 if (o
->storage
== REDIS_VM_SWAPPED
) {
986 vmpointer
*vp
= (vmpointer
*)o
;
988 o
->storage
= REDIS_VM_LOADING
;
989 j
= zmalloc(sizeof(*j
));
990 j
->type
= REDIS_IOJOB_LOAD
;
998 j
->thread
= (pthread_t
) -1;
1006 /* Preload keys for any command with first, last and step values for
1007 * the command keys prototype, as defined in the command table. */
1008 void waitForMultipleSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
1010 if (cmd
->vm_firstkey
== 0) return;
1011 last
= cmd
->vm_lastkey
;
1012 if (last
< 0) last
= argc
+last
;
1013 for (j
= cmd
->vm_firstkey
; j
<= last
; j
+= cmd
->vm_keystep
) {
1014 redisAssert(j
< argc
);
1015 waitForSwappedKey(c
,argv
[j
]);
1019 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
1020 * Note that the number of keys to preload is user-defined, so we need to
1021 * apply a sanity check against argc. */
1022 void zunionInterBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
1026 num
= atoi(argv
[2]->ptr
);
1027 if (num
> (argc
-3)) return;
1028 for (i
= 0; i
< num
; i
++) {
1029 waitForSwappedKey(c
,argv
[3+i
]);
1033 /* Preload keys needed to execute the entire MULTI/EXEC block.
1035 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
1036 * and will block the client when any command requires a swapped out value. */
1037 void execBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
1039 struct redisCommand
*mcmd
;
1042 REDIS_NOTUSED(argc
);
1043 REDIS_NOTUSED(argv
);
1045 if (!(c
->flags
& REDIS_MULTI
)) return;
1046 for (i
= 0; i
< c
->mstate
.count
; i
++) {
1047 mcmd
= c
->mstate
.commands
[i
].cmd
;
1048 margc
= c
->mstate
.commands
[i
].argc
;
1049 margv
= c
->mstate
.commands
[i
].argv
;
1051 if (mcmd
->vm_preload_proc
!= NULL
) {
1052 mcmd
->vm_preload_proc(c
,mcmd
,margc
,margv
);
1054 waitForMultipleSwappedKeys(c
,mcmd
,margc
,margv
);
1059 /* Is this client attempting to run a command against swapped keys?
1060 * If so, block it ASAP, load the keys in background, then resume it.
1062 * The important idea about this function is that it can fail! If keys will
1063 * still be swapped when the client is resumed, this key lookups will
1064 * just block loading keys from disk. In practical terms this should only
1065 * happen with SORT BY command or if there is a bug in this function.
1067 * Return 1 if the client is marked as blocked, 0 if the client can
1068 * continue as the keys it is going to access appear to be in memory. */
1069 int blockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
) {
1070 if (cmd
->vm_preload_proc
!= NULL
) {
1071 cmd
->vm_preload_proc(c
,cmd
,c
->argc
,c
->argv
);
1073 waitForMultipleSwappedKeys(c
,cmd
,c
->argc
,c
->argv
);
1076 /* If the client was blocked for at least one key, mark it as blocked. */
1077 if (listLength(c
->io_keys
)) {
1078 c
->flags
|= REDIS_IO_WAIT
;
1079 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
1080 server
.vm_blocked_clients
++;
1087 /* Remove the 'key' from the list of blocked keys for a given client.
1089 * The function returns 1 when there are no longer blocking keys after
1090 * the current one was removed (and the client can be unblocked). */
1091 int dontWaitForSwappedKey(redisClient
*c
, robj
*key
) {
1095 struct dictEntry
*de
;
1097 /* The key object might be destroyed when deleted from the c->io_keys
1098 * list (and the "key" argument is physically the same object as the
1099 * object inside the list), so we need to protect it. */
1102 /* Remove the key from the list of keys this client is waiting for. */
1103 listRewind(c
->io_keys
,&li
);
1104 while ((ln
= listNext(&li
)) != NULL
) {
1105 if (equalStringObjects(ln
->value
,key
)) {
1106 listDelNode(c
->io_keys
,ln
);
1110 redisAssert(ln
!= NULL
);
1112 /* Remove the client form the key => waiting clients map. */
1113 de
= dictFind(c
->db
->io_keys
,key
);
1114 redisAssert(de
!= NULL
);
1115 l
= dictGetEntryVal(de
);
1116 ln
= listSearchKey(l
,c
);
1117 redisAssert(ln
!= NULL
);
1119 if (listLength(l
) == 0)
1120 dictDelete(c
->db
->io_keys
,key
);
1123 return listLength(c
->io_keys
) == 0;
1126 /* Every time we now a key was loaded back in memory, we handle clients
1127 * waiting for this key if any. */
1128 void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
) {
1129 struct dictEntry
*de
;
1134 de
= dictFind(db
->io_keys
,key
);
1137 l
= dictGetEntryVal(de
);
1138 len
= listLength(l
);
1139 /* Note: we can't use something like while(listLength(l)) as the list
1140 * can be freed by the calling function when we remove the last element. */
1143 redisClient
*c
= ln
->value
;
1145 if (dontWaitForSwappedKey(c
,key
)) {
1146 /* Put the client in the list of clients ready to go as we
1147 * loaded all the keys about it. */
1148 listAddNodeTail(server
.io_ready_clients
,c
);