]> git.saurik.com Git - redis.git/blob - src/dscache.c
implemented a different approach to IO scheduling, so object->storage is no longer...
[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 robj keyobj;
218 sds keystr;
219
220 if (maxtries) maxtries--;
221 de = dictGetRandomKey(db->dict);
222 keystr = dictGetEntryKey(de);
223 val = dictGetEntryVal(de);
224 initStaticStringObject(keyobj,keystr);
225
226 /* Don't remove objects that are currently target of a
227 * read or write operation. */
228 if (cacheScheduleIOGetFlags(db,&keyobj) != 0) {
229 if (maxtries) i--; /* don't count this try */
230 continue;
231 }
232 swappability = computeObjectSwappability(val);
233 if (!best || swappability > best_swappability) {
234 best = de;
235 best_swappability = swappability;
236 best_db = db;
237 }
238 }
239 }
240 if (best == NULL) {
241 /* FIXME: If there are objects marked as DS_DIRTY or DS_SAVING
242 * let's wait for this objects to be clear and retry...
243 *
244 * Object cache vm limit is considered an hard limit. */
245 return REDIS_ERR;
246 }
247 key = dictGetEntryKey(best);
248 val = dictGetEntryVal(best);
249
250 redisLog(REDIS_DEBUG,"Key selected for cache eviction: %s swappability:%f",
251 key, best_swappability);
252
253 /* Delete this key from memory */
254 {
255 robj *kobj = createStringObject(key,sdslen(key));
256 dbDelete(best_db,kobj);
257 decrRefCount(kobj);
258 }
259 return REDIS_OK;
260 }
261
262 /* Return true if it's safe to swap out objects in a given moment.
263 * Basically we don't want to swap objects out while there is a BGSAVE
264 * or a BGAEOREWRITE running in backgroud. */
265 int dsCanTouchDiskStore(void) {
266 return (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1);
267 }
268
269 /* ==================== Disk store negative caching ========================
270 *
271 * When disk store is enabled, we need negative caching, that is, to remember
272 * keys that are for sure *not* on the disk key-value store.
273 *
274 * This is usefuls because without negative caching cache misses will cost us
275 * a disk lookup, even if the same non existing key is accessed again and again.
276 *
277 * With negative caching we remember that the key is not on disk, so if it's
278 * not in memory and we have a negative cache entry, we don't try a disk
279 * access at all.
280 */
281
282 /* Returns true if the specified key may exists on disk, that is, we don't
283 * have an entry in our negative cache for this key */
284 int cacheKeyMayExist(redisDb *db, robj *key) {
285 return dictFind(db->io_negcache,key) == NULL;
286 }
287
288 /* Set the specified key as an entry that may possibily exist on disk, that is,
289 * remove the negative cache entry for this key if any. */
290 void cacheSetKeyMayExist(redisDb *db, robj *key) {
291 dictDelete(db->io_negcache,key);
292 }
293
294 /* Set the specified key as non existing on disk, that is, create a negative
295 * cache entry for this key. */
296 void cacheSetKeyDoesNotExist(redisDb *db, robj *key) {
297 if (dictReplace(db->io_negcache,key,(void*)time(NULL))) {
298 incrRefCount(key);
299 }
300 }
301
302 /* ================== Disk store cache - Threaded I/O ====================== */
303
304 void freeIOJob(iojob *j) {
305 decrRefCount(j->key);
306 /* j->val can be NULL if the job is about deleting the key from disk. */
307 if (j->val) decrRefCount(j->val);
308 zfree(j);
309 }
310
311 /* Every time a thread finished a Job, it writes a byte into the write side
312 * of an unix pipe in order to "awake" the main thread, and this function
313 * is called. */
314 void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata,
315 int mask)
316 {
317 char buf[1];
318 int retval, processed = 0, toprocess = -1;
319 REDIS_NOTUSED(el);
320 REDIS_NOTUSED(mask);
321 REDIS_NOTUSED(privdata);
322
323 /* For every byte we read in the read side of the pipe, there is one
324 * I/O job completed to process. */
325 while((retval = read(fd,buf,1)) == 1) {
326 iojob *j;
327 listNode *ln;
328
329 redisLog(REDIS_DEBUG,"Processing I/O completed job");
330
331 /* Get the processed element (the oldest one) */
332 lockThreadedIO();
333 redisAssert(listLength(server.io_processed) != 0);
334 if (toprocess == -1) {
335 toprocess = (listLength(server.io_processed)*REDIS_MAX_COMPLETED_JOBS_PROCESSED)/100;
336 if (toprocess <= 0) toprocess = 1;
337 }
338 ln = listFirst(server.io_processed);
339 j = ln->value;
340 listDelNode(server.io_processed,ln);
341 unlockThreadedIO();
342
343 /* Post process it in the main thread, as there are things we
344 * can do just here to avoid race conditions and/or invasive locks */
345 redisLog(REDIS_DEBUG,"COMPLETED Job type %s, key: %s",
346 (j->type == REDIS_IOJOB_LOAD) ? "load" : "save",
347 (unsigned char*)j->key->ptr);
348 if (j->type == REDIS_IOJOB_LOAD) {
349 /* Create the key-value pair in the in-memory database */
350 if (j->val != NULL) {
351 /* Note: it's possible that the key is already in memory
352 * due to a blocking load operation. */
353 if (dbAdd(j->db,j->key,j->val) == REDIS_OK) {
354 incrRefCount(j->val);
355 if (j->expire != -1) setExpire(j->db,j->key,j->expire);
356 }
357 } else {
358 /* The key does not exist. Create a negative cache entry
359 * for this key. */
360 cacheSetKeyDoesNotExist(j->db,j->key);
361 }
362 cacheScheduleIODelFlag(j->db,j->key,REDIS_IO_LOADINPROG);
363 handleClientsBlockedOnSwappedKey(j->db,j->key);
364 freeIOJob(j);
365 } else if (j->type == REDIS_IOJOB_SAVE) {
366 if (j->val) {
367 cacheSetKeyMayExist(j->db,j->key);
368 } else {
369 cacheSetKeyDoesNotExist(j->db,j->key);
370 }
371 cacheScheduleIODelFlag(j->db,j->key,REDIS_IO_SAVEINPROG);
372 freeIOJob(j);
373 }
374 processed++;
375 if (processed == toprocess) return;
376 }
377 if (retval < 0 && errno != EAGAIN) {
378 redisLog(REDIS_WARNING,
379 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
380 strerror(errno));
381 }
382 }
383
384 void lockThreadedIO(void) {
385 pthread_mutex_lock(&server.io_mutex);
386 }
387
388 void unlockThreadedIO(void) {
389 pthread_mutex_unlock(&server.io_mutex);
390 }
391
392 void *IOThreadEntryPoint(void *arg) {
393 iojob *j;
394 listNode *ln;
395 REDIS_NOTUSED(arg);
396
397 pthread_detach(pthread_self());
398 lockThreadedIO();
399 while(1) {
400 /* Get a new job to process */
401 if (listLength(server.io_newjobs) == 0) {
402 /* Wait for more work to do */
403 pthread_cond_wait(&server.io_condvar,&server.io_mutex);
404 continue;
405 }
406 redisLog(REDIS_DEBUG,"%ld IO jobs to process",
407 listLength(server.io_newjobs));
408 ln = listFirst(server.io_newjobs);
409 j = ln->value;
410 listDelNode(server.io_newjobs,ln);
411 /* Add the job in the processing queue */
412 listAddNodeTail(server.io_processing,j);
413 ln = listLast(server.io_processing); /* We use ln later to remove it */
414 unlockThreadedIO();
415
416 redisLog(REDIS_DEBUG,"Thread %ld: new job type %s: %p about key '%s'",
417 (long) pthread_self(),
418 (j->type == REDIS_IOJOB_LOAD) ? "load" : "save",
419 (void*)j, (char*)j->key->ptr);
420
421 /* Process the Job */
422 if (j->type == REDIS_IOJOB_LOAD) {
423 time_t expire;
424
425 j->val = dsGet(j->db,j->key,&expire);
426 if (j->val) j->expire = expire;
427 } else if (j->type == REDIS_IOJOB_SAVE) {
428 if (j->val) {
429 dsSet(j->db,j->key,j->val);
430 } else {
431 dsDel(j->db,j->key);
432 }
433 }
434
435 /* Done: insert the job into the processed queue */
436 redisLog(REDIS_DEBUG,"Thread %ld completed the job: %p (key %s)",
437 (long) pthread_self(), (void*)j, (char*)j->key->ptr);
438
439 lockThreadedIO();
440 listDelNode(server.io_processing,ln);
441 listAddNodeTail(server.io_processed,j);
442
443 /* Signal the main thread there is new stuff to process */
444 redisAssert(write(server.io_ready_pipe_write,"x",1) == 1);
445 }
446 /* never reached, but that's the full pattern... */
447 unlockThreadedIO();
448 return NULL;
449 }
450
451 void spawnIOThread(void) {
452 pthread_t thread;
453 sigset_t mask, omask;
454 int err;
455
456 sigemptyset(&mask);
457 sigaddset(&mask,SIGCHLD);
458 sigaddset(&mask,SIGHUP);
459 sigaddset(&mask,SIGPIPE);
460 pthread_sigmask(SIG_SETMASK, &mask, &omask);
461 while ((err = pthread_create(&thread,&server.io_threads_attr,IOThreadEntryPoint,NULL)) != 0) {
462 redisLog(REDIS_WARNING,"Unable to spawn an I/O thread: %s",
463 strerror(err));
464 usleep(1000000);
465 }
466 pthread_sigmask(SIG_SETMASK, &omask, NULL);
467 server.io_active_threads++;
468 }
469
470 /* Wait that all the pending IO Jobs are processed */
471 void waitEmptyIOJobsQueue(void) {
472 while(1) {
473 int io_processed_len;
474
475 lockThreadedIO();
476 if (listLength(server.io_newjobs) == 0 &&
477 listLength(server.io_processing) == 0)
478 {
479 unlockThreadedIO();
480 return;
481 }
482 /* If there are new jobs we need to signal the thread to
483 * process the next one. */
484 redisLog(REDIS_DEBUG,"waitEmptyIOJobsQueue: new %d, processing %d",
485 listLength(server.io_newjobs),
486 listLength(server.io_processing));
487 /*
488 if (listLength(server.io_newjobs)) {
489 pthread_cond_signal(&server.io_condvar);
490 }
491 */
492 /* While waiting for empty jobs queue condition we post-process some
493 * finshed job, as I/O threads may be hanging trying to write against
494 * the io_ready_pipe_write FD but there are so much pending jobs that
495 * it's blocking. */
496 io_processed_len = listLength(server.io_processed);
497 unlockThreadedIO();
498 if (io_processed_len) {
499 vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,
500 (void*)0xdeadbeef,0);
501 usleep(1000); /* 1 millisecond */
502 } else {
503 usleep(10000); /* 10 milliseconds */
504 }
505 }
506 }
507
508 /* Process all the IO Jobs already completed by threads but still waiting
509 * processing from the main thread. */
510 void processAllPendingIOJobs(void) {
511 while(1) {
512 int io_processed_len;
513
514 lockThreadedIO();
515 io_processed_len = listLength(server.io_processed);
516 unlockThreadedIO();
517 if (io_processed_len == 0) return;
518 vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,
519 (void*)0xdeadbeef,0);
520 }
521 }
522
523 /* This function must be called while with threaded IO locked */
524 void queueIOJob(iojob *j) {
525 redisLog(REDIS_DEBUG,"Queued IO Job %p type %d about key '%s'\n",
526 (void*)j, j->type, (char*)j->key->ptr);
527 listAddNodeTail(server.io_newjobs,j);
528 if (server.io_active_threads < server.vm_max_threads)
529 spawnIOThread();
530 }
531
532 void dsCreateIOJob(int type, redisDb *db, robj *key, robj *val) {
533 iojob *j;
534
535 j = zmalloc(sizeof(*j));
536 j->type = type;
537 j->db = db;
538 j->key = key;
539 incrRefCount(key);
540 j->val = val;
541 if (val) incrRefCount(val);
542
543 lockThreadedIO();
544 queueIOJob(j);
545 pthread_cond_signal(&server.io_condvar);
546 unlockThreadedIO();
547 }
548
549 /* ============= Disk store cache - Scheduling of IO operations =============
550 *
551 * We use a queue and an hash table to hold the state of IO operations
552 * so that's fast to lookup if there is already an IO operation in queue
553 * for a given key.
554 *
555 * There are two types of IO operations for a given key:
556 * REDIS_IO_LOAD and REDIS_IO_SAVE.
557 *
558 * The function cacheScheduleIO() function pushes the specified IO operation
559 * in the queue, but avoid adding the same key for the same operation
560 * multiple times, thanks to the associated hash table.
561 *
562 * We take a set of flags per every key, so when the scheduled IO operation
563 * gets moved from the scheduled queue to the actual IO Jobs queue that
564 * is processed by the IO thread, we flag it as IO_LOADINPROG or
565 * IO_SAVEINPROG.
566 *
567 * So for every given key we always know if there is some IO operation
568 * scheduled, or in progress, for this key.
569 *
570 * NOTE: all this is very important in order to guarantee correctness of
571 * the Disk Store Cache. Jobs are always queued here. Load jobs are
572 * queued at the head for faster execution only in the case there is not
573 * already a write operation of some kind for this job.
574 *
575 * So we have ordering, but can do exceptions when there are no already
576 * operations for a given key. Also when we need to block load a given
577 * key, for an immediate lookup operation, we can check if the key can
578 * be accessed synchronously without race conditions (no IN PROGRESS
579 * operations for this key), otherwise we blocking wait for completion. */
580
581 #define REDIS_IO_LOAD 1
582 #define REDIS_IO_SAVE 2
583 #define REDIS_IO_LOADINPROG 4
584 #define REDIS_IO_SAVEINPROG 8
585
586 void cacheScheduleIOAddFlag(redisDb *db, robj *key, long flag) {
587 struct dictEntry *de = dictFind(db->io_queued,key);
588
589 if (!de) {
590 dictAdd(db->io_queued,key,(void*)flag);
591 incrRefCount(key);
592 return;
593 } else {
594 long flags = (long) dictGetEntryVal(de);
595 flags |= flag;
596 dictGetEntryVal(de) = (void*) flags;
597 }
598 }
599
600 void cacheScheduleIODelFlag(redisDb *db, robj *key, long flag) {
601 struct dictEntry *de = dictFind(db->io_queued,key);
602 long flags;
603
604 redisAssert(de != NULL);
605 flags = (long) dictGetEntryVal(de);
606 redisAssert(flags & flag);
607 flags &= ~flag;
608 if (flags == 0) {
609 dictDelete(db->io_queued,key);
610 } else {
611 dictGetEntryVal(de) = (void*) flags;
612 }
613 }
614
615 int cacheScheduleIOGetFlags(redisDb *db, robj *key) {
616 struct dictEntry *de = dictFind(db->io_queued,key);
617
618 return (de == NULL) ? 0 : ((long) dictGetEntryVal(de));
619 }
620
621 void cacheScheduleIO(redisDb *db, robj *key, int type) {
622 ioop *op;
623 long flags;
624
625 if ((flags = cacheScheduleIOGetFlags(db,key)) & type) return;
626
627 redisLog(REDIS_DEBUG,"Scheduling key %s for %s",
628 key->ptr, type == REDIS_IO_LOAD ? "loading" : "saving");
629 cacheScheduleIOAddFlag(db,key,type);
630 op = zmalloc(sizeof(*op));
631 op->type = type;
632 op->db = db;
633 op->key = key;
634 incrRefCount(key);
635 op->ctime = time(NULL);
636
637 /* Give priority to load operations if there are no save already
638 * in queue for the same key. */
639 if (type == REDIS_IO_LOAD && !(flags & REDIS_IO_SAVE)) {
640 listAddNodeHead(server.cache_io_queue, op);
641 } else {
642 /* FIXME: probably when this happens we want to at least move
643 * the write job about this queue on top, and set the creation time
644 * to a value that will force processing ASAP. */
645 listAddNodeTail(server.cache_io_queue, op);
646 }
647 }
648
649 void cacheCron(void) {
650 time_t now = time(NULL);
651 listNode *ln;
652 int jobs, topush = 0;
653
654 /* Sync stuff on disk, but only if we have less than 100 IO jobs */
655 lockThreadedIO();
656 jobs = listLength(server.io_newjobs);
657 unlockThreadedIO();
658
659 topush = 100-jobs;
660 if (topush < 0) topush = 0;
661
662 while((ln = listFirst(server.cache_io_queue)) != NULL) {
663 ioop *op = ln->value;
664
665 if (!topush) break;
666 topush--;
667
668 if (op->type == REDIS_IO_LOAD ||
669 (now - op->ctime) >= server.cache_flush_delay)
670 {
671 struct dictEntry *de;
672 robj *val;
673
674 redisLog(REDIS_DEBUG,"Creating IO %s Job for key %s",
675 op->type == REDIS_IO_LOAD ? "load" : "save", op->key->ptr);
676
677 if (op->type == REDIS_IO_LOAD) {
678 dsCreateIOJob(REDIS_IOJOB_LOAD,op->db,op->key,NULL);
679 } else {
680 /* Lookup the key, in order to put the current value in the IO
681 * Job. Otherwise if the key does not exists we schedule a disk
682 * store delete operation, setting the value to NULL. */
683 de = dictFind(op->db->dict,op->key->ptr);
684 if (de) {
685 val = dictGetEntryVal(de);
686 } else {
687 /* Setting the value to NULL tells the IO thread to delete
688 * the key on disk. */
689 val = NULL;
690 }
691 dsCreateIOJob(REDIS_IOJOB_SAVE,op->db,op->key,val);
692 }
693 /* Mark the operation as in progress. */
694 cacheScheduleIODelFlag(op->db,op->key,op->type);
695 cacheScheduleIOAddFlag(op->db,op->key,
696 (op->type == REDIS_IO_LOAD) ? REDIS_IO_LOADINPROG :
697 REDIS_IO_SAVEINPROG);
698 /* Finally remove the operation from the queue.
699 * But we'll have trace of it in the hash table. */
700 listDelNode(server.cache_io_queue,ln);
701 decrRefCount(op->key);
702 zfree(op);
703 } else {
704 break; /* too early */
705 }
706 }
707
708 /* Reclaim memory from the object cache */
709 while (server.ds_enabled && zmalloc_used_memory() >
710 server.cache_max_memory)
711 {
712 if (cacheFreeOneEntry() == REDIS_ERR) break;
713 /* FIXME: also free negative cache entries here. */
714 }
715 }
716
717 /* ========== Disk store cache - Blocking clients on missing keys =========== */
718
719 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
720 * If the key is already in memory we don't need to block.
721 *
722 * FIXME: we should try if it's actually better to suspend the client
723 * accessing an object that is being saved, and awake it only when
724 * the saving was completed.
725 *
726 * Otherwise if the key is not in memory, we block the client and start
727 * an IO Job to load it:
728 *
729 * the key is added to the io_keys list in the client structure, and also
730 * in the hash table mapping swapped keys to waiting clients, that is,
731 * server.io_waited_keys. */
732 int waitForSwappedKey(redisClient *c, robj *key) {
733 struct dictEntry *de;
734 list *l;
735
736 /* Return ASAP if the key is in memory */
737 de = dictFind(c->db->dict,key->ptr);
738 if (de != NULL) return 0;
739
740 /* Don't wait for keys we are sure are not on disk either */
741 if (!cacheKeyMayExist(c->db,key)) return 0;
742
743 /* Add the key to the list of keys this client is waiting for.
744 * This maps clients to keys they are waiting for. */
745 listAddNodeTail(c->io_keys,key);
746 incrRefCount(key);
747
748 /* Add the client to the swapped keys => clients waiting map. */
749 de = dictFind(c->db->io_keys,key);
750 if (de == NULL) {
751 int retval;
752
753 /* For every key we take a list of clients blocked for it */
754 l = listCreate();
755 retval = dictAdd(c->db->io_keys,key,l);
756 incrRefCount(key);
757 redisAssert(retval == DICT_OK);
758 } else {
759 l = dictGetEntryVal(de);
760 }
761 listAddNodeTail(l,c);
762
763 /* Are we already loading the key from disk? If not create a job */
764 if (de == NULL)
765 cacheScheduleIO(c->db,key,REDIS_IO_LOAD);
766 return 1;
767 }
768
769 /* Preload keys for any command with first, last and step values for
770 * the command keys prototype, as defined in the command table. */
771 void waitForMultipleSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
772 int j, last;
773 if (cmd->vm_firstkey == 0) return;
774 last = cmd->vm_lastkey;
775 if (last < 0) last = argc+last;
776 for (j = cmd->vm_firstkey; j <= last; j += cmd->vm_keystep) {
777 redisAssert(j < argc);
778 waitForSwappedKey(c,argv[j]);
779 }
780 }
781
782 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
783 * Note that the number of keys to preload is user-defined, so we need to
784 * apply a sanity check against argc. */
785 void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
786 int i, num;
787 REDIS_NOTUSED(cmd);
788
789 num = atoi(argv[2]->ptr);
790 if (num > (argc-3)) return;
791 for (i = 0; i < num; i++) {
792 waitForSwappedKey(c,argv[3+i]);
793 }
794 }
795
796 /* Preload keys needed to execute the entire MULTI/EXEC block.
797 *
798 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
799 * and will block the client when any command requires a swapped out value. */
800 void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
801 int i, margc;
802 struct redisCommand *mcmd;
803 robj **margv;
804 REDIS_NOTUSED(cmd);
805 REDIS_NOTUSED(argc);
806 REDIS_NOTUSED(argv);
807
808 if (!(c->flags & REDIS_MULTI)) return;
809 for (i = 0; i < c->mstate.count; i++) {
810 mcmd = c->mstate.commands[i].cmd;
811 margc = c->mstate.commands[i].argc;
812 margv = c->mstate.commands[i].argv;
813
814 if (mcmd->vm_preload_proc != NULL) {
815 mcmd->vm_preload_proc(c,mcmd,margc,margv);
816 } else {
817 waitForMultipleSwappedKeys(c,mcmd,margc,margv);
818 }
819 }
820 }
821
822 /* Is this client attempting to run a command against swapped keys?
823 * If so, block it ASAP, load the keys in background, then resume it.
824 *
825 * The important idea about this function is that it can fail! If keys will
826 * still be swapped when the client is resumed, this key lookups will
827 * just block loading keys from disk. In practical terms this should only
828 * happen with SORT BY command or if there is a bug in this function.
829 *
830 * Return 1 if the client is marked as blocked, 0 if the client can
831 * continue as the keys it is going to access appear to be in memory. */
832 int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd) {
833 if (cmd->vm_preload_proc != NULL) {
834 cmd->vm_preload_proc(c,cmd,c->argc,c->argv);
835 } else {
836 waitForMultipleSwappedKeys(c,cmd,c->argc,c->argv);
837 }
838
839 /* If the client was blocked for at least one key, mark it as blocked. */
840 if (listLength(c->io_keys)) {
841 c->flags |= REDIS_IO_WAIT;
842 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
843 server.cache_blocked_clients++;
844 return 1;
845 } else {
846 return 0;
847 }
848 }
849
850 /* Remove the 'key' from the list of blocked keys for a given client.
851 *
852 * The function returns 1 when there are no longer blocking keys after
853 * the current one was removed (and the client can be unblocked). */
854 int dontWaitForSwappedKey(redisClient *c, robj *key) {
855 list *l;
856 listNode *ln;
857 listIter li;
858 struct dictEntry *de;
859
860 /* The key object might be destroyed when deleted from the c->io_keys
861 * list (and the "key" argument is physically the same object as the
862 * object inside the list), so we need to protect it. */
863 incrRefCount(key);
864
865 /* Remove the key from the list of keys this client is waiting for. */
866 listRewind(c->io_keys,&li);
867 while ((ln = listNext(&li)) != NULL) {
868 if (equalStringObjects(ln->value,key)) {
869 listDelNode(c->io_keys,ln);
870 break;
871 }
872 }
873 redisAssert(ln != NULL);
874
875 /* Remove the client form the key => waiting clients map. */
876 de = dictFind(c->db->io_keys,key);
877 redisAssert(de != NULL);
878 l = dictGetEntryVal(de);
879 ln = listSearchKey(l,c);
880 redisAssert(ln != NULL);
881 listDelNode(l,ln);
882 if (listLength(l) == 0)
883 dictDelete(c->db->io_keys,key);
884
885 decrRefCount(key);
886 return listLength(c->io_keys) == 0;
887 }
888
889 /* Every time we now a key was loaded back in memory, we handle clients
890 * waiting for this key if any. */
891 void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key) {
892 struct dictEntry *de;
893 list *l;
894 listNode *ln;
895 int len;
896
897 de = dictFind(db->io_keys,key);
898 if (!de) return;
899
900 l = dictGetEntryVal(de);
901 len = listLength(l);
902 /* Note: we can't use something like while(listLength(l)) as the list
903 * can be freed by the calling function when we remove the last element. */
904 while (len--) {
905 ln = listFirst(l);
906 redisClient *c = ln->value;
907
908 if (dontWaitForSwappedKey(c,key)) {
909 /* Put the client in the list of clients ready to go as we
910 * loaded all the keys about it. */
911 listAddNodeTail(server.io_ready_clients,c);
912 }
913 }
914 }