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