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