xref: /memcached-1.4.29/items.c (revision 9150c85b)
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();
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 static item *heads[LARGEST_ID];
31 static item *tails[LARGEST_ID];
32 static unsigned int sizes[LARGEST_ID];
33 
34 void item_init(void) {
35     int i;
36     for(i = 0; i < LARGEST_ID; i++) {
37         heads[i] = NULL;
38         tails[i] = NULL;
39         sizes[i] = 0;
40     }
41 }
42 
43 /* Get the next CAS id for a new item. */
44 uint64_t get_cas_id() {
45     static uint64_t cas_id = 0;
46     return ++cas_id;
47 }
48 
49 /* Enable this for reference-count debugging. */
50 #if 0
51 # define DEBUG_REFCNT(it,op) \
52                 fprintf(stderr, "item %x refcnt(%c) %d %c%c%c\n", \
53                         it, op, it->refcount, \
54                         (it->it_flags & ITEM_LINKED) ? 'L' : ' ', \
55                         (it->it_flags & ITEM_SLABBED) ? 'S' : ' ', \
56                         (it->it_flags & ITEM_DELETED) ? 'D' : ' ')
57 #else
58 # define DEBUG_REFCNT(it,op) while(0)
59 #endif
60 
61 /**
62  * Generates the variable-sized part of the header for an object.
63  *
64  * key     - The key
65  * nkey    - The length of the key
66  * flags   - key flags
67  * nbytes  - Number of bytes to hold value and addition CRLF terminator
68  * suffix  - Buffer for the "VALUE" line suffix (flags, size).
69  * nsuffix - The length of the suffix is stored here.
70  *
71  * Returns the total size of the header.
72  */
73 static size_t item_make_header(const uint8_t nkey, const int flags, const int nbytes,
74                      char *suffix, uint8_t *nsuffix) {
75     /* suffix is defined at 40 chars elsewhere.. */
76     *nsuffix = (uint8_t) snprintf(suffix, 40, " %d %d\r\n", flags, nbytes - 2);
77     return sizeof(item) + nkey + *nsuffix + nbytes;
78 }
79 
80 /*@null@*/
81 item *do_item_alloc(char *key, const size_t nkey, const int flags, const rel_time_t exptime, const int nbytes) {
82     uint8_t nsuffix;
83     item *it;
84     char suffix[40];
85     size_t ntotal = item_make_header(nkey + 1, flags, nbytes, suffix, &nsuffix);
86 
87     unsigned int id = slabs_clsid(ntotal);
88     if (id == 0)
89         return 0;
90 
91     it = slabs_alloc(ntotal);
92     if (it == 0) {
93         int tries = 50;
94         item *search;
95 
96         /* If requested to not push old items out of cache when memory runs out,
97          * we're out of luck at this point...
98          */
99 
100         if (settings.evict_to_free == 0) return NULL;
101 
102         /*
103          * try to get one off the right LRU
104          * don't necessariuly unlink the tail because it may be locked: refcount>0
105          * search up from tail an item with refcount==0 and unlink it; give up after 50
106          * tries
107          */
108 
109         if (id > LARGEST_ID) return NULL;
110         if (tails[id] == 0) return NULL;
111 
112         for (search = tails[id]; tries > 0 && search != NULL; tries--, search=search->prev) {
113             if (search->refcount == 0) {
114                if (search->exptime == 0 || search->exptime > current_time) {
115                        STATS_LOCK();
116                        stats.evictions++;
117                        STATS_UNLOCK();
118                 }
119                 do_item_unlink(search);
120                 break;
121             }
122         }
123         it = slabs_alloc(ntotal);
124         if (it == 0) return NULL;
125     }
126 
127     assert(it->slabs_clsid == 0);
128 
129     it->slabs_clsid = id;
130 
131     assert(it != heads[it->slabs_clsid]);
132 
133     it->next = it->prev = it->h_next = 0;
134     it->refcount = 1;     /* the caller will have a reference */
135     DEBUG_REFCNT(it, '*');
136     it->it_flags = 0;
137     it->nkey = nkey;
138     it->nbytes = nbytes;
139     strcpy(ITEM_key(it), key);
140     it->exptime = exptime;
141     memcpy(ITEM_suffix(it), suffix, (size_t)nsuffix);
142     it->nsuffix = nsuffix;
143     return it;
144 }
145 
146 void item_free(item *it) {
147     size_t ntotal = ITEM_ntotal(it);
148     assert((it->it_flags & ITEM_LINKED) == 0);
149     assert(it != heads[it->slabs_clsid]);
150     assert(it != tails[it->slabs_clsid]);
151     assert(it->refcount == 0);
152 
153     /* so slab size changer can tell later if item is already free or not */
154     it->slabs_clsid = 0;
155     it->it_flags |= ITEM_SLABBED;
156     DEBUG_REFCNT(it, 'F');
157     slabs_free(it, ntotal);
158 }
159 
160 /**
161  * Returns true if an item will fit in the cache (its size does not exceed
162  * the maximum for a cache entry.)
163  */
164 bool item_size_ok(const size_t nkey, const int flags, const int nbytes) {
165     char prefix[40];
166     uint8_t nsuffix;
167 
168     return slabs_clsid(item_make_header(nkey + 1, flags, nbytes,
169                                         prefix, &nsuffix)) != 0;
170 }
171 
172 static void item_link_q(item *it) { /* item is the new head */
173     item **head, **tail;
174     /* always true, warns: assert(it->slabs_clsid <= LARGEST_ID); */
175     assert((it->it_flags & ITEM_SLABBED) == 0);
176 
177     head = &heads[it->slabs_clsid];
178     tail = &tails[it->slabs_clsid];
179     assert(it != *head);
180     assert((*head && *tail) || (*head == 0 && *tail == 0));
181     it->prev = 0;
182     it->next = *head;
183     if (it->next) it->next->prev = it;
184     *head = it;
185     if (*tail == 0) *tail = it;
186     sizes[it->slabs_clsid]++;
187     return;
188 }
189 
190 static void item_unlink_q(item *it) {
191     item **head, **tail;
192     /* always true, warns: assert(it->slabs_clsid <= LARGEST_ID); */
193     head = &heads[it->slabs_clsid];
194     tail = &tails[it->slabs_clsid];
195 
196     if (*head == it) {
197         assert(it->prev == 0);
198         *head = it->next;
199     }
200     if (*tail == it) {
201         assert(it->next == 0);
202         *tail = it->prev;
203     }
204     assert(it->next != it);
205     assert(it->prev != it);
206 
207     if (it->next) it->next->prev = it->prev;
208     if (it->prev) it->prev->next = it->next;
209     sizes[it->slabs_clsid]--;
210     return;
211 }
212 
213 int do_item_link(item *it) {
214     assert((it->it_flags & (ITEM_LINKED|ITEM_SLABBED)) == 0);
215     assert(it->nbytes < (1024 * 1024));  /* 1MB max size */
216     it->it_flags |= ITEM_LINKED;
217     it->time = current_time;
218     assoc_insert(it);
219 
220     STATS_LOCK();
221     stats.curr_bytes += ITEM_ntotal(it);
222     stats.curr_items += 1;
223     stats.total_items += 1;
224     STATS_UNLOCK();
225 
226     /* Allocate a new CAS ID on link. */
227     it->cas_id = get_cas_id();
228 
229     item_link_q(it);
230 
231     return 1;
232 }
233 
234 void do_item_unlink(item *it) {
235     if ((it->it_flags & ITEM_LINKED) != 0) {
236         it->it_flags &= ~ITEM_LINKED;
237         STATS_LOCK();
238         stats.curr_bytes -= ITEM_ntotal(it);
239         stats.curr_items -= 1;
240         STATS_UNLOCK();
241         assoc_delete(ITEM_key(it), it->nkey);
242         item_unlink_q(it);
243         if (it->refcount == 0) item_free(it);
244     }
245 }
246 
247 void do_item_remove(item *it) {
248     assert((it->it_flags & ITEM_SLABBED) == 0);
249     if (it->refcount != 0) {
250         it->refcount--;
251         DEBUG_REFCNT(it, '-');
252     }
253     assert((it->it_flags & ITEM_DELETED) == 0 || it->refcount != 0);
254     if (it->refcount == 0 && (it->it_flags & ITEM_LINKED) == 0) {
255         item_free(it);
256     }
257 }
258 
259 void do_item_update(item *it) {
260     if (it->time < current_time - ITEM_UPDATE_INTERVAL) {
261         assert((it->it_flags & ITEM_SLABBED) == 0);
262 
263         if ((it->it_flags & ITEM_LINKED) != 0) {
264             item_unlink_q(it);
265             it->time = current_time;
266             item_link_q(it);
267         }
268     }
269 }
270 
271 int do_item_replace(item *it, item *new_it) {
272     assert((it->it_flags & ITEM_SLABBED) == 0);
273 
274     do_item_unlink(it);
275     return do_item_link(new_it);
276 }
277 
278 /*@null@*/
279 char *do_item_cachedump(const unsigned int slabs_clsid, const unsigned int limit, unsigned int *bytes) {
280     unsigned int memlimit = 2 * 1024 * 1024;   /* 2MB max response size */
281     char *buffer;
282     unsigned int bufcurr;
283     item *it;
284     unsigned int len;
285     unsigned int shown = 0;
286     char temp[512];
287 
288     if (slabs_clsid > LARGEST_ID) return NULL;
289     it = heads[slabs_clsid];
290 
291     buffer = malloc((size_t)memlimit);
292     if (buffer == 0) return NULL;
293     bufcurr = 0;
294 
295     while (it != NULL && (limit == 0 || shown < limit)) {
296         len = snprintf(temp, sizeof(temp), "ITEM %s [%d b; %lu s]\r\n", ITEM_key(it), it->nbytes - 2, it->exptime + stats.started);
297         if (bufcurr + len + 6 > memlimit)  /* 6 is END\r\n\0 */
298             break;
299         strcpy(buffer + bufcurr, temp);
300         bufcurr += len;
301         shown++;
302         it = it->next;
303     }
304 
305     memcpy(buffer + bufcurr, "END\r\n", 6);
306     bufcurr += 5;
307 
308     *bytes = bufcurr;
309     return buffer;
310 }
311 
312 char *do_item_stats(int *bytes) {
313     size_t bufleft = (size_t) LARGEST_ID * 80;
314     char *buffer = malloc(bufleft);
315     char *bufcurr = buffer;
316     rel_time_t now = current_time;
317     int i;
318     int linelen;
319 
320     if (buffer == NULL) {
321         return NULL;
322     }
323 
324     for (i = 0; i < LARGEST_ID; i++) {
325         if (tails[i] != NULL) {
326             linelen = snprintf(bufcurr, bufleft, "STAT items:%d:number %u\r\nSTAT items:%d:age %u\r\n",
327                                i, sizes[i], i, now - tails[i]->time);
328             if (linelen + sizeof("END\r\n") < bufleft) {
329                 bufcurr += linelen;
330                 bufleft -= linelen;
331             }
332             else {
333                 /* The caller didn't allocate enough buffer space. */
334                 break;
335             }
336         }
337     }
338     memcpy(bufcurr, "END\r\n", 6);
339     bufcurr += 5;
340 
341     *bytes = bufcurr - buffer;
342     return buffer;
343 }
344 
345 /** dumps out a list of objects of each size, with granularity of 32 bytes */
346 /*@null@*/
347 char* do_item_stats_sizes(int *bytes) {
348     const int num_buckets = 32768;   /* max 1MB object, divided into 32 bytes size buckets */
349     unsigned int *histogram = (unsigned int *)malloc((size_t)num_buckets * sizeof(int));
350     char *buf = (char *)malloc(2 * 1024 * 1024); /* 2MB max response size */
351     int i;
352 
353     if (histogram == 0 || buf == 0) {
354         if (histogram) free(histogram);
355         if (buf) free(buf);
356         return NULL;
357     }
358 
359     /* build the histogram */
360     memset(histogram, 0, (size_t)num_buckets * sizeof(int));
361     for (i = 0; i < LARGEST_ID; i++) {
362         item *iter = heads[i];
363         while (iter) {
364             int ntotal = ITEM_ntotal(iter);
365             int bucket = ntotal / 32;
366             if ((ntotal % 32) != 0) bucket++;
367             if (bucket < num_buckets) histogram[bucket]++;
368             iter = iter->next;
369         }
370     }
371 
372     /* write the buffer */
373     *bytes = 0;
374     for (i = 0; i < num_buckets; i++) {
375         if (histogram[i] != 0) {
376             *bytes += sprintf(&buf[*bytes], "%d %u\r\n", i * 32, histogram[i]);
377         }
378     }
379     *bytes += sprintf(&buf[*bytes], "END\r\n");
380     free(histogram);
381     return buf;
382 }
383 
384 /** returns true if a deleted item's delete-locked-time is over, and it
385     should be removed from the namespace */
386 bool item_delete_lock_over (item *it) {
387     assert(it->it_flags & ITEM_DELETED);
388     return (current_time >= it->exptime);
389 }
390 
391 /** wrapper around assoc_find which does the lazy expiration/deletion logic */
392 item *do_item_get_notedeleted(const char *key, const size_t nkey, bool *delete_locked) {
393     item *it = assoc_find(key, nkey);
394     if (delete_locked) *delete_locked = false;
395     if (it != NULL && (it->it_flags & ITEM_DELETED)) {
396         /* it's flagged as delete-locked.  let's see if that condition
397            is past due, and the 5-second delete_timer just hasn't
398            gotten to it yet... */
399         if (!item_delete_lock_over(it)) {
400             if (delete_locked) *delete_locked = true;
401             it = NULL;
402         }
403     }
404     if (it != NULL && settings.oldest_live != 0 && settings.oldest_live <= current_time &&
405         it->time <= settings.oldest_live) {
406         do_item_unlink(it);           /* MTSAFE - cache_lock held */
407         it = NULL;
408     }
409     if (it != NULL && it->exptime != 0 && it->exptime <= current_time) {
410         do_item_unlink(it);           /* MTSAFE - cache_lock held */
411         it = NULL;
412     }
413 
414     if (it != NULL) {
415         it->refcount++;
416         DEBUG_REFCNT(it, '+');
417     }
418     return it;
419 }
420 
421 item *item_get(const char *key, const size_t nkey) {
422     return item_get_notedeleted(key, nkey, 0);
423 }
424 
425 /** returns an item whether or not it's delete-locked or expired. */
426 item *do_item_get_nocheck(const char *key, const size_t nkey) {
427     item *it = assoc_find(key, nkey);
428     if (it) {
429         it->refcount++;
430         DEBUG_REFCNT(it, '+');
431     }
432     return it;
433 }
434 
435 /* expires items that are more recent than the oldest_live setting. */
436 void do_item_flush_expired(void) {
437     int i;
438     item *iter, *next;
439     if (settings.oldest_live == 0)
440         return;
441     for (i = 0; i < LARGEST_ID; i++) {
442         /* The LRU is sorted in decreasing time order, and an item's timestamp
443          * is never newer than its last access time, so we only need to walk
444          * back until we hit an item older than the oldest_live time.
445          * The oldest_live checking will auto-expire the remaining items.
446          */
447         for (iter = heads[i]; iter != NULL; iter = next) {
448             if (iter->time >= settings.oldest_live) {
449                 next = iter->next;
450                 if ((iter->it_flags & ITEM_SLABBED) == 0) {
451                     do_item_unlink(iter);
452                 }
453             } else {
454                 /* We've hit the first old item. Continue to the next queue. */
455                 break;
456             }
457         }
458     }
459 }
460