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