2 * Copyright (c) 2015 Cisco and/or its affiliates.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at:
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
16 #include <vppinfra/format.h>
17 #include <vppinfra/dlmalloc.h>
18 #include <vppinfra/os.h>
19 #include <vppinfra/lock.h>
20 #include <vppinfra/hash.h>
21 #include <vppinfra/elf_clib.h>
25 /* Address of callers: outer first, inner last. */
28 /* Count of allocations with this traceback. */
31 /* Count of bytes allocated with this traceback. */
34 /* Offset of this item */
43 mheap_trace_t *traces;
45 /* Indices of free traces. */
48 /* Hash table mapping callers to trace index. */
49 uword *trace_by_callers;
51 /* Hash table mapping mheap offset to trace index. */
52 uword *trace_index_by_offset;
54 /* So we can easily shut off current segment trace, if any */
55 void *current_traced_mheap;
59 mheap_trace_main_t mheap_trace_main;
62 mheap_get_trace (uword offset, uword size)
64 mheap_trace_main_t *tm = &mheap_trace_main;
66 uword i, n_callers, trace_index, *p;
70 if (tm->enabled == 0 || (clib_mem_get_heap () != tm->current_traced_mheap))
73 /* Spurious Coverity warnings be gone. */
74 clib_memset (&trace, 0, sizeof (trace));
76 clib_spinlock_lock (&tm->lock);
78 /* Turn off tracing to avoid embarrassment... */
79 save_enabled = tm->enabled;
82 /* Skip our frame and mspace_get_aligned's frame */
83 n_callers = clib_backtrace (trace.callers, ARRAY_LEN (trace.callers), 2);
87 if (!tm->trace_by_callers)
88 tm->trace_by_callers =
89 hash_create_shmem (0, sizeof (trace.callers), sizeof (uword));
91 p = hash_get_mem (tm->trace_by_callers, &trace.callers);
95 t = tm->traces + trace_index;
99 i = vec_len (tm->trace_free_list);
102 trace_index = tm->trace_free_list[i - 1];
103 vec_set_len (tm->trace_free_list, i - 1);
107 mheap_trace_t *old_start = tm->traces;
108 mheap_trace_t *old_end = vec_end (tm->traces);
110 vec_add2 (tm->traces, t, 1);
112 if (tm->traces != old_start)
117 hash_foreach_pair (p, tm->trace_by_callers,
119 q = uword_to_pointer (p->key, mheap_trace_t *);
120 ASSERT (q >= old_start && q < old_end);
121 p->key = pointer_to_uword (tm->traces + (q - old_start));
125 trace_index = t - tm->traces;
128 t = tm->traces + trace_index;
130 t->n_allocations = 0;
132 hash_set_mem (tm->trace_by_callers, t->callers, trace_index);
135 t->n_allocations += 1;
137 t->offset = offset; /* keep a sample to autopsy */
138 hash_set (tm->trace_index_by_offset, offset, t - tm->traces);
141 tm->enabled = save_enabled;
142 clib_spinlock_unlock (&tm->lock);
146 mheap_put_trace (uword offset, uword size)
149 uword trace_index, *p;
150 mheap_trace_main_t *tm = &mheap_trace_main;
153 if (tm->enabled == 0)
156 clib_spinlock_lock (&tm->lock);
158 /* Turn off tracing for a moment */
159 save_enabled = tm->enabled;
162 p = hash_get (tm->trace_index_by_offset, offset);
165 tm->enabled = save_enabled;
166 clib_spinlock_unlock (&tm->lock);
171 hash_unset (tm->trace_index_by_offset, offset);
172 ASSERT (trace_index < vec_len (tm->traces));
174 t = tm->traces + trace_index;
175 ASSERT (t->n_allocations > 0);
176 ASSERT (t->n_bytes >= size);
177 t->n_allocations -= 1;
179 if (t->n_allocations == 0)
181 hash_unset_mem (tm->trace_by_callers, t->callers);
182 vec_add1 (tm->trace_free_list, trace_index);
183 clib_memset (t, 0, sizeof (t[0]));
185 tm->enabled = save_enabled;
186 clib_spinlock_unlock (&tm->lock);
190 mheap_trace_main_free (mheap_trace_main_t * tm)
192 vec_free (tm->traces);
193 vec_free (tm->trace_free_list);
194 hash_free (tm->trace_by_callers);
195 hash_free (tm->trace_index_by_offset);
198 static clib_mem_heap_t *
199 clib_mem_create_heap_internal (void *base, uword size,
200 clib_mem_page_sz_t log2_page_sz, int is_locked,
205 int sz = sizeof (clib_mem_heap_t);
209 log2_page_sz = clib_mem_log2_page_size_validate (log2_page_sz);
210 size = round_pow2 (size, clib_mem_page_bytes (log2_page_sz));
211 base = clib_mem_vm_map_internal (0, log2_page_sz, size, -1, 0,
214 if (base == CLIB_MEM_VM_MAP_FAILED)
217 flags = CLIB_MEM_HEAP_F_UNMAP_ON_DESTROY;
220 log2_page_sz = CLIB_MEM_PAGE_SZ_UNKNOWN;
223 flags |= CLIB_MEM_HEAP_F_LOCKED;
228 h->log2_page_sz = log2_page_sz;
231 strcpy (h->name, name);
232 sz = round_pow2 (sz + sizeof (clib_mem_heap_t), 16);
233 h->mspace = create_mspace_with_base (base + sz, size - sz, is_locked);
235 mspace_disable_expand (h->mspace);
237 clib_mem_poison (mspace_least_addr (h->mspace),
238 mspace_footprint (h->mspace));
243 /* Initialize CLIB heap based on memory/size given by user.
244 Set memory to 0 and CLIB will try to allocate its own heap. */
246 clib_mem_init_internal (void *base, uword size,
247 clib_mem_page_sz_t log2_page_sz)
251 clib_mem_main_init ();
253 h = clib_mem_create_heap_internal (base, size, log2_page_sz,
254 1 /*is_locked */ , "main heap");
256 clib_mem_set_heap (h);
258 if (mheap_trace_main.lock == 0)
259 clib_spinlock_init (&mheap_trace_main.lock);
265 clib_mem_init (void *memory, uword memory_size)
267 return clib_mem_init_internal (memory, memory_size,
268 CLIB_MEM_PAGE_SZ_DEFAULT);
272 clib_mem_init_with_page_size (uword memory_size,
273 clib_mem_page_sz_t log2_page_sz)
275 return clib_mem_init_internal (0, memory_size, log2_page_sz);
279 clib_mem_init_thread_safe (void *memory, uword memory_size)
281 return clib_mem_init_internal (memory, memory_size,
282 CLIB_MEM_PAGE_SZ_DEFAULT);
286 clib_mem_destroy (void)
288 mheap_trace_main_t *tm = &mheap_trace_main;
289 clib_mem_heap_t *heap = clib_mem_get_heap ();
290 void *base = mspace_least_addr (heap->mspace);
292 if (tm->enabled && heap->mspace == tm->current_traced_mheap)
295 destroy_mspace (heap->mspace);
296 clib_mem_vm_unmap (base);
300 format_clib_mem_usage (u8 *s, va_list *va)
302 int verbose = va_arg (*va, int);
303 return format (s, "$$$$ heap at %llx verbose %d", clib_mem_get_heap (),
308 * Magic decoder ring for mallinfo stats (ala dlmalloc):
310 * size_t arena; / * Non-mmapped space allocated (bytes) * /
311 * size_t ordblks; / * Number of free chunks * /
312 * size_t smblks; / * Number of free fastbin blocks * /
313 * size_t hblks; / * Number of mmapped regions * /
314 * size_t hblkhd; / * Space allocated in mmapped regions (bytes) * /
315 * size_t usmblks; / * Maximum total allocated space (bytes) * /
316 * size_t fsmblks; / * Space in freed fastbin blocks (bytes) * /
317 * size_t uordblks; / * Total allocated space (bytes) * /
318 * size_t fordblks; / * Total free space (bytes) * /
319 * size_t keepcost; / * Top-most, releasable space (bytes) * /
324 format_msize (u8 * s, va_list * va)
326 uword a = va_arg (*va, uword);
329 s = format (s, "%.2fG", (((f64) a) / ((f64) (1ULL << 30))));
330 else if (a >= 1ULL << 20)
331 s = format (s, "%.2fM", (((f64) a) / ((f64) (1ULL << 20))));
332 else if (a >= 1ULL << 10)
333 s = format (s, "%.2fK", (((f64) a) / ((f64) (1ULL << 10))));
335 s = format (s, "%lld", a);
340 mheap_trace_sort (const void *_t1, const void *_t2)
342 const mheap_trace_t *t1 = _t1;
343 const mheap_trace_t *t2 = _t2;
346 cmp = (word) t2->n_bytes - (word) t1->n_bytes;
348 cmp = (word) t2->n_allocations - (word) t1->n_allocations;
353 format_mheap_trace (u8 * s, va_list * va)
355 mheap_trace_main_t *tm = va_arg (*va, mheap_trace_main_t *);
356 int verbose = va_arg (*va, int);
360 clib_spinlock_lock (&tm->lock);
361 if (vec_len (tm->traces) > 0 &&
362 clib_mem_get_heap () == tm->current_traced_mheap)
366 /* Make a copy of traces since we'll be sorting them. */
367 mheap_trace_t *t, *traces_copy;
368 u32 indent, total_objects_traced;
370 traces_copy = vec_dup (tm->traces);
372 qsort (traces_copy, vec_len (traces_copy), sizeof (traces_copy[0]),
375 total_objects_traced = 0;
376 s = format (s, "\n");
377 vec_foreach (t, traces_copy)
379 /* Skip over free elements. */
380 if (t->n_allocations == 0)
383 total_objects_traced += t->n_allocations;
385 /* When not verbose only report allocations of more than 1k. */
386 if (!verbose && t->n_bytes < 1024)
389 if (t == traces_copy)
390 s = format (s, "%=9s%=9s %=10s Traceback\n", "Bytes", "Count",
392 s = format (s, "%9d%9d %p", t->n_bytes, t->n_allocations, t->offset);
393 indent = format_get_indent (s);
394 for (i = 0; i < ARRAY_LEN (t->callers) && t->callers[i]; i++)
397 s = format (s, "%U", format_white_space, indent);
398 #if defined(CLIB_UNIX) && !defined(__APPLE__)
399 /* $$$$ does this actually work? */
401 format (s, " %U\n", format_clib_elf_symbol_with_address,
404 s = format (s, " %p\n", t->callers[i]);
409 s = format (s, "%d total traced objects\n", total_objects_traced);
411 vec_free (traces_copy);
413 clib_spinlock_unlock (&tm->lock);
414 if (have_traces == 0)
415 s = format (s, "no traced allocations\n");
421 format_clib_mem_heap (u8 * s, va_list * va)
423 clib_mem_heap_t *heap = va_arg (*va, clib_mem_heap_t *);
424 int verbose = va_arg (*va, int);
425 struct dlmallinfo mi;
426 mheap_trace_main_t *tm = &mheap_trace_main;
427 u32 indent = format_get_indent (s) + 2;
430 heap = clib_mem_get_heap ();
432 mi = mspace_mallinfo (heap->mspace);
434 s = format (s, "base %p, size %U",
435 heap->base, format_memory_size, heap->size);
438 if (heap->flags & CLIB_MEM_HEAP_F_##v) s = format (s, ", %s", str);
439 foreach_clib_mem_heap_flag;
442 s = format (s, ", name '%s'", heap->name);
444 if (heap->log2_page_sz != CLIB_MEM_PAGE_SZ_UNKNOWN)
446 clib_mem_page_stats_t stats;
447 clib_mem_get_page_stats (heap->base, heap->log2_page_sz,
448 heap->size >> heap->log2_page_sz, &stats);
449 s = format (s, "\n%U%U", format_white_space, indent,
450 format_clib_mem_page_stats, &stats);
453 s = format (s, "\n%Utotal: %U, used: %U, free: %U, trimmable: %U",
454 format_white_space, indent,
455 format_msize, mi.arena,
456 format_msize, mi.uordblks,
457 format_msize, mi.fordblks, format_msize, mi.keepcost);
460 s = format (s, "\n%Ufree chunks %llu free fastbin blks %llu",
461 format_white_space, indent + 2, mi.ordblks, mi.smblks);
462 s = format (s, "\n%Umax total allocated %U",
463 format_white_space, indent + 2, format_msize, mi.usmblks);
466 if (heap->flags & CLIB_MEM_HEAP_F_TRACED)
467 s = format (s, "\n%U", format_mheap_trace, tm, verbose);
471 __clib_export __clib_flatten void
472 clib_mem_get_heap_usage (clib_mem_heap_t *heap, clib_mem_usage_t *usage)
474 struct dlmallinfo mi = mspace_mallinfo (heap->mspace);
476 usage->bytes_total = mi.arena; /* non-mmapped space allocated from system */
477 usage->bytes_used = mi.uordblks; /* total allocated space */
478 usage->bytes_free = mi.fordblks; /* total free space */
479 usage->bytes_used_mmap = mi.hblkhd; /* space in mmapped regions */
480 usage->bytes_max = mi.usmblks; /* maximum total allocated space */
481 usage->bytes_free_reclaimed = mi.ordblks; /* number of free chunks */
482 usage->bytes_overhead = mi.keepcost; /* releasable (via malloc_trim) space */
485 usage->bytes_used_sbrk = 0;
486 usage->object_count = 0;
489 /* Call serial number for debugger breakpoints. */
490 uword clib_mem_validate_serial = 0;
493 mheap_trace (clib_mem_heap_t * h, int enable)
496 h->flags |= CLIB_MEM_HEAP_F_TRACED;
498 h->flags &= ~CLIB_MEM_HEAP_F_TRACED;
501 mheap_trace_main_free (&mheap_trace_main);
505 clib_mem_trace (int enable)
507 mheap_trace_main_t *tm = &mheap_trace_main;
508 void *current_heap = clib_mem_get_heap ();
510 tm->enabled = enable;
511 mheap_trace (current_heap, enable);
514 tm->current_traced_mheap = current_heap;
516 tm->current_traced_mheap = 0;
520 clib_mem_is_traced (void)
522 clib_mem_heap_t *h = clib_mem_get_heap ();
523 return (h->flags &= CLIB_MEM_HEAP_F_TRACED) != 0;
527 clib_mem_trace_enable_disable (uword enable)
530 mheap_trace_main_t *tm = &mheap_trace_main;
533 tm->enabled = enable;
537 __clib_export clib_mem_heap_t *
538 clib_mem_create_heap (void *base, uword size, int is_locked, char *fmt, ...)
540 clib_mem_page_sz_t log2_page_sz = clib_mem_get_log2_page_size ();
549 else if (strchr (fmt, '%'))
553 s = va_format (0, fmt, &va);
561 h = clib_mem_create_heap_internal (base, size, log2_page_sz, is_locked,
568 clib_mem_destroy_heap (clib_mem_heap_t * h)
570 mheap_trace_main_t *tm = &mheap_trace_main;
572 if (tm->enabled && h->mspace == tm->current_traced_mheap)
575 destroy_mspace (h->mspace);
576 if (h->flags & CLIB_MEM_HEAP_F_UNMAP_ON_DESTROY)
577 clib_mem_vm_unmap (h->base);
580 __clib_export __clib_flatten uword
581 clib_mem_get_heap_free_space (clib_mem_heap_t *h)
583 struct dlmallinfo dlminfo = mspace_mallinfo (h->mspace);
584 return dlminfo.fordblks;
587 __clib_export __clib_flatten void *
588 clib_mem_get_heap_base (clib_mem_heap_t *h)
593 __clib_export __clib_flatten uword
594 clib_mem_get_heap_size (clib_mem_heap_t *heap)
599 /* Memory allocator which may call os_out_of_memory() if it fails */
601 clib_mem_heap_alloc_inline (void *heap, uword size, uword align,
602 int os_out_of_memory_on_failure)
604 clib_mem_heap_t *h = heap ? heap : clib_mem_get_per_cpu_heap ();
607 align = clib_max (CLIB_MEM_MIN_ALIGN, align);
609 p = mspace_memalign (h->mspace, align, size);
611 if (PREDICT_FALSE (0 == p))
613 if (os_out_of_memory_on_failure)
618 if (PREDICT_FALSE (h->flags & CLIB_MEM_HEAP_F_TRACED))
619 mheap_get_trace (pointer_to_uword (p), clib_mem_size (p));
621 clib_mem_unpoison (p, size);
625 /* Memory allocator which calls os_out_of_memory() when it fails */
626 __clib_export __clib_flatten void *
627 clib_mem_alloc (uword size)
629 return clib_mem_heap_alloc_inline (0, size, CLIB_MEM_MIN_ALIGN,
630 /* os_out_of_memory */ 1);
633 __clib_export __clib_flatten void *
634 clib_mem_alloc_aligned (uword size, uword align)
636 return clib_mem_heap_alloc_inline (0, size, align,
637 /* os_out_of_memory */ 1);
640 /* Memory allocator which calls os_out_of_memory() when it fails */
641 __clib_export __clib_flatten void *
642 clib_mem_alloc_or_null (uword size)
644 return clib_mem_heap_alloc_inline (0, size, CLIB_MEM_MIN_ALIGN,
645 /* os_out_of_memory */ 0);
648 __clib_export __clib_flatten void *
649 clib_mem_alloc_aligned_or_null (uword size, uword align)
651 return clib_mem_heap_alloc_inline (0, size, align,
652 /* os_out_of_memory */ 0);
655 __clib_export __clib_flatten void *
656 clib_mem_heap_alloc (void *heap, uword size)
658 return clib_mem_heap_alloc_inline (heap, size, CLIB_MEM_MIN_ALIGN,
659 /* os_out_of_memory */ 1);
662 __clib_export __clib_flatten void *
663 clib_mem_heap_alloc_aligned (void *heap, uword size, uword align)
665 return clib_mem_heap_alloc_inline (heap, size, align,
666 /* os_out_of_memory */ 1);
669 __clib_export __clib_flatten void *
670 clib_mem_heap_alloc_or_null (void *heap, uword size)
672 return clib_mem_heap_alloc_inline (heap, size, CLIB_MEM_MIN_ALIGN,
673 /* os_out_of_memory */ 0);
676 __clib_export __clib_flatten void *
677 clib_mem_heap_alloc_aligned_or_null (void *heap, uword size, uword align)
679 return clib_mem_heap_alloc_inline (heap, size, align,
680 /* os_out_of_memory */ 0);
683 __clib_export __clib_flatten void *
684 clib_mem_heap_realloc_aligned (void *heap, void *p, uword new_size,
687 uword old_alloc_size;
688 clib_mem_heap_t *h = heap ? heap : clib_mem_get_per_cpu_heap ();
691 ASSERT (count_set_bits (align) == 1);
693 old_alloc_size = p ? mspace_usable_size (p) : 0;
695 if (new_size == old_alloc_size)
698 if (p && pointer_is_aligned (p, align) &&
699 mspace_realloc_in_place (h->mspace, p, new_size))
701 clib_mem_unpoison (p, new_size);
705 new = clib_mem_heap_alloc_inline (h, new_size, align, 1);
707 clib_mem_unpoison (new, new_size);
710 clib_mem_unpoison (p, old_alloc_size);
711 clib_memcpy_fast (new, p, clib_min (new_size, old_alloc_size));
712 clib_mem_heap_free (h, p);
720 __clib_export __clib_flatten void *
721 clib_mem_heap_realloc (void *heap, void *p, uword new_size)
723 return clib_mem_heap_realloc_aligned (heap, p, new_size, CLIB_MEM_MIN_ALIGN);
726 __clib_export __clib_flatten void *
727 clib_mem_realloc_aligned (void *p, uword new_size, uword align)
729 return clib_mem_heap_realloc_aligned (0, p, new_size, align);
732 __clib_export __clib_flatten void *
733 clib_mem_realloc (void *p, uword new_size)
735 return clib_mem_heap_realloc_aligned (0, p, new_size, CLIB_MEM_MIN_ALIGN);
738 __clib_export __clib_flatten uword
739 clib_mem_heap_is_heap_object (void *heap, void *p)
741 clib_mem_heap_t *h = heap ? heap : clib_mem_get_per_cpu_heap ();
742 return mspace_is_heap_object (h->mspace, p);
745 __clib_export __clib_flatten uword
746 clib_mem_is_heap_object (void *p)
748 return clib_mem_heap_is_heap_object (0, p);
751 __clib_export __clib_flatten void
752 clib_mem_heap_free (void *heap, void *p)
754 clib_mem_heap_t *h = heap ? heap : clib_mem_get_per_cpu_heap ();
755 uword size = clib_mem_size (p);
757 /* Make sure object is in the correct heap. */
758 ASSERT (clib_mem_heap_is_heap_object (h, p));
760 if (PREDICT_FALSE (h->flags & CLIB_MEM_HEAP_F_TRACED))
761 mheap_put_trace (pointer_to_uword (p), size);
762 clib_mem_poison (p, clib_mem_size (p));
764 mspace_free (h->mspace, p);
767 __clib_export __clib_flatten void
768 clib_mem_free (void *p)
770 clib_mem_heap_free (0, p);
773 __clib_export __clib_flatten uword
774 clib_mem_size (void *p)
776 return mspace_usable_size (p);
780 clib_mem_free_s (void *p)
782 uword size = clib_mem_size (p);
783 clib_mem_unpoison (p, size);
784 memset_s_inline (p, size, 0, size);