New upstream version 1.2.3
[quagga-debian.git] / lib / memory.c
1 /*
2  * Memory management routine
3  * Copyright (C) 1998 Kunihiro Ishiguro
4  *
5  * This file is part of GNU Zebra.
6  *
7  * GNU Zebra is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by the
9  * Free Software Foundation; either version 2, or (at your option) any
10  * later version.
11  *
12  * GNU Zebra is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with GNU Zebra; see the file COPYING.  If not, write to the Free
19  * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
20  * 02111-1307, USA.  
21  */
22
23 #include <zebra.h>
24 /* malloc.h is generally obsolete, however GNU Libc mallinfo wants it. */
25 #if !defined(HAVE_STDLIB_H) || (defined(GNU_LINUX) && defined(HAVE_MALLINFO))
26 #include <malloc.h>
27 #endif /* !HAVE_STDLIB_H || HAVE_MALLINFO */
28
29 #include "log.h"
30 #include "memory.h"
31
32 static void alloc_inc (int);
33 static void alloc_dec (int);
34 static void log_memstats(int log_priority);
35
36 static const struct message mstr [] =
37 {
38   { MTYPE_THREAD, "thread" },
39   { MTYPE_THREAD_MASTER, "thread_master" },
40   { MTYPE_VECTOR, "vector" },
41   { MTYPE_VECTOR_INDEX, "vector_index" },
42   { MTYPE_IF, "interface" },
43   { 0, NULL },
44 };
45
46 /* Fatal memory allocation error occurred. */
47 static void __attribute__ ((noreturn))
48 zerror (const char *fname, int type, size_t size)
49 {
50   zlog_err ("%s : can't allocate memory for `%s' size %d: %s\n", 
51             fname, lookup (mstr, type), (int) size, safe_strerror(errno));
52   log_memstats(LOG_WARNING);
53   /* N.B. It might be preferable to call zlog_backtrace_sigsafe here, since
54      that function should definitely be safe in an OOM condition.  But
55      unfortunately zlog_backtrace_sigsafe does not support syslog logging at
56      this time... */
57   zlog_backtrace(LOG_WARNING);
58   abort();
59 }
60
61 /*
62  * Allocate memory of a given size, to be tracked by a given type.
63  * Effects: Returns a pointer to usable memory.  If memory cannot
64  * be allocated, aborts execution.
65  */
66 void *
67 zmalloc (int type, size_t size)
68 {
69   void *memory;
70
71   memory = malloc (size);
72
73   if (memory == NULL)
74     zerror ("malloc", type, size);
75
76   alloc_inc (type);
77
78   return memory;
79 }
80
81 /*
82  * Allocate memory as in zmalloc, and also clear the memory.
83  * Add an extra 'z' prefix to function name to avoid collision when linking
84  * statically with zlib that exports the 'zcalloc' symbol.
85  */
86 void *
87 zzcalloc (int type, size_t size)
88 {
89   void *memory;
90
91   memory = calloc (1, size);
92
93   if (memory == NULL)
94     zerror ("calloc", type, size);
95
96   alloc_inc (type);
97
98   return memory;
99 }
100
101 /* 
102  * Given a pointer returned by zmalloc or zzcalloc, free it and
103  * return a pointer to a new size, basically acting like realloc().
104  * Requires: ptr was returned by zmalloc, zzcalloc, or zrealloc with the
105  * same type.
106  * Effects: Returns a pointer to the new memory, or aborts.
107  */
108 void *
109 zrealloc (int type, void *ptr, size_t size)
110 {
111   void *memory;
112
113   if (ptr == NULL)              /* is really alloc */
114       return zzcalloc(type, size);
115
116   memory = realloc (ptr, size);
117   if (memory == NULL)
118     zerror ("realloc", type, size);
119   if (ptr == NULL)
120     alloc_inc (type);
121
122   return memory;
123 }
124
125 /*
126  * Free memory allocated by z*alloc or zstrdup.
127  * Requires: ptr was returned by zmalloc, zzcalloc, or zrealloc with the
128  * same type.
129  * Effects: The memory is freed and may no longer be referenced.
130  */
131 void
132 zfree (int type, void *ptr)
133 {
134   if (ptr != NULL)
135     {
136       alloc_dec (type);
137       free (ptr);
138     }
139 }
140
141 /*
142  * Duplicate a string, counting memory usage by type.
143  * Effects: The string is duplicated, and the return value must
144  * eventually be passed to zfree with the same type.  The function will
145  * succeed or abort.
146  */
147 char *
148 zstrdup (int type, const char *str)
149 {
150   void *dup;
151
152   dup = strdup (str);
153   if (dup == NULL)
154     zerror ("strdup", type, strlen (str));
155   alloc_inc (type);
156   return dup;
157 }
158
159 #ifdef MEMORY_LOG
160 static struct 
161 {
162   const char *name;
163   long alloc;
164   unsigned long t_malloc;
165   unsigned long c_malloc;
166   unsigned long t_calloc;
167   unsigned long c_calloc;
168   unsigned long t_realloc;
169   unsigned long t_free;
170   unsigned long c_strdup;
171 } mstat [MTYPE_MAX];
172
173 static void
174 mtype_log (char *func, void *memory, const char *file, int line, int type)
175 {
176   zlog_debug ("%s: %s %p %s %d", func, lookup (mstr, type), memory, file, line);
177 }
178
179 void *
180 mtype_zmalloc (const char *file, int line, int type, size_t size)
181 {
182   void *memory;
183
184   mstat[type].c_malloc++;
185   mstat[type].t_malloc++;
186
187   memory = zmalloc (type, size);
188   mtype_log ("zmalloc", memory, file, line, type);
189
190   return memory;
191 }
192
193 void *
194 mtype_zcalloc (const char *file, int line, int type, size_t size)
195 {
196   void *memory;
197
198   mstat[type].c_calloc++;
199   mstat[type].t_calloc++;
200
201   memory = zzcalloc (type, size);
202   mtype_log ("xcalloc", memory, file, line, type);
203
204   return memory;
205 }
206
207 void *
208 mtype_zrealloc (const char *file, int line, int type, void *ptr, size_t size)
209 {
210   void *memory;
211
212   /* Realloc need before allocated pointer. */
213   mstat[type].t_realloc++;
214
215   memory = zrealloc (type, ptr, size);
216
217   mtype_log ("xrealloc", memory, file, line, type);
218
219   return memory;
220 }
221
222 /* Important function. */
223 void 
224 mtype_zfree (const char *file, int line, int type, void *ptr)
225 {
226   mstat[type].t_free++;
227
228   mtype_log ("xfree", ptr, file, line, type);
229
230   zfree (type, ptr);
231 }
232
233 char *
234 mtype_zstrdup (const char *file, int line, int type, const char *str)
235 {
236   char *memory;
237
238   mstat[type].c_strdup++;
239
240   memory = zstrdup (type, str);
241   
242   mtype_log ("xstrdup", memory, file, line, type);
243
244   return memory;
245 }
246 #else
247 static struct 
248 {
249   char *name;
250   long alloc;
251 } mstat [MTYPE_MAX];
252 #endif /* MEMORY_LOG */
253
254 /* Increment allocation counter. */
255 static void
256 alloc_inc (int type)
257 {
258   mstat[type].alloc++;
259 }
260
261 /* Decrement allocation counter. */
262 static void
263 alloc_dec (int type)
264 {
265   mstat[type].alloc--;
266 }
267
268 /* Looking up memory status from vty interface. */
269 #include "vector.h"
270 #include "vty.h"
271 #include "command.h"
272
273 static void
274 log_memstats(int pri)
275 {
276   struct mlist *ml;
277
278   for (ml = mlists; ml->list; ml++)
279     {
280       struct memory_list *m;
281
282       zlog (NULL, pri, "Memory utilization in module %s:", ml->name);
283       for (m = ml->list; m->index >= 0; m++)
284         if (m->index && mstat[m->index].alloc)
285           zlog (NULL, pri, "  %-30s: %10ld", m->format, mstat[m->index].alloc);
286     }
287 }
288
289 void
290 log_memstats_stderr (const char *prefix)
291 {
292   struct mlist *ml;
293   struct memory_list *m;
294   int i;
295   int j = 0;
296
297   for (ml = mlists; ml->list; ml++)
298     {
299       i = 0;
300
301       for (m = ml->list; m->index >= 0; m++)
302         if (m->index && mstat[m->index].alloc)
303           {
304             if (!i)
305               fprintf (stderr,
306                        "%s: memstats: Current memory utilization in module %s:\n",
307                        prefix,
308                        ml->name);
309             fprintf (stderr,
310                      "%s: memstats:  %-30s: %10ld%s\n",
311                      prefix,
312                      m->format,
313                      mstat[m->index].alloc,
314                      mstat[m->index].alloc < 0 ? " (REPORT THIS BUG!)" : "");
315             i = j = 1;
316           }
317     }
318
319   if (j)
320     fprintf (stderr,
321              "%s: memstats: NOTE: If configuration exists, utilization may be "
322              "expected.\n",
323              prefix);
324   else
325     fprintf (stderr,
326              "%s: memstats: No remaining tracked memory utilization.\n",
327              prefix);
328 }
329
330 static void
331 show_separator(struct vty *vty)
332 {
333   vty_out (vty, "-----------------------------\r\n");
334 }
335
336 static int
337 show_memory_vty (struct vty *vty, struct memory_list *list)
338 {
339   struct memory_list *m;
340   int needsep = 0;
341
342   for (m = list; m->index >= 0; m++)
343     if (m->index == 0)
344       {
345         if (needsep)
346           {
347             show_separator (vty);
348             needsep = 0;
349           }
350       }
351     else if (mstat[m->index].alloc)
352       {
353         vty_out (vty, "%-30s: %10ld\r\n", m->format, mstat[m->index].alloc);
354         needsep = 1;
355       }
356   return needsep;
357 }
358
359 #ifdef HAVE_MALLINFO
360 static int
361 show_memory_mallinfo (struct vty *vty)
362 {
363   struct mallinfo minfo = mallinfo();
364   char buf[MTYPE_MEMSTR_LEN];
365   
366   vty_out (vty, "System allocator statistics:%s", VTY_NEWLINE);
367   vty_out (vty, "  Total heap allocated:  %s%s",
368            mtype_memstr (buf, MTYPE_MEMSTR_LEN, minfo.arena),
369            VTY_NEWLINE);
370   vty_out (vty, "  Holding block headers: %s%s",
371            mtype_memstr (buf, MTYPE_MEMSTR_LEN, minfo.hblkhd),
372            VTY_NEWLINE);
373   vty_out (vty, "  Used small blocks:     %s%s",
374            mtype_memstr (buf, MTYPE_MEMSTR_LEN, minfo.usmblks),
375            VTY_NEWLINE);
376   vty_out (vty, "  Used ordinary blocks:  %s%s",
377            mtype_memstr (buf, MTYPE_MEMSTR_LEN, minfo.uordblks),
378            VTY_NEWLINE);
379   vty_out (vty, "  Free small blocks:     %s%s",
380            mtype_memstr (buf, MTYPE_MEMSTR_LEN, minfo.fsmblks),
381            VTY_NEWLINE);
382   vty_out (vty, "  Free ordinary blocks:  %s%s",
383            mtype_memstr (buf, MTYPE_MEMSTR_LEN, minfo.fordblks),
384            VTY_NEWLINE);
385   vty_out (vty, "  Ordinary blocks:       %ld%s",
386            (unsigned long)minfo.ordblks,
387            VTY_NEWLINE);
388   vty_out (vty, "  Small blocks:          %ld%s",
389            (unsigned long)minfo.smblks,
390            VTY_NEWLINE);
391   vty_out (vty, "  Holding blocks:        %ld%s",
392            (unsigned long)minfo.hblks,
393            VTY_NEWLINE);
394   vty_out (vty, "(see system documentation for 'mallinfo' for meaning)%s",
395            VTY_NEWLINE);
396   return 1;
397 }
398 #endif /* HAVE_MALLINFO */
399
400 DEFUN (show_memory,
401        show_memory_cmd,
402        "show memory",
403        "Show running system information\n"
404        "Memory statistics\n")
405 {
406   struct mlist *ml;
407   int needsep = 0;
408   
409 #ifdef HAVE_MALLINFO
410   needsep = show_memory_mallinfo (vty);
411 #endif /* HAVE_MALLINFO */
412   
413   for (ml = mlists; ml->list; ml++)
414     {
415       if (needsep)
416         show_separator (vty);
417       needsep = show_memory_vty (vty, ml->list);
418     }
419
420   return CMD_SUCCESS;
421 }
422
423
424 void
425 memory_init (void)
426 {
427   install_element (RESTRICTED_NODE, &show_memory_cmd);
428
429   install_element (VIEW_NODE, &show_memory_cmd);
430 }
431
432 /* Stats querying from users */
433 /* Return a pointer to a human friendly string describing
434  * the byte count passed in. E.g:
435  * "0 bytes", "2048 bytes", "110kB", "500MiB", "11GiB", etc.
436  * Up to 4 significant figures will be given.
437  * The pointer returned may be NULL (indicating an error)
438  * or point to the given buffer, or point to static storage.
439  */
440 const char *
441 mtype_memstr (char *buf, size_t len, unsigned long bytes)
442 {
443   unsigned int m, k;
444
445   /* easy cases */
446   if (!bytes)
447     return "0 bytes";
448   if (bytes == 1)
449     return "1 byte";
450
451   /*
452    * When we pass the 2gb barrier mallinfo() can no longer report
453    * correct data so it just does something odd...
454    * Reporting like Terrabytes of data.  Which makes users...
455    * edgy.. yes edgy that's the term for it.
456    * So let's just give up gracefully
457    */
458   if (bytes > 0x7fffffff)
459     return "> 2GB";
460
461   m = bytes >> 20;
462   k = bytes >> 10;
463
464  if (m > 10)
465     {
466       if (bytes & (1 << 19))
467         m++;
468       snprintf (buf, len, "%d MiB", m);
469     }
470   else if (k > 10)
471     {
472       if (bytes & (1 << 9))
473         k++;
474       snprintf (buf, len, "%d KiB", k);
475     }
476   else
477     snprintf (buf, len, "%ld bytes", bytes);
478   
479   return buf;
480 }
481
482 unsigned long
483 mtype_stats_alloc (int type)
484 {
485   return mstat[type].alloc;
486 }