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