The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/kern/kern_malloc.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*-
    2  * Copyright (c) 1987, 1991, 1993
    3  *      The Regents of the University of California.
    4  * Copyright (c) 2005 Robert N. M. Watson
    5  * All rights reserved.
    6  *
    7  * Redistribution and use in source and binary forms, with or without
    8  * modification, are permitted provided that the following conditions
    9  * are met:
   10  * 1. Redistributions of source code must retain the above copyright
   11  *    notice, this list of conditions and the following disclaimer.
   12  * 2. Redistributions in binary form must reproduce the above copyright
   13  *    notice, this list of conditions and the following disclaimer in the
   14  *    documentation and/or other materials provided with the distribution.
   15  * 4. Neither the name of the University nor the names of its contributors
   16  *    may be used to endorse or promote products derived from this software
   17  *    without specific prior written permission.
   18  *
   19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   29  * SUCH DAMAGE.
   30  *
   31  *      @(#)kern_malloc.c       8.3 (Berkeley) 1/4/94
   32  */
   33 
   34 #include <sys/cdefs.h>
   35 __FBSDID("$FreeBSD: releng/6.1/sys/kern/kern_malloc.c 158179 2006-04-30 16:44:43Z cvs2svn $");
   36 
   37 #include "opt_ddb.h"
   38 #include "opt_vm.h"
   39 
   40 #include <sys/param.h>
   41 #include <sys/systm.h>
   42 #include <sys/kdb.h>
   43 #include <sys/kernel.h>
   44 #include <sys/lock.h>
   45 #include <sys/malloc.h>
   46 #include <sys/mbuf.h>
   47 #include <sys/mutex.h>
   48 #include <sys/vmmeter.h>
   49 #include <sys/proc.h>
   50 #include <sys/sbuf.h>
   51 #include <sys/sysctl.h>
   52 #include <sys/time.h>
   53 
   54 #include <vm/vm.h>
   55 #include <vm/pmap.h>
   56 #include <vm/vm_param.h>
   57 #include <vm/vm_kern.h>
   58 #include <vm/vm_extern.h>
   59 #include <vm/vm_map.h>
   60 #include <vm/vm_page.h>
   61 #include <vm/uma.h>
   62 #include <vm/uma_int.h>
   63 #include <vm/uma_dbg.h>
   64 
   65 #ifdef DEBUG_MEMGUARD
   66 #include <vm/memguard.h>
   67 #endif
   68 
   69 #if defined(INVARIANTS) && defined(__i386__)
   70 #include <machine/cpu.h>
   71 #endif
   72 
   73 #include <ddb/ddb.h>
   74 
   75 /*
   76  * When realloc() is called, if the new size is sufficiently smaller than
   77  * the old size, realloc() will allocate a new, smaller block to avoid
   78  * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
   79  * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
   80  */
   81 #ifndef REALLOC_FRACTION
   82 #define REALLOC_FRACTION        1       /* new block if <= half the size */
   83 #endif
   84 
   85 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
   86 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
   87 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
   88 
   89 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
   90 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
   91 
   92 static void kmeminit(void *);
   93 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, kmeminit, NULL)
   94 
   95 static MALLOC_DEFINE(M_FREE, "free", "should be on free list");
   96 
   97 static struct malloc_type *kmemstatistics;
   98 static char *kmembase;
   99 static char *kmemlimit;
  100 static int kmemcount;
  101 
  102 #define KMEM_ZSHIFT     4
  103 #define KMEM_ZBASE      16
  104 #define KMEM_ZMASK      (KMEM_ZBASE - 1)
  105 
  106 #define KMEM_ZMAX       PAGE_SIZE
  107 #define KMEM_ZSIZE      (KMEM_ZMAX >> KMEM_ZSHIFT)
  108 static u_int8_t kmemsize[KMEM_ZSIZE + 1];
  109 
  110 /* These won't be powers of two for long */
  111 struct {
  112         int kz_size;
  113         char *kz_name;
  114         uma_zone_t kz_zone;
  115 } kmemzones[] = {
  116         {16, "16", NULL},
  117         {32, "32", NULL},
  118         {64, "64", NULL},
  119         {128, "128", NULL},
  120         {256, "256", NULL},
  121         {512, "512", NULL},
  122         {1024, "1024", NULL},
  123         {2048, "2048", NULL},
  124         {4096, "4096", NULL},
  125 #if PAGE_SIZE > 4096
  126         {8192, "8192", NULL},
  127 #if PAGE_SIZE > 8192
  128         {16384, "16384", NULL},
  129 #if PAGE_SIZE > 16384
  130         {32768, "32768", NULL},
  131 #if PAGE_SIZE > 32768
  132         {65536, "65536", NULL},
  133 #if PAGE_SIZE > 65536
  134 #error  "Unsupported PAGE_SIZE"
  135 #endif  /* 65536 */
  136 #endif  /* 32768 */
  137 #endif  /* 16384 */
  138 #endif  /* 8192 */
  139 #endif  /* 4096 */
  140         {0, NULL},
  141 };
  142 
  143 static uma_zone_t mt_zone;
  144 
  145 #ifdef DEBUG_MEMGUARD
  146 u_int vm_memguard_divisor;
  147 SYSCTL_UINT(_vm, OID_AUTO, memguard_divisor, CTLFLAG_RD, &vm_memguard_divisor,
  148     0, "(kmem_size/memguard_divisor) == memguard submap size");
  149 #endif
  150 
  151 u_int vm_kmem_size;
  152 SYSCTL_UINT(_vm, OID_AUTO, kmem_size, CTLFLAG_RD, &vm_kmem_size, 0,
  153     "Size of kernel memory");
  154 
  155 u_int vm_kmem_size_max;
  156 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RD, &vm_kmem_size_max, 0,
  157     "Maximum size of kernel memory");
  158 
  159 u_int vm_kmem_size_scale;
  160 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RD, &vm_kmem_size_scale, 0,
  161     "Scale factor for kernel memory size");
  162 
  163 /*
  164  * The malloc_mtx protects the kmemstatistics linked list.
  165  */
  166 
  167 struct mtx malloc_mtx;
  168 
  169 #ifdef MALLOC_PROFILE
  170 uint64_t krequests[KMEM_ZSIZE + 1];
  171 
  172 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
  173 #endif
  174 
  175 static int sysctl_kern_malloc(SYSCTL_HANDLER_ARGS);
  176 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
  177 
  178 /* time_uptime of last malloc(9) failure */
  179 static time_t t_malloc_fail;
  180 
  181 #ifdef MALLOC_MAKE_FAILURES
  182 /*
  183  * Causes malloc failures every (n) mallocs with M_NOWAIT.  If set to 0,
  184  * doesn't cause failures.
  185  */
  186 SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0,
  187     "Kernel malloc debugging options");
  188 
  189 static int malloc_failure_rate;
  190 static int malloc_nowait_count;
  191 static int malloc_failure_count;
  192 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RW,
  193     &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
  194 TUNABLE_INT("debug.malloc.failure_rate", &malloc_failure_rate);
  195 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
  196     &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
  197 #endif
  198 
  199 int
  200 malloc_last_fail(void)
  201 {
  202 
  203         return (time_uptime - t_malloc_fail);
  204 }
  205 
  206 /*
  207  * Add this to the informational malloc_type bucket.
  208  */
  209 static void
  210 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
  211     int zindx)
  212 {
  213         struct malloc_type_internal *mtip;
  214         struct malloc_type_stats *mtsp;
  215 
  216         critical_enter();
  217         mtip = mtp->ks_handle;
  218         mtsp = &mtip->mti_stats[curcpu];
  219         if (size > 0) {
  220                 mtsp->mts_memalloced += size;
  221                 mtsp->mts_numallocs++;
  222         }
  223         if (zindx != -1)
  224                 mtsp->mts_size |= 1 << zindx;
  225         critical_exit();
  226 }
  227 
  228 void
  229 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
  230 {
  231 
  232         if (size > 0)
  233                 malloc_type_zone_allocated(mtp, size, -1);
  234 }
  235 
  236 /*
  237  * Remove this allocation from the informational malloc_type bucket.
  238  */
  239 void
  240 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
  241 {
  242         struct malloc_type_internal *mtip;
  243         struct malloc_type_stats *mtsp;
  244 
  245         critical_enter();
  246         mtip = mtp->ks_handle;
  247         mtsp = &mtip->mti_stats[curcpu];
  248         mtsp->mts_memfreed += size;
  249         mtsp->mts_numfrees++;
  250         critical_exit();
  251 }
  252 
  253 /*
  254  *      malloc:
  255  *
  256  *      Allocate a block of memory.
  257  *
  258  *      If M_NOWAIT is set, this routine will not block and return NULL if
  259  *      the allocation fails.
  260  */
  261 void *
  262 malloc(unsigned long size, struct malloc_type *mtp, int flags)
  263 {
  264         int indx;
  265         caddr_t va;
  266         uma_zone_t zone;
  267         uma_keg_t keg;
  268 #ifdef DIAGNOSTIC
  269         unsigned long osize = size;
  270 #endif
  271 
  272 #ifdef INVARIANTS
  273         /*
  274          * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
  275          */
  276         indx = flags & (M_WAITOK | M_NOWAIT);
  277         if (indx != M_NOWAIT && indx != M_WAITOK) {
  278                 static  struct timeval lasterr;
  279                 static  int curerr, once;
  280                 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
  281                         printf("Bad malloc flags: %x\n", indx);
  282                         kdb_backtrace();
  283                         flags |= M_WAITOK;
  284                         once++;
  285                 }
  286         }
  287 #endif
  288 #if 0
  289         if (size == 0)
  290                 kdb_enter("zero size malloc");
  291 #endif
  292 #ifdef MALLOC_MAKE_FAILURES
  293         if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
  294                 atomic_add_int(&malloc_nowait_count, 1);
  295                 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
  296                         atomic_add_int(&malloc_failure_count, 1);
  297                         t_malloc_fail = time_uptime;
  298                         return (NULL);
  299                 }
  300         }
  301 #endif
  302         if (flags & M_WAITOK)
  303                 KASSERT(curthread->td_intr_nesting_level == 0,
  304                    ("malloc(M_WAITOK) in interrupt context"));
  305 
  306 #ifdef DEBUG_MEMGUARD
  307         /* XXX CHANGEME! */
  308         if (mtp == M_SUBPROC)
  309                 return memguard_alloc(size, flags);
  310 #endif
  311 
  312         if (size <= KMEM_ZMAX) {
  313                 if (size & KMEM_ZMASK)
  314                         size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
  315                 indx = kmemsize[size >> KMEM_ZSHIFT];
  316                 zone = kmemzones[indx].kz_zone;
  317                 keg = zone->uz_keg;
  318 #ifdef MALLOC_PROFILE
  319                 krequests[size >> KMEM_ZSHIFT]++;
  320 #endif
  321                 va = uma_zalloc(zone, flags);
  322                 if (va != NULL)
  323                         size = keg->uk_size;
  324                 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
  325         } else {
  326                 size = roundup(size, PAGE_SIZE);
  327                 zone = NULL;
  328                 keg = NULL;
  329                 va = uma_large_malloc(size, flags);
  330                 malloc_type_allocated(mtp, va == NULL ? 0 : size);
  331         }
  332         if (flags & M_WAITOK)
  333                 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
  334         else if (va == NULL)
  335                 t_malloc_fail = time_uptime;
  336 #ifdef DIAGNOSTIC
  337         if (va != NULL && !(flags & M_ZERO)) {
  338                 memset(va, 0x70, osize);
  339         }
  340 #endif
  341         return ((void *) va);
  342 }
  343 
  344 /*
  345  *      free:
  346  *
  347  *      Free a block of memory allocated by malloc.
  348  *
  349  *      This routine may not block.
  350  */
  351 void
  352 free(void *addr, struct malloc_type *mtp)
  353 {
  354         uma_slab_t slab;
  355         u_long size;
  356 
  357         /* free(NULL, ...) does nothing */
  358         if (addr == NULL)
  359                 return;
  360 
  361 #ifdef DEBUG_MEMGUARD
  362         /* XXX CHANGEME! */
  363         if (mtp == M_SUBPROC) {
  364                 memguard_free(addr);
  365                 return;
  366         }
  367 #endif
  368 
  369         size = 0;
  370 
  371         slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
  372 
  373         if (slab == NULL)
  374                 panic("free: address %p(%p) has not been allocated.\n",
  375                     addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
  376 
  377 
  378         if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
  379 #ifdef INVARIANTS
  380                 struct malloc_type **mtpp = addr;
  381 #endif
  382                 size = slab->us_keg->uk_size;
  383 #ifdef INVARIANTS
  384                 /*
  385                  * Cache a pointer to the malloc_type that most recently freed
  386                  * this memory here.  This way we know who is most likely to
  387                  * have stepped on it later.
  388                  *
  389                  * This code assumes that size is a multiple of 8 bytes for
  390                  * 64 bit machines
  391                  */
  392                 mtpp = (struct malloc_type **)
  393                     ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
  394                 mtpp += (size - sizeof(struct malloc_type *)) /
  395                     sizeof(struct malloc_type *);
  396                 *mtpp = mtp;
  397 #endif
  398                 uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
  399         } else {
  400                 size = slab->us_size;
  401                 uma_large_free(slab);
  402         }
  403         malloc_type_freed(mtp, size);
  404 }
  405 
  406 /*
  407  *      realloc: change the size of a memory block
  408  */
  409 void *
  410 realloc(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
  411 {
  412         uma_slab_t slab;
  413         unsigned long alloc;
  414         void *newaddr;
  415 
  416         /* realloc(NULL, ...) is equivalent to malloc(...) */
  417         if (addr == NULL)
  418                 return (malloc(size, mtp, flags));
  419 
  420         /*
  421          * XXX: Should report free of old memory and alloc of new memory to
  422          * per-CPU stats.
  423          */
  424 
  425 #ifdef DEBUG_MEMGUARD
  426 /* XXX: CHANGEME! */
  427 if (mtp == M_SUBPROC) {
  428         slab = NULL;
  429         alloc = size;
  430 } else {
  431 #endif
  432 
  433         slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
  434 
  435         /* Sanity check */
  436         KASSERT(slab != NULL,
  437             ("realloc: address %p out of range", (void *)addr));
  438 
  439         /* Get the size of the original block */
  440         if (!(slab->us_flags & UMA_SLAB_MALLOC))
  441                 alloc = slab->us_keg->uk_size;
  442         else
  443                 alloc = slab->us_size;
  444 
  445         /* Reuse the original block if appropriate */
  446         if (size <= alloc
  447             && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
  448                 return (addr);
  449 
  450 #ifdef DEBUG_MEMGUARD
  451 }
  452 #endif
  453 
  454         /* Allocate a new, bigger (or smaller) block */
  455         if ((newaddr = malloc(size, mtp, flags)) == NULL)
  456                 return (NULL);
  457 
  458         /* Copy over original contents */
  459         bcopy(addr, newaddr, min(size, alloc));
  460         free(addr, mtp);
  461         return (newaddr);
  462 }
  463 
  464 /*
  465  *      reallocf: same as realloc() but free memory on failure.
  466  */
  467 void *
  468 reallocf(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
  469 {
  470         void *mem;
  471 
  472         if ((mem = realloc(addr, size, mtp, flags)) == NULL)
  473                 free(addr, mtp);
  474         return (mem);
  475 }
  476 
  477 /*
  478  * Initialize the kernel memory allocator
  479  */
  480 /* ARGSUSED*/
  481 static void
  482 kmeminit(void *dummy)
  483 {
  484         u_int8_t indx;
  485         u_long mem_size;
  486         int i;
  487  
  488         mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
  489 
  490         /*
  491          * Try to auto-tune the kernel memory size, so that it is
  492          * more applicable for a wider range of machine sizes.
  493          * On an X86, a VM_KMEM_SIZE_SCALE value of 4 is good, while
  494          * a VM_KMEM_SIZE of 12MB is a fair compromise.  The
  495          * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
  496          * available, and on an X86 with a total KVA space of 256MB,
  497          * try to keep VM_KMEM_SIZE_MAX at 80MB or below.
  498          *
  499          * Note that the kmem_map is also used by the zone allocator,
  500          * so make sure that there is enough space.
  501          */
  502         vm_kmem_size = VM_KMEM_SIZE + nmbclusters * PAGE_SIZE;
  503         mem_size = cnt.v_page_count;
  504 
  505 #if defined(VM_KMEM_SIZE_SCALE)
  506         vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
  507 #endif
  508         TUNABLE_INT_FETCH("vm.kmem_size_scale", &vm_kmem_size_scale);
  509         if (vm_kmem_size_scale > 0 &&
  510             (mem_size / vm_kmem_size_scale) > (vm_kmem_size / PAGE_SIZE))
  511                 vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
  512 
  513 #if defined(VM_KMEM_SIZE_MAX)
  514         vm_kmem_size_max = VM_KMEM_SIZE_MAX;
  515 #endif
  516         TUNABLE_INT_FETCH("vm.kmem_size_max", &vm_kmem_size_max);
  517         if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
  518                 vm_kmem_size = vm_kmem_size_max;
  519 
  520         /* Allow final override from the kernel environment */
  521 #ifndef BURN_BRIDGES
  522         if (TUNABLE_INT_FETCH("kern.vm.kmem.size", &vm_kmem_size) != 0)
  523                 printf("kern.vm.kmem.size is now called vm.kmem_size!\n");
  524 #endif
  525         TUNABLE_INT_FETCH("vm.kmem_size", &vm_kmem_size);
  526 
  527         /*
  528          * Limit kmem virtual size to twice the physical memory.
  529          * This allows for kmem map sparseness, but limits the size
  530          * to something sane. Be careful to not overflow the 32bit
  531          * ints while doing the check.
  532          */
  533         if (((vm_kmem_size / 2) / PAGE_SIZE) > cnt.v_page_count)
  534                 vm_kmem_size = 2 * cnt.v_page_count * PAGE_SIZE;
  535 
  536         /*
  537          * Tune settings based on the kernel map's size at this time.
  538          */
  539         init_param3(vm_kmem_size / PAGE_SIZE);
  540 
  541         kmem_map = kmem_suballoc(kernel_map, (vm_offset_t *)&kmembase,
  542                 (vm_offset_t *)&kmemlimit, vm_kmem_size);
  543         kmem_map->system_map = 1;
  544 
  545 #ifdef DEBUG_MEMGUARD
  546         /*
  547          * Initialize MemGuard if support compiled in.  MemGuard is a
  548          * replacement allocator used for detecting tamper-after-free
  549          * scenarios as they occur.  It is only used for debugging.
  550          */
  551         vm_memguard_divisor = 10;
  552         TUNABLE_INT_FETCH("vm.memguard_divisor", &vm_memguard_divisor);
  553 
  554         /* Pick a conservative value if provided value sucks. */
  555         if ((vm_memguard_divisor <= 0) ||
  556             ((vm_kmem_size / vm_memguard_divisor) == 0))
  557                 vm_memguard_divisor = 10;
  558         memguard_init(kmem_map, vm_kmem_size / vm_memguard_divisor);
  559 #endif
  560 
  561         uma_startup2();
  562 
  563         mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
  564 #ifdef INVARIANTS
  565             mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
  566 #else
  567             NULL, NULL, NULL, NULL,
  568 #endif
  569             UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
  570         for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
  571                 int size = kmemzones[indx].kz_size;
  572                 char *name = kmemzones[indx].kz_name;
  573 
  574                 kmemzones[indx].kz_zone = uma_zcreate(name, size,
  575 #ifdef INVARIANTS
  576                     mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
  577 #else
  578                     NULL, NULL, NULL, NULL,
  579 #endif
  580                     UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
  581                     
  582                 for (;i <= size; i+= KMEM_ZBASE)
  583                         kmemsize[i >> KMEM_ZSHIFT] = indx;
  584                 
  585         }
  586 }
  587 
  588 void
  589 malloc_init(void *data)
  590 {
  591         struct malloc_type_internal *mtip;
  592         struct malloc_type *mtp;
  593 
  594         KASSERT(cnt.v_page_count != 0, ("malloc_register before vm_init"));
  595 
  596         mtp = data;
  597         mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
  598         mtp->ks_handle = mtip;
  599 
  600         mtx_lock(&malloc_mtx);
  601         mtp->ks_next = kmemstatistics;
  602         kmemstatistics = mtp;
  603         kmemcount++;
  604         mtx_unlock(&malloc_mtx);
  605 }
  606 
  607 void
  608 malloc_uninit(void *data)
  609 {
  610         struct malloc_type_internal *mtip;
  611         struct malloc_type_stats *mtsp;
  612         struct malloc_type *mtp, *temp;
  613         uma_slab_t slab;
  614         long temp_allocs, temp_bytes;
  615         int i;
  616 
  617         mtp = data;
  618         KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
  619         mtx_lock(&malloc_mtx);
  620         mtip = mtp->ks_handle;
  621         mtp->ks_handle = NULL;
  622         if (mtp != kmemstatistics) {
  623                 for (temp = kmemstatistics; temp != NULL;
  624                     temp = temp->ks_next) {
  625                         if (temp->ks_next == mtp)
  626                                 temp->ks_next = mtp->ks_next;
  627                 }
  628         } else
  629                 kmemstatistics = mtp->ks_next;
  630         kmemcount--;
  631         mtx_unlock(&malloc_mtx);
  632 
  633         /*
  634          * Look for memory leaks.
  635          */
  636         temp_allocs = temp_bytes = 0;
  637         for (i = 0; i < MAXCPU; i++) {
  638                 mtsp = &mtip->mti_stats[i];
  639                 temp_allocs += mtsp->mts_numallocs;
  640                 temp_allocs -= mtsp->mts_numfrees;
  641                 temp_bytes += mtsp->mts_memalloced;
  642                 temp_bytes -= mtsp->mts_memfreed;
  643         }
  644         if (temp_allocs > 0 || temp_bytes > 0) {
  645                 printf("Warning: memory type %s leaked memory on destroy "
  646                     "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
  647                     temp_allocs, temp_bytes);
  648         }
  649 
  650         slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
  651         uma_zfree_arg(mt_zone, mtip, slab);
  652 }
  653 
  654 static int
  655 sysctl_kern_malloc(SYSCTL_HANDLER_ARGS)
  656 {
  657         struct malloc_type_stats mts_local, *mtsp;
  658         struct malloc_type_internal *mtip;
  659         struct malloc_type *mtp;
  660         struct sbuf sbuf;
  661         long temp_allocs, temp_bytes;
  662         int linesize = 128;
  663         int bufsize;
  664         int first;
  665         int error;
  666         char *buf;
  667         int cnt;
  668         int i;
  669 
  670         cnt = 0;
  671 
  672         /* Guess at how much room is needed. */
  673         mtx_lock(&malloc_mtx);
  674         cnt = kmemcount;
  675         mtx_unlock(&malloc_mtx);
  676 
  677         bufsize = linesize * (cnt + 1);
  678         buf = malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO);
  679         sbuf_new(&sbuf, buf, bufsize, SBUF_FIXEDLEN);
  680 
  681         mtx_lock(&malloc_mtx);
  682         sbuf_printf(&sbuf,
  683             "\n        Type  InUse MemUse HighUse Requests  Size(s)\n");
  684         for (mtp = kmemstatistics; cnt != 0 && mtp != NULL;
  685             mtp = mtp->ks_next, cnt--) {
  686                 mtip = mtp->ks_handle;
  687                 bzero(&mts_local, sizeof(mts_local));
  688                 for (i = 0; i < MAXCPU; i++) {
  689                         mtsp = &mtip->mti_stats[i];
  690                         mts_local.mts_memalloced += mtsp->mts_memalloced;
  691                         mts_local.mts_memfreed += mtsp->mts_memfreed;
  692                         mts_local.mts_numallocs += mtsp->mts_numallocs;
  693                         mts_local.mts_numfrees += mtsp->mts_numfrees;
  694                         mts_local.mts_size |= mtsp->mts_size;
  695                 }
  696                 if (mts_local.mts_numallocs == 0)
  697                         continue;
  698 
  699                 /*
  700                  * Due to races in per-CPU statistics gather, it's possible to
  701                  * get a slightly negative number here.  If we do, approximate
  702                  * with 0.
  703                  */
  704                 if (mts_local.mts_numallocs > mts_local.mts_numfrees)
  705                         temp_allocs = mts_local.mts_numallocs -
  706                             mts_local.mts_numfrees;
  707                 else
  708                         temp_allocs = 0;
  709 
  710                 /*
  711                  * Ditto for bytes allocated.
  712                  */
  713                 if (mts_local.mts_memalloced > mts_local.mts_memfreed)
  714                         temp_bytes = mts_local.mts_memalloced -
  715                             mts_local.mts_memfreed;
  716                 else
  717                         temp_bytes = 0;
  718 
  719                 /*
  720                  * High-waterwark is no longer easily available, so we just
  721                  * print '-' for that column.
  722                  */
  723                 sbuf_printf(&sbuf, "%13s%6lu%6luK       -%9llu",
  724                     mtp->ks_shortdesc,
  725                     temp_allocs,
  726                     (temp_bytes + 1023) / 1024,
  727                     (unsigned long long)mts_local.mts_numallocs);
  728 
  729                 first = 1;
  730                 for (i = 0; i < sizeof(kmemzones) / sizeof(kmemzones[0]) - 1;
  731                     i++) {
  732                         if (mts_local.mts_size & (1 << i)) {
  733                                 if (first)
  734                                         sbuf_printf(&sbuf, "  ");
  735                                 else
  736                                         sbuf_printf(&sbuf, ",");
  737                                 sbuf_printf(&sbuf, "%s",
  738                                     kmemzones[i].kz_name);
  739                                 first = 0;
  740                         }
  741                 }
  742                 sbuf_printf(&sbuf, "\n");
  743         }
  744         sbuf_finish(&sbuf);
  745         mtx_unlock(&malloc_mtx);
  746 
  747         error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
  748 
  749         sbuf_delete(&sbuf);
  750         free(buf, M_TEMP);
  751         return (error);
  752 }
  753 
  754 SYSCTL_OID(_kern, OID_AUTO, malloc, CTLTYPE_STRING|CTLFLAG_RD,
  755     NULL, 0, sysctl_kern_malloc, "A", "Malloc Stats");
  756 
  757 static int
  758 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
  759 {
  760         struct malloc_type_stream_header mtsh;
  761         struct malloc_type_internal *mtip;
  762         struct malloc_type_header mth;
  763         struct malloc_type *mtp;
  764         int buflen, count, error, i;
  765         struct sbuf sbuf;
  766         char *buffer;
  767 
  768         mtx_lock(&malloc_mtx);
  769 restart:
  770         mtx_assert(&malloc_mtx, MA_OWNED);
  771         count = kmemcount;
  772         mtx_unlock(&malloc_mtx);
  773         buflen = sizeof(mtsh) + count * (sizeof(mth) +
  774             sizeof(struct malloc_type_stats) * MAXCPU) + 1;
  775         buffer = malloc(buflen, M_TEMP, M_WAITOK | M_ZERO);
  776         mtx_lock(&malloc_mtx);
  777         if (count < kmemcount) {
  778                 free(buffer, M_TEMP);
  779                 goto restart;
  780         }
  781 
  782         sbuf_new(&sbuf, buffer, buflen, SBUF_FIXEDLEN);
  783 
  784         /*
  785          * Insert stream header.
  786          */
  787         bzero(&mtsh, sizeof(mtsh));
  788         mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
  789         mtsh.mtsh_maxcpus = MAXCPU;
  790         mtsh.mtsh_count = kmemcount;
  791         if (sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh)) < 0) {
  792                 mtx_unlock(&malloc_mtx);
  793                 error = ENOMEM;
  794                 goto out;
  795         }
  796 
  797         /*
  798          * Insert alternating sequence of type headers and type statistics.
  799          */
  800         for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
  801                 mtip = (struct malloc_type_internal *)mtp->ks_handle;
  802 
  803                 /*
  804                  * Insert type header.
  805                  */
  806                 bzero(&mth, sizeof(mth));
  807                 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
  808                 if (sbuf_bcat(&sbuf, &mth, sizeof(mth)) < 0) {
  809                         mtx_unlock(&malloc_mtx);
  810                         error = ENOMEM;
  811                         goto out;
  812                 }
  813 
  814                 /*
  815                  * Insert type statistics for each CPU.
  816                  */
  817                 for (i = 0; i < MAXCPU; i++) {
  818                         if (sbuf_bcat(&sbuf, &mtip->mti_stats[i],
  819                             sizeof(mtip->mti_stats[i])) < 0) {
  820                                 mtx_unlock(&malloc_mtx);
  821                                 error = ENOMEM;
  822                                 goto out;
  823                         }
  824                 }
  825         }
  826         mtx_unlock(&malloc_mtx);
  827         sbuf_finish(&sbuf);
  828         error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
  829 out:
  830         sbuf_delete(&sbuf);
  831         free(buffer, M_TEMP);
  832         return (error);
  833 }
  834 
  835 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
  836     0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
  837     "Return malloc types");
  838 
  839 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
  840     "Count of kernel malloc types");
  841 
  842 #ifdef DDB
  843 DB_SHOW_COMMAND(malloc, db_show_malloc)
  844 {
  845         struct malloc_type_internal *mtip;
  846         struct malloc_type *mtp;
  847         u_int64_t allocs, frees;
  848         int i;
  849 
  850         db_printf("%18s %12s %12s %12s\n", "Type", "Allocs", "Frees",
  851             "Used");
  852         for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
  853                 mtip = (struct malloc_type_internal *)mtp->ks_handle;
  854                 allocs = 0;
  855                 frees = 0;
  856                 for (i = 0; i < MAXCPU; i++) {
  857                         allocs += mtip->mti_stats[i].mts_numallocs;
  858                         frees += mtip->mti_stats[i].mts_numfrees;
  859                 }
  860                 db_printf("%18s %12ju %12ju %12ju\n", mtp->ks_shortdesc,
  861                     allocs, frees, allocs - frees);
  862         }
  863 }
  864 #endif
  865 
  866 #ifdef MALLOC_PROFILE
  867 
  868 static int
  869 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
  870 {
  871         int linesize = 64;
  872         struct sbuf sbuf;
  873         uint64_t count;
  874         uint64_t waste;
  875         uint64_t mem;
  876         int bufsize;
  877         int error;
  878         char *buf;
  879         int rsize;
  880         int size;
  881         int i;
  882 
  883         bufsize = linesize * (KMEM_ZSIZE + 1);
  884         bufsize += 128;         /* For the stats line */
  885         bufsize += 128;         /* For the banner line */
  886         waste = 0;
  887         mem = 0;
  888 
  889         buf = malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO);
  890         sbuf_new(&sbuf, buf, bufsize, SBUF_FIXEDLEN);
  891         sbuf_printf(&sbuf, 
  892             "\n  Size                    Requests  Real Size\n");
  893         for (i = 0; i < KMEM_ZSIZE; i++) {
  894                 size = i << KMEM_ZSHIFT;
  895                 rsize = kmemzones[kmemsize[i]].kz_size;
  896                 count = (long long unsigned)krequests[i];
  897 
  898                 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
  899                     (unsigned long long)count, rsize);
  900 
  901                 if ((rsize * count) > (size * count))
  902                         waste += (rsize * count) - (size * count);
  903                 mem += (rsize * count);
  904         }
  905         sbuf_printf(&sbuf,
  906             "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
  907             (unsigned long long)mem, (unsigned long long)waste);
  908         sbuf_finish(&sbuf);
  909 
  910         error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
  911 
  912         sbuf_delete(&sbuf);
  913         free(buf, M_TEMP);
  914         return (error);
  915 }
  916 
  917 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
  918     NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
  919 #endif /* MALLOC_PROFILE */

Cache object: a9f0c70112e97d45b015f3364159c6da


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.