]> git.saurik.com Git - redis.git/blob - src/dscache.c
92f529418359fe767eb9639872c30d4b155c24d6
[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 * WARNING: most of the following todo items and design issues are no
23 * longer relevant with the new design. Here as a checklist to see if
24 * some old ideas still apply.
25 *
26 * - What happens when an object is destroyed?
27 *
28 * If the object is destroyed since semantically it was deleted or
29 * replaced with something new, we don't care if there was a SAVE
30 * job pending for it. Anyway when the IO JOb will be created we'll get
31 * the pointer of the current value.
32 *
33 * If the object is already a REDIS_IO_SAVEINPROG object, then it is
34 * impossible that we get a decrRefCount() that will reach refcount of zero
35 * since the object is both in the dataset and in the io job entry.
36 *
37 * - What happens with MULTI/EXEC?
38 *
39 * Good question. Without some kind of versioning with a global counter
40 * it is not possible to have trasactions on disk, but they are still
41 * useful since from the point of view of memory and client bugs it is
42 * a protection anyway. Also it's useful for WATCH.
43 *
44 * Btw there is to check what happens when WATCH gets combined to keys
45 * that gets removed from the object cache. Should be save but better
46 * to check.
47 *
48 * - Check if/why INCR will not update the LRU info for the object.
49 *
50 * - Fix/Check the following race condition: a key gets a DEL so there is
51 * a write operation scheduled against this key. Later the same key will
52 * be the argument of a GET, but the write operation was still not
53 * completed (to delete the file). If the GET will be for some reason
54 * a blocking loading (via lookup) we can load the old value on memory.
55 *
56 * This problems can be fixed with negative caching. We can use it
57 * to optimize the system, but also when a key is deleted we mark
58 * it as non existing on disk as well (in a way that this cache
59 * entry can't be evicted, setting time to 0), then we avoid looking at
60 * the disk at all if the key can't be there. When an IO Job complete
61 * a deletion, we set the time of the negative caching to a non zero
62 * value so it will be evicted later.
63 *
64 * Are there other patterns like this where we load stale data?
65 *
66 * Also, make sure that key preloading is ONLY done for keys that are
67 * not marked as cacheKeyDoesNotExist(), otherwise, again, we can load
68 * data from disk that should instead be deleted.
69 *
70 * - dsSet() should use rename(2) in order to avoid corruptions.
71 *
72 * - Don't add a LOAD if there is already a LOADINPROGRESS, or is this
73 * impossible since anyway the io_keys stuff will work as lock?
74 *
75 * - Serialize special encoded things in a raw form.
76 *
77 * - When putting IO read operations on top of the queue, do this only if
78 * the already-on-top operation is not a save or if it is a save that
79 * is scheduled for later execution. If there is a save that is ready to
80 * fire, let's insert the load operation just before the first save that
81 * is scheduled for later exection for instance.
82 *
83 * - Support MULTI/EXEC transactions via a journal file, that is played on
84 * startup to check if there is cleanup to do. This way we can implement
85 * transactions with our simple file based KV store.
86 */
87
88 /* Virtual Memory is composed mainly of two subsystems:
89 * - Blocking Virutal Memory
90 * - Threaded Virtual Memory I/O
91 * The two parts are not fully decoupled, but functions are split among two
92 * different sections of the source code (delimited by comments) in order to
93 * make more clear what functionality is about the blocking VM and what about
94 * the threaded (not blocking) VM.
95 *
96 * Redis VM design:
97 *
98 * Redis VM is a blocking VM (one that blocks reading swapped values from
99 * disk into memory when a value swapped out is needed in memory) that is made
100 * unblocking by trying to examine the command argument vector in order to
101 * load in background values that will likely be needed in order to exec
102 * the command. The command is executed only once all the relevant keys
103 * are loaded into memory.
104 *
105 * This basically is almost as simple of a blocking VM, but almost as parallel
106 * as a fully non-blocking VM.
107 */
108
109 void spawnIOThread(void);
110
111 /* =================== Virtual Memory - Blocking Side ====================== */
112
113 void dsInit(void) {
114 int pipefds[2];
115 size_t stacksize;
116
117 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
118
119 redisLog(REDIS_NOTICE,"Opening Disk Store: %s", server.ds_path);
120 /* Open Disk Store */
121 if (dsOpen() != REDIS_OK) {
122 redisLog(REDIS_WARNING,"Fatal error opening disk store. Exiting.");
123 exit(1);
124 };
125
126 /* Initialize threaded I/O for Object Cache */
127 server.io_newjobs = listCreate();
128 server.io_processing = listCreate();
129 server.io_processed = listCreate();
130 server.io_ready_clients = listCreate();
131 pthread_mutex_init(&server.io_mutex,NULL);
132 pthread_cond_init(&server.io_condvar,NULL);
133 server.io_active_threads = 0;
134 if (pipe(pipefds) == -1) {
135 redisLog(REDIS_WARNING,"Unable to intialized DS: pipe(2): %s. Exiting."
136 ,strerror(errno));
137 exit(1);
138 }
139 server.io_ready_pipe_read = pipefds[0];
140 server.io_ready_pipe_write = pipefds[1];
141 redisAssert(anetNonBlock(NULL,server.io_ready_pipe_read) != ANET_ERR);
142 /* LZF requires a lot of stack */
143 pthread_attr_init(&server.io_threads_attr);
144 pthread_attr_getstacksize(&server.io_threads_attr, &stacksize);
145
146 /* Solaris may report a stacksize of 0, let's set it to 1 otherwise
147 * multiplying it by 2 in the while loop later will not really help ;) */
148 if (!stacksize) stacksize = 1;
149
150 while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2;
151 pthread_attr_setstacksize(&server.io_threads_attr, stacksize);
152 /* Listen for events in the threaded I/O pipe */
153 if (aeCreateFileEvent(server.el, server.io_ready_pipe_read, AE_READABLE,
154 vmThreadedIOCompletedJob, NULL) == AE_ERR)
155 oom("creating file event");
156
157 /* Spawn our I/O thread */
158 spawnIOThread();
159 }
160
161 /* Compute how good candidate the specified object is for eviction.
162 * An higher number means a better candidate. */
163 double computeObjectSwappability(robj *o) {
164 /* actual age can be >= minage, but not < minage. As we use wrapping
165 * 21 bit clocks with minutes resolution for the LRU. */
166 return (double) estimateObjectIdleTime(o);
167 }
168
169 /* Try to free one entry from the diskstore object cache */
170 int cacheFreeOneEntry(void) {
171 int j, i;
172 struct dictEntry *best = NULL;
173 double best_swappability = 0;
174 redisDb *best_db = NULL;
175 robj *val;
176 sds key;
177
178 for (j = 0; j < server.dbnum; j++) {
179 redisDb *db = server.db+j;
180 /* Why maxtries is set to 100?
181 * Because this way (usually) we'll find 1 object even if just 1% - 2%
182 * are swappable objects */
183 int maxtries = 100;
184
185 if (dictSize(db->dict) == 0) continue;
186 for (i = 0; i < 5; i++) {
187 dictEntry *de;
188 double swappability;
189 robj keyobj;
190 sds keystr;
191
192 if (maxtries) maxtries--;
193 de = dictGetRandomKey(db->dict);
194 keystr = dictGetEntryKey(de);
195 val = dictGetEntryVal(de);
196 initStaticStringObject(keyobj,keystr);
197
198 /* Don't remove objects that are currently target of a
199 * read or write operation. */
200 if (cacheScheduleIOGetFlags(db,&keyobj) != 0) {
201 if (maxtries) i--; /* don't count this try */
202 continue;
203 }
204 swappability = computeObjectSwappability(val);
205 if (!best || swappability > best_swappability) {
206 best = de;
207 best_swappability = swappability;
208 best_db = db;
209 }
210 }
211 }
212 if (best == NULL) {
213 /* FIXME: If there are objects that are in the write queue
214 * so we can't delete them we should block here, at the cost of
215 * slowness as the object cache memory limit is considered
216 * n hard limit. */
217 return REDIS_ERR;
218 }
219 key = dictGetEntryKey(best);
220 val = dictGetEntryVal(best);
221
222 redisLog(REDIS_DEBUG,"Key selected for cache eviction: %s swappability:%f",
223 key, best_swappability);
224
225 /* Delete this key from memory */
226 {
227 robj *kobj = createStringObject(key,sdslen(key));
228 dbDelete(best_db,kobj);
229 decrRefCount(kobj);
230 }
231 return REDIS_OK;
232 }
233
234 /* Return true if it's safe to swap out objects in a given moment.
235 * Basically we don't want to swap objects out while there is a BGSAVE
236 * or a BGAEOREWRITE running in backgroud. */
237 int dsCanTouchDiskStore(void) {
238 return (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1);
239 }
240
241 /* ==================== Disk store negative caching ========================
242 *
243 * When disk store is enabled, we need negative caching, that is, to remember
244 * keys that are for sure *not* on the disk key-value store.
245 *
246 * This is usefuls because without negative caching cache misses will cost us
247 * a disk lookup, even if the same non existing key is accessed again and again.
248 *
249 * With negative caching we remember that the key is not on disk, so if it's
250 * not in memory and we have a negative cache entry, we don't try a disk
251 * access at all.
252 */
253
254 /* Returns true if the specified key may exists on disk, that is, we don't
255 * have an entry in our negative cache for this key */
256 int cacheKeyMayExist(redisDb *db, robj *key) {
257 return dictFind(db->io_negcache,key) == NULL;
258 }
259
260 /* Set the specified key as an entry that may possibily exist on disk, that is,
261 * remove the negative cache entry for this key if any. */
262 void cacheSetKeyMayExist(redisDb *db, robj *key) {
263 dictDelete(db->io_negcache,key);
264 }
265
266 /* Set the specified key as non existing on disk, that is, create a negative
267 * cache entry for this key. */
268 void cacheSetKeyDoesNotExist(redisDb *db, robj *key) {
269 if (dictReplace(db->io_negcache,key,(void*)time(NULL))) {
270 incrRefCount(key);
271 }
272 }
273
274 /* Remove one entry from negative cache using approximated LRU. */
275 int negativeCacheEvictOneEntry(void) {
276 struct dictEntry *de;
277 robj *best = NULL;
278 redisDb *best_db = NULL;
279 time_t time, best_time = 0;
280 int j;
281
282 for (j = 0; j < server.dbnum; j++) {
283 redisDb *db = server.db+j;
284 int i;
285
286 if (dictSize(db->io_negcache) == 0) continue;
287 for (i = 0; i < 3; i++) {
288 de = dictGetRandomKey(db->io_negcache);
289 time = (time_t) dictGetEntryVal(de);
290
291 if (best == NULL || time < best_time) {
292 best = dictGetEntryKey(de);
293 best_db = db;
294 best_time = time;
295 }
296 }
297 }
298 if (best) {
299 dictDelete(best_db->io_negcache,best);
300 return REDIS_OK;
301 } else {
302 return REDIS_ERR;
303 }
304 }
305
306 /* ================== Disk store cache - Threaded I/O ====================== */
307
308 void freeIOJob(iojob *j) {
309 decrRefCount(j->key);
310 /* j->val can be NULL if the job is about deleting the key from disk. */
311 if (j->val) decrRefCount(j->val);
312 zfree(j);
313 }
314
315 /* Every time a thread finished a Job, it writes a byte into the write side
316 * of an unix pipe in order to "awake" the main thread, and this function
317 * is called. */
318 void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata,
319 int mask)
320 {
321 char buf[1];
322 int retval, processed = 0, toprocess = -1;
323 REDIS_NOTUSED(el);
324 REDIS_NOTUSED(mask);
325 REDIS_NOTUSED(privdata);
326
327 /* For every byte we read in the read side of the pipe, there is one
328 * I/O job completed to process. */
329 while((retval = read(fd,buf,1)) == 1) {
330 iojob *j;
331 listNode *ln;
332
333 redisLog(REDIS_DEBUG,"Processing I/O completed job");
334
335 /* Get the processed element (the oldest one) */
336 lockThreadedIO();
337 redisAssert(listLength(server.io_processed) != 0);
338 if (toprocess == -1) {
339 toprocess = (listLength(server.io_processed)*REDIS_MAX_COMPLETED_JOBS_PROCESSED)/100;
340 if (toprocess <= 0) toprocess = 1;
341 }
342 ln = listFirst(server.io_processed);
343 j = ln->value;
344 listDelNode(server.io_processed,ln);
345 unlockThreadedIO();
346
347 /* Post process it in the main thread, as there are things we
348 * can do just here to avoid race conditions and/or invasive locks */
349 redisLog(REDIS_DEBUG,"COMPLETED Job type %s, key: %s",
350 (j->type == REDIS_IOJOB_LOAD) ? "load" : "save",
351 (unsigned char*)j->key->ptr);
352 if (j->type == REDIS_IOJOB_LOAD) {
353 /* Create the key-value pair in the in-memory database */
354 if (j->val != NULL) {
355 /* Note: it's possible that the key is already in memory
356 * due to a blocking load operation. */
357 if (dbAdd(j->db,j->key,j->val) == REDIS_OK) {
358 incrRefCount(j->val);
359 if (j->expire != -1) setExpire(j->db,j->key,j->expire);
360 }
361 } else {
362 /* Key not found on disk. If it is also not in memory
363 * as a cached object, nor there is a job writing it
364 * in background, we are sure the key does not exist
365 * currently.
366 *
367 * So we set a negative cache entry avoiding that the
368 * resumed client will block load what does not exist... */
369 if (dictFind(j->db->dict,j->key->ptr) == NULL &&
370 (cacheScheduleIOGetFlags(j->db,j->key) &
371 (REDIS_IO_SAVE|REDIS_IO_SAVEINPROG)) == 0)
372 {
373 cacheSetKeyDoesNotExist(j->db,j->key);
374 }
375 }
376 cacheScheduleIODelFlag(j->db,j->key,REDIS_IO_LOADINPROG);
377 handleClientsBlockedOnSwappedKey(j->db,j->key);
378 freeIOJob(j);
379 } else if (j->type == REDIS_IOJOB_SAVE) {
380 cacheScheduleIODelFlag(j->db,j->key,REDIS_IO_SAVEINPROG);
381 freeIOJob(j);
382 }
383 processed++;
384 if (processed == toprocess) return;
385 }
386 if (retval < 0 && errno != EAGAIN) {
387 redisLog(REDIS_WARNING,
388 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
389 strerror(errno));
390 }
391 }
392
393 void lockThreadedIO(void) {
394 pthread_mutex_lock(&server.io_mutex);
395 }
396
397 void unlockThreadedIO(void) {
398 pthread_mutex_unlock(&server.io_mutex);
399 }
400
401 void *IOThreadEntryPoint(void *arg) {
402 iojob *j;
403 listNode *ln;
404 REDIS_NOTUSED(arg);
405
406 pthread_detach(pthread_self());
407 lockThreadedIO();
408 while(1) {
409 /* Get a new job to process */
410 if (listLength(server.io_newjobs) == 0) {
411 /* Wait for more work to do */
412 pthread_cond_wait(&server.io_condvar,&server.io_mutex);
413 continue;
414 }
415 redisLog(REDIS_DEBUG,"%ld IO jobs to process",
416 listLength(server.io_newjobs));
417 ln = listFirst(server.io_newjobs);
418 j = ln->value;
419 listDelNode(server.io_newjobs,ln);
420 /* Add the job in the processing queue */
421 listAddNodeTail(server.io_processing,j);
422 ln = listLast(server.io_processing); /* We use ln later to remove it */
423 unlockThreadedIO();
424
425 redisLog(REDIS_DEBUG,"Thread %ld: new job type %s: %p about key '%s'",
426 (long) pthread_self(),
427 (j->type == REDIS_IOJOB_LOAD) ? "load" : "save",
428 (void*)j, (char*)j->key->ptr);
429
430 /* Process the Job */
431 if (j->type == REDIS_IOJOB_LOAD) {
432 time_t expire;
433
434 j->val = dsGet(j->db,j->key,&expire);
435 if (j->val) j->expire = expire;
436 } else if (j->type == REDIS_IOJOB_SAVE) {
437 if (j->val) {
438 dsSet(j->db,j->key,j->val);
439 } else {
440 dsDel(j->db,j->key);
441 }
442 }
443
444 /* Done: insert the job into the processed queue */
445 redisLog(REDIS_DEBUG,"Thread %ld completed the job: %p (key %s)",
446 (long) pthread_self(), (void*)j, (char*)j->key->ptr);
447
448 lockThreadedIO();
449 listDelNode(server.io_processing,ln);
450 listAddNodeTail(server.io_processed,j);
451
452 /* Signal the main thread there is new stuff to process */
453 redisAssert(write(server.io_ready_pipe_write,"x",1) == 1);
454 }
455 /* never reached, but that's the full pattern... */
456 unlockThreadedIO();
457 return NULL;
458 }
459
460 void spawnIOThread(void) {
461 pthread_t thread;
462 sigset_t mask, omask;
463 int err;
464
465 sigemptyset(&mask);
466 sigaddset(&mask,SIGCHLD);
467 sigaddset(&mask,SIGHUP);
468 sigaddset(&mask,SIGPIPE);
469 pthread_sigmask(SIG_SETMASK, &mask, &omask);
470 while ((err = pthread_create(&thread,&server.io_threads_attr,IOThreadEntryPoint,NULL)) != 0) {
471 redisLog(REDIS_WARNING,"Unable to spawn an I/O thread: %s",
472 strerror(err));
473 usleep(1000000);
474 }
475 pthread_sigmask(SIG_SETMASK, &omask, NULL);
476 server.io_active_threads++;
477 }
478
479 /* Wait that all the pending IO Jobs are processed */
480 void waitEmptyIOJobsQueue(void) {
481 while(1) {
482 int io_processed_len;
483
484 lockThreadedIO();
485 if (listLength(server.io_newjobs) == 0 &&
486 listLength(server.io_processing) == 0)
487 {
488 unlockThreadedIO();
489 return;
490 }
491 /* If there are new jobs we need to signal the thread to
492 * process the next one. */
493 redisLog(REDIS_DEBUG,"waitEmptyIOJobsQueue: new %d, processing %d",
494 listLength(server.io_newjobs),
495 listLength(server.io_processing));
496
497 /* FIXME: signal or not?
498 if (listLength(server.io_newjobs)) {
499 pthread_cond_signal(&server.io_condvar);
500 }
501 */
502 /* While waiting for empty jobs queue condition we post-process some
503 * finshed job, as I/O threads may be hanging trying to write against
504 * the io_ready_pipe_write FD but there are so much pending jobs that
505 * it's blocking. */
506 io_processed_len = listLength(server.io_processed);
507 unlockThreadedIO();
508 if (io_processed_len) {
509 vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,
510 (void*)0xdeadbeef,0);
511 /* FIXME: probably wiser to drop this sleeps. Anyway
512 * the contention on the IO thread will avoid we to loop
513 * too fast here. */
514 usleep(1000); /* 1 millisecond */
515 } else {
516 /* FIXME: same as fixme above. */
517 usleep(10000); /* 10 milliseconds */
518 }
519 }
520 }
521
522 /* Process all the IO Jobs already completed by threads but still waiting
523 * processing from the main thread. */
524 void processAllPendingIOJobs(void) {
525 while(1) {
526 int io_processed_len;
527
528 lockThreadedIO();
529 io_processed_len = listLength(server.io_processed);
530 unlockThreadedIO();
531 if (io_processed_len == 0) return;
532 vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,
533 (void*)0xdeadbeef,0);
534 }
535 }
536
537 /* This function must be called while with threaded IO locked */
538 void queueIOJob(iojob *j) {
539 redisLog(REDIS_DEBUG,"Queued IO Job %p type %d about key '%s'\n",
540 (void*)j, j->type, (char*)j->key->ptr);
541 listAddNodeTail(server.io_newjobs,j);
542 if (server.io_active_threads < server.vm_max_threads)
543 spawnIOThread();
544 }
545
546 void dsCreateIOJob(int type, redisDb *db, robj *key, robj *val) {
547 iojob *j;
548
549 j = zmalloc(sizeof(*j));
550 j->type = type;
551 j->db = db;
552 j->key = key;
553 incrRefCount(key);
554 j->val = val;
555 if (val) incrRefCount(val);
556
557 lockThreadedIO();
558 queueIOJob(j);
559 pthread_cond_signal(&server.io_condvar);
560 unlockThreadedIO();
561 }
562
563 /* ============= Disk store cache - Scheduling of IO operations =============
564 *
565 * We use a queue and an hash table to hold the state of IO operations
566 * so that's fast to lookup if there is already an IO operation in queue
567 * for a given key.
568 *
569 * There are two types of IO operations for a given key:
570 * REDIS_IO_LOAD and REDIS_IO_SAVE.
571 *
572 * The function cacheScheduleIO() function pushes the specified IO operation
573 * in the queue, but avoid adding the same key for the same operation
574 * multiple times, thanks to the associated hash table.
575 *
576 * We take a set of flags per every key, so when the scheduled IO operation
577 * gets moved from the scheduled queue to the actual IO Jobs queue that
578 * is processed by the IO thread, we flag it as IO_LOADINPROG or
579 * IO_SAVEINPROG.
580 *
581 * So for every given key we always know if there is some IO operation
582 * scheduled, or in progress, for this key.
583 *
584 * NOTE: all this is very important in order to guarantee correctness of
585 * the Disk Store Cache. Jobs are always queued here. Load jobs are
586 * queued at the head for faster execution only in the case there is not
587 * already a write operation of some kind for this job.
588 *
589 * So we have ordering, but can do exceptions when there are no already
590 * operations for a given key. Also when we need to block load a given
591 * key, for an immediate lookup operation, we can check if the key can
592 * be accessed synchronously without race conditions (no IN PROGRESS
593 * operations for this key), otherwise we blocking wait for completion. */
594
595 #define REDIS_IO_LOAD 1
596 #define REDIS_IO_SAVE 2
597 #define REDIS_IO_LOADINPROG 4
598 #define REDIS_IO_SAVEINPROG 8
599
600 void cacheScheduleIOPushJobs(int onlyloads);
601
602 void cacheScheduleIOAddFlag(redisDb *db, robj *key, long flag) {
603 struct dictEntry *de = dictFind(db->io_queued,key);
604
605 if (!de) {
606 dictAdd(db->io_queued,key,(void*)flag);
607 incrRefCount(key);
608 return;
609 } else {
610 long flags = (long) dictGetEntryVal(de);
611
612 if (flags & flag) {
613 redisLog(REDIS_WARNING,"Adding the same flag again: was: %ld, addede: %ld",flags,flag);
614 redisAssert(!(flags & flag));
615 }
616 flags |= flag;
617 dictGetEntryVal(de) = (void*) flags;
618 }
619 }
620
621 void cacheScheduleIODelFlag(redisDb *db, robj *key, long flag) {
622 struct dictEntry *de = dictFind(db->io_queued,key);
623 long flags;
624
625 redisAssert(de != NULL);
626 flags = (long) dictGetEntryVal(de);
627 redisAssert(flags & flag);
628 flags &= ~flag;
629 if (flags == 0) {
630 dictDelete(db->io_queued,key);
631 } else {
632 dictGetEntryVal(de) = (void*) flags;
633 }
634 }
635
636 int cacheScheduleIOGetFlags(redisDb *db, robj *key) {
637 struct dictEntry *de = dictFind(db->io_queued,key);
638
639 return (de == NULL) ? 0 : ((long) dictGetEntryVal(de));
640 }
641
642 void cacheScheduleIO(redisDb *db, robj *key, int type) {
643 ioop *op;
644 long flags;
645
646 if ((flags = cacheScheduleIOGetFlags(db,key)) & type) return;
647
648 redisLog(REDIS_DEBUG,"Scheduling key %s for %s",
649 key->ptr, type == REDIS_IO_LOAD ? "loading" : "saving");
650 cacheScheduleIOAddFlag(db,key,type);
651 op = zmalloc(sizeof(*op));
652 op->type = type;
653 op->db = db;
654 op->key = key;
655 incrRefCount(key);
656 op->ctime = time(NULL);
657
658 /* Give priority to load operations if there are no save already
659 * in queue for the same key. */
660 if (type == REDIS_IO_LOAD && !(flags & REDIS_IO_SAVE)) {
661 listAddNodeHead(server.cache_io_queue, op);
662 cacheScheduleIOPushJobs(1);
663 } else {
664 /* FIXME: probably when this happens we want to at least move
665 * the write job about this queue on top, and set the creation time
666 * to a value that will force processing ASAP. */
667 listAddNodeTail(server.cache_io_queue, op);
668 }
669 }
670
671 /* Push scheduled IO operations into IO Jobs that the IO thread can process.
672 * If 'onlyloads' is true only IO_LOAD jobs are processed: this is useful
673 * since it's save to push LOAD IO jobs from any place of the code, while
674 * SAVE io jobs should never be pushed while we are processing a command
675 * (not protected by lookupKey() that will block on keys in IO_SAVEINPROG
676 * state. */
677 #define MAX_IO_JOBS_QUEUE 100
678 void cacheScheduleIOPushJobs(int onlyloads) {
679 time_t now = time(NULL);
680 listNode *ln;
681 int jobs, topush = 0;
682
683 /* Sync stuff on disk, but only if we have less
684 * than MAX_IO_JOBS_QUEUE IO jobs. */
685 lockThreadedIO();
686 jobs = listLength(server.io_newjobs);
687 unlockThreadedIO();
688
689 topush = MAX_IO_JOBS_QUEUE-jobs;
690 if (topush < 0) topush = 0;
691 if (topush > (signed)listLength(server.cache_io_queue))
692 topush = listLength(server.cache_io_queue);
693
694 while((ln = listFirst(server.cache_io_queue)) != NULL) {
695 ioop *op = ln->value;
696
697 if (!topush) break;
698 topush--;
699
700 if (op->type == REDIS_IO_LOAD ||
701 (!onlyloads && (now - op->ctime) >= server.cache_flush_delay))
702 {
703 struct dictEntry *de;
704 robj *val;
705
706 /* Don't add a SAVE job in queue if there is already
707 * a save in progress for the same key. */
708 if (op->type == REDIS_IO_SAVE &&
709 cacheScheduleIOGetFlags(op->db,op->key) & REDIS_IO_SAVEINPROG)
710 {
711 /* Move the operation at the end of the list of there
712 * are other operations. Otherwise break, nothing to do
713 * here. */
714 if (listLength(server.cache_io_queue) > 1) {
715 listDelNode(server.cache_io_queue,ln);
716 listAddNodeTail(server.cache_io_queue,op);
717 continue;
718 } else {
719 break;
720 }
721 }
722
723 redisLog(REDIS_DEBUG,"Creating IO %s Job for key %s",
724 op->type == REDIS_IO_LOAD ? "load" : "save", op->key->ptr);
725
726 if (op->type == REDIS_IO_LOAD) {
727 dsCreateIOJob(REDIS_IOJOB_LOAD,op->db,op->key,NULL);
728 } else {
729 /* Lookup the key, in order to put the current value in the IO
730 * Job. Otherwise if the key does not exists we schedule a disk
731 * store delete operation, setting the value to NULL. */
732 de = dictFind(op->db->dict,op->key->ptr);
733 if (de) {
734 val = dictGetEntryVal(de);
735 } else {
736 /* Setting the value to NULL tells the IO thread to delete
737 * the key on disk. */
738 val = NULL;
739 }
740 dsCreateIOJob(REDIS_IOJOB_SAVE,op->db,op->key,val);
741 }
742 /* Mark the operation as in progress. */
743 cacheScheduleIODelFlag(op->db,op->key,op->type);
744 cacheScheduleIOAddFlag(op->db,op->key,
745 (op->type == REDIS_IO_LOAD) ? REDIS_IO_LOADINPROG :
746 REDIS_IO_SAVEINPROG);
747 /* Finally remove the operation from the queue.
748 * But we'll have trace of it in the hash table. */
749 listDelNode(server.cache_io_queue,ln);
750 decrRefCount(op->key);
751 zfree(op);
752 } else {
753 break; /* too early */
754 }
755 }
756 }
757
758 void cacheCron(void) {
759 /* Push jobs */
760 cacheScheduleIOPushJobs(0);
761
762 /* Reclaim memory from the object cache */
763 while (server.ds_enabled && zmalloc_used_memory() >
764 server.cache_max_memory)
765 {
766 int done = 0;
767
768 if (cacheFreeOneEntry() == REDIS_OK) done++;
769 if (negativeCacheEvictOneEntry() == REDIS_OK) done++;
770 if (done == 0) break; /* nothing more to free */
771 }
772 }
773
774 /* ========== Disk store cache - Blocking clients on missing keys =========== */
775
776 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
777 * If the key is already in memory we don't need to block.
778 *
779 * FIXME: we should try if it's actually better to suspend the client
780 * accessing an object that is being saved, and awake it only when
781 * the saving was completed.
782 *
783 * Otherwise if the key is not in memory, we block the client and start
784 * an IO Job to load it:
785 *
786 * the key is added to the io_keys list in the client structure, and also
787 * in the hash table mapping swapped keys to waiting clients, that is,
788 * server.io_waited_keys. */
789 int waitForSwappedKey(redisClient *c, robj *key) {
790 struct dictEntry *de;
791 list *l;
792
793 /* Return ASAP if the key is in memory */
794 de = dictFind(c->db->dict,key->ptr);
795 if (de != NULL) return 0;
796
797 /* Don't wait for keys we are sure are not on disk either */
798 if (!cacheKeyMayExist(c->db,key)) return 0;
799
800 /* Add the key to the list of keys this client is waiting for.
801 * This maps clients to keys they are waiting for. */
802 listAddNodeTail(c->io_keys,key);
803 incrRefCount(key);
804
805 /* Add the client to the swapped keys => clients waiting map. */
806 de = dictFind(c->db->io_keys,key);
807 if (de == NULL) {
808 int retval;
809
810 /* For every key we take a list of clients blocked for it */
811 l = listCreate();
812 retval = dictAdd(c->db->io_keys,key,l);
813 incrRefCount(key);
814 redisAssert(retval == DICT_OK);
815 } else {
816 l = dictGetEntryVal(de);
817 }
818 listAddNodeTail(l,c);
819
820 /* Are we already loading the key from disk? If not create a job */
821 if (de == NULL)
822 cacheScheduleIO(c->db,key,REDIS_IO_LOAD);
823 return 1;
824 }
825
826 /* Preload keys for any command with first, last and step values for
827 * the command keys prototype, as defined in the command table. */
828 void waitForMultipleSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
829 int j, last;
830 if (cmd->vm_firstkey == 0) return;
831 last = cmd->vm_lastkey;
832 if (last < 0) last = argc+last;
833 for (j = cmd->vm_firstkey; j <= last; j += cmd->vm_keystep) {
834 redisAssert(j < argc);
835 waitForSwappedKey(c,argv[j]);
836 }
837 }
838
839 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
840 * Note that the number of keys to preload is user-defined, so we need to
841 * apply a sanity check against argc. */
842 void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
843 int i, num;
844 REDIS_NOTUSED(cmd);
845
846 num = atoi(argv[2]->ptr);
847 if (num > (argc-3)) return;
848 for (i = 0; i < num; i++) {
849 waitForSwappedKey(c,argv[3+i]);
850 }
851 }
852
853 /* Preload keys needed to execute the entire MULTI/EXEC block.
854 *
855 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
856 * and will block the client when any command requires a swapped out value. */
857 void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
858 int i, margc;
859 struct redisCommand *mcmd;
860 robj **margv;
861 REDIS_NOTUSED(cmd);
862 REDIS_NOTUSED(argc);
863 REDIS_NOTUSED(argv);
864
865 if (!(c->flags & REDIS_MULTI)) return;
866 for (i = 0; i < c->mstate.count; i++) {
867 mcmd = c->mstate.commands[i].cmd;
868 margc = c->mstate.commands[i].argc;
869 margv = c->mstate.commands[i].argv;
870
871 if (mcmd->vm_preload_proc != NULL) {
872 mcmd->vm_preload_proc(c,mcmd,margc,margv);
873 } else {
874 waitForMultipleSwappedKeys(c,mcmd,margc,margv);
875 }
876 }
877 }
878
879 /* Is this client attempting to run a command against swapped keys?
880 * If so, block it ASAP, load the keys in background, then resume it.
881 *
882 * The important idea about this function is that it can fail! If keys will
883 * still be swapped when the client is resumed, this key lookups will
884 * just block loading keys from disk. In practical terms this should only
885 * happen with SORT BY command or if there is a bug in this function.
886 *
887 * Return 1 if the client is marked as blocked, 0 if the client can
888 * continue as the keys it is going to access appear to be in memory. */
889 int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd) {
890 if (cmd->vm_preload_proc != NULL) {
891 cmd->vm_preload_proc(c,cmd,c->argc,c->argv);
892 } else {
893 waitForMultipleSwappedKeys(c,cmd,c->argc,c->argv);
894 }
895
896 /* If the client was blocked for at least one key, mark it as blocked. */
897 if (listLength(c->io_keys)) {
898 c->flags |= REDIS_IO_WAIT;
899 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
900 server.cache_blocked_clients++;
901 return 1;
902 } else {
903 return 0;
904 }
905 }
906
907 /* Remove the 'key' from the list of blocked keys for a given client.
908 *
909 * The function returns 1 when there are no longer blocking keys after
910 * the current one was removed (and the client can be unblocked). */
911 int dontWaitForSwappedKey(redisClient *c, robj *key) {
912 list *l;
913 listNode *ln;
914 listIter li;
915 struct dictEntry *de;
916
917 /* The key object might be destroyed when deleted from the c->io_keys
918 * list (and the "key" argument is physically the same object as the
919 * object inside the list), so we need to protect it. */
920 incrRefCount(key);
921
922 /* Remove the key from the list of keys this client is waiting for. */
923 listRewind(c->io_keys,&li);
924 while ((ln = listNext(&li)) != NULL) {
925 if (equalStringObjects(ln->value,key)) {
926 listDelNode(c->io_keys,ln);
927 break;
928 }
929 }
930 redisAssert(ln != NULL);
931
932 /* Remove the client form the key => waiting clients map. */
933 de = dictFind(c->db->io_keys,key);
934 redisAssert(de != NULL);
935 l = dictGetEntryVal(de);
936 ln = listSearchKey(l,c);
937 redisAssert(ln != NULL);
938 listDelNode(l,ln);
939 if (listLength(l) == 0)
940 dictDelete(c->db->io_keys,key);
941
942 decrRefCount(key);
943 return listLength(c->io_keys) == 0;
944 }
945
946 /* Every time we now a key was loaded back in memory, we handle clients
947 * waiting for this key if any. */
948 void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key) {
949 struct dictEntry *de;
950 list *l;
951 listNode *ln;
952 int len;
953
954 de = dictFind(db->io_keys,key);
955 if (!de) return;
956
957 l = dictGetEntryVal(de);
958 len = listLength(l);
959 /* Note: we can't use something like while(listLength(l)) as the list
960 * can be freed by the calling function when we remove the last element. */
961 while (len--) {
962 ln = listFirst(l);
963 redisClient *c = ln->value;
964
965 if (dontWaitForSwappedKey(c,key)) {
966 /* Put the client in the list of clients ready to go as we
967 * loaded all the keys about it. */
968 listAddNodeTail(server.io_ready_clients,c);
969 }
970 }
971 }