source: lib/data-struct/object_cache.c @ ee6e802

4.0.1-hotfixescachetimestampsdevelopdpdk-ndagetsilivendag_formatrc-4.0.1rc-4.0.2rc-4.0.3rc-4.0.4ringdecrementfixringperformanceringtimestampfixes
Last change on this file since ee6e802 was ee6e802, checked in by Shane Alcock <salcock@…>, 4 years ago

Updated copyright blurb on all source files

In some cases, this meant adding copyright blurbs to files that
had never had them before.

  • Property mode set to 100644
File size: 16.5 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        lcs->t_mem_caches += 0x10;
147        lcs->t_mem_caches = realloc(lcs->t_mem_caches,
148                                    lcs->t_mem_caches_total * sizeof(struct local_cache));
149}
150
151/* Get TLS for the list of local_caches */
152static inline struct local_caches *get_local_caches() {
153#if HAVE_TLS
154        static __thread struct local_caches *lcs = NULL;
155        if (lcs) {
156                return lcs;
157        }
158#else
159        struct local_caches *lcs;
160        pthread_once(&memory_destructor_once, &once_memory_cache_key_init);
161        if ((lcs=pthread_getspecific(memory_destructor_key)) != 0) {
162                return lcs;
163        }
164#endif
165        else {
166                /* This thread has not been used with a memory pool before */
167                /* Allocate our TLS */
168                assert(lcs == NULL);
169                lcs = calloc(1, sizeof (struct local_caches));
170                assert(lcs);
171                /* Hook into pthreads to destroy this when the thread ends */
172                pthread_once(&memory_destructor_once, &once_memory_cache_key_init);
173                pthread_setspecific(memory_destructor_key, (void *) lcs);
174                lcs->t_mem_caches_total = 0x10;
175                lcs->t_mem_caches = calloc(0x10, sizeof(struct local_cache));
176                assert(lcs);
177                assert(lcs->t_mem_caches);
178                return lcs;
179        }
180}
181
182static inline struct local_cache * find_cache(libtrace_ocache_t *oc) {
183        size_t i;
184        struct local_cache *lc = NULL;
185        struct local_caches *lcs = get_local_caches();
186
187        for (i = 0; i < lcs->t_mem_caches_used; ++i) {
188                if (lcs->t_mem_caches[i].oc == oc) {
189                        lc = &lcs->t_mem_caches[i];
190                        break;
191                }
192        }
193
194        if (!oc->thread_cache_size)
195                return 0;
196
197        // Create a cache
198        if (!lc) {
199                if (lcs->t_mem_caches_used == lcs->t_mem_caches_total)
200                        resize_memory_caches(lcs);
201                lcs->t_mem_caches[lcs->t_mem_caches_used].oc = oc;
202                lcs->t_mem_caches[lcs->t_mem_caches_used].used = 0;
203                lcs->t_mem_caches[lcs->t_mem_caches_used].total = oc->thread_cache_size;
204                lcs->t_mem_caches[lcs->t_mem_caches_used].cache = malloc(sizeof(void*) * oc->thread_cache_size);
205                lcs->t_mem_caches[lcs->t_mem_caches_used].invalid = false;
206                lc = &lcs->t_mem_caches[lcs->t_mem_caches_used];
207                // Register it with the underlying ring_buffer
208                register_thread(lc->oc, lc);
209                ++lcs->t_mem_caches_used;
210        }
211
212        assert(!lc->invalid);
213        return lc;
214}
215
216/**
217  * Creates a object cache, that is a pool of dynamically allocated and recycled
218  * objects of a fixed size. This should be faster than malloc and free.
219  * The alloc and free methods are supplied by the user and are used when no
220  * recycled objects are available, or to tidy the final results.
221  *
222  * The performance of these pools will decrease if thread caches are used
223  * as this results in a list to lookup per thread. The pool is added when
224  * to this list when first encountered, these persist untill the thread exits.
225  *
226  * NOTE: If limit_size is true do not attempt to 'free' any objects that were
227  * not created by this pool back otherwise the 'free' might deadlock. Also
228  * be cautious when picking the buffer size, upto thread_cache_size*(threads-1)
229  * could be unusable at any given time if these are stuck in thread local caches.
230  *
231  * @param oc A pointer to the object cache structure which is to be initialised.
232  * @param alloc The allocation method, must not be NULL. [void *alloc()]
233  * @param free The free method used to destroy packets. [void free(void * obj)]
234  * @param thread_cache_size A small cache kept on a per thread basis, this can be 0
235  *             however should only be done if bulk reads of packets are being performed
236  *             or contention is minimal.
237  * @param buffer_size The number of packets to be stored in the main buffer.
238  * @param limit_size If true no more objects than buffer_size will be allocated,
239  *             reads will block (free never should).Otherwise packets can be freely
240  *     allocated upon requested and are free'd if there is not enough space for them.
241  * @return If successful returns 0 otherwise -1.
242  */
243DLLEXPORT int libtrace_ocache_init(libtrace_ocache_t *oc, void *(*alloc)(void),
244                                    void (*free)(void *),
245                                    size_t thread_cache_size,
246                                    size_t buffer_size, bool limit_size) {
247
248        assert(buffer_size);
249        assert(alloc);
250        assert(free);
251        if (libtrace_ringbuffer_init(&oc->rb, buffer_size, LIBTRACE_RINGBUFFER_BLOCKING) != 0) {
252                return -1;
253        }
254        oc->alloc = alloc;
255        oc->free = free;
256        oc->current_allocations = 0;
257        oc->thread_cache_size = thread_cache_size;
258        oc->nb_thread_list = 0;
259        oc->max_nb_thread_list = 0x10;
260        oc->thread_list = calloc(0x10, sizeof(void*));
261        if (oc->thread_list == NULL) {
262                libtrace_ringbuffer_destroy(&oc->rb);
263                return -1;
264        }
265        pthread_spin_init(&oc->spin, 0);
266        if (limit_size)
267                oc->max_allocations = buffer_size;
268        else
269                oc->max_allocations = 0;
270        return 0;
271}
272
273/**
274  * Destroys the object cache. Call this only once all memory has
275  * been free'd back and no more accesses will be made.
276  *
277  * @return Returns the number of packets outstanding, or extra object recevied
278  *             Ideally this should be zero (0) otherwise some form of memory leak
279  *             is likely present. Currenty only implemented in the case limit_size
280  *     is true.
281  */
282DLLEXPORT int libtrace_ocache_destroy(libtrace_ocache_t *oc) {
283        void *ele;
284
285        while (oc->nb_thread_list)
286                unregister_thread(oc->thread_list[0]);
287
288        pthread_spin_lock(&oc->spin);
289        while (libtrace_ringbuffer_try_read(&oc->rb, &ele)) {
290                oc->free(ele);
291                if (oc->max_allocations)
292                        --oc->current_allocations;
293        }
294        pthread_spin_unlock(&oc->spin);
295
296        if (oc->current_allocations)
297                fprintf(stderr, "OCache destroyed, leaking %d packets!!\n", (int) oc->current_allocations);
298
299        libtrace_ringbuffer_destroy(&oc->rb);
300        pthread_spin_destroy(&oc->spin);
301        free(oc->thread_list);
302        libtrace_zero_ocache(oc);
303        if (oc->current_allocations)
304                return (int) oc->current_allocations;
305        else
306                return 0;
307}
308
309static inline size_t libtrace_ocache_alloc_cache(libtrace_ocache_t *oc, void *values[], size_t nb_buffers, size_t min_nb_buffers,
310                                                                                 struct local_cache *lc) {
311        libtrace_ringbuffer_t *rb = &oc->rb;
312        size_t i;
313
314        // We have enough cached!! Yay
315        if (nb_buffers <= lc->used) {
316                // Copy all from cache
317                memcpy(values, &lc->cache[lc->used - nb_buffers], sizeof(void *) * nb_buffers);
318                lc->used -= nb_buffers;
319#ifdef ENABLE_MEM_STATS
320                mem_hits.read.cache_hit += nb_buffers;
321                mem_hits.readbulk.cache_hit += 1;
322#endif
323                return nb_buffers;
324        }
325        // Cache is not big enough try read all from ringbuffer
326        else if (nb_buffers > lc->total) {
327                i = libtrace_ringbuffer_sread_bulk(rb, values, nb_buffers, min_nb_buffers);
328#ifdef ENABLE_MEM_STATS
329                if (i)
330                        mem_hits.readbulk.ring_hit += 1;
331                else
332                        mem_hits.readbulk.miss += 1;
333                mem_hits.read.ring_hit += i;
334#endif
335        } else { // Not enough cached
336                // Empty the cache and re-fill it and then see what we're left with
337                i = lc->used;
338                memcpy(values, lc->cache, sizeof(void *) * lc->used);
339#ifdef ENABLE_MEM_STATS
340                mem_hits.read.cache_hit += i;
341#endif
342
343                // Make sure we still meet the minimum requirement
344                if (i < min_nb_buffers)
345                        lc->used = libtrace_ringbuffer_sread_bulk(rb, lc->cache, lc->total, min_nb_buffers - i);
346                else
347                        lc->used = libtrace_ringbuffer_sread_bulk(rb, lc->cache, lc->total, 0);
348#ifdef ENABLE_MEM_STATS
349                if (lc->used == lc->total)
350                        mem_hits.readbulk.ring_hit += 1;
351                else
352                        mem_hits.readbulk.miss += 1;
353                mem_hits.read.ring_hit += lc->used;
354#endif
355        }
356
357        // Try fill the remaining
358        if (i < nb_buffers && lc->used) {
359                size_t remaining;
360                remaining = MIN(lc->used, nb_buffers - i);
361                memcpy(&values[i], &lc->cache[lc->used - remaining], sizeof(void *) * remaining);
362                lc->used -= remaining;
363                i += remaining;
364        }
365#ifdef ENABLE_MEM_STATS
366        mem_hits.read.miss += nb_buffers - i;
367#endif
368        assert(i >= min_nb_buffers);
369        return i;
370}
371
372DLLEXPORT size_t libtrace_ocache_alloc(libtrace_ocache_t *oc, void *values[], size_t nb_buffers, size_t min_nb_buffers) {
373        struct local_cache *lc = find_cache(oc);
374        size_t i;
375        size_t min;
376        bool try_alloc = !(oc->max_allocations && oc->max_allocations <= oc->current_allocations);
377
378        assert(oc->max_allocations ? nb_buffers < oc->max_allocations : 1);
379        min = try_alloc ? 0: min_nb_buffers;
380        if (lc)
381                i = libtrace_ocache_alloc_cache(oc, values, nb_buffers, min,  lc);
382        else
383                i = libtrace_ringbuffer_sread_bulk(&oc->rb, values, nb_buffers, min);
384
385        if (try_alloc) {
386                size_t nb;
387
388                // Try alloc the rest
389                if (oc->max_allocations) {
390                        pthread_spin_lock(&oc->spin);
391                        nb = MIN(oc->max_allocations - oc->current_allocations, nb_buffers - i);
392                        oc->current_allocations += nb;
393                        pthread_spin_unlock(&oc->spin);
394                        nb += i;
395                } else {
396                        nb = nb_buffers;
397                }
398
399                for (;i < nb; ++i) {
400                        values[i] = (*oc->alloc)();
401                        assert(values[i]);
402                }
403                assert (i == nb);
404                // Still got to wait for more
405                if (nb < min_nb_buffers) {
406                        if (lc)
407                                i += libtrace_ocache_alloc_cache(oc, &values[nb], nb_buffers - nb, min_nb_buffers - nb, lc);
408                        else
409                                i += libtrace_ringbuffer_sread_bulk(&oc->rb, &values[nb], nb_buffers - nb, min_nb_buffers - nb);
410                }
411        }
412        assert(i >= min_nb_buffers);
413        return i;
414}
415
416
417static inline size_t libtrace_ocache_free_cache(libtrace_ocache_t *oc, void *values[], size_t nb_buffers, size_t min_nb_buffers,
418                                                                                        struct local_cache *lc) {
419        libtrace_ringbuffer_t *rb = &oc->rb;
420        size_t i;
421
422        // We have enough cached!! Yay
423        if (nb_buffers <= lc->total - lc->used) {
424                // Copy all to the cache
425                memcpy(&lc->cache[lc->used], values, sizeof(void *) * nb_buffers);
426                lc->used += nb_buffers;
427#ifdef ENABLE_MEM_STATS
428                mem_hits.write.cache_hit += nb_buffers;
429                mem_hits.writebulk.cache_hit += 1;
430#endif
431                return nb_buffers;
432        }
433        // Cache is not big enough try write all to the ringbuffer
434        else if (nb_buffers > lc->total) {
435                i = libtrace_ringbuffer_swrite_bulk(rb, values, nb_buffers, min_nb_buffers);
436#ifdef ENABLE_MEM_STATS
437                if (i)
438                        mem_hits.writebulk.ring_hit += 1;
439                else
440                        mem_hits.writebulk.miss += 1;
441                mem_hits.write.ring_hit += i;
442#endif
443        } else { // Not enough cache space but there might later
444                // Fill the cache and empty it and then see what we're left with
445                i = (lc->total - lc->used);
446                memcpy(&lc->cache[lc->used], values, sizeof(void *) * i);
447#ifdef ENABLE_MEM_STATS
448                mem_hits.write.cache_hit += i;
449#endif
450
451                // Make sure we still meet the minimum requirement
452                if (i < min_nb_buffers)
453                        lc->used = lc->total - libtrace_ringbuffer_swrite_bulk(rb, lc->cache, lc->total, min_nb_buffers - i);
454                else
455                        lc->used = lc->total - libtrace_ringbuffer_swrite_bulk(rb, lc->cache, lc->total, 0);
456
457                // Re originise fulls to the front
458                if (lc->used)
459                        memmove(lc->cache, &lc->cache[lc->total - lc->used], sizeof(void *) * lc->used);
460
461#ifdef ENABLE_MEM_STATS
462                if (lc->used)
463                        mem_hits.writebulk.miss += 1;
464                else
465                        mem_hits.writebulk.ring_hit += 1;
466                mem_hits.write.ring_hit += lc->total - lc->used;
467#endif
468        }
469
470        // Try empty the remaining
471        if (i < nb_buffers && lc->used != lc->total) {
472                size_t remaining;
473                remaining = MIN(lc->total - lc->used, nb_buffers - i);
474                memcpy(&lc->cache[lc->used], &values[i], sizeof(void *) * remaining);
475                lc->used += remaining;
476                i += remaining;
477        }
478#ifdef ENABLE_MEM_STATS
479        mem_hits.write.miss += nb_buffers - i;
480#endif
481        return i;
482}
483
484DLLEXPORT size_t libtrace_ocache_free(libtrace_ocache_t *oc, void *values[], size_t nb_buffers, size_t min_nb_buffers) {
485        struct local_cache *lc = find_cache(oc);
486        size_t i;
487        size_t min;
488
489        assert(oc->max_allocations ? nb_buffers < oc->max_allocations : 1);
490        min = oc->max_allocations ? min_nb_buffers : 0;
491        if (lc)
492                i = libtrace_ocache_free_cache(oc, values, nb_buffers, min, lc);
493        else
494                i = libtrace_ringbuffer_swrite_bulk(&oc->rb, values, nb_buffers, min);
495
496        if (!oc->max_allocations) {
497                // Free these normally
498                for (;i < min_nb_buffers; ++i) {
499                        oc->free(values[i]);
500                }
501        }
502        return i;
503}
504
505DLLEXPORT void libtrace_zero_ocache(libtrace_ocache_t *oc) {
506        libtrace_zero_ringbuffer(&oc->rb);
507        oc->thread_cache_size = 0;
508        oc->alloc = NULL;
509        oc->free = NULL;
510        oc->current_allocations = 0;
511        oc->max_allocations = 0;
512        oc->nb_thread_list = 0;
513        oc->max_nb_thread_list = 0;
514        oc->thread_list = NULL;
515}
516
517/**
518 * @brief ocache_unregister_thread removes a thread from an ocache.
519 * @param The ocache to remove this thread, this will free any packets in the TLS cache
520 */
521DLLEXPORT void libtrace_ocache_unregister_thread(libtrace_ocache_t *oc) {
522        size_t i;
523        struct local_caches *lcs = get_local_caches();
524        struct local_cache *lc = find_cache(oc);
525
526        if (lc) {
527                for (i = 0; i < lcs->t_mem_caches_used; ++i) {
528                        if (&lcs->t_mem_caches[i] == lc) {
529                                // Free the cache against the ocache
530                                unregister_thread(&lcs->t_mem_caches[i]);
531                                free(lcs->t_mem_caches[i].cache);
532                                // And remove it from the thread itself
533                                --lcs->t_mem_caches_used;
534                                lcs->t_mem_caches[i] = lcs->t_mem_caches[lcs->t_mem_caches_used];
535                                memset(&lcs->t_mem_caches[lcs->t_mem_caches_used], 0, sizeof(struct local_cache));
536                        }
537                }
538        }
539}
Note: See TracBrowser for help on using the repository browser.