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