0401df5993e1ff6f04ed02841af85f616927c566
[vpp.git] / src / vppinfra / mem_dlmalloc.c
1 /*
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:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
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.
14  */
15
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>
22 #include <vppinfra/sanitizer.h>
23
24 typedef struct
25 {
26   /* Address of callers: outer first, inner last. */
27   uword callers[12];
28
29   /* Count of allocations with this traceback. */
30   u32 n_allocations;
31
32   /* Count of bytes allocated with this traceback. */
33   u32 n_bytes;
34
35   /* Offset of this item */
36   uword offset;
37 } mheap_trace_t;
38
39 typedef struct
40 {
41   clib_spinlock_t lock;
42   uword enabled;
43
44   mheap_trace_t *traces;
45
46   /* Indices of free traces. */
47   u32 *trace_free_list;
48
49   /* Hash table mapping callers to trace index. */
50   uword *trace_by_callers;
51
52   /* Hash table mapping mheap offset to trace index. */
53   uword *trace_index_by_offset;
54
55   /* So we can easily shut off current segment trace, if any */
56   void *current_traced_mheap;
57
58 } mheap_trace_main_t;
59
60 mheap_trace_main_t mheap_trace_main;
61
62 void
63 mheap_get_trace (uword offset, uword size)
64 {
65   mheap_trace_main_t *tm = &mheap_trace_main;
66   mheap_trace_t *t;
67   uword i, n_callers, trace_index, *p;
68   mheap_trace_t trace;
69   uword save_enabled;
70
71   if (tm->enabled == 0 || (clib_mem_get_heap () != tm->current_traced_mheap))
72     return;
73
74   /* Spurious Coverity warnings be gone. */
75   clib_memset (&trace, 0, sizeof (trace));
76
77   /* Skip our frame and mspace_get_aligned's frame */
78   n_callers = clib_backtrace (trace.callers, ARRAY_LEN (trace.callers), 2);
79   if (n_callers == 0)
80     return;
81
82   clib_spinlock_lock (&tm->lock);
83
84   /* Turn off tracing to avoid embarrassment... */
85   save_enabled = tm->enabled;
86   tm->enabled = 0;
87
88   if (!tm->trace_by_callers)
89     tm->trace_by_callers =
90       hash_create_shmem (0, sizeof (trace.callers), sizeof (uword));
91
92   p = hash_get_mem (tm->trace_by_callers, &trace.callers);
93   if (p)
94     {
95       trace_index = p[0];
96       t = tm->traces + trace_index;
97     }
98   else
99     {
100       i = vec_len (tm->trace_free_list);
101       if (i > 0)
102         {
103           trace_index = tm->trace_free_list[i - 1];
104           _vec_len (tm->trace_free_list) = i - 1;
105         }
106       else
107         {
108           mheap_trace_t *old_start = tm->traces;
109           mheap_trace_t *old_end = vec_end (tm->traces);
110
111           vec_add2 (tm->traces, t, 1);
112
113           if (tm->traces != old_start)
114             {
115               hash_pair_t *p;
116               mheap_trace_t *q;
117             /* *INDENT-OFF* */
118             hash_foreach_pair (p, tm->trace_by_callers,
119             ({
120               q = uword_to_pointer (p->key, mheap_trace_t *);
121               ASSERT (q >= old_start && q < old_end);
122               p->key = pointer_to_uword (tm->traces + (q - old_start));
123             }));
124             /* *INDENT-ON* */
125             }
126           trace_index = t - tm->traces;
127         }
128
129       t = tm->traces + trace_index;
130       t[0] = trace;
131       t->n_allocations = 0;
132       t->n_bytes = 0;
133       hash_set_mem (tm->trace_by_callers, t->callers, trace_index);
134     }
135
136   t->n_allocations += 1;
137   t->n_bytes += size;
138   t->offset = offset;           /* keep a sample to autopsy */
139   hash_set (tm->trace_index_by_offset, offset, t - tm->traces);
140   tm->enabled = save_enabled;
141   clib_spinlock_unlock (&tm->lock);
142 }
143
144 void
145 mheap_put_trace (uword offset, uword size)
146 {
147   mheap_trace_t *t;
148   uword trace_index, *p;
149   mheap_trace_main_t *tm = &mheap_trace_main;
150   uword save_enabled;
151
152   if (tm->enabled == 0)
153     return;
154
155   clib_spinlock_lock (&tm->lock);
156
157   /* Turn off tracing for a moment */
158   save_enabled = tm->enabled;
159   tm->enabled = 0;
160
161   p = hash_get (tm->trace_index_by_offset, offset);
162   if (!p)
163     {
164       tm->enabled = save_enabled;
165       clib_spinlock_unlock (&tm->lock);
166       return;
167     }
168
169   trace_index = p[0];
170   hash_unset (tm->trace_index_by_offset, offset);
171   ASSERT (trace_index < vec_len (tm->traces));
172
173   t = tm->traces + trace_index;
174   ASSERT (t->n_allocations > 0);
175   ASSERT (t->n_bytes >= size);
176   t->n_allocations -= 1;
177   t->n_bytes -= size;
178   if (t->n_allocations == 0)
179     {
180       hash_unset_mem (tm->trace_by_callers, t->callers);
181       vec_add1 (tm->trace_free_list, trace_index);
182       clib_memset (t, 0, sizeof (t[0]));
183     }
184   tm->enabled = save_enabled;
185   clib_spinlock_unlock (&tm->lock);
186 }
187
188 always_inline void
189 mheap_trace_main_free (mheap_trace_main_t * tm)
190 {
191   vec_free (tm->traces);
192   vec_free (tm->trace_free_list);
193   hash_free (tm->trace_by_callers);
194   hash_free (tm->trace_index_by_offset);
195 }
196
197 /* Initialize CLIB heap based on memory/size given by user.
198    Set memory to 0 and CLIB will try to allocate its own heap. */
199 static void *
200 clib_mem_init_internal (void *memory, uword memory_size, int set_heap)
201 {
202   u8 *heap;
203
204   clib_mem_main_init ();
205
206   if (memory)
207     {
208       heap = create_mspace_with_base (memory, memory_size, 1 /* locked */ );
209       mspace_disable_expand (heap);
210     }
211   else
212     heap = create_mspace (memory_size, 1 /* locked */ );
213
214   CLIB_MEM_POISON (mspace_least_addr (heap), mspace_footprint (heap));
215
216   if (set_heap)
217     clib_mem_set_heap (heap);
218
219   if (mheap_trace_main.lock == 0)
220     clib_spinlock_init (&mheap_trace_main.lock);
221
222   return heap;
223 }
224
225 void *
226 clib_mem_init (void *memory, uword memory_size)
227 {
228   return clib_mem_init_internal (memory, memory_size,
229                                  1 /* do clib_mem_set_heap */ );
230 }
231
232 void *
233 clib_mem_init_thread_safe (void *memory, uword memory_size)
234 {
235   return clib_mem_init_internal (memory, memory_size,
236                                  1 /* do clib_mem_set_heap */ );
237 }
238
239 void
240 clib_mem_destroy_mspace (void *mspace)
241 {
242   mheap_trace_main_t *tm = &mheap_trace_main;
243
244   if (tm->enabled && mspace == tm->current_traced_mheap)
245     tm->enabled = 0;
246
247   destroy_mspace (mspace);
248 }
249
250 void
251 clib_mem_destroy (void)
252 {
253   clib_mem_destroy_mspace (clib_mem_get_heap ());
254 }
255
256 void *
257 clib_mem_init_thread_safe_numa (void *memory, uword memory_size, u8 numa)
258 {
259   clib_mem_vm_alloc_t alloc = { 0 };
260   clib_error_t *err;
261   void *heap;
262
263   alloc.size = memory_size;
264   alloc.flags = CLIB_MEM_VM_F_NUMA_FORCE;
265   alloc.numa_node = numa;
266   if ((err = clib_mem_vm_ext_alloc (&alloc)))
267     {
268       clib_error_report (err);
269       return 0;
270     }
271
272   heap = clib_mem_init_internal (memory, memory_size,
273                                  0 /* do NOT clib_mem_set_heap */ );
274
275   ASSERT (heap);
276
277   return heap;
278 }
279
280 u8 *
281 format_clib_mem_usage (u8 * s, va_list * va)
282 {
283   int verbose = va_arg (*va, int);
284   return format (s, "$$$$ heap at %llx verbose %d", clib_mem_get_heap (),
285                  verbose);
286 }
287
288 /*
289  * Magic decoder ring for mallinfo stats (ala dlmalloc):
290  *
291  * size_t arena;     / * Non-mmapped space allocated (bytes) * /
292  * size_t ordblks;   / * Number of free chunks * /
293  * size_t smblks;    / * Number of free fastbin blocks * /
294  * size_t hblks;     / * Number of mmapped regions * /
295  * size_t hblkhd;    / * Space allocated in mmapped regions (bytes) * /
296  * size_t usmblks;   / * Maximum total allocated space (bytes) * /
297  * size_t fsmblks;   / * Space in freed fastbin blocks (bytes) * /
298  * size_t uordblks;  / * Total allocated space (bytes) * /
299  * size_t fordblks;  / * Total free space (bytes) * /
300  * size_t keepcost;  / * Top-most, releasable space (bytes) * /
301  *
302  */
303
304 u8 *
305 format_msize (u8 * s, va_list * va)
306 {
307   uword a = va_arg (*va, uword);
308
309   if (a >= 1ULL << 30)
310     s = format (s, "%.2fG", (((f64) a) / ((f64) (1ULL << 30))));
311   else if (a >= 1ULL << 20)
312     s = format (s, "%.2fM", (((f64) a) / ((f64) (1ULL << 20))));
313   else if (a >= 1ULL << 10)
314     s = format (s, "%.2fK", (((f64) a) / ((f64) (1ULL << 10))));
315   else
316     s = format (s, "%lld", a);
317   return s;
318 }
319
320 static int
321 mheap_trace_sort (const void *_t1, const void *_t2)
322 {
323   const mheap_trace_t *t1 = _t1;
324   const mheap_trace_t *t2 = _t2;
325   word cmp;
326
327   cmp = (word) t2->n_bytes - (word) t1->n_bytes;
328   if (!cmp)
329     cmp = (word) t2->n_allocations - (word) t1->n_allocations;
330   return cmp;
331 }
332
333 u8 *
334 format_mheap_trace (u8 * s, va_list * va)
335 {
336   mheap_trace_main_t *tm = va_arg (*va, mheap_trace_main_t *);
337   int verbose = va_arg (*va, int);
338   int have_traces = 0;
339   int i;
340
341   clib_spinlock_lock (&tm->lock);
342   if (vec_len (tm->traces) > 0 &&
343       clib_mem_get_heap () == tm->current_traced_mheap)
344     {
345       have_traces = 1;
346
347       /* Make a copy of traces since we'll be sorting them. */
348       mheap_trace_t *t, *traces_copy;
349       u32 indent, total_objects_traced;
350
351       traces_copy = vec_dup (tm->traces);
352
353       qsort (traces_copy, vec_len (traces_copy), sizeof (traces_copy[0]),
354              mheap_trace_sort);
355
356       total_objects_traced = 0;
357       s = format (s, "\n");
358       vec_foreach (t, traces_copy)
359       {
360         /* Skip over free elements. */
361         if (t->n_allocations == 0)
362           continue;
363
364         total_objects_traced += t->n_allocations;
365
366         /* When not verbose only report allocations of more than 1k. */
367         if (!verbose && t->n_bytes < 1024)
368           continue;
369
370         if (t == traces_copy)
371           s = format (s, "%=9s%=9s %=10s Traceback\n", "Bytes", "Count",
372                       "Sample");
373         s = format (s, "%9d%9d %p", t->n_bytes, t->n_allocations, t->offset);
374         indent = format_get_indent (s);
375         for (i = 0; i < ARRAY_LEN (t->callers) && t->callers[i]; i++)
376           {
377             if (i > 0)
378               s = format (s, "%U", format_white_space, indent);
379 #if defined(CLIB_UNIX) && !defined(__APPLE__)
380             /* $$$$ does this actually work? */
381             s =
382               format (s, " %U\n", format_clib_elf_symbol_with_address,
383                       t->callers[i]);
384 #else
385             s = format (s, " %p\n", t->callers[i]);
386 #endif
387           }
388       }
389
390       s = format (s, "%d total traced objects\n", total_objects_traced);
391
392       vec_free (traces_copy);
393     }
394   clib_spinlock_unlock (&tm->lock);
395   if (have_traces == 0)
396     s = format (s, "no traced allocations\n");
397
398   return s;
399 }
400
401
402 u8 *
403 format_mheap (u8 * s, va_list * va)
404 {
405   void *heap = va_arg (*va, u8 *);
406   int verbose = va_arg (*va, int);
407   struct dlmallinfo mi;
408   mheap_trace_main_t *tm = &mheap_trace_main;
409
410   mi = mspace_mallinfo (heap);
411
412   s = format (s, "total: %U, used: %U, free: %U, trimmable: %U",
413               format_msize, mi.arena,
414               format_msize, mi.uordblks,
415               format_msize, mi.fordblks, format_msize, mi.keepcost);
416   if (verbose > 0)
417     {
418       s = format (s, "\n    free chunks %llu free fastbin blks %llu",
419                   mi.ordblks, mi.smblks);
420       s =
421         format (s, "\n    max total allocated %U", format_msize, mi.usmblks);
422     }
423
424   if (mspace_is_traced (heap))
425     s = format (s, "\n%U", format_mheap_trace, tm, verbose);
426   return s;
427 }
428
429 void
430 clib_mem_usage (clib_mem_usage_t * u)
431 {
432   clib_warning ("unimp");
433 }
434
435 void
436 mheap_usage (void *heap, clib_mem_usage_t * usage)
437 {
438   struct dlmallinfo mi = mspace_mallinfo (heap);
439
440   /* TODO: Fill in some more values */
441   usage->object_count = 0;
442   usage->bytes_total = mi.arena;
443   usage->bytes_overhead = 0;
444   usage->bytes_max = 0;
445   usage->bytes_used = mi.uordblks;
446   usage->bytes_free = mi.fordblks;
447   usage->bytes_free_reclaimed = 0;
448 }
449
450 /* Call serial number for debugger breakpoints. */
451 uword clib_mem_validate_serial = 0;
452
453 void
454 clib_mem_validate (void)
455 {
456   clib_warning ("unimp");
457 }
458
459 void
460 mheap_trace (void *v, int enable)
461 {
462   (void) mspace_enable_disable_trace (v, enable);
463
464   if (enable == 0)
465     mheap_trace_main_free (&mheap_trace_main);
466 }
467
468 void
469 clib_mem_trace (int enable)
470 {
471   mheap_trace_main_t *tm = &mheap_trace_main;
472   void *current_heap = clib_mem_get_heap ();
473
474   tm->enabled = enable;
475   mheap_trace (current_heap, enable);
476
477   if (enable)
478     tm->current_traced_mheap = current_heap;
479   else
480     tm->current_traced_mheap = 0;
481 }
482
483 int
484 clib_mem_is_traced (void)
485 {
486   return mspace_is_traced (clib_mem_get_heap ());
487 }
488
489 uword
490 clib_mem_trace_enable_disable (uword enable)
491 {
492   uword rv;
493   mheap_trace_main_t *tm = &mheap_trace_main;
494
495   rv = tm->enabled;
496   tm->enabled = enable;
497   return rv;
498 }
499
500 /*
501  * These API functions seem like layering violations, but
502  * by introducing them we greatly reduce the number
503  * of code changes required to use dlmalloc spaces
504  */
505 void *
506 mheap_alloc_with_lock (void *memory, uword size, int locked)
507 {
508   void *rv;
509   if (memory == 0)
510     return create_mspace (size, locked);
511   else
512     {
513       rv = create_mspace_with_base (memory, size, locked);
514       if (rv)
515         mspace_disable_expand (rv);
516       return rv;
517     }
518 }
519
520 /*
521  * fd.io coding-style-patch-verification: ON
522  *
523  * Local Variables:
524  * eval: (c-set-style "gnu")
525  * End:
526  */