xref: /memcached-1.4.29/items.c (revision fba0a891)
1 /* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2 #include "memcached.h"
3 #include <sys/stat.h>
4 #include <sys/socket.h>
5 #include <sys/signal.h>
6 #include <sys/resource.h>
7 #include <fcntl.h>
8 #include <netinet/in.h>
9 #include <errno.h>
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <time.h>
14 #include <assert.h>
15 
16 /* Forward Declarations */
17 static void item_link_q(item *it);
18 static void item_unlink_q(item *it);
19 
20 /*
21  * We only reposition items in the LRU queue if they haven't been repositioned
22  * in this many seconds. That saves us from churning on frequently-accessed
23  * items.
24  */
25 #define ITEM_UPDATE_INTERVAL 60
26 
27 #define LARGEST_ID 255
28 typedef struct {
29     unsigned int evicted;
30     rel_time_t evicted_time;
31     unsigned int outofmemory;
32     unsigned int tailrepairs;
33 } itemstats_t;
34 
35 static item *heads[LARGEST_ID];
36 static item *tails[LARGEST_ID];
37 static itemstats_t itemstats[LARGEST_ID];
38 static unsigned int sizes[LARGEST_ID];
39 
40 void item_init(void) {
41     int i;
42     memset(itemstats, 0, sizeof(itemstats_t) * LARGEST_ID);
43     for(i = 0; i < LARGEST_ID; i++) {
44         heads[i] = NULL;
45         tails[i] = NULL;
46         sizes[i] = 0;
47     }
48 }
49 
50 void item_stats_reset(void) {
51     pthread_mutex_lock(&cache_lock);
52     memset(itemstats, 0, sizeof(itemstats_t) * LARGEST_ID);
53     pthread_mutex_unlock(&cache_lock);
54 }
55 
56 
57 /* Get the next CAS id for a new item. */
58 uint64_t get_cas_id(void) {
59     static uint64_t cas_id = 0;
60     return ++cas_id;
61 }
62 
63 /* Enable this for reference-count debugging. */
64 #if 0
65 # define DEBUG_REFCNT(it,op) \
66                 fprintf(stderr, "item %x refcnt(%c) %d %c%c%c\n", \
67                         it, op, it->refcount, \
68                         (it->it_flags & ITEM_LINKED) ? 'L' : ' ', \
69                         (it->it_flags & ITEM_SLABBED) ? 'S' : ' ')
70 #else
71 # define DEBUG_REFCNT(it,op) while(0)
72 #endif
73 
74 /**
75  * Generates the variable-sized part of the header for an object.
76  *
77  * key     - The key
78  * nkey    - The length of the key
79  * flags   - key flags
80  * nbytes  - Number of bytes to hold value and addition CRLF terminator
81  * suffix  - Buffer for the "VALUE" line suffix (flags, size).
82  * nsuffix - The length of the suffix is stored here.
83  *
84  * Returns the total size of the header.
85  */
86 static size_t item_make_header(const uint8_t nkey, const int flags, const int nbytes,
87                      char *suffix, uint8_t *nsuffix) {
88     /* suffix is defined at 40 chars elsewhere.. */
89     *nsuffix = (uint8_t) snprintf(suffix, 40, " %d %d\r\n", flags, nbytes - 2);
90     return sizeof(item) + nkey + *nsuffix + nbytes;
91 }
92 
93 /*@null@*/
94 item *do_item_alloc(char *key, const size_t nkey, const int flags, const rel_time_t exptime, const int nbytes) {
95     uint8_t nsuffix;
96     item *it = NULL;
97     char suffix[40];
98     size_t ntotal = item_make_header(nkey + 1, flags, nbytes, suffix, &nsuffix);
99     if (settings.use_cas) {
100         ntotal += sizeof(uint64_t);
101     }
102 
103     unsigned int id = slabs_clsid(ntotal);
104     if (id == 0)
105         return 0;
106 
107     /* do a quick check if we have any expired items in the tail.. */
108     int tries = 50;
109     item *search;
110 
111     for (search = tails[id];
112          tries > 0 && search != NULL;
113          tries--, search=search->prev) {
114         if (search->refcount == 0 &&
115             (search->exptime != 0 && search->exptime < current_time)) {
116             it = search;
117             /* I don't want to actually free the object, just steal
118              * the item to avoid to grab the slab mutex twice ;-)
119              */
120             it->refcount = 1;
121             do_item_unlink(it);
122             /* Initialize the item block: */
123             it->slabs_clsid = 0;
124             it->refcount = 0;
125             break;
126         }
127     }
128 
129     if (it == NULL && (it = slabs_alloc(ntotal, id)) == NULL) {
130         /*
131         ** Could not find an expired item at the tail, and memory allocation
132         ** failed. Try to evict some items!
133         */
134         tries = 50;
135 
136         /* If requested to not push old items out of cache when memory runs out,
137          * we're out of luck at this point...
138          */
139 
140         if (settings.evict_to_free == 0) {
141             itemstats[id].outofmemory++;
142             return NULL;
143         }
144 
145         /*
146          * try to get one off the right LRU
147          * don't necessariuly unlink the tail because it may be locked: refcount>0
148          * search up from tail an item with refcount==0 and unlink it; give up after 50
149          * tries
150          */
151 
152         if (tails[id] == 0) {
153             itemstats[id].outofmemory++;
154             return NULL;
155         }
156 
157         for (search = tails[id]; tries > 0 && search != NULL; tries--, search=search->prev) {
158             if (search->refcount == 0) {
159                 if (search->exptime == 0 || search->exptime > current_time) {
160                     itemstats[id].evicted++;
161                     itemstats[id].evicted_time = current_time - search->time;
162                     STATS_LOCK();
163                     stats.evictions++;
164                     STATS_UNLOCK();
165                 }
166                 do_item_unlink(search);
167                 break;
168             }
169         }
170         it = slabs_alloc(ntotal, id);
171         if (it == 0) {
172             itemstats[id].outofmemory++;
173             /* Last ditch effort. There is a very rare bug which causes
174              * refcount leaks. We've fixed most of them, but it still happens,
175              * and it may happen in the future.
176              * We can reasonably assume no item can stay locked for more than
177              * three hours, so if we find one in the tail which is that old,
178              * free it anyway.
179              */
180             tries = 50;
181             for (search = tails[id]; tries > 0 && search != NULL; tries--, search=search->prev) {
182                 if (search->refcount != 0 && search->time + TAIL_REPAIR_TIME < current_time) {
183                     itemstats[id].tailrepairs++;
184                     search->refcount = 0;
185                     do_item_unlink(search);
186                     break;
187                 }
188             }
189             it = slabs_alloc(ntotal, id);
190             if (it == 0) {
191                 return NULL;
192             }
193         }
194     }
195 
196     assert(it->slabs_clsid == 0);
197 
198     it->slabs_clsid = id;
199 
200     assert(it != heads[it->slabs_clsid]);
201 
202     it->next = it->prev = it->h_next = 0;
203     it->refcount = 1;     /* the caller will have a reference */
204     DEBUG_REFCNT(it, '*');
205     it->it_flags = settings.use_cas ? ITEM_CAS : 0;
206     it->nkey = nkey;
207     it->nbytes = nbytes;
208     memcpy(ITEM_key(it), key, nkey);
209     it->exptime = exptime;
210     memcpy(ITEM_suffix(it), suffix, (size_t)nsuffix);
211     it->nsuffix = nsuffix;
212     return it;
213 }
214 
215 void item_free(item *it) {
216     size_t ntotal = ITEM_ntotal(it);
217     unsigned int clsid;
218     assert((it->it_flags & ITEM_LINKED) == 0);
219     assert(it != heads[it->slabs_clsid]);
220     assert(it != tails[it->slabs_clsid]);
221     assert(it->refcount == 0);
222 
223     /* so slab size changer can tell later if item is already free or not */
224     clsid = it->slabs_clsid;
225     it->slabs_clsid = 0;
226     it->it_flags |= ITEM_SLABBED;
227     DEBUG_REFCNT(it, 'F');
228     slabs_free(it, ntotal, clsid);
229 }
230 
231 /**
232  * Returns true if an item will fit in the cache (its size does not exceed
233  * the maximum for a cache entry.)
234  */
235 bool item_size_ok(const size_t nkey, const int flags, const int nbytes) {
236     char prefix[40];
237     uint8_t nsuffix;
238 
239     return slabs_clsid(item_make_header(nkey + 1, flags, nbytes,
240                                         prefix, &nsuffix)) != 0;
241 }
242 
243 static void item_link_q(item *it) { /* item is the new head */
244     item **head, **tail;
245     /* always true, warns: assert(it->slabs_clsid <= LARGEST_ID); */
246     assert((it->it_flags & ITEM_SLABBED) == 0);
247 
248     head = &heads[it->slabs_clsid];
249     tail = &tails[it->slabs_clsid];
250     assert(it != *head);
251     assert((*head && *tail) || (*head == 0 && *tail == 0));
252     it->prev = 0;
253     it->next = *head;
254     if (it->next) it->next->prev = it;
255     *head = it;
256     if (*tail == 0) *tail = it;
257     sizes[it->slabs_clsid]++;
258     return;
259 }
260 
261 static void item_unlink_q(item *it) {
262     item **head, **tail;
263     /* always true, warns: assert(it->slabs_clsid <= LARGEST_ID); */
264     head = &heads[it->slabs_clsid];
265     tail = &tails[it->slabs_clsid];
266 
267     if (*head == it) {
268         assert(it->prev == 0);
269         *head = it->next;
270     }
271     if (*tail == it) {
272         assert(it->next == 0);
273         *tail = it->prev;
274     }
275     assert(it->next != it);
276     assert(it->prev != it);
277 
278     if (it->next) it->next->prev = it->prev;
279     if (it->prev) it->prev->next = it->next;
280     sizes[it->slabs_clsid]--;
281     return;
282 }
283 
284 int do_item_link(item *it) {
285     MEMCACHED_ITEM_LINK(ITEM_key(it), it->nkey, it->nbytes);
286     assert((it->it_flags & (ITEM_LINKED|ITEM_SLABBED)) == 0);
287     assert(it->nbytes < (1024 * 1024));  /* 1MB max size */
288     it->it_flags |= ITEM_LINKED;
289     it->time = current_time;
290     assoc_insert(it);
291 
292     STATS_LOCK();
293     stats.curr_bytes += ITEM_ntotal(it);
294     stats.curr_items += 1;
295     stats.total_items += 1;
296     STATS_UNLOCK();
297 
298     /* Allocate a new CAS ID on link. */
299     ITEM_set_cas(it, (settings.use_cas) ? get_cas_id() : 0);
300 
301     item_link_q(it);
302 
303     return 1;
304 }
305 
306 void do_item_unlink(item *it) {
307     MEMCACHED_ITEM_UNLINK(ITEM_key(it), it->nkey, it->nbytes);
308     if ((it->it_flags & ITEM_LINKED) != 0) {
309         it->it_flags &= ~ITEM_LINKED;
310         STATS_LOCK();
311         stats.curr_bytes -= ITEM_ntotal(it);
312         stats.curr_items -= 1;
313         STATS_UNLOCK();
314         assoc_delete(ITEM_key(it), it->nkey);
315         item_unlink_q(it);
316         if (it->refcount == 0) item_free(it);
317     }
318 }
319 
320 void do_item_remove(item *it) {
321     MEMCACHED_ITEM_REMOVE(ITEM_key(it), it->nkey, it->nbytes);
322     assert((it->it_flags & ITEM_SLABBED) == 0);
323     if (it->refcount != 0) {
324         it->refcount--;
325         DEBUG_REFCNT(it, '-');
326     }
327     if (it->refcount == 0 && (it->it_flags & ITEM_LINKED) == 0) {
328         item_free(it);
329     }
330 }
331 
332 void do_item_update(item *it) {
333     MEMCACHED_ITEM_UPDATE(ITEM_key(it), it->nkey, it->nbytes);
334     if (it->time < current_time - ITEM_UPDATE_INTERVAL) {
335         assert((it->it_flags & ITEM_SLABBED) == 0);
336 
337         if ((it->it_flags & ITEM_LINKED) != 0) {
338             item_unlink_q(it);
339             it->time = current_time;
340             item_link_q(it);
341         }
342     }
343 }
344 
345 int do_item_replace(item *it, item *new_it) {
346     MEMCACHED_ITEM_REPLACE(ITEM_key(it), it->nkey, it->nbytes,
347                            ITEM_key(new_it), new_it->nkey, new_it->nbytes);
348     assert((it->it_flags & ITEM_SLABBED) == 0);
349 
350     do_item_unlink(it);
351     return do_item_link(new_it);
352 }
353 
354 /*@null@*/
355 char *do_item_cachedump(const unsigned int slabs_clsid, const unsigned int limit, unsigned int *bytes) {
356     unsigned int memlimit = 2 * 1024 * 1024;   /* 2MB max response size */
357     char *buffer;
358     unsigned int bufcurr;
359     item *it;
360     unsigned int len;
361     unsigned int shown = 0;
362     char key_temp[KEY_MAX_LENGTH + 1];
363     char temp[512];
364 
365     if (slabs_clsid > LARGEST_ID) return NULL;
366     it = heads[slabs_clsid];
367 
368     buffer = malloc((size_t)memlimit);
369     if (buffer == 0) return NULL;
370     bufcurr = 0;
371 
372     while (it != NULL && (limit == 0 || shown < limit)) {
373         assert(it->nkey <= KEY_MAX_LENGTH);
374         /* Copy the key since it may not be null-terminated in the struct */
375         strncpy(key_temp, ITEM_key(it), it->nkey);
376         key_temp[it->nkey] = 0x00; /* terminate */
377         len = snprintf(temp, sizeof(temp), "ITEM %s [%d b; %lu s]\r\n",
378                        key_temp, it->nbytes - 2,
379                        (unsigned long)it->exptime + process_started);
380         if (bufcurr + len + 6 > memlimit)  /* 6 is END\r\n\0 */
381             break;
382         strcpy(buffer + bufcurr, temp);
383         bufcurr += len;
384         shown++;
385         it = it->next;
386     }
387 
388     memcpy(buffer + bufcurr, "END\r\n", 6);
389     bufcurr += 5;
390 
391     *bytes = bufcurr;
392     return buffer;
393 }
394 
395 void do_item_stats(ADD_STAT add_stats, void *c) {
396     int i;
397     for (i = 0; i < LARGEST_ID; i++) {
398         if (tails[i] != NULL) {
399             const char *fmt = "items:%d:%s";
400             char key_str[128];
401             char val_str[256];
402             int klen = 0, vlen = 0;
403 
404             APPEND_NUM_FMT_STAT(fmt, i, "number", "%u", sizes[i]);
405             APPEND_NUM_FMT_STAT(fmt, i, "age", "%u", tails[i]->time);
406             APPEND_NUM_FMT_STAT(fmt, i, "evicted",
407                                 "%u", itemstats[i].evicted);
408             APPEND_NUM_FMT_STAT(fmt, i, "evicted_time",
409                                 "%u", itemstats[i].evicted_time);
410             APPEND_NUM_FMT_STAT(fmt, i, "outofmemory",
411                                 "%u", itemstats[i].outofmemory);
412             APPEND_NUM_FMT_STAT(fmt, i, "tailrepairs",
413                                 "%u", itemstats[i].tailrepairs);;
414         }
415     }
416 
417     /* getting here means both ascii and binary terminators fit */
418     add_stats(NULL, 0, NULL, 0, c);
419 }
420 
421 /** dumps out a list of objects of each size, with granularity of 32 bytes */
422 /*@null@*/
423 void do_item_stats_sizes(ADD_STAT add_stats, void *c) {
424 
425     /* max 1MB object, divided into 32 bytes size buckets */
426     const int num_buckets = 32768;
427     unsigned int *histogram = calloc(num_buckets, sizeof(int));
428 
429     if (histogram != NULL) {
430         int i;
431 
432         /* build the histogram */
433         for (i = 0; i < LARGEST_ID; i++) {
434             item *iter = heads[i];
435             while (iter) {
436                 int ntotal = ITEM_ntotal(iter);
437                 int bucket = ntotal / 32;
438                 if ((ntotal % 32) != 0) bucket++;
439                 if (bucket < num_buckets) histogram[bucket]++;
440                 iter = iter->next;
441             }
442         }
443 
444         /* write the buffer */
445         for (i = 0; i < num_buckets; i++) {
446             if (histogram[i] != 0) {
447                 char key[8];
448                 int klen = 0;
449                 klen = sprintf(key, "%d", i * 32);
450                 assert(klen < sizeof(key));
451                 APPEND_STAT(key, "%u", histogram[i]);
452             }
453         }
454         free(histogram);
455     }
456     add_stats(NULL, 0, NULL, 0, c);
457 }
458 
459 /** wrapper around assoc_find which does the lazy expiration logic */
460 item *do_item_get(const char *key, const size_t nkey) {
461     item *it = assoc_find(key, nkey);
462     int was_found = 0;
463 
464     if (settings.verbose > 2) {
465         if (it == NULL) {
466             fprintf(stderr, "> NOT FOUND %s", key);
467         } else {
468             fprintf(stderr, "> FOUND KEY %s", ITEM_key(it));
469             was_found++;
470         }
471     }
472 
473     if (it != NULL && settings.oldest_live != 0 && settings.oldest_live <= current_time &&
474         it->time <= settings.oldest_live) {
475         do_item_unlink(it);           /* MTSAFE - cache_lock held */
476         it = NULL;
477     }
478 
479     if (it == NULL && was_found) {
480         fprintf(stderr, " -nuked by flush");
481         was_found--;
482     }
483 
484     if (it != NULL && it->exptime != 0 && it->exptime <= current_time) {
485         do_item_unlink(it);           /* MTSAFE - cache_lock held */
486         it = NULL;
487     }
488 
489     if (it == NULL && was_found) {
490         fprintf(stderr, " -nuked by expire");
491         was_found--;
492     }
493 
494     if (it != NULL) {
495         it->refcount++;
496         DEBUG_REFCNT(it, '+');
497     }
498 
499     if (settings.verbose > 2)
500         fprintf(stderr, "\n");
501 
502     return it;
503 }
504 
505 /** returns an item whether or not it's expired. */
506 item *do_item_get_nocheck(const char *key, const size_t nkey) {
507     item *it = assoc_find(key, nkey);
508     if (it) {
509         it->refcount++;
510         DEBUG_REFCNT(it, '+');
511     }
512     return it;
513 }
514 
515 /* expires items that are more recent than the oldest_live setting. */
516 void do_item_flush_expired(void) {
517     int i;
518     item *iter, *next;
519     if (settings.oldest_live == 0)
520         return;
521     for (i = 0; i < LARGEST_ID; i++) {
522         /* The LRU is sorted in decreasing time order, and an item's timestamp
523          * is never newer than its last access time, so we only need to walk
524          * back until we hit an item older than the oldest_live time.
525          * The oldest_live checking will auto-expire the remaining items.
526          */
527         for (iter = heads[i]; iter != NULL; iter = next) {
528             if (iter->time >= settings.oldest_live) {
529                 next = iter->next;
530                 if ((iter->it_flags & ITEM_SLABBED) == 0) {
531                     do_item_unlink(iter);
532                 }
533             } else {
534                 /* We've hit the first old item. Continue to the next queue. */
535                 break;
536             }
537         }
538     }
539 }
540