]> git.saurik.com Git - redis.git/blob - src/dscache.c
6f180b9226f2cec14264c19585caffceaa0f41dd
[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 * NOTE: We disalbe object sharing when server.ds_enabled == 1 so objects
30 * that are referenced an IO job for flushing on disk are marked as
31 * o->storage == REDIS_DS_SAVING.
32 *
33 * - This is what we do on key lookup:
34 * 1) The key already exists in memory. object->storage == REDIS_DS_MEMORY
35 * or it is object->storage == REDIS_DS_DIRTY:
36 * We don't do nothing special, lookup, return value object pointer.
37 * 2) The key is in memory but object->storage == REDIS_DS_SAVING.
38 * When this happens we block waiting for the I/O thread to process
39 * this object. Then continue.
40 * 3) The key is not in memory. We block to load the key from disk.
41 * Of course the key may not be present at all on the disk store as well,
42 * in such case we just detect this condition and continue, returning
43 * NULL from lookup.
44 *
45 * - Preloading of needed keys:
46 * 1) As it was done with VM, also with this new system we try preloading
47 * keys a client is going to use. We block the client, load keys
48 * using the I/O thread, unblock the client. Same code as VM more or less.
49 *
50 * - Reclaiming memory.
51 * In cron() we detect our memory limit was reached. What we
52 * do is deleting keys that are REDIS_DS_MEMORY, using LRU.
53 *
54 * If this is not enough to return again under the memory limits we also
55 * start to flush keys that need to be synched on disk synchronously,
56 * removing it from the memory. We do this blocking as memory limit is a
57 * much "harder" barrirer in the new design.
58 *
59 * - IO thread operations are no longer stopped for sync loading/saving of
60 * things. When a key is found to be in the process of being saved
61 * we simply wait for the IO thread to end its work.
62 *
63 * Otherwise if there is to load a key without any IO thread operation
64 * just started it is blocking-loaded in the lookup function.
65 *
66 * - What happens when an object is destroyed?
67 *
68 * If o->storage == REDIS_DS_MEMORY then we simply destory the object.
69 * If o->storage == REDIS_DS_DIRTY we can still remove the object. It had
70 * changes not flushed on disk, but is being removed so
71 * who cares.
72 * if o->storage == REDIS_DS_SAVING then the object is being saved so
73 * it is impossible that its refcount == 1, must be at
74 * least two. When the object is saved the storage will
75 * be set back to DS_MEMORY.
76 *
77 * - What happens when keys are deleted?
78 *
79 * We simply schedule a key flush operation as usually, but when the
80 * IO thread will be created the object pointer will be set to NULL
81 * so the IO thread will know that the work to do is to delete the key
82 * from the disk store.
83 *
84 * - What happens with MULTI/EXEC?
85 *
86 * Good question.
87 */
88
89 /* Virtual Memory is composed mainly of two subsystems:
90 * - Blocking Virutal Memory
91 * - Threaded Virtual Memory I/O
92 * The two parts are not fully decoupled, but functions are split among two
93 * different sections of the source code (delimited by comments) in order to
94 * make more clear what functionality is about the blocking VM and what about
95 * the threaded (not blocking) VM.
96 *
97 * Redis VM design:
98 *
99 * Redis VM is a blocking VM (one that blocks reading swapped values from
100 * disk into memory when a value swapped out is needed in memory) that is made
101 * unblocking by trying to examine the command argument vector in order to
102 * load in background values that will likely be needed in order to exec
103 * the command. The command is executed only once all the relevant keys
104 * are loaded into memory.
105 *
106 * This basically is almost as simple of a blocking VM, but almost as parallel
107 * as a fully non-blocking VM.
108 */
109
110 /* =================== Virtual Memory - Blocking Side ====================== */
111
112 void vmInit(void) {
113 off_t totsize;
114 int pipefds[2];
115 size_t stacksize;
116 struct flock fl;
117
118 if (server.vm_max_threads != 0)
119 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
120
121 redisLog(REDIS_NOTICE,"Using '%s' as swap file",server.vm_swap_file);
122 /* Try to open the old swap file, otherwise create it */
123 if ((server.vm_fp = fopen(server.vm_swap_file,"r+b")) == NULL) {
124 server.vm_fp = fopen(server.vm_swap_file,"w+b");
125 }
126 if (server.vm_fp == NULL) {
127 redisLog(REDIS_WARNING,
128 "Can't open the swap file: %s. Exiting.",
129 strerror(errno));
130 exit(1);
131 }
132 server.vm_fd = fileno(server.vm_fp);
133 /* Lock the swap file for writing, this is useful in order to avoid
134 * another instance to use the same swap file for a config error. */
135 fl.l_type = F_WRLCK;
136 fl.l_whence = SEEK_SET;
137 fl.l_start = fl.l_len = 0;
138 if (fcntl(server.vm_fd,F_SETLK,&fl) == -1) {
139 redisLog(REDIS_WARNING,
140 "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));
141 exit(1);
142 }
143 /* Initialize */
144 server.vm_next_page = 0;
145 server.vm_near_pages = 0;
146 server.vm_stats_used_pages = 0;
147 server.vm_stats_swapped_objects = 0;
148 server.vm_stats_swapouts = 0;
149 server.vm_stats_swapins = 0;
150 totsize = server.vm_pages*server.vm_page_size;
151 redisLog(REDIS_NOTICE,"Allocating %lld bytes of swap file",totsize);
152 if (ftruncate(server.vm_fd,totsize) == -1) {
153 redisLog(REDIS_WARNING,"Can't ftruncate swap file: %s. Exiting.",
154 strerror(errno));
155 exit(1);
156 } else {
157 redisLog(REDIS_NOTICE,"Swap file allocated with success");
158 }
159 server.vm_bitmap = zcalloc((server.vm_pages+7)/8);
160 redisLog(REDIS_VERBOSE,"Allocated %lld bytes page table for %lld pages",
161 (long long) (server.vm_pages+7)/8, server.vm_pages);
162
163 /* Initialize threaded I/O (used by Virtual Memory) */
164 server.io_newjobs = listCreate();
165 server.io_processing = listCreate();
166 server.io_processed = listCreate();
167 server.io_ready_clients = listCreate();
168 pthread_mutex_init(&server.io_mutex,NULL);
169 pthread_mutex_init(&server.io_swapfile_mutex,NULL);
170 server.io_active_threads = 0;
171 if (pipe(pipefds) == -1) {
172 redisLog(REDIS_WARNING,"Unable to intialized VM: pipe(2): %s. Exiting."
173 ,strerror(errno));
174 exit(1);
175 }
176 server.io_ready_pipe_read = pipefds[0];
177 server.io_ready_pipe_write = pipefds[1];
178 redisAssert(anetNonBlock(NULL,server.io_ready_pipe_read) != ANET_ERR);
179 /* LZF requires a lot of stack */
180 pthread_attr_init(&server.io_threads_attr);
181 pthread_attr_getstacksize(&server.io_threads_attr, &stacksize);
182
183 /* Solaris may report a stacksize of 0, let's set it to 1 otherwise
184 * multiplying it by 2 in the while loop later will not really help ;) */
185 if (!stacksize) stacksize = 1;
186
187 while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2;
188 pthread_attr_setstacksize(&server.io_threads_attr, stacksize);
189 /* Listen for events in the threaded I/O pipe */
190 if (aeCreateFileEvent(server.el, server.io_ready_pipe_read, AE_READABLE,
191 vmThreadedIOCompletedJob, NULL) == AE_ERR)
192 oom("creating file event");
193 }
194
195 /* Write the specified object at the specified page of the swap file */
196 int vmWriteObjectOnSwap(robj *o, off_t page) {
197 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
198 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
199 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
200 redisLog(REDIS_WARNING,
201 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
202 strerror(errno));
203 return REDIS_ERR;
204 }
205 rdbSaveObject(server.vm_fp,o);
206 fflush(server.vm_fp);
207 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
208 return REDIS_OK;
209 }
210
211 /* Transfers the 'val' object to disk. Store all the information
212 * a 'vmpointer' object containing all the information needed to load the
213 * object back later is returned.
214 *
215 * If we can't find enough contiguous empty pages to swap the object on disk
216 * NULL is returned. */
217 vmpointer *vmSwapObjectBlocking(robj *val) {
218 off_t pages = rdbSavedObjectPages(val);
219 off_t page;
220 vmpointer *vp;
221
222 redisAssert(val->storage == REDIS_VM_MEMORY);
223 redisAssert(val->refcount == 1);
224 if (vmFindContiguousPages(&page,pages) == REDIS_ERR) return NULL;
225 if (vmWriteObjectOnSwap(val,page) == REDIS_ERR) return NULL;
226
227 vp = createVmPointer(val->type);
228 vp->page = page;
229 vp->usedpages = pages;
230 decrRefCount(val); /* Deallocate the object from memory. */
231 vmMarkPagesUsed(page,pages);
232 redisLog(REDIS_DEBUG,"VM: object %p swapped out at %lld (%lld pages)",
233 (void*) val,
234 (unsigned long long) page, (unsigned long long) pages);
235 server.vm_stats_swapped_objects++;
236 server.vm_stats_swapouts++;
237 return vp;
238 }
239
240 robj *vmReadObjectFromSwap(off_t page, int type) {
241 robj *o;
242
243 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
244 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
245 redisLog(REDIS_WARNING,
246 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
247 strerror(errno));
248 _exit(1);
249 }
250 o = rdbLoadObject(type,server.vm_fp);
251 if (o == NULL) {
252 redisLog(REDIS_WARNING, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno));
253 _exit(1);
254 }
255 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
256 return o;
257 }
258
259 /* Load the specified object from swap to memory.
260 * The newly allocated object is returned.
261 *
262 * If preview is true the unserialized object is returned to the caller but
263 * the pages are not marked as freed, nor the vp object is freed. */
264 robj *vmGenericLoadObject(vmpointer *vp, int preview) {
265 robj *val;
266
267 redisAssert(vp->type == REDIS_VMPOINTER &&
268 (vp->storage == REDIS_VM_SWAPPED || vp->storage == REDIS_VM_LOADING));
269 val = vmReadObjectFromSwap(vp->page,vp->vtype);
270 if (!preview) {
271 redisLog(REDIS_DEBUG, "VM: object %p loaded from disk", (void*)vp);
272 vmMarkPagesFree(vp->page,vp->usedpages);
273 zfree(vp);
274 server.vm_stats_swapped_objects--;
275 } else {
276 redisLog(REDIS_DEBUG, "VM: object %p previewed from disk", (void*)vp);
277 }
278 server.vm_stats_swapins++;
279 return val;
280 }
281
282 /* Plain object loading, from swap to memory.
283 *
284 * 'o' is actually a redisVmPointer structure that will be freed by the call.
285 * The return value is the loaded object. */
286 robj *vmLoadObject(robj *o) {
287 /* If we are loading the object in background, stop it, we
288 * need to load this object synchronously ASAP. */
289 if (o->storage == REDIS_VM_LOADING)
290 vmCancelThreadedIOJob(o);
291 return vmGenericLoadObject((vmpointer*)o,0);
292 }
293
294 /* Just load the value on disk, without to modify the key.
295 * This is useful when we want to perform some operation on the value
296 * without to really bring it from swap to memory, like while saving the
297 * dataset or rewriting the append only log. */
298 robj *vmPreviewObject(robj *o) {
299 return vmGenericLoadObject((vmpointer*)o,1);
300 }
301
302 /* How a good candidate is this object for swapping?
303 * The better candidate it is, the greater the returned value.
304 *
305 * Currently we try to perform a fast estimation of the object size in
306 * memory, and combine it with aging informations.
307 *
308 * Basically swappability = idle-time * log(estimated size)
309 *
310 * Bigger objects are preferred over smaller objects, but not
311 * proportionally, this is why we use the logarithm. This algorithm is
312 * just a first try and will probably be tuned later. */
313 double computeObjectSwappability(robj *o) {
314 /* actual age can be >= minage, but not < minage. As we use wrapping
315 * 21 bit clocks with minutes resolution for the LRU. */
316 return (double) estimateObjectIdleTime(o);
317 }
318
319 /* Try to swap an object that's a good candidate for swapping.
320 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
321 * to swap any object at all.
322 *
323 * If 'usethreaded' is true, Redis will try to swap the object in background
324 * using I/O threads. */
325 int vmSwapOneObject(int usethreads) {
326 int j, i;
327 struct dictEntry *best = NULL;
328 double best_swappability = 0;
329 redisDb *best_db = NULL;
330 robj *val;
331 sds key;
332
333 for (j = 0; j < server.dbnum; j++) {
334 redisDb *db = server.db+j;
335 /* Why maxtries is set to 100?
336 * Because this way (usually) we'll find 1 object even if just 1% - 2%
337 * are swappable objects */
338 int maxtries = 100;
339
340 if (dictSize(db->dict) == 0) continue;
341 for (i = 0; i < 5; i++) {
342 dictEntry *de;
343 double swappability;
344
345 if (maxtries) maxtries--;
346 de = dictGetRandomKey(db->dict);
347 val = dictGetEntryVal(de);
348 /* Only swap objects that are currently in memory.
349 *
350 * Also don't swap shared objects: not a good idea in general and
351 * we need to ensure that the main thread does not touch the
352 * object while the I/O thread is using it, but we can't
353 * control other keys without adding additional mutex. */
354 if (val->storage != REDIS_VM_MEMORY || val->refcount != 1) {
355 if (maxtries) i--; /* don't count this try */
356 continue;
357 }
358 swappability = computeObjectSwappability(val);
359 if (!best || swappability > best_swappability) {
360 best = de;
361 best_swappability = swappability;
362 best_db = db;
363 }
364 }
365 }
366 if (best == NULL) return REDIS_ERR;
367 key = dictGetEntryKey(best);
368 val = dictGetEntryVal(best);
369
370 redisLog(REDIS_DEBUG,"Key with best swappability: %s, %f",
371 key, best_swappability);
372
373 /* Swap it */
374 if (usethreads) {
375 robj *keyobj = createStringObject(key,sdslen(key));
376 vmSwapObjectThreaded(keyobj,val,best_db);
377 decrRefCount(keyobj);
378 return REDIS_OK;
379 } else {
380 vmpointer *vp;
381
382 if ((vp = vmSwapObjectBlocking(val)) != NULL) {
383 dictGetEntryVal(best) = vp;
384 return REDIS_OK;
385 } else {
386 return REDIS_ERR;
387 }
388 }
389 }
390
391 int vmSwapOneObjectBlocking() {
392 return vmSwapOneObject(0);
393 }
394
395 int vmSwapOneObjectThreaded() {
396 return vmSwapOneObject(1);
397 }
398
399 /* Return true if it's safe to swap out objects in a given moment.
400 * Basically we don't want to swap objects out while there is a BGSAVE
401 * or a BGAEOREWRITE running in backgroud. */
402 int vmCanSwapOut(void) {
403 return (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1);
404 }
405
406 /* =================== Virtual Memory - Threaded I/O ======================= */
407
408 void freeIOJob(iojob *j) {
409 if ((j->type == REDIS_IOJOB_PREPARE_SWAP ||
410 j->type == REDIS_IOJOB_DO_SWAP ||
411 j->type == REDIS_IOJOB_LOAD) && j->val != NULL)
412 {
413 /* we fix the storage type, otherwise decrRefCount() will try to
414 * kill the I/O thread Job (that does no longer exists). */
415 if (j->val->storage == REDIS_VM_SWAPPING)
416 j->val->storage = REDIS_VM_MEMORY;
417 decrRefCount(j->val);
418 }
419 decrRefCount(j->key);
420 zfree(j);
421 }
422
423 /* Every time a thread finished a Job, it writes a byte into the write side
424 * of an unix pipe in order to "awake" the main thread, and this function
425 * is called.
426 *
427 * Note that this is called both by the event loop, when a I/O thread
428 * sends a byte in the notification pipe, and is also directly called from
429 * waitEmptyIOJobsQueue().
430 *
431 * In the latter case we don't want to swap more, so we use the
432 * "privdata" argument setting it to a not NULL value to signal this
433 * condition. */
434 void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata,
435 int mask)
436 {
437 char buf[1];
438 int retval, processed = 0, toprocess = -1, trytoswap = 1;
439 REDIS_NOTUSED(el);
440 REDIS_NOTUSED(mask);
441 REDIS_NOTUSED(privdata);
442
443 if (privdata != NULL) trytoswap = 0; /* check the comments above... */
444
445 /* For every byte we read in the read side of the pipe, there is one
446 * I/O job completed to process. */
447 while((retval = read(fd,buf,1)) == 1) {
448 iojob *j;
449 listNode *ln;
450 struct dictEntry *de;
451
452 redisLog(REDIS_DEBUG,"Processing I/O completed job");
453
454 /* Get the processed element (the oldest one) */
455 lockThreadedIO();
456 redisAssert(listLength(server.io_processed) != 0);
457 if (toprocess == -1) {
458 toprocess = (listLength(server.io_processed)*REDIS_MAX_COMPLETED_JOBS_PROCESSED)/100;
459 if (toprocess <= 0) toprocess = 1;
460 }
461 ln = listFirst(server.io_processed);
462 j = ln->value;
463 listDelNode(server.io_processed,ln);
464 unlockThreadedIO();
465 /* If this job is marked as canceled, just ignore it */
466 if (j->canceled) {
467 freeIOJob(j);
468 continue;
469 }
470 /* Post process it in the main thread, as there are things we
471 * can do just here to avoid race conditions and/or invasive locks */
472 redisLog(REDIS_DEBUG,"COMPLETED Job type: %d, ID %p, key: %s", j->type, (void*)j->id, (unsigned char*)j->key->ptr);
473 de = dictFind(j->db->dict,j->key->ptr);
474 redisAssert(de != NULL);
475 if (j->type == REDIS_IOJOB_LOAD) {
476 redisDb *db;
477 vmpointer *vp = dictGetEntryVal(de);
478
479 /* Key loaded, bring it at home */
480 vmMarkPagesFree(vp->page,vp->usedpages);
481 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk (threaded)",
482 (unsigned char*) j->key->ptr);
483 server.vm_stats_swapped_objects--;
484 server.vm_stats_swapins++;
485 dictGetEntryVal(de) = j->val;
486 incrRefCount(j->val);
487 db = j->db;
488 /* Handle clients waiting for this key to be loaded. */
489 handleClientsBlockedOnSwappedKey(db,j->key);
490 freeIOJob(j);
491 zfree(vp);
492 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
493 /* Now we know the amount of pages required to swap this object.
494 * Let's find some space for it, and queue this task again
495 * rebranded as REDIS_IOJOB_DO_SWAP. */
496 if (!vmCanSwapOut() ||
497 vmFindContiguousPages(&j->page,j->pages) == REDIS_ERR)
498 {
499 /* Ooops... no space or we can't swap as there is
500 * a fork()ed Redis trying to save stuff on disk. */
501 j->val->storage = REDIS_VM_MEMORY; /* undo operation */
502 freeIOJob(j);
503 } else {
504 /* Note that we need to mark this pages as used now,
505 * if the job will be canceled, we'll mark them as freed
506 * again. */
507 vmMarkPagesUsed(j->page,j->pages);
508 j->type = REDIS_IOJOB_DO_SWAP;
509 lockThreadedIO();
510 queueIOJob(j);
511 unlockThreadedIO();
512 }
513 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
514 vmpointer *vp;
515
516 /* Key swapped. We can finally free some memory. */
517 if (j->val->storage != REDIS_VM_SWAPPING) {
518 vmpointer *vp = (vmpointer*) j->id;
519 printf("storage: %d\n",vp->storage);
520 printf("key->name: %s\n",(char*)j->key->ptr);
521 printf("val: %p\n",(void*)j->val);
522 printf("val->type: %d\n",j->val->type);
523 printf("val->ptr: %s\n",(char*)j->val->ptr);
524 }
525 redisAssert(j->val->storage == REDIS_VM_SWAPPING);
526 vp = createVmPointer(j->val->type);
527 vp->page = j->page;
528 vp->usedpages = j->pages;
529 dictGetEntryVal(de) = vp;
530 /* Fix the storage otherwise decrRefCount will attempt to
531 * remove the associated I/O job */
532 j->val->storage = REDIS_VM_MEMORY;
533 decrRefCount(j->val);
534 redisLog(REDIS_DEBUG,
535 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
536 (unsigned char*) j->key->ptr,
537 (unsigned long long) j->page, (unsigned long long) j->pages);
538 server.vm_stats_swapped_objects++;
539 server.vm_stats_swapouts++;
540 freeIOJob(j);
541 /* Put a few more swap requests in queue if we are still
542 * out of memory */
543 if (trytoswap && vmCanSwapOut() &&
544 zmalloc_used_memory() > server.vm_max_memory)
545 {
546 int more = 1;
547 while(more) {
548 lockThreadedIO();
549 more = listLength(server.io_newjobs) <
550 (unsigned) server.vm_max_threads;
551 unlockThreadedIO();
552 /* Don't waste CPU time if swappable objects are rare. */
553 if (vmSwapOneObjectThreaded() == REDIS_ERR) {
554 trytoswap = 0;
555 break;
556 }
557 }
558 }
559 }
560 processed++;
561 if (processed == toprocess) return;
562 }
563 if (retval < 0 && errno != EAGAIN) {
564 redisLog(REDIS_WARNING,
565 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
566 strerror(errno));
567 }
568 }
569
570 void lockThreadedIO(void) {
571 pthread_mutex_lock(&server.io_mutex);
572 }
573
574 void unlockThreadedIO(void) {
575 pthread_mutex_unlock(&server.io_mutex);
576 }
577
578 void *IOThreadEntryPoint(void *arg) {
579 iojob *j;
580 listNode *ln;
581 REDIS_NOTUSED(arg);
582
583 pthread_detach(pthread_self());
584 while(1) {
585 /* Get a new job to process */
586 lockThreadedIO();
587 if (listLength(server.io_newjobs) == 0) {
588 /* No new jobs in queue, exit. */
589 redisLog(REDIS_DEBUG,"Thread %ld exiting, nothing to do",
590 (long) pthread_self());
591 server.io_active_threads--;
592 unlockThreadedIO();
593 return NULL;
594 }
595 ln = listFirst(server.io_newjobs);
596 j = ln->value;
597 listDelNode(server.io_newjobs,ln);
598 /* Add the job in the processing queue */
599 j->thread = pthread_self();
600 listAddNodeTail(server.io_processing,j);
601 ln = listLast(server.io_processing); /* We use ln later to remove it */
602 unlockThreadedIO();
603 redisLog(REDIS_DEBUG,"Thread %ld got a new job (type %d): %p about key '%s'",
604 (long) pthread_self(), j->type, (void*)j, (char*)j->key->ptr);
605
606 /* Process the Job */
607 if (j->type == REDIS_IOJOB_LOAD) {
608 vmpointer *vp = (vmpointer*)j->id;
609 j->val = vmReadObjectFromSwap(j->page,vp->vtype);
610 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
611 j->pages = rdbSavedObjectPages(j->val);
612 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
613 if (vmWriteObjectOnSwap(j->val,j->page) == REDIS_ERR)
614 j->canceled = 1;
615 }
616
617 /* Done: insert the job into the processed queue */
618 redisLog(REDIS_DEBUG,"Thread %ld completed the job: %p (key %s)",
619 (long) pthread_self(), (void*)j, (char*)j->key->ptr);
620 lockThreadedIO();
621 listDelNode(server.io_processing,ln);
622 listAddNodeTail(server.io_processed,j);
623 unlockThreadedIO();
624
625 /* Signal the main thread there is new stuff to process */
626 redisAssert(write(server.io_ready_pipe_write,"x",1) == 1);
627 }
628 return NULL; /* never reached */
629 }
630
631 void spawnIOThread(void) {
632 pthread_t thread;
633 sigset_t mask, omask;
634 int err;
635
636 sigemptyset(&mask);
637 sigaddset(&mask,SIGCHLD);
638 sigaddset(&mask,SIGHUP);
639 sigaddset(&mask,SIGPIPE);
640 pthread_sigmask(SIG_SETMASK, &mask, &omask);
641 while ((err = pthread_create(&thread,&server.io_threads_attr,IOThreadEntryPoint,NULL)) != 0) {
642 redisLog(REDIS_WARNING,"Unable to spawn an I/O thread: %s",
643 strerror(err));
644 usleep(1000000);
645 }
646 pthread_sigmask(SIG_SETMASK, &omask, NULL);
647 server.io_active_threads++;
648 }
649
650 /* We need to wait for the last thread to exit before we are able to
651 * fork() in order to BGSAVE or BGREWRITEAOF. */
652 void waitEmptyIOJobsQueue(void) {
653 while(1) {
654 int io_processed_len;
655
656 lockThreadedIO();
657 if (listLength(server.io_newjobs) == 0 &&
658 listLength(server.io_processing) == 0 &&
659 server.io_active_threads == 0)
660 {
661 unlockThreadedIO();
662 return;
663 }
664 /* While waiting for empty jobs queue condition we post-process some
665 * finshed job, as I/O threads may be hanging trying to write against
666 * the io_ready_pipe_write FD but there are so much pending jobs that
667 * it's blocking. */
668 io_processed_len = listLength(server.io_processed);
669 unlockThreadedIO();
670 if (io_processed_len) {
671 vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,
672 (void*)0xdeadbeef,0);
673 usleep(1000); /* 1 millisecond */
674 } else {
675 usleep(10000); /* 10 milliseconds */
676 }
677 }
678 }
679
680 /* This function must be called while with threaded IO locked */
681 void queueIOJob(iojob *j) {
682 redisLog(REDIS_DEBUG,"Queued IO Job %p type %d about key '%s'\n",
683 (void*)j, j->type, (char*)j->key->ptr);
684 listAddNodeTail(server.io_newjobs,j);
685 if (server.io_active_threads < server.vm_max_threads)
686 spawnIOThread();
687 }
688
689 int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db) {
690 iojob *j;
691
692 j = zmalloc(sizeof(*j));
693 j->type = REDIS_IOJOB_PREPARE_SWAP;
694 j->db = db;
695 j->key = key;
696 incrRefCount(key);
697 j->id = j->val = val;
698 incrRefCount(val);
699 j->canceled = 0;
700 j->thread = (pthread_t) -1;
701 val->storage = REDIS_VM_SWAPPING;
702
703 lockThreadedIO();
704 queueIOJob(j);
705 unlockThreadedIO();
706 return REDIS_OK;
707 }
708
709 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
710
711 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
712 * If there is not already a job loading the key, it is craeted.
713 * The key is added to the io_keys list in the client structure, and also
714 * in the hash table mapping swapped keys to waiting clients, that is,
715 * server.io_waited_keys. */
716 int waitForSwappedKey(redisClient *c, robj *key) {
717 struct dictEntry *de;
718 robj *o;
719 list *l;
720
721 /* If the key does not exist or is already in RAM we don't need to
722 * block the client at all. */
723 de = dictFind(c->db->dict,key->ptr);
724 if (de == NULL) return 0;
725 o = dictGetEntryVal(de);
726 if (o->storage == REDIS_VM_MEMORY) {
727 return 0;
728 } else if (o->storage == REDIS_VM_SWAPPING) {
729 /* We were swapping the key, undo it! */
730 vmCancelThreadedIOJob(o);
731 return 0;
732 }
733
734 /* OK: the key is either swapped, or being loaded just now. */
735
736 /* Add the key to the list of keys this client is waiting for.
737 * This maps clients to keys they are waiting for. */
738 listAddNodeTail(c->io_keys,key);
739 incrRefCount(key);
740
741 /* Add the client to the swapped keys => clients waiting map. */
742 de = dictFind(c->db->io_keys,key);
743 if (de == NULL) {
744 int retval;
745
746 /* For every key we take a list of clients blocked for it */
747 l = listCreate();
748 retval = dictAdd(c->db->io_keys,key,l);
749 incrRefCount(key);
750 redisAssert(retval == DICT_OK);
751 } else {
752 l = dictGetEntryVal(de);
753 }
754 listAddNodeTail(l,c);
755
756 /* Are we already loading the key from disk? If not create a job */
757 if (o->storage == REDIS_VM_SWAPPED) {
758 iojob *j;
759 vmpointer *vp = (vmpointer*)o;
760
761 o->storage = REDIS_VM_LOADING;
762 j = zmalloc(sizeof(*j));
763 j->type = REDIS_IOJOB_LOAD;
764 j->db = c->db;
765 j->id = (robj*)vp;
766 j->key = key;
767 incrRefCount(key);
768 j->page = vp->page;
769 j->val = NULL;
770 j->canceled = 0;
771 j->thread = (pthread_t) -1;
772 lockThreadedIO();
773 queueIOJob(j);
774 unlockThreadedIO();
775 }
776 return 1;
777 }
778
779 /* Preload keys for any command with first, last and step values for
780 * the command keys prototype, as defined in the command table. */
781 void waitForMultipleSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
782 int j, last;
783 if (cmd->vm_firstkey == 0) return;
784 last = cmd->vm_lastkey;
785 if (last < 0) last = argc+last;
786 for (j = cmd->vm_firstkey; j <= last; j += cmd->vm_keystep) {
787 redisAssert(j < argc);
788 waitForSwappedKey(c,argv[j]);
789 }
790 }
791
792 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
793 * Note that the number of keys to preload is user-defined, so we need to
794 * apply a sanity check against argc. */
795 void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
796 int i, num;
797 REDIS_NOTUSED(cmd);
798
799 num = atoi(argv[2]->ptr);
800 if (num > (argc-3)) return;
801 for (i = 0; i < num; i++) {
802 waitForSwappedKey(c,argv[3+i]);
803 }
804 }
805
806 /* Preload keys needed to execute the entire MULTI/EXEC block.
807 *
808 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
809 * and will block the client when any command requires a swapped out value. */
810 void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
811 int i, margc;
812 struct redisCommand *mcmd;
813 robj **margv;
814 REDIS_NOTUSED(cmd);
815 REDIS_NOTUSED(argc);
816 REDIS_NOTUSED(argv);
817
818 if (!(c->flags & REDIS_MULTI)) return;
819 for (i = 0; i < c->mstate.count; i++) {
820 mcmd = c->mstate.commands[i].cmd;
821 margc = c->mstate.commands[i].argc;
822 margv = c->mstate.commands[i].argv;
823
824 if (mcmd->vm_preload_proc != NULL) {
825 mcmd->vm_preload_proc(c,mcmd,margc,margv);
826 } else {
827 waitForMultipleSwappedKeys(c,mcmd,margc,margv);
828 }
829 }
830 }
831
832 /* Is this client attempting to run a command against swapped keys?
833 * If so, block it ASAP, load the keys in background, then resume it.
834 *
835 * The important idea about this function is that it can fail! If keys will
836 * still be swapped when the client is resumed, this key lookups will
837 * just block loading keys from disk. In practical terms this should only
838 * happen with SORT BY command or if there is a bug in this function.
839 *
840 * Return 1 if the client is marked as blocked, 0 if the client can
841 * continue as the keys it is going to access appear to be in memory. */
842 int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd) {
843 if (cmd->vm_preload_proc != NULL) {
844 cmd->vm_preload_proc(c,cmd,c->argc,c->argv);
845 } else {
846 waitForMultipleSwappedKeys(c,cmd,c->argc,c->argv);
847 }
848
849 /* If the client was blocked for at least one key, mark it as blocked. */
850 if (listLength(c->io_keys)) {
851 c->flags |= REDIS_IO_WAIT;
852 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
853 server.vm_blocked_clients++;
854 return 1;
855 } else {
856 return 0;
857 }
858 }
859
860 /* Remove the 'key' from the list of blocked keys for a given client.
861 *
862 * The function returns 1 when there are no longer blocking keys after
863 * the current one was removed (and the client can be unblocked). */
864 int dontWaitForSwappedKey(redisClient *c, robj *key) {
865 list *l;
866 listNode *ln;
867 listIter li;
868 struct dictEntry *de;
869
870 /* The key object might be destroyed when deleted from the c->io_keys
871 * list (and the "key" argument is physically the same object as the
872 * object inside the list), so we need to protect it. */
873 incrRefCount(key);
874
875 /* Remove the key from the list of keys this client is waiting for. */
876 listRewind(c->io_keys,&li);
877 while ((ln = listNext(&li)) != NULL) {
878 if (equalStringObjects(ln->value,key)) {
879 listDelNode(c->io_keys,ln);
880 break;
881 }
882 }
883 redisAssert(ln != NULL);
884
885 /* Remove the client form the key => waiting clients map. */
886 de = dictFind(c->db->io_keys,key);
887 redisAssert(de != NULL);
888 l = dictGetEntryVal(de);
889 ln = listSearchKey(l,c);
890 redisAssert(ln != NULL);
891 listDelNode(l,ln);
892 if (listLength(l) == 0)
893 dictDelete(c->db->io_keys,key);
894
895 decrRefCount(key);
896 return listLength(c->io_keys) == 0;
897 }
898
899 /* Every time we now a key was loaded back in memory, we handle clients
900 * waiting for this key if any. */
901 void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key) {
902 struct dictEntry *de;
903 list *l;
904 listNode *ln;
905 int len;
906
907 de = dictFind(db->io_keys,key);
908 if (!de) return;
909
910 l = dictGetEntryVal(de);
911 len = listLength(l);
912 /* Note: we can't use something like while(listLength(l)) as the list
913 * can be freed by the calling function when we remove the last element. */
914 while (len--) {
915 ln = listFirst(l);
916 redisClient *c = ln->value;
917
918 if (dontWaitForSwappedKey(c,key)) {
919 /* Put the client in the list of clients ready to go as we
920 * loaded all the keys about it. */
921 listAddNodeTail(server.io_ready_clients,c);
922 }
923 }
924 }