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