]> git.saurik.com Git - redis.git/blob - src/vm.c
635016b859a2096057bfb73b62e52c04b1d79afc
[redis.git] / src / vm.c
1 #include "redis.h"
2
3 #include <fcntl.h>
4 #include <pthread.h>
5 #include <math.h>
6 #include <signal.h>
7
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.
15 *
16 * Redis VM design:
17 *
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.
24 *
25 * This basically is almost as simple of a blocking VM, but almost as parallel
26 * as a fully non-blocking VM.
27 */
28
29 /* =================== Virtual Memory - Blocking Side ====================== */
30
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));
35
36 vp->type = REDIS_VMPOINTER;
37 vp->storage = REDIS_VM_SWAPPED;
38 vp->vtype = vtype;
39 return vp;
40 }
41
42 void vmInit(void) {
43 off_t totsize;
44 int pipefds[2];
45 size_t stacksize;
46 struct flock fl;
47
48 if (server.vm_max_threads != 0)
49 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
50
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");
55 }
56 if (server.vm_fp == NULL) {
57 redisLog(REDIS_WARNING,
58 "Can't open the swap file: %s. Exiting.",
59 strerror(errno));
60 exit(1);
61 }
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. */
65 fl.l_type = F_WRLCK;
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));
71 exit(1);
72 }
73 /* Initialize */
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.",
84 strerror(errno));
85 exit(1);
86 } else {
87 redisLog(REDIS_NOTICE,"Swap file allocated with success");
88 }
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);
92
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.obj_freelist_mutex,NULL);
100 pthread_mutex_init(&server.io_swapfile_mutex,NULL);
101 server.io_active_threads = 0;
102 if (pipe(pipefds) == -1) {
103 redisLog(REDIS_WARNING,"Unable to intialized VM: pipe(2): %s. Exiting."
104 ,strerror(errno));
105 exit(1);
106 }
107 server.io_ready_pipe_read = pipefds[0];
108 server.io_ready_pipe_write = pipefds[1];
109 redisAssert(anetNonBlock(NULL,server.io_ready_pipe_read) != ANET_ERR);
110 /* LZF requires a lot of stack */
111 pthread_attr_init(&server.io_threads_attr);
112 pthread_attr_getstacksize(&server.io_threads_attr, &stacksize);
113 if(!stacksize) {
114 stacksize = 1;
115 }
116 while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2;
117 pthread_attr_setstacksize(&server.io_threads_attr, stacksize);
118 /* Listen for events in the threaded I/O pipe */
119 if (aeCreateFileEvent(server.el, server.io_ready_pipe_read, AE_READABLE,
120 vmThreadedIOCompletedJob, NULL) == AE_ERR)
121 oom("creating file event");
122 }
123
124 /* Mark the page as used */
125 void vmMarkPageUsed(off_t page) {
126 off_t byte = page/8;
127 int bit = page&7;
128 redisAssert(vmFreePage(page) == 1);
129 server.vm_bitmap[byte] |= 1<<bit;
130 }
131
132 /* Mark N contiguous pages as used, with 'page' being the first. */
133 void vmMarkPagesUsed(off_t page, off_t count) {
134 off_t j;
135
136 for (j = 0; j < count; j++)
137 vmMarkPageUsed(page+j);
138 server.vm_stats_used_pages += count;
139 redisLog(REDIS_DEBUG,"Mark USED pages: %lld pages at %lld\n",
140 (long long)count, (long long)page);
141 }
142
143 /* Mark the page as free */
144 void vmMarkPageFree(off_t page) {
145 off_t byte = page/8;
146 int bit = page&7;
147 redisAssert(vmFreePage(page) == 0);
148 server.vm_bitmap[byte] &= ~(1<<bit);
149 }
150
151 /* Mark N contiguous pages as free, with 'page' being the first. */
152 void vmMarkPagesFree(off_t page, off_t count) {
153 off_t j;
154
155 for (j = 0; j < count; j++)
156 vmMarkPageFree(page+j);
157 server.vm_stats_used_pages -= count;
158 redisLog(REDIS_DEBUG,"Mark FREE pages: %lld pages at %lld\n",
159 (long long)count, (long long)page);
160 }
161
162 /* Test if the page is free */
163 int vmFreePage(off_t page) {
164 off_t byte = page/8;
165 int bit = page&7;
166 return (server.vm_bitmap[byte] & (1<<bit)) == 0;
167 }
168
169 /* Find N contiguous free pages storing the first page of the cluster in *first.
170 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
171 * REDIS_ERR is returned.
172 *
173 * This function uses a simple algorithm: we try to allocate
174 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
175 * again from the start of the swap file searching for free spaces.
176 *
177 * If it looks pretty clear that there are no free pages near our offset
178 * we try to find less populated places doing a forward jump of
179 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
180 * without hurry, and then we jump again and so forth...
181 *
182 * This function can be improved using a free list to avoid to guess
183 * too much, since we could collect data about freed pages.
184 *
185 * note: I implemented this function just after watching an episode of
186 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
187 */
188 int vmFindContiguousPages(off_t *first, off_t n) {
189 off_t base, offset = 0, since_jump = 0, numfree = 0;
190
191 if (server.vm_near_pages == REDIS_VM_MAX_NEAR_PAGES) {
192 server.vm_near_pages = 0;
193 server.vm_next_page = 0;
194 }
195 server.vm_near_pages++; /* Yet another try for pages near to the old ones */
196 base = server.vm_next_page;
197
198 while(offset < server.vm_pages) {
199 off_t this = base+offset;
200
201 /* If we overflow, restart from page zero */
202 if (this >= server.vm_pages) {
203 this -= server.vm_pages;
204 if (this == 0) {
205 /* Just overflowed, what we found on tail is no longer
206 * interesting, as it's no longer contiguous. */
207 numfree = 0;
208 }
209 }
210 if (vmFreePage(this)) {
211 /* This is a free page */
212 numfree++;
213 /* Already got N free pages? Return to the caller, with success */
214 if (numfree == n) {
215 *first = this-(n-1);
216 server.vm_next_page = this+1;
217 redisLog(REDIS_DEBUG, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n, (long long) *first);
218 return REDIS_OK;
219 }
220 } else {
221 /* The current one is not a free page */
222 numfree = 0;
223 }
224
225 /* Fast-forward if the current page is not free and we already
226 * searched enough near this place. */
227 since_jump++;
228 if (!numfree && since_jump >= REDIS_VM_MAX_RANDOM_JUMP/4) {
229 offset += random() % REDIS_VM_MAX_RANDOM_JUMP;
230 since_jump = 0;
231 /* Note that even if we rewind after the jump, we are don't need
232 * to make sure numfree is set to zero as we only jump *if* it
233 * is set to zero. */
234 } else {
235 /* Otherwise just check the next page */
236 offset++;
237 }
238 }
239 return REDIS_ERR;
240 }
241
242 /* Write the specified object at the specified page of the swap file */
243 int vmWriteObjectOnSwap(robj *o, off_t page) {
244 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
245 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
246 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
247 redisLog(REDIS_WARNING,
248 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
249 strerror(errno));
250 return REDIS_ERR;
251 }
252 rdbSaveObject(server.vm_fp,o);
253 fflush(server.vm_fp);
254 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
255 return REDIS_OK;
256 }
257
258 /* Transfers the 'val' object to disk. Store all the information
259 * a 'vmpointer' object containing all the information needed to load the
260 * object back later is returned.
261 *
262 * If we can't find enough contiguous empty pages to swap the object on disk
263 * NULL is returned. */
264 vmpointer *vmSwapObjectBlocking(robj *val) {
265 off_t pages = rdbSavedObjectPages(val,NULL);
266 off_t page;
267 vmpointer *vp;
268
269 redisAssert(val->storage == REDIS_VM_MEMORY);
270 redisAssert(val->refcount == 1);
271 if (vmFindContiguousPages(&page,pages) == REDIS_ERR) return NULL;
272 if (vmWriteObjectOnSwap(val,page) == REDIS_ERR) return NULL;
273
274 vp = createVmPointer(val->type);
275 vp->page = page;
276 vp->usedpages = pages;
277 decrRefCount(val); /* Deallocate the object from memory. */
278 vmMarkPagesUsed(page,pages);
279 redisLog(REDIS_DEBUG,"VM: object %p swapped out at %lld (%lld pages)",
280 (void*) val,
281 (unsigned long long) page, (unsigned long long) pages);
282 server.vm_stats_swapped_objects++;
283 server.vm_stats_swapouts++;
284 return vp;
285 }
286
287 robj *vmReadObjectFromSwap(off_t page, int type) {
288 robj *o;
289
290 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
291 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
292 redisLog(REDIS_WARNING,
293 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
294 strerror(errno));
295 _exit(1);
296 }
297 o = rdbLoadObject(type,server.vm_fp);
298 if (o == NULL) {
299 redisLog(REDIS_WARNING, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno));
300 _exit(1);
301 }
302 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
303 return o;
304 }
305
306 /* Load the specified object from swap to memory.
307 * The newly allocated object is returned.
308 *
309 * If preview is true the unserialized object is returned to the caller but
310 * the pages are not marked as freed, nor the vp object is freed. */
311 robj *vmGenericLoadObject(vmpointer *vp, int preview) {
312 robj *val;
313
314 redisAssert(vp->type == REDIS_VMPOINTER &&
315 (vp->storage == REDIS_VM_SWAPPED || vp->storage == REDIS_VM_LOADING));
316 val = vmReadObjectFromSwap(vp->page,vp->vtype);
317 if (!preview) {
318 redisLog(REDIS_DEBUG, "VM: object %p loaded from disk", (void*)vp);
319 vmMarkPagesFree(vp->page,vp->usedpages);
320 zfree(vp);
321 server.vm_stats_swapped_objects--;
322 } else {
323 redisLog(REDIS_DEBUG, "VM: object %p previewed from disk", (void*)vp);
324 }
325 server.vm_stats_swapins++;
326 return val;
327 }
328
329 /* Plain object loading, from swap to memory.
330 *
331 * 'o' is actually a redisVmPointer structure that will be freed by the call.
332 * The return value is the loaded object. */
333 robj *vmLoadObject(robj *o) {
334 /* If we are loading the object in background, stop it, we
335 * need to load this object synchronously ASAP. */
336 if (o->storage == REDIS_VM_LOADING)
337 vmCancelThreadedIOJob(o);
338 return vmGenericLoadObject((vmpointer*)o,0);
339 }
340
341 /* Just load the value on disk, without to modify the key.
342 * This is useful when we want to perform some operation on the value
343 * without to really bring it from swap to memory, like while saving the
344 * dataset or rewriting the append only log. */
345 robj *vmPreviewObject(robj *o) {
346 return vmGenericLoadObject((vmpointer*)o,1);
347 }
348
349 /* How a good candidate is this object for swapping?
350 * The better candidate it is, the greater the returned value.
351 *
352 * Currently we try to perform a fast estimation of the object size in
353 * memory, and combine it with aging informations.
354 *
355 * Basically swappability = idle-time * log(estimated size)
356 *
357 * Bigger objects are preferred over smaller objects, but not
358 * proportionally, this is why we use the logarithm. This algorithm is
359 * just a first try and will probably be tuned later. */
360 double computeObjectSwappability(robj *o) {
361 /* actual age can be >= minage, but not < minage. As we use wrapping
362 * 21 bit clocks with minutes resolution for the LRU. */
363 time_t minage = abs(server.lruclock - o->lru);
364 long asize = 0, elesize;
365 robj *ele;
366 list *l;
367 listNode *ln;
368 dict *d;
369 struct dictEntry *de;
370 int z;
371
372 if (minage <= 0) return 0;
373 switch(o->type) {
374 case REDIS_STRING:
375 if (o->encoding != REDIS_ENCODING_RAW) {
376 asize = sizeof(*o);
377 } else {
378 asize = sdslen(o->ptr)+sizeof(*o)+sizeof(long)*2;
379 }
380 break;
381 case REDIS_LIST:
382 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
383 asize = sizeof(*o)+ziplistSize(o->ptr);
384 } else {
385 l = o->ptr;
386 ln = listFirst(l);
387 asize = sizeof(list);
388 if (ln) {
389 ele = ln->value;
390 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
391 (sizeof(*o)+sdslen(ele->ptr)) : sizeof(*o);
392 asize += (sizeof(listNode)+elesize)*listLength(l);
393 }
394 }
395 break;
396 case REDIS_SET:
397 case REDIS_ZSET:
398 z = (o->type == REDIS_ZSET);
399 d = z ? ((zset*)o->ptr)->dict : o->ptr;
400
401 if (!z && o->encoding == REDIS_ENCODING_INTSET) {
402 intset *is = o->ptr;
403 asize = sizeof(*is)+is->encoding*is->length;
404 } else {
405 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
406 if (z) asize += sizeof(zset)-sizeof(dict);
407 if (dictSize(d)) {
408 de = dictGetRandomKey(d);
409 ele = dictGetEntryKey(de);
410 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
411 (sizeof(*o)+sdslen(ele->ptr)) : sizeof(*o);
412 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
413 if (z) asize += sizeof(zskiplistNode)*dictSize(d);
414 }
415 }
416 break;
417 case REDIS_HASH:
418 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
419 unsigned char *p = zipmapRewind((unsigned char*)o->ptr);
420 unsigned int len = zipmapLen((unsigned char*)o->ptr);
421 unsigned int klen, vlen;
422 unsigned char *key, *val;
423
424 if ((p = zipmapNext(p,&key,&klen,&val,&vlen)) == NULL) {
425 klen = 0;
426 vlen = 0;
427 }
428 asize = len*(klen+vlen+3);
429 } else if (o->encoding == REDIS_ENCODING_HT) {
430 d = o->ptr;
431 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
432 if (dictSize(d)) {
433 de = dictGetRandomKey(d);
434 ele = dictGetEntryKey(de);
435 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
436 (sizeof(*o)+sdslen(ele->ptr)) : sizeof(*o);
437 ele = dictGetEntryVal(de);
438 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
439 (sizeof(*o)+sdslen(ele->ptr)) : sizeof(*o);
440 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
441 }
442 }
443 break;
444 }
445 return (double)minage*log(1+asize);
446 }
447
448 /* Try to swap an object that's a good candidate for swapping.
449 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
450 * to swap any object at all.
451 *
452 * If 'usethreaded' is true, Redis will try to swap the object in background
453 * using I/O threads. */
454 int vmSwapOneObject(int usethreads) {
455 int j, i;
456 struct dictEntry *best = NULL;
457 double best_swappability = 0;
458 redisDb *best_db = NULL;
459 robj *val;
460 sds key;
461
462 for (j = 0; j < server.dbnum; j++) {
463 redisDb *db = server.db+j;
464 /* Why maxtries is set to 100?
465 * Because this way (usually) we'll find 1 object even if just 1% - 2%
466 * are swappable objects */
467 int maxtries = 100;
468
469 if (dictSize(db->dict) == 0) continue;
470 for (i = 0; i < 5; i++) {
471 dictEntry *de;
472 double swappability;
473
474 if (maxtries) maxtries--;
475 de = dictGetRandomKey(db->dict);
476 val = dictGetEntryVal(de);
477 /* Only swap objects that are currently in memory.
478 *
479 * Also don't swap shared objects: not a good idea in general and
480 * we need to ensure that the main thread does not touch the
481 * object while the I/O thread is using it, but we can't
482 * control other keys without adding additional mutex. */
483 if (val->storage != REDIS_VM_MEMORY || val->refcount != 1) {
484 if (maxtries) i--; /* don't count this try */
485 continue;
486 }
487 swappability = computeObjectSwappability(val);
488 if (!best || swappability > best_swappability) {
489 best = de;
490 best_swappability = swappability;
491 best_db = db;
492 }
493 }
494 }
495 if (best == NULL) return REDIS_ERR;
496 key = dictGetEntryKey(best);
497 val = dictGetEntryVal(best);
498
499 redisLog(REDIS_DEBUG,"Key with best swappability: %s, %f",
500 key, best_swappability);
501
502 /* Swap it */
503 if (usethreads) {
504 robj *keyobj = createStringObject(key,sdslen(key));
505 vmSwapObjectThreaded(keyobj,val,best_db);
506 decrRefCount(keyobj);
507 return REDIS_OK;
508 } else {
509 vmpointer *vp;
510
511 if ((vp = vmSwapObjectBlocking(val)) != NULL) {
512 dictGetEntryVal(best) = vp;
513 return REDIS_OK;
514 } else {
515 return REDIS_ERR;
516 }
517 }
518 }
519
520 int vmSwapOneObjectBlocking() {
521 return vmSwapOneObject(0);
522 }
523
524 int vmSwapOneObjectThreaded() {
525 return vmSwapOneObject(1);
526 }
527
528 /* Return true if it's safe to swap out objects in a given moment.
529 * Basically we don't want to swap objects out while there is a BGSAVE
530 * or a BGAEOREWRITE running in backgroud. */
531 int vmCanSwapOut(void) {
532 return (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1);
533 }
534
535 /* =================== Virtual Memory - Threaded I/O ======================= */
536
537 void freeIOJob(iojob *j) {
538 if ((j->type == REDIS_IOJOB_PREPARE_SWAP ||
539 j->type == REDIS_IOJOB_DO_SWAP ||
540 j->type == REDIS_IOJOB_LOAD) && j->val != NULL)
541 {
542 /* we fix the storage type, otherwise decrRefCount() will try to
543 * kill the I/O thread Job (that does no longer exists). */
544 if (j->val->storage == REDIS_VM_SWAPPING)
545 j->val->storage = REDIS_VM_MEMORY;
546 decrRefCount(j->val);
547 }
548 decrRefCount(j->key);
549 zfree(j);
550 }
551
552 /* Every time a thread finished a Job, it writes a byte into the write side
553 * of an unix pipe in order to "awake" the main thread, and this function
554 * is called.
555 *
556 * Note that this is called both by the event loop, when a I/O thread
557 * sends a byte in the notification pipe, and is also directly called from
558 * waitEmptyIOJobsQueue().
559 *
560 * In the latter case we don't want to swap more, so we use the
561 * "privdata" argument setting it to a not NULL value to signal this
562 * condition. */
563 void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata,
564 int mask)
565 {
566 char buf[1];
567 int retval, processed = 0, toprocess = -1, trytoswap = 1;
568 REDIS_NOTUSED(el);
569 REDIS_NOTUSED(mask);
570 REDIS_NOTUSED(privdata);
571
572 if (privdata != NULL) trytoswap = 0; /* check the comments above... */
573
574 /* For every byte we read in the read side of the pipe, there is one
575 * I/O job completed to process. */
576 while((retval = read(fd,buf,1)) == 1) {
577 iojob *j;
578 listNode *ln;
579 struct dictEntry *de;
580
581 redisLog(REDIS_DEBUG,"Processing I/O completed job");
582
583 /* Get the processed element (the oldest one) */
584 lockThreadedIO();
585 redisAssert(listLength(server.io_processed) != 0);
586 if (toprocess == -1) {
587 toprocess = (listLength(server.io_processed)*REDIS_MAX_COMPLETED_JOBS_PROCESSED)/100;
588 if (toprocess <= 0) toprocess = 1;
589 }
590 ln = listFirst(server.io_processed);
591 j = ln->value;
592 listDelNode(server.io_processed,ln);
593 unlockThreadedIO();
594 /* If this job is marked as canceled, just ignore it */
595 if (j->canceled) {
596 freeIOJob(j);
597 continue;
598 }
599 /* Post process it in the main thread, as there are things we
600 * can do just here to avoid race conditions and/or invasive locks */
601 redisLog(REDIS_DEBUG,"COMPLETED Job type: %d, ID %p, key: %s", j->type, (void*)j->id, (unsigned char*)j->key->ptr);
602 de = dictFind(j->db->dict,j->key->ptr);
603 redisAssert(de != NULL);
604 if (j->type == REDIS_IOJOB_LOAD) {
605 redisDb *db;
606 vmpointer *vp = dictGetEntryVal(de);
607
608 /* Key loaded, bring it at home */
609 vmMarkPagesFree(vp->page,vp->usedpages);
610 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk (threaded)",
611 (unsigned char*) j->key->ptr);
612 server.vm_stats_swapped_objects--;
613 server.vm_stats_swapins++;
614 dictGetEntryVal(de) = j->val;
615 incrRefCount(j->val);
616 db = j->db;
617 /* Handle clients waiting for this key to be loaded. */
618 handleClientsBlockedOnSwappedKey(db,j->key);
619 freeIOJob(j);
620 zfree(vp);
621 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
622 /* Now we know the amount of pages required to swap this object.
623 * Let's find some space for it, and queue this task again
624 * rebranded as REDIS_IOJOB_DO_SWAP. */
625 if (!vmCanSwapOut() ||
626 vmFindContiguousPages(&j->page,j->pages) == REDIS_ERR)
627 {
628 /* Ooops... no space or we can't swap as there is
629 * a fork()ed Redis trying to save stuff on disk. */
630 j->val->storage = REDIS_VM_MEMORY; /* undo operation */
631 freeIOJob(j);
632 } else {
633 /* Note that we need to mark this pages as used now,
634 * if the job will be canceled, we'll mark them as freed
635 * again. */
636 vmMarkPagesUsed(j->page,j->pages);
637 j->type = REDIS_IOJOB_DO_SWAP;
638 lockThreadedIO();
639 queueIOJob(j);
640 unlockThreadedIO();
641 }
642 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
643 vmpointer *vp;
644
645 /* Key swapped. We can finally free some memory. */
646 if (j->val->storage != REDIS_VM_SWAPPING) {
647 vmpointer *vp = (vmpointer*) j->id;
648 printf("storage: %d\n",vp->storage);
649 printf("key->name: %s\n",(char*)j->key->ptr);
650 printf("val: %p\n",(void*)j->val);
651 printf("val->type: %d\n",j->val->type);
652 printf("val->ptr: %s\n",(char*)j->val->ptr);
653 }
654 redisAssert(j->val->storage == REDIS_VM_SWAPPING);
655 vp = createVmPointer(j->val->type);
656 vp->page = j->page;
657 vp->usedpages = j->pages;
658 dictGetEntryVal(de) = vp;
659 /* Fix the storage otherwise decrRefCount will attempt to
660 * remove the associated I/O job */
661 j->val->storage = REDIS_VM_MEMORY;
662 decrRefCount(j->val);
663 redisLog(REDIS_DEBUG,
664 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
665 (unsigned char*) j->key->ptr,
666 (unsigned long long) j->page, (unsigned long long) j->pages);
667 server.vm_stats_swapped_objects++;
668 server.vm_stats_swapouts++;
669 freeIOJob(j);
670 /* Put a few more swap requests in queue if we are still
671 * out of memory */
672 if (trytoswap && vmCanSwapOut() &&
673 zmalloc_used_memory() > server.vm_max_memory)
674 {
675 int more = 1;
676 while(more) {
677 lockThreadedIO();
678 more = listLength(server.io_newjobs) <
679 (unsigned) server.vm_max_threads;
680 unlockThreadedIO();
681 /* Don't waste CPU time if swappable objects are rare. */
682 if (vmSwapOneObjectThreaded() == REDIS_ERR) {
683 trytoswap = 0;
684 break;
685 }
686 }
687 }
688 }
689 processed++;
690 if (processed == toprocess) return;
691 }
692 if (retval < 0 && errno != EAGAIN) {
693 redisLog(REDIS_WARNING,
694 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
695 strerror(errno));
696 }
697 }
698
699 void lockThreadedIO(void) {
700 pthread_mutex_lock(&server.io_mutex);
701 }
702
703 void unlockThreadedIO(void) {
704 pthread_mutex_unlock(&server.io_mutex);
705 }
706
707 /* Remove the specified object from the threaded I/O queue if still not
708 * processed, otherwise make sure to flag it as canceled. */
709 void vmCancelThreadedIOJob(robj *o) {
710 list *lists[3] = {
711 server.io_newjobs, /* 0 */
712 server.io_processing, /* 1 */
713 server.io_processed /* 2 */
714 };
715 int i;
716
717 redisAssert(o->storage == REDIS_VM_LOADING || o->storage == REDIS_VM_SWAPPING);
718 again:
719 lockThreadedIO();
720 /* Search for a matching object in one of the queues */
721 for (i = 0; i < 3; i++) {
722 listNode *ln;
723 listIter li;
724
725 listRewind(lists[i],&li);
726 while ((ln = listNext(&li)) != NULL) {
727 iojob *job = ln->value;
728
729 if (job->canceled) continue; /* Skip this, already canceled. */
730 if (job->id == o) {
731 redisLog(REDIS_DEBUG,"*** CANCELED %p (key %s) (type %d) (LIST ID %d)\n",
732 (void*)job, (char*)job->key->ptr, job->type, i);
733 /* Mark the pages as free since the swap didn't happened
734 * or happened but is now discarded. */
735 if (i != 1 && job->type == REDIS_IOJOB_DO_SWAP)
736 vmMarkPagesFree(job->page,job->pages);
737 /* Cancel the job. It depends on the list the job is
738 * living in. */
739 switch(i) {
740 case 0: /* io_newjobs */
741 /* If the job was yet not processed the best thing to do
742 * is to remove it from the queue at all */
743 freeIOJob(job);
744 listDelNode(lists[i],ln);
745 break;
746 case 1: /* io_processing */
747 /* Oh Shi- the thread is messing with the Job:
748 *
749 * Probably it's accessing the object if this is a
750 * PREPARE_SWAP or DO_SWAP job.
751 * If it's a LOAD job it may be reading from disk and
752 * if we don't wait for the job to terminate before to
753 * cancel it, maybe in a few microseconds data can be
754 * corrupted in this pages. So the short story is:
755 *
756 * Better to wait for the job to move into the
757 * next queue (processed)... */
758
759 /* We try again and again until the job is completed. */
760 unlockThreadedIO();
761 /* But let's wait some time for the I/O thread
762 * to finish with this job. After all this condition
763 * should be very rare. */
764 usleep(1);
765 goto again;
766 case 2: /* io_processed */
767 /* The job was already processed, that's easy...
768 * just mark it as canceled so that we'll ignore it
769 * when processing completed jobs. */
770 job->canceled = 1;
771 break;
772 }
773 /* Finally we have to adjust the storage type of the object
774 * in order to "UNDO" the operaiton. */
775 if (o->storage == REDIS_VM_LOADING)
776 o->storage = REDIS_VM_SWAPPED;
777 else if (o->storage == REDIS_VM_SWAPPING)
778 o->storage = REDIS_VM_MEMORY;
779 unlockThreadedIO();
780 redisLog(REDIS_DEBUG,"*** DONE");
781 return;
782 }
783 }
784 }
785 unlockThreadedIO();
786 printf("Not found: %p\n", (void*)o);
787 redisAssert(1 != 1); /* We should never reach this */
788 }
789
790 void *IOThreadEntryPoint(void *arg) {
791 iojob *j;
792 listNode *ln;
793 REDIS_NOTUSED(arg);
794
795 pthread_detach(pthread_self());
796 while(1) {
797 /* Get a new job to process */
798 lockThreadedIO();
799 if (listLength(server.io_newjobs) == 0) {
800 /* No new jobs in queue, exit. */
801 redisLog(REDIS_DEBUG,"Thread %ld exiting, nothing to do",
802 (long) pthread_self());
803 server.io_active_threads--;
804 unlockThreadedIO();
805 return NULL;
806 }
807 ln = listFirst(server.io_newjobs);
808 j = ln->value;
809 listDelNode(server.io_newjobs,ln);
810 /* Add the job in the processing queue */
811 j->thread = pthread_self();
812 listAddNodeTail(server.io_processing,j);
813 ln = listLast(server.io_processing); /* We use ln later to remove it */
814 unlockThreadedIO();
815 redisLog(REDIS_DEBUG,"Thread %ld got a new job (type %d): %p about key '%s'",
816 (long) pthread_self(), j->type, (void*)j, (char*)j->key->ptr);
817
818 /* Process the Job */
819 if (j->type == REDIS_IOJOB_LOAD) {
820 vmpointer *vp = (vmpointer*)j->id;
821 j->val = vmReadObjectFromSwap(j->page,vp->vtype);
822 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
823 FILE *fp = fopen("/dev/null","w+");
824 j->pages = rdbSavedObjectPages(j->val,fp);
825 fclose(fp);
826 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
827 if (vmWriteObjectOnSwap(j->val,j->page) == REDIS_ERR)
828 j->canceled = 1;
829 }
830
831 /* Done: insert the job into the processed queue */
832 redisLog(REDIS_DEBUG,"Thread %ld completed the job: %p (key %s)",
833 (long) pthread_self(), (void*)j, (char*)j->key->ptr);
834 lockThreadedIO();
835 listDelNode(server.io_processing,ln);
836 listAddNodeTail(server.io_processed,j);
837 unlockThreadedIO();
838
839 /* Signal the main thread there is new stuff to process */
840 redisAssert(write(server.io_ready_pipe_write,"x",1) == 1);
841 }
842 return NULL; /* never reached */
843 }
844
845 void spawnIOThread(void) {
846 pthread_t thread;
847 sigset_t mask, omask;
848 int err;
849
850 sigemptyset(&mask);
851 sigaddset(&mask,SIGCHLD);
852 sigaddset(&mask,SIGHUP);
853 sigaddset(&mask,SIGPIPE);
854 pthread_sigmask(SIG_SETMASK, &mask, &omask);
855 while ((err = pthread_create(&thread,&server.io_threads_attr,IOThreadEntryPoint,NULL)) != 0) {
856 redisLog(REDIS_WARNING,"Unable to spawn an I/O thread: %s",
857 strerror(err));
858 usleep(1000000);
859 }
860 pthread_sigmask(SIG_SETMASK, &omask, NULL);
861 server.io_active_threads++;
862 }
863
864 /* We need to wait for the last thread to exit before we are able to
865 * fork() in order to BGSAVE or BGREWRITEAOF. */
866 void waitEmptyIOJobsQueue(void) {
867 while(1) {
868 int io_processed_len;
869
870 lockThreadedIO();
871 if (listLength(server.io_newjobs) == 0 &&
872 listLength(server.io_processing) == 0 &&
873 server.io_active_threads == 0)
874 {
875 unlockThreadedIO();
876 return;
877 }
878 /* While waiting for empty jobs queue condition we post-process some
879 * finshed job, as I/O threads may be hanging trying to write against
880 * the io_ready_pipe_write FD but there are so much pending jobs that
881 * it's blocking. */
882 io_processed_len = listLength(server.io_processed);
883 unlockThreadedIO();
884 if (io_processed_len) {
885 vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,
886 (void*)0xdeadbeef,0);
887 usleep(1000); /* 1 millisecond */
888 } else {
889 usleep(10000); /* 10 milliseconds */
890 }
891 }
892 }
893
894 void vmReopenSwapFile(void) {
895 /* Note: we don't close the old one as we are in the child process
896 * and don't want to mess at all with the original file object. */
897 server.vm_fp = fopen(server.vm_swap_file,"r+b");
898 if (server.vm_fp == NULL) {
899 redisLog(REDIS_WARNING,"Can't re-open the VM swap file: %s. Exiting.",
900 server.vm_swap_file);
901 _exit(1);
902 }
903 server.vm_fd = fileno(server.vm_fp);
904 }
905
906 /* This function must be called while with threaded IO locked */
907 void queueIOJob(iojob *j) {
908 redisLog(REDIS_DEBUG,"Queued IO Job %p type %d about key '%s'\n",
909 (void*)j, j->type, (char*)j->key->ptr);
910 listAddNodeTail(server.io_newjobs,j);
911 if (server.io_active_threads < server.vm_max_threads)
912 spawnIOThread();
913 }
914
915 int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db) {
916 iojob *j;
917
918 j = zmalloc(sizeof(*j));
919 j->type = REDIS_IOJOB_PREPARE_SWAP;
920 j->db = db;
921 j->key = key;
922 incrRefCount(key);
923 j->id = j->val = val;
924 incrRefCount(val);
925 j->canceled = 0;
926 j->thread = (pthread_t) -1;
927 val->storage = REDIS_VM_SWAPPING;
928
929 lockThreadedIO();
930 queueIOJob(j);
931 unlockThreadedIO();
932 return REDIS_OK;
933 }
934
935 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
936
937 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
938 * If there is not already a job loading the key, it is craeted.
939 * The key is added to the io_keys list in the client structure, and also
940 * in the hash table mapping swapped keys to waiting clients, that is,
941 * server.io_waited_keys. */
942 int waitForSwappedKey(redisClient *c, robj *key) {
943 struct dictEntry *de;
944 robj *o;
945 list *l;
946
947 /* If the key does not exist or is already in RAM we don't need to
948 * block the client at all. */
949 de = dictFind(c->db->dict,key->ptr);
950 if (de == NULL) return 0;
951 o = dictGetEntryVal(de);
952 if (o->storage == REDIS_VM_MEMORY) {
953 return 0;
954 } else if (o->storage == REDIS_VM_SWAPPING) {
955 /* We were swapping the key, undo it! */
956 vmCancelThreadedIOJob(o);
957 return 0;
958 }
959
960 /* OK: the key is either swapped, or being loaded just now. */
961
962 /* Add the key to the list of keys this client is waiting for.
963 * This maps clients to keys they are waiting for. */
964 listAddNodeTail(c->io_keys,key);
965 incrRefCount(key);
966
967 /* Add the client to the swapped keys => clients waiting map. */
968 de = dictFind(c->db->io_keys,key);
969 if (de == NULL) {
970 int retval;
971
972 /* For every key we take a list of clients blocked for it */
973 l = listCreate();
974 retval = dictAdd(c->db->io_keys,key,l);
975 incrRefCount(key);
976 redisAssert(retval == DICT_OK);
977 } else {
978 l = dictGetEntryVal(de);
979 }
980 listAddNodeTail(l,c);
981
982 /* Are we already loading the key from disk? If not create a job */
983 if (o->storage == REDIS_VM_SWAPPED) {
984 iojob *j;
985 vmpointer *vp = (vmpointer*)o;
986
987 o->storage = REDIS_VM_LOADING;
988 j = zmalloc(sizeof(*j));
989 j->type = REDIS_IOJOB_LOAD;
990 j->db = c->db;
991 j->id = (robj*)vp;
992 j->key = key;
993 incrRefCount(key);
994 j->page = vp->page;
995 j->val = NULL;
996 j->canceled = 0;
997 j->thread = (pthread_t) -1;
998 lockThreadedIO();
999 queueIOJob(j);
1000 unlockThreadedIO();
1001 }
1002 return 1;
1003 }
1004
1005 /* Preload keys for any command with first, last and step values for
1006 * the command keys prototype, as defined in the command table. */
1007 void waitForMultipleSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
1008 int j, last;
1009 if (cmd->vm_firstkey == 0) return;
1010 last = cmd->vm_lastkey;
1011 if (last < 0) last = argc+last;
1012 for (j = cmd->vm_firstkey; j <= last; j += cmd->vm_keystep) {
1013 redisAssert(j < argc);
1014 waitForSwappedKey(c,argv[j]);
1015 }
1016 }
1017
1018 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
1019 * Note that the number of keys to preload is user-defined, so we need to
1020 * apply a sanity check against argc. */
1021 void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
1022 int i, num;
1023 REDIS_NOTUSED(cmd);
1024
1025 num = atoi(argv[2]->ptr);
1026 if (num > (argc-3)) return;
1027 for (i = 0; i < num; i++) {
1028 waitForSwappedKey(c,argv[3+i]);
1029 }
1030 }
1031
1032 /* Preload keys needed to execute the entire MULTI/EXEC block.
1033 *
1034 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
1035 * and will block the client when any command requires a swapped out value. */
1036 void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
1037 int i, margc;
1038 struct redisCommand *mcmd;
1039 robj **margv;
1040 REDIS_NOTUSED(cmd);
1041 REDIS_NOTUSED(argc);
1042 REDIS_NOTUSED(argv);
1043
1044 if (!(c->flags & REDIS_MULTI)) return;
1045 for (i = 0; i < c->mstate.count; i++) {
1046 mcmd = c->mstate.commands[i].cmd;
1047 margc = c->mstate.commands[i].argc;
1048 margv = c->mstate.commands[i].argv;
1049
1050 if (mcmd->vm_preload_proc != NULL) {
1051 mcmd->vm_preload_proc(c,mcmd,margc,margv);
1052 } else {
1053 waitForMultipleSwappedKeys(c,mcmd,margc,margv);
1054 }
1055 }
1056 }
1057
1058 /* Is this client attempting to run a command against swapped keys?
1059 * If so, block it ASAP, load the keys in background, then resume it.
1060 *
1061 * The important idea about this function is that it can fail! If keys will
1062 * still be swapped when the client is resumed, this key lookups will
1063 * just block loading keys from disk. In practical terms this should only
1064 * happen with SORT BY command or if there is a bug in this function.
1065 *
1066 * Return 1 if the client is marked as blocked, 0 if the client can
1067 * continue as the keys it is going to access appear to be in memory. */
1068 int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd) {
1069 if (cmd->vm_preload_proc != NULL) {
1070 cmd->vm_preload_proc(c,cmd,c->argc,c->argv);
1071 } else {
1072 waitForMultipleSwappedKeys(c,cmd,c->argc,c->argv);
1073 }
1074
1075 /* If the client was blocked for at least one key, mark it as blocked. */
1076 if (listLength(c->io_keys)) {
1077 c->flags |= REDIS_IO_WAIT;
1078 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
1079 server.vm_blocked_clients++;
1080 return 1;
1081 } else {
1082 return 0;
1083 }
1084 }
1085
1086 /* Remove the 'key' from the list of blocked keys for a given client.
1087 *
1088 * The function returns 1 when there are no longer blocking keys after
1089 * the current one was removed (and the client can be unblocked). */
1090 int dontWaitForSwappedKey(redisClient *c, robj *key) {
1091 list *l;
1092 listNode *ln;
1093 listIter li;
1094 struct dictEntry *de;
1095
1096 /* The key object might be destroyed when deleted from the c->io_keys
1097 * list (and the "key" argument is physically the same object as the
1098 * object inside the list), so we need to protect it. */
1099 incrRefCount(key);
1100
1101 /* Remove the key from the list of keys this client is waiting for. */
1102 listRewind(c->io_keys,&li);
1103 while ((ln = listNext(&li)) != NULL) {
1104 if (equalStringObjects(ln->value,key)) {
1105 listDelNode(c->io_keys,ln);
1106 break;
1107 }
1108 }
1109 redisAssert(ln != NULL);
1110
1111 /* Remove the client form the key => waiting clients map. */
1112 de = dictFind(c->db->io_keys,key);
1113 redisAssert(de != NULL);
1114 l = dictGetEntryVal(de);
1115 ln = listSearchKey(l,c);
1116 redisAssert(ln != NULL);
1117 listDelNode(l,ln);
1118 if (listLength(l) == 0)
1119 dictDelete(c->db->io_keys,key);
1120
1121 decrRefCount(key);
1122 return listLength(c->io_keys) == 0;
1123 }
1124
1125 /* Every time we now a key was loaded back in memory, we handle clients
1126 * waiting for this key if any. */
1127 void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key) {
1128 struct dictEntry *de;
1129 list *l;
1130 listNode *ln;
1131 int len;
1132
1133 de = dictFind(db->io_keys,key);
1134 if (!de) return;
1135
1136 l = dictGetEntryVal(de);
1137 len = listLength(l);
1138 /* Note: we can't use something like while(listLength(l)) as the list
1139 * can be freed by the calling function when we remove the last element. */
1140 while (len--) {
1141 ln = listFirst(l);
1142 redisClient *c = ln->value;
1143
1144 if (dontWaitForSwappedKey(c,key)) {
1145 /* Put the client in the list of clients ready to go as we
1146 * loaded all the keys about it. */
1147 listAddNodeTail(server.io_ready_clients,c);
1148 }
1149 }
1150 }