source: lib/data-struct/object_cache.c @ 0a474e3

develop
Last change on this file since 0a474e3 was 0a474e3, checked in by Jacob Van Walraven <jcv9@…>, 2 years ago

And more..

  • Property mode set to 100644
File size: 17.8 KB
Line 
1/*
2 *
3 * Copyright (c) 2007-2016 The University of Waikato, Hamilton, New Zealand.
4 * All rights reserved.
5 *
6 * This file is part of libtrace.
7 *
8 * This code has been developed by the University of Waikato WAND
9 * research group. For further information please see http://www.wand.net.nz/
10 *
11 * libtrace is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation; either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * libtrace is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 * GNU Lesser General Public License for more details.
20 *
21 * You should have received a copy of the GNU Lesser General Public License
22 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 *
24 *
25 */
26#include "config.h"
27#include "object_cache.h"
28#include <assert.h>
29#include <stdio.h>
30#include <stdlib.h>
31#include <string.h>
32
33
34// pthread tls is most likely slower than __thread, but they have destructors so
35// we use a combination of the two here!!
36// Note Apples implementation of TLS means that memory is not available / has
37// been zeroed by the time the pthread destructor is called.
38struct local_cache {
39        libtrace_ocache_t *oc;
40        size_t total;
41        size_t used;
42        void **cache;
43        bool invalid;
44};
45
46struct mem_stats {
47        struct memfail {
48           uint64_t cache_hit;
49           uint64_t ring_hit;
50           uint64_t miss;
51           uint64_t recycled;
52        } readbulk, read, write, writebulk;
53};
54
55#ifdef ENABLE_MEM_STATS
56extern __thread struct mem_stats mem_hits;
57#endif
58
59struct local_caches {
60        size_t t_mem_caches_used;
61        size_t t_mem_caches_total;
62        struct local_cache *t_mem_caches;
63};
64
65static pthread_key_t memory_destructor_key;
66static pthread_once_t memory_destructor_once = PTHREAD_ONCE_INIT;
67static inline struct local_caches *get_local_caches();
68
69/**
70 * @brief unregister_thread assumes we DONT hold spin
71 */
72static inline void unregister_thread(struct local_cache *lc) {
73        size_t i;
74        if (lc->invalid)
75                fprintf(stderr, "Already free'd the thread cache!!\n");
76        pthread_spin_lock(&lc->oc->spin);
77        // Remove it from our thread list
78        for (i=0; i < lc->oc->nb_thread_list; ++i) {
79                if (lc->oc->thread_list[i] == lc) {
80                        --lc->oc->nb_thread_list;
81                        lc->oc->thread_list[i] = lc->oc->thread_list[lc->oc->nb_thread_list];
82                        lc->oc->thread_list[lc->oc->nb_thread_list] = NULL;
83                        i = ~0U;
84                        break;
85                }
86        }
87        if (i != ~0U) {
88                fprintf(stderr, "Attempted to unregistered a thread with an"
89                         " ocache that had never registered this thread. Ignoring.\n");
90                pthread_spin_unlock(&lc->oc->spin);
91                return;
92        }
93        lc->invalid = true;
94
95        if (lc->oc->max_allocations) {
96                libtrace_ringbuffer_swrite_bulk(&lc->oc->rb, lc->cache, lc->used, lc->used);
97        } else {
98                size_t i;
99                // We just run the free these
100                for(i = 0; i < lc->used; ++i) {
101                        lc->oc->free(lc->cache[i]);
102                }
103        }
104        pthread_spin_unlock(&lc->oc->spin);
105}
106
107/**
108 * @brief register_thread assumes we DONT hold spin
109 */
110static inline void register_thread(libtrace_ocache_t *oc, struct local_cache *lc) {
111        lc->invalid = false;
112        pthread_spin_lock(&oc->spin);
113        if (oc->nb_thread_list == oc->max_nb_thread_list) {
114                oc->max_nb_thread_list += 0x10;
115                oc->thread_list = realloc(oc->thread_list, sizeof(void*) * oc->max_nb_thread_list);
116        }
117        oc->thread_list[oc->nb_thread_list] = lc;
118        ++oc->nb_thread_list;
119        pthread_spin_unlock(&oc->spin);
120}
121
122static void destroy_memory_caches(void *tlsaddr) {
123        size_t a;
124        struct local_caches *lcs = tlsaddr;
125
126        for (a = 0; a < lcs->t_mem_caches_used; ++a) {
127                unregister_thread(&lcs->t_mem_caches[a]);
128                // Write these all back to the main buffer, this might have issues we would want to free these
129                free(lcs->t_mem_caches[a].cache);
130        }
131        free(lcs->t_mem_caches);
132        lcs->t_mem_caches = NULL;
133        free(lcs);
134
135}
136
137static void once_memory_cache_key_init() {
138        ASSERT_RET(pthread_key_create(&memory_destructor_key, &destroy_memory_caches), == 0);
139}
140
141/**
142 * Adds more space to our mem_caches
143 */
144static void resize_memory_caches(struct local_caches *lcs) {
145        /*assert (lcs->t_mem_caches_total > 0);*/
146        if (lcs->t_mem_caches_total <= 0) {
147
148        }
149        lcs->t_mem_caches += 0x10;
150        lcs->t_mem_caches = realloc(lcs->t_mem_caches,
151                                    lcs->t_mem_caches_total * sizeof(struct local_cache));
152}
153
154/* Get TLS for the list of local_caches */
155static inline struct local_caches *get_local_caches() {
156#if HAVE_TLS
157        static __thread struct local_caches *lcs = NULL;
158        if (lcs) {
159                return lcs;
160        }
161#else
162        struct local_caches *lcs;
163        pthread_once(&memory_destructor_once, &once_memory_cache_key_init);
164        if ((lcs=pthread_getspecific(memory_destructor_key)) != 0) {
165                return lcs;
166        }
167#endif
168        else {
169                /* This thread has not been used with a memory pool before */
170                /* Allocate our TLS */
171                /*assert(lcs == NULL);*/
172                if (lcs) {
173                        fprintf(stderr, "Expected lcs to be NULL in get_local_caches()\n");
174                        return NULL;
175                }
176                lcs = calloc(1, sizeof (struct local_caches));
177                /*assert(lcs);*/
178                if (!lcs) {
179                        fprintf(stderr, "Unable to allocate memory for lcs in get_local_caches()\n");
180                        return NULL;
181                }
182                /* Hook into pthreads to destroy this when the thread ends */
183                pthread_once(&memory_destructor_once, &once_memory_cache_key_init);
184                pthread_setspecific(memory_destructor_key, (void *) lcs);
185                lcs->t_mem_caches_total = 0x10;
186                lcs->t_mem_caches = calloc(0x10, sizeof(struct local_cache));
187                /*assert(lcs);*/
188                /*assert(lcs->t_mem_caches);*/
189                if (!lcs->t_mem_caches) {
190                        fprintf(stderr, "Unable to allocate memory for lcs->t_mem_caches in get_local_cahces()\n");
191                        return NULL;
192                }
193                return lcs;
194        }
195}
196
197static inline struct local_cache * find_cache(libtrace_ocache_t *oc) {
198        size_t i;
199        struct local_cache *lc = NULL;
200        struct local_caches *lcs = get_local_caches();
201
202        for (i = 0; i < lcs->t_mem_caches_used; ++i) {
203                if (lcs->t_mem_caches[i].oc == oc) {
204                        lc = &lcs->t_mem_caches[i];
205                        break;
206                }
207        }
208
209        if (!oc->thread_cache_size)
210                return 0;
211
212        // Create a cache
213        if (!lc) {
214                if (lcs->t_mem_caches_used == lcs->t_mem_caches_total)
215                        resize_memory_caches(lcs);
216                lcs->t_mem_caches[lcs->t_mem_caches_used].oc = oc;
217                lcs->t_mem_caches[lcs->t_mem_caches_used].used = 0;
218                lcs->t_mem_caches[lcs->t_mem_caches_used].total = oc->thread_cache_size;
219                lcs->t_mem_caches[lcs->t_mem_caches_used].cache = malloc(sizeof(void*) * oc->thread_cache_size);
220                lcs->t_mem_caches[lcs->t_mem_caches_used].invalid = false;
221                lc = &lcs->t_mem_caches[lcs->t_mem_caches_used];
222                // Register it with the underlying ring_buffer
223                register_thread(lc->oc, lc);
224                ++lcs->t_mem_caches_used;
225        }
226
227        /*assert(!lc->invalid);*/
228        if (lc->invalid) {
229                fprintf(stderr, "lc cache is invalid in find_cache()\n");
230                return NULL;
231        }
232        return lc;
233}
234
235/**
236  * Creates a object cache, that is a pool of dynamically allocated and recycled
237  * objects of a fixed size. This should be faster than malloc and free.
238  * The alloc and free methods are supplied by the user and are used when no
239  * recycled objects are available, or to tidy the final results.
240  *
241  * The performance of these pools will decrease if thread caches are used
242  * as this results in a list to lookup per thread. The pool is added when
243  * to this list when first encountered, these persist untill the thread exits.
244  *
245  * NOTE: If limit_size is true do not attempt to 'free' any objects that were
246  * not created by this pool back otherwise the 'free' might deadlock. Also
247  * be cautious when picking the buffer size, upto thread_cache_size*(threads-1)
248  * could be unusable at any given time if these are stuck in thread local caches.
249  *
250  * @param oc A pointer to the object cache structure which is to be initialised.
251  * @param alloc The allocation method, must not be NULL. [void *alloc()]
252  * @param free The free method used to destroy packets. [void free(void * obj)]
253  * @param thread_cache_size A small cache kept on a per thread basis, this can be 0
254  *             however should only be done if bulk reads of packets are being performed
255  *             or contention is minimal.
256  * @param buffer_size The number of packets to be stored in the main buffer.
257  * @param limit_size If true no more objects than buffer_size will be allocated,
258  *             reads will block (free never should).Otherwise packets can be freely
259  *     allocated upon requested and are free'd if there is not enough space for them.
260  * @return If successful returns 0 otherwise -1.
261  */
262DLLEXPORT int libtrace_ocache_init(libtrace_ocache_t *oc, void *(*alloc)(void),
263                                    void (*free)(void *),
264                                    size_t thread_cache_size,
265                                    size_t buffer_size, bool limit_size) {
266
267        /*assert(buffer_size);*/
268        if (!buffer_size) {
269                fprintf(stderr, "NULL bugger_size passed into libtrace_ocache_init()\n");
270                return -1;
271        }
272        /*assert(alloc);*/
273        if (!alloc) {
274                fprintf(stderr, "NULL alloc passed into libtrace_ocache_init()\n");
275                return -1;
276        }
277        /*assert(free);*/
278        if (!free) {
279                fprintf(stderr, "NULL free method passed into libtrace_ocache_init()\n");
280                return -1;
281        }
282        if (libtrace_ringbuffer_init(&oc->rb, buffer_size, LIBTRACE_RINGBUFFER_BLOCKING) != 0) {
283                return -1;
284        }
285        oc->alloc = alloc;
286        oc->free = free;
287        oc->current_allocations = 0;
288        oc->thread_cache_size = thread_cache_size;
289        oc->nb_thread_list = 0;
290        oc->max_nb_thread_list = 0x10;
291        oc->thread_list = calloc(0x10, sizeof(void*));
292        if (oc->thread_list == NULL) {
293                libtrace_ringbuffer_destroy(&oc->rb);
294                return -1;
295        }
296        pthread_spin_init(&oc->spin, 0);
297        if (limit_size)
298                oc->max_allocations = buffer_size;
299        else
300                oc->max_allocations = 0;
301        return 0;
302}
303
304/**
305  * Destroys the object cache. Call this only once all memory has
306  * been free'd back and no more accesses will be made.
307  *
308  * @return Returns the number of packets outstanding, or extra object recevied
309  *             Ideally this should be zero (0) otherwise some form of memory leak
310  *             is likely present. Currenty only implemented in the case limit_size
311  *     is true.
312  */
313DLLEXPORT int libtrace_ocache_destroy(libtrace_ocache_t *oc) {
314        void *ele;
315
316        while (oc->nb_thread_list)
317                unregister_thread(oc->thread_list[0]);
318
319        pthread_spin_lock(&oc->spin);
320        while (libtrace_ringbuffer_try_read(&oc->rb, &ele)) {
321                oc->free(ele);
322                if (oc->max_allocations)
323                        --oc->current_allocations;
324        }
325        pthread_spin_unlock(&oc->spin);
326
327        if (oc->current_allocations)
328                fprintf(stderr, "OCache destroyed, leaking %d packets!!\n", (int) oc->current_allocations);
329
330        libtrace_ringbuffer_destroy(&oc->rb);
331        pthread_spin_destroy(&oc->spin);
332        free(oc->thread_list);
333        libtrace_zero_ocache(oc);
334        if (oc->current_allocations)
335                return (int) oc->current_allocations;
336        else
337                return 0;
338}
339
340static inline size_t libtrace_ocache_alloc_cache(libtrace_ocache_t *oc, void *values[], size_t nb_buffers, size_t min_nb_buffers,
341                                                                                 struct local_cache *lc) {
342        libtrace_ringbuffer_t *rb = &oc->rb;
343        size_t i;
344
345        // We have enough cached!! Yay
346        if (nb_buffers <= lc->used) {
347                // Copy all from cache
348                memcpy(values, &lc->cache[lc->used - nb_buffers], sizeof(void *) * nb_buffers);
349                lc->used -= nb_buffers;
350#ifdef ENABLE_MEM_STATS
351                mem_hits.read.cache_hit += nb_buffers;
352                mem_hits.readbulk.cache_hit += 1;
353#endif
354                return nb_buffers;
355        }
356        // Cache is not big enough try read all from ringbuffer
357        else if (nb_buffers > lc->total) {
358                i = libtrace_ringbuffer_sread_bulk(rb, values, nb_buffers, min_nb_buffers);
359#ifdef ENABLE_MEM_STATS
360                if (i)
361                        mem_hits.readbulk.ring_hit += 1;
362                else
363                        mem_hits.readbulk.miss += 1;
364                mem_hits.read.ring_hit += i;
365#endif
366        } else { // Not enough cached
367                // Empty the cache and re-fill it and then see what we're left with
368                i = lc->used;
369                memcpy(values, lc->cache, sizeof(void *) * lc->used);
370#ifdef ENABLE_MEM_STATS
371                mem_hits.read.cache_hit += i;
372#endif
373
374                // Make sure we still meet the minimum requirement
375                if (i < min_nb_buffers)
376                        lc->used = libtrace_ringbuffer_sread_bulk(rb, lc->cache, lc->total, min_nb_buffers - i);
377                else
378                        lc->used = libtrace_ringbuffer_sread_bulk(rb, lc->cache, lc->total, 0);
379#ifdef ENABLE_MEM_STATS
380                if (lc->used == lc->total)
381                        mem_hits.readbulk.ring_hit += 1;
382                else
383                        mem_hits.readbulk.miss += 1;
384                mem_hits.read.ring_hit += lc->used;
385#endif
386        }
387
388        // Try fill the remaining
389        if (i < nb_buffers && lc->used) {
390                size_t remaining;
391                remaining = MIN(lc->used, nb_buffers - i);
392                memcpy(&values[i], &lc->cache[lc->used - remaining], sizeof(void *) * remaining);
393                lc->used -= remaining;
394                i += remaining;
395        }
396#ifdef ENABLE_MEM_STATS
397        mem_hits.read.miss += nb_buffers - i;
398#endif
399        /*assert(i >= min_nb_buffers);*/
400        if (i < min_nb_buffers) {
401                fprintf(stderr, "Unable to fill remaining cache in libtrace_ocache_alloc_cache()\n");
402                return ~0U;
403        }
404        return i;
405}
406
407DLLEXPORT size_t libtrace_ocache_alloc(libtrace_ocache_t *oc, void *values[], size_t nb_buffers, size_t min_nb_buffers) {
408        struct local_cache *lc = find_cache(oc);
409        size_t i;
410        size_t min;
411        bool try_alloc = !(oc->max_allocations && oc->max_allocations <= oc->current_allocations);
412
413        assert(oc->max_allocations ? nb_buffers < oc->max_allocations : 1);
414        min = try_alloc ? 0: min_nb_buffers;
415        if (lc)
416                i = libtrace_ocache_alloc_cache(oc, values, nb_buffers, min,  lc);
417        else
418                i = libtrace_ringbuffer_sread_bulk(&oc->rb, values, nb_buffers, min);
419
420        if (try_alloc) {
421                size_t nb;
422
423                // Try alloc the rest
424                if (oc->max_allocations) {
425                        pthread_spin_lock(&oc->spin);
426                        nb = MIN(oc->max_allocations - oc->current_allocations, nb_buffers - i);
427                        oc->current_allocations += nb;
428                        pthread_spin_unlock(&oc->spin);
429                        nb += i;
430                } else {
431                        nb = nb_buffers;
432                }
433
434                for (;i < nb; ++i) {
435                        values[i] = (*oc->alloc)();
436                        /*assert(values[i]);*/
437                        if (!values[i]) {
438                                fprintf(stderr, "Unable to alloc memory for values[%zu] in libtrace_ocache_alloc()\n", i);
439                                return ~0U;
440                        }
441                }
442                /*assert (i == nb);*/
443                if (i != nb) {
444                        fprintf(stderr, "Expected i == nb in libtrace_ocache_alloc()\n");
445                        return ~0U;
446                }
447                // Still got to wait for more
448                if (nb < min_nb_buffers) {
449                        if (lc)
450                                i += libtrace_ocache_alloc_cache(oc, &values[nb], nb_buffers - nb, min_nb_buffers - nb, lc);
451                        else
452                                i += libtrace_ringbuffer_sread_bulk(&oc->rb, &values[nb], nb_buffers - nb, min_nb_buffers - nb);
453                }
454        }
455        /*assert(i >= min_nb_buffers);*/
456        if (i < min_nb_buffers) {
457                fprintf(stderr, "Expected min_nb_buffers to be equal or less than i in libtrace_ocache_alloc()\n");
458                return ~0U;
459        }
460        return i;
461}
462
463
464static inline size_t libtrace_ocache_free_cache(libtrace_ocache_t *oc, void *values[], size_t nb_buffers, size_t min_nb_buffers,
465                                                                                        struct local_cache *lc) {
466        libtrace_ringbuffer_t *rb = &oc->rb;
467        size_t i;
468
469        // We have enough cached!! Yay
470        if (nb_buffers <= lc->total - lc->used) {
471                // Copy all to the cache
472                memcpy(&lc->cache[lc->used], values, sizeof(void *) * nb_buffers);
473                lc->used += nb_buffers;
474#ifdef ENABLE_MEM_STATS
475                mem_hits.write.cache_hit += nb_buffers;
476                mem_hits.writebulk.cache_hit += 1;
477#endif
478                return nb_buffers;
479        }
480        // Cache is not big enough try write all to the ringbuffer
481        else if (nb_buffers > lc->total) {
482                i = libtrace_ringbuffer_swrite_bulk(rb, values, nb_buffers, min_nb_buffers);
483#ifdef ENABLE_MEM_STATS
484                if (i)
485                        mem_hits.writebulk.ring_hit += 1;
486                else
487                        mem_hits.writebulk.miss += 1;
488                mem_hits.write.ring_hit += i;
489#endif
490        } else { // Not enough cache space but there might later
491                // Fill the cache and empty it and then see what we're left with
492                i = (lc->total - lc->used);
493                memcpy(&lc->cache[lc->used], values, sizeof(void *) * i);
494#ifdef ENABLE_MEM_STATS
495                mem_hits.write.cache_hit += i;
496#endif
497
498                // Make sure we still meet the minimum requirement
499                if (i < min_nb_buffers)
500                        lc->used = lc->total - libtrace_ringbuffer_swrite_bulk(rb, lc->cache, lc->total, min_nb_buffers - i);
501                else
502                        lc->used = lc->total - libtrace_ringbuffer_swrite_bulk(rb, lc->cache, lc->total, 0);
503
504                // Re originise fulls to the front
505                if (lc->used)
506                        memmove(lc->cache, &lc->cache[lc->total - lc->used], sizeof(void *) * lc->used);
507
508#ifdef ENABLE_MEM_STATS
509                if (lc->used)
510                        mem_hits.writebulk.miss += 1;
511                else
512                        mem_hits.writebulk.ring_hit += 1;
513                mem_hits.write.ring_hit += lc->total - lc->used;
514#endif
515        }
516
517        // Try empty the remaining
518        if (i < nb_buffers && lc->used != lc->total) {
519                size_t remaining;
520                remaining = MIN(lc->total - lc->used, nb_buffers - i);
521                memcpy(&lc->cache[lc->used], &values[i], sizeof(void *) * remaining);
522                lc->used += remaining;
523                i += remaining;
524        }
525#ifdef ENABLE_MEM_STATS
526        mem_hits.write.miss += nb_buffers - i;
527#endif
528        return i;
529}
530
531DLLEXPORT size_t libtrace_ocache_free(libtrace_ocache_t *oc, void *values[], size_t nb_buffers, size_t min_nb_buffers) {
532        struct local_cache *lc = find_cache(oc);
533        size_t i;
534        size_t min;
535
536        assert(oc->max_allocations ? nb_buffers < oc->max_allocations : 1);
537        min = oc->max_allocations ? min_nb_buffers : 0;
538        if (lc)
539                i = libtrace_ocache_free_cache(oc, values, nb_buffers, min, lc);
540        else
541                i = libtrace_ringbuffer_swrite_bulk(&oc->rb, values, nb_buffers, min);
542
543        if (!oc->max_allocations) {
544                // Free these normally
545                for (;i < min_nb_buffers; ++i) {
546                        oc->free(values[i]);
547                }
548        }
549        return i;
550}
551
552DLLEXPORT void libtrace_zero_ocache(libtrace_ocache_t *oc) {
553        libtrace_zero_ringbuffer(&oc->rb);
554        oc->thread_cache_size = 0;
555        oc->alloc = NULL;
556        oc->free = NULL;
557        oc->current_allocations = 0;
558        oc->max_allocations = 0;
559        oc->nb_thread_list = 0;
560        oc->max_nb_thread_list = 0;
561        oc->thread_list = NULL;
562}
563
564/**
565 * @brief ocache_unregister_thread removes a thread from an ocache.
566 * @param The ocache to remove this thread, this will free any packets in the TLS cache
567 */
568DLLEXPORT void libtrace_ocache_unregister_thread(libtrace_ocache_t *oc) {
569        size_t i;
570        struct local_caches *lcs = get_local_caches();
571        struct local_cache *lc = find_cache(oc);
572
573        if (lc) {
574                for (i = 0; i < lcs->t_mem_caches_used; ++i) {
575                        if (&lcs->t_mem_caches[i] == lc) {
576                                // Free the cache against the ocache
577                                unregister_thread(&lcs->t_mem_caches[i]);
578                                free(lcs->t_mem_caches[i].cache);
579                                // And remove it from the thread itself
580                                --lcs->t_mem_caches_used;
581                                lcs->t_mem_caches[i] = lcs->t_mem_caches[lcs->t_mem_caches_used];
582                                memset(&lcs->t_mem_caches[lcs->t_mem_caches_used], 0, sizeof(struct local_cache));
583                        }
584                }
585        }
586}
Note: See TracBrowser for help on using the repository browser.