2 * Copyright (c) 1998-2018 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
28 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
30 * Copyright (c) 1982, 1986, 1988, 1991, 1993
31 * The Regents of the University of California. All rights reserved.
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
36 * 1. Redistributions of source code must retain the above copyright
37 * notice, this list of conditions and the following disclaimer.
38 * 2. Redistributions in binary form must reproduce the above copyright
39 * notice, this list of conditions and the following disclaimer in the
40 * documentation and/or other materials provided with the distribution.
41 * 3. All advertising materials mentioning features or use of this software
42 * must display the following acknowledgement:
43 * This product includes software developed by the University of
44 * California, Berkeley and its contributors.
45 * 4. Neither the name of the University nor the names of its contributors
46 * may be used to endorse or promote products derived from this software
47 * without specific prior written permission.
49 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
61 * @(#)uipc_mbuf.c 8.2 (Berkeley) 1/4/94
64 * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
65 * support for mandatory and extensible security protections. This notice
66 * is included in support of clause 2.2 (b) of the Apple Public License,
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/malloc.h>
74 #include <sys/kernel.h>
75 #include <sys/sysctl.h>
76 #include <sys/syslog.h>
77 #include <sys/protosw.h>
78 #include <sys/domain.h>
79 #include <sys/queue.h>
82 #include <dev/random/randomdev.h>
84 #include <kern/kern_types.h>
85 #include <kern/simple_lock.h>
86 #include <kern/queue.h>
87 #include <kern/sched_prim.h>
88 #include <kern/backtrace.h>
89 #include <kern/cpu_number.h>
90 #include <kern/zalloc.h>
92 #include <libkern/OSAtomic.h>
93 #include <libkern/OSDebug.h>
94 #include <libkern/libkern.h>
98 #include <IOKit/IOMapper.h>
100 #include <machine/limits.h>
101 #include <machine/machine_routines.h>
104 #include <security/mac_framework.h>
107 #include <sys/mcache.h>
108 #include <net/ntstat.h>
111 * MBUF IMPLEMENTATION NOTES.
113 * There is a total of 5 per-CPU caches:
116 * This is a cache of rudimentary objects of MSIZE in size; each
117 * object represents an mbuf structure. This cache preserves only
118 * the m_type field of the mbuf during its transactions.
121 * This is a cache of rudimentary objects of MCLBYTES in size; each
122 * object represents a mcluster structure. This cache does not
123 * preserve the contents of the objects during its transactions.
126 * This is a cache of rudimentary objects of MBIGCLBYTES in size; each
127 * object represents a mbigcluster structure. This cache does not
128 * preserve the contents of the objects during its transaction.
131 * This is a cache of mbufs each having a cluster attached to it.
132 * It is backed by MC_MBUF and MC_CL rudimentary caches. Several
133 * fields of the mbuf related to the external cluster are preserved
134 * during transactions.
137 * This is a cache of mbufs each having a big cluster attached to it.
138 * It is backed by MC_MBUF and MC_BIGCL rudimentary caches. Several
139 * fields of the mbuf related to the external cluster are preserved
140 * during transactions.
144 * Allocation requests are handled first at the per-CPU (mcache) layer
145 * before falling back to the slab layer. Performance is optimal when
146 * the request is satisfied at the CPU layer because global data/lock
147 * never gets accessed. When the slab layer is entered for allocation,
148 * the slab freelist will be checked first for available objects before
149 * the VM backing store is invoked. Slab layer operations are serialized
150 * for all of the caches as the mbuf global lock is held most of the time.
151 * Allocation paths are different depending on the class of objects:
153 * a. Rudimentary object:
155 * { m_get_common(), m_clattach(), m_mclget(),
156 * m_mclalloc(), m_bigalloc(), m_copym_with_hdrs(),
157 * composite object allocation }
160 * | +-----------------------+
162 * mcache_alloc/mcache_alloc_ext() mbuf_slab_audit()
165 * [CPU cache] -------> (found?) -------+
168 * mbuf_slab_alloc() |
171 * +---------> [freelist] -------> (found?) -------+
177 * +---<<---- kmem_mb_alloc()
179 * b. Composite object:
181 * { m_getpackets_internal(), m_allocpacket_internal() }
184 * | +------ (done) ---------+
186 * mcache_alloc/mcache_alloc_ext() mbuf_cslab_audit()
189 * [CPU cache] -------> (found?) -------+
192 * mbuf_cslab_alloc() |
195 * [freelist] -------> (found?) -------+
198 * (rudimentary object) |
199 * mcache_alloc/mcache_alloc_ext() ------>>-----+
201 * Auditing notes: If auditing is enabled, buffers will be subjected to
202 * integrity checks by the audit routine. This is done by verifying their
203 * contents against DEADBEEF (free) pattern before returning them to caller.
204 * As part of this step, the routine will also record the transaction and
205 * pattern-fill the buffers with BADDCAFE (uninitialized) pattern. It will
206 * also restore any constructed data structure fields if necessary.
208 * OBJECT DEALLOCATION:
210 * Freeing an object simply involves placing it into the CPU cache; this
211 * pollutes the cache to benefit subsequent allocations. The slab layer
212 * will only be entered if the object is to be purged out of the cache.
213 * During normal operations, this happens only when the CPU layer resizes
214 * its bucket while it's adjusting to the allocation load. Deallocation
215 * paths are different depending on the class of objects:
217 * a. Rudimentary object:
219 * { m_free(), m_freem_list(), composite object deallocation }
222 * | +------ (done) ---------+
224 * mcache_free/mcache_free_ext() |
227 * mbuf_slab_audit() |
230 * [CPU cache] ---> (not purging?) -----+
236 * [freelist] ----------->>------------+
237 * (objects get purged to VM only on demand)
239 * b. Composite object:
241 * { m_free(), m_freem_list() }
244 * | +------ (done) ---------+
246 * mcache_free/mcache_free_ext() |
249 * mbuf_cslab_audit() |
252 * [CPU cache] ---> (not purging?) -----+
255 * mbuf_cslab_free() |
258 * [freelist] ---> (not purging?) -----+
261 * (rudimentary object) |
262 * mcache_free/mcache_free_ext() ------->>------+
264 * Auditing notes: If auditing is enabled, the audit routine will save
265 * any constructed data structure fields (if necessary) before filling the
266 * contents of the buffers with DEADBEEF (free) pattern and recording the
267 * transaction. Buffers that are freed (whether at CPU or slab layer) are
268 * expected to contain the free pattern.
272 * Debugging can be enabled by adding "mbuf_debug=0x3" to boot-args; this
273 * translates to the mcache flags (MCF_VERIFY | MCF_AUDIT). Additionally,
274 * the CPU layer cache can be disabled by setting the MCF_NOCPUCACHE flag,
275 * i.e. modify the boot argument parameter to "mbuf_debug=0x13". Leak
276 * detection may also be disabled by setting the MCF_NOLEAKLOG flag, e.g.
277 * "mbuf_debug=0x113". Note that debugging consumes more CPU and memory.
279 * Each object is associated with exactly one mcache_audit_t structure that
280 * contains the information related to its last buffer transaction. Given
281 * an address of an object, the audit structure can be retrieved by finding
282 * the position of the object relevant to the base address of the cluster:
284 * +------------+ +=============+
285 * | mbuf addr | | mclaudit[i] |
286 * +------------+ +=============+
288 * i = MTOBG(addr) +-------------+
289 * | +-----> | cl_audit[1] | -----> mcache_audit_t
290 * b = BGTOM(i) | +-------------+
292 * x = MCLIDX(b, addr) | +-------------+
293 * | | | cl_audit[7] |
294 * +-----------------+ +-------------+
297 * The mclaudit[] array is allocated at initialization time, but its contents
298 * get populated when the corresponding cluster is created. Because a page
299 * can be turned into NMBPG number of mbufs, we preserve enough space for the
300 * mbufs so that there is a 1-to-1 mapping between them. A page that never
301 * gets (or has not yet) turned into mbufs will use only cl_audit[0] with the
302 * remaining entries unused. For 16KB cluster, only one entry from the first
303 * page is allocated and used for the entire object.
306 /* TODO: should be in header file */
307 /* kernel translater */
308 extern vm_offset_t
kmem_mb_alloc(vm_map_t
, int, int, kern_return_t
*);
309 extern ppnum_t
pmap_find_phys(pmap_t pmap
, addr64_t va
);
310 extern vm_map_t mb_map
; /* special map */
312 static uint32_t mb_kmem_contig_failed
;
313 static uint32_t mb_kmem_failed
;
314 static uint32_t mb_kmem_one_failed
;
315 /* Timestamp of allocation failures. */
316 static uint64_t mb_kmem_contig_failed_ts
;
317 static uint64_t mb_kmem_failed_ts
;
318 static uint64_t mb_kmem_one_failed_ts
;
319 static uint64_t mb_kmem_contig_failed_size
;
320 static uint64_t mb_kmem_failed_size
;
321 static uint32_t mb_kmem_stats
[6];
322 static const char *mb_kmem_stats_labels
[] = { "INVALID_ARGUMENT",
330 decl_lck_mtx_data(static, mbuf_mlock_data
);
331 static lck_mtx_t
*mbuf_mlock
= &mbuf_mlock_data
;
332 static lck_attr_t
*mbuf_mlock_attr
;
333 static lck_grp_t
*mbuf_mlock_grp
;
334 static lck_grp_attr_t
*mbuf_mlock_grp_attr
;
336 /* Back-end (common) layer */
337 static uint64_t mb_expand_cnt
;
338 static uint64_t mb_expand_cl_cnt
;
339 static uint64_t mb_expand_cl_total
;
340 static uint64_t mb_expand_bigcl_cnt
;
341 static uint64_t mb_expand_bigcl_total
;
342 static uint64_t mb_expand_16kcl_cnt
;
343 static uint64_t mb_expand_16kcl_total
;
344 static boolean_t mbuf_worker_needs_wakeup
; /* wait channel for mbuf worker */
345 static uint32_t mbuf_worker_run_cnt
;
346 static uint64_t mbuf_worker_last_runtime
;
347 static uint64_t mbuf_drain_last_runtime
;
348 static int mbuf_worker_ready
; /* worker thread is runnable */
349 static int ncpu
; /* number of CPUs */
350 static ppnum_t
*mcl_paddr
; /* Array of cluster physical addresses */
351 static ppnum_t mcl_pages
; /* Size of array (# physical pages) */
352 static ppnum_t mcl_paddr_base
; /* Handle returned by IOMapper::iovmAlloc() */
353 static mcache_t
*ref_cache
; /* Cache of cluster reference & flags */
354 static mcache_t
*mcl_audit_con_cache
; /* Audit contents cache */
355 static unsigned int mbuf_debug
; /* patchable mbuf mcache flags */
356 static unsigned int mb_normalized
; /* number of packets "normalized" */
358 #define MB_GROWTH_AGGRESSIVE 1 /* Threshold: 1/2 of total */
359 #define MB_GROWTH_NORMAL 2 /* Threshold: 3/4 of total */
362 MC_MBUF
= 0, /* Regular mbuf */
364 MC_BIGCL
, /* Large (4KB) cluster */
365 MC_16KCL
, /* Jumbo (16KB) cluster */
366 MC_MBUF_CL
, /* mbuf + cluster */
367 MC_MBUF_BIGCL
, /* mbuf + large (4KB) cluster */
368 MC_MBUF_16KCL
/* mbuf + jumbo (16KB) cluster */
371 #define MBUF_CLASS_MIN MC_MBUF
372 #define MBUF_CLASS_MAX MC_MBUF_16KCL
373 #define MBUF_CLASS_LAST MC_16KCL
374 #define MBUF_CLASS_VALID(c) \
375 ((int)(c) >= MBUF_CLASS_MIN && (int)(c) <= MBUF_CLASS_MAX)
376 #define MBUF_CLASS_COMPOSITE(c) \
377 ((int)(c) > MBUF_CLASS_LAST)
381 * mbuf specific mcache allocation request flags.
383 #define MCR_COMP MCR_USR1 /* for MC_MBUF_{CL,BIGCL,16KCL} caches */
386 * Per-cluster slab structure.
388 * A slab is a cluster control structure that contains one or more object
389 * chunks; the available chunks are chained in the slab's freelist (sl_head).
390 * Each time a chunk is taken out of the slab, the slab's reference count
391 * gets incremented. When all chunks have been taken out, the empty slab
392 * gets removed (SLF_DETACHED) from the class's slab list. A chunk that is
393 * returned to a slab causes the slab's reference count to be decremented;
394 * it also causes the slab to be reinserted back to class's slab list, if
395 * it's not already done.
397 * Compartmentalizing of the object chunks into slabs allows us to easily
398 * merge one or more slabs together when the adjacent slabs are idle, as
399 * well as to convert or move a slab from one class to another; e.g. the
400 * mbuf cluster slab can be converted to a regular cluster slab when all
401 * mbufs in the slab have been freed.
403 * A slab may also span across multiple clusters for chunks larger than
404 * a cluster's size. In this case, only the slab of the first cluster is
405 * used. The rest of the slabs are marked with SLF_PARTIAL to indicate
406 * that they are part of the larger slab.
408 * Each slab controls a page of memory.
410 typedef struct mcl_slab
{
411 struct mcl_slab
*sl_next
; /* neighboring slab */
412 u_int8_t sl_class
; /* controlling mbuf class */
413 int8_t sl_refcnt
; /* outstanding allocations */
414 int8_t sl_chunks
; /* chunks (bufs) in this slab */
415 u_int16_t sl_flags
; /* slab flags (see below) */
416 u_int16_t sl_len
; /* slab length */
417 void *sl_base
; /* base of allocated memory */
418 void *sl_head
; /* first free buffer */
419 TAILQ_ENTRY(mcl_slab
) sl_link
; /* next/prev slab on freelist */
422 #define SLF_MAPPED 0x0001 /* backed by a mapped page */
423 #define SLF_PARTIAL 0x0002 /* part of another slab */
424 #define SLF_DETACHED 0x0004 /* not in slab freelist */
427 * The array of slabs are broken into groups of arrays per 1MB of kernel
428 * memory to reduce the footprint. Each group is allocated on demand
429 * whenever a new piece of memory mapped in from the VM crosses the 1MB
432 #define NSLABSPMB ((1 << MBSHIFT) >> PAGE_SHIFT)
434 typedef struct mcl_slabg
{
435 mcl_slab_t
*slg_slab
; /* group of slabs */
439 * Number of slabs needed to control a 16KB cluster object.
441 #define NSLABSP16KB (M16KCLBYTES >> PAGE_SHIFT)
444 * Per-cluster audit structure.
447 mcache_audit_t
**cl_audit
; /* array of audits */
451 struct thread
*msa_thread
; /* thread doing transaction */
452 struct thread
*msa_pthread
; /* previous transaction thread */
453 uint32_t msa_tstamp
; /* transaction timestamp (ms) */
454 uint32_t msa_ptstamp
; /* prev transaction timestamp (ms) */
455 uint16_t msa_depth
; /* pc stack depth */
456 uint16_t msa_pdepth
; /* previous transaction pc stack */
457 void *msa_stack
[MCACHE_STACK_DEPTH
];
458 void *msa_pstack
[MCACHE_STACK_DEPTH
];
459 } mcl_scratch_audit_t
;
463 * Size of data from the beginning of an mbuf that covers m_hdr,
464 * pkthdr and m_ext structures. If auditing is enabled, we allocate
465 * a shadow mbuf structure of this size inside each audit structure,
466 * and the contents of the real mbuf gets copied into it when the mbuf
467 * is freed. This allows us to pattern-fill the mbuf for integrity
468 * check, and to preserve any constructed mbuf fields (e.g. mbuf +
469 * cluster cache case). Note that we don't save the contents of
470 * clusters when they are freed; we simply pattern-fill them.
472 u_int8_t sc_mbuf
[(MSIZE
- _MHLEN
) + sizeof(_m_ext_t
)];
473 mcl_scratch_audit_t sc_scratch
__attribute__((aligned(8)));
474 } mcl_saved_contents_t
;
476 #define AUDIT_CONTENTS_SIZE (sizeof (mcl_saved_contents_t))
478 #define MCA_SAVED_MBUF_PTR(_mca) \
479 ((struct mbuf *)(void *)((mcl_saved_contents_t *) \
480 (_mca)->mca_contents)->sc_mbuf)
481 #define MCA_SAVED_MBUF_SIZE \
482 (sizeof (((mcl_saved_contents_t *)0)->sc_mbuf))
483 #define MCA_SAVED_SCRATCH_PTR(_mca) \
484 (&((mcl_saved_contents_t *)(_mca)->mca_contents)->sc_scratch)
487 * mbuf specific mcache audit flags
489 #define MB_INUSE 0x01 /* object has not been returned to slab */
490 #define MB_COMP_INUSE 0x02 /* object has not been returned to cslab */
491 #define MB_SCVALID 0x04 /* object has valid saved contents */
494 * Each of the following two arrays hold up to nmbclusters elements.
496 static mcl_audit_t
*mclaudit
; /* array of cluster audit information */
497 static unsigned int maxclaudit
; /* max # of entries in audit table */
498 static mcl_slabg_t
**slabstbl
; /* cluster slabs table */
499 static unsigned int maxslabgrp
; /* max # of entries in slabs table */
500 static unsigned int slabgrp
; /* # of entries in slabs table */
503 int nclusters
; /* # of clusters for non-jumbo (legacy) sizes */
504 int njcl
; /* # of clusters for jumbo sizes */
505 int njclbytes
; /* size of a jumbo cluster */
506 unsigned char *mbutl
; /* first mapped cluster address */
507 unsigned char *embutl
; /* ending virtual address of mclusters */
508 int _max_linkhdr
; /* largest link-level header */
509 int _max_protohdr
; /* largest protocol header */
510 int max_hdr
; /* largest link+protocol header */
511 int max_datalen
; /* MHLEN - max_hdr */
513 static boolean_t mclverify
; /* debug: pattern-checking */
514 static boolean_t mcltrace
; /* debug: stack tracing */
515 static boolean_t mclfindleak
; /* debug: leak detection */
516 static boolean_t mclexpleak
; /* debug: expose leak info to user space */
518 static struct timeval mb_start
; /* beginning of time */
520 /* mbuf leak detection variables */
521 static struct mleak_table mleak_table
;
522 static mleak_stat_t
*mleak_stat
;
524 #define MLEAK_STAT_SIZE(n) \
525 __builtin_offsetof(mleak_stat_t, ml_trace[n])
528 mcache_obj_t
*element
; /* the alloc'ed element, NULL if unused */
529 u_int32_t trace_index
; /* mtrace index for corresponding backtrace */
530 u_int32_t count
; /* How many objects were requested */
531 u_int64_t hitcount
; /* for determining hash effectiveness */
535 u_int64_t collisions
;
539 uintptr_t addr
[MLEAK_STACK_DEPTH
];
542 /* Size must be a power of two for the zhash to be able to just mask off bits */
543 #define MLEAK_ALLOCATION_MAP_NUM 512
544 #define MLEAK_TRACE_MAP_NUM 256
547 * Sample factor for how often to record a trace. This is overwritable
548 * by the boot-arg mleak_sample_factor.
550 #define MLEAK_SAMPLE_FACTOR 500
553 * Number of top leakers recorded.
555 #define MLEAK_NUM_TRACES 5
557 #define MB_LEAK_SPACING_64 " "
558 #define MB_LEAK_SPACING_32 " "
561 #define MB_LEAK_HDR_32 "\n\
562 trace [1] trace [2] trace [3] trace [4] trace [5] \n\
563 ---------- ---------- ---------- ---------- ---------- \n\
566 #define MB_LEAK_HDR_64 "\n\
567 trace [1] trace [2] trace [3] \
568 trace [4] trace [5] \n\
569 ------------------ ------------------ ------------------ \
570 ------------------ ------------------ \n\
573 static uint32_t mleak_alloc_buckets
= MLEAK_ALLOCATION_MAP_NUM
;
574 static uint32_t mleak_trace_buckets
= MLEAK_TRACE_MAP_NUM
;
576 /* Hashmaps of allocations and their corresponding traces */
577 static struct mallocation
*mleak_allocations
;
578 static struct mtrace
*mleak_traces
;
579 static struct mtrace
*mleak_top_trace
[MLEAK_NUM_TRACES
];
581 /* Lock to protect mleak tables from concurrent modification */
582 decl_lck_mtx_data(static, mleak_lock_data
);
583 static lck_mtx_t
*mleak_lock
= &mleak_lock_data
;
584 static lck_attr_t
*mleak_lock_attr
;
585 static lck_grp_t
*mleak_lock_grp
;
586 static lck_grp_attr_t
*mleak_lock_grp_attr
;
588 /* *Failed* large allocations. */
592 uintptr_t addr
[MLEAK_STACK_DEPTH
];
595 #define MTRACELARGE_NUM_TRACES 5
596 static struct mtracelarge mtracelarge_table
[MTRACELARGE_NUM_TRACES
];
598 static void mtracelarge_register(size_t size
);
600 /* Lock to protect the completion callback table */
601 static lck_grp_attr_t
*mbuf_tx_compl_tbl_lck_grp_attr
= NULL
;
602 static lck_attr_t
*mbuf_tx_compl_tbl_lck_attr
= NULL
;
603 static lck_grp_t
*mbuf_tx_compl_tbl_lck_grp
= NULL
;
604 decl_lck_rw_data(, mbuf_tx_compl_tbl_lck_rw_data
);
605 lck_rw_t
*mbuf_tx_compl_tbl_lock
= &mbuf_tx_compl_tbl_lck_rw_data
;
607 extern u_int32_t high_sb_max
;
609 /* The minimum number of objects that are allocated, to start. */
611 #define MINBIGCL (MINCL >> 1)
612 #define MIN16KCL (MINCL >> 2)
614 /* Low watermarks (only map in pages once free counts go below) */
615 #define MBIGCL_LOWAT MINBIGCL
616 #define M16KCL_LOWAT MIN16KCL
619 mbuf_class_t mtbl_class
; /* class type */
620 mcache_t
*mtbl_cache
; /* mcache for this buffer class */
621 TAILQ_HEAD(mcl_slhead
, mcl_slab
) mtbl_slablist
; /* slab list */
622 mcache_obj_t
*mtbl_cobjlist
; /* composite objects freelist */
623 mb_class_stat_t
*mtbl_stats
; /* statistics fetchable via sysctl */
624 u_int32_t mtbl_maxsize
; /* maximum buffer size */
625 int mtbl_minlimit
; /* minimum allowed */
626 int mtbl_maxlimit
; /* maximum allowed */
627 u_int32_t mtbl_wantpurge
; /* purge during next reclaim */
628 uint32_t mtbl_avgtotal
; /* average total on iOS */
629 u_int32_t mtbl_expand
; /* worker should expand the class */
632 #define m_class(c) mbuf_table[c].mtbl_class
633 #define m_cache(c) mbuf_table[c].mtbl_cache
634 #define m_slablist(c) mbuf_table[c].mtbl_slablist
635 #define m_cobjlist(c) mbuf_table[c].mtbl_cobjlist
636 #define m_maxsize(c) mbuf_table[c].mtbl_maxsize
637 #define m_minlimit(c) mbuf_table[c].mtbl_minlimit
638 #define m_maxlimit(c) mbuf_table[c].mtbl_maxlimit
639 #define m_wantpurge(c) mbuf_table[c].mtbl_wantpurge
640 #define m_cname(c) mbuf_table[c].mtbl_stats->mbcl_cname
641 #define m_size(c) mbuf_table[c].mtbl_stats->mbcl_size
642 #define m_total(c) mbuf_table[c].mtbl_stats->mbcl_total
643 #define m_active(c) mbuf_table[c].mtbl_stats->mbcl_active
644 #define m_infree(c) mbuf_table[c].mtbl_stats->mbcl_infree
645 #define m_slab_cnt(c) mbuf_table[c].mtbl_stats->mbcl_slab_cnt
646 #define m_alloc_cnt(c) mbuf_table[c].mtbl_stats->mbcl_alloc_cnt
647 #define m_free_cnt(c) mbuf_table[c].mtbl_stats->mbcl_free_cnt
648 #define m_notified(c) mbuf_table[c].mtbl_stats->mbcl_notified
649 #define m_purge_cnt(c) mbuf_table[c].mtbl_stats->mbcl_purge_cnt
650 #define m_fail_cnt(c) mbuf_table[c].mtbl_stats->mbcl_fail_cnt
651 #define m_ctotal(c) mbuf_table[c].mtbl_stats->mbcl_ctotal
652 #define m_peak(c) mbuf_table[c].mtbl_stats->mbcl_peak_reported
653 #define m_release_cnt(c) mbuf_table[c].mtbl_stats->mbcl_release_cnt
654 #define m_region_expand(c) mbuf_table[c].mtbl_expand
656 static mbuf_table_t mbuf_table
[] = {
658 * The caches for mbufs, regular clusters and big clusters.
659 * The average total values were based on data gathered by actual
660 * usage patterns on iOS.
662 { MC_MBUF
, NULL
, TAILQ_HEAD_INITIALIZER(m_slablist(MC_MBUF
)),
663 NULL
, NULL
, 0, 0, 0, 0, 3000, 0 },
664 { MC_CL
, NULL
, TAILQ_HEAD_INITIALIZER(m_slablist(MC_CL
)),
665 NULL
, NULL
, 0, 0, 0, 0, 2000, 0 },
666 { MC_BIGCL
, NULL
, TAILQ_HEAD_INITIALIZER(m_slablist(MC_BIGCL
)),
667 NULL
, NULL
, 0, 0, 0, 0, 1000, 0 },
668 { MC_16KCL
, NULL
, TAILQ_HEAD_INITIALIZER(m_slablist(MC_16KCL
)),
669 NULL
, NULL
, 0, 0, 0, 0, 200, 0 },
671 * The following are special caches; they serve as intermediate
672 * caches backed by the above rudimentary caches. Each object
673 * in the cache is an mbuf with a cluster attached to it. Unlike
674 * the above caches, these intermediate caches do not directly
675 * deal with the slab structures; instead, the constructed
676 * cached elements are simply stored in the freelists.
678 { MC_MBUF_CL
, NULL
, { NULL
, NULL
}, NULL
, NULL
, 0, 0, 0, 0, 2000, 0 },
679 { MC_MBUF_BIGCL
, NULL
, { NULL
, NULL
}, NULL
, NULL
, 0, 0, 0, 0, 1000, 0 },
680 { MC_MBUF_16KCL
, NULL
, { NULL
, NULL
}, NULL
, NULL
, 0, 0, 0, 0, 200, 0 },
683 #define NELEM(a) (sizeof (a) / sizeof ((a)[0]))
687 m_avgtotal(mbuf_class_t c
)
689 return mbuf_table
[c
].mtbl_avgtotal
;
692 static void *mb_waitchan
= &mbuf_table
; /* wait channel for all caches */
693 static int mb_waiters
; /* number of waiters */
695 boolean_t mb_peak_newreport
= FALSE
;
696 boolean_t mb_peak_firstreport
= FALSE
;
698 /* generate a report by default after 1 week of uptime */
699 #define MBUF_PEAK_FIRST_REPORT_THRESHOLD 604800
701 #define MB_WDT_MAXTIME 10 /* # of secs before watchdog panic */
702 static struct timeval mb_wdtstart
; /* watchdog start timestamp */
703 static char *mbuf_dump_buf
;
705 #define MBUF_DUMP_BUF_SIZE 4096
708 * mbuf watchdog is enabled by default. It is also toggeable via the
709 * kern.ipc.mb_watchdog sysctl.
710 * Garbage collection is enabled by default on embedded platforms.
711 * mb_drain_maxint controls the amount of time to wait (in seconds) before
712 * consecutive calls to mbuf_drain().
714 #if CONFIG_EMBEDDED || DEVELOPMENT || DEBUG
715 static unsigned int mb_watchdog
= 1;
717 static unsigned int mb_watchdog
= 0;
720 static unsigned int mb_drain_maxint
= 60;
722 static unsigned int mb_drain_maxint
= 0;
723 #endif /* CONFIG_EMBEDDED */
725 uintptr_t mb_obscure_extfree
__attribute__((visibility("hidden")));
726 uintptr_t mb_obscure_extref
__attribute__((visibility("hidden")));
729 static u_int32_t mb_redzone_cookie
;
730 static void m_redzone_init(struct mbuf
*);
731 static void m_redzone_verify(struct mbuf
*m
);
733 /* The following are used to serialize m_clalloc() */
734 static boolean_t mb_clalloc_busy
;
735 static void *mb_clalloc_waitchan
= &mb_clalloc_busy
;
736 static int mb_clalloc_waiters
;
738 static void mbuf_mtypes_sync(boolean_t
);
739 static int mbstat_sysctl SYSCTL_HANDLER_ARGS
;
740 static void mbuf_stat_sync(void);
741 static int mb_stat_sysctl SYSCTL_HANDLER_ARGS
;
742 static int mleak_top_trace_sysctl SYSCTL_HANDLER_ARGS
;
743 static int mleak_table_sysctl SYSCTL_HANDLER_ARGS
;
744 static char *mbuf_dump(void);
745 static void mbuf_table_init(void);
746 static inline void m_incref(struct mbuf
*);
747 static inline u_int16_t
m_decref(struct mbuf
*);
748 static int m_clalloc(const u_int32_t
, const int, const u_int32_t
);
749 static void mbuf_worker_thread_init(void);
750 static mcache_obj_t
*slab_alloc(mbuf_class_t
, int);
751 static void slab_free(mbuf_class_t
, mcache_obj_t
*);
752 static unsigned int mbuf_slab_alloc(void *, mcache_obj_t
***,
754 static void mbuf_slab_free(void *, mcache_obj_t
*, int);
755 static void mbuf_slab_audit(void *, mcache_obj_t
*, boolean_t
);
756 static void mbuf_slab_notify(void *, u_int32_t
);
757 static unsigned int cslab_alloc(mbuf_class_t
, mcache_obj_t
***,
759 static unsigned int cslab_free(mbuf_class_t
, mcache_obj_t
*, int);
760 static unsigned int mbuf_cslab_alloc(void *, mcache_obj_t
***,
762 static void mbuf_cslab_free(void *, mcache_obj_t
*, int);
763 static void mbuf_cslab_audit(void *, mcache_obj_t
*, boolean_t
);
764 static int freelist_populate(mbuf_class_t
, unsigned int, int);
765 static void freelist_init(mbuf_class_t
);
766 static boolean_t
mbuf_cached_above(mbuf_class_t
, int);
767 static boolean_t
mbuf_steal(mbuf_class_t
, unsigned int);
768 static void m_reclaim(mbuf_class_t
, unsigned int, boolean_t
);
769 static int m_howmany(int, size_t);
770 static void mbuf_worker_thread(void);
771 static void mbuf_watchdog(void);
772 static boolean_t
mbuf_sleep(mbuf_class_t
, unsigned int, int);
774 static void mcl_audit_init(void *, mcache_audit_t
**, mcache_obj_t
**,
775 size_t, unsigned int);
776 static void mcl_audit_free(void *, unsigned int);
777 static mcache_audit_t
*mcl_audit_buf2mca(mbuf_class_t
, mcache_obj_t
*);
778 static void mcl_audit_mbuf(mcache_audit_t
*, void *, boolean_t
, boolean_t
);
779 static void mcl_audit_cluster(mcache_audit_t
*, void *, size_t, boolean_t
,
781 static void mcl_audit_restore_mbuf(struct mbuf
*, mcache_audit_t
*, boolean_t
);
782 static void mcl_audit_save_mbuf(struct mbuf
*, mcache_audit_t
*);
783 static void mcl_audit_scratch(mcache_audit_t
*);
784 static void mcl_audit_mcheck_panic(struct mbuf
*);
785 static void mcl_audit_verify_nextptr(void *, mcache_audit_t
*);
787 static void mleak_activate(void);
788 static void mleak_logger(u_int32_t
, mcache_obj_t
*, boolean_t
);
789 static boolean_t
mleak_log(uintptr_t *, mcache_obj_t
*, uint32_t, int);
790 static void mleak_free(mcache_obj_t
*);
791 static void mleak_sort_traces(void);
792 static void mleak_update_stats(void);
794 static mcl_slab_t
*slab_get(void *);
795 static void slab_init(mcl_slab_t
*, mbuf_class_t
, u_int32_t
,
796 void *, void *, unsigned int, int, int);
797 static void slab_insert(mcl_slab_t
*, mbuf_class_t
);
798 static void slab_remove(mcl_slab_t
*, mbuf_class_t
);
799 static boolean_t
slab_inrange(mcl_slab_t
*, void *);
800 static void slab_nextptr_panic(mcl_slab_t
*, void *);
801 static void slab_detach(mcl_slab_t
*);
802 static boolean_t
slab_is_detached(mcl_slab_t
*);
804 static int m_copyback0(struct mbuf
**, int, int, const void *, int, int);
805 static struct mbuf
*m_split0(struct mbuf
*, int, int, int);
806 __private_extern__
void mbuf_report_peak_usage(void);
807 static boolean_t
mbuf_report_usage(mbuf_class_t
);
808 #if DEBUG || DEVELOPMENT
809 #define mbwdog_logger(fmt, ...) _mbwdog_logger(__func__, __LINE__, fmt, ## __VA_ARGS__)
810 static void _mbwdog_logger(const char *func
, const int line
, const char *fmt
, ...);
811 static char *mbwdog_logging
;
812 const unsigned mbwdog_logging_size
= 4096;
813 static size_t mbwdog_logging_used
;
815 #define mbwdog_logger(fmt, ...) do { } while (0)
817 static void mbuf_drain_locked(boolean_t
);
819 /* flags for m_copyback0 */
820 #define M_COPYBACK0_COPYBACK 0x0001 /* copyback from cp */
821 #define M_COPYBACK0_PRESERVE 0x0002 /* preserve original data */
822 #define M_COPYBACK0_COW 0x0004 /* do copy-on-write */
823 #define M_COPYBACK0_EXTEND 0x0008 /* extend chain */
826 * This flag is set for all mbufs that come out of and into the composite
827 * mbuf + cluster caches, i.e. MC_MBUF_CL and MC_MBUF_BIGCL. mbufs that
828 * are marked with such a flag have clusters attached to them, and will be
829 * treated differently when they are freed; instead of being placed back
830 * into the mbuf and cluster freelists, the composite mbuf + cluster objects
831 * are placed back into the appropriate composite cache's freelist, and the
832 * actual freeing is deferred until the composite objects are purged. At
833 * such a time, this flag will be cleared from the mbufs and the objects
834 * will be freed into their own separate freelists.
836 #define EXTF_COMPOSITE 0x1
839 * This flag indicates that the external cluster is read-only, i.e. it is
840 * or was referred to by more than one mbufs. Once set, this flag is never
843 #define EXTF_READONLY 0x2
845 * This flag indicates that the external cluster is paired with the mbuf.
846 * Pairing implies an external free routine defined which will be invoked
847 * when the reference count drops to the minimum at m_free time. This
848 * flag is never cleared.
850 #define EXTF_PAIRED 0x4
853 (EXTF_COMPOSITE | EXTF_READONLY | EXTF_PAIRED)
855 #define MEXT_MINREF(m) ((m_get_rfa(m))->minref)
856 #define MEXT_REF(m) ((m_get_rfa(m))->refcnt)
857 #define MEXT_PREF(m) ((m_get_rfa(m))->prefcnt)
858 #define MEXT_FLAGS(m) ((m_get_rfa(m))->flags)
859 #define MEXT_PRIV(m) ((m_get_rfa(m))->priv)
860 #define MEXT_PMBUF(m) ((m_get_rfa(m))->paired)
861 #define MEXT_TOKEN(m) ((m_get_rfa(m))->ext_token)
862 #define MBUF_IS_COMPOSITE(m) \
863 (MEXT_REF(m) == MEXT_MINREF(m) && \
864 (MEXT_FLAGS(m) & EXTF_MASK) == EXTF_COMPOSITE)
866 * This macro can be used to test if the mbuf is paired to an external
867 * cluster. The test for MEXT_PMBUF being equal to the mbuf in subject
868 * is important, as EXTF_PAIRED alone is insufficient since it is immutable,
869 * and thus survives calls to m_free_paired.
871 #define MBUF_IS_PAIRED(m) \
872 (((m)->m_flags & M_EXT) && \
873 (MEXT_FLAGS(m) & EXTF_MASK) == EXTF_PAIRED && \
874 MEXT_PMBUF(m) == (m))
877 * Macros used to verify the integrity of the mbuf.
879 #define _MCHECK(m) { \
880 if ((m)->m_type != MT_FREE && !MBUF_IS_PAIRED(m)) { \
881 if (mclaudit == NULL) \
882 panic("MCHECK: m_type=%d m=%p", \
883 (u_int16_t)(m)->m_type, m); \
885 mcl_audit_mcheck_panic(m); \
889 #define MBUF_IN_MAP(addr) \
890 ((unsigned char *)(addr) >= mbutl && \
891 (unsigned char *)(addr) < embutl)
893 #define MRANGE(addr) { \
894 if (!MBUF_IN_MAP(addr)) \
895 panic("MRANGE: address out of range 0x%p", addr); \
899 * Macro version of mtod.
901 #define MTOD(m, t) ((t)((m)->m_data))
904 * Macros to obtain page index given a base cluster address
906 #define MTOPG(x) (((unsigned char *)x - mbutl) >> PAGE_SHIFT)
907 #define PGTOM(x) (mbutl + (x << PAGE_SHIFT))
910 * Macro to find the mbuf index relative to a base.
912 #define MBPAGEIDX(c, m) \
913 (((unsigned char *)(m) - (unsigned char *)(c)) >> MSIZESHIFT)
916 * Same thing for 2KB cluster index.
918 #define CLPAGEIDX(c, m) \
919 (((unsigned char *)(m) - (unsigned char *)(c)) >> MCLSHIFT)
922 * Macro to find 4KB cluster index relative to a base
924 #define BCLPAGEIDX(c, m) \
925 (((unsigned char *)(m) - (unsigned char *)(c)) >> MBIGCLSHIFT)
928 * Macros used during mbuf and cluster initialization.
930 #define MBUF_INIT_PKTHDR(m) { \
931 (m)->m_pkthdr.rcvif = NULL; \
932 (m)->m_pkthdr.pkt_hdr = NULL; \
933 (m)->m_pkthdr.len = 0; \
934 (m)->m_pkthdr.csum_flags = 0; \
935 (m)->m_pkthdr.csum_data = 0; \
936 (m)->m_pkthdr.vlan_tag = 0; \
937 m_classifier_init(m, 0); \
943 #define MBUF_INIT(m, pkthdr, type) { \
945 (m)->m_next = (m)->m_nextpkt = NULL; \
947 (m)->m_type = type; \
948 if ((pkthdr) == 0) { \
949 (m)->m_data = (m)->m_dat; \
952 (m)->m_data = (m)->m_pktdat; \
953 (m)->m_flags = M_PKTHDR; \
954 MBUF_INIT_PKTHDR(m); \
958 #define MEXT_INIT(m, buf, size, free, arg, rfa, min, ref, pref, flag, \
960 (m)->m_data = (m)->m_ext.ext_buf = (buf); \
961 (m)->m_flags |= M_EXT; \
962 m_set_ext((m), (rfa), (free), (arg)); \
963 (m)->m_ext.ext_size = (size); \
964 MEXT_MINREF(m) = (min); \
965 MEXT_REF(m) = (ref); \
966 MEXT_PREF(m) = (pref); \
967 MEXT_FLAGS(m) = (flag); \
968 MEXT_PRIV(m) = (priv); \
969 MEXT_PMBUF(m) = (pm); \
972 #define MBUF_CL_INIT(m, buf, rfa, ref, flag) \
973 MEXT_INIT(m, buf, m_maxsize(MC_CL), NULL, NULL, rfa, 0, \
974 ref, 0, flag, 0, NULL)
976 #define MBUF_BIGCL_INIT(m, buf, rfa, ref, flag) \
977 MEXT_INIT(m, buf, m_maxsize(MC_BIGCL), m_bigfree, NULL, rfa, 0, \
978 ref, 0, flag, 0, NULL)
980 #define MBUF_16KCL_INIT(m, buf, rfa, ref, flag) \
981 MEXT_INIT(m, buf, m_maxsize(MC_16KCL), m_16kfree, NULL, rfa, 0, \
982 ref, 0, flag, 0, NULL)
985 * Macro to convert BSD malloc sleep flag to mcache's
987 #define MSLEEPF(f) ((!((f) & M_DONTWAIT)) ? MCR_SLEEP : MCR_NOSLEEP)
990 * The structure that holds all mbuf class statistics exportable via sysctl.
991 * Similar to mbstat structure, the mb_stat structure is protected by the
992 * global mbuf lock. It contains additional information about the classes
993 * that allows for a more accurate view of the state of the allocator.
995 struct mb_stat
*mb_stat
;
996 struct omb_stat
*omb_stat
; /* For backwards compatibility */
998 #define MB_STAT_SIZE(n) \
999 __builtin_offsetof(mb_stat_t, mbs_class[n])
1000 #define OMB_STAT_SIZE(n) \
1001 ((size_t)(&((struct omb_stat *)0)->mbs_class[n]))
1004 * The legacy structure holding all of the mbuf allocation statistics.
1005 * The actual statistics used by the kernel are stored in the mbuf_table
1006 * instead, and are updated atomically while the global mbuf lock is held.
1007 * They are mirrored in mbstat to support legacy applications (e.g. netstat).
1008 * Unlike before, the kernel no longer relies on the contents of mbstat for
1009 * its operations (e.g. cluster expansion) because the structure is exposed
1010 * to outside and could possibly be modified, therefore making it unsafe.
1011 * With the exception of the mbstat.m_mtypes array (see below), all of the
1012 * statistics are updated as they change.
1014 struct mbstat mbstat
;
1016 #define MBSTAT_MTYPES_MAX \
1017 (sizeof (mbstat.m_mtypes) / sizeof (mbstat.m_mtypes[0]))
1020 * Allocation statistics related to mbuf types (up to MT_MAX-1) are updated
1021 * atomically and stored in a per-CPU structure which is lock-free; this is
1022 * done in order to avoid writing to the global mbstat data structure which
1023 * would cause false sharing. During sysctl request for kern.ipc.mbstat,
1024 * the statistics across all CPUs will be converged into the mbstat.m_mtypes
1025 * array and returned to the application. Any updates for types greater or
1026 * equal than MT_MAX would be done atomically to the mbstat; this slows down
1027 * performance but is okay since the kernel uses only up to MT_MAX-1 while
1028 * anything beyond that (up to type 255) is considered a corner case.
1031 unsigned int cpu_mtypes
[MT_MAX
];
1032 } __attribute__((aligned(MAX_CPU_CACHE_LINE_SIZE
), packed
)) mtypes_cpu_t
;
1035 mtypes_cpu_t mbs_cpu
[1];
1038 static mbuf_mtypes_t
*mbuf_mtypes
; /* per-CPU statistics */
1040 #define MBUF_MTYPES_SIZE(n) \
1041 ((size_t)(&((mbuf_mtypes_t *)0)->mbs_cpu[n]))
1043 #define MTYPES_CPU(p) \
1044 ((mtypes_cpu_t *)(void *)((char *)(p) + MBUF_MTYPES_SIZE(cpu_number())))
1046 #define mtype_stat_add(type, n) { \
1047 if ((unsigned)(type) < MT_MAX) { \
1048 mtypes_cpu_t *mbs = MTYPES_CPU(mbuf_mtypes); \
1049 atomic_add_32(&mbs->cpu_mtypes[type], n); \
1050 } else if ((unsigned)(type) < (unsigned)MBSTAT_MTYPES_MAX) { \
1051 atomic_add_16((int16_t *)&mbstat.m_mtypes[type], n); \
1055 #define mtype_stat_sub(t, n) mtype_stat_add(t, -(n))
1056 #define mtype_stat_inc(t) mtype_stat_add(t, 1)
1057 #define mtype_stat_dec(t) mtype_stat_sub(t, 1)
1060 mbuf_mtypes_sync(boolean_t locked
)
1066 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_OWNED
);
1069 bzero(&mtc
, sizeof(mtc
));
1070 for (m
= 0; m
< ncpu
; m
++) {
1071 mtypes_cpu_t
*scp
= &mbuf_mtypes
->mbs_cpu
[m
];
1074 bcopy(&scp
->cpu_mtypes
, &temp
.cpu_mtypes
,
1075 sizeof(temp
.cpu_mtypes
));
1077 for (n
= 0; n
< MT_MAX
; n
++) {
1078 mtc
.cpu_mtypes
[n
] += temp
.cpu_mtypes
[n
];
1082 lck_mtx_lock(mbuf_mlock
);
1084 for (n
= 0; n
< MT_MAX
; n
++) {
1085 mbstat
.m_mtypes
[n
] = mtc
.cpu_mtypes
[n
];
1088 lck_mtx_unlock(mbuf_mlock
);
1093 mbstat_sysctl SYSCTL_HANDLER_ARGS
1095 #pragma unused(oidp, arg1, arg2)
1096 mbuf_mtypes_sync(FALSE
);
1098 return SYSCTL_OUT(req
, &mbstat
, sizeof(mbstat
));
1102 mbuf_stat_sync(void)
1104 mb_class_stat_t
*sp
;
1109 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_OWNED
);
1111 for (k
= 0; k
< NELEM(mbuf_table
); k
++) {
1113 ccp
= &cp
->mc_cpu
[0];
1114 bktsize
= ccp
->cc_bktsize
;
1115 sp
= mbuf_table
[k
].mtbl_stats
;
1117 if (cp
->mc_flags
& MCF_NOCPUCACHE
) {
1118 sp
->mbcl_mc_state
= MCS_DISABLED
;
1119 } else if (cp
->mc_purge_cnt
> 0) {
1120 sp
->mbcl_mc_state
= MCS_PURGING
;
1121 } else if (bktsize
== 0) {
1122 sp
->mbcl_mc_state
= MCS_OFFLINE
;
1124 sp
->mbcl_mc_state
= MCS_ONLINE
;
1127 sp
->mbcl_mc_cached
= 0;
1128 for (m
= 0; m
< ncpu
; m
++) {
1129 ccp
= &cp
->mc_cpu
[m
];
1130 if (ccp
->cc_objs
> 0) {
1131 sp
->mbcl_mc_cached
+= ccp
->cc_objs
;
1133 if (ccp
->cc_pobjs
> 0) {
1134 sp
->mbcl_mc_cached
+= ccp
->cc_pobjs
;
1137 sp
->mbcl_mc_cached
+= (cp
->mc_full
.bl_total
* bktsize
);
1138 sp
->mbcl_active
= sp
->mbcl_total
- sp
->mbcl_mc_cached
-
1141 sp
->mbcl_mc_waiter_cnt
= cp
->mc_waiter_cnt
;
1142 sp
->mbcl_mc_wretry_cnt
= cp
->mc_wretry_cnt
;
1143 sp
->mbcl_mc_nwretry_cnt
= cp
->mc_nwretry_cnt
;
1145 /* Calculate total count specific to each class */
1146 sp
->mbcl_ctotal
= sp
->mbcl_total
;
1147 switch (m_class(k
)) {
1149 /* Deduct mbufs used in composite caches */
1150 sp
->mbcl_ctotal
-= (m_total(MC_MBUF_CL
) +
1151 m_total(MC_MBUF_BIGCL
));
1155 /* Deduct clusters used in composite cache */
1156 sp
->mbcl_ctotal
-= m_total(MC_MBUF_CL
);
1160 /* Deduct clusters used in composite cache */
1161 sp
->mbcl_ctotal
-= m_total(MC_MBUF_BIGCL
);
1165 /* Deduct clusters used in composite cache */
1166 sp
->mbcl_ctotal
-= m_total(MC_MBUF_16KCL
);
1176 mb_stat_sysctl SYSCTL_HANDLER_ARGS
1178 #pragma unused(oidp, arg1, arg2)
1180 int k
, statsz
, proc64
= proc_is64bit(req
->p
);
1182 lck_mtx_lock(mbuf_mlock
);
1186 struct omb_class_stat
*oc
;
1187 struct mb_class_stat
*c
;
1189 omb_stat
->mbs_cnt
= mb_stat
->mbs_cnt
;
1190 oc
= &omb_stat
->mbs_class
[0];
1191 c
= &mb_stat
->mbs_class
[0];
1192 for (k
= 0; k
< omb_stat
->mbs_cnt
; k
++, oc
++, c
++) {
1193 (void) snprintf(oc
->mbcl_cname
, sizeof(oc
->mbcl_cname
),
1194 "%s", c
->mbcl_cname
);
1195 oc
->mbcl_size
= c
->mbcl_size
;
1196 oc
->mbcl_total
= c
->mbcl_total
;
1197 oc
->mbcl_active
= c
->mbcl_active
;
1198 oc
->mbcl_infree
= c
->mbcl_infree
;
1199 oc
->mbcl_slab_cnt
= c
->mbcl_slab_cnt
;
1200 oc
->mbcl_alloc_cnt
= c
->mbcl_alloc_cnt
;
1201 oc
->mbcl_free_cnt
= c
->mbcl_free_cnt
;
1202 oc
->mbcl_notified
= c
->mbcl_notified
;
1203 oc
->mbcl_purge_cnt
= c
->mbcl_purge_cnt
;
1204 oc
->mbcl_fail_cnt
= c
->mbcl_fail_cnt
;
1205 oc
->mbcl_ctotal
= c
->mbcl_ctotal
;
1206 oc
->mbcl_release_cnt
= c
->mbcl_release_cnt
;
1207 oc
->mbcl_mc_state
= c
->mbcl_mc_state
;
1208 oc
->mbcl_mc_cached
= c
->mbcl_mc_cached
;
1209 oc
->mbcl_mc_waiter_cnt
= c
->mbcl_mc_waiter_cnt
;
1210 oc
->mbcl_mc_wretry_cnt
= c
->mbcl_mc_wretry_cnt
;
1211 oc
->mbcl_mc_nwretry_cnt
= c
->mbcl_mc_nwretry_cnt
;
1214 statsz
= OMB_STAT_SIZE(NELEM(mbuf_table
));
1217 statsz
= MB_STAT_SIZE(NELEM(mbuf_table
));
1220 lck_mtx_unlock(mbuf_mlock
);
1222 return SYSCTL_OUT(req
, statp
, statsz
);
1226 mleak_top_trace_sysctl SYSCTL_HANDLER_ARGS
1228 #pragma unused(oidp, arg1, arg2)
1231 /* Ensure leak tracing turned on */
1232 if (!mclfindleak
|| !mclexpleak
) {
1236 lck_mtx_lock(mleak_lock
);
1237 mleak_update_stats();
1238 i
= SYSCTL_OUT(req
, mleak_stat
, MLEAK_STAT_SIZE(MLEAK_NUM_TRACES
));
1239 lck_mtx_unlock(mleak_lock
);
1245 mleak_table_sysctl SYSCTL_HANDLER_ARGS
1247 #pragma unused(oidp, arg1, arg2)
1250 /* Ensure leak tracing turned on */
1251 if (!mclfindleak
|| !mclexpleak
) {
1255 lck_mtx_lock(mleak_lock
);
1256 i
= SYSCTL_OUT(req
, &mleak_table
, sizeof(mleak_table
));
1257 lck_mtx_unlock(mleak_lock
);
1263 m_incref(struct mbuf
*m
)
1266 volatile UInt16
*addr
= (volatile UInt16
*)&MEXT_REF(m
);
1272 } while (!OSCompareAndSwap16(old
, new, addr
));
1275 * If cluster is shared, mark it with (sticky) EXTF_READONLY;
1276 * we don't clear the flag when the refcount goes back to the
1277 * minimum, to simplify code calling m_mclhasreference().
1279 if (new > (MEXT_MINREF(m
) + 1) && !(MEXT_FLAGS(m
) & EXTF_READONLY
)) {
1280 (void) OSBitOrAtomic16(EXTF_READONLY
, &MEXT_FLAGS(m
));
1284 static inline u_int16_t
1285 m_decref(struct mbuf
*m
)
1288 volatile UInt16
*addr
= (volatile UInt16
*)&MEXT_REF(m
);
1294 } while (!OSCompareAndSwap16(old
, new, addr
));
1300 mbuf_table_init(void)
1302 unsigned int b
, c
, s
;
1303 int m
, config_mbuf_jumbo
= 0;
1305 MALLOC(omb_stat
, struct omb_stat
*, OMB_STAT_SIZE(NELEM(mbuf_table
)),
1306 M_TEMP
, M_WAITOK
| M_ZERO
);
1307 VERIFY(omb_stat
!= NULL
);
1309 MALLOC(mb_stat
, mb_stat_t
*, MB_STAT_SIZE(NELEM(mbuf_table
)),
1310 M_TEMP
, M_WAITOK
| M_ZERO
);
1311 VERIFY(mb_stat
!= NULL
);
1313 mb_stat
->mbs_cnt
= NELEM(mbuf_table
);
1314 for (m
= 0; m
< NELEM(mbuf_table
); m
++) {
1315 mbuf_table
[m
].mtbl_stats
= &mb_stat
->mbs_class
[m
];
1318 #if CONFIG_MBUF_JUMBO
1319 config_mbuf_jumbo
= 1;
1320 #endif /* CONFIG_MBUF_JUMBO */
1322 if (config_mbuf_jumbo
== 1 || PAGE_SIZE
== M16KCLBYTES
) {
1324 * Set aside 1/3 of the mbuf cluster map for jumbo
1325 * clusters; we do this only on platforms where jumbo
1326 * cluster pool is enabled.
1328 njcl
= nmbclusters
/ 3;
1329 njclbytes
= M16KCLBYTES
;
1333 * nclusters holds both the 2KB and 4KB pools, so ensure it's
1334 * a multiple of 4KB clusters.
1336 nclusters
= P2ROUNDDOWN(nmbclusters
- njcl
, NCLPG
);
1339 * Each jumbo cluster takes 8 2KB clusters, so make
1340 * sure that the pool size is evenly divisible by 8;
1341 * njcl is in 2KB unit, hence treated as such.
1343 njcl
= P2ROUNDDOWN(nmbclusters
- nclusters
, NCLPJCL
);
1345 /* Update nclusters with rounded down value of njcl */
1346 nclusters
= P2ROUNDDOWN(nmbclusters
- njcl
, NCLPG
);
1350 * njcl is valid only on platforms with 16KB jumbo clusters or
1351 * with 16KB pages, where it is configured to 1/3 of the pool
1352 * size. On these platforms, the remaining is used for 2KB
1353 * and 4KB clusters. On platforms without 16KB jumbo clusters,
1354 * the entire pool is used for both 2KB and 4KB clusters. A 4KB
1355 * cluster can either be splitted into 16 mbufs, or into 2 2KB
1358 * +---+---+------------ ... -----------+------- ... -------+
1359 * | c | b | s | njcl |
1360 * +---+---+------------ ... -----------+------- ... -------+
1362 * 1/32th of the shared region is reserved for pure 2KB and 4KB
1363 * clusters (1/64th each.)
1365 c
= P2ROUNDDOWN((nclusters
>> 6), NCLPG
); /* in 2KB unit */
1366 b
= P2ROUNDDOWN((nclusters
>> (6 + NCLPBGSHIFT
)), NBCLPG
); /* in 4KB unit */
1367 s
= nclusters
- (c
+ (b
<< NCLPBGSHIFT
)); /* in 2KB unit */
1370 * 1/64th (c) is reserved for 2KB clusters.
1372 m_minlimit(MC_CL
) = c
;
1373 m_maxlimit(MC_CL
) = s
+ c
; /* in 2KB unit */
1374 m_maxsize(MC_CL
) = m_size(MC_CL
) = MCLBYTES
;
1375 (void) snprintf(m_cname(MC_CL
), MAX_MBUF_CNAME
, "cl");
1378 * Another 1/64th (b) of the map is reserved for 4KB clusters.
1379 * It cannot be turned into 2KB clusters or mbufs.
1381 m_minlimit(MC_BIGCL
) = b
;
1382 m_maxlimit(MC_BIGCL
) = (s
>> NCLPBGSHIFT
) + b
; /* in 4KB unit */
1383 m_maxsize(MC_BIGCL
) = m_size(MC_BIGCL
) = MBIGCLBYTES
;
1384 (void) snprintf(m_cname(MC_BIGCL
), MAX_MBUF_CNAME
, "bigcl");
1387 * The remaining 31/32ths (s) are all-purpose (mbufs, 2KB, or 4KB)
1389 m_minlimit(MC_MBUF
) = 0;
1390 m_maxlimit(MC_MBUF
) = (s
<< NMBPCLSHIFT
); /* in mbuf unit */
1391 m_maxsize(MC_MBUF
) = m_size(MC_MBUF
) = MSIZE
;
1392 (void) snprintf(m_cname(MC_MBUF
), MAX_MBUF_CNAME
, "mbuf");
1395 * Set limits for the composite classes.
1397 m_minlimit(MC_MBUF_CL
) = 0;
1398 m_maxlimit(MC_MBUF_CL
) = m_maxlimit(MC_CL
);
1399 m_maxsize(MC_MBUF_CL
) = MCLBYTES
;
1400 m_size(MC_MBUF_CL
) = m_size(MC_MBUF
) + m_size(MC_CL
);
1401 (void) snprintf(m_cname(MC_MBUF_CL
), MAX_MBUF_CNAME
, "mbuf_cl");
1403 m_minlimit(MC_MBUF_BIGCL
) = 0;
1404 m_maxlimit(MC_MBUF_BIGCL
) = m_maxlimit(MC_BIGCL
);
1405 m_maxsize(MC_MBUF_BIGCL
) = MBIGCLBYTES
;
1406 m_size(MC_MBUF_BIGCL
) = m_size(MC_MBUF
) + m_size(MC_BIGCL
);
1407 (void) snprintf(m_cname(MC_MBUF_BIGCL
), MAX_MBUF_CNAME
, "mbuf_bigcl");
1410 * And for jumbo classes.
1412 m_minlimit(MC_16KCL
) = 0;
1413 m_maxlimit(MC_16KCL
) = (njcl
>> NCLPJCLSHIFT
); /* in 16KB unit */
1414 m_maxsize(MC_16KCL
) = m_size(MC_16KCL
) = M16KCLBYTES
;
1415 (void) snprintf(m_cname(MC_16KCL
), MAX_MBUF_CNAME
, "16kcl");
1417 m_minlimit(MC_MBUF_16KCL
) = 0;
1418 m_maxlimit(MC_MBUF_16KCL
) = m_maxlimit(MC_16KCL
);
1419 m_maxsize(MC_MBUF_16KCL
) = M16KCLBYTES
;
1420 m_size(MC_MBUF_16KCL
) = m_size(MC_MBUF
) + m_size(MC_16KCL
);
1421 (void) snprintf(m_cname(MC_MBUF_16KCL
), MAX_MBUF_CNAME
, "mbuf_16kcl");
1424 * Initialize the legacy mbstat structure.
1426 bzero(&mbstat
, sizeof(mbstat
));
1427 mbstat
.m_msize
= m_maxsize(MC_MBUF
);
1428 mbstat
.m_mclbytes
= m_maxsize(MC_CL
);
1429 mbstat
.m_minclsize
= MINCLSIZE
;
1430 mbstat
.m_mlen
= MLEN
;
1431 mbstat
.m_mhlen
= MHLEN
;
1432 mbstat
.m_bigmclbytes
= m_maxsize(MC_BIGCL
);
1435 #if defined(__LP64__)
1436 typedef struct ncl_tbl
{
1437 uint64_t nt_maxmem
; /* memory (sane) size */
1438 uint32_t nt_mbpool
; /* mbuf pool size */
1442 static ncl_tbl_t ncl_table
[] = {
1443 { (1ULL << GBSHIFT
) /* 1 GB */, (64 << MBSHIFT
) /* 64 MB */ },
1444 { (1ULL << (GBSHIFT
+ 3)) /* 8 GB */, (96 << MBSHIFT
) /* 96 MB */ },
1445 { (1ULL << (GBSHIFT
+ 4)) /* 16 GB */, (128 << MBSHIFT
) /* 128 MB */ },
1450 static ncl_tbl_t ncl_table_srv
[] = {
1451 { (1ULL << GBSHIFT
) /* 1 GB */, (96 << MBSHIFT
) /* 96 MB */ },
1452 { (1ULL << (GBSHIFT
+ 2)) /* 4 GB */, (128 << MBSHIFT
) /* 128 MB */ },
1453 { (1ULL << (GBSHIFT
+ 3)) /* 8 GB */, (160 << MBSHIFT
) /* 160 MB */ },
1454 { (1ULL << (GBSHIFT
+ 4)) /* 16 GB */, (192 << MBSHIFT
) /* 192 MB */ },
1455 { (1ULL << (GBSHIFT
+ 5)) /* 32 GB */, (256 << MBSHIFT
) /* 256 MB */ },
1456 { (1ULL << (GBSHIFT
+ 6)) /* 64 GB */, (384 << MBSHIFT
) /* 384 MB */ },
1459 #endif /* __LP64__ */
1461 __private_extern__
unsigned int
1462 mbuf_default_ncl(int server
, uint64_t mem
)
1464 #if !defined(__LP64__)
1465 #pragma unused(server)
1468 * 32-bit kernel (default to 64MB of mbuf pool for >= 1GB RAM).
1470 if ((n
= ((mem
/ 16) / MCLBYTES
)) > 32768) {
1475 ncl_tbl_t
*tbl
= (server
? ncl_table_srv
: ncl_table
);
1477 * 64-bit kernel (mbuf pool size based on table).
1479 n
= tbl
[0].nt_mbpool
;
1480 for (i
= 0; tbl
[i
].nt_mbpool
!= 0; i
++) {
1481 if (mem
< tbl
[i
].nt_maxmem
) {
1484 n
= tbl
[i
].nt_mbpool
;
1487 #endif /* !__LP64__ */
1491 __private_extern__
void
1495 unsigned int initmcl
= 0;
1497 thread_t thread
= THREAD_NULL
;
1499 microuptime(&mb_start
);
1502 * These MBUF_ values must be equal to their private counterparts.
1504 _CASSERT(MBUF_EXT
== M_EXT
);
1505 _CASSERT(MBUF_PKTHDR
== M_PKTHDR
);
1506 _CASSERT(MBUF_EOR
== M_EOR
);
1507 _CASSERT(MBUF_LOOP
== M_LOOP
);
1508 _CASSERT(MBUF_BCAST
== M_BCAST
);
1509 _CASSERT(MBUF_MCAST
== M_MCAST
);
1510 _CASSERT(MBUF_FRAG
== M_FRAG
);
1511 _CASSERT(MBUF_FIRSTFRAG
== M_FIRSTFRAG
);
1512 _CASSERT(MBUF_LASTFRAG
== M_LASTFRAG
);
1513 _CASSERT(MBUF_PROMISC
== M_PROMISC
);
1514 _CASSERT(MBUF_HASFCS
== M_HASFCS
);
1516 _CASSERT(MBUF_TYPE_FREE
== MT_FREE
);
1517 _CASSERT(MBUF_TYPE_DATA
== MT_DATA
);
1518 _CASSERT(MBUF_TYPE_HEADER
== MT_HEADER
);
1519 _CASSERT(MBUF_TYPE_SOCKET
== MT_SOCKET
);
1520 _CASSERT(MBUF_TYPE_PCB
== MT_PCB
);
1521 _CASSERT(MBUF_TYPE_RTABLE
== MT_RTABLE
);
1522 _CASSERT(MBUF_TYPE_HTABLE
== MT_HTABLE
);
1523 _CASSERT(MBUF_TYPE_ATABLE
== MT_ATABLE
);
1524 _CASSERT(MBUF_TYPE_SONAME
== MT_SONAME
);
1525 _CASSERT(MBUF_TYPE_SOOPTS
== MT_SOOPTS
);
1526 _CASSERT(MBUF_TYPE_FTABLE
== MT_FTABLE
);
1527 _CASSERT(MBUF_TYPE_RIGHTS
== MT_RIGHTS
);
1528 _CASSERT(MBUF_TYPE_IFADDR
== MT_IFADDR
);
1529 _CASSERT(MBUF_TYPE_CONTROL
== MT_CONTROL
);
1530 _CASSERT(MBUF_TYPE_OOBDATA
== MT_OOBDATA
);
1532 _CASSERT(MBUF_TSO_IPV4
== CSUM_TSO_IPV4
);
1533 _CASSERT(MBUF_TSO_IPV6
== CSUM_TSO_IPV6
);
1534 _CASSERT(MBUF_CSUM_REQ_SUM16
== CSUM_PARTIAL
);
1535 _CASSERT(MBUF_CSUM_TCP_SUM16
== MBUF_CSUM_REQ_SUM16
);
1536 _CASSERT(MBUF_CSUM_REQ_ZERO_INVERT
== CSUM_ZERO_INVERT
);
1537 _CASSERT(MBUF_CSUM_REQ_IP
== CSUM_IP
);
1538 _CASSERT(MBUF_CSUM_REQ_TCP
== CSUM_TCP
);
1539 _CASSERT(MBUF_CSUM_REQ_UDP
== CSUM_UDP
);
1540 _CASSERT(MBUF_CSUM_REQ_TCPIPV6
== CSUM_TCPIPV6
);
1541 _CASSERT(MBUF_CSUM_REQ_UDPIPV6
== CSUM_UDPIPV6
);
1542 _CASSERT(MBUF_CSUM_DID_IP
== CSUM_IP_CHECKED
);
1543 _CASSERT(MBUF_CSUM_IP_GOOD
== CSUM_IP_VALID
);
1544 _CASSERT(MBUF_CSUM_DID_DATA
== CSUM_DATA_VALID
);
1545 _CASSERT(MBUF_CSUM_PSEUDO_HDR
== CSUM_PSEUDO_HDR
);
1547 _CASSERT(MBUF_WAITOK
== M_WAIT
);
1548 _CASSERT(MBUF_DONTWAIT
== M_DONTWAIT
);
1549 _CASSERT(MBUF_COPYALL
== M_COPYALL
);
1551 _CASSERT(MBUF_SC2TC(MBUF_SC_BK_SYS
) == MBUF_TC_BK
);
1552 _CASSERT(MBUF_SC2TC(MBUF_SC_BK
) == MBUF_TC_BK
);
1553 _CASSERT(MBUF_SC2TC(MBUF_SC_BE
) == MBUF_TC_BE
);
1554 _CASSERT(MBUF_SC2TC(MBUF_SC_RD
) == MBUF_TC_BE
);
1555 _CASSERT(MBUF_SC2TC(MBUF_SC_OAM
) == MBUF_TC_BE
);
1556 _CASSERT(MBUF_SC2TC(MBUF_SC_AV
) == MBUF_TC_VI
);
1557 _CASSERT(MBUF_SC2TC(MBUF_SC_RV
) == MBUF_TC_VI
);
1558 _CASSERT(MBUF_SC2TC(MBUF_SC_VI
) == MBUF_TC_VI
);
1559 _CASSERT(MBUF_SC2TC(MBUF_SC_SIG
) == MBUF_TC_VI
);
1560 _CASSERT(MBUF_SC2TC(MBUF_SC_VO
) == MBUF_TC_VO
);
1561 _CASSERT(MBUF_SC2TC(MBUF_SC_CTL
) == MBUF_TC_VO
);
1563 _CASSERT(MBUF_TC2SCVAL(MBUF_TC_BK
) == SCVAL_BK
);
1564 _CASSERT(MBUF_TC2SCVAL(MBUF_TC_BE
) == SCVAL_BE
);
1565 _CASSERT(MBUF_TC2SCVAL(MBUF_TC_VI
) == SCVAL_VI
);
1566 _CASSERT(MBUF_TC2SCVAL(MBUF_TC_VO
) == SCVAL_VO
);
1568 /* Module specific scratch space (32-bit alignment requirement) */
1569 _CASSERT(!(offsetof(struct mbuf
, m_pkthdr
.pkt_mpriv
) %
1572 /* Initialize random red zone cookie value */
1573 _CASSERT(sizeof(mb_redzone_cookie
) ==
1574 sizeof(((struct pkthdr
*)0)->redzone
));
1575 read_random(&mb_redzone_cookie
, sizeof(mb_redzone_cookie
));
1576 read_random(&mb_obscure_extref
, sizeof(mb_obscure_extref
));
1577 read_random(&mb_obscure_extfree
, sizeof(mb_obscure_extfree
));
1578 mb_obscure_extref
|= 0x3;
1579 mb_obscure_extfree
|= 0x3;
1581 /* Make sure we don't save more than we should */
1582 _CASSERT(MCA_SAVED_MBUF_SIZE
<= sizeof(struct mbuf
));
1584 if (nmbclusters
== 0) {
1585 nmbclusters
= NMBCLUSTERS
;
1588 /* This should be a sane (at least even) value by now */
1589 VERIFY(nmbclusters
!= 0 && !(nmbclusters
& 0x1));
1591 /* Setup the mbuf table */
1594 /* Global lock for common layer */
1595 mbuf_mlock_grp_attr
= lck_grp_attr_alloc_init();
1596 mbuf_mlock_grp
= lck_grp_alloc_init("mbuf", mbuf_mlock_grp_attr
);
1597 mbuf_mlock_attr
= lck_attr_alloc_init();
1598 lck_mtx_init(mbuf_mlock
, mbuf_mlock_grp
, mbuf_mlock_attr
);
1601 * Allocate cluster slabs table:
1603 * maxslabgrp = (N * 2048) / (1024 * 1024)
1605 * Where N is nmbclusters rounded up to the nearest 512. This yields
1606 * mcl_slab_g_t units, each one representing a MB of memory.
1609 (P2ROUNDUP(nmbclusters
, (MBSIZE
>> MCLSHIFT
)) << MCLSHIFT
) >> MBSHIFT
;
1610 MALLOC(slabstbl
, mcl_slabg_t
* *, maxslabgrp
* sizeof(mcl_slabg_t
*),
1611 M_TEMP
, M_WAITOK
| M_ZERO
);
1612 VERIFY(slabstbl
!= NULL
);
1615 * Allocate audit structures, if needed:
1617 * maxclaudit = (maxslabgrp * 1024 * 1024) / PAGE_SIZE
1619 * This yields mcl_audit_t units, each one representing a page.
1621 PE_parse_boot_argn("mbuf_debug", &mbuf_debug
, sizeof(mbuf_debug
));
1622 mbuf_debug
|= mcache_getflags();
1623 if (mbuf_debug
& MCF_DEBUG
) {
1626 maxclaudit
= ((maxslabgrp
<< MBSHIFT
) >> PAGE_SHIFT
);
1627 MALLOC(mclaudit
, mcl_audit_t
*, maxclaudit
* sizeof(*mclaudit
),
1628 M_TEMP
, M_WAITOK
| M_ZERO
);
1629 VERIFY(mclaudit
!= NULL
);
1630 for (l
= 0, mclad
= mclaudit
; l
< maxclaudit
; l
++) {
1631 MALLOC(mclad
[l
].cl_audit
, mcache_audit_t
* *,
1632 NMBPG
* sizeof(mcache_audit_t
*),
1633 M_TEMP
, M_WAITOK
| M_ZERO
);
1634 VERIFY(mclad
[l
].cl_audit
!= NULL
);
1637 mcl_audit_con_cache
= mcache_create("mcl_audit_contents",
1638 AUDIT_CONTENTS_SIZE
, sizeof(u_int64_t
), 0, MCR_SLEEP
);
1639 VERIFY(mcl_audit_con_cache
!= NULL
);
1641 mclverify
= (mbuf_debug
& MCF_VERIFY
);
1642 mcltrace
= (mbuf_debug
& MCF_TRACE
);
1643 mclfindleak
= !(mbuf_debug
& MCF_NOLEAKLOG
);
1644 mclexpleak
= mclfindleak
&& (mbuf_debug
& MCF_EXPLEAKLOG
);
1646 /* Enable mbuf leak logging, with a lock to protect the tables */
1648 mleak_lock_grp_attr
= lck_grp_attr_alloc_init();
1649 mleak_lock_grp
= lck_grp_alloc_init("mleak_lock", mleak_lock_grp_attr
);
1650 mleak_lock_attr
= lck_attr_alloc_init();
1651 lck_mtx_init(mleak_lock
, mleak_lock_grp
, mleak_lock_attr
);
1656 * Allocate structure for per-CPU statistics that's aligned
1657 * on the CPU cache boundary; this code assumes that we never
1658 * uninitialize this framework, since the original address
1659 * before alignment is not saved.
1661 ncpu
= ml_get_max_cpus();
1662 MALLOC(buf
, void *, MBUF_MTYPES_SIZE(ncpu
) + CPU_CACHE_LINE_SIZE
,
1664 VERIFY(buf
!= NULL
);
1666 mbuf_mtypes
= (mbuf_mtypes_t
*)P2ROUNDUP((intptr_t)buf
,
1667 CPU_CACHE_LINE_SIZE
);
1668 bzero(mbuf_mtypes
, MBUF_MTYPES_SIZE(ncpu
));
1670 /* Calculate the number of pages assigned to the cluster pool */
1671 mcl_pages
= (nmbclusters
<< MCLSHIFT
) / PAGE_SIZE
;
1672 MALLOC(mcl_paddr
, ppnum_t
*, mcl_pages
* sizeof(ppnum_t
),
1674 VERIFY(mcl_paddr
!= NULL
);
1676 /* Register with the I/O Bus mapper */
1677 mcl_paddr_base
= IOMapperIOVMAlloc(mcl_pages
);
1678 bzero((char *)mcl_paddr
, mcl_pages
* sizeof(ppnum_t
));
1680 embutl
= (mbutl
+ (nmbclusters
* MCLBYTES
));
1681 VERIFY(((embutl
- mbutl
) % MBIGCLBYTES
) == 0);
1683 /* Prime up the freelist */
1684 PE_parse_boot_argn("initmcl", &initmcl
, sizeof(initmcl
));
1686 initmcl
>>= NCLPBGSHIFT
; /* become a 4K unit */
1687 if (initmcl
> m_maxlimit(MC_BIGCL
)) {
1688 initmcl
= m_maxlimit(MC_BIGCL
);
1691 if (initmcl
< m_minlimit(MC_BIGCL
)) {
1692 initmcl
= m_minlimit(MC_BIGCL
);
1695 lck_mtx_lock(mbuf_mlock
);
1698 * For classes with non-zero minimum limits, populate their freelists
1699 * so that m_total(class) is at least m_minlimit(class).
1701 VERIFY(m_total(MC_BIGCL
) == 0 && m_minlimit(MC_BIGCL
) != 0);
1702 freelist_populate(m_class(MC_BIGCL
), initmcl
, M_WAIT
);
1703 VERIFY(m_total(MC_BIGCL
) >= m_minlimit(MC_BIGCL
));
1704 freelist_init(m_class(MC_CL
));
1706 for (m
= 0; m
< NELEM(mbuf_table
); m
++) {
1707 /* Make sure we didn't miss any */
1708 VERIFY(m_minlimit(m_class(m
)) == 0 ||
1709 m_total(m_class(m
)) >= m_minlimit(m_class(m
)));
1711 /* populate the initial sizes and report from there on */
1712 m_peak(m_class(m
)) = m_total(m_class(m
));
1714 mb_peak_newreport
= FALSE
;
1716 lck_mtx_unlock(mbuf_mlock
);
1718 (void) kernel_thread_start((thread_continue_t
)mbuf_worker_thread_init
,
1720 thread_deallocate(thread
);
1722 ref_cache
= mcache_create("mext_ref", sizeof(struct ext_ref
),
1725 /* Create the cache for each class */
1726 for (m
= 0; m
< NELEM(mbuf_table
); m
++) {
1727 void *allocfunc
, *freefunc
, *auditfunc
, *logfunc
;
1731 if (m_class(m
) == MC_MBUF_CL
|| m_class(m
) == MC_MBUF_BIGCL
||
1732 m_class(m
) == MC_MBUF_16KCL
) {
1733 allocfunc
= mbuf_cslab_alloc
;
1734 freefunc
= mbuf_cslab_free
;
1735 auditfunc
= mbuf_cslab_audit
;
1736 logfunc
= mleak_logger
;
1738 allocfunc
= mbuf_slab_alloc
;
1739 freefunc
= mbuf_slab_free
;
1740 auditfunc
= mbuf_slab_audit
;
1741 logfunc
= mleak_logger
;
1745 * Disable per-CPU caches for jumbo classes if there
1746 * is no jumbo cluster pool available in the system.
1747 * The cache itself is still created (but will never
1748 * be populated) since it simplifies the code.
1750 if ((m_class(m
) == MC_MBUF_16KCL
|| m_class(m
) == MC_16KCL
) &&
1752 flags
|= MCF_NOCPUCACHE
;
1756 flags
|= MCF_NOLEAKLOG
;
1759 m_cache(m
) = mcache_create_ext(m_cname(m
), m_maxsize(m
),
1760 allocfunc
, freefunc
, auditfunc
, logfunc
, mbuf_slab_notify
,
1761 (void *)(uintptr_t)m
, flags
, MCR_SLEEP
);
1765 * Set the max limit on sb_max to be 1/16 th of the size of
1766 * memory allocated for mbuf clusters.
1768 high_sb_max
= (nmbclusters
<< (MCLSHIFT
- 4));
1769 if (high_sb_max
< sb_max
) {
1770 /* sb_max is too large for this configuration, scale it down */
1771 if (high_sb_max
> (1 << MBSHIFT
)) {
1772 /* We have atleast 16 M of mbuf pool */
1773 sb_max
= high_sb_max
;
1774 } else if ((nmbclusters
<< MCLSHIFT
) > (1 << MBSHIFT
)) {
1776 * If we have more than 1M of mbufpool, cap the size of
1777 * max sock buf at 1M
1779 sb_max
= high_sb_max
= (1 << MBSHIFT
);
1781 sb_max
= high_sb_max
;
1785 /* allocate space for mbuf_dump_buf */
1786 MALLOC(mbuf_dump_buf
, char *, MBUF_DUMP_BUF_SIZE
, M_TEMP
, M_WAITOK
);
1787 VERIFY(mbuf_dump_buf
!= NULL
);
1789 if (mbuf_debug
& MCF_DEBUG
) {
1790 printf("%s: MLEN %d, MHLEN %d\n", __func__
,
1791 (int)_MLEN
, (int)_MHLEN
);
1794 printf("%s: done [%d MB total pool size, (%d/%d) split]\n", __func__
,
1795 (nmbclusters
<< MCLSHIFT
) >> MBSHIFT
,
1796 (nclusters
<< MCLSHIFT
) >> MBSHIFT
,
1797 (njcl
<< MCLSHIFT
) >> MBSHIFT
);
1799 /* initialize lock form tx completion callback table */
1800 mbuf_tx_compl_tbl_lck_grp_attr
= lck_grp_attr_alloc_init();
1801 if (mbuf_tx_compl_tbl_lck_grp_attr
== NULL
) {
1802 panic("%s: lck_grp_attr_alloc_init failed", __func__
);
1805 mbuf_tx_compl_tbl_lck_grp
= lck_grp_alloc_init("mbuf_tx_compl_tbl",
1806 mbuf_tx_compl_tbl_lck_grp_attr
);
1807 if (mbuf_tx_compl_tbl_lck_grp
== NULL
) {
1808 panic("%s: lck_grp_alloc_init failed", __func__
);
1811 mbuf_tx_compl_tbl_lck_attr
= lck_attr_alloc_init();
1812 if (mbuf_tx_compl_tbl_lck_attr
== NULL
) {
1813 panic("%s: lck_attr_alloc_init failed", __func__
);
1816 lck_rw_init(mbuf_tx_compl_tbl_lock
, mbuf_tx_compl_tbl_lck_grp
,
1817 mbuf_tx_compl_tbl_lck_attr
);
1821 * Obtain a slab of object(s) from the class's freelist.
1823 static mcache_obj_t
*
1824 slab_alloc(mbuf_class_t
class, int wait
)
1829 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_OWNED
);
1831 /* This should always be NULL for us */
1832 VERIFY(m_cobjlist(class) == NULL
);
1835 * Treat composite objects as having longer lifespan by using
1836 * a slab from the reverse direction, in hoping that this could
1837 * reduce the probability of fragmentation for slabs that hold
1838 * more than one buffer chunks (e.g. mbuf slabs). For other
1839 * slabs, this probably doesn't make much of a difference.
1841 if ((class == MC_MBUF
|| class == MC_CL
|| class == MC_BIGCL
)
1842 && (wait
& MCR_COMP
)) {
1843 sp
= (mcl_slab_t
*)TAILQ_LAST(&m_slablist(class), mcl_slhead
);
1845 sp
= (mcl_slab_t
*)TAILQ_FIRST(&m_slablist(class));
1849 VERIFY(m_infree(class) == 0 && m_slab_cnt(class) == 0);
1850 /* The slab list for this class is empty */
1854 VERIFY(m_infree(class) > 0);
1855 VERIFY(!slab_is_detached(sp
));
1856 VERIFY(sp
->sl_class
== class &&
1857 (sp
->sl_flags
& (SLF_MAPPED
| SLF_PARTIAL
)) == SLF_MAPPED
);
1859 VERIFY(slab_inrange(sp
, buf
) && sp
== slab_get(buf
));
1860 sp
->sl_head
= buf
->obj_next
;
1861 /* Increment slab reference */
1864 VERIFY(sp
->sl_head
!= NULL
|| sp
->sl_refcnt
== sp
->sl_chunks
);
1866 if (sp
->sl_head
!= NULL
&& !slab_inrange(sp
, sp
->sl_head
)) {
1867 slab_nextptr_panic(sp
, sp
->sl_head
);
1868 /* In case sl_head is in the map but not in the slab */
1869 VERIFY(slab_inrange(sp
, sp
->sl_head
));
1873 if (mclaudit
!= NULL
) {
1874 mcache_audit_t
*mca
= mcl_audit_buf2mca(class, buf
);
1875 mca
->mca_uflags
= 0;
1876 /* Save contents on mbuf objects only */
1877 if (class == MC_MBUF
) {
1878 mca
->mca_uflags
|= MB_SCVALID
;
1882 if (class == MC_CL
) {
1883 mbstat
.m_clfree
= (--m_infree(MC_CL
)) + m_infree(MC_MBUF_CL
);
1885 * A 2K cluster slab can have at most NCLPG references.
1887 VERIFY(sp
->sl_refcnt
>= 1 && sp
->sl_refcnt
<= NCLPG
&&
1888 sp
->sl_chunks
== NCLPG
&& sp
->sl_len
== PAGE_SIZE
);
1889 VERIFY(sp
->sl_refcnt
< NCLPG
|| sp
->sl_head
== NULL
);
1890 } else if (class == MC_BIGCL
) {
1891 mbstat
.m_bigclfree
= (--m_infree(MC_BIGCL
)) +
1892 m_infree(MC_MBUF_BIGCL
);
1894 * A 4K cluster slab can have NBCLPG references.
1896 VERIFY(sp
->sl_refcnt
>= 1 && sp
->sl_chunks
== NBCLPG
&&
1897 sp
->sl_len
== PAGE_SIZE
&&
1898 (sp
->sl_refcnt
< NBCLPG
|| sp
->sl_head
== NULL
));
1899 } else if (class == MC_16KCL
) {
1903 --m_infree(MC_16KCL
);
1904 VERIFY(sp
->sl_refcnt
== 1 && sp
->sl_chunks
== 1 &&
1905 sp
->sl_len
== m_maxsize(class) && sp
->sl_head
== NULL
);
1907 * Increment 2nd-Nth slab reference, where N is NSLABSP16KB.
1908 * A 16KB big cluster takes NSLABSP16KB slabs, each having at
1911 for (nsp
= sp
, k
= 1; k
< NSLABSP16KB
; k
++) {
1913 /* Next slab must already be present */
1914 VERIFY(nsp
!= NULL
);
1916 VERIFY(!slab_is_detached(nsp
));
1917 VERIFY(nsp
->sl_class
== MC_16KCL
&&
1918 nsp
->sl_flags
== (SLF_MAPPED
| SLF_PARTIAL
) &&
1919 nsp
->sl_refcnt
== 1 && nsp
->sl_chunks
== 0 &&
1920 nsp
->sl_len
== 0 && nsp
->sl_base
== sp
->sl_base
&&
1921 nsp
->sl_head
== NULL
);
1924 VERIFY(class == MC_MBUF
);
1925 --m_infree(MC_MBUF
);
1927 * If auditing is turned on, this check is
1928 * deferred until later in mbuf_slab_audit().
1930 if (mclaudit
== NULL
) {
1931 _MCHECK((struct mbuf
*)buf
);
1934 * Since we have incremented the reference count above,
1935 * an mbuf slab (formerly a 4KB cluster slab that was cut
1936 * up into mbufs) must have a reference count between 1
1937 * and NMBPG at this point.
1939 VERIFY(sp
->sl_refcnt
>= 1 && sp
->sl_refcnt
<= NMBPG
&&
1940 sp
->sl_chunks
== NMBPG
&&
1941 sp
->sl_len
== PAGE_SIZE
);
1942 VERIFY(sp
->sl_refcnt
< NMBPG
|| sp
->sl_head
== NULL
);
1945 /* If empty, remove this slab from the class's freelist */
1946 if (sp
->sl_head
== NULL
) {
1947 VERIFY(class != MC_MBUF
|| sp
->sl_refcnt
== NMBPG
);
1948 VERIFY(class != MC_CL
|| sp
->sl_refcnt
== NCLPG
);
1949 VERIFY(class != MC_BIGCL
|| sp
->sl_refcnt
== NBCLPG
);
1950 slab_remove(sp
, class);
1957 * Place a slab of object(s) back into a class's slab list.
1960 slab_free(mbuf_class_t
class, mcache_obj_t
*buf
)
1963 boolean_t reinit_supercl
= false;
1964 mbuf_class_t super_class
;
1966 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_OWNED
);
1968 VERIFY(class != MC_16KCL
|| njcl
> 0);
1969 VERIFY(buf
->obj_next
== NULL
);
1972 * Synchronizing with m_clalloc, as it reads m_total, while we here
1973 * are modifying m_total.
1975 while (mb_clalloc_busy
) {
1976 mb_clalloc_waiters
++;
1977 (void) msleep(mb_clalloc_waitchan
, mbuf_mlock
,
1978 (PZERO
- 1), "m_clalloc", NULL
);
1979 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_OWNED
);
1982 /* We are busy now; tell everyone else to go away */
1983 mb_clalloc_busy
= TRUE
;
1986 VERIFY(sp
->sl_class
== class && slab_inrange(sp
, buf
) &&
1987 (sp
->sl_flags
& (SLF_MAPPED
| SLF_PARTIAL
)) == SLF_MAPPED
);
1989 /* Decrement slab reference */
1992 if (class == MC_CL
) {
1993 VERIFY(IS_P2ALIGNED(buf
, MCLBYTES
));
1995 * A slab that has been splitted for 2KB clusters can have
1996 * at most 1 outstanding reference at this point.
1998 VERIFY(sp
->sl_refcnt
>= 0 && sp
->sl_refcnt
<= (NCLPG
- 1) &&
1999 sp
->sl_chunks
== NCLPG
&& sp
->sl_len
== PAGE_SIZE
);
2000 VERIFY(sp
->sl_refcnt
< (NCLPG
- 1) ||
2001 (slab_is_detached(sp
) && sp
->sl_head
== NULL
));
2002 } else if (class == MC_BIGCL
) {
2003 VERIFY(IS_P2ALIGNED(buf
, MBIGCLBYTES
));
2005 /* A 4KB cluster slab can have NBCLPG references at most */
2006 VERIFY(sp
->sl_refcnt
>= 0 && sp
->sl_chunks
== NBCLPG
);
2007 VERIFY(sp
->sl_refcnt
< (NBCLPG
- 1) ||
2008 (slab_is_detached(sp
) && sp
->sl_head
== NULL
));
2009 } else if (class == MC_16KCL
) {
2013 * A 16KB cluster takes NSLABSP16KB slabs, all must
2014 * now have 0 reference.
2016 VERIFY(IS_P2ALIGNED(buf
, PAGE_SIZE
));
2017 VERIFY(sp
->sl_refcnt
== 0 && sp
->sl_chunks
== 1 &&
2018 sp
->sl_len
== m_maxsize(class) && sp
->sl_head
== NULL
);
2019 VERIFY(slab_is_detached(sp
));
2020 for (nsp
= sp
, k
= 1; k
< NSLABSP16KB
; k
++) {
2022 /* Next slab must already be present */
2023 VERIFY(nsp
!= NULL
);
2025 VERIFY(slab_is_detached(nsp
));
2026 VERIFY(nsp
->sl_class
== MC_16KCL
&&
2027 (nsp
->sl_flags
& (SLF_MAPPED
| SLF_PARTIAL
)) &&
2028 nsp
->sl_refcnt
== 0 && nsp
->sl_chunks
== 0 &&
2029 nsp
->sl_len
== 0 && nsp
->sl_base
== sp
->sl_base
&&
2030 nsp
->sl_head
== NULL
);
2034 * A slab that has been splitted for mbufs has at most
2035 * NMBPG reference counts. Since we have decremented
2036 * one reference above, it must now be between 0 and
2039 VERIFY(class == MC_MBUF
);
2040 VERIFY(sp
->sl_refcnt
>= 0 &&
2041 sp
->sl_refcnt
<= (NMBPG
- 1) &&
2042 sp
->sl_chunks
== NMBPG
&&
2043 sp
->sl_len
== PAGE_SIZE
);
2044 VERIFY(sp
->sl_refcnt
< (NMBPG
- 1) ||
2045 (slab_is_detached(sp
) && sp
->sl_head
== NULL
));
2049 * When auditing is enabled, ensure that the buffer still
2050 * contains the free pattern. Otherwise it got corrupted
2051 * while at the CPU cache layer.
2053 if (mclaudit
!= NULL
) {
2054 mcache_audit_t
*mca
= mcl_audit_buf2mca(class, buf
);
2056 mcache_audit_free_verify(mca
, buf
, 0,
2059 mca
->mca_uflags
&= ~MB_SCVALID
;
2062 if (class == MC_CL
) {
2063 mbstat
.m_clfree
= (++m_infree(MC_CL
)) + m_infree(MC_MBUF_CL
);
2064 buf
->obj_next
= sp
->sl_head
;
2065 } else if (class == MC_BIGCL
) {
2066 mbstat
.m_bigclfree
= (++m_infree(MC_BIGCL
)) +
2067 m_infree(MC_MBUF_BIGCL
);
2068 buf
->obj_next
= sp
->sl_head
;
2069 } else if (class == MC_16KCL
) {
2070 ++m_infree(MC_16KCL
);
2072 ++m_infree(MC_MBUF
);
2073 buf
->obj_next
= sp
->sl_head
;
2078 * If a slab has been split to either one which holds 2KB clusters,
2079 * or one which holds mbufs, turn it back to one which holds a
2080 * 4 or 16 KB cluster depending on the page size.
2082 if (m_maxsize(MC_BIGCL
) == PAGE_SIZE
) {
2083 super_class
= MC_BIGCL
;
2085 VERIFY(PAGE_SIZE
== m_maxsize(MC_16KCL
));
2086 super_class
= MC_16KCL
;
2088 if (class == MC_MBUF
&& sp
->sl_refcnt
== 0 &&
2089 m_total(class) >= (m_minlimit(class) + NMBPG
) &&
2090 m_total(super_class
) < m_maxlimit(super_class
)) {
2093 m_total(MC_MBUF
) -= NMBPG
;
2094 mbstat
.m_mbufs
= m_total(MC_MBUF
);
2095 m_infree(MC_MBUF
) -= NMBPG
;
2096 mtype_stat_add(MT_FREE
, -((unsigned)NMBPG
));
2099 struct mbuf
*m
= sp
->sl_head
;
2101 sp
->sl_head
= m
->m_next
;
2104 reinit_supercl
= true;
2105 } else if (class == MC_CL
&& sp
->sl_refcnt
== 0 &&
2106 m_total(class) >= (m_minlimit(class) + NCLPG
) &&
2107 m_total(super_class
) < m_maxlimit(super_class
)) {
2110 m_total(MC_CL
) -= NCLPG
;
2111 mbstat
.m_clusters
= m_total(MC_CL
);
2112 m_infree(MC_CL
) -= NCLPG
;
2115 union mcluster
*c
= sp
->sl_head
;
2117 sp
->sl_head
= c
->mcl_next
;
2120 reinit_supercl
= true;
2121 } else if (class == MC_BIGCL
&& super_class
!= MC_BIGCL
&&
2122 sp
->sl_refcnt
== 0 &&
2123 m_total(class) >= (m_minlimit(class) + NBCLPG
) &&
2124 m_total(super_class
) < m_maxlimit(super_class
)) {
2127 VERIFY(super_class
== MC_16KCL
);
2128 m_total(MC_BIGCL
) -= NBCLPG
;
2129 mbstat
.m_bigclusters
= m_total(MC_BIGCL
);
2130 m_infree(MC_BIGCL
) -= NBCLPG
;
2133 union mbigcluster
*bc
= sp
->sl_head
;
2135 sp
->sl_head
= bc
->mbc_next
;
2136 bc
->mbc_next
= NULL
;
2138 reinit_supercl
= true;
2141 if (reinit_supercl
) {
2142 VERIFY(sp
->sl_head
== NULL
);
2143 VERIFY(m_total(class) >= m_minlimit(class));
2144 slab_remove(sp
, class);
2146 /* Reinitialize it as a cluster for the super class */
2147 m_total(super_class
)++;
2148 m_infree(super_class
)++;
2149 VERIFY(sp
->sl_flags
== (SLF_MAPPED
| SLF_DETACHED
) &&
2150 sp
->sl_len
== PAGE_SIZE
&& sp
->sl_refcnt
== 0);
2152 slab_init(sp
, super_class
, SLF_MAPPED
, sp
->sl_base
,
2153 sp
->sl_base
, PAGE_SIZE
, 0, 1);
2155 mcache_set_pattern(MCACHE_FREE_PATTERN
,
2156 (caddr_t
)sp
->sl_base
, sp
->sl_len
);
2158 ((mcache_obj_t
*)(sp
->sl_base
))->obj_next
= NULL
;
2160 if (super_class
== MC_BIGCL
) {
2161 mbstat
.m_bigclusters
= m_total(MC_BIGCL
);
2162 mbstat
.m_bigclfree
= m_infree(MC_BIGCL
) +
2163 m_infree(MC_MBUF_BIGCL
);
2166 VERIFY(slab_is_detached(sp
));
2167 VERIFY(m_total(super_class
) <= m_maxlimit(super_class
));
2169 /* And finally switch class */
2170 class = super_class
;
2173 /* Reinsert the slab to the class's slab list */
2174 if (slab_is_detached(sp
)) {
2175 slab_insert(sp
, class);
2178 /* We're done; let others enter */
2179 mb_clalloc_busy
= FALSE
;
2180 if (mb_clalloc_waiters
> 0) {
2181 mb_clalloc_waiters
= 0;
2182 wakeup(mb_clalloc_waitchan
);
2187 * Common allocator for rudimentary objects called by the CPU cache layer
2188 * during an allocation request whenever there is no available element in the
2189 * bucket layer. It returns one or more elements from the appropriate global
2190 * freelist. If the freelist is empty, it will attempt to populate it and
2191 * retry the allocation.
2194 mbuf_slab_alloc(void *arg
, mcache_obj_t
***plist
, unsigned int num
, int wait
)
2196 mbuf_class_t
class = (mbuf_class_t
)arg
;
2197 unsigned int need
= num
;
2198 mcache_obj_t
**list
= *plist
;
2200 ASSERT(MBUF_CLASS_VALID(class) && !MBUF_CLASS_COMPOSITE(class));
2203 lck_mtx_lock(mbuf_mlock
);
2206 if ((*list
= slab_alloc(class, wait
)) != NULL
) {
2207 (*list
)->obj_next
= NULL
;
2208 list
= *plist
= &(*list
)->obj_next
;
2212 * If the number of elements in freelist has
2213 * dropped below low watermark, asynchronously
2214 * populate the freelist now rather than doing
2215 * it later when we run out of elements.
2217 if (!mbuf_cached_above(class, wait
) &&
2218 m_infree(class) < (m_total(class) >> 5)) {
2219 (void) freelist_populate(class, 1,
2225 VERIFY(m_infree(class) == 0 || class == MC_CL
);
2227 (void) freelist_populate(class, 1,
2228 (wait
& MCR_NOSLEEP
) ? M_DONTWAIT
: M_WAIT
);
2230 if (m_infree(class) > 0) {
2234 /* Check if there's anything at the cache layer */
2235 if (mbuf_cached_above(class, wait
)) {
2239 /* watchdog checkpoint */
2242 /* We have nothing and cannot block; give up */
2243 if (wait
& MCR_NOSLEEP
) {
2244 if (!(wait
& MCR_TRYHARD
)) {
2245 m_fail_cnt(class)++;
2252 * If the freelist is still empty and the caller is
2253 * willing to be blocked, sleep on the wait channel
2254 * until an element is available. Otherwise, if
2255 * MCR_TRYHARD is set, do our best to satisfy the
2256 * request without having to go to sleep.
2258 if (mbuf_worker_ready
&&
2259 mbuf_sleep(class, need
, wait
)) {
2263 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_OWNED
);
2267 m_alloc_cnt(class) += num
- need
;
2268 lck_mtx_unlock(mbuf_mlock
);
2274 * Common de-allocator for rudimentary objects called by the CPU cache
2275 * layer when one or more elements need to be returned to the appropriate
2279 mbuf_slab_free(void *arg
, mcache_obj_t
*list
, __unused
int purged
)
2281 mbuf_class_t
class = (mbuf_class_t
)arg
;
2282 mcache_obj_t
*nlist
;
2283 unsigned int num
= 0;
2286 ASSERT(MBUF_CLASS_VALID(class) && !MBUF_CLASS_COMPOSITE(class));
2288 lck_mtx_lock(mbuf_mlock
);
2291 nlist
= list
->obj_next
;
2292 list
->obj_next
= NULL
;
2293 slab_free(class, list
);
2295 if ((list
= nlist
) == NULL
) {
2299 m_free_cnt(class) += num
;
2301 if ((w
= mb_waiters
) > 0) {
2305 mbwdog_logger("waking up all threads");
2307 lck_mtx_unlock(mbuf_mlock
);
2310 wakeup(mb_waitchan
);
2315 * Common auditor for rudimentary objects called by the CPU cache layer
2316 * during an allocation or free request. For the former, this is called
2317 * after the objects are obtained from either the bucket or slab layer
2318 * and before they are returned to the caller. For the latter, this is
2319 * called immediately during free and before placing the objects into
2320 * the bucket or slab layer.
2323 mbuf_slab_audit(void *arg
, mcache_obj_t
*list
, boolean_t alloc
)
2325 mbuf_class_t
class = (mbuf_class_t
)arg
;
2326 mcache_audit_t
*mca
;
2328 ASSERT(MBUF_CLASS_VALID(class) && !MBUF_CLASS_COMPOSITE(class));
2330 while (list
!= NULL
) {
2331 lck_mtx_lock(mbuf_mlock
);
2332 mca
= mcl_audit_buf2mca(class, list
);
2334 /* Do the sanity checks */
2335 if (class == MC_MBUF
) {
2336 mcl_audit_mbuf(mca
, list
, FALSE
, alloc
);
2337 ASSERT(mca
->mca_uflags
& MB_SCVALID
);
2339 mcl_audit_cluster(mca
, list
, m_maxsize(class),
2341 ASSERT(!(mca
->mca_uflags
& MB_SCVALID
));
2343 /* Record this transaction */
2345 mcache_buffer_log(mca
, list
, m_cache(class), &mb_start
);
2349 mca
->mca_uflags
|= MB_INUSE
;
2351 mca
->mca_uflags
&= ~MB_INUSE
;
2353 /* Unpair the object (unconditionally) */
2354 mca
->mca_uptr
= NULL
;
2355 lck_mtx_unlock(mbuf_mlock
);
2357 list
= list
->obj_next
;
2362 * Common notify routine for all caches. It is called by mcache when
2363 * one or more objects get freed. We use this indication to trigger
2364 * the wakeup of any sleeping threads so that they can retry their
2365 * allocation requests.
2368 mbuf_slab_notify(void *arg
, u_int32_t reason
)
2370 mbuf_class_t
class = (mbuf_class_t
)arg
;
2373 ASSERT(MBUF_CLASS_VALID(class));
2375 if (reason
!= MCN_RETRYALLOC
) {
2379 lck_mtx_lock(mbuf_mlock
);
2380 if ((w
= mb_waiters
) > 0) {
2381 m_notified(class)++;
2385 mbwdog_logger("waking up all threads");
2387 lck_mtx_unlock(mbuf_mlock
);
2390 wakeup(mb_waitchan
);
2395 * Obtain object(s) from the composite class's freelist.
2398 cslab_alloc(mbuf_class_t
class, mcache_obj_t
***plist
, unsigned int num
)
2400 unsigned int need
= num
;
2401 mcl_slab_t
*sp
, *clsp
, *nsp
;
2403 mcache_obj_t
**list
= *plist
;
2407 VERIFY(class != MC_MBUF_16KCL
|| njcl
> 0);
2408 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_OWNED
);
2410 /* Get what we can from the freelist */
2411 while ((*list
= m_cobjlist(class)) != NULL
) {
2414 m
= (struct mbuf
*)*list
;
2416 cl
= m
->m_ext
.ext_buf
;
2417 clsp
= slab_get(cl
);
2418 VERIFY(m
->m_flags
== M_EXT
&& cl
!= NULL
);
2419 VERIFY(m_get_rfa(m
) != NULL
&& MBUF_IS_COMPOSITE(m
));
2421 if (class == MC_MBUF_CL
) {
2422 VERIFY(clsp
->sl_refcnt
>= 1 &&
2423 clsp
->sl_refcnt
<= NCLPG
);
2425 VERIFY(clsp
->sl_refcnt
>= 1 &&
2426 clsp
->sl_refcnt
<= NBCLPG
);
2429 if (class == MC_MBUF_16KCL
) {
2431 for (nsp
= clsp
, k
= 1; k
< NSLABSP16KB
; k
++) {
2433 /* Next slab must already be present */
2434 VERIFY(nsp
!= NULL
);
2435 VERIFY(nsp
->sl_refcnt
== 1);
2439 if ((m_cobjlist(class) = (*list
)->obj_next
) != NULL
&&
2440 !MBUF_IN_MAP(m_cobjlist(class))) {
2441 slab_nextptr_panic(sp
, m_cobjlist(class));
2444 (*list
)->obj_next
= NULL
;
2445 list
= *plist
= &(*list
)->obj_next
;
2451 m_infree(class) -= (num
- need
);
2457 * Place object(s) back into a composite class's freelist.
2460 cslab_free(mbuf_class_t
class, mcache_obj_t
*list
, int purged
)
2462 mcache_obj_t
*o
, *tail
;
2463 unsigned int num
= 0;
2464 struct mbuf
*m
, *ms
;
2465 mcache_audit_t
*mca
= NULL
;
2466 mcache_obj_t
*ref_list
= NULL
;
2467 mcl_slab_t
*clsp
, *nsp
;
2469 mbuf_class_t cl_class
;
2471 ASSERT(MBUF_CLASS_VALID(class) && MBUF_CLASS_COMPOSITE(class));
2472 VERIFY(class != MC_MBUF_16KCL
|| njcl
> 0);
2473 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_OWNED
);
2475 if (class == MC_MBUF_CL
) {
2477 } else if (class == MC_MBUF_BIGCL
) {
2478 cl_class
= MC_BIGCL
;
2480 VERIFY(class == MC_MBUF_16KCL
);
2481 cl_class
= MC_16KCL
;
2486 while ((m
= ms
= (struct mbuf
*)o
) != NULL
) {
2487 mcache_obj_t
*rfa
, *nexto
= o
->obj_next
;
2489 /* Do the mbuf sanity checks */
2490 if (mclaudit
!= NULL
) {
2491 mca
= mcl_audit_buf2mca(MC_MBUF
, (mcache_obj_t
*)m
);
2493 mcache_audit_free_verify(mca
, m
, 0,
2494 m_maxsize(MC_MBUF
));
2496 ms
= MCA_SAVED_MBUF_PTR(mca
);
2499 /* Do the cluster sanity checks */
2500 cl
= ms
->m_ext
.ext_buf
;
2501 clsp
= slab_get(cl
);
2503 size_t size
= m_maxsize(cl_class
);
2504 mcache_audit_free_verify(mcl_audit_buf2mca(cl_class
,
2505 (mcache_obj_t
*)cl
), cl
, 0, size
);
2507 VERIFY(ms
->m_type
== MT_FREE
);
2508 VERIFY(ms
->m_flags
== M_EXT
);
2509 VERIFY(m_get_rfa(ms
) != NULL
&& MBUF_IS_COMPOSITE(ms
));
2510 if (cl_class
== MC_CL
) {
2511 VERIFY(clsp
->sl_refcnt
>= 1 &&
2512 clsp
->sl_refcnt
<= NCLPG
);
2514 VERIFY(clsp
->sl_refcnt
>= 1 &&
2515 clsp
->sl_refcnt
<= NBCLPG
);
2517 if (cl_class
== MC_16KCL
) {
2519 for (nsp
= clsp
, k
= 1; k
< NSLABSP16KB
; k
++) {
2521 /* Next slab must already be present */
2522 VERIFY(nsp
!= NULL
);
2523 VERIFY(nsp
->sl_refcnt
== 1);
2528 * If we're asked to purge, restore the actual mbuf using
2529 * contents of the shadow structure (if auditing is enabled)
2530 * and clear EXTF_COMPOSITE flag from the mbuf, as we are
2531 * about to free it and the attached cluster into their caches.
2534 /* Restore constructed mbuf fields */
2535 if (mclaudit
!= NULL
) {
2536 mcl_audit_restore_mbuf(m
, mca
, TRUE
);
2544 MEXT_PMBUF(m
) = NULL
;
2547 rfa
= (mcache_obj_t
*)(void *)m_get_rfa(m
);
2548 m_set_ext(m
, NULL
, NULL
, NULL
);
2549 rfa
->obj_next
= ref_list
;
2552 m
->m_type
= MT_FREE
;
2553 m
->m_flags
= m
->m_len
= 0;
2554 m
->m_next
= m
->m_nextpkt
= NULL
;
2556 /* Save mbuf fields and make auditing happy */
2557 if (mclaudit
!= NULL
) {
2558 mcl_audit_mbuf(mca
, o
, FALSE
, FALSE
);
2561 VERIFY(m_total(class) > 0);
2566 slab_free(MC_MBUF
, o
);
2568 /* And free the cluster */
2569 ((mcache_obj_t
*)cl
)->obj_next
= NULL
;
2570 if (class == MC_MBUF_CL
) {
2571 slab_free(MC_CL
, cl
);
2572 } else if (class == MC_MBUF_BIGCL
) {
2573 slab_free(MC_BIGCL
, cl
);
2575 slab_free(MC_16KCL
, cl
);
2585 tail
->obj_next
= m_cobjlist(class);
2586 m_cobjlist(class) = list
;
2587 m_infree(class) += num
;
2588 } else if (ref_list
!= NULL
) {
2589 mcache_free_ext(ref_cache
, ref_list
);
2596 * Common allocator for composite objects called by the CPU cache layer
2597 * during an allocation request whenever there is no available element in
2598 * the bucket layer. It returns one or more composite elements from the
2599 * appropriate global freelist. If the freelist is empty, it will attempt
2600 * to obtain the rudimentary objects from their caches and construct them
2601 * into composite mbuf + cluster objects.
2604 mbuf_cslab_alloc(void *arg
, mcache_obj_t
***plist
, unsigned int needed
,
2607 mbuf_class_t
class = (mbuf_class_t
)arg
;
2608 mbuf_class_t cl_class
= 0;
2609 unsigned int num
= 0, cnum
= 0, want
= needed
;
2610 mcache_obj_t
*ref_list
= NULL
;
2611 mcache_obj_t
*mp_list
= NULL
;
2612 mcache_obj_t
*clp_list
= NULL
;
2613 mcache_obj_t
**list
;
2614 struct ext_ref
*rfa
;
2618 ASSERT(MBUF_CLASS_VALID(class) && MBUF_CLASS_COMPOSITE(class));
2621 VERIFY(class != MC_MBUF_16KCL
|| njcl
> 0);
2623 /* There should not be any slab for this class */
2624 VERIFY(m_slab_cnt(class) == 0 &&
2625 m_slablist(class).tqh_first
== NULL
&&
2626 m_slablist(class).tqh_last
== NULL
);
2628 lck_mtx_lock(mbuf_mlock
);
2630 /* Try using the freelist first */
2631 num
= cslab_alloc(class, plist
, needed
);
2633 if (num
== needed
) {
2634 m_alloc_cnt(class) += num
;
2635 lck_mtx_unlock(mbuf_mlock
);
2639 lck_mtx_unlock(mbuf_mlock
);
2642 * We could not satisfy the request using the freelist alone;
2643 * allocate from the appropriate rudimentary caches and use
2644 * whatever we can get to construct the composite objects.
2649 * Mark these allocation requests as coming from a composite cache.
2650 * Also, if the caller is willing to be blocked, mark the request
2651 * with MCR_FAILOK such that we don't end up sleeping at the mbuf
2652 * slab layer waiting for the individual object when one or more
2653 * of the already-constructed composite objects are available.
2656 if (!(wait
& MCR_NOSLEEP
)) {
2660 /* allocate mbufs */
2661 needed
= mcache_alloc_ext(m_cache(MC_MBUF
), &mp_list
, needed
, wait
);
2663 ASSERT(mp_list
== NULL
);
2667 /* allocate clusters */
2668 if (class == MC_MBUF_CL
) {
2670 } else if (class == MC_MBUF_BIGCL
) {
2671 cl_class
= MC_BIGCL
;
2673 VERIFY(class == MC_MBUF_16KCL
);
2674 cl_class
= MC_16KCL
;
2676 needed
= mcache_alloc_ext(m_cache(cl_class
), &clp_list
, needed
, wait
);
2678 ASSERT(clp_list
== NULL
);
2682 needed
= mcache_alloc_ext(ref_cache
, &ref_list
, needed
, wait
);
2684 ASSERT(ref_list
== NULL
);
2689 * By this time "needed" is MIN(mbuf, cluster, ref). Any left
2690 * overs will get freed accordingly before we return to caller.
2692 for (cnum
= 0; cnum
< needed
; cnum
++) {
2695 m
= ms
= (struct mbuf
*)mp_list
;
2696 mp_list
= mp_list
->obj_next
;
2699 clp_list
= clp_list
->obj_next
;
2700 ((mcache_obj_t
*)cl
)->obj_next
= NULL
;
2702 rfa
= (struct ext_ref
*)ref_list
;
2703 ref_list
= ref_list
->obj_next
;
2704 ((mcache_obj_t
*)(void *)rfa
)->obj_next
= NULL
;
2707 * If auditing is enabled, construct the shadow mbuf
2708 * in the audit structure instead of in the actual one.
2709 * mbuf_cslab_audit() will take care of restoring the
2710 * contents after the integrity check.
2712 if (mclaudit
!= NULL
) {
2713 mcache_audit_t
*mca
, *cl_mca
;
2715 lck_mtx_lock(mbuf_mlock
);
2716 mca
= mcl_audit_buf2mca(MC_MBUF
, (mcache_obj_t
*)m
);
2717 ms
= MCA_SAVED_MBUF_PTR(mca
);
2718 cl_mca
= mcl_audit_buf2mca(cl_class
,
2719 (mcache_obj_t
*)cl
);
2722 * Pair them up. Note that this is done at the time
2723 * the mbuf+cluster objects are constructed. This
2724 * information should be treated as "best effort"
2725 * debugging hint since more than one mbufs can refer
2726 * to a cluster. In that case, the cluster might not
2727 * be freed along with the mbuf it was paired with.
2729 mca
->mca_uptr
= cl_mca
;
2730 cl_mca
->mca_uptr
= mca
;
2732 ASSERT(mca
->mca_uflags
& MB_SCVALID
);
2733 ASSERT(!(cl_mca
->mca_uflags
& MB_SCVALID
));
2734 lck_mtx_unlock(mbuf_mlock
);
2736 /* Technically, they are in the freelist */
2740 mcache_set_pattern(MCACHE_FREE_PATTERN
, m
,
2741 m_maxsize(MC_MBUF
));
2743 if (class == MC_MBUF_CL
) {
2744 size
= m_maxsize(MC_CL
);
2745 } else if (class == MC_MBUF_BIGCL
) {
2746 size
= m_maxsize(MC_BIGCL
);
2748 size
= m_maxsize(MC_16KCL
);
2751 mcache_set_pattern(MCACHE_FREE_PATTERN
, cl
,
2756 MBUF_INIT(ms
, 0, MT_FREE
);
2757 if (class == MC_MBUF_16KCL
) {
2758 MBUF_16KCL_INIT(ms
, cl
, rfa
, 0, EXTF_COMPOSITE
);
2759 } else if (class == MC_MBUF_BIGCL
) {
2760 MBUF_BIGCL_INIT(ms
, cl
, rfa
, 0, EXTF_COMPOSITE
);
2762 MBUF_CL_INIT(ms
, cl
, rfa
, 0, EXTF_COMPOSITE
);
2764 VERIFY(ms
->m_flags
== M_EXT
);
2765 VERIFY(m_get_rfa(ms
) != NULL
&& MBUF_IS_COMPOSITE(ms
));
2767 *list
= (mcache_obj_t
*)m
;
2768 (*list
)->obj_next
= NULL
;
2769 list
= *plist
= &(*list
)->obj_next
;
2774 * Free up what's left of the above.
2776 if (mp_list
!= NULL
) {
2777 mcache_free_ext(m_cache(MC_MBUF
), mp_list
);
2779 if (clp_list
!= NULL
) {
2780 mcache_free_ext(m_cache(cl_class
), clp_list
);
2782 if (ref_list
!= NULL
) {
2783 mcache_free_ext(ref_cache
, ref_list
);
2786 lck_mtx_lock(mbuf_mlock
);
2787 if (num
> 0 || cnum
> 0) {
2788 m_total(class) += cnum
;
2789 VERIFY(m_total(class) <= m_maxlimit(class));
2790 m_alloc_cnt(class) += num
+ cnum
;
2792 if ((num
+ cnum
) < want
) {
2793 m_fail_cnt(class) += (want
- (num
+ cnum
));
2795 lck_mtx_unlock(mbuf_mlock
);
2801 * Common de-allocator for composite objects called by the CPU cache
2802 * layer when one or more elements need to be returned to the appropriate
2806 mbuf_cslab_free(void *arg
, mcache_obj_t
*list
, int purged
)
2808 mbuf_class_t
class = (mbuf_class_t
)arg
;
2812 ASSERT(MBUF_CLASS_VALID(class) && MBUF_CLASS_COMPOSITE(class));
2814 lck_mtx_lock(mbuf_mlock
);
2816 num
= cslab_free(class, list
, purged
);
2817 m_free_cnt(class) += num
;
2819 if ((w
= mb_waiters
) > 0) {
2823 mbwdog_logger("waking up all threads");
2826 lck_mtx_unlock(mbuf_mlock
);
2829 wakeup(mb_waitchan
);
2834 * Common auditor for composite objects called by the CPU cache layer
2835 * during an allocation or free request. For the former, this is called
2836 * after the objects are obtained from either the bucket or slab layer
2837 * and before they are returned to the caller. For the latter, this is
2838 * called immediately during free and before placing the objects into
2839 * the bucket or slab layer.
2842 mbuf_cslab_audit(void *arg
, mcache_obj_t
*list
, boolean_t alloc
)
2844 mbuf_class_t
class = (mbuf_class_t
)arg
, cl_class
;
2845 mcache_audit_t
*mca
;
2846 struct mbuf
*m
, *ms
;
2847 mcl_slab_t
*clsp
, *nsp
;
2851 ASSERT(MBUF_CLASS_VALID(class) && MBUF_CLASS_COMPOSITE(class));
2852 if (class == MC_MBUF_CL
) {
2854 } else if (class == MC_MBUF_BIGCL
) {
2855 cl_class
= MC_BIGCL
;
2857 cl_class
= MC_16KCL
;
2859 cl_size
= m_maxsize(cl_class
);
2861 while ((m
= ms
= (struct mbuf
*)list
) != NULL
) {
2862 lck_mtx_lock(mbuf_mlock
);
2863 /* Do the mbuf sanity checks and record its transaction */
2864 mca
= mcl_audit_buf2mca(MC_MBUF
, (mcache_obj_t
*)m
);
2865 mcl_audit_mbuf(mca
, m
, TRUE
, alloc
);
2867 mcache_buffer_log(mca
, m
, m_cache(class), &mb_start
);
2871 mca
->mca_uflags
|= MB_COMP_INUSE
;
2873 mca
->mca_uflags
&= ~MB_COMP_INUSE
;
2877 * Use the shadow mbuf in the audit structure if we are
2878 * freeing, since the contents of the actual mbuf has been
2879 * pattern-filled by the above call to mcl_audit_mbuf().
2881 if (!alloc
&& mclverify
) {
2882 ms
= MCA_SAVED_MBUF_PTR(mca
);
2885 /* Do the cluster sanity checks and record its transaction */
2886 cl
= ms
->m_ext
.ext_buf
;
2887 clsp
= slab_get(cl
);
2888 VERIFY(ms
->m_flags
== M_EXT
&& cl
!= NULL
);
2889 VERIFY(m_get_rfa(ms
) != NULL
&& MBUF_IS_COMPOSITE(ms
));
2890 if (class == MC_MBUF_CL
) {
2891 VERIFY(clsp
->sl_refcnt
>= 1 &&
2892 clsp
->sl_refcnt
<= NCLPG
);
2894 VERIFY(clsp
->sl_refcnt
>= 1 &&
2895 clsp
->sl_refcnt
<= NBCLPG
);
2898 if (class == MC_MBUF_16KCL
) {
2900 for (nsp
= clsp
, k
= 1; k
< NSLABSP16KB
; k
++) {
2902 /* Next slab must already be present */
2903 VERIFY(nsp
!= NULL
);
2904 VERIFY(nsp
->sl_refcnt
== 1);
2909 mca
= mcl_audit_buf2mca(cl_class
, cl
);
2910 mcl_audit_cluster(mca
, cl
, cl_size
, alloc
, FALSE
);
2912 mcache_buffer_log(mca
, cl
, m_cache(class), &mb_start
);
2916 mca
->mca_uflags
|= MB_COMP_INUSE
;
2918 mca
->mca_uflags
&= ~MB_COMP_INUSE
;
2920 lck_mtx_unlock(mbuf_mlock
);
2922 list
= list
->obj_next
;
2927 m_vm_error_stats(uint32_t *cnt
, uint64_t *ts
, uint64_t *size
,
2928 uint64_t alloc_size
, kern_return_t error
)
2935 _CASSERT(sizeof(mb_kmem_stats
) / sizeof(mb_kmem_stats
[0]) ==
2936 sizeof(mb_kmem_stats_labels
) / sizeof(mb_kmem_stats_labels
[0]));
2940 case KERN_INVALID_ARGUMENT
:
2943 case KERN_INVALID_ADDRESS
:
2946 case KERN_RESOURCE_SHORTAGE
:
2962 * Allocate some number of mbuf clusters and place on cluster freelist.
2965 m_clalloc(const u_int32_t num
, const int wait
, const u_int32_t bufsize
)
2969 int numpages
= 0, large_buffer
;
2970 vm_offset_t page
= 0;
2971 mcache_audit_t
*mca_list
= NULL
;
2972 mcache_obj_t
*con_list
= NULL
;
2975 kern_return_t error
;
2977 /* Set if a buffer allocation needs allocation of multiple pages */
2978 large_buffer
= ((bufsize
== m_maxsize(MC_16KCL
)) &&
2979 PAGE_SIZE
< M16KCLBYTES
);
2980 VERIFY(bufsize
== m_maxsize(MC_BIGCL
) ||
2981 bufsize
== m_maxsize(MC_16KCL
));
2983 VERIFY((bufsize
== PAGE_SIZE
) ||
2984 (bufsize
> PAGE_SIZE
&& bufsize
== m_maxsize(MC_16KCL
)));
2986 if (bufsize
== m_size(MC_BIGCL
)) {
2992 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_OWNED
);
2995 * Multiple threads may attempt to populate the cluster map one
2996 * after another. Since we drop the lock below prior to acquiring
2997 * the physical page(s), our view of the cluster map may no longer
2998 * be accurate, and we could end up over-committing the pages beyond
2999 * the maximum allowed for each class. To prevent it, this entire
3000 * operation (including the page mapping) is serialized.
3002 while (mb_clalloc_busy
) {
3003 mb_clalloc_waiters
++;
3004 (void) msleep(mb_clalloc_waitchan
, mbuf_mlock
,
3005 (PZERO
- 1), "m_clalloc", NULL
);
3006 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_OWNED
);
3009 /* We are busy now; tell everyone else to go away */
3010 mb_clalloc_busy
= TRUE
;
3013 * Honor the caller's wish to block or not block. We have a way
3014 * to grow the pool asynchronously using the mbuf worker thread.
3016 i
= m_howmany(num
, bufsize
);
3017 if (i
<= 0 || (wait
& M_DONTWAIT
)) {
3021 lck_mtx_unlock(mbuf_mlock
);
3023 size
= round_page(i
* bufsize
);
3024 page
= kmem_mb_alloc(mb_map
, size
, large_buffer
, &error
);
3027 * If we did ask for "n" 16KB physically contiguous chunks
3028 * and didn't get them, then please try again without this
3031 net_update_uptime();
3032 if (large_buffer
&& page
== 0) {
3033 m_vm_error_stats(&mb_kmem_contig_failed
,
3034 &mb_kmem_contig_failed_ts
,
3035 &mb_kmem_contig_failed_size
,
3037 page
= kmem_mb_alloc(mb_map
, size
, 0, &error
);
3041 m_vm_error_stats(&mb_kmem_failed
,
3043 &mb_kmem_failed_size
,
3045 #if PAGE_SIZE == 4096
3046 if (bufsize
== m_maxsize(MC_BIGCL
)) {
3048 if (bufsize
>= m_maxsize(MC_BIGCL
)) {
3050 /* Try for 1 page if failed */
3052 page
= kmem_mb_alloc(mb_map
, size
, 0, &error
);
3054 m_vm_error_stats(&mb_kmem_one_failed
,
3055 &mb_kmem_one_failed_ts
,
3061 lck_mtx_lock(mbuf_mlock
);
3066 VERIFY(IS_P2ALIGNED(page
, PAGE_SIZE
));
3067 numpages
= size
/ PAGE_SIZE
;
3069 /* If auditing is enabled, allocate the audit structures now */
3070 if (mclaudit
!= NULL
) {
3074 * Yes, I realize this is a waste of memory for clusters
3075 * that never get transformed into mbufs, as we may end
3076 * up with NMBPG-1 unused audit structures per cluster.
3077 * But doing so tremendously simplifies the allocation
3078 * strategy, since at this point we are not holding the
3079 * mbuf lock and the caller is okay to be blocked.
3081 if (bufsize
== PAGE_SIZE
) {
3082 needed
= numpages
* NMBPG
;
3084 i
= mcache_alloc_ext(mcl_audit_con_cache
,
3085 &con_list
, needed
, MCR_SLEEP
);
3087 VERIFY(con_list
!= NULL
&& i
== needed
);
3090 * if multiple 4K pages are being used for a
3093 needed
= numpages
/ NSLABSP16KB
;
3096 i
= mcache_alloc_ext(mcache_audit_cache
,
3097 (mcache_obj_t
**)&mca_list
, needed
, MCR_SLEEP
);
3099 VERIFY(mca_list
!= NULL
&& i
== needed
);
3102 lck_mtx_lock(mbuf_mlock
);
3104 for (i
= 0; i
< numpages
; i
++, page
+= PAGE_SIZE
) {
3106 ((unsigned char *)page
- mbutl
) >> PAGE_SHIFT
;
3107 ppnum_t new_page
= pmap_find_phys(kernel_pmap
, page
);
3110 * If there is a mapper the appropriate I/O page is
3111 * returned; zero out the page to discard its past
3112 * contents to prevent exposing leftover kernel memory.
3114 VERIFY(offset
< mcl_pages
);
3115 if (mcl_paddr_base
!= 0) {
3116 bzero((void *)(uintptr_t) page
, PAGE_SIZE
);
3117 new_page
= IOMapperInsertPage(mcl_paddr_base
,
3120 mcl_paddr
[offset
] = new_page
;
3122 /* Pattern-fill this fresh page */
3124 mcache_set_pattern(MCACHE_FREE_PATTERN
,
3125 (caddr_t
)page
, PAGE_SIZE
);
3127 if (bufsize
== PAGE_SIZE
) {
3129 /* One for the entire page */
3130 sp
= slab_get((void *)page
);
3131 if (mclaudit
!= NULL
) {
3132 mcl_audit_init((void *)page
,
3133 &mca_list
, &con_list
,
3134 AUDIT_CONTENTS_SIZE
, NMBPG
);
3136 VERIFY(sp
->sl_refcnt
== 0 && sp
->sl_flags
== 0);
3137 slab_init(sp
, class, SLF_MAPPED
, (void *)page
,
3138 (void *)page
, PAGE_SIZE
, 0, 1);
3139 buf
= (mcache_obj_t
*)page
;
3140 buf
->obj_next
= NULL
;
3142 /* Insert this slab */
3143 slab_insert(sp
, class);
3145 /* Update stats now since slab_get drops the lock */
3148 VERIFY(m_total(class) <= m_maxlimit(class));
3149 if (class == MC_BIGCL
) {
3150 mbstat
.m_bigclfree
= m_infree(MC_BIGCL
) +
3151 m_infree(MC_MBUF_BIGCL
);
3152 mbstat
.m_bigclusters
= m_total(MC_BIGCL
);
3155 } else if ((bufsize
> PAGE_SIZE
) &&
3156 (i
% NSLABSP16KB
) == 0) {
3157 union m16kcluster
*m16kcl
= (union m16kcluster
*)page
;
3161 /* One for the entire 16KB */
3162 sp
= slab_get(m16kcl
);
3163 if (mclaudit
!= NULL
) {
3164 mcl_audit_init(m16kcl
, &mca_list
, NULL
, 0, 1);
3167 VERIFY(sp
->sl_refcnt
== 0 && sp
->sl_flags
== 0);
3168 slab_init(sp
, MC_16KCL
, SLF_MAPPED
,
3169 m16kcl
, m16kcl
, bufsize
, 0, 1);
3170 m16kcl
->m16kcl_next
= NULL
;
3173 * 2nd-Nth page's slab is part of the first one,
3174 * where N is NSLABSP16KB.
3176 for (k
= 1; k
< NSLABSP16KB
; k
++) {
3177 nsp
= slab_get(((union mbigcluster
*)page
) + k
);
3178 VERIFY(nsp
->sl_refcnt
== 0 &&
3179 nsp
->sl_flags
== 0);
3180 slab_init(nsp
, MC_16KCL
,
3181 SLF_MAPPED
| SLF_PARTIAL
,
3182 m16kcl
, NULL
, 0, 0, 0);
3184 /* Insert this slab */
3185 slab_insert(sp
, MC_16KCL
);
3187 /* Update stats now since slab_get drops the lock */
3188 ++m_infree(MC_16KCL
);
3189 ++m_total(MC_16KCL
);
3190 VERIFY(m_total(MC_16KCL
) <= m_maxlimit(MC_16KCL
));
3194 VERIFY(mca_list
== NULL
&& con_list
== NULL
);
3196 if (!mb_peak_newreport
&& mbuf_report_usage(class)) {
3197 mb_peak_newreport
= TRUE
;
3200 /* We're done; let others enter */
3201 mb_clalloc_busy
= FALSE
;
3202 if (mb_clalloc_waiters
> 0) {
3203 mb_clalloc_waiters
= 0;
3204 wakeup(mb_clalloc_waitchan
);
3209 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_OWNED
);
3211 mtracelarge_register(size
);
3213 /* We're done; let others enter */
3214 mb_clalloc_busy
= FALSE
;
3215 if (mb_clalloc_waiters
> 0) {
3216 mb_clalloc_waiters
= 0;
3217 wakeup(mb_clalloc_waitchan
);
3221 * When non-blocking we kick a thread if we have to grow the
3222 * pool or if the number of free clusters is less than requested.
3224 if (i
> 0 && mbuf_worker_ready
&& mbuf_worker_needs_wakeup
) {
3225 mbwdog_logger("waking up the worker thread to to grow %s by %d",
3227 wakeup((caddr_t
)&mbuf_worker_needs_wakeup
);
3228 mbuf_worker_needs_wakeup
= FALSE
;
3230 if (class == MC_BIGCL
) {
3233 * Remember total number of 4KB clusters needed
3236 i
+= m_total(MC_BIGCL
);
3237 if (i
> m_region_expand(MC_BIGCL
)) {
3238 m_region_expand(MC_BIGCL
) = i
;
3241 if (m_infree(MC_BIGCL
) >= num
) {
3247 * Remember total number of 16KB clusters needed
3250 i
+= m_total(MC_16KCL
);
3251 if (i
> m_region_expand(MC_16KCL
)) {
3252 m_region_expand(MC_16KCL
) = i
;
3255 if (m_infree(MC_16KCL
) >= num
) {
3263 * Populate the global freelist of the corresponding buffer class.
3266 freelist_populate(mbuf_class_t
class, unsigned int num
, int wait
)
3268 mcache_obj_t
*o
= NULL
;
3269 int i
, numpages
= 0, count
;
3270 mbuf_class_t super_class
;
3272 VERIFY(class == MC_MBUF
|| class == MC_CL
|| class == MC_BIGCL
||
3275 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_OWNED
);
3277 VERIFY(PAGE_SIZE
== m_maxsize(MC_BIGCL
) ||
3278 PAGE_SIZE
== m_maxsize(MC_16KCL
));
3280 if (m_maxsize(class) >= PAGE_SIZE
) {
3281 return m_clalloc(num
, wait
, m_maxsize(class)) != 0;
3285 * The rest of the function will allocate pages and will slice
3286 * them up into the right size
3289 numpages
= (num
* m_size(class) + PAGE_SIZE
- 1) / PAGE_SIZE
;
3291 /* Currently assume that pages are 4K or 16K */
3292 if (PAGE_SIZE
== m_maxsize(MC_BIGCL
)) {
3293 super_class
= MC_BIGCL
;
3295 super_class
= MC_16KCL
;
3298 i
= m_clalloc(numpages
, wait
, m_maxsize(super_class
));
3300 /* how many objects will we cut the page into? */
3301 int numobj
= PAGE_SIZE
/ m_maxsize(class);
3303 for (count
= 0; count
< numpages
; count
++) {
3304 /* respect totals, minlimit, maxlimit */
3305 if (m_total(super_class
) <= m_minlimit(super_class
) ||
3306 m_total(class) >= m_maxlimit(class)) {
3310 if ((o
= slab_alloc(super_class
, wait
)) == NULL
) {
3314 struct mbuf
*m
= (struct mbuf
*)o
;
3315 union mcluster
*c
= (union mcluster
*)o
;
3316 union mbigcluster
*mbc
= (union mbigcluster
*)o
;
3317 mcl_slab_t
*sp
= slab_get(o
);
3318 mcache_audit_t
*mca
= NULL
;
3321 * since one full page will be converted to MC_MBUF or
3322 * MC_CL, verify that the reference count will match that
3325 VERIFY(sp
->sl_refcnt
== 1 && slab_is_detached(sp
));
3326 VERIFY((sp
->sl_flags
& (SLF_MAPPED
| SLF_PARTIAL
)) == SLF_MAPPED
);
3328 * Make sure that the cluster is unmolested
3332 mca
= mcl_audit_buf2mca(super_class
,
3334 mcache_audit_free_verify(mca
,
3335 (mcache_obj_t
*)o
, 0, m_maxsize(super_class
));
3338 /* Reinitialize it as an mbuf or 2K or 4K slab */
3339 slab_init(sp
, class, sp
->sl_flags
,
3340 sp
->sl_base
, NULL
, PAGE_SIZE
, 0, numobj
);
3342 VERIFY(sp
->sl_head
== NULL
);
3344 VERIFY(m_total(super_class
) >= 1);
3345 m_total(super_class
)--;
3347 if (super_class
== MC_BIGCL
) {
3348 mbstat
.m_bigclusters
= m_total(MC_BIGCL
);
3351 m_total(class) += numobj
;
3352 VERIFY(m_total(class) <= m_maxlimit(class));
3353 m_infree(class) += numobj
;
3355 if (!mb_peak_newreport
&& mbuf_report_usage(class)) {
3356 mb_peak_newreport
= TRUE
;
3360 if (class == MC_MBUF
) {
3361 mbstat
.m_mbufs
= m_total(MC_MBUF
);
3362 mtype_stat_add(MT_FREE
, NMBPG
);
3365 * If auditing is enabled, construct the
3366 * shadow mbuf in the audit structure
3367 * instead of the actual one.
3368 * mbuf_slab_audit() will take care of
3369 * restoring the contents after the
3372 if (mclaudit
!= NULL
) {
3374 mca
= mcl_audit_buf2mca(MC_MBUF
,
3376 ms
= MCA_SAVED_MBUF_PTR(mca
);
3377 ms
->m_type
= MT_FREE
;
3379 m
->m_type
= MT_FREE
;
3381 m
->m_next
= sp
->sl_head
;
3382 sp
->sl_head
= (void *)m
++;
3384 } else if (class == MC_CL
) { /* MC_CL */
3386 m_infree(MC_CL
) + m_infree(MC_MBUF_CL
);
3387 mbstat
.m_clusters
= m_total(MC_CL
);
3389 c
->mcl_next
= sp
->sl_head
;
3390 sp
->sl_head
= (void *)c
++;
3393 VERIFY(class == MC_BIGCL
);
3394 mbstat
.m_bigclusters
= m_total(MC_BIGCL
);
3395 mbstat
.m_bigclfree
= m_infree(MC_BIGCL
) +
3396 m_infree(MC_MBUF_BIGCL
);
3398 mbc
->mbc_next
= sp
->sl_head
;
3399 sp
->sl_head
= (void *)mbc
++;
3403 /* Insert into the mbuf or 2k or 4k slab list */
3404 slab_insert(sp
, class);
3406 if ((i
= mb_waiters
) > 0) {
3410 mbwdog_logger("waking up all threads");
3411 wakeup(mb_waitchan
);
3418 * For each class, initialize the freelist to hold m_minlimit() objects.
3421 freelist_init(mbuf_class_t
class)
3423 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_OWNED
);
3425 VERIFY(class == MC_CL
|| class == MC_BIGCL
);
3426 VERIFY(m_total(class) == 0);
3427 VERIFY(m_minlimit(class) > 0);
3429 while (m_total(class) < m_minlimit(class)) {
3430 (void) freelist_populate(class, m_minlimit(class), M_WAIT
);
3433 VERIFY(m_total(class) >= m_minlimit(class));
3437 * (Inaccurately) check if it might be worth a trip back to the
3438 * mcache layer due the availability of objects there. We'll
3439 * end up back here if there's nothing up there.
3442 mbuf_cached_above(mbuf_class_t
class, int wait
)
3446 if (wait
& MCR_COMP
) {
3447 return !mcache_bkt_isempty(m_cache(MC_MBUF_CL
)) ||
3448 !mcache_bkt_isempty(m_cache(MC_MBUF_BIGCL
));
3453 if (wait
& MCR_COMP
) {
3454 return !mcache_bkt_isempty(m_cache(MC_MBUF_CL
));
3459 if (wait
& MCR_COMP
) {
3460 return !mcache_bkt_isempty(m_cache(MC_MBUF_BIGCL
));
3465 if (wait
& MCR_COMP
) {
3466 return !mcache_bkt_isempty(m_cache(MC_MBUF_16KCL
));
3480 return !mcache_bkt_isempty(m_cache(class));
3484 * If possible, convert constructed objects to raw ones.
3487 mbuf_steal(mbuf_class_t
class, unsigned int num
)
3489 mcache_obj_t
*top
= NULL
;
3490 mcache_obj_t
**list
= &top
;
3491 unsigned int tot
= 0;
3493 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_OWNED
);
3505 /* Get the required number of constructed objects if possible */
3506 if (m_infree(class) > m_minlimit(class)) {
3507 tot
= cslab_alloc(class, &list
,
3508 MIN(num
, m_infree(class)));
3511 /* And destroy them to get back the raw objects */
3513 (void) cslab_free(class, top
, 1);
3526 m_reclaim(mbuf_class_t
class, unsigned int num
, boolean_t comp
)
3530 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_OWNED
);
3532 VERIFY(m_total(MC_CL
) <= m_maxlimit(MC_CL
));
3533 VERIFY(m_total(MC_BIGCL
) <= m_maxlimit(MC_BIGCL
));
3534 VERIFY(m_total(MC_16KCL
) <= m_maxlimit(MC_16KCL
));
3537 * This logic can be made smarter; for now, simply mark
3538 * all other related classes as potential victims.
3542 m_wantpurge(MC_CL
)++;
3543 m_wantpurge(MC_BIGCL
)++;
3544 m_wantpurge(MC_MBUF_CL
)++;
3545 m_wantpurge(MC_MBUF_BIGCL
)++;
3549 m_wantpurge(MC_MBUF
)++;
3550 m_wantpurge(MC_BIGCL
)++;
3551 m_wantpurge(MC_MBUF_BIGCL
)++;
3553 m_wantpurge(MC_MBUF_CL
)++;
3558 m_wantpurge(MC_MBUF
)++;
3559 m_wantpurge(MC_CL
)++;
3560 m_wantpurge(MC_MBUF_CL
)++;
3562 m_wantpurge(MC_MBUF_BIGCL
)++;
3568 m_wantpurge(MC_MBUF_16KCL
)++;
3578 * Run through each marked class and check if we really need to
3579 * purge (and therefore temporarily disable) the per-CPU caches
3580 * layer used by the class. If so, remember the classes since
3581 * we are going to drop the lock below prior to purging.
3583 for (m
= 0; m
< NELEM(mbuf_table
); m
++) {
3584 if (m_wantpurge(m
) > 0) {
3587 * Try hard to steal the required number of objects
3588 * from the freelist of other mbuf classes. Only
3589 * purge and disable the per-CPU caches layer when
3590 * we don't have enough; it's the last resort.
3592 if (!mbuf_steal(m
, num
)) {
3598 lck_mtx_unlock(mbuf_mlock
);
3601 /* signal the domains to drain */
3602 net_drain_domains();
3604 /* Sigh; we have no other choices but to ask mcache to purge */
3605 for (m
= 0; m
< NELEM(mbuf_table
); m
++) {
3606 if ((bmap
& (1 << m
)) &&
3607 mcache_purge_cache(m_cache(m
), TRUE
)) {
3608 lck_mtx_lock(mbuf_mlock
);
3611 lck_mtx_unlock(mbuf_mlock
);
3616 * Request mcache to reap extra elements from all of its caches;
3617 * note that all reaps are serialized and happen only at a fixed
3622 lck_mtx_lock(mbuf_mlock
);
3625 static inline struct mbuf
*
3626 m_get_common(int wait
, short type
, int hdr
)
3629 int mcflags
= MSLEEPF(wait
);
3631 /* Is this due to a non-blocking retry? If so, then try harder */
3632 if (mcflags
& MCR_NOSLEEP
) {
3633 mcflags
|= MCR_TRYHARD
;
3636 m
= mcache_alloc(m_cache(MC_MBUF
), mcflags
);
3638 MBUF_INIT(m
, hdr
, type
);
3639 mtype_stat_inc(type
);
3640 mtype_stat_dec(MT_FREE
);
3642 if (hdr
&& mac_init_mbuf(m
, wait
) != 0) {
3646 #endif /* MAC_NET */
3652 * Space allocation routines; these are also available as macros
3653 * for critical paths.
3655 #define _M_GET(wait, type) m_get_common(wait, type, 0)
3656 #define _M_GETHDR(wait, type) m_get_common(wait, type, 1)
3657 #define _M_RETRY(wait, type) _M_GET(wait, type)
3658 #define _M_RETRYHDR(wait, type) _M_GETHDR(wait, type)
3659 #define _MGET(m, how, type) ((m) = _M_GET(how, type))
3660 #define _MGETHDR(m, how, type) ((m) = _M_GETHDR(how, type))
3663 m_get(int wait
, int type
)
3665 return _M_GET(wait
, type
);
3669 m_gethdr(int wait
, int type
)
3671 return _M_GETHDR(wait
, type
);
3675 m_retry(int wait
, int type
)
3677 return _M_RETRY(wait
, type
);
3681 m_retryhdr(int wait
, int type
)
3683 return _M_RETRYHDR(wait
, type
);
3687 m_getclr(int wait
, int type
)
3691 _MGET(m
, wait
, type
);
3693 bzero(MTOD(m
, caddr_t
), MLEN
);
3699 m_free_paired(struct mbuf
*m
)
3701 VERIFY((m
->m_flags
& M_EXT
) && (MEXT_FLAGS(m
) & EXTF_PAIRED
));
3704 if (MEXT_PMBUF(m
) == m
) {
3705 volatile UInt16
*addr
= (volatile UInt16
*)&MEXT_PREF(m
);
3706 int16_t oprefcnt
, prefcnt
;
3709 * Paired ref count might be negative in case we lose
3710 * against another thread clearing MEXT_PMBUF, in the
3711 * event it occurs after the above memory barrier sync.
3712 * In that case just ignore as things have been unpaired.
3716 prefcnt
= oprefcnt
- 1;
3717 } while (!OSCompareAndSwap16(oprefcnt
, prefcnt
, addr
));
3721 } else if (prefcnt
== 1) {
3722 (*(m_get_ext_free(m
)))(m
->m_ext
.ext_buf
,
3723 m
->m_ext
.ext_size
, m_get_ext_arg(m
));
3725 } else if (prefcnt
== 0) {
3726 VERIFY(MBUF_IS_PAIRED(m
));
3729 * Restore minref to its natural value, so that
3730 * the caller will be able to free the cluster
3736 * Clear MEXT_PMBUF, but leave EXTF_PAIRED intact
3737 * as it is immutable. atomic_set_ptr also causes
3738 * memory barrier sync.
3740 atomic_set_ptr(&MEXT_PMBUF(m
), NULL
);
3742 switch (m
->m_ext
.ext_size
) {
3744 m_set_ext(m
, m_get_rfa(m
), NULL
, NULL
);
3748 m_set_ext(m
, m_get_rfa(m
), m_bigfree
, NULL
);
3752 m_set_ext(m
, m_get_rfa(m
), m_16kfree
, NULL
);
3763 * Tell caller the unpair has occurred, and that the reference
3764 * count on the external cluster held for the paired mbuf should
3771 m_free(struct mbuf
*m
)
3773 struct mbuf
*n
= m
->m_next
;
3775 if (m
->m_type
== MT_FREE
) {
3776 panic("m_free: freeing an already freed mbuf");
3779 if (m
->m_flags
& M_PKTHDR
) {
3780 /* Check for scratch area overflow */
3781 m_redzone_verify(m
);
3782 /* Free the aux data and tags if there is any */
3783 m_tag_delete_chain(m
, NULL
);
3785 m_do_tx_compl_callback(m
, NULL
);
3788 if (m
->m_flags
& M_EXT
) {
3790 u_int32_t composite
;
3791 m_ext_free_func_t m_free_func
;
3793 if (MBUF_IS_PAIRED(m
) && m_free_paired(m
)) {
3797 refcnt
= m_decref(m
);
3798 composite
= (MEXT_FLAGS(m
) & EXTF_COMPOSITE
);
3799 m_free_func
= m_get_ext_free(m
);
3801 if (refcnt
== MEXT_MINREF(m
) && !composite
) {
3802 if (m_free_func
== NULL
) {
3803 mcache_free(m_cache(MC_CL
), m
->m_ext
.ext_buf
);
3804 } else if (m_free_func
== m_bigfree
) {
3805 mcache_free(m_cache(MC_BIGCL
),
3807 } else if (m_free_func
== m_16kfree
) {
3808 mcache_free(m_cache(MC_16KCL
),
3811 (*m_free_func
)(m
->m_ext
.ext_buf
,
3812 m
->m_ext
.ext_size
, m_get_ext_arg(m
));
3814 mcache_free(ref_cache
, m_get_rfa(m
));
3815 m_set_ext(m
, NULL
, NULL
, NULL
);
3816 } else if (refcnt
== MEXT_MINREF(m
) && composite
) {
3817 VERIFY(!(MEXT_FLAGS(m
) & EXTF_PAIRED
));
3818 VERIFY(m
->m_type
!= MT_FREE
);
3820 mtype_stat_dec(m
->m_type
);
3821 mtype_stat_inc(MT_FREE
);
3823 m
->m_type
= MT_FREE
;
3826 m
->m_next
= m
->m_nextpkt
= NULL
;
3828 MEXT_FLAGS(m
) &= ~EXTF_READONLY
;
3830 /* "Free" into the intermediate cache */
3831 if (m_free_func
== NULL
) {
3832 mcache_free(m_cache(MC_MBUF_CL
), m
);
3833 } else if (m_free_func
== m_bigfree
) {
3834 mcache_free(m_cache(MC_MBUF_BIGCL
), m
);
3836 VERIFY(m_free_func
== m_16kfree
);
3837 mcache_free(m_cache(MC_MBUF_16KCL
), m
);
3843 if (m
->m_type
!= MT_FREE
) {
3844 mtype_stat_dec(m
->m_type
);
3845 mtype_stat_inc(MT_FREE
);
3848 m
->m_type
= MT_FREE
;
3849 m
->m_flags
= m
->m_len
= 0;
3850 m
->m_next
= m
->m_nextpkt
= NULL
;
3852 mcache_free(m_cache(MC_MBUF
), m
);
3857 __private_extern__
struct mbuf
*
3858 m_clattach(struct mbuf
*m
, int type
, caddr_t extbuf
,
3859 void (*extfree
)(caddr_t
, u_int
, caddr_t
), u_int extsize
, caddr_t extarg
,
3862 struct ext_ref
*rfa
= NULL
;
3865 * If pairing is requested and an existing mbuf is provided, reject
3866 * it if it's already been paired to another cluster. Otherwise,
3867 * allocate a new one or free any existing below.
3869 if ((m
!= NULL
&& MBUF_IS_PAIRED(m
)) ||
3870 (m
== NULL
&& (m
= _M_GETHDR(wait
, type
)) == NULL
)) {
3874 if (m
->m_flags
& M_EXT
) {
3876 u_int32_t composite
;
3877 m_ext_free_func_t m_free_func
;
3879 refcnt
= m_decref(m
);
3880 composite
= (MEXT_FLAGS(m
) & EXTF_COMPOSITE
);
3881 VERIFY(!(MEXT_FLAGS(m
) & EXTF_PAIRED
) && MEXT_PMBUF(m
) == NULL
);
3882 m_free_func
= m_get_ext_free(m
);
3883 if (refcnt
== MEXT_MINREF(m
) && !composite
) {
3884 if (m_free_func
== NULL
) {
3885 mcache_free(m_cache(MC_CL
), m
->m_ext
.ext_buf
);
3886 } else if (m_free_func
== m_bigfree
) {
3887 mcache_free(m_cache(MC_BIGCL
),
3889 } else if (m_free_func
== m_16kfree
) {
3890 mcache_free(m_cache(MC_16KCL
),
3893 (*m_free_func
)(m
->m_ext
.ext_buf
,
3894 m
->m_ext
.ext_size
, m_get_ext_arg(m
));
3896 /* Re-use the reference structure */
3898 } else if (refcnt
== MEXT_MINREF(m
) && composite
) {
3899 VERIFY(m
->m_type
!= MT_FREE
);
3901 mtype_stat_dec(m
->m_type
);
3902 mtype_stat_inc(MT_FREE
);
3904 m
->m_type
= MT_FREE
;
3907 m
->m_next
= m
->m_nextpkt
= NULL
;
3909 MEXT_FLAGS(m
) &= ~EXTF_READONLY
;
3911 /* "Free" into the intermediate cache */
3912 if (m_free_func
== NULL
) {
3913 mcache_free(m_cache(MC_MBUF_CL
), m
);
3914 } else if (m_free_func
== m_bigfree
) {
3915 mcache_free(m_cache(MC_MBUF_BIGCL
), m
);
3917 VERIFY(m_free_func
== m_16kfree
);
3918 mcache_free(m_cache(MC_MBUF_16KCL
), m
);
3921 * Allocate a new mbuf, since we didn't divorce
3922 * the composite mbuf + cluster pair above.
3924 if ((m
= _M_GETHDR(wait
, type
)) == NULL
) {
3931 (rfa
= mcache_alloc(ref_cache
, MSLEEPF(wait
))) == NULL
) {
3937 MEXT_INIT(m
, extbuf
, extsize
, extfree
, extarg
, rfa
,
3938 0, 1, 0, 0, 0, NULL
);
3940 MEXT_INIT(m
, extbuf
, extsize
, extfree
, (caddr_t
)m
, rfa
,
3941 1, 1, 1, EXTF_PAIRED
, 0, m
);
3948 * Perform `fast' allocation mbuf clusters from a cache of recently-freed
3949 * clusters. (If the cache is empty, new clusters are allocated en-masse.)
3952 m_getcl(int wait
, int type
, int flags
)
3955 int mcflags
= MSLEEPF(wait
);
3956 int hdr
= (flags
& M_PKTHDR
);
3958 /* Is this due to a non-blocking retry? If so, then try harder */
3959 if (mcflags
& MCR_NOSLEEP
) {
3960 mcflags
|= MCR_TRYHARD
;
3963 m
= mcache_alloc(m_cache(MC_MBUF_CL
), mcflags
);
3966 struct ext_ref
*rfa
;
3969 VERIFY(m
->m_type
== MT_FREE
&& m
->m_flags
== M_EXT
);
3970 cl
= m
->m_ext
.ext_buf
;
3973 ASSERT(cl
!= NULL
&& rfa
!= NULL
);
3974 VERIFY(MBUF_IS_COMPOSITE(m
) && m_get_ext_free(m
) == NULL
);
3976 flag
= MEXT_FLAGS(m
);
3978 MBUF_INIT(m
, hdr
, type
);
3979 MBUF_CL_INIT(m
, cl
, rfa
, 1, flag
);
3981 mtype_stat_inc(type
);
3982 mtype_stat_dec(MT_FREE
);
3984 if (hdr
&& mac_init_mbuf(m
, wait
) != 0) {
3988 #endif /* MAC_NET */
3993 /* m_mclget() add an mbuf cluster to a normal mbuf */
3995 m_mclget(struct mbuf
*m
, int wait
)
3997 struct ext_ref
*rfa
;
3999 if ((rfa
= mcache_alloc(ref_cache
, MSLEEPF(wait
))) == NULL
) {
4003 m
->m_ext
.ext_buf
= m_mclalloc(wait
);
4004 if (m
->m_ext
.ext_buf
!= NULL
) {
4005 MBUF_CL_INIT(m
, m
->m_ext
.ext_buf
, rfa
, 1, 0);
4007 mcache_free(ref_cache
, rfa
);
4012 /* Allocate an mbuf cluster */
4014 m_mclalloc(int wait
)
4016 int mcflags
= MSLEEPF(wait
);
4018 /* Is this due to a non-blocking retry? If so, then try harder */
4019 if (mcflags
& MCR_NOSLEEP
) {
4020 mcflags
|= MCR_TRYHARD
;
4023 return mcache_alloc(m_cache(MC_CL
), mcflags
);
4026 /* Free an mbuf cluster */
4028 m_mclfree(caddr_t p
)
4030 mcache_free(m_cache(MC_CL
), p
);
4034 * mcl_hasreference() checks if a cluster of an mbuf is referenced by
4035 * another mbuf; see comments in m_incref() regarding EXTF_READONLY.
4038 m_mclhasreference(struct mbuf
*m
)
4040 if (!(m
->m_flags
& M_EXT
)) {
4044 ASSERT(m_get_rfa(m
) != NULL
);
4046 return (MEXT_FLAGS(m
) & EXTF_READONLY
) ? 1 : 0;
4049 __private_extern__ caddr_t
4050 m_bigalloc(int wait
)
4052 int mcflags
= MSLEEPF(wait
);
4054 /* Is this due to a non-blocking retry? If so, then try harder */
4055 if (mcflags
& MCR_NOSLEEP
) {
4056 mcflags
|= MCR_TRYHARD
;
4059 return mcache_alloc(m_cache(MC_BIGCL
), mcflags
);
4062 __private_extern__
void
4063 m_bigfree(caddr_t p
, __unused u_int size
, __unused caddr_t arg
)
4065 mcache_free(m_cache(MC_BIGCL
), p
);
4068 /* m_mbigget() add an 4KB mbuf cluster to a normal mbuf */
4069 __private_extern__
struct mbuf
*
4070 m_mbigget(struct mbuf
*m
, int wait
)
4072 struct ext_ref
*rfa
;
4074 if ((rfa
= mcache_alloc(ref_cache
, MSLEEPF(wait
))) == NULL
) {
4078 m
->m_ext
.ext_buf
= m_bigalloc(wait
);
4079 if (m
->m_ext
.ext_buf
!= NULL
) {
4080 MBUF_BIGCL_INIT(m
, m
->m_ext
.ext_buf
, rfa
, 1, 0);
4082 mcache_free(ref_cache
, rfa
);
4087 __private_extern__ caddr_t
4088 m_16kalloc(int wait
)
4090 int mcflags
= MSLEEPF(wait
);
4092 /* Is this due to a non-blocking retry? If so, then try harder */
4093 if (mcflags
& MCR_NOSLEEP
) {
4094 mcflags
|= MCR_TRYHARD
;
4097 return mcache_alloc(m_cache(MC_16KCL
), mcflags
);
4100 __private_extern__
void
4101 m_16kfree(caddr_t p
, __unused u_int size
, __unused caddr_t arg
)
4103 mcache_free(m_cache(MC_16KCL
), p
);
4106 /* m_m16kget() add a 16KB mbuf cluster to a normal mbuf */
4107 __private_extern__
struct mbuf
*
4108 m_m16kget(struct mbuf
*m
, int wait
)
4110 struct ext_ref
*rfa
;
4112 if ((rfa
= mcache_alloc(ref_cache
, MSLEEPF(wait
))) == NULL
) {
4116 m
->m_ext
.ext_buf
= m_16kalloc(wait
);
4117 if (m
->m_ext
.ext_buf
!= NULL
) {
4118 MBUF_16KCL_INIT(m
, m
->m_ext
.ext_buf
, rfa
, 1, 0);
4120 mcache_free(ref_cache
, rfa
);
4126 * "Move" mbuf pkthdr from "from" to "to".
4127 * "from" must have M_PKTHDR set, and "to" must be empty.
4130 m_copy_pkthdr(struct mbuf
*to
, struct mbuf
*from
)
4132 VERIFY(from
->m_flags
& M_PKTHDR
);
4134 /* Check for scratch area overflow */
4135 m_redzone_verify(from
);
4137 if (to
->m_flags
& M_PKTHDR
) {
4138 /* Check for scratch area overflow */
4139 m_redzone_verify(to
);
4140 /* We will be taking over the tags of 'to' */
4141 m_tag_delete_chain(to
, NULL
);
4143 to
->m_pkthdr
= from
->m_pkthdr
; /* especially tags */
4144 m_classifier_init(from
, 0); /* purge classifier info */
4145 m_tag_init(from
, 1); /* purge all tags from src */
4146 m_scratch_init(from
); /* clear src scratch area */
4147 to
->m_flags
= (from
->m_flags
& M_COPYFLAGS
) | (to
->m_flags
& M_EXT
);
4148 if ((to
->m_flags
& M_EXT
) == 0) {
4149 to
->m_data
= to
->m_pktdat
;
4151 m_redzone_init(to
); /* setup red zone on dst */
4155 * Duplicate "from"'s mbuf pkthdr in "to".
4156 * "from" must have M_PKTHDR set, and "to" must be empty.
4157 * In particular, this does a deep copy of the packet tags.
4160 m_dup_pkthdr(struct mbuf
*to
, struct mbuf
*from
, int how
)
4162 VERIFY(from
->m_flags
& M_PKTHDR
);
4164 /* Check for scratch area overflow */
4165 m_redzone_verify(from
);
4167 if (to
->m_flags
& M_PKTHDR
) {
4168 /* Check for scratch area overflow */
4169 m_redzone_verify(to
);
4170 /* We will be taking over the tags of 'to' */
4171 m_tag_delete_chain(to
, NULL
);
4173 to
->m_flags
= (from
->m_flags
& M_COPYFLAGS
) | (to
->m_flags
& M_EXT
);
4174 if ((to
->m_flags
& M_EXT
) == 0) {
4175 to
->m_data
= to
->m_pktdat
;
4177 to
->m_pkthdr
= from
->m_pkthdr
;
4178 m_redzone_init(to
); /* setup red zone on dst */
4179 m_tag_init(to
, 0); /* preserve dst static tags */
4180 return m_tag_copy_chain(to
, from
, how
);
4184 m_copy_pftag(struct mbuf
*to
, struct mbuf
*from
)
4186 memcpy(m_pftag(to
), m_pftag(from
), sizeof(struct pf_mtag
));
4188 m_pftag(to
)->pftag_hdr
= NULL
;
4189 m_pftag(to
)->pftag_flags
&= ~(PF_TAG_HDR_INET
| PF_TAG_HDR_INET6
);
4194 m_classifier_init(struct mbuf
*m
, uint32_t pktf_mask
)
4196 VERIFY(m
->m_flags
& M_PKTHDR
);
4198 m
->m_pkthdr
.pkt_proto
= 0;
4199 m
->m_pkthdr
.pkt_flowsrc
= 0;
4200 m
->m_pkthdr
.pkt_flowid
= 0;
4201 m
->m_pkthdr
.pkt_flags
&= pktf_mask
; /* caller-defined mask */
4202 /* preserve service class and interface info for loopback packets */
4203 if (!(m
->m_pkthdr
.pkt_flags
& PKTF_LOOP
)) {
4204 (void) m_set_service_class(m
, MBUF_SC_BE
);
4206 if (!(m
->m_pkthdr
.pkt_flags
& PKTF_IFAINFO
)) {
4207 m
->m_pkthdr
.pkt_ifainfo
= 0;
4210 * Preserve timestamp if requested
4212 if (!(m
->m_pkthdr
.pkt_flags
& PKTF_TS_VALID
)) {
4213 m
->m_pkthdr
.pkt_timestamp
= 0;
4218 m_copy_classifier(struct mbuf
*to
, struct mbuf
*from
)
4220 VERIFY(to
->m_flags
& M_PKTHDR
);
4221 VERIFY(from
->m_flags
& M_PKTHDR
);
4223 to
->m_pkthdr
.pkt_proto
= from
->m_pkthdr
.pkt_proto
;
4224 to
->m_pkthdr
.pkt_flowsrc
= from
->m_pkthdr
.pkt_flowsrc
;
4225 to
->m_pkthdr
.pkt_flowid
= from
->m_pkthdr
.pkt_flowid
;
4226 to
->m_pkthdr
.pkt_flags
= from
->m_pkthdr
.pkt_flags
;
4227 (void) m_set_service_class(to
, from
->m_pkthdr
.pkt_svc
);
4228 to
->m_pkthdr
.pkt_ifainfo
= from
->m_pkthdr
.pkt_ifainfo
;
4232 * Return a list of mbuf hdrs that point to clusters. Try for num_needed;
4233 * if wantall is not set, return whatever number were available. Set up the
4234 * first num_with_pkthdrs with mbuf hdrs configured as packet headers; these
4235 * are chained on the m_nextpkt field. Any packets requested beyond this
4236 * are chained onto the last packet header's m_next field. The size of
4237 * the cluster is controlled by the parameter bufsize.
4239 __private_extern__
struct mbuf
*
4240 m_getpackets_internal(unsigned int *num_needed
, int num_with_pkthdrs
,
4241 int wait
, int wantall
, size_t bufsize
)
4244 struct mbuf
**np
, *top
;
4245 unsigned int pnum
, needed
= *num_needed
;
4246 mcache_obj_t
*mp_list
= NULL
;
4247 int mcflags
= MSLEEPF(wait
);
4249 struct ext_ref
*rfa
;
4253 ASSERT(bufsize
== m_maxsize(MC_CL
) ||
4254 bufsize
== m_maxsize(MC_BIGCL
) ||
4255 bufsize
== m_maxsize(MC_16KCL
));
4258 * Caller must first check for njcl because this
4259 * routine is internal and not exposed/used via KPI.
4261 VERIFY(bufsize
!= m_maxsize(MC_16KCL
) || njcl
> 0);
4268 * The caller doesn't want all the requested buffers; only some.
4269 * Try hard to get what we can, but don't block. This effectively
4270 * overrides MCR_SLEEP, since this thread will not go to sleep
4271 * if we can't get all the buffers.
4273 if (!wantall
|| (mcflags
& MCR_NOSLEEP
)) {
4274 mcflags
|= MCR_TRYHARD
;
4277 /* Allocate the composite mbuf + cluster elements from the cache */
4278 if (bufsize
== m_maxsize(MC_CL
)) {
4279 cp
= m_cache(MC_MBUF_CL
);
4280 } else if (bufsize
== m_maxsize(MC_BIGCL
)) {
4281 cp
= m_cache(MC_MBUF_BIGCL
);
4283 cp
= m_cache(MC_MBUF_16KCL
);
4285 needed
= mcache_alloc_ext(cp
, &mp_list
, needed
, mcflags
);
4287 for (pnum
= 0; pnum
< needed
; pnum
++) {
4288 m
= (struct mbuf
*)mp_list
;
4289 mp_list
= mp_list
->obj_next
;
4291 VERIFY(m
->m_type
== MT_FREE
&& m
->m_flags
== M_EXT
);
4292 cl
= m
->m_ext
.ext_buf
;
4295 ASSERT(cl
!= NULL
&& rfa
!= NULL
);
4296 VERIFY(MBUF_IS_COMPOSITE(m
));
4298 flag
= MEXT_FLAGS(m
);
4300 MBUF_INIT(m
, num_with_pkthdrs
, MT_DATA
);
4301 if (bufsize
== m_maxsize(MC_16KCL
)) {
4302 MBUF_16KCL_INIT(m
, cl
, rfa
, 1, flag
);
4303 } else if (bufsize
== m_maxsize(MC_BIGCL
)) {
4304 MBUF_BIGCL_INIT(m
, cl
, rfa
, 1, flag
);
4306 MBUF_CL_INIT(m
, cl
, rfa
, 1, flag
);
4309 if (num_with_pkthdrs
> 0) {
4312 if (mac_mbuf_label_init(m
, wait
) != 0) {
4316 #endif /* MAC_NET */
4320 if (num_with_pkthdrs
> 0) {
4326 ASSERT(pnum
!= *num_needed
|| mp_list
== NULL
);
4327 if (mp_list
!= NULL
) {
4328 mcache_free_ext(cp
, mp_list
);
4332 mtype_stat_add(MT_DATA
, pnum
);
4333 mtype_stat_sub(MT_FREE
, pnum
);
4336 if (wantall
&& (pnum
!= *num_needed
)) {
4343 if (pnum
> *num_needed
) {
4344 printf("%s: File a radar related to <rdar://10146739>. \
4345 needed = %u, pnum = %u, num_needed = %u \n",
4346 __func__
, needed
, pnum
, *num_needed
);
4354 * Return list of mbuf linked by m_nextpkt. Try for numlist, and if
4355 * wantall is not set, return whatever number were available. The size of
4356 * each mbuf in the list is controlled by the parameter packetlen. Each
4357 * mbuf of the list may have a chain of mbufs linked by m_next. Each mbuf
4358 * in the chain is called a segment. If maxsegments is not null and the
4359 * value pointed to is not null, this specify the maximum number of segments
4360 * for a chain of mbufs. If maxsegments is zero or the value pointed to
4361 * is zero the caller does not have any restriction on the number of segments.
4362 * The actual number of segments of a mbuf chain is return in the value
4363 * pointed to by maxsegments.
4365 __private_extern__
struct mbuf
*
4366 m_allocpacket_internal(unsigned int *numlist
, size_t packetlen
,
4367 unsigned int *maxsegments
, int wait
, int wantall
, size_t wantsize
)
4369 struct mbuf
**np
, *top
, *first
= NULL
;
4370 size_t bufsize
, r_bufsize
;
4371 unsigned int num
= 0;
4372 unsigned int nsegs
= 0;
4373 unsigned int needed
, resid
;
4374 int mcflags
= MSLEEPF(wait
);
4375 mcache_obj_t
*mp_list
= NULL
, *rmp_list
= NULL
;
4376 mcache_t
*cp
= NULL
, *rcp
= NULL
;
4378 if (*numlist
== 0) {
4385 if (wantsize
== 0) {
4386 if (packetlen
<= MINCLSIZE
) {
4387 bufsize
= packetlen
;
4388 } else if (packetlen
> m_maxsize(MC_CL
)) {
4389 /* Use 4KB if jumbo cluster pool isn't available */
4390 if (packetlen
<= m_maxsize(MC_BIGCL
) || njcl
== 0) {
4391 bufsize
= m_maxsize(MC_BIGCL
);
4393 bufsize
= m_maxsize(MC_16KCL
);
4396 bufsize
= m_maxsize(MC_CL
);
4398 } else if (wantsize
== m_maxsize(MC_CL
) ||
4399 wantsize
== m_maxsize(MC_BIGCL
) ||
4400 (wantsize
== m_maxsize(MC_16KCL
) && njcl
> 0)) {
4406 if (bufsize
<= MHLEN
) {
4408 } else if (bufsize
<= MINCLSIZE
) {
4409 if (maxsegments
!= NULL
&& *maxsegments
== 1) {
4410 bufsize
= m_maxsize(MC_CL
);
4415 } else if (bufsize
== m_maxsize(MC_16KCL
)) {
4417 nsegs
= ((packetlen
- 1) >> M16KCLSHIFT
) + 1;
4418 } else if (bufsize
== m_maxsize(MC_BIGCL
)) {
4419 nsegs
= ((packetlen
- 1) >> MBIGCLSHIFT
) + 1;
4421 nsegs
= ((packetlen
- 1) >> MCLSHIFT
) + 1;
4423 if (maxsegments
!= NULL
) {
4424 if (*maxsegments
&& nsegs
> *maxsegments
) {
4425 *maxsegments
= nsegs
;
4428 *maxsegments
= nsegs
;
4432 * The caller doesn't want all the requested buffers; only some.
4433 * Try hard to get what we can, but don't block. This effectively
4434 * overrides MCR_SLEEP, since this thread will not go to sleep
4435 * if we can't get all the buffers.
4437 if (!wantall
|| (mcflags
& MCR_NOSLEEP
)) {
4438 mcflags
|= MCR_TRYHARD
;
4442 * Simple case where all elements in the lists/chains are mbufs.
4443 * Unless bufsize is greater than MHLEN, each segment chain is made
4444 * up of exactly 1 mbuf. Otherwise, each segment chain is made up
4445 * of 2 mbufs; the second one is used for the residual data, i.e.
4446 * the remaining data that cannot fit into the first mbuf.
4448 if (bufsize
<= MINCLSIZE
) {
4449 /* Allocate the elements in one shot from the mbuf cache */
4450 ASSERT(bufsize
<= MHLEN
|| nsegs
== 2);
4451 cp
= m_cache(MC_MBUF
);
4452 needed
= mcache_alloc_ext(cp
, &mp_list
,
4453 (*numlist
) * nsegs
, mcflags
);
4456 * The number of elements must be even if we are to use an
4457 * mbuf (instead of a cluster) to store the residual data.
4458 * If we couldn't allocate the requested number of mbufs,
4459 * trim the number down (if it's odd) in order to avoid
4460 * creating a partial segment chain.
4462 if (bufsize
> MHLEN
&& (needed
& 0x1)) {
4466 while (num
< needed
) {
4469 m
= (struct mbuf
*)mp_list
;
4470 mp_list
= mp_list
->obj_next
;
4473 MBUF_INIT(m
, 1, MT_DATA
);
4475 if (mac_init_mbuf(m
, wait
) != 0) {
4479 #endif /* MAC_NET */
4481 if (bufsize
> MHLEN
) {
4482 /* A second mbuf for this segment chain */
4483 m
->m_next
= (struct mbuf
*)mp_list
;
4484 mp_list
= mp_list
->obj_next
;
4485 ASSERT(m
->m_next
!= NULL
);
4487 MBUF_INIT(m
->m_next
, 0, MT_DATA
);
4493 ASSERT(num
!= *numlist
|| mp_list
== NULL
);
4496 mtype_stat_add(MT_DATA
, num
);
4497 mtype_stat_sub(MT_FREE
, num
);
4501 /* We've got them all; return to caller */
4502 if (num
== *numlist
) {
4510 * Complex cases where elements are made up of one or more composite
4511 * mbufs + cluster, depending on packetlen. Each N-segment chain can
4512 * be illustrated as follows:
4514 * [mbuf + cluster 1] [mbuf + cluster 2] ... [mbuf + cluster N]
4516 * Every composite mbuf + cluster element comes from the intermediate
4517 * cache (either MC_MBUF_CL or MC_MBUF_BIGCL). For space efficiency,
4518 * the last composite element will come from the MC_MBUF_CL cache,
4519 * unless the residual data is larger than 2KB where we use the
4520 * big cluster composite cache (MC_MBUF_BIGCL) instead. Residual
4521 * data is defined as extra data beyond the first element that cannot
4522 * fit into the previous element, i.e. there is no residual data if
4523 * the chain only has 1 segment.
4525 r_bufsize
= bufsize
;
4526 resid
= packetlen
> bufsize
? packetlen
% bufsize
: 0;
4528 /* There is residual data; figure out the cluster size */
4529 if (wantsize
== 0 && packetlen
> MINCLSIZE
) {
4531 * Caller didn't request that all of the segments
4532 * in the chain use the same cluster size; use the
4533 * smaller of the cluster sizes.
4535 if (njcl
> 0 && resid
> m_maxsize(MC_BIGCL
)) {
4536 r_bufsize
= m_maxsize(MC_16KCL
);
4537 } else if (resid
> m_maxsize(MC_CL
)) {
4538 r_bufsize
= m_maxsize(MC_BIGCL
);
4540 r_bufsize
= m_maxsize(MC_CL
);
4543 /* Use the same cluster size as the other segments */
4551 * Attempt to allocate composite mbuf + cluster elements for
4552 * the residual data in each chain; record the number of such
4553 * elements that can be allocated so that we know how many
4554 * segment chains we can afford to create.
4556 if (r_bufsize
<= m_maxsize(MC_CL
)) {
4557 rcp
= m_cache(MC_MBUF_CL
);
4558 } else if (r_bufsize
<= m_maxsize(MC_BIGCL
)) {
4559 rcp
= m_cache(MC_MBUF_BIGCL
);
4561 rcp
= m_cache(MC_MBUF_16KCL
);
4563 needed
= mcache_alloc_ext(rcp
, &rmp_list
, *numlist
, mcflags
);
4569 /* This is temporarily reduced for calculation */
4575 * Attempt to allocate the rest of the composite mbuf + cluster
4576 * elements for the number of segment chains that we need.
4578 if (bufsize
<= m_maxsize(MC_CL
)) {
4579 cp
= m_cache(MC_MBUF_CL
);
4580 } else if (bufsize
<= m_maxsize(MC_BIGCL
)) {
4581 cp
= m_cache(MC_MBUF_BIGCL
);
4583 cp
= m_cache(MC_MBUF_16KCL
);
4585 needed
= mcache_alloc_ext(cp
, &mp_list
, needed
* nsegs
, mcflags
);
4587 /* Round it down to avoid creating a partial segment chain */
4588 needed
= (needed
/ nsegs
) * nsegs
;
4595 * We're about to construct the chain(s); take into account
4596 * the number of segments we have created above to hold the
4597 * residual data for each chain, as well as restore the
4598 * original count of segments per chain.
4601 needed
+= needed
/ nsegs
;
4608 struct ext_ref
*rfa
;
4611 m_ext_free_func_t m_free_func
;
4614 if (nsegs
== 1 || (num
% nsegs
) != 0 || resid
== 0) {
4615 m
= (struct mbuf
*)mp_list
;
4616 mp_list
= mp_list
->obj_next
;
4618 m
= (struct mbuf
*)rmp_list
;
4619 rmp_list
= rmp_list
->obj_next
;
4621 m_free_func
= m_get_ext_free(m
);
4623 VERIFY(m
->m_type
== MT_FREE
&& m
->m_flags
== M_EXT
);
4624 VERIFY(m_free_func
== NULL
|| m_free_func
== m_bigfree
||
4625 m_free_func
== m_16kfree
);
4627 cl
= m
->m_ext
.ext_buf
;
4630 ASSERT(cl
!= NULL
&& rfa
!= NULL
);
4631 VERIFY(MBUF_IS_COMPOSITE(m
));
4633 flag
= MEXT_FLAGS(m
);
4635 pkthdr
= (nsegs
== 1 || (num
% nsegs
) == 1);
4639 MBUF_INIT(m
, pkthdr
, MT_DATA
);
4640 if (m_free_func
== m_16kfree
) {
4641 MBUF_16KCL_INIT(m
, cl
, rfa
, 1, flag
);
4642 } else if (m_free_func
== m_bigfree
) {
4643 MBUF_BIGCL_INIT(m
, cl
, rfa
, 1, flag
);
4645 MBUF_CL_INIT(m
, cl
, rfa
, 1, flag
);
4648 if (pkthdr
&& mac_init_mbuf(m
, wait
) != 0) {
4653 #endif /* MAC_NET */
4656 if ((num
% nsegs
) == 0) {
4657 np
= &first
->m_nextpkt
;
4662 if (num
== needed
) {
4668 mtype_stat_add(MT_DATA
, num
);
4669 mtype_stat_sub(MT_FREE
, num
);
4674 /* We've got them all; return to caller */
4675 if (num
== *numlist
) {
4676 ASSERT(mp_list
== NULL
&& rmp_list
== NULL
);
4681 /* Free up what's left of the above */
4682 if (mp_list
!= NULL
) {
4683 mcache_free_ext(cp
, mp_list
);
4685 if (rmp_list
!= NULL
) {
4686 mcache_free_ext(rcp
, rmp_list
);
4688 if (wantall
&& top
!= NULL
) {
4697 * Best effort to get a mbuf cluster + pkthdr. Used by drivers to allocated
4698 * packets on receive ring.
4700 __private_extern__
struct mbuf
*
4701 m_getpacket_how(int wait
)
4703 unsigned int num_needed
= 1;
4705 return m_getpackets_internal(&num_needed
, 1, wait
, 1,
4710 * Best effort to get a mbuf cluster + pkthdr. Used by drivers to allocated
4711 * packets on receive ring.
4716 unsigned int num_needed
= 1;
4718 return m_getpackets_internal(&num_needed
, 1, M_WAIT
, 1,
4723 * Return a list of mbuf hdrs that point to clusters. Try for num_needed;
4724 * if this can't be met, return whatever number were available. Set up the
4725 * first num_with_pkthdrs with mbuf hdrs configured as packet headers. These
4726 * are chained on the m_nextpkt field. Any packets requested beyond this are
4727 * chained onto the last packet header's m_next field.
4730 m_getpackets(int num_needed
, int num_with_pkthdrs
, int how
)
4732 unsigned int n
= num_needed
;
4734 return m_getpackets_internal(&n
, num_with_pkthdrs
, how
, 0,
4739 * Return a list of mbuf hdrs set up as packet hdrs chained together
4740 * on the m_nextpkt field
4743 m_getpackethdrs(int num_needed
, int how
)
4746 struct mbuf
**np
, *top
;
4751 while (num_needed
--) {
4752 m
= _M_RETRYHDR(how
, MT_DATA
);
4765 * Free an mbuf list (m_nextpkt) while following m_next. Returns the count
4766 * for mbufs packets freed. Used by the drivers.
4769 m_freem_list(struct mbuf
*m
)
4771 struct mbuf
*nextpkt
;
4772 mcache_obj_t
*mp_list
= NULL
;
4773 mcache_obj_t
*mcl_list
= NULL
;
4774 mcache_obj_t
*mbc_list
= NULL
;
4775 mcache_obj_t
*m16k_list
= NULL
;
4776 mcache_obj_t
*m_mcl_list
= NULL
;
4777 mcache_obj_t
*m_mbc_list
= NULL
;
4778 mcache_obj_t
*m_m16k_list
= NULL
;
4779 mcache_obj_t
*ref_list
= NULL
;
4781 int mt_free
= 0, mt_data
= 0, mt_header
= 0, mt_soname
= 0, mt_tag
= 0;
4786 nextpkt
= m
->m_nextpkt
;
4787 m
->m_nextpkt
= NULL
;
4790 struct mbuf
*next
= m
->m_next
;
4791 mcache_obj_t
*o
, *rfa
;
4792 u_int32_t composite
;
4794 m_ext_free_func_t m_free_func
;
4796 if (m
->m_type
== MT_FREE
) {
4797 panic("m_free: freeing an already freed mbuf");
4800 if (m
->m_flags
& M_PKTHDR
) {
4801 /* Check for scratch area overflow */
4802 m_redzone_verify(m
);
4803 /* Free the aux data and tags if there is any */
4804 m_tag_delete_chain(m
, NULL
);
4807 if (!(m
->m_flags
& M_EXT
)) {
4812 if (MBUF_IS_PAIRED(m
) && m_free_paired(m
)) {
4819 o
= (mcache_obj_t
*)(void *)m
->m_ext
.ext_buf
;
4820 refcnt
= m_decref(m
);
4821 composite
= (MEXT_FLAGS(m
) & EXTF_COMPOSITE
);
4822 m_free_func
= m_get_ext_free(m
);
4823 if (refcnt
== MEXT_MINREF(m
) && !composite
) {
4824 if (m_free_func
== NULL
) {
4825 o
->obj_next
= mcl_list
;
4827 } else if (m_free_func
== m_bigfree
) {
4828 o
->obj_next
= mbc_list
;
4830 } else if (m_free_func
== m_16kfree
) {
4831 o
->obj_next
= m16k_list
;
4834 (*(m_free_func
))((caddr_t
)o
,
4838 rfa
= (mcache_obj_t
*)(void *)m_get_rfa(m
);
4839 rfa
->obj_next
= ref_list
;
4841 m_set_ext(m
, NULL
, NULL
, NULL
);
4842 } else if (refcnt
== MEXT_MINREF(m
) && composite
) {
4843 VERIFY(!(MEXT_FLAGS(m
) & EXTF_PAIRED
));
4844 VERIFY(m
->m_type
!= MT_FREE
);
4846 * Amortize the costs of atomic operations
4847 * by doing them at the end, if possible.
4849 if (m
->m_type
== MT_DATA
) {
4851 } else if (m
->m_type
== MT_HEADER
) {
4853 } else if (m
->m_type
== MT_SONAME
) {
4855 } else if (m
->m_type
== MT_TAG
) {
4858 mtype_stat_dec(m
->m_type
);
4861 m
->m_type
= MT_FREE
;
4864 m
->m_next
= m
->m_nextpkt
= NULL
;
4866 MEXT_FLAGS(m
) &= ~EXTF_READONLY
;
4868 /* "Free" into the intermediate cache */
4869 o
= (mcache_obj_t
*)m
;
4870 if (m_free_func
== NULL
) {
4871 o
->obj_next
= m_mcl_list
;
4873 } else if (m_free_func
== m_bigfree
) {
4874 o
->obj_next
= m_mbc_list
;
4877 VERIFY(m_free_func
== m_16kfree
);
4878 o
->obj_next
= m_m16k_list
;
4886 * Amortize the costs of atomic operations
4887 * by doing them at the end, if possible.
4889 if (m
->m_type
== MT_DATA
) {
4891 } else if (m
->m_type
== MT_HEADER
) {
4893 } else if (m
->m_type
== MT_SONAME
) {
4895 } else if (m
->m_type
== MT_TAG
) {
4897 } else if (m
->m_type
!= MT_FREE
) {
4898 mtype_stat_dec(m
->m_type
);
4901 m
->m_type
= MT_FREE
;
4902 m
->m_flags
= m
->m_len
= 0;
4903 m
->m_next
= m
->m_nextpkt
= NULL
;
4905 ((mcache_obj_t
*)m
)->obj_next
= mp_list
;
4906 mp_list
= (mcache_obj_t
*)m
;
4915 mtype_stat_add(MT_FREE
, mt_free
);
4918 mtype_stat_sub(MT_DATA
, mt_data
);
4920 if (mt_header
> 0) {
4921 mtype_stat_sub(MT_HEADER
, mt_header
);
4923 if (mt_soname
> 0) {
4924 mtype_stat_sub(MT_SONAME
, mt_soname
);
4927 mtype_stat_sub(MT_TAG
, mt_tag
);
4930 if (mp_list
!= NULL
) {
4931 mcache_free_ext(m_cache(MC_MBUF
), mp_list
);
4933 if (mcl_list
!= NULL
) {
4934 mcache_free_ext(m_cache(MC_CL
), mcl_list
);
4936 if (mbc_list
!= NULL
) {
4937 mcache_free_ext(m_cache(MC_BIGCL
), mbc_list
);
4939 if (m16k_list
!= NULL
) {
4940 mcache_free_ext(m_cache(MC_16KCL
), m16k_list
);
4942 if (m_mcl_list
!= NULL
) {
4943 mcache_free_ext(m_cache(MC_MBUF_CL
), m_mcl_list
);
4945 if (m_mbc_list
!= NULL
) {
4946 mcache_free_ext(m_cache(MC_MBUF_BIGCL
), m_mbc_list
);
4948 if (m_m16k_list
!= NULL
) {
4949 mcache_free_ext(m_cache(MC_MBUF_16KCL
), m_m16k_list
);
4951 if (ref_list
!= NULL
) {
4952 mcache_free_ext(ref_cache
, ref_list
);
4959 m_freem(struct mbuf
*m
)
4967 * Mbuffer utility routines.
4970 * Set the m_data pointer of a newly allocated mbuf to place an object of the
4971 * specified size at the end of the mbuf, longword aligned.
4973 * NB: Historically, we had M_ALIGN(), MH_ALIGN(), and MEXT_ALIGN() as
4974 * separate macros, each asserting that it was called at the proper moment.
4975 * This required callers to themselves test the storage type and call the
4976 * right one. Rather than require callers to be aware of those layout
4977 * decisions, we centralize here.
4980 m_align(struct mbuf
*m
, int len
)
4984 /* At this point data must point to start */
4985 VERIFY(m
->m_data
== M_START(m
));
4987 VERIFY(len
<= M_SIZE(m
));
4988 adjust
= M_SIZE(m
) - len
;
4989 m
->m_data
+= adjust
& ~(sizeof(long) - 1);
4993 * Lesser-used path for M_PREPEND: allocate new mbuf to prepend to chain,
4994 * copy junk along. Does not adjust packet header length.
4997 m_prepend(struct mbuf
*m
, int len
, int how
)
5001 _MGET(mn
, how
, m
->m_type
);
5006 if (m
->m_flags
& M_PKTHDR
) {
5007 M_COPY_PKTHDR(mn
, m
);
5008 m
->m_flags
&= ~M_PKTHDR
;
5012 if (m
->m_flags
& M_PKTHDR
) {
5013 VERIFY(len
<= MHLEN
);
5016 VERIFY(len
<= MLEN
);
5024 * Replacement for old M_PREPEND macro: allocate new mbuf to prepend to
5025 * chain, copy junk along, and adjust length.
5028 m_prepend_2(struct mbuf
*m
, int len
, int how
, int align
)
5030 if (M_LEADINGSPACE(m
) >= len
&&
5031 (!align
|| IS_P2ALIGNED((m
->m_data
- len
), sizeof(u_int32_t
)))) {
5035 m
= m_prepend(m
, len
, how
);
5037 if ((m
) && (m
->m_flags
& M_PKTHDR
)) {
5038 m
->m_pkthdr
.len
+= len
;
5044 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
5045 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
5046 * The wait parameter is a choice of M_WAIT/M_DONTWAIT from caller.
5051 m_copym_mode(struct mbuf
*m
, int off0
, int len
, int wait
, uint32_t mode
)
5053 struct mbuf
*n
, *mhdr
= NULL
, **np
;
5058 if (off
< 0 || len
< 0) {
5059 panic("m_copym: invalid offset %d or len %d", off
, len
);
5062 VERIFY((mode
!= M_COPYM_MUST_COPY_HDR
&&
5063 mode
!= M_COPYM_MUST_MOVE_HDR
) || (m
->m_flags
& M_PKTHDR
));
5065 if ((off
== 0 && (m
->m_flags
& M_PKTHDR
)) ||
5066 mode
== M_COPYM_MUST_COPY_HDR
|| mode
== M_COPYM_MUST_MOVE_HDR
) {
5071 while (off
>= m
->m_len
) {
5072 if (m
->m_next
== NULL
) {
5073 panic("m_copym: invalid mbuf chain");
5083 if (len
!= M_COPYALL
) {
5084 panic("m_copym: len != M_COPYALL");
5090 n
= _M_RETRYHDR(wait
, m
->m_type
);
5092 n
= _M_RETRY(wait
, m
->m_type
);
5101 if ((mode
== M_COPYM_MOVE_HDR
) ||
5102 (mode
== M_COPYM_MUST_MOVE_HDR
)) {
5103 M_COPY_PKTHDR(n
, mhdr
);
5104 } else if ((mode
== M_COPYM_COPY_HDR
) ||
5105 (mode
== M_COPYM_MUST_COPY_HDR
)) {
5106 if (m_dup_pkthdr(n
, mhdr
, wait
) == 0) {
5110 if (len
== M_COPYALL
) {
5111 n
->m_pkthdr
.len
-= off0
;
5113 n
->m_pkthdr
.len
= len
;
5117 * There is data to copy from the packet header mbuf
5118 * if it is empty or it is before the starting offset
5125 n
->m_len
= MIN(len
, (m
->m_len
- off
));
5126 if (m
->m_flags
& M_EXT
) {
5127 n
->m_ext
= m
->m_ext
;
5129 n
->m_data
= m
->m_data
+ off
;
5130 n
->m_flags
|= M_EXT
;
5133 * Limit to the capacity of the destination
5135 if (n
->m_flags
& M_PKTHDR
) {
5136 n
->m_len
= MIN(n
->m_len
, MHLEN
);
5138 n
->m_len
= MIN(n
->m_len
, MLEN
);
5141 if (MTOD(n
, char *) + n
->m_len
> ((char *)n
) + MSIZE
) {
5142 panic("%s n %p copy overflow",
5146 bcopy(MTOD(m
, caddr_t
) + off
, MTOD(n
, caddr_t
),
5147 (unsigned)n
->m_len
);
5149 if (len
!= M_COPYALL
) {
5171 m_copym(struct mbuf
*m
, int off0
, int len
, int wait
)
5173 return m_copym_mode(m
, off0
, len
, wait
, M_COPYM_MOVE_HDR
);
5177 * Equivalent to m_copym except that all necessary mbuf hdrs are allocated
5178 * within this routine also, the last mbuf and offset accessed are passed
5179 * out and can be passed back in to avoid having to rescan the entire mbuf
5180 * list (normally hung off of the socket)
5183 m_copym_with_hdrs(struct mbuf
*m0
, int off0
, int len0
, int wait
,
5184 struct mbuf
**m_lastm
, int *m_off
, uint32_t mode
)
5186 struct mbuf
*m
= m0
, *n
, **np
= NULL
;
5187 int off
= off0
, len
= len0
;
5188 struct mbuf
*top
= NULL
;
5189 int mcflags
= MSLEEPF(wait
);
5192 mcache_obj_t
*list
= NULL
;
5195 if (off
== 0 && (m
->m_flags
& M_PKTHDR
)) {
5199 if (m_lastm
!= NULL
&& *m_lastm
!= NULL
) {
5203 while (off
>= m
->m_len
) {
5213 len
-= MIN(len
, (n
->m_len
- ((needed
== 1) ? off
: 0)));
5220 * If the caller doesn't want to be put to sleep, mark it with
5221 * MCR_TRYHARD so that we may reclaim buffers from other places
5224 if (mcflags
& MCR_NOSLEEP
) {
5225 mcflags
|= MCR_TRYHARD
;
5228 if (mcache_alloc_ext(m_cache(MC_MBUF
), &list
, needed
,
5229 mcflags
) != needed
) {
5235 n
= (struct mbuf
*)list
;
5236 list
= list
->obj_next
;
5237 ASSERT(n
!= NULL
&& m
!= NULL
);
5239 type
= (top
== NULL
) ? MT_HEADER
: m
->m_type
;
5240 MBUF_INIT(n
, (top
== NULL
), type
);
5242 if (top
== NULL
&& mac_mbuf_label_init(n
, wait
) != 0) {
5243 mtype_stat_inc(MT_HEADER
);
5244 mtype_stat_dec(MT_FREE
);
5248 #endif /* MAC_NET */
5260 if ((mode
== M_COPYM_MOVE_HDR
) ||
5261 (mode
== M_COPYM_MUST_MOVE_HDR
)) {
5262 M_COPY_PKTHDR(n
, m
);
5263 } else if ((mode
== M_COPYM_COPY_HDR
) ||
5264 (mode
== M_COPYM_MUST_COPY_HDR
)) {
5265 if (m_dup_pkthdr(n
, m
, wait
) == 0) {
5269 n
->m_pkthdr
.len
= len
;
5272 n
->m_len
= MIN(len
, (m
->m_len
- off
));
5274 if (m
->m_flags
& M_EXT
) {
5275 n
->m_ext
= m
->m_ext
;
5277 n
->m_data
= m
->m_data
+ off
;
5278 n
->m_flags
|= M_EXT
;
5280 if (MTOD(n
, char *) + n
->m_len
> ((char *)n
) + MSIZE
) {
5281 panic("%s n %p copy overflow",
5285 bcopy(MTOD(m
, caddr_t
) + off
, MTOD(n
, caddr_t
),
5286 (unsigned)n
->m_len
);
5291 if (m_lastm
!= NULL
&& m_off
!= NULL
) {
5292 if ((off
+ n
->m_len
) == m
->m_len
) {
5293 *m_lastm
= m
->m_next
;
5297 *m_off
= off
+ n
->m_len
;
5307 mtype_stat_inc(MT_HEADER
);
5308 mtype_stat_add(type
, needed
);
5309 mtype_stat_sub(MT_FREE
, needed
+ 1);
5311 ASSERT(list
== NULL
);
5316 mcache_free_ext(m_cache(MC_MBUF
), list
);
5326 * Copy data from an mbuf chain starting "off" bytes from the beginning,
5327 * continuing for "len" bytes, into the indicated buffer.
5330 m_copydata(struct mbuf
*m
, int off
, int len
, void *vp
)
5332 int off0
= off
, len0
= len
;
5333 struct mbuf
*m0
= m
;
5337 if (__improbable(off
< 0 || len
< 0)) {
5338 panic("%s: invalid offset %d or len %d", __func__
, off
, len
);
5343 if (__improbable(m
== NULL
)) {
5344 panic("%s: invalid mbuf chain %p [off %d, len %d]",
5345 __func__
, m0
, off0
, len0
);
5348 if (off
< m
->m_len
) {
5355 if (__improbable(m
== NULL
)) {
5356 panic("%s: invalid mbuf chain %p [off %d, len %d]",
5357 __func__
, m0
, off0
, len0
);
5360 count
= MIN(m
->m_len
- off
, len
);
5361 bcopy(MTOD(m
, caddr_t
) + off
, cp
, count
);
5370 * Concatenate mbuf chain n to m. Both chains must be of the same type
5371 * (e.g. MT_DATA). Any m_pkthdr is not updated.
5374 m_cat(struct mbuf
*m
, struct mbuf
*n
)
5380 if ((m
->m_flags
& M_EXT
) ||
5381 m
->m_data
+ m
->m_len
+ n
->m_len
>= &m
->m_dat
[MLEN
]) {
5382 /* just join the two chains */
5386 /* splat the data from one into the other */
5387 bcopy(MTOD(n
, caddr_t
), MTOD(m
, caddr_t
) + m
->m_len
,
5389 m
->m_len
+= n
->m_len
;
5395 m_adj(struct mbuf
*mp
, int req_len
)
5401 if ((m
= mp
) == NULL
) {
5408 while (m
!= NULL
&& len
> 0) {
5409 if (m
->m_len
<= len
) {
5420 if (m
->m_flags
& M_PKTHDR
) {
5421 m
->m_pkthdr
.len
-= (req_len
- len
);
5425 * Trim from tail. Scan the mbuf chain,
5426 * calculating its length and finding the last mbuf.
5427 * If the adjustment only affects this mbuf, then just
5428 * adjust and return. Otherwise, rescan and truncate
5429 * after the remaining size.
5435 if (m
->m_next
== (struct mbuf
*)0) {
5440 if (m
->m_len
>= len
) {
5443 if (m
->m_flags
& M_PKTHDR
) {
5444 m
->m_pkthdr
.len
-= len
;
5453 * Correct length for chain is "count".
5454 * Find the mbuf with last data, adjust its length,
5455 * and toss data from remaining mbufs on chain.
5458 if (m
->m_flags
& M_PKTHDR
) {
5459 m
->m_pkthdr
.len
= count
;
5461 for (; m
; m
= m
->m_next
) {
5462 if (m
->m_len
>= count
) {
5468 while ((m
= m
->m_next
)) {
5475 * Rearange an mbuf chain so that len bytes are contiguous
5476 * and in the data area of an mbuf (so that mtod and dtom
5477 * will work for a structure of size len). Returns the resulting
5478 * mbuf chain on success, frees it and returns null on failure.
5479 * If there is room, it will add up to max_protohdr-len extra bytes to the
5480 * contiguous region in an attempt to avoid being called next time.
5485 m_pullup(struct mbuf
*n
, int len
)
5491 /* check invalid arguments */
5493 panic("%s: n == NULL", __func__
);
5496 os_log_info(OS_LOG_DEFAULT
, "%s: failed negative len %d",
5501 os_log_info(OS_LOG_DEFAULT
, "%s: failed len %d too big",
5505 if ((n
->m_flags
& M_EXT
) == 0 &&
5506 n
->m_data
>= &n
->m_dat
[MLEN
]) {
5507 os_log_info(OS_LOG_DEFAULT
, "%s: m_data out of bounds",
5513 * If first mbuf has no cluster, and has room for len bytes
5514 * without shifting current data, pullup into it,
5515 * otherwise allocate a new mbuf to prepend to the chain.
5517 if ((n
->m_flags
& M_EXT
) == 0 &&
5518 len
< &n
->m_dat
[MLEN
] - n
->m_data
&& n
->m_next
!= NULL
) {
5519 if (n
->m_len
>= len
) {
5529 _MGET(m
, M_DONTWAIT
, n
->m_type
);
5534 if (n
->m_flags
& M_PKTHDR
) {
5535 M_COPY_PKTHDR(m
, n
);
5536 n
->m_flags
&= ~M_PKTHDR
;
5539 space
= &m
->m_dat
[MLEN
] - (m
->m_data
+ m
->m_len
);
5541 count
= MIN(MIN(MAX(len
, max_protohdr
), space
), n
->m_len
);
5542 bcopy(MTOD(n
, caddr_t
), MTOD(m
, caddr_t
) + m
->m_len
,
5548 if (n
->m_len
!= 0) {
5553 } while (len
> 0 && n
!= NULL
);
5567 * Like m_pullup(), except a new mbuf is always allocated, and we allow
5568 * the amount of empty space before the data in the new mbuf to be specified
5569 * (in the event that the caller expects to prepend later).
5571 __private_extern__
int MSFail
= 0;
5573 __private_extern__
struct mbuf
*
5574 m_copyup(struct mbuf
*n
, int len
, int dstoff
)
5579 if (len
> (MHLEN
- dstoff
)) {
5582 MGET(m
, M_DONTWAIT
, n
->m_type
);
5587 if (n
->m_flags
& M_PKTHDR
) {
5588 m_copy_pkthdr(m
, n
);
5589 n
->m_flags
&= ~M_PKTHDR
;
5591 m
->m_data
+= dstoff
;
5592 space
= &m
->m_dat
[MLEN
] - (m
->m_data
+ m
->m_len
);
5594 count
= min(min(max(len
, max_protohdr
), space
), n
->m_len
);
5595 memcpy(mtod(m
, caddr_t
) + m
->m_len
, mtod(n
, caddr_t
),
5606 } while (len
> 0 && n
);
5620 * Partition an mbuf chain in two pieces, returning the tail --
5621 * all but the first len0 bytes. In case of failure, it returns NULL and
5622 * attempts to restore the chain to its original state.
5625 m_split(struct mbuf
*m0
, int len0
, int wait
)
5627 return m_split0(m0
, len0
, wait
, 1);
5630 static struct mbuf
*
5631 m_split0(struct mbuf
*m0
, int len0
, int wait
, int copyhdr
)
5634 unsigned len
= len0
, remain
;
5637 * First iterate to the mbuf which contains the first byte of
5638 * data at offset len0
5640 for (m
= m0
; m
&& len
> m
->m_len
; m
= m
->m_next
) {
5647 * len effectively is now the offset in the current
5648 * mbuf where we have to perform split.
5650 * remain becomes the tail length.
5651 * Note that len can also be == m->m_len
5653 remain
= m
->m_len
- len
;
5656 * If current mbuf len contains the entire remaining offset len,
5657 * just make the second mbuf chain pointing to next mbuf onwards
5658 * and return after making necessary adjustments
5660 if (copyhdr
&& (m0
->m_flags
& M_PKTHDR
) && remain
== 0) {
5661 _MGETHDR(n
, wait
, m0
->m_type
);
5665 n
->m_next
= m
->m_next
;
5667 n
->m_pkthdr
.rcvif
= m0
->m_pkthdr
.rcvif
;
5668 n
->m_pkthdr
.len
= m0
->m_pkthdr
.len
- len0
;
5669 m0
->m_pkthdr
.len
= len0
;
5672 if (copyhdr
&& (m0
->m_flags
& M_PKTHDR
)) {
5673 _MGETHDR(n
, wait
, m0
->m_type
);
5677 n
->m_pkthdr
.rcvif
= m0
->m_pkthdr
.rcvif
;
5678 n
->m_pkthdr
.len
= m0
->m_pkthdr
.len
- len0
;
5679 m0
->m_pkthdr
.len
= len0
;
5682 * If current points to external storage
5683 * then it can be shared by making last mbuf
5684 * of head chain and first mbuf of current chain
5685 * pointing to different data offsets
5687 if (m
->m_flags
& M_EXT
) {
5690 if (remain
> MHLEN
) {
5691 /* m can't be the lead packet */
5693 n
->m_next
= m_split(m
, len
, wait
);
5694 if (n
->m_next
== NULL
) {
5701 MH_ALIGN(n
, remain
);
5703 } else if (remain
== 0) {
5708 _MGET(n
, wait
, m
->m_type
);
5713 if ((m
->m_flags
& M_EXT
) == 0) {
5714 VERIFY(remain
<= MLEN
);
5719 if (m
->m_flags
& M_EXT
) {
5720 n
->m_flags
|= M_EXT
;
5721 n
->m_ext
= m
->m_ext
;
5723 n
->m_data
= m
->m_data
+ len
;
5725 bcopy(MTOD(m
, caddr_t
) + len
, MTOD(n
, caddr_t
), remain
);
5729 n
->m_next
= m
->m_next
;
5735 * Routine to copy from device local memory into mbufs.
5738 m_devget(char *buf
, int totlen
, int off0
, struct ifnet
*ifp
,
5739 void (*copy
)(const void *, void *, size_t))
5742 struct mbuf
*top
= NULL
, **mp
= &top
;
5743 int off
= off0
, len
;
5751 * If 'off' is non-zero, packet is trailer-encapsulated,
5752 * so we have to skip the type and length fields.
5754 cp
+= off
+ 2 * sizeof(u_int16_t
);
5755 totlen
-= 2 * sizeof(u_int16_t
);
5757 _MGETHDR(m
, M_DONTWAIT
, MT_DATA
);
5761 m
->m_pkthdr
.rcvif
= ifp
;
5762 m
->m_pkthdr
.len
= totlen
;
5765 while (totlen
> 0) {
5767 _MGET(m
, M_DONTWAIT
, MT_DATA
);
5774 len
= MIN(totlen
, epkt
- cp
);
5775 if (len
>= MINCLSIZE
) {
5776 MCLGET(m
, M_DONTWAIT
);
5777 if (m
->m_flags
& M_EXT
) {
5778 m
->m_len
= len
= MIN(len
, m_maxsize(MC_CL
));
5780 /* give up when it's out of cluster mbufs */
5789 * Place initial small packet/header at end of mbuf.
5791 if (len
< m
->m_len
) {
5793 len
+ max_linkhdr
<= m
->m_len
) {
5794 m
->m_data
+= max_linkhdr
;
5802 copy(cp
, MTOD(m
, caddr_t
), (unsigned)len
);
5804 bcopy(cp
, MTOD(m
, caddr_t
), (unsigned)len
);
5817 #ifndef MBUF_GROWTH_NORMAL_THRESH
5818 #define MBUF_GROWTH_NORMAL_THRESH 25
5822 * Cluster freelist allocation check.
5825 m_howmany(int num
, size_t bufsize
)
5828 u_int32_t m_mbclusters
, m_clusters
, m_bigclusters
, m_16kclusters
;
5829 u_int32_t m_mbfree
, m_clfree
, m_bigclfree
, m_16kclfree
;
5830 u_int32_t sumclusters
, freeclusters
;
5831 u_int32_t percent_pool
, percent_kmem
;
5832 u_int32_t mb_growth
, mb_growth_thresh
;
5834 VERIFY(bufsize
== m_maxsize(MC_BIGCL
) ||
5835 bufsize
== m_maxsize(MC_16KCL
));
5837 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_OWNED
);
5839 /* Numbers in 2K cluster units */
5840 m_mbclusters
= m_total(MC_MBUF
) >> NMBPCLSHIFT
;
5841 m_clusters
= m_total(MC_CL
);
5842 m_bigclusters
= m_total(MC_BIGCL
) << NCLPBGSHIFT
;
5843 m_16kclusters
= m_total(MC_16KCL
);
5844 sumclusters
= m_mbclusters
+ m_clusters
+ m_bigclusters
;
5846 m_mbfree
= m_infree(MC_MBUF
) >> NMBPCLSHIFT
;
5847 m_clfree
= m_infree(MC_CL
);
5848 m_bigclfree
= m_infree(MC_BIGCL
) << NCLPBGSHIFT
;
5849 m_16kclfree
= m_infree(MC_16KCL
);
5850 freeclusters
= m_mbfree
+ m_clfree
+ m_bigclfree
;
5852 /* Bail if we've maxed out the mbuf memory map */
5853 if ((bufsize
== m_maxsize(MC_BIGCL
) && sumclusters
>= nclusters
) ||
5854 (njcl
> 0 && bufsize
== m_maxsize(MC_16KCL
) &&
5855 (m_16kclusters
<< NCLPJCLSHIFT
) >= njcl
)) {
5856 mbwdog_logger("maxed out nclusters (%u >= %u) or njcl (%u >= %u)",
5857 sumclusters
, nclusters
,
5858 (m_16kclusters
<< NCLPJCLSHIFT
), njcl
);
5862 if (bufsize
== m_maxsize(MC_BIGCL
)) {
5864 if (m_bigclusters
< m_minlimit(MC_BIGCL
)) {
5865 return m_minlimit(MC_BIGCL
) - m_bigclusters
;
5869 ((sumclusters
- freeclusters
) * 100) / sumclusters
;
5870 percent_kmem
= (sumclusters
* 100) / nclusters
;
5873 * If a light/normal user, grow conservatively (75%)
5874 * If a heavy user, grow aggressively (50%)
5876 if (percent_kmem
< MBUF_GROWTH_NORMAL_THRESH
) {
5877 mb_growth
= MB_GROWTH_NORMAL
;
5879 mb_growth
= MB_GROWTH_AGGRESSIVE
;
5882 if (percent_kmem
< 5) {
5883 /* For initial allocations */
5886 /* Return if >= MBIGCL_LOWAT clusters available */
5887 if (m_infree(MC_BIGCL
) >= MBIGCL_LOWAT
&&
5888 m_total(MC_BIGCL
) >=
5889 MBIGCL_LOWAT
+ m_minlimit(MC_BIGCL
)) {
5893 /* Ensure at least num clusters are accessible */
5894 if (num
>= m_infree(MC_BIGCL
)) {
5895 i
= num
- m_infree(MC_BIGCL
);
5897 if (num
> m_total(MC_BIGCL
) - m_minlimit(MC_BIGCL
)) {
5898 j
= num
- (m_total(MC_BIGCL
) -
5899 m_minlimit(MC_BIGCL
));
5905 * Grow pool if percent_pool > 75 (normal growth)
5906 * or percent_pool > 50 (aggressive growth).
5908 mb_growth_thresh
= 100 - (100 / (1 << mb_growth
));
5909 if (percent_pool
> mb_growth_thresh
) {
5910 j
= ((sumclusters
+ num
) >> mb_growth
) -
5916 /* Check to ensure we didn't go over limits */
5917 if (i
+ m_bigclusters
>= m_maxlimit(MC_BIGCL
)) {
5918 i
= m_maxlimit(MC_BIGCL
) - m_bigclusters
;
5920 if ((i
<< 1) + sumclusters
>= nclusters
) {
5921 i
= (nclusters
- sumclusters
) >> 1;
5923 VERIFY((m_total(MC_BIGCL
) + i
) <= m_maxlimit(MC_BIGCL
));
5924 VERIFY(sumclusters
+ (i
<< 1) <= nclusters
);
5925 } else { /* 16K CL */
5927 /* Ensure at least num clusters are available */
5928 if (num
>= m_16kclfree
) {
5929 i
= num
- m_16kclfree
;
5932 /* Always grow 16KCL pool aggressively */
5933 if (((m_16kclusters
+ num
) >> 1) > m_16kclfree
) {
5934 j
= ((m_16kclusters
+ num
) >> 1) - m_16kclfree
;
5938 /* Check to ensure we don't go over limit */
5939 if ((i
+ m_total(MC_16KCL
)) >= m_maxlimit(MC_16KCL
)) {
5940 i
= m_maxlimit(MC_16KCL
) - m_total(MC_16KCL
);
5946 * Return the number of bytes in the mbuf chain, m.
5949 m_length(struct mbuf
*m
)
5952 unsigned int pktlen
;
5954 if (m
->m_flags
& M_PKTHDR
) {
5955 return m
->m_pkthdr
.len
;
5959 for (m0
= m
; m0
!= NULL
; m0
= m0
->m_next
) {
5960 pktlen
+= m0
->m_len
;
5966 * Copy data from a buffer back into the indicated mbuf chain,
5967 * starting "off" bytes from the beginning, extending the mbuf
5968 * chain if necessary.
5971 m_copyback(struct mbuf
*m0
, int off
, int len
, const void *cp
)
5974 struct mbuf
*origm
= m0
;
5985 m_copyback0(&m0
, off
, len
, cp
,
5986 M_COPYBACK0_COPYBACK
| M_COPYBACK0_EXTEND
, M_DONTWAIT
);
5989 if (error
!= 0 || (m0
!= NULL
&& origm
!= m0
)) {
5990 panic("m_copyback");
5996 m_copyback_cow(struct mbuf
*m0
, int off
, int len
, const void *cp
, int how
)
6000 /* don't support chain expansion */
6001 VERIFY(off
+ len
<= m_length(m0
));
6003 error
= m_copyback0(&m0
, off
, len
, cp
,
6004 M_COPYBACK0_COPYBACK
| M_COPYBACK0_COW
, how
);
6007 * no way to recover from partial success.
6008 * just free the chain.
6017 * m_makewritable: ensure the specified range writable.
6020 m_makewritable(struct mbuf
**mp
, int off
, int len
, int how
)
6025 int origlen
, reslen
;
6027 origlen
= m_length(*mp
);
6030 #if 0 /* M_COPYALL is large enough */
6031 if (len
== M_COPYALL
) {
6032 len
= m_length(*mp
) - off
; /* XXX */
6036 error
= m_copyback0(mp
, off
, len
, NULL
,
6037 M_COPYBACK0_PRESERVE
| M_COPYBACK0_COW
, how
);
6041 for (n
= *mp
; n
; n
= n
->m_next
) {
6044 if (origlen
!= reslen
) {
6045 panic("m_makewritable: length changed");
6047 if (((*mp
)->m_flags
& M_PKTHDR
) && reslen
!= (*mp
)->m_pkthdr
.len
) {
6048 panic("m_makewritable: inconsist");
6056 m_copyback0(struct mbuf
**mp0
, int off
, int len
, const void *vp
, int flags
,
6063 const char *cp
= vp
;
6065 VERIFY(mp0
!= NULL
);
6066 VERIFY(*mp0
!= NULL
);
6067 VERIFY((flags
& M_COPYBACK0_PRESERVE
) == 0 || cp
== NULL
);
6068 VERIFY((flags
& M_COPYBACK0_COPYBACK
) == 0 || cp
!= NULL
);
6071 * we don't bother to update "totlen" in the case of M_COPYBACK0_COW,
6072 * assuming that M_COPYBACK0_EXTEND and M_COPYBACK0_COW are exclusive.
6075 VERIFY((~flags
& (M_COPYBACK0_EXTEND
| M_COPYBACK0_COW
)) != 0);
6079 while (off
> (mlen
= m
->m_len
)) {
6082 if (m
->m_next
== NULL
) {
6085 if (!(flags
& M_COPYBACK0_EXTEND
)) {
6090 * try to make some space at the end of "m".
6094 if (off
+ len
>= MINCLSIZE
&&
6095 !(m
->m_flags
& M_EXT
) && m
->m_len
== 0) {
6098 tspace
= M_TRAILINGSPACE(m
);
6100 tspace
= MIN(tspace
, off
+ len
);
6102 bzero(mtod(m
, char *) + m
->m_len
,
6111 * need to allocate an mbuf.
6114 if (off
+ len
>= MINCLSIZE
) {
6115 n
= m_getcl(how
, m
->m_type
, 0);
6117 n
= _M_GET(how
, m
->m_type
);
6123 n
->m_len
= MIN(M_TRAILINGSPACE(n
), off
+ len
);
6124 bzero(mtod(n
, char *), MIN(n
->m_len
, off
));
6131 mlen
= m
->m_len
- off
;
6132 if (mlen
!= 0 && m_mclhasreference(m
)) {
6137 * this mbuf is read-only.
6138 * allocate a new writable mbuf and try again.
6142 if (!(flags
& M_COPYBACK0_COW
)) {
6143 panic("m_copyback0: read-only");
6145 #endif /* DIAGNOSTIC */
6148 * if we're going to write into the middle of
6149 * a mbuf, split it first.
6151 if (off
> 0 && len
< mlen
) {
6152 n
= m_split0(m
, off
, how
, 0);
6164 * XXX TODO coalesce into the trailingspace of
6165 * the previous mbuf when possible.
6169 * allocate a new mbuf. copy packet header if needed.
6171 n
= _M_GET(how
, m
->m_type
);
6175 if (off
== 0 && (m
->m_flags
& M_PKTHDR
)) {
6176 M_COPY_PKTHDR(n
, m
);
6179 if (len
>= MINCLSIZE
) {
6180 MCLGET(n
, M_DONTWAIT
);
6183 (n
->m_flags
& M_EXT
) ? MCLBYTES
: MLEN
;
6185 if (n
->m_len
> len
) {
6190 * free the region which has been overwritten.
6191 * copying data from old mbufs if requested.
6193 if (flags
& M_COPYBACK0_PRESERVE
) {
6194 datap
= mtod(n
, char *);
6199 VERIFY(off
== 0 || eatlen
>= mlen
);
6201 VERIFY(len
>= mlen
);
6205 m_copydata(m
, off
, mlen
, datap
);
6212 while (m
!= NULL
&& m_mclhasreference(m
) &&
6213 n
->m_type
== m
->m_type
&& eatlen
> 0) {
6214 mlen
= MIN(eatlen
, m
->m_len
);
6216 m_copydata(m
, 0, mlen
, datap
);
6222 if (m
->m_len
== 0) {
6223 *mp
= m
= m_free(m
);
6233 mlen
= MIN(mlen
, len
);
6234 if (flags
& M_COPYBACK0_COPYBACK
) {
6235 bcopy(cp
, mtod(m
, caddr_t
) + off
, (unsigned)mlen
);
6245 if (m
->m_next
== NULL
) {
6252 if (((m
= *mp0
)->m_flags
& M_PKTHDR
) && (m
->m_pkthdr
.len
< totlen
)) {
6253 VERIFY(flags
& M_COPYBACK0_EXTEND
);
6254 m
->m_pkthdr
.len
= totlen
;
6264 mcl_to_paddr(char *addr
)
6266 vm_offset_t base_phys
;
6268 if (!MBUF_IN_MAP(addr
)) {
6271 base_phys
= mcl_paddr
[atop_64(addr
- (char *)mbutl
)];
6273 if (base_phys
== 0) {
6276 return (uint64_t)(ptoa_64(base_phys
) | ((uint64_t)addr
& PAGE_MASK
));
6280 * Dup the mbuf chain passed in. The whole thing. No cute additional cruft.
6281 * And really copy the thing. That way, we don't "precompute" checksums
6282 * for unsuspecting consumers. Assumption: m->m_nextpkt == 0. Trick: for
6283 * small packets, don't dup into a cluster. That way received packets
6284 * don't take up too much room in the sockbuf (cf. sbspace()).
6289 m_dup(struct mbuf
*m
, int how
)
6291 struct mbuf
*n
, **np
;
6297 if (m
->m_flags
& M_PKTHDR
) {
6302 * Quick check: if we have one mbuf and its data fits in an
6303 * mbuf with packet header, just copy and go.
6305 if (m
->m_next
== NULL
) {
6306 /* Then just move the data into an mbuf and be done... */
6308 if (m
->m_pkthdr
.len
<= MHLEN
&& m
->m_len
<= MHLEN
) {
6309 if ((n
= _M_GETHDR(how
, m
->m_type
)) == NULL
) {
6312 n
->m_len
= m
->m_len
;
6313 m_dup_pkthdr(n
, m
, how
);
6314 bcopy(m
->m_data
, n
->m_data
, m
->m_len
);
6317 } else if (m
->m_len
<= MLEN
) {
6318 if ((n
= _M_GET(how
, m
->m_type
)) == NULL
) {
6321 bcopy(m
->m_data
, n
->m_data
, m
->m_len
);
6322 n
->m_len
= m
->m_len
;
6328 printf("<%x: %x, %x, %x\n", m
, m
->m_flags
, m
->m_len
,
6332 n
= _M_GETHDR(how
, m
->m_type
);
6334 n
= _M_GET(how
, m
->m_type
);
6339 if (m
->m_flags
& M_EXT
) {
6340 if (m
->m_len
<= m_maxsize(MC_CL
)) {
6342 } else if (m
->m_len
<= m_maxsize(MC_BIGCL
)) {
6343 n
= m_mbigget(n
, how
);
6344 } else if (m
->m_len
<= m_maxsize(MC_16KCL
) && njcl
> 0) {
6345 n
= m_m16kget(n
, how
);
6347 if (!(n
->m_flags
& M_EXT
)) {
6354 /* Don't use M_COPY_PKTHDR: preserve m_data */
6355 m_dup_pkthdr(n
, m
, how
);
6357 if (!(n
->m_flags
& M_EXT
)) {
6358 n
->m_data
= n
->m_pktdat
;
6361 n
->m_len
= m
->m_len
;
6363 * Get the dup on the same bdry as the original
6364 * Assume that the two mbufs have the same offset to data area
6365 * (up to word boundaries)
6367 bcopy(MTOD(m
, caddr_t
), MTOD(n
, caddr_t
), (unsigned)n
->m_len
);
6371 printf(">%x: %x, %x, %x\n", n
, n
->m_flags
, n
->m_len
,
6387 #define MBUF_MULTIPAGES(m) \
6388 (((m)->m_flags & M_EXT) && \
6389 ((IS_P2ALIGNED((m)->m_data, PAGE_SIZE) \
6390 && (m)->m_len > PAGE_SIZE) || \
6391 (!IS_P2ALIGNED((m)->m_data, PAGE_SIZE) && \
6392 P2ROUNDUP((m)->m_data, PAGE_SIZE) < ((uintptr_t)(m)->m_data + (m)->m_len))))
6394 static struct mbuf
*
6395 m_expand(struct mbuf
*m
, struct mbuf
**last
)
6397 struct mbuf
*top
= NULL
;
6398 struct mbuf
**nm
= &top
;
6399 uintptr_t data0
, data
;
6400 unsigned int len0
, len
;
6402 VERIFY(MBUF_MULTIPAGES(m
));
6403 VERIFY(m
->m_next
== NULL
);
6404 data0
= (uintptr_t)m
->m_data
;
6412 if (IS_P2ALIGNED(data
, PAGE_SIZE
) && len0
> PAGE_SIZE
) {
6414 } else if (!IS_P2ALIGNED(data
, PAGE_SIZE
) &&
6415 P2ROUNDUP(data
, PAGE_SIZE
) < (data
+ len0
)) {
6416 len
= P2ROUNDUP(data
, PAGE_SIZE
) - data
;
6422 VERIFY(m
->m_flags
& M_EXT
);
6423 m
->m_data
= (void *)data
;
6436 n
= _M_RETRY(M_DONTWAIT
, MT_DATA
);
6443 n
->m_ext
= m
->m_ext
;
6445 n
->m_flags
|= M_EXT
;
6452 m_normalize(struct mbuf
*m
)
6454 struct mbuf
*top
= NULL
;
6455 struct mbuf
**nm
= &top
;
6456 boolean_t expanded
= FALSE
;
6464 /* Does the data cross one or more page boundaries? */
6465 if (MBUF_MULTIPAGES(m
)) {
6467 if ((m
= m_expand(m
, &last
)) == NULL
) {
6483 atomic_add_32(&mb_normalized
, 1);
6489 * Append the specified data to the indicated mbuf chain,
6490 * Extend the mbuf chain if the new data does not fit in
6493 * Return 1 if able to complete the job; otherwise 0.
6496 m_append(struct mbuf
*m0
, int len
, caddr_t cp
)
6499 int remainder
, space
;
6501 for (m
= m0
; m
->m_next
!= NULL
; m
= m
->m_next
) {
6505 space
= M_TRAILINGSPACE(m
);
6508 * Copy into available space.
6510 if (space
> remainder
) {
6513 bcopy(cp
, mtod(m
, caddr_t
) + m
->m_len
, space
);
6518 while (remainder
> 0) {
6520 * Allocate a new mbuf; could check space
6521 * and allocate a cluster instead.
6523 n
= m_get(M_WAITOK
, m
->m_type
);
6527 n
->m_len
= min(MLEN
, remainder
);
6528 bcopy(cp
, mtod(n
, caddr_t
), n
->m_len
);
6530 remainder
-= n
->m_len
;
6534 if (m0
->m_flags
& M_PKTHDR
) {
6535 m0
->m_pkthdr
.len
+= len
- remainder
;
6537 return remainder
== 0;
6541 m_last(struct mbuf
*m
)
6543 while (m
->m_next
!= NULL
) {
6550 m_fixhdr(struct mbuf
*m0
)
6554 VERIFY(m0
->m_flags
& M_PKTHDR
);
6556 len
= m_length2(m0
, NULL
);
6557 m0
->m_pkthdr
.len
= len
;
6562 m_length2(struct mbuf
*m0
, struct mbuf
**last
)
6568 for (m
= m0
; m
!= NULL
; m
= m
->m_next
) {
6570 if (m
->m_next
== NULL
) {
6581 * Defragment a mbuf chain, returning the shortest possible chain of mbufs
6582 * and clusters. If allocation fails and this cannot be completed, NULL will
6583 * be returned, but the passed in chain will be unchanged. Upon success,
6584 * the original chain will be freed, and the new chain will be returned.
6586 * If a non-packet header is passed in, the original mbuf (chain?) will
6587 * be returned unharmed.
6589 * If offset is specfied, the first mbuf in the chain will have a leading
6590 * space of the amount stated by the "off" parameter.
6592 * This routine requires that the m_pkthdr.header field of the original
6593 * mbuf chain is cleared by the caller.
6596 m_defrag_offset(struct mbuf
*m0
, u_int32_t off
, int how
)
6598 struct mbuf
*m_new
= NULL
, *m_final
= NULL
;
6599 int progress
= 0, length
, pktlen
;
6601 if (!(m0
->m_flags
& M_PKTHDR
)) {
6605 VERIFY(off
< MHLEN
);
6606 m_fixhdr(m0
); /* Needed sanity check */
6608 pktlen
= m0
->m_pkthdr
.len
+ off
;
6609 if (pktlen
> MHLEN
) {
6610 m_final
= m_getcl(how
, MT_DATA
, M_PKTHDR
);
6612 m_final
= m_gethdr(how
, MT_DATA
);
6615 if (m_final
== NULL
) {
6621 m_final
->m_data
+= off
;
6625 * Caller must have handled the contents pointed to by this
6626 * pointer before coming here, as otherwise it will point to
6627 * the original mbuf which will get freed upon success.
6629 VERIFY(m0
->m_pkthdr
.pkt_hdr
== NULL
);
6631 if (m_dup_pkthdr(m_final
, m0
, how
) == 0) {
6637 while (progress
< pktlen
) {
6638 length
= pktlen
- progress
;
6639 if (length
> MCLBYTES
) {
6642 length
-= ((m_new
== m_final
) ? off
: 0);
6647 if (m_new
== NULL
) {
6648 if (length
> MLEN
) {
6649 m_new
= m_getcl(how
, MT_DATA
, 0);
6651 m_new
= m_get(how
, MT_DATA
);
6653 if (m_new
== NULL
) {
6658 m_copydata(m0
, progress
, length
, mtod(m_new
, caddr_t
));
6660 m_new
->m_len
= length
;
6661 if (m_new
!= m_final
) {
6662 m_cat(m_final
, m_new
);
6677 m_defrag(struct mbuf
*m0
, int how
)
6679 return m_defrag_offset(m0
, 0, how
);
6683 m_mchtype(struct mbuf
*m
, int t
)
6686 mtype_stat_dec(m
->m_type
);
6691 m_mtod(struct mbuf
*m
)
6693 return MTOD(m
, void *);
6699 return (struct mbuf
*)((uintptr_t)(x
) & ~(MSIZE
- 1));
6703 m_mcheck(struct mbuf
*m
)
6709 * Return a pointer to mbuf/offset of location in mbuf chain.
6712 m_getptr(struct mbuf
*m
, int loc
, int *off
)
6715 /* Normal end of search. */
6716 if (m
->m_len
> loc
) {
6721 if (m
->m_next
== NULL
) {
6723 /* Point at the end of valid data. */
6736 * Inform the corresponding mcache(s) that there's a waiter below.
6739 mbuf_waiter_inc(mbuf_class_t
class, boolean_t comp
)
6741 mcache_waiter_inc(m_cache(class));
6743 if (class == MC_CL
) {
6744 mcache_waiter_inc(m_cache(MC_MBUF_CL
));
6745 } else if (class == MC_BIGCL
) {
6746 mcache_waiter_inc(m_cache(MC_MBUF_BIGCL
));
6747 } else if (class == MC_16KCL
) {
6748 mcache_waiter_inc(m_cache(MC_MBUF_16KCL
));
6750 mcache_waiter_inc(m_cache(MC_MBUF_CL
));
6751 mcache_waiter_inc(m_cache(MC_MBUF_BIGCL
));
6757 * Inform the corresponding mcache(s) that there's no more waiter below.
6760 mbuf_waiter_dec(mbuf_class_t
class, boolean_t comp
)
6762 mcache_waiter_dec(m_cache(class));
6764 if (class == MC_CL
) {
6765 mcache_waiter_dec(m_cache(MC_MBUF_CL
));
6766 } else if (class == MC_BIGCL
) {
6767 mcache_waiter_dec(m_cache(MC_MBUF_BIGCL
));
6768 } else if (class == MC_16KCL
) {
6769 mcache_waiter_dec(m_cache(MC_MBUF_16KCL
));
6771 mcache_waiter_dec(m_cache(MC_MBUF_CL
));
6772 mcache_waiter_dec(m_cache(MC_MBUF_BIGCL
));
6778 * Called during slab (blocking and non-blocking) allocation. If there
6779 * is at least one waiter, and the time since the first waiter is blocked
6780 * is greater than the watchdog timeout, panic the system.
6788 if (mb_waiters
== 0 || !mb_watchdog
) {
6793 since
= now
.tv_sec
- mb_wdtstart
.tv_sec
;
6794 if (since
>= MB_WDT_MAXTIME
) {
6795 panic_plain("%s: %d waiters stuck for %u secs\n%s", __func__
,
6796 mb_waiters
, since
, mbuf_dump());
6802 * Called during blocking allocation. Returns TRUE if one or more objects
6803 * are available at the per-CPU caches layer and that allocation should be
6804 * retried at that level.
6807 mbuf_sleep(mbuf_class_t
class, unsigned int num
, int wait
)
6809 boolean_t mcache_retry
= FALSE
;
6811 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_OWNED
);
6813 /* Check if there's anything at the cache layer */
6814 if (mbuf_cached_above(class, wait
)) {
6815 mcache_retry
= TRUE
;
6819 /* Nothing? Then try hard to get it from somewhere */
6820 m_reclaim(class, num
, (wait
& MCR_COMP
));
6822 /* We tried hard and got something? */
6823 if (m_infree(class) > 0) {
6826 } else if (mbuf_cached_above(class, wait
)) {
6828 mcache_retry
= TRUE
;
6830 } else if (wait
& MCR_TRYHARD
) {
6831 mcache_retry
= TRUE
;
6836 * There's really nothing for us right now; inform the
6837 * cache(s) that there is a waiter below and go to sleep.
6839 mbuf_waiter_inc(class, (wait
& MCR_COMP
));
6841 VERIFY(!(wait
& MCR_NOSLEEP
));
6844 * If this is the first waiter, arm the watchdog timer. Otherwise
6845 * check if we need to panic the system due to watchdog timeout.
6847 if (mb_waiters
== 0) {
6848 microuptime(&mb_wdtstart
);
6854 m_region_expand(class) += m_total(class) + num
;
6855 /* wake up the worker thread */
6856 if (mbuf_worker_ready
&&
6857 mbuf_worker_needs_wakeup
) {
6858 wakeup((caddr_t
)&mbuf_worker_needs_wakeup
);
6859 mbuf_worker_needs_wakeup
= FALSE
;
6861 mbwdog_logger("waiting (%d mbufs in class %s)", num
, m_cname(class));
6862 (void) msleep(mb_waitchan
, mbuf_mlock
, (PZERO
- 1), m_cname(class), NULL
);
6863 mbwdog_logger("woke up (%d mbufs in class %s) ", num
, m_cname(class));
6865 /* We are now up; stop getting notified until next round */
6866 mbuf_waiter_dec(class, (wait
& MCR_COMP
));
6868 /* We waited and got something */
6869 if (m_infree(class) > 0) {
6872 } else if (mbuf_cached_above(class, wait
)) {
6874 mcache_retry
= TRUE
;
6877 return mcache_retry
;
6880 __attribute__((noreturn
))
6882 mbuf_worker_thread(void)
6887 lck_mtx_lock(mbuf_mlock
);
6888 mbwdog_logger("worker thread running");
6889 mbuf_worker_run_cnt
++;
6892 * Allocations are based on page size, so if we have depleted
6893 * the reserved spaces, try to free mbufs from the major classes.
6895 #if PAGE_SIZE == 4096
6896 uint32_t m_mbclusters
= m_total(MC_MBUF
) >> NMBPCLSHIFT
;
6897 uint32_t m_clusters
= m_total(MC_CL
);
6898 uint32_t m_bigclusters
= m_total(MC_BIGCL
) << NCLPBGSHIFT
;
6899 uint32_t sumclusters
= m_mbclusters
+ m_clusters
+ m_bigclusters
;
6900 if (sumclusters
>= nclusters
) {
6901 mbwdog_logger("reclaiming bigcl");
6902 mbuf_drain_locked(TRUE
);
6903 m_reclaim(MC_BIGCL
, 4, FALSE
);
6906 uint32_t m_16kclusters
= m_total(MC_16KCL
);
6907 if (njcl
> 0 && (m_16kclusters
<< NCLPJCLSHIFT
) >= njcl
) {
6908 mbwdog_logger("reclaiming 16kcl");
6909 mbuf_drain_locked(TRUE
);
6910 m_reclaim(MC_16KCL
, 4, FALSE
);
6913 if (m_region_expand(MC_CL
) > 0) {
6916 /* Adjust to current number of cluster in use */
6917 n
= m_region_expand(MC_CL
) -
6918 (m_total(MC_CL
) - m_infree(MC_CL
));
6919 if ((n
+ m_total(MC_CL
)) > m_maxlimit(MC_CL
)) {
6920 n
= m_maxlimit(MC_CL
) - m_total(MC_CL
);
6923 mb_expand_cl_total
+= n
;
6925 m_region_expand(MC_CL
) = 0;
6928 mbwdog_logger("expanding MC_CL by %d", n
);
6929 freelist_populate(MC_CL
, n
, M_WAIT
);
6932 if (m_region_expand(MC_BIGCL
) > 0) {
6934 mb_expand_bigcl_cnt
++;
6935 /* Adjust to current number of 4 KB cluster in use */
6936 n
= m_region_expand(MC_BIGCL
) -
6937 (m_total(MC_BIGCL
) - m_infree(MC_BIGCL
));
6938 if ((n
+ m_total(MC_BIGCL
)) > m_maxlimit(MC_BIGCL
)) {
6939 n
= m_maxlimit(MC_BIGCL
) - m_total(MC_BIGCL
);
6942 mb_expand_bigcl_total
+= n
;
6944 m_region_expand(MC_BIGCL
) = 0;
6947 mbwdog_logger("expanding MC_BIGCL by %d", n
);
6948 freelist_populate(MC_BIGCL
, n
, M_WAIT
);
6951 if (m_region_expand(MC_16KCL
) > 0) {
6953 mb_expand_16kcl_cnt
++;
6954 /* Adjust to current number of 16 KB cluster in use */
6955 n
= m_region_expand(MC_16KCL
) -
6956 (m_total(MC_16KCL
) - m_infree(MC_16KCL
));
6957 if ((n
+ m_total(MC_16KCL
)) > m_maxlimit(MC_16KCL
)) {
6958 n
= m_maxlimit(MC_16KCL
) - m_total(MC_16KCL
);
6961 mb_expand_16kcl_total
+= n
;
6963 m_region_expand(MC_16KCL
) = 0;
6966 mbwdog_logger("expanding MC_16KCL by %d", n
);
6967 (void) freelist_populate(MC_16KCL
, n
, M_WAIT
);
6972 * Because we can run out of memory before filling the mbuf
6973 * map, we should not allocate more clusters than they are
6974 * mbufs -- otherwise we could have a large number of useless
6975 * clusters allocated.
6977 mbwdog_logger("totals: MC_MBUF %d MC_BIGCL %d MC_CL %d MC_16KCL %d",
6978 m_total(MC_MBUF
), m_total(MC_BIGCL
), m_total(MC_CL
),
6980 uint32_t total_mbufs
= m_total(MC_MBUF
);
6981 uint32_t total_clusters
= m_total(MC_BIGCL
) + m_total(MC_CL
) +
6983 if (total_mbufs
< total_clusters
) {
6984 mbwdog_logger("expanding MC_MBUF by %d",
6985 total_clusters
- total_mbufs
);
6987 while (total_mbufs
< total_clusters
) {
6989 if (freelist_populate(MC_MBUF
, 1, M_WAIT
) == 0) {
6992 total_mbufs
= m_total(MC_MBUF
);
6993 total_clusters
= m_total(MC_BIGCL
) + m_total(MC_CL
) +
6997 mbuf_worker_needs_wakeup
= TRUE
;
6999 * If there's a deadlock and we're not sending / receiving
7000 * packets, net_uptime() won't be updated. Update it here
7001 * so we are sure it's correct.
7003 net_update_uptime();
7004 mbuf_worker_last_runtime
= net_uptime();
7005 assert_wait((caddr_t
)&mbuf_worker_needs_wakeup
,
7007 mbwdog_logger("worker thread sleeping");
7008 lck_mtx_unlock(mbuf_mlock
);
7009 (void) thread_block((thread_continue_t
)mbuf_worker_thread
);
7013 __attribute__((noreturn
))
7015 mbuf_worker_thread_init(void)
7017 mbuf_worker_ready
++;
7018 mbuf_worker_thread();
7027 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_OWNED
);
7029 VERIFY(MBUF_IN_MAP(buf
));
7030 ix
= ((unsigned char *)buf
- mbutl
) >> MBSHIFT
;
7031 VERIFY(ix
< maxslabgrp
);
7033 if ((slg
= slabstbl
[ix
]) == NULL
) {
7035 * In the current implementation, we never shrink the slabs
7036 * table; if we attempt to reallocate a cluster group when
7037 * it's already allocated, panic since this is a sign of a
7038 * memory corruption (slabstbl[ix] got nullified).
7041 VERIFY(ix
< slabgrp
);
7043 * Slabs expansion can only be done single threaded; when
7044 * we get here, it must be as a result of m_clalloc() which
7045 * is serialized and therefore mb_clalloc_busy must be set.
7047 VERIFY(mb_clalloc_busy
);
7048 lck_mtx_unlock(mbuf_mlock
);
7050 /* This is a new buffer; create the slabs group for it */
7051 MALLOC(slg
, mcl_slabg_t
*, sizeof(*slg
), M_TEMP
,
7053 MALLOC(slg
->slg_slab
, mcl_slab_t
*, sizeof(mcl_slab_t
) * NSLABSPMB
,
7054 M_TEMP
, M_WAITOK
| M_ZERO
);
7055 VERIFY(slg
!= NULL
&& slg
->slg_slab
!= NULL
);
7057 lck_mtx_lock(mbuf_mlock
);
7059 * No other thread could have gone into m_clalloc() after
7060 * we dropped the lock above, so verify that it's true.
7062 VERIFY(mb_clalloc_busy
);
7066 /* Chain each slab in the group to its forward neighbor */
7067 for (k
= 1; k
< NSLABSPMB
; k
++) {
7068 slg
->slg_slab
[k
- 1].sl_next
= &slg
->slg_slab
[k
];
7070 VERIFY(slg
->slg_slab
[NSLABSPMB
- 1].sl_next
== NULL
);
7072 /* And chain the last slab in the previous group to this */
7074 VERIFY(slabstbl
[ix
- 1]->
7075 slg_slab
[NSLABSPMB
- 1].sl_next
== NULL
);
7076 slabstbl
[ix
- 1]->slg_slab
[NSLABSPMB
- 1].sl_next
=
7081 ix
= MTOPG(buf
) % NSLABSPMB
;
7082 VERIFY(ix
< NSLABSPMB
);
7084 return &slg
->slg_slab
[ix
];
7088 slab_init(mcl_slab_t
*sp
, mbuf_class_t
class, u_int32_t flags
,
7089 void *base
, void *head
, unsigned int len
, int refcnt
, int chunks
)
7091 sp
->sl_class
= class;
7092 sp
->sl_flags
= flags
;
7096 sp
->sl_refcnt
= refcnt
;
7097 sp
->sl_chunks
= chunks
;
7102 slab_insert(mcl_slab_t
*sp
, mbuf_class_t
class)
7104 VERIFY(slab_is_detached(sp
));
7105 m_slab_cnt(class)++;
7106 TAILQ_INSERT_TAIL(&m_slablist(class), sp
, sl_link
);
7107 sp
->sl_flags
&= ~SLF_DETACHED
;
7110 * If a buffer spans multiple contiguous pages then mark them as
7113 if (class == MC_16KCL
) {
7115 for (k
= 1; k
< NSLABSP16KB
; k
++) {
7117 /* Next slab must already be present */
7118 VERIFY(sp
!= NULL
&& slab_is_detached(sp
));
7119 sp
->sl_flags
&= ~SLF_DETACHED
;
7125 slab_remove(mcl_slab_t
*sp
, mbuf_class_t
class)
7128 VERIFY(!slab_is_detached(sp
));
7129 VERIFY(m_slab_cnt(class) > 0);
7130 m_slab_cnt(class)--;
7131 TAILQ_REMOVE(&m_slablist(class), sp
, sl_link
);
7133 if (class == MC_16KCL
) {
7134 for (k
= 1; k
< NSLABSP16KB
; k
++) {
7136 /* Next slab must already be present */
7138 VERIFY(!slab_is_detached(sp
));
7145 slab_inrange(mcl_slab_t
*sp
, void *buf
)
7147 return (uintptr_t)buf
>= (uintptr_t)sp
->sl_base
&&
7148 (uintptr_t)buf
< ((uintptr_t)sp
->sl_base
+ sp
->sl_len
);
7154 slab_nextptr_panic(mcl_slab_t
*sp
, void *addr
)
7157 unsigned int chunk_len
= sp
->sl_len
/ sp
->sl_chunks
;
7158 uintptr_t buf
= (uintptr_t)sp
->sl_base
;
7160 for (i
= 0; i
< sp
->sl_chunks
; i
++, buf
+= chunk_len
) {
7161 void *next
= ((mcache_obj_t
*)buf
)->obj_next
;
7166 if (next
!= NULL
&& !MBUF_IN_MAP(next
)) {
7167 mcache_t
*cp
= m_cache(sp
->sl_class
);
7168 panic("%s: %s buffer %p in slab %p modified "
7169 "after free at offset 0: %p out of range "
7170 "[%p-%p)\n", __func__
, cp
->mc_name
,
7171 (void *)buf
, sp
, next
, mbutl
, embutl
);
7175 mcache_audit_t
*mca
= mcl_audit_buf2mca(sp
->sl_class
,
7176 (mcache_obj_t
*)buf
);
7177 mcl_audit_verify_nextptr(next
, mca
);
7183 slab_detach(mcl_slab_t
*sp
)
7185 sp
->sl_link
.tqe_next
= (mcl_slab_t
*)-1;
7186 sp
->sl_link
.tqe_prev
= (mcl_slab_t
**)-1;
7187 sp
->sl_flags
|= SLF_DETACHED
;
7191 slab_is_detached(mcl_slab_t
*sp
)
7193 return (intptr_t)sp
->sl_link
.tqe_next
== -1 &&
7194 (intptr_t)sp
->sl_link
.tqe_prev
== -1 &&
7195 (sp
->sl_flags
& SLF_DETACHED
);
7199 mcl_audit_init(void *buf
, mcache_audit_t
**mca_list
,
7200 mcache_obj_t
**con_list
, size_t con_size
, unsigned int num
)
7202 mcache_audit_t
*mca
, *mca_tail
;
7203 mcache_obj_t
*con
= NULL
;
7204 boolean_t save_contents
= (con_list
!= NULL
);
7207 ASSERT(num
<= NMBPG
);
7208 ASSERT(con_list
== NULL
|| con_size
!= 0);
7211 VERIFY(ix
< maxclaudit
);
7213 /* Make sure we haven't been here before */
7214 for (i
= 0; i
< num
; i
++) {
7215 VERIFY(mclaudit
[ix
].cl_audit
[i
] == NULL
);
7218 mca
= mca_tail
= *mca_list
;
7219 if (save_contents
) {
7223 for (i
= 0; i
< num
; i
++) {
7224 mcache_audit_t
*next
;
7226 next
= mca
->mca_next
;
7227 bzero(mca
, sizeof(*mca
));
7228 mca
->mca_next
= next
;
7229 mclaudit
[ix
].cl_audit
[i
] = mca
;
7231 /* Attach the contents buffer if requested */
7232 if (save_contents
) {
7233 mcl_saved_contents_t
*msc
=
7234 (mcl_saved_contents_t
*)(void *)con
;
7236 VERIFY(msc
!= NULL
);
7237 VERIFY(IS_P2ALIGNED(msc
, sizeof(u_int64_t
)));
7238 VERIFY(con_size
== sizeof(*msc
));
7239 mca
->mca_contents_size
= con_size
;
7240 mca
->mca_contents
= msc
;
7241 con
= con
->obj_next
;
7242 bzero(mca
->mca_contents
, mca
->mca_contents_size
);
7246 mca
= mca
->mca_next
;
7249 if (save_contents
) {
7253 *mca_list
= mca_tail
->mca_next
;
7254 mca_tail
->mca_next
= NULL
;
7258 mcl_audit_free(void *buf
, unsigned int num
)
7261 mcache_audit_t
*mca
, *mca_list
;
7264 VERIFY(ix
< maxclaudit
);
7266 if (mclaudit
[ix
].cl_audit
[0] != NULL
) {
7267 mca_list
= mclaudit
[ix
].cl_audit
[0];
7268 for (i
= 0; i
< num
; i
++) {
7269 mca
= mclaudit
[ix
].cl_audit
[i
];
7270 mclaudit
[ix
].cl_audit
[i
] = NULL
;
7271 if (mca
->mca_contents
) {
7272 mcache_free(mcl_audit_con_cache
,
7276 mcache_free_ext(mcache_audit_cache
,
7277 (mcache_obj_t
*)mca_list
);
7282 * Given an address of a buffer (mbuf/2KB/4KB/16KB), return
7283 * the corresponding audit structure for that buffer.
7285 static mcache_audit_t
*
7286 mcl_audit_buf2mca(mbuf_class_t
class, mcache_obj_t
*mobj
)
7288 mcache_audit_t
*mca
= NULL
;
7289 int ix
= MTOPG(mobj
), m_idx
= 0;
7290 unsigned char *page_addr
;
7292 VERIFY(ix
< maxclaudit
);
7293 VERIFY(IS_P2ALIGNED(mobj
, MIN(m_maxsize(class), PAGE_SIZE
)));
7295 page_addr
= PGTOM(ix
);
7300 * For the mbuf case, find the index of the page
7301 * used by the mbuf and use that index to locate the
7302 * base address of the page. Then find out the
7303 * mbuf index relative to the page base and use
7304 * it to locate the audit structure.
7306 m_idx
= MBPAGEIDX(page_addr
, mobj
);
7307 VERIFY(m_idx
< (int)NMBPG
);
7308 mca
= mclaudit
[ix
].cl_audit
[m_idx
];
7313 * Same thing as above, but for 2KB clusters in a page.
7315 m_idx
= CLPAGEIDX(page_addr
, mobj
);
7316 VERIFY(m_idx
< (int)NCLPG
);
7317 mca
= mclaudit
[ix
].cl_audit
[m_idx
];
7321 m_idx
= BCLPAGEIDX(page_addr
, mobj
);
7322 VERIFY(m_idx
< (int)NBCLPG
);
7323 mca
= mclaudit
[ix
].cl_audit
[m_idx
];
7327 * Same as above, but only return the first element.
7329 mca
= mclaudit
[ix
].cl_audit
[0];
7341 mcl_audit_mbuf(mcache_audit_t
*mca
, void *addr
, boolean_t composite
,
7344 struct mbuf
*m
= addr
;
7345 mcache_obj_t
*next
= ((mcache_obj_t
*)m
)->obj_next
;
7347 VERIFY(mca
->mca_contents
!= NULL
&&
7348 mca
->mca_contents_size
== AUDIT_CONTENTS_SIZE
);
7351 mcl_audit_verify_nextptr(next
, mca
);
7355 /* Save constructed mbuf fields */
7356 mcl_audit_save_mbuf(m
, mca
);
7358 mcache_set_pattern(MCACHE_FREE_PATTERN
, m
,
7359 m_maxsize(MC_MBUF
));
7361 ((mcache_obj_t
*)m
)->obj_next
= next
;
7365 /* Check if the buffer has been corrupted while in freelist */
7367 mcache_audit_free_verify_set(mca
, addr
, 0, m_maxsize(MC_MBUF
));
7369 /* Restore constructed mbuf fields */
7370 mcl_audit_restore_mbuf(m
, mca
, composite
);
7374 mcl_audit_restore_mbuf(struct mbuf
*m
, mcache_audit_t
*mca
, boolean_t composite
)
7376 struct mbuf
*ms
= MCA_SAVED_MBUF_PTR(mca
);
7379 struct mbuf
*next
= m
->m_next
;
7380 VERIFY(ms
->m_flags
== M_EXT
&& m_get_rfa(ms
) != NULL
&&
7381 MBUF_IS_COMPOSITE(ms
));
7382 VERIFY(mca
->mca_contents_size
== AUDIT_CONTENTS_SIZE
);
7384 * We could have hand-picked the mbuf fields and restore
7385 * them individually, but that will be a maintenance
7386 * headache. Instead, restore everything that was saved;
7387 * the mbuf layer will recheck and reinitialize anyway.
7389 bcopy(ms
, m
, MCA_SAVED_MBUF_SIZE
);
7393 * For a regular mbuf (no cluster attached) there's nothing
7394 * to restore other than the type field, which is expected
7397 m
->m_type
= ms
->m_type
;
7403 mcl_audit_save_mbuf(struct mbuf
*m
, mcache_audit_t
*mca
)
7405 VERIFY(mca
->mca_contents_size
== AUDIT_CONTENTS_SIZE
);
7407 bcopy(m
, MCA_SAVED_MBUF_PTR(mca
), MCA_SAVED_MBUF_SIZE
);
7411 mcl_audit_cluster(mcache_audit_t
*mca
, void *addr
, size_t size
, boolean_t alloc
,
7412 boolean_t save_next
)
7414 mcache_obj_t
*next
= ((mcache_obj_t
*)addr
)->obj_next
;
7418 mcache_set_pattern(MCACHE_FREE_PATTERN
, addr
, size
);
7421 mcl_audit_verify_nextptr(next
, mca
);
7422 ((mcache_obj_t
*)addr
)->obj_next
= next
;
7424 } else if (mclverify
) {
7425 /* Check if the buffer has been corrupted while in freelist */
7426 mcl_audit_verify_nextptr(next
, mca
);
7427 mcache_audit_free_verify_set(mca
, addr
, 0, size
);
7432 mcl_audit_scratch(mcache_audit_t
*mca
)
7434 void *stack
[MCACHE_STACK_DEPTH
+ 1];
7435 mcl_scratch_audit_t
*msa
;
7438 VERIFY(mca
->mca_contents
!= NULL
);
7439 msa
= MCA_SAVED_SCRATCH_PTR(mca
);
7441 msa
->msa_pthread
= msa
->msa_thread
;
7442 msa
->msa_thread
= current_thread();
7443 bcopy(msa
->msa_stack
, msa
->msa_pstack
, sizeof(msa
->msa_pstack
));
7444 msa
->msa_pdepth
= msa
->msa_depth
;
7445 bzero(stack
, sizeof(stack
));
7446 msa
->msa_depth
= OSBacktrace(stack
, MCACHE_STACK_DEPTH
+ 1) - 1;
7447 bcopy(&stack
[1], msa
->msa_stack
, sizeof(msa
->msa_stack
));
7449 msa
->msa_ptstamp
= msa
->msa_tstamp
;
7451 /* tstamp is in ms relative to base_ts */
7452 msa
->msa_tstamp
= ((now
.tv_usec
- mb_start
.tv_usec
) / 1000);
7453 if ((now
.tv_sec
- mb_start
.tv_sec
) > 0) {
7454 msa
->msa_tstamp
+= ((now
.tv_sec
- mb_start
.tv_sec
) * 1000);
7459 mcl_audit_mcheck_panic(struct mbuf
*m
)
7461 mcache_audit_t
*mca
;
7464 mca
= mcl_audit_buf2mca(MC_MBUF
, (mcache_obj_t
*)m
);
7466 panic("mcl_audit: freed mbuf %p with type 0x%x (instead of 0x%x)\n%s\n",
7467 m
, (u_int16_t
)m
->m_type
, MT_FREE
, mcache_dump_mca(mca
));
7472 mcl_audit_verify_nextptr(void *next
, mcache_audit_t
*mca
)
7474 if (next
!= NULL
&& !MBUF_IN_MAP(next
) &&
7475 (next
!= (void *)MCACHE_FREE_PATTERN
|| !mclverify
)) {
7476 panic("mcl_audit: buffer %p modified after free at offset 0: "
7477 "%p out of range [%p-%p)\n%s\n",
7478 mca
->mca_addr
, next
, mbutl
, embutl
, mcache_dump_mca(mca
));
7483 /* This function turns on mbuf leak detection */
7485 mleak_activate(void)
7487 mleak_table
.mleak_sample_factor
= MLEAK_SAMPLE_FACTOR
;
7488 PE_parse_boot_argn("mleak_sample_factor",
7489 &mleak_table
.mleak_sample_factor
,
7490 sizeof(mleak_table
.mleak_sample_factor
));
7492 if (mleak_table
.mleak_sample_factor
== 0) {
7496 if (mclfindleak
== 0) {
7500 vm_size_t alloc_size
=
7501 mleak_alloc_buckets
* sizeof(struct mallocation
);
7502 vm_size_t trace_size
= mleak_trace_buckets
* sizeof(struct mtrace
);
7504 MALLOC(mleak_allocations
, struct mallocation
*, alloc_size
,
7505 M_TEMP
, M_WAITOK
| M_ZERO
);
7506 VERIFY(mleak_allocations
!= NULL
);
7508 MALLOC(mleak_traces
, struct mtrace
*, trace_size
,
7509 M_TEMP
, M_WAITOK
| M_ZERO
);
7510 VERIFY(mleak_traces
!= NULL
);
7512 MALLOC(mleak_stat
, mleak_stat_t
*, MLEAK_STAT_SIZE(MLEAK_NUM_TRACES
),
7513 M_TEMP
, M_WAITOK
| M_ZERO
);
7514 VERIFY(mleak_stat
!= NULL
);
7515 mleak_stat
->ml_cnt
= MLEAK_NUM_TRACES
;
7517 mleak_stat
->ml_isaddr64
= 1;
7518 #endif /* __LP64__ */
7522 mleak_logger(u_int32_t num
, mcache_obj_t
*addr
, boolean_t alloc
)
7526 if (mclfindleak
== 0) {
7531 return mleak_free(addr
);
7534 temp
= atomic_add_32_ov(&mleak_table
.mleak_capture
, 1);
7536 if ((temp
% mleak_table
.mleak_sample_factor
) == 0 && addr
!= NULL
) {
7537 uintptr_t bt
[MLEAK_STACK_DEPTH
];
7538 int logged
= backtrace(bt
, MLEAK_STACK_DEPTH
);
7539 mleak_log(bt
, addr
, logged
, num
);
7544 * This function records the allocation in the mleak_allocations table
7545 * and the backtrace in the mleak_traces table; if allocation slot is in use,
7546 * replace old allocation with new one if the trace slot is in use, return
7547 * (or increment refcount if same trace).
7550 mleak_log(uintptr_t *bt
, mcache_obj_t
*addr
, uint32_t depth
, int num
)
7552 struct mallocation
*allocation
;
7553 struct mtrace
*trace
;
7554 uint32_t trace_index
;
7556 /* Quit if someone else modifying the tables */
7557 if (!lck_mtx_try_lock_spin(mleak_lock
)) {
7558 mleak_table
.total_conflicts
++;
7562 allocation
= &mleak_allocations
[hashaddr((uintptr_t)addr
,
7563 mleak_alloc_buckets
)];
7564 trace_index
= hashbacktrace(bt
, depth
, mleak_trace_buckets
);
7565 trace
= &mleak_traces
[trace_index
];
7567 VERIFY(allocation
<= &mleak_allocations
[mleak_alloc_buckets
- 1]);
7568 VERIFY(trace
<= &mleak_traces
[mleak_trace_buckets
- 1]);
7570 allocation
->hitcount
++;
7574 * If the allocation bucket we want is occupied
7575 * and the occupier has the same trace, just bail.
7577 if (allocation
->element
!= NULL
&&
7578 trace_index
== allocation
->trace_index
) {
7579 mleak_table
.alloc_collisions
++;
7580 lck_mtx_unlock(mleak_lock
);
7585 * Store the backtrace in the traces array;
7586 * Size of zero = trace bucket is free.
7588 if (trace
->allocs
> 0 &&
7589 bcmp(trace
->addr
, bt
, (depth
* sizeof(uintptr_t))) != 0) {
7590 /* Different, unique trace, but the same hash! Bail out. */
7591 trace
->collisions
++;
7592 mleak_table
.trace_collisions
++;
7593 lck_mtx_unlock(mleak_lock
);
7595 } else if (trace
->allocs
> 0) {
7596 /* Same trace, already added, so increment refcount */
7599 /* Found an unused trace bucket, so record the trace here */
7600 if (trace
->depth
!= 0) {
7601 /* this slot previously used but not currently in use */
7602 mleak_table
.trace_overwrites
++;
7604 mleak_table
.trace_recorded
++;
7606 memcpy(trace
->addr
, bt
, (depth
* sizeof(uintptr_t)));
7607 trace
->depth
= depth
;
7608 trace
->collisions
= 0;
7611 /* Step 2: Store the allocation record in the allocations array */
7612 if (allocation
->element
!= NULL
) {
7614 * Replace an existing allocation. No need to preserve
7615 * because only a subset of the allocations are being
7618 mleak_table
.alloc_collisions
++;
7619 } else if (allocation
->trace_index
!= 0) {
7620 mleak_table
.alloc_overwrites
++;
7622 allocation
->element
= addr
;
7623 allocation
->trace_index
= trace_index
;
7624 allocation
->count
= num
;
7625 mleak_table
.alloc_recorded
++;
7626 mleak_table
.outstanding_allocs
++;
7628 lck_mtx_unlock(mleak_lock
);
7633 mleak_free(mcache_obj_t
*addr
)
7635 while (addr
!= NULL
) {
7636 struct mallocation
*allocation
= &mleak_allocations
7637 [hashaddr((uintptr_t)addr
, mleak_alloc_buckets
)];
7639 if (allocation
->element
== addr
&&
7640 allocation
->trace_index
< mleak_trace_buckets
) {
7641 lck_mtx_lock_spin(mleak_lock
);
7642 if (allocation
->element
== addr
&&
7643 allocation
->trace_index
< mleak_trace_buckets
) {
7644 struct mtrace
*trace
;
7645 trace
= &mleak_traces
[allocation
->trace_index
];
7646 /* allocs = 0 means trace bucket is unused */
7647 if (trace
->allocs
> 0) {
7650 if (trace
->allocs
== 0) {
7653 /* NULL element means alloc bucket is unused */
7654 allocation
->element
= NULL
;
7655 mleak_table
.outstanding_allocs
--;
7657 lck_mtx_unlock(mleak_lock
);
7659 addr
= addr
->obj_next
;
7667 struct mtrace
*swap
;
7669 for (i
= 0; i
< MLEAK_NUM_TRACES
; i
++) {
7670 mleak_top_trace
[i
] = NULL
;
7673 for (i
= 0, j
= 0; j
< MLEAK_NUM_TRACES
&& i
< mleak_trace_buckets
; i
++) {
7674 if (mleak_traces
[i
].allocs
<= 0) {
7678 mleak_top_trace
[j
] = &mleak_traces
[i
];
7679 for (k
= j
; k
> 0; k
--) {
7680 if (mleak_top_trace
[k
]->allocs
<=
7681 mleak_top_trace
[k
- 1]->allocs
) {
7685 swap
= mleak_top_trace
[k
- 1];
7686 mleak_top_trace
[k
- 1] = mleak_top_trace
[k
];
7687 mleak_top_trace
[k
] = swap
;
7693 for (; i
< mleak_trace_buckets
; i
++) {
7694 if (mleak_traces
[i
].allocs
<= mleak_top_trace
[j
]->allocs
) {
7698 mleak_top_trace
[j
] = &mleak_traces
[i
];
7700 for (k
= j
; k
> 0; k
--) {
7701 if (mleak_top_trace
[k
]->allocs
<=
7702 mleak_top_trace
[k
- 1]->allocs
) {
7706 swap
= mleak_top_trace
[k
- 1];
7707 mleak_top_trace
[k
- 1] = mleak_top_trace
[k
];
7708 mleak_top_trace
[k
] = swap
;
7714 mleak_update_stats()
7716 mleak_trace_stat_t
*mltr
;
7719 VERIFY(mleak_stat
!= NULL
);
7721 VERIFY(mleak_stat
->ml_isaddr64
);
7723 VERIFY(!mleak_stat
->ml_isaddr64
);
7724 #endif /* !__LP64__ */
7725 VERIFY(mleak_stat
->ml_cnt
== MLEAK_NUM_TRACES
);
7727 mleak_sort_traces();
7729 mltr
= &mleak_stat
->ml_trace
[0];
7730 bzero(mltr
, sizeof(*mltr
) * MLEAK_NUM_TRACES
);
7731 for (i
= 0; i
< MLEAK_NUM_TRACES
; i
++) {
7734 if (mleak_top_trace
[i
] == NULL
||
7735 mleak_top_trace
[i
]->allocs
== 0) {
7739 mltr
->mltr_collisions
= mleak_top_trace
[i
]->collisions
;
7740 mltr
->mltr_hitcount
= mleak_top_trace
[i
]->hitcount
;
7741 mltr
->mltr_allocs
= mleak_top_trace
[i
]->allocs
;
7742 mltr
->mltr_depth
= mleak_top_trace
[i
]->depth
;
7744 VERIFY(mltr
->mltr_depth
<= MLEAK_STACK_DEPTH
);
7745 for (j
= 0; j
< mltr
->mltr_depth
; j
++) {
7746 mltr
->mltr_addr
[j
] = mleak_top_trace
[i
]->addr
[j
];
7753 static struct mbtypes
{
7755 const char *mt_name
;
7757 { MT_DATA
, "data" },
7758 { MT_OOBDATA
, "oob data" },
7759 { MT_CONTROL
, "ancillary data" },
7760 { MT_HEADER
, "packet headers" },
7761 { MT_SOCKET
, "socket structures" },
7762 { MT_PCB
, "protocol control blocks" },
7763 { MT_RTABLE
, "routing table entries" },
7764 { MT_HTABLE
, "IMP host table entries" },
7765 { MT_ATABLE
, "address resolution tables" },
7766 { MT_FTABLE
, "fragment reassembly queue headers" },
7767 { MT_SONAME
, "socket names and addresses" },
7768 { MT_SOOPTS
, "socket options" },
7769 { MT_RIGHTS
, "access rights" },
7770 { MT_IFADDR
, "interface addresses" },
7771 { MT_TAG
, "packet tags" },
7775 #define MBUF_DUMP_BUF_CHK() { \
7785 unsigned long totmem
= 0, totfree
= 0, totmbufs
, totused
, totpct
,
7787 u_int32_t m_mbufs
= 0, m_clfree
= 0, m_bigclfree
= 0;
7788 u_int32_t m_mbufclfree
= 0, m_mbufbigclfree
= 0;
7789 u_int32_t m_16kclusters
= 0, m_16kclfree
= 0, m_mbuf16kclfree
= 0;
7790 int nmbtypes
= sizeof(mbstat
.m_mtypes
) / sizeof(short);
7793 mb_class_stat_t
*sp
;
7794 mleak_trace_stat_t
*mltr
;
7795 char *c
= mbuf_dump_buf
;
7796 int i
, j
, k
, clen
= MBUF_DUMP_BUF_SIZE
;
7797 bool printed_banner
= false;
7799 mbuf_dump_buf
[0] = '\0';
7801 /* synchronize all statistics in the mbuf table */
7803 mbuf_mtypes_sync(TRUE
);
7805 sp
= &mb_stat
->mbs_class
[0];
7806 for (i
= 0; i
< mb_stat
->mbs_cnt
; i
++, sp
++) {
7809 if (m_class(i
) == MC_MBUF
) {
7810 m_mbufs
= sp
->mbcl_active
;
7811 } else if (m_class(i
) == MC_CL
) {
7812 m_clfree
= sp
->mbcl_total
- sp
->mbcl_active
;
7813 } else if (m_class(i
) == MC_BIGCL
) {
7814 m_bigclfree
= sp
->mbcl_total
- sp
->mbcl_active
;
7815 } else if (njcl
> 0 && m_class(i
) == MC_16KCL
) {
7816 m_16kclfree
= sp
->mbcl_total
- sp
->mbcl_active
;
7817 m_16kclusters
= sp
->mbcl_total
;
7818 } else if (m_class(i
) == MC_MBUF_CL
) {
7819 m_mbufclfree
= sp
->mbcl_total
- sp
->mbcl_active
;
7820 } else if (m_class(i
) == MC_MBUF_BIGCL
) {
7821 m_mbufbigclfree
= sp
->mbcl_total
- sp
->mbcl_active
;
7822 } else if (njcl
> 0 && m_class(i
) == MC_MBUF_16KCL
) {
7823 m_mbuf16kclfree
= sp
->mbcl_total
- sp
->mbcl_active
;
7826 mem
= sp
->mbcl_ctotal
* sp
->mbcl_size
;
7828 totfree
+= (sp
->mbcl_mc_cached
+ sp
->mbcl_infree
) *
7830 totreturned
+= sp
->mbcl_release_cnt
;
7833 /* adjust free counts to include composite caches */
7834 m_clfree
+= m_mbufclfree
;
7835 m_bigclfree
+= m_mbufbigclfree
;
7836 m_16kclfree
+= m_mbuf16kclfree
;
7839 for (mp
= mbtypes
; mp
->mt_name
!= NULL
; mp
++) {
7840 totmbufs
+= mbstat
.m_mtypes
[mp
->mt_type
];
7842 if (totmbufs
> m_mbufs
) {
7845 k
= snprintf(c
, clen
, "%lu/%u mbufs in use:\n", totmbufs
, m_mbufs
);
7846 MBUF_DUMP_BUF_CHK();
7848 bzero(&seen
, sizeof(seen
));
7849 for (mp
= mbtypes
; mp
->mt_name
!= NULL
; mp
++) {
7850 if (mbstat
.m_mtypes
[mp
->mt_type
] != 0) {
7851 seen
[mp
->mt_type
] = 1;
7852 k
= snprintf(c
, clen
, "\t%u mbufs allocated to %s\n",
7853 mbstat
.m_mtypes
[mp
->mt_type
], mp
->mt_name
);
7854 MBUF_DUMP_BUF_CHK();
7858 for (i
= 0; i
< nmbtypes
; i
++) {
7859 if (!seen
[i
] && mbstat
.m_mtypes
[i
] != 0) {
7860 k
= snprintf(c
, clen
, "\t%u mbufs allocated to "
7861 "<mbuf type %d>\n", mbstat
.m_mtypes
[i
], i
);
7862 MBUF_DUMP_BUF_CHK();
7865 if ((m_mbufs
- totmbufs
) > 0) {
7866 k
= snprintf(c
, clen
, "\t%lu mbufs allocated to caches\n",
7867 m_mbufs
- totmbufs
);
7868 MBUF_DUMP_BUF_CHK();
7870 k
= snprintf(c
, clen
, "%u/%u mbuf 2KB clusters in use\n"
7871 "%u/%u mbuf 4KB clusters in use\n",
7872 (unsigned int)(mbstat
.m_clusters
- m_clfree
),
7873 (unsigned int)mbstat
.m_clusters
,
7874 (unsigned int)(mbstat
.m_bigclusters
- m_bigclfree
),
7875 (unsigned int)mbstat
.m_bigclusters
);
7876 MBUF_DUMP_BUF_CHK();
7879 k
= snprintf(c
, clen
, "%u/%u mbuf %uKB clusters in use\n",
7880 m_16kclusters
- m_16kclfree
, m_16kclusters
,
7882 MBUF_DUMP_BUF_CHK();
7884 totused
= totmem
- totfree
;
7887 } else if (totused
< (ULONG_MAX
/ 100)) {
7888 totpct
= (totused
* 100) / totmem
;
7890 u_long totmem1
= totmem
/ 100;
7891 u_long totused1
= totused
/ 100;
7892 totpct
= (totused1
* 100) / totmem1
;
7894 k
= snprintf(c
, clen
, "%lu KB allocated to network (approx. %lu%% "
7895 "in use)\n", totmem
/ 1024, totpct
);
7896 MBUF_DUMP_BUF_CHK();
7897 k
= snprintf(c
, clen
, "%lu KB returned to the system\n",
7898 totreturned
/ 1024);
7899 MBUF_DUMP_BUF_CHK();
7901 net_update_uptime();
7902 k
= snprintf(c
, clen
,
7903 "VM allocation failures: contiguous %u, normal %u, one page %u\n",
7904 mb_kmem_contig_failed
, mb_kmem_failed
, mb_kmem_one_failed
);
7905 MBUF_DUMP_BUF_CHK();
7906 if (mb_kmem_contig_failed_ts
|| mb_kmem_failed_ts
||
7907 mb_kmem_one_failed_ts
) {
7908 k
= snprintf(c
, clen
,
7909 "VM allocation failure timestamps: contiguous %llu "
7910 "(size %llu), normal %llu (size %llu), one page %llu "
7912 mb_kmem_contig_failed_ts
, mb_kmem_contig_failed_size
,
7913 mb_kmem_failed_ts
, mb_kmem_failed_size
,
7914 mb_kmem_one_failed_ts
, net_uptime());
7915 MBUF_DUMP_BUF_CHK();
7916 k
= snprintf(c
, clen
,
7917 "VM return codes: ");
7918 MBUF_DUMP_BUF_CHK();
7920 i
< sizeof(mb_kmem_stats
) / sizeof(mb_kmem_stats
[0]);
7922 k
= snprintf(c
, clen
, "%s: %u ", mb_kmem_stats_labels
[i
],
7924 MBUF_DUMP_BUF_CHK();
7926 k
= snprintf(c
, clen
, "\n");
7927 MBUF_DUMP_BUF_CHK();
7929 k
= snprintf(c
, clen
,
7930 "worker thread runs: %u, expansions: %llu, cl %llu/%llu, "
7931 "bigcl %llu/%llu, 16k %llu/%llu\n", mbuf_worker_run_cnt
,
7932 mb_expand_cnt
, mb_expand_cl_cnt
, mb_expand_cl_total
,
7933 mb_expand_bigcl_cnt
, mb_expand_bigcl_total
, mb_expand_16kcl_cnt
,
7934 mb_expand_16kcl_total
);
7935 MBUF_DUMP_BUF_CHK();
7936 if (mbuf_worker_last_runtime
!= 0) {
7937 k
= snprintf(c
, clen
, "worker thread last run time: "
7938 "%llu (%llu seconds ago)\n",
7939 mbuf_worker_last_runtime
,
7940 net_uptime() - mbuf_worker_last_runtime
);
7941 MBUF_DUMP_BUF_CHK();
7943 if (mbuf_drain_last_runtime
!= 0) {
7944 k
= snprintf(c
, clen
, "drain routine last run time: "
7945 "%llu (%llu seconds ago)\n",
7946 mbuf_drain_last_runtime
,
7947 net_uptime() - mbuf_drain_last_runtime
);
7948 MBUF_DUMP_BUF_CHK();
7951 #if DEBUG || DEVELOPMENT
7952 k
= snprintf(c
, clen
, "\nworker thread log:\n%s\n", mbwdog_logging
);
7953 MBUF_DUMP_BUF_CHK();
7956 for (j
= 0; j
< MTRACELARGE_NUM_TRACES
; j
++) {
7957 struct mtracelarge
*trace
= &mtracelarge_table
[j
];
7958 if (trace
->size
== 0 || trace
->depth
== 0) {
7961 if (printed_banner
== false) {
7962 k
= snprintf(c
, clen
,
7963 "\nlargest allocation failure backtraces:\n");
7964 MBUF_DUMP_BUF_CHK();
7965 printed_banner
= true;
7967 k
= snprintf(c
, clen
, "size %llu: < ", trace
->size
);
7968 MBUF_DUMP_BUF_CHK();
7969 for (i
= 0; i
< trace
->depth
; i
++) {
7970 if (mleak_stat
->ml_isaddr64
) {
7971 k
= snprintf(c
, clen
, "0x%0llx ",
7972 (uint64_t)VM_KERNEL_UNSLIDE(
7975 k
= snprintf(c
, clen
,
7977 (uint32_t)VM_KERNEL_UNSLIDE(
7980 MBUF_DUMP_BUF_CHK();
7982 k
= snprintf(c
, clen
, ">\n");
7983 MBUF_DUMP_BUF_CHK();
7986 /* mbuf leak detection statistics */
7987 mleak_update_stats();
7989 k
= snprintf(c
, clen
, "\nmbuf leak detection table:\n");
7990 MBUF_DUMP_BUF_CHK();
7991 k
= snprintf(c
, clen
, "\ttotal captured: %u (one per %u)\n",
7992 mleak_table
.mleak_capture
/ mleak_table
.mleak_sample_factor
,
7993 mleak_table
.mleak_sample_factor
);
7994 MBUF_DUMP_BUF_CHK();
7995 k
= snprintf(c
, clen
, "\ttotal allocs outstanding: %llu\n",
7996 mleak_table
.outstanding_allocs
);
7997 MBUF_DUMP_BUF_CHK();
7998 k
= snprintf(c
, clen
, "\tnew hash recorded: %llu allocs, %llu traces\n",
7999 mleak_table
.alloc_recorded
, mleak_table
.trace_recorded
);
8000 MBUF_DUMP_BUF_CHK();
8001 k
= snprintf(c
, clen
, "\thash collisions: %llu allocs, %llu traces\n",
8002 mleak_table
.alloc_collisions
, mleak_table
.trace_collisions
);
8003 MBUF_DUMP_BUF_CHK();
8004 k
= snprintf(c
, clen
, "\toverwrites: %llu allocs, %llu traces\n",
8005 mleak_table
.alloc_overwrites
, mleak_table
.trace_overwrites
);
8006 MBUF_DUMP_BUF_CHK();
8007 k
= snprintf(c
, clen
, "\tlock conflicts: %llu\n\n",
8008 mleak_table
.total_conflicts
);
8009 MBUF_DUMP_BUF_CHK();
8011 k
= snprintf(c
, clen
, "top %d outstanding traces:\n",
8012 mleak_stat
->ml_cnt
);
8013 MBUF_DUMP_BUF_CHK();
8014 for (i
= 0; i
< mleak_stat
->ml_cnt
; i
++) {
8015 mltr
= &mleak_stat
->ml_trace
[i
];
8016 k
= snprintf(c
, clen
, "[%d] %llu outstanding alloc(s), "
8017 "%llu hit(s), %llu collision(s)\n", (i
+ 1),
8018 mltr
->mltr_allocs
, mltr
->mltr_hitcount
,
8019 mltr
->mltr_collisions
);
8020 MBUF_DUMP_BUF_CHK();
8023 if (mleak_stat
->ml_isaddr64
) {
8024 k
= snprintf(c
, clen
, MB_LEAK_HDR_64
);
8026 k
= snprintf(c
, clen
, MB_LEAK_HDR_32
);
8028 MBUF_DUMP_BUF_CHK();
8030 for (i
= 0; i
< MLEAK_STACK_DEPTH
; i
++) {
8031 k
= snprintf(c
, clen
, "%2d: ", (i
+ 1));
8032 MBUF_DUMP_BUF_CHK();
8033 for (j
= 0; j
< mleak_stat
->ml_cnt
; j
++) {
8034 mltr
= &mleak_stat
->ml_trace
[j
];
8035 if (i
< mltr
->mltr_depth
) {
8036 if (mleak_stat
->ml_isaddr64
) {
8037 k
= snprintf(c
, clen
, "0x%0llx ",
8038 (uint64_t)VM_KERNEL_UNSLIDE(
8039 mltr
->mltr_addr
[i
]));
8041 k
= snprintf(c
, clen
,
8043 (uint32_t)VM_KERNEL_UNSLIDE(
8044 mltr
->mltr_addr
[i
]));
8047 if (mleak_stat
->ml_isaddr64
) {
8048 k
= snprintf(c
, clen
,
8049 MB_LEAK_SPACING_64
);
8051 k
= snprintf(c
, clen
,
8052 MB_LEAK_SPACING_32
);
8055 MBUF_DUMP_BUF_CHK();
8057 k
= snprintf(c
, clen
, "\n");
8058 MBUF_DUMP_BUF_CHK();
8061 return mbuf_dump_buf
;
8064 #undef MBUF_DUMP_BUF_CHK
8067 * Convert between a regular and a packet header mbuf. Caller is responsible
8068 * for setting or clearing M_PKTHDR; this routine does the rest of the work.
8071 m_reinit(struct mbuf
*m
, int hdr
)
8076 VERIFY(!(m
->m_flags
& M_PKTHDR
));
8077 if (!(m
->m_flags
& M_EXT
) &&
8078 (m
->m_data
!= m
->m_dat
|| m
->m_len
> 0)) {
8080 * If there's no external cluster attached and the
8081 * mbuf appears to contain user data, we cannot
8082 * safely convert this to a packet header mbuf,
8083 * as the packet header structure might overlap
8086 printf("%s: cannot set M_PKTHDR on altered mbuf %llx, "
8087 "m_data %llx (expected %llx), "
8088 "m_len %d (expected 0)\n",
8090 (uint64_t)VM_KERNEL_ADDRPERM(m
),
8091 (uint64_t)VM_KERNEL_ADDRPERM(m
->m_data
),
8092 (uint64_t)VM_KERNEL_ADDRPERM(m
->m_dat
), m
->m_len
);
8095 VERIFY((m
->m_flags
& M_EXT
) || m
->m_data
== m
->m_dat
);
8096 m
->m_flags
|= M_PKTHDR
;
8097 MBUF_INIT_PKTHDR(m
);
8100 /* Check for scratch area overflow */
8101 m_redzone_verify(m
);
8102 /* Free the aux data and tags if there is any */
8103 m_tag_delete_chain(m
, NULL
);
8104 m
->m_flags
&= ~M_PKTHDR
;
8111 m_ext_set_prop(struct mbuf
*m
, uint32_t o
, uint32_t n
)
8113 ASSERT(m
->m_flags
& M_EXT
);
8114 return atomic_test_set_32(&MEXT_PRIV(m
), o
, n
);
8118 m_ext_get_prop(struct mbuf
*m
)
8120 ASSERT(m
->m_flags
& M_EXT
);
8121 return MEXT_PRIV(m
);
8125 m_ext_paired_is_active(struct mbuf
*m
)
8127 return MBUF_IS_PAIRED(m
) ? (MEXT_PREF(m
) > MEXT_MINREF(m
)) : 1;
8131 m_ext_paired_activate(struct mbuf
*m
)
8133 struct ext_ref
*rfa
;
8136 m_ext_free_func_t extfree
;
8139 VERIFY(MBUF_IS_PAIRED(m
));
8140 VERIFY(MEXT_REF(m
) == MEXT_MINREF(m
));
8141 VERIFY(MEXT_PREF(m
) == MEXT_MINREF(m
));
8143 hdr
= (m
->m_flags
& M_PKTHDR
);
8145 extbuf
= m
->m_ext
.ext_buf
;
8146 extfree
= m_get_ext_free(m
);
8147 extsize
= m
->m_ext
.ext_size
;
8150 VERIFY(extbuf
!= NULL
&& rfa
!= NULL
);
8153 * Safe to reinitialize packet header tags, since it's
8154 * already taken care of at m_free() time. Similar to
8155 * what's done in m_clattach() for the cluster. Bump
8156 * up MEXT_PREF to indicate activation.
8158 MBUF_INIT(m
, hdr
, type
);
8159 MEXT_INIT(m
, extbuf
, extsize
, extfree
, (caddr_t
)m
, rfa
,
8160 1, 1, 2, EXTF_PAIRED
, MEXT_PRIV(m
), m
);
8164 m_scratch_init(struct mbuf
*m
)
8166 struct pkthdr
*pkt
= &m
->m_pkthdr
;
8168 VERIFY(m
->m_flags
& M_PKTHDR
);
8170 /* See comments in <rdar://problem/14040693> */
8171 if (pkt
->pkt_flags
& PKTF_PRIV_GUARDED
) {
8172 panic_plain("Invalid attempt to modify guarded module-private "
8173 "area: mbuf %p, pkt_flags 0x%x\n", m
, pkt
->pkt_flags
);
8177 bzero(&pkt
->pkt_mpriv
, sizeof(pkt
->pkt_mpriv
));
8181 * This routine is reserved for mbuf_get_driver_scratch(); clients inside
8182 * xnu that intend on utilizing the module-private area should directly
8183 * refer to the pkt_mpriv structure in the pkthdr. They are also expected
8184 * to set and clear PKTF_PRIV_GUARDED, while owning the packet and prior
8185 * to handing it off to another module, respectively.
8188 m_scratch_get(struct mbuf
*m
, u_int8_t
**p
)
8190 struct pkthdr
*pkt
= &m
->m_pkthdr
;
8192 VERIFY(m
->m_flags
& M_PKTHDR
);
8194 /* See comments in <rdar://problem/14040693> */
8195 if (pkt
->pkt_flags
& PKTF_PRIV_GUARDED
) {
8196 panic_plain("Invalid attempt to access guarded module-private "
8197 "area: mbuf %p, pkt_flags 0x%x\n", m
, pkt
->pkt_flags
);
8202 mcache_audit_t
*mca
;
8204 lck_mtx_lock(mbuf_mlock
);
8205 mca
= mcl_audit_buf2mca(MC_MBUF
, (mcache_obj_t
*)m
);
8206 if (mca
->mca_uflags
& MB_SCVALID
) {
8207 mcl_audit_scratch(mca
);
8209 lck_mtx_unlock(mbuf_mlock
);
8212 *p
= (u_int8_t
*)&pkt
->pkt_mpriv
;
8213 return sizeof(pkt
->pkt_mpriv
);
8217 m_redzone_init(struct mbuf
*m
)
8219 VERIFY(m
->m_flags
& M_PKTHDR
);
8221 * Each mbuf has a unique red zone pattern, which is a XOR
8222 * of the red zone cookie and the address of the mbuf.
8224 m
->m_pkthdr
.redzone
= ((u_int32_t
)(uintptr_t)m
) ^ mb_redzone_cookie
;
8228 m_redzone_verify(struct mbuf
*m
)
8230 u_int32_t mb_redzone
;
8232 VERIFY(m
->m_flags
& M_PKTHDR
);
8234 mb_redzone
= ((u_int32_t
)(uintptr_t)m
) ^ mb_redzone_cookie
;
8235 if (m
->m_pkthdr
.redzone
!= mb_redzone
) {
8236 panic("mbuf %p redzone violation with value 0x%x "
8237 "(instead of 0x%x, using cookie 0x%x)\n",
8238 m
, m
->m_pkthdr
.redzone
, mb_redzone
, mb_redzone_cookie
);
8243 __private_extern__
inline void
8244 m_set_ext(struct mbuf
*m
, struct ext_ref
*rfa
, m_ext_free_func_t ext_free
,
8247 VERIFY(m
->m_flags
& M_EXT
);
8249 m
->m_ext
.ext_refflags
=
8250 (struct ext_ref
*)(((uintptr_t)rfa
) ^ mb_obscure_extref
);
8251 if (ext_free
!= NULL
) {
8252 rfa
->ext_token
= ((uintptr_t)&rfa
->ext_token
) ^
8254 m
->m_ext
.ext_free
= (m_ext_free_func_t
)
8255 (((uintptr_t)ext_free
) ^ rfa
->ext_token
);
8256 if (ext_arg
!= NULL
) {
8258 (caddr_t
)(((uintptr_t)ext_arg
) ^ rfa
->ext_token
);
8260 m
->m_ext
.ext_arg
= NULL
;
8264 m
->m_ext
.ext_free
= NULL
;
8265 m
->m_ext
.ext_arg
= NULL
;
8269 * If we are going to loose the cookie in ext_token by
8270 * resetting the rfa, we should use the global cookie
8271 * to obscure the ext_free and ext_arg pointers.
8273 if (ext_free
!= NULL
) {
8275 (m_ext_free_func_t
)((uintptr_t)ext_free
^
8276 mb_obscure_extfree
);
8277 if (ext_arg
!= NULL
) {
8279 (caddr_t
)((uintptr_t)ext_arg
^
8280 mb_obscure_extfree
);
8282 m
->m_ext
.ext_arg
= NULL
;
8285 m
->m_ext
.ext_free
= NULL
;
8286 m
->m_ext
.ext_arg
= NULL
;
8288 m
->m_ext
.ext_refflags
= NULL
;
8292 __private_extern__
inline struct ext_ref
*
8293 m_get_rfa(struct mbuf
*m
)
8295 if (m
->m_ext
.ext_refflags
== NULL
) {
8298 return (struct ext_ref
*)(((uintptr_t)m
->m_ext
.ext_refflags
) ^ mb_obscure_extref
);
8302 __private_extern__
inline m_ext_free_func_t
8303 m_get_ext_free(struct mbuf
*m
)
8305 struct ext_ref
*rfa
;
8306 if (m
->m_ext
.ext_free
== NULL
) {
8312 return (m_ext_free_func_t
)((uintptr_t)m
->m_ext
.ext_free
^ mb_obscure_extfree
);
8314 return (m_ext_free_func_t
)(((uintptr_t)m
->m_ext
.ext_free
)
8319 __private_extern__
inline caddr_t
8320 m_get_ext_arg(struct mbuf
*m
)
8322 struct ext_ref
*rfa
;
8323 if (m
->m_ext
.ext_arg
== NULL
) {
8329 return (caddr_t
)((uintptr_t)m
->m_ext
.ext_arg
^ mb_obscure_extfree
);
8331 return (caddr_t
)(((uintptr_t)m
->m_ext
.ext_arg
) ^
8337 * Send a report of mbuf usage if the usage is at least 6% of max limit
8338 * or if there has been at least 3% increase since the last report.
8340 * The values 6% and 3% are chosen so that we can do simple arithmetic
8341 * with shift operations.
8344 mbuf_report_usage(mbuf_class_t cl
)
8346 /* if a report is already in progress, nothing to do */
8347 if (mb_peak_newreport
) {
8351 if (m_total(cl
) > m_peak(cl
) &&
8352 m_total(cl
) >= (m_maxlimit(cl
) >> 4) &&
8353 (m_total(cl
) - m_peak(cl
)) >= (m_peak(cl
) >> 5)) {
8359 __private_extern__
void
8360 mbuf_report_peak_usage(void)
8364 struct nstat_sysinfo_data ns_data
;
8365 uint32_t memreleased
= 0;
8366 static uint32_t prevmemreleased
;
8368 uptime
= net_uptime();
8369 lck_mtx_lock(mbuf_mlock
);
8371 /* Generate an initial report after 1 week of uptime */
8372 if (!mb_peak_firstreport
&&
8373 uptime
> MBUF_PEAK_FIRST_REPORT_THRESHOLD
) {
8374 mb_peak_newreport
= TRUE
;
8375 mb_peak_firstreport
= TRUE
;
8378 if (!mb_peak_newreport
) {
8379 lck_mtx_unlock(mbuf_mlock
);
8384 * Since a report is being generated before 1 week,
8385 * we do not need to force another one later
8387 if (uptime
< MBUF_PEAK_FIRST_REPORT_THRESHOLD
) {
8388 mb_peak_firstreport
= TRUE
;
8391 for (i
= 0; i
< NELEM(mbuf_table
); i
++) {
8392 m_peak(m_class(i
)) = m_total(m_class(i
));
8393 memreleased
+= m_release_cnt(i
);
8395 memreleased
= memreleased
- prevmemreleased
;
8396 prevmemreleased
= memreleased
;
8397 mb_peak_newreport
= FALSE
;
8398 lck_mtx_unlock(mbuf_mlock
);
8400 bzero(&ns_data
, sizeof(ns_data
));
8401 ns_data
.flags
= NSTAT_SYSINFO_MBUF_STATS
;
8402 ns_data
.u
.mb_stats
.total_256b
= m_peak(MC_MBUF
);
8403 ns_data
.u
.mb_stats
.total_2kb
= m_peak(MC_CL
);
8404 ns_data
.u
.mb_stats
.total_4kb
= m_peak(MC_BIGCL
);
8405 ns_data
.u
.mb_stats
.total_16kb
= m_peak(MC_16KCL
);
8406 ns_data
.u
.mb_stats
.sbmb_total
= total_sbmb_cnt_peak
;
8407 ns_data
.u
.mb_stats
.sb_atmbuflimit
= sbmb_limreached
;
8408 ns_data
.u
.mb_stats
.draincnt
= mbstat
.m_drain
;
8409 ns_data
.u
.mb_stats
.memreleased
= memreleased
;
8410 ns_data
.u
.mb_stats
.sbmb_floor
= total_sbmb_cnt_floor
;
8412 nstat_sysinfo_send_data(&ns_data
);
8415 * Reset the floor whenever we report a new
8416 * peak to track the trend (increase peek usage
8417 * is not a leak if mbufs get released
8418 * between reports and the floor stays low)
8420 total_sbmb_cnt_floor
= total_sbmb_cnt_peak
;
8424 * Simple routine to avoid taking the lock when we can't run the
8428 mbuf_drain_checks(boolean_t ignore_waiters
)
8430 if (mb_drain_maxint
== 0) {
8433 if (!ignore_waiters
&& mb_waiters
!= 0) {
8441 * Called by the VM when there's memory pressure or when we exhausted
8442 * the 4k/16k reserved space.
8445 mbuf_drain_locked(boolean_t ignore_waiters
)
8448 mcl_slab_t
*sp
, *sp_tmp
, *nsp
;
8449 unsigned int num
, k
, interval
, released
= 0;
8450 unsigned long total_mem
= 0, use_mem
= 0;
8451 boolean_t ret
, purge_caches
= FALSE
;
8455 static unsigned char scratch
[32];
8456 static ppnum_t scratch_pa
= 0;
8458 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_OWNED
);
8459 if (!mbuf_drain_checks(ignore_waiters
)) {
8462 if (scratch_pa
== 0) {
8463 bzero(scratch
, sizeof(scratch
));
8464 scratch_pa
= pmap_find_phys(kernel_pmap
, (addr64_t
)scratch
);
8466 } else if (mclverify
) {
8468 * Panic if a driver wrote to our scratch memory.
8470 for (k
= 0; k
< sizeof(scratch
); k
++) {
8472 panic("suspect DMA to freed address");
8477 * Don't free memory too often as that could cause excessive
8478 * waiting times for mbufs. Purge caches if we were asked to drain
8479 * in the last 5 minutes.
8481 if (mbuf_drain_last_runtime
!= 0) {
8482 interval
= net_uptime() - mbuf_drain_last_runtime
;
8483 if (interval
<= mb_drain_maxint
) {
8486 if (interval
<= mb_drain_maxint
* 5) {
8487 purge_caches
= TRUE
;
8490 mbuf_drain_last_runtime
= net_uptime();
8492 * Don't free any memory if we're using 60% or more.
8494 for (mc
= 0; mc
< NELEM(mbuf_table
); mc
++) {
8495 total_mem
+= m_total(mc
) * m_maxsize(mc
);
8496 use_mem
+= m_active(mc
) * m_maxsize(mc
);
8498 per
= (use_mem
* 100) / total_mem
;
8503 * Purge all the caches. This effectively disables
8504 * caching for a few seconds, but the mbuf worker thread will
8505 * re-enable them again.
8507 if (purge_caches
== TRUE
) {
8508 for (mc
= 0; mc
< NELEM(mbuf_table
); mc
++) {
8509 if (m_total(mc
) < m_avgtotal(mc
)) {
8512 lck_mtx_unlock(mbuf_mlock
);
8513 ret
= mcache_purge_cache(m_cache(mc
), FALSE
);
8514 lck_mtx_lock(mbuf_mlock
);
8521 * Move the objects from the composite class freelist to
8522 * the rudimentary slabs list, but keep at least 10% of the average
8523 * total in the freelist.
8525 for (mc
= 0; mc
< NELEM(mbuf_table
); mc
++) {
8526 while (m_cobjlist(mc
) &&
8527 m_total(mc
) < m_avgtotal(mc
) &&
8528 m_infree(mc
) > 0.1 * m_avgtotal(mc
) + m_minlimit(mc
)) {
8529 obj
= m_cobjlist(mc
);
8530 m_cobjlist(mc
) = obj
->obj_next
;
8531 obj
->obj_next
= NULL
;
8532 num
= cslab_free(mc
, obj
, 1);
8536 /* cslab_free() handles m_total */
8540 * Free the buffers present in the slab list up to 10% of the total
8541 * average per class.
8543 * We walk the list backwards in an attempt to reduce fragmentation.
8545 for (mc
= NELEM(mbuf_table
) - 1; (int)mc
>= 0; mc
--) {
8546 TAILQ_FOREACH_SAFE(sp
, &m_slablist(mc
), sl_link
, sp_tmp
) {
8548 * Process only unused slabs occupying memory.
8550 if (sp
->sl_refcnt
!= 0 || sp
->sl_len
== 0 ||
8551 sp
->sl_base
== NULL
) {
8554 if (m_total(mc
) < m_avgtotal(mc
) ||
8555 m_infree(mc
) < 0.1 * m_avgtotal(mc
) + m_minlimit(mc
)) {
8558 slab_remove(sp
, mc
);
8561 m_infree(mc
) -= NMBPG
;
8562 m_total(mc
) -= NMBPG
;
8563 if (mclaudit
!= NULL
) {
8564 mcl_audit_free(sp
->sl_base
, NMBPG
);
8568 m_infree(mc
) -= NCLPG
;
8569 m_total(mc
) -= NCLPG
;
8570 if (mclaudit
!= NULL
) {
8571 mcl_audit_free(sp
->sl_base
, NMBPG
);
8576 m_infree(mc
) -= NBCLPG
;
8577 m_total(mc
) -= NBCLPG
;
8578 if (mclaudit
!= NULL
) {
8579 mcl_audit_free(sp
->sl_base
, NMBPG
);
8586 for (nsp
= sp
, k
= 1; k
< NSLABSP16KB
; k
++) {
8588 VERIFY(nsp
->sl_refcnt
== 0 &&
8589 nsp
->sl_base
!= NULL
&&
8591 slab_init(nsp
, 0, 0, NULL
, NULL
, 0, 0,
8595 if (mclaudit
!= NULL
) {
8596 if (sp
->sl_len
== PAGE_SIZE
) {
8597 mcl_audit_free(sp
->sl_base
,
8600 mcl_audit_free(sp
->sl_base
, 1);
8606 * The composite classes have their own
8607 * freelist (m_cobjlist), so we only
8608 * process rudimentary classes here.
8612 m_release_cnt(mc
) += m_size(mc
);
8613 released
+= m_size(mc
);
8614 VERIFY(sp
->sl_base
!= NULL
&&
8615 sp
->sl_len
>= PAGE_SIZE
);
8616 offset
= MTOPG(sp
->sl_base
);
8618 * Make sure the IOMapper points to a valid, but
8619 * bogus, address. This should prevent further DMA
8620 * accesses to freed memory.
8622 IOMapperInsertPage(mcl_paddr_base
, offset
, scratch_pa
);
8623 mcl_paddr
[offset
] = 0;
8624 kmem_free(mb_map
, (vm_offset_t
)sp
->sl_base
,
8626 slab_init(sp
, 0, 0, NULL
, NULL
, 0, 0, 0);
8631 mbstat
.m_bigclusters
= m_total(MC_BIGCL
);
8632 mbstat
.m_clusters
= m_total(MC_CL
);
8633 mbstat
.m_mbufs
= m_total(MC_MBUF
);
8635 mbuf_mtypes_sync(TRUE
);
8638 __private_extern__
void
8639 mbuf_drain(boolean_t ignore_waiters
)
8641 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_NOTOWNED
);
8642 if (!mbuf_drain_checks(ignore_waiters
)) {
8645 lck_mtx_lock(mbuf_mlock
);
8646 mbuf_drain_locked(ignore_waiters
);
8647 lck_mtx_unlock(mbuf_mlock
);
8652 m_drain_force_sysctl SYSCTL_HANDLER_ARGS
8654 #pragma unused(arg1, arg2)
8657 err
= sysctl_handle_int(oidp
, &val
, 0, req
);
8658 if (err
!= 0 || req
->newptr
== USER_ADDR_NULL
) {
8668 #if DEBUG || DEVELOPMENT
8670 _mbwdog_logger(const char *func
, const int line
, const char *fmt
, ...)
8674 char str
[384], p
[256];
8677 LCK_MTX_ASSERT(mbuf_mlock
, LCK_MTX_ASSERT_OWNED
);
8678 if (mbwdog_logging
== NULL
) {
8679 mbwdog_logging
= _MALLOC(mbwdog_logging_size
,
8680 M_TEMP
, M_ZERO
| M_NOWAIT
);
8681 if (mbwdog_logging
== NULL
) {
8686 vsnprintf(p
, sizeof(p
), fmt
, ap
);
8689 len
= snprintf(str
, sizeof(str
),
8690 "\n%ld.%d (%d/%llx) %s:%d %s",
8691 now
.tv_sec
, now
.tv_usec
,
8692 current_proc()->p_pid
,
8693 (uint64_t)VM_KERNEL_ADDRPERM(current_thread()),
8698 if (mbwdog_logging_used
+ len
> mbwdog_logging_size
) {
8699 mbwdog_logging_used
= mbwdog_logging_used
/ 2;
8700 memmove(mbwdog_logging
, mbwdog_logging
+ mbwdog_logging_used
,
8701 mbwdog_logging_size
- mbwdog_logging_used
);
8702 mbwdog_logging
[mbwdog_logging_used
] = 0;
8704 strlcat(mbwdog_logging
, str
, mbwdog_logging_size
);
8705 mbwdog_logging_used
+= len
;
8709 sysctl_mbwdog_log SYSCTL_HANDLER_ARGS
8711 #pragma unused(oidp, arg1, arg2)
8712 return SYSCTL_OUT(req
, mbwdog_logging
, mbwdog_logging_used
);
8714 SYSCTL_DECL(_kern_ipc
);
8715 SYSCTL_PROC(_kern_ipc
, OID_AUTO
, mbwdog_log
,
8716 CTLTYPE_STRING
| CTLFLAG_RD
| CTLFLAG_LOCKED
,
8717 0, 0, sysctl_mbwdog_log
, "A", "");
8719 static int mbtest_val
;
8720 static int mbtest_running
;
8723 mbtest_thread(__unused
void *arg
)
8727 int iterations
= 250;
8728 int allocations
= nmbclusters
;
8729 iterations
= iterations
/ scale_down
;
8730 allocations
= allocations
/ scale_down
;
8731 printf("%s thread starting\n", __func__
);
8732 for (i
= 0; i
< iterations
; i
++) {
8733 unsigned int needed
= allocations
;
8734 struct mbuf
*m1
, *m2
, *m3
;
8737 needed
= allocations
;
8738 m3
= m_getpackets_internal(&needed
, 0, M_DONTWAIT
, 0, M16KCLBYTES
);
8742 needed
= allocations
;
8743 m2
= m_getpackets_internal(&needed
, 0, M_DONTWAIT
, 0, MBIGCLBYTES
);
8746 m1
= m_getpackets_internal(&needed
, 0, M_DONTWAIT
, 0, MCLBYTES
);
8750 printf("%s thread ending\n", __func__
);
8752 OSDecrementAtomic(&mbtest_running
);
8753 wakeup_one((caddr_t
)&mbtest_running
);
8759 /* We launch three threads - wait for all of them */
8760 OSIncrementAtomic(&mbtest_running
);
8761 OSIncrementAtomic(&mbtest_running
);
8762 OSIncrementAtomic(&mbtest_running
);
8764 thread_call_func_delayed((thread_call_func_t
)mbtest_thread
, NULL
, 10);
8765 thread_call_func_delayed((thread_call_func_t
)mbtest_thread
, NULL
, 10);
8766 thread_call_func_delayed((thread_call_func_t
)mbtest_thread
, NULL
, 10);
8768 while (mbtest_running
) {
8769 msleep((caddr_t
)&mbtest_running
, NULL
, PUSER
, "mbtest_running", NULL
);
8774 mbtest SYSCTL_HANDLER_ARGS
8776 #pragma unused(arg1, arg2)
8777 int error
= 0, val
, oldval
= mbtest_val
;
8780 error
= sysctl_handle_int(oidp
, &val
, 0, req
);
8781 if (error
|| !req
->newptr
) {
8785 if (val
!= oldval
) {
8793 #endif // DEBUG || DEVELOPMENT
8796 mtracelarge_register(size_t size
)
8799 struct mtracelarge
*trace
;
8800 uintptr_t bt
[MLEAK_STACK_DEPTH
];
8803 depth
= backtrace(bt
, MLEAK_STACK_DEPTH
);
8804 /* Check if this entry is already on the list. */
8805 for (i
= 0; i
< MTRACELARGE_NUM_TRACES
; i
++) {
8806 trace
= &mtracelarge_table
[i
];
8807 if (trace
->size
== size
&& trace
->depth
== depth
&&
8808 memcmp(bt
, trace
->addr
, depth
* sizeof(uintptr_t)) == 0) {
8812 for (i
= 0; i
< MTRACELARGE_NUM_TRACES
; i
++) {
8813 trace
= &mtracelarge_table
[i
];
8814 if (size
> trace
->size
) {
8815 trace
->depth
= depth
;
8816 memcpy(trace
->addr
, bt
, depth
* sizeof(uintptr_t));
8823 SYSCTL_DECL(_kern_ipc
);
8824 #if DEBUG || DEVELOPMENT
8825 SYSCTL_PROC(_kern_ipc
, OID_AUTO
, mbtest
,
8826 CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
, &mbtest_val
, 0, &mbtest
, "I",
8827 "Toggle to test mbufs");
8829 SYSCTL_PROC(_kern_ipc
, KIPC_MBSTAT
, mbstat
,
8830 CTLTYPE_STRUCT
| CTLFLAG_RD
| CTLFLAG_LOCKED
,
8831 0, 0, mbstat_sysctl
, "S,mbstat", "");
8832 SYSCTL_PROC(_kern_ipc
, OID_AUTO
, mb_stat
,
8833 CTLTYPE_STRUCT
| CTLFLAG_RD
| CTLFLAG_LOCKED
,
8834 0, 0, mb_stat_sysctl
, "S,mb_stat", "");
8835 SYSCTL_PROC(_kern_ipc
, OID_AUTO
, mleak_top_trace
,
8836 CTLTYPE_STRUCT
| CTLFLAG_RD
| CTLFLAG_LOCKED
,
8837 0, 0, mleak_top_trace_sysctl
, "S,mb_top_trace", "");
8838 SYSCTL_PROC(_kern_ipc
, OID_AUTO
, mleak_table
,
8839 CTLTYPE_STRUCT
| CTLFLAG_RD
| CTLFLAG_LOCKED
,
8840 0, 0, mleak_table_sysctl
, "S,mleak_table", "");
8841 SYSCTL_INT(_kern_ipc
, OID_AUTO
, mleak_sample_factor
,
8842 CTLFLAG_RW
| CTLFLAG_LOCKED
, &mleak_table
.mleak_sample_factor
, 0, "");
8843 SYSCTL_INT(_kern_ipc
, OID_AUTO
, mb_normalized
,
8844 CTLFLAG_RD
| CTLFLAG_LOCKED
, &mb_normalized
, 0, "");
8845 SYSCTL_INT(_kern_ipc
, OID_AUTO
, mb_watchdog
,
8846 CTLFLAG_RW
| CTLFLAG_LOCKED
, &mb_watchdog
, 0, "");
8847 SYSCTL_PROC(_kern_ipc
, OID_AUTO
, mb_drain_force
,
8848 CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
, NULL
, 0,
8849 m_drain_force_sysctl
, "I",
8850 "Forces the mbuf garbage collection to run");
8851 SYSCTL_INT(_kern_ipc
, OID_AUTO
, mb_drain_maxint
,
8852 CTLFLAG_RW
| CTLFLAG_LOCKED
, &mb_drain_maxint
, 0,
8853 "Minimum time interval between garbage collection");