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