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