]> git.saurik.com Git - redis.git/blob - src/dscache.c
major bug and a dead lock fixed
[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 * - If dsSet() fails on the write thread log the error and reschedule the
89 * key for flush.
90 *
91 * - Check why INCR will not update the LRU info for the object.
92 *
93 * - Fix/Check the following race condition: a key gets a DEL so there is
94 * a write operation scheduled against this key. Later the same key will
95 * be the argument of a GET, but the write operation was still not
96 * completed (to delete the file). If the GET will be for some reason
97 * a blocking loading (via lookup) we can load the old value on memory.
98 *
99 * This problems can be fixed with negative caching. We can use it
100 * to optimize the system, but also when a key is deleted we mark
101 * it as non existing on disk as well (in a way that this cache
102 * entry can't be evicted, setting time to 0), then we avoid looking at
103 * the disk at all if the key can't be there. When an IO Job complete
104 * a deletion, we set the time of the negative caching to a non zero
105 * value so it will be evicted later.
106 *
107 * Are there other patterns like this where we load stale data?
108 */
109
110 /* Virtual Memory is composed mainly of two subsystems:
111 * - Blocking Virutal Memory
112 * - Threaded Virtual Memory I/O
113 * The two parts are not fully decoupled, but functions are split among two
114 * different sections of the source code (delimited by comments) in order to
115 * make more clear what functionality is about the blocking VM and what about
116 * the threaded (not blocking) VM.
117 *
118 * Redis VM design:
119 *
120 * Redis VM is a blocking VM (one that blocks reading swapped values from
121 * disk into memory when a value swapped out is needed in memory) that is made
122 * unblocking by trying to examine the command argument vector in order to
123 * load in background values that will likely be needed in order to exec
124 * the command. The command is executed only once all the relevant keys
125 * are loaded into memory.
126 *
127 * This basically is almost as simple of a blocking VM, but almost as parallel
128 * as a fully non-blocking VM.
129 */
130
131 void spawnIOThread(void);
132
133 /* =================== Virtual Memory - Blocking Side ====================== */
134
135 void dsInit(void) {
136 int pipefds[2];
137 size_t stacksize;
138
139 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
140
141 redisLog(REDIS_NOTICE,"Opening Disk Store: %s", server.ds_path);
142 /* Open Disk Store */
143 if (dsOpen() != REDIS_OK) {
144 redisLog(REDIS_WARNING,"Fatal error opening disk store. Exiting.");
145 exit(1);
146 };
147
148 /* Initialize threaded I/O for Object Cache */
149 server.io_newjobs = listCreate();
150 server.io_processing = listCreate();
151 server.io_processed = listCreate();
152 server.io_ready_clients = listCreate();
153 pthread_mutex_init(&server.io_mutex,NULL);
154 pthread_cond_init(&server.io_condvar,NULL);
155 server.io_active_threads = 0;
156 if (pipe(pipefds) == -1) {
157 redisLog(REDIS_WARNING,"Unable to intialized DS: pipe(2): %s. Exiting."
158 ,strerror(errno));
159 exit(1);
160 }
161 server.io_ready_pipe_read = pipefds[0];
162 server.io_ready_pipe_write = pipefds[1];
163 redisAssert(anetNonBlock(NULL,server.io_ready_pipe_read) != ANET_ERR);
164 /* LZF requires a lot of stack */
165 pthread_attr_init(&server.io_threads_attr);
166 pthread_attr_getstacksize(&server.io_threads_attr, &stacksize);
167
168 /* Solaris may report a stacksize of 0, let's set it to 1 otherwise
169 * multiplying it by 2 in the while loop later will not really help ;) */
170 if (!stacksize) stacksize = 1;
171
172 while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2;
173 pthread_attr_setstacksize(&server.io_threads_attr, stacksize);
174 /* Listen for events in the threaded I/O pipe */
175 if (aeCreateFileEvent(server.el, server.io_ready_pipe_read, AE_READABLE,
176 vmThreadedIOCompletedJob, NULL) == AE_ERR)
177 oom("creating file event");
178
179 /* Spawn our I/O thread */
180 spawnIOThread();
181 }
182
183 /* Compute how good candidate the specified object is for eviction.
184 * An higher number means a better candidate. */
185 double computeObjectSwappability(robj *o) {
186 /* actual age can be >= minage, but not < minage. As we use wrapping
187 * 21 bit clocks with minutes resolution for the LRU. */
188 return (double) estimateObjectIdleTime(o);
189 }
190
191 /* Try to free one entry from the diskstore object cache */
192 int cacheFreeOneEntry(void) {
193 int j, i;
194 struct dictEntry *best = NULL;
195 double best_swappability = 0;
196 redisDb *best_db = NULL;
197 robj *val;
198 sds key;
199
200 for (j = 0; j < server.dbnum; j++) {
201 redisDb *db = server.db+j;
202 /* Why maxtries is set to 100?
203 * Because this way (usually) we'll find 1 object even if just 1% - 2%
204 * are swappable objects */
205 int maxtries = 100;
206
207 if (dictSize(db->dict) == 0) continue;
208 for (i = 0; i < 5; i++) {
209 dictEntry *de;
210 double swappability;
211
212 if (maxtries) maxtries--;
213 de = dictGetRandomKey(db->dict);
214 val = dictGetEntryVal(de);
215 /* Only swap objects that are currently in memory.
216 *
217 * Also don't swap shared objects: not a good idea in general and
218 * we need to ensure that the main thread does not touch the
219 * object while the I/O thread is using it, but we can't
220 * control other keys without adding additional mutex. */
221 if (val->storage != REDIS_DS_MEMORY) {
222 if (maxtries) i--; /* don't count this try */
223 continue;
224 }
225 swappability = computeObjectSwappability(val);
226 if (!best || swappability > best_swappability) {
227 best = de;
228 best_swappability = swappability;
229 best_db = db;
230 }
231 }
232 }
233 if (best == NULL) {
234 /* FIXME: If there are objects marked as DS_DIRTY or DS_SAVING
235 * let's wait for this objects to be clear and retry...
236 *
237 * Object cache vm limit is considered an hard limit. */
238 return REDIS_ERR;
239 }
240 key = dictGetEntryKey(best);
241 val = dictGetEntryVal(best);
242
243 redisLog(REDIS_DEBUG,"Key selected for cache eviction: %s swappability:%f",
244 key, best_swappability);
245
246 /* Delete this key from memory */
247 {
248 robj *kobj = createStringObject(key,sdslen(key));
249 dbDelete(best_db,kobj);
250 decrRefCount(kobj);
251 }
252 return REDIS_OK;
253 }
254
255 /* Return true if it's safe to swap out objects in a given moment.
256 * Basically we don't want to swap objects out while there is a BGSAVE
257 * or a BGAEOREWRITE running in backgroud. */
258 int dsCanTouchDiskStore(void) {
259 return (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1);
260 }
261
262 /* =================== Virtual Memory - Threaded I/O ======================= */
263
264 void freeIOJob(iojob *j) {
265 decrRefCount(j->key);
266 /* j->val can be NULL if the job is about deleting the key from disk. */
267 if (j->val) decrRefCount(j->val);
268 zfree(j);
269 }
270
271 /* Every time a thread finished a Job, it writes a byte into the write side
272 * of an unix pipe in order to "awake" the main thread, and this function
273 * is called. */
274 void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata,
275 int mask)
276 {
277 char buf[1];
278 int retval, processed = 0, toprocess = -1;
279 REDIS_NOTUSED(el);
280 REDIS_NOTUSED(mask);
281 REDIS_NOTUSED(privdata);
282
283 /* For every byte we read in the read side of the pipe, there is one
284 * I/O job completed to process. */
285 while((retval = read(fd,buf,1)) == 1) {
286 iojob *j;
287 listNode *ln;
288
289 redisLog(REDIS_DEBUG,"Processing I/O completed job");
290
291 /* Get the processed element (the oldest one) */
292 lockThreadedIO();
293 redisAssert(listLength(server.io_processed) != 0);
294 if (toprocess == -1) {
295 toprocess = (listLength(server.io_processed)*REDIS_MAX_COMPLETED_JOBS_PROCESSED)/100;
296 if (toprocess <= 0) toprocess = 1;
297 }
298 ln = listFirst(server.io_processed);
299 j = ln->value;
300 listDelNode(server.io_processed,ln);
301 unlockThreadedIO();
302
303 /* Post process it in the main thread, as there are things we
304 * can do just here to avoid race conditions and/or invasive locks */
305 redisLog(REDIS_DEBUG,"COMPLETED Job type %s, key: %s",
306 (j->type == REDIS_IOJOB_LOAD) ? "load" : "save",
307 (unsigned char*)j->key->ptr);
308 if (j->type == REDIS_IOJOB_LOAD) {
309 /* Create the key-value pair in the in-memory database */
310 if (j->val != NULL) {
311 /* Note: the key may already be here if between the time
312 * this key loading was scheduled and now there was the
313 * need to blocking load the key for a key lookup. */
314 if (dbAdd(j->db,j->key,j->val) == REDIS_OK) {
315 incrRefCount(j->val);
316 if (j->expire != -1) setExpire(j->db,j->key,j->expire);
317 }
318 } else {
319 /* The key does not exist. Create a negative cache entry
320 * for this key. */
321 /* FIXME: add this entry into the negative cache */
322 }
323 /* Handle clients waiting for this key to be loaded. */
324 handleClientsBlockedOnSwappedKey(j->db,j->key);
325 freeIOJob(j);
326 } else if (j->type == REDIS_IOJOB_SAVE) {
327 if (j->val) {
328 redisAssert(j->val->storage == REDIS_DS_SAVING);
329 j->val->storage = REDIS_DS_MEMORY;
330 }
331 freeIOJob(j);
332 }
333 processed++;
334 if (processed == toprocess) return;
335 }
336 if (retval < 0 && errno != EAGAIN) {
337 redisLog(REDIS_WARNING,
338 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
339 strerror(errno));
340 }
341 }
342
343 void lockThreadedIO(void) {
344 pthread_mutex_lock(&server.io_mutex);
345 }
346
347 void unlockThreadedIO(void) {
348 pthread_mutex_unlock(&server.io_mutex);
349 }
350
351 void *IOThreadEntryPoint(void *arg) {
352 iojob *j;
353 listNode *ln;
354 REDIS_NOTUSED(arg);
355
356 pthread_detach(pthread_self());
357 lockThreadedIO();
358 while(1) {
359 /* Get a new job to process */
360 if (listLength(server.io_newjobs) == 0) {
361 /* Wait for more work to do */
362 pthread_cond_wait(&server.io_condvar,&server.io_mutex);
363 continue;
364 }
365 ln = listFirst(server.io_newjobs);
366 j = ln->value;
367 listDelNode(server.io_newjobs,ln);
368 /* Add the job in the processing queue */
369 listAddNodeTail(server.io_processing,j);
370 ln = listLast(server.io_processing); /* We use ln later to remove it */
371 unlockThreadedIO();
372
373 redisLog(REDIS_DEBUG,"Thread %ld: new job type %s: %p about key '%s'",
374 (long) pthread_self(),
375 (j->type == REDIS_IOJOB_LOAD) ? "load" : "save",
376 (void*)j, (char*)j->key->ptr);
377
378 /* Process the Job */
379 if (j->type == REDIS_IOJOB_LOAD) {
380 time_t expire;
381
382 j->val = dsGet(j->db,j->key,&expire);
383 if (j->val) j->expire = expire;
384 } else if (j->type == REDIS_IOJOB_SAVE) {
385 if (j->val) {
386 redisAssert(j->val->storage == REDIS_DS_SAVING);
387 dsSet(j->db,j->key,j->val);
388 } else {
389 dsDel(j->db,j->key);
390 }
391 }
392
393 /* Done: insert the job into the processed queue */
394 redisLog(REDIS_DEBUG,"Thread %ld completed the job: %p (key %s)",
395 (long) pthread_self(), (void*)j, (char*)j->key->ptr);
396
397 lockThreadedIO();
398 listDelNode(server.io_processing,ln);
399 listAddNodeTail(server.io_processed,j);
400
401 /* Signal the main thread there is new stuff to process */
402 redisAssert(write(server.io_ready_pipe_write,"x",1) == 1);
403 }
404 /* never reached, but that's the full pattern... */
405 unlockThreadedIO();
406 return NULL;
407 }
408
409 void spawnIOThread(void) {
410 pthread_t thread;
411 sigset_t mask, omask;
412 int err;
413
414 sigemptyset(&mask);
415 sigaddset(&mask,SIGCHLD);
416 sigaddset(&mask,SIGHUP);
417 sigaddset(&mask,SIGPIPE);
418 pthread_sigmask(SIG_SETMASK, &mask, &omask);
419 while ((err = pthread_create(&thread,&server.io_threads_attr,IOThreadEntryPoint,NULL)) != 0) {
420 redisLog(REDIS_WARNING,"Unable to spawn an I/O thread: %s",
421 strerror(err));
422 usleep(1000000);
423 }
424 pthread_sigmask(SIG_SETMASK, &omask, NULL);
425 server.io_active_threads++;
426 }
427
428 /* Wait that all the pending IO Jobs are processed */
429 void waitEmptyIOJobsQueue(void) {
430 while(1) {
431 int io_processed_len;
432
433 lockThreadedIO();
434 if (listLength(server.io_newjobs) == 0 &&
435 listLength(server.io_processing) == 0)
436 {
437 unlockThreadedIO();
438 return;
439 }
440 /* If there are new jobs we need to signal the thread to
441 * process the next one. */
442 redisLog(REDIS_DEBUG,"waitEmptyIOJobsQueue: new %d, processing %d",
443 listLength(server.io_newjobs),
444 listLength(server.io_processing));
445 /*
446 if (listLength(server.io_newjobs)) {
447 pthread_cond_signal(&server.io_condvar);
448 }
449 */
450 /* While waiting for empty jobs queue condition we post-process some
451 * finshed job, as I/O threads may be hanging trying to write against
452 * the io_ready_pipe_write FD but there are so much pending jobs that
453 * it's blocking. */
454 io_processed_len = listLength(server.io_processed);
455 unlockThreadedIO();
456 if (io_processed_len) {
457 vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,
458 (void*)0xdeadbeef,0);
459 usleep(1000); /* 1 millisecond */
460 } else {
461 usleep(10000); /* 10 milliseconds */
462 }
463 }
464 }
465
466 /* Process all the IO Jobs already completed by threads but still waiting
467 * processing from the main thread. */
468 void processAllPendingIOJobs(void) {
469 while(1) {
470 int io_processed_len;
471
472 lockThreadedIO();
473 io_processed_len = listLength(server.io_processed);
474 unlockThreadedIO();
475 if (io_processed_len == 0) return;
476 vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,
477 (void*)0xdeadbeef,0);
478 }
479 }
480
481 /* This function must be called while with threaded IO locked */
482 void queueIOJob(iojob *j) {
483 redisLog(REDIS_DEBUG,"Queued IO Job %p type %d about key '%s'\n",
484 (void*)j, j->type, (char*)j->key->ptr);
485 listAddNodeTail(server.io_newjobs,j);
486 if (server.io_active_threads < server.vm_max_threads)
487 spawnIOThread();
488 }
489
490 void dsCreateIOJob(int type, redisDb *db, robj *key, robj *val) {
491 iojob *j;
492
493 j = zmalloc(sizeof(*j));
494 j->type = type;
495 j->db = db;
496 j->key = key;
497 incrRefCount(key);
498 j->val = val;
499 if (val) incrRefCount(val);
500
501 lockThreadedIO();
502 queueIOJob(j);
503 pthread_cond_signal(&server.io_condvar);
504 unlockThreadedIO();
505 }
506
507 void cacheScheduleForFlush(redisDb *db, robj *key) {
508 dirtykey *dk;
509 dictEntry *de;
510
511 de = dictFind(db->dict,key->ptr);
512 if (de) {
513 robj *val = dictGetEntryVal(de);
514 if (val->storage == REDIS_DS_DIRTY)
515 return;
516 else
517 val->storage = REDIS_DS_DIRTY;
518 }
519
520 redisLog(REDIS_DEBUG,"Scheduling key %s for saving (%s)",key->ptr,
521 de ? "key exists" : "key does not exist");
522 dk = zmalloc(sizeof(*dk));
523 dk->db = db;
524 dk->key = key;
525 incrRefCount(key);
526 dk->ctime = time(NULL);
527 listAddNodeTail(server.cache_flush_queue, dk);
528 }
529
530 void cacheCron(void) {
531 time_t now = time(NULL);
532 listNode *ln;
533
534 /* Sync stuff on disk */
535 while((ln = listFirst(server.cache_flush_queue)) != NULL) {
536 dirtykey *dk = ln->value;
537
538 if ((now - dk->ctime) >= server.cache_flush_delay) {
539 struct dictEntry *de;
540 robj *val;
541
542 redisLog(REDIS_DEBUG,"Creating IO Job to save key %s",dk->key->ptr);
543
544 /* Lookup the key, in order to put the current value in the IO
545 * Job and mark it as DS_SAVING.
546 * Otherwise if the key does not exists we schedule a disk store
547 * delete operation, setting the value to NULL. */
548 de = dictFind(dk->db->dict,dk->key->ptr);
549 if (de) {
550 val = dictGetEntryVal(de);
551 redisAssert(val->storage == REDIS_DS_DIRTY);
552 val->storage = REDIS_DS_SAVING;
553 } else {
554 /* Setting the value to NULL tells the IO thread to delete
555 * the key on disk. */
556 val = NULL;
557 }
558 dsCreateIOJob(REDIS_IOJOB_SAVE,dk->db,dk->key,val);
559 listDelNode(server.cache_flush_queue,ln);
560 decrRefCount(dk->key);
561 zfree(dk);
562 } else {
563 break; /* too early */
564 }
565 }
566
567 /* Reclaim memory from the object cache */
568 while (server.ds_enabled && zmalloc_used_memory() >
569 server.cache_max_memory)
570 {
571 if (cacheFreeOneEntry() == REDIS_ERR) break;
572 }
573 }
574
575 /* ============ Negative caching for diskstore objects ====================== */
576 /* Since accesses to keys that don't exist with disk store cost us a disk
577 * access, we need to cache names of keys that do not exist but are frequently
578 * accessed. */
579 int cacheKeyMayExist(redisDb *db, robj *key) {
580 /* FIXME: for now we just always return true. */
581 return 1;
582 }
583
584 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
585
586 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
587 * If the key is already in memory we don't need to block, regardless
588 * of the storage of the value object for this key:
589 *
590 * - If it's REDIS_DS_MEMORY we have the key in memory.
591 * - If it's REDIS_DS_DIRTY they key was modified, but still in memory.
592 * - if it's REDIS_DS_SAVING the key is being saved by an IO Job. When
593 * the client will lookup the key it will block if the key is still
594 * in this stage but it's more or less the best we can do.
595 *
596 * FIXME: we should try if it's actually better to suspend the client
597 * accessing an object that is being saved, and awake it only when
598 * the saving was completed.
599 *
600 * Otherwise if the key is not in memory, we block the client and start
601 * an IO Job to load it:
602 *
603 * the key is added to the io_keys list in the client structure, and also
604 * in the hash table mapping swapped keys to waiting clients, that is,
605 * server.io_waited_keys. */
606 int waitForSwappedKey(redisClient *c, robj *key) {
607 struct dictEntry *de;
608 list *l;
609
610 /* Return ASAP if the key is in memory */
611 de = dictFind(c->db->dict,key->ptr);
612 if (de != NULL) return 0;
613
614 /* Add the key to the list of keys this client is waiting for.
615 * This maps clients to keys they are waiting for. */
616 listAddNodeTail(c->io_keys,key);
617 incrRefCount(key);
618
619 /* Add the client to the swapped keys => clients waiting map. */
620 de = dictFind(c->db->io_keys,key);
621 if (de == NULL) {
622 int retval;
623
624 /* For every key we take a list of clients blocked for it */
625 l = listCreate();
626 retval = dictAdd(c->db->io_keys,key,l);
627 incrRefCount(key);
628 redisAssert(retval == DICT_OK);
629 } else {
630 l = dictGetEntryVal(de);
631 }
632 listAddNodeTail(l,c);
633
634 /* Are we already loading the key from disk? If not create a job */
635 /* FIXME: if a given client was blocked for this key (so job already
636 * created) but the client was freed, there may be a job loading this
637 * key even if de == NULL. Does this creates some race condition?
638 *
639 * Example: after the first load the key gets a DEL that will schedule
640 * a write. But the write will happen later, the duplicated load will
641 * fire and we'll get again the key in memory. */
642 if (de == NULL)
643 dsCreateIOJob(REDIS_IOJOB_LOAD,c->db,key,NULL);
644 return 1;
645 }
646
647 /* Preload keys for any command with first, last and step values for
648 * the command keys prototype, as defined in the command table. */
649 void waitForMultipleSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
650 int j, last;
651 if (cmd->vm_firstkey == 0) return;
652 last = cmd->vm_lastkey;
653 if (last < 0) last = argc+last;
654 for (j = cmd->vm_firstkey; j <= last; j += cmd->vm_keystep) {
655 redisAssert(j < argc);
656 waitForSwappedKey(c,argv[j]);
657 }
658 }
659
660 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
661 * Note that the number of keys to preload is user-defined, so we need to
662 * apply a sanity check against argc. */
663 void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
664 int i, num;
665 REDIS_NOTUSED(cmd);
666
667 num = atoi(argv[2]->ptr);
668 if (num > (argc-3)) return;
669 for (i = 0; i < num; i++) {
670 waitForSwappedKey(c,argv[3+i]);
671 }
672 }
673
674 /* Preload keys needed to execute the entire MULTI/EXEC block.
675 *
676 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
677 * and will block the client when any command requires a swapped out value. */
678 void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
679 int i, margc;
680 struct redisCommand *mcmd;
681 robj **margv;
682 REDIS_NOTUSED(cmd);
683 REDIS_NOTUSED(argc);
684 REDIS_NOTUSED(argv);
685
686 if (!(c->flags & REDIS_MULTI)) return;
687 for (i = 0; i < c->mstate.count; i++) {
688 mcmd = c->mstate.commands[i].cmd;
689 margc = c->mstate.commands[i].argc;
690 margv = c->mstate.commands[i].argv;
691
692 if (mcmd->vm_preload_proc != NULL) {
693 mcmd->vm_preload_proc(c,mcmd,margc,margv);
694 } else {
695 waitForMultipleSwappedKeys(c,mcmd,margc,margv);
696 }
697 }
698 }
699
700 /* Is this client attempting to run a command against swapped keys?
701 * If so, block it ASAP, load the keys in background, then resume it.
702 *
703 * The important idea about this function is that it can fail! If keys will
704 * still be swapped when the client is resumed, this key lookups will
705 * just block loading keys from disk. In practical terms this should only
706 * happen with SORT BY command or if there is a bug in this function.
707 *
708 * Return 1 if the client is marked as blocked, 0 if the client can
709 * continue as the keys it is going to access appear to be in memory. */
710 int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd) {
711 if (cmd->vm_preload_proc != NULL) {
712 cmd->vm_preload_proc(c,cmd,c->argc,c->argv);
713 } else {
714 waitForMultipleSwappedKeys(c,cmd,c->argc,c->argv);
715 }
716
717 /* If the client was blocked for at least one key, mark it as blocked. */
718 if (listLength(c->io_keys)) {
719 c->flags |= REDIS_IO_WAIT;
720 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
721 server.cache_blocked_clients++;
722 return 1;
723 } else {
724 return 0;
725 }
726 }
727
728 /* Remove the 'key' from the list of blocked keys for a given client.
729 *
730 * The function returns 1 when there are no longer blocking keys after
731 * the current one was removed (and the client can be unblocked). */
732 int dontWaitForSwappedKey(redisClient *c, robj *key) {
733 list *l;
734 listNode *ln;
735 listIter li;
736 struct dictEntry *de;
737
738 /* The key object might be destroyed when deleted from the c->io_keys
739 * list (and the "key" argument is physically the same object as the
740 * object inside the list), so we need to protect it. */
741 incrRefCount(key);
742
743 /* Remove the key from the list of keys this client is waiting for. */
744 listRewind(c->io_keys,&li);
745 while ((ln = listNext(&li)) != NULL) {
746 if (equalStringObjects(ln->value,key)) {
747 listDelNode(c->io_keys,ln);
748 break;
749 }
750 }
751 redisAssert(ln != NULL);
752
753 /* Remove the client form the key => waiting clients map. */
754 de = dictFind(c->db->io_keys,key);
755 redisAssert(de != NULL);
756 l = dictGetEntryVal(de);
757 ln = listSearchKey(l,c);
758 redisAssert(ln != NULL);
759 listDelNode(l,ln);
760 if (listLength(l) == 0)
761 dictDelete(c->db->io_keys,key);
762
763 decrRefCount(key);
764 return listLength(c->io_keys) == 0;
765 }
766
767 /* Every time we now a key was loaded back in memory, we handle clients
768 * waiting for this key if any. */
769 void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key) {
770 struct dictEntry *de;
771 list *l;
772 listNode *ln;
773 int len;
774
775 de = dictFind(db->io_keys,key);
776 if (!de) return;
777
778 l = dictGetEntryVal(de);
779 len = listLength(l);
780 /* Note: we can't use something like while(listLength(l)) as the list
781 * can be freed by the calling function when we remove the last element. */
782 while (len--) {
783 ln = listFirst(l);
784 redisClient *c = ln->value;
785
786 if (dontWaitForSwappedKey(c,key)) {
787 /* Put the client in the list of clients ready to go as we
788 * loaded all the keys about it. */
789 listAddNodeTail(server.io_ready_clients,c);
790 }
791 }
792 }