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