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