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