]> git.saurik.com Git - apple/xnu.git/blame - bsd/kern/uipc_mbuf.c
xnu-6153.41.3.tar.gz
[apple/xnu.git] / bsd / kern / uipc_mbuf.c
CommitLineData
1c79356b 1/*
cb323159 2 * Copyright (c) 1998-2019 Apple Inc. All rights reserved.
5d5c5d0d 3 *
2d21ac55
A
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
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.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
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
8f6c56a5
A
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
2d21ac55
A
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.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
1c79356b
A
27 */
28/* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
29/*
30 * Copyright (c) 1982, 1986, 1988, 1991, 1993
31 * The Regents of the University of California. All rights reserved.
32 *
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
35 * are met:
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.
48 *
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
59 * SUCH DAMAGE.
60 *
61 * @(#)uipc_mbuf.c 8.2 (Berkeley) 1/4/94
62 */
2d21ac55
A
63/*
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,
67 * Version 2.0.
1c79356b
A
68 */
69
70#include <sys/param.h>
71#include <sys/systm.h>
72#include <sys/malloc.h>
73#include <sys/mbuf.h>
74#include <sys/kernel.h>
91447636 75#include <sys/sysctl.h>
1c79356b
A
76#include <sys/syslog.h>
77#include <sys/protosw.h>
78#include <sys/domain.h>
2d21ac55 79#include <sys/queue.h>
b0d623f7 80#include <sys/proc.h>
1c79356b 81
39236c6e
A
82#include <dev/random/randomdev.h>
83
9bccf70c 84#include <kern/kern_types.h>
2d21ac55
A
85#include <kern/simple_lock.h>
86#include <kern/queue.h>
9bccf70c 87#include <kern/sched_prim.h>
39037602 88#include <kern/backtrace.h>
2d21ac55 89#include <kern/cpu_number.h>
6d2010ae 90#include <kern/zalloc.h>
2d21ac55
A
91
92#include <libkern/OSAtomic.h>
39236c6e 93#include <libkern/OSDebug.h>
2d21ac55 94#include <libkern/libkern.h>
9bccf70c 95
a39ff7e2
A
96#include <os/log.h>
97
55e303ae
A
98#include <IOKit/IOMapper.h>
99
2d21ac55
A
100#include <machine/limits.h>
101#include <machine/machine_routines.h>
55e303ae 102
2d21ac55
A
103#if CONFIG_MACF_NET
104#include <security/mac_framework.h>
105#endif /* MAC_NET */
106
107#include <sys/mcache.h>
fe8ab488 108#include <net/ntstat.h>
1c79356b 109
2d21ac55
A
110/*
111 * MBUF IMPLEMENTATION NOTES.
112 *
113 * There is a total of 5 per-CPU caches:
114 *
115 * MC_MBUF:
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.
119 *
120 * MC_CL:
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.
124 *
125 * MC_BIGCL:
6d2010ae 126 * This is a cache of rudimentary objects of MBIGCLBYTES in size; each
2d21ac55
A
127 * object represents a mbigcluster structure. This cache does not
128 * preserve the contents of the objects during its transaction.
129 *
130 * MC_MBUF_CL:
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.
135 *
136 * MC_MBUF_BIGCL:
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.
141 *
142 * OBJECT ALLOCATION:
143 *
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:
152 *
153 * a. Rudimentary object:
154 *
155 * { m_get_common(), m_clattach(), m_mclget(),
156 * m_mclalloc(), m_bigalloc(), m_copym_with_hdrs(),
157 * composite object allocation }
158 * | ^
159 * | |
160 * | +-----------------------+
161 * v |
162 * mcache_alloc/mcache_alloc_ext() mbuf_slab_audit()
163 * | ^
164 * v |
165 * [CPU cache] -------> (found?) -------+
166 * | |
167 * v |
168 * mbuf_slab_alloc() |
169 * | |
170 * v |
171 * +---------> [freelist] -------> (found?) -------+
172 * | |
173 * | v
174 * | m_clalloc()
175 * | |
176 * | v
177 * +---<<---- kmem_mb_alloc()
178 *
179 * b. Composite object:
180 *
181 * { m_getpackets_internal(), m_allocpacket_internal() }
182 * | ^
183 * | |
184 * | +------ (done) ---------+
185 * v |
186 * mcache_alloc/mcache_alloc_ext() mbuf_cslab_audit()
187 * | ^
188 * v |
189 * [CPU cache] -------> (found?) -------+
190 * | |
191 * v |
192 * mbuf_cslab_alloc() |
193 * | |
194 * v |
195 * [freelist] -------> (found?) -------+
196 * | |
197 * v |
198 * (rudimentary object) |
199 * mcache_alloc/mcache_alloc_ext() ------>>-----+
200 *
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.
207 *
208 * OBJECT DEALLOCATION:
209 *
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:
216 *
217 * a. Rudimentary object:
218 *
219 * { m_free(), m_freem_list(), composite object deallocation }
220 * | ^
221 * | |
222 * | +------ (done) ---------+
223 * v |
224 * mcache_free/mcache_free_ext() |
225 * | |
226 * v |
227 * mbuf_slab_audit() |
228 * | |
229 * v |
230 * [CPU cache] ---> (not purging?) -----+
231 * | |
232 * v |
233 * mbuf_slab_free() |
234 * | |
235 * v |
236 * [freelist] ----------->>------------+
3e170ce0 237 * (objects get purged to VM only on demand)
2d21ac55
A
238 *
239 * b. Composite object:
240 *
241 * { m_free(), m_freem_list() }
242 * | ^
243 * | |
244 * | +------ (done) ---------+
245 * v |
246 * mcache_free/mcache_free_ext() |
247 * | |
248 * v |
249 * mbuf_cslab_audit() |
250 * | |
251 * v |
252 * [CPU cache] ---> (not purging?) -----+
253 * | |
254 * v |
255 * mbuf_cslab_free() |
256 * | |
257 * v |
258 * [freelist] ---> (not purging?) -----+
259 * | |
260 * v |
261 * (rudimentary object) |
262 * mcache_free/mcache_free_ext() ------->>------+
263 *
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.
269 *
270 * DEBUGGING:
271 *
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,
6d2010ae
A
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.
2d21ac55
A
278 *
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:
283 *
284 * +------------+ +=============+
285 * | mbuf addr | | mclaudit[i] |
286 * +------------+ +=============+
287 * | | cl_audit[0] |
6d2010ae 288 * i = MTOBG(addr) +-------------+
2d21ac55 289 * | +-----> | cl_audit[1] | -----> mcache_audit_t
6d2010ae 290 * b = BGTOM(i) | +-------------+
2d21ac55
A
291 * | | | ... |
292 * x = MCLIDX(b, addr) | +-------------+
293 * | | | cl_audit[7] |
294 * +-----------------+ +-------------+
295 * (e.g. x == 1)
296 *
297 * The mclaudit[] array is allocated at initialization time, but its contents
6d2010ae 298 * get populated when the corresponding cluster is created. Because a page
3e170ce0 299 * can be turned into NMBPG number of mbufs, we preserve enough space for the
6d2010ae 300 * mbufs so that there is a 1-to-1 mapping between them. A page that never
2d21ac55 301 * gets (or has not yet) turned into mbufs will use only cl_audit[0] with the
6d2010ae
A
302 * remaining entries unused. For 16KB cluster, only one entry from the first
303 * page is allocated and used for the entire object.
2d21ac55 304 */
91447636 305
2d21ac55
A
306/* TODO: should be in header file */
307/* kernel translater */
cc8bc92a 308extern vm_offset_t kmem_mb_alloc(vm_map_t, int, int, kern_return_t *);
2d21ac55 309extern ppnum_t pmap_find_phys(pmap_t pmap, addr64_t va);
0a7de745 310extern vm_map_t mb_map; /* special map */
2d21ac55 311
cc8bc92a
A
312static uint32_t mb_kmem_contig_failed;
313static uint32_t mb_kmem_failed;
314static uint32_t mb_kmem_one_failed;
315/* Timestamp of allocation failures. */
316static uint64_t mb_kmem_contig_failed_ts;
317static uint64_t mb_kmem_failed_ts;
318static uint64_t mb_kmem_one_failed_ts;
319static uint64_t mb_kmem_contig_failed_size;
320static uint64_t mb_kmem_failed_size;
321static uint32_t mb_kmem_stats[6];
322static const char *mb_kmem_stats_labels[] = { "INVALID_ARGUMENT",
0a7de745
A
323 "INVALID_ADDRESS",
324 "RESOURCE_SHORTAGE",
325 "NO_SPACE",
326 "KERN_FAILURE",
327 "OTHERS" };
cc8bc92a 328
2d21ac55 329/* Global lock */
316670eb
A
330decl_lck_mtx_data(static, mbuf_mlock_data);
331static lck_mtx_t *mbuf_mlock = &mbuf_mlock_data;
2d21ac55
A
332static lck_attr_t *mbuf_mlock_attr;
333static lck_grp_t *mbuf_mlock_grp;
334static lck_grp_attr_t *mbuf_mlock_grp_attr;
335
336/* Back-end (common) layer */
cc8bc92a
A
337static uint64_t mb_expand_cnt;
338static uint64_t mb_expand_cl_cnt;
339static uint64_t mb_expand_cl_total;
340static uint64_t mb_expand_bigcl_cnt;
341static uint64_t mb_expand_bigcl_total;
342static uint64_t mb_expand_16kcl_cnt;
343static uint64_t mb_expand_16kcl_total;
39037602 344static boolean_t mbuf_worker_needs_wakeup; /* wait channel for mbuf worker */
cc8bc92a
A
345static uint32_t mbuf_worker_run_cnt;
346static uint64_t mbuf_worker_last_runtime;
d9a64523 347static uint64_t mbuf_drain_last_runtime;
0a7de745
A
348static int mbuf_worker_ready; /* worker thread is runnable */
349static int ncpu; /* number of CPUs */
350static ppnum_t *mcl_paddr; /* Array of cluster physical addresses */
351static ppnum_t mcl_pages; /* Size of array (# physical pages) */
352static ppnum_t mcl_paddr_base; /* Handle returned by IOMapper::iovmAlloc() */
353static mcache_t *ref_cache; /* Cache of cluster reference & flags */
2d21ac55 354static mcache_t *mcl_audit_con_cache; /* Audit contents cache */
0a7de745 355static unsigned int mbuf_debug; /* patchable mbuf mcache flags */
2d21ac55 356static unsigned int mb_normalized; /* number of packets "normalized" */
b0d623f7 357
0a7de745
A
358#define MB_GROWTH_AGGRESSIVE 1 /* Threshold: 1/2 of total */
359#define MB_GROWTH_NORMAL 2 /* Threshold: 3/4 of total */
2d21ac55
A
360
361typedef enum {
0a7de745
A
362 MC_MBUF = 0, /* Regular mbuf */
363 MC_CL, /* Cluster */
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 */
2d21ac55
A
369} mbuf_class_t;
370
0a7de745
A
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) \
2d21ac55 375 ((int)(c) >= MBUF_CLASS_MIN && (int)(c) <= MBUF_CLASS_MAX)
0a7de745 376#define MBUF_CLASS_COMPOSITE(c) \
2d21ac55 377 ((int)(c) > MBUF_CLASS_LAST)
91447636 378
9bccf70c 379
2d21ac55
A
380/*
381 * mbuf specific mcache allocation request flags.
382 */
0a7de745 383#define MCR_COMP MCR_USR1 /* for MC_MBUF_{CL,BIGCL,16KCL} caches */
9bccf70c 384
2d21ac55
A
385/*
386 * Per-cluster slab structure.
387 *
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.
396 *
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.
402 *
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.
6d2010ae
A
407 *
408 * Each slab controls a page of memory.
2d21ac55
A
409 */
410typedef struct mcl_slab {
0a7de745
A
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 */
2d21ac55
A
420} mcl_slab_t;
421
0a7de745
A
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 */
1c79356b 425
2d21ac55
A
426/*
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
430 * boundary.
431 */
0a7de745 432#define NSLABSPMB ((1 << MBSHIFT) >> PAGE_SHIFT)
91447636 433
2d21ac55 434typedef struct mcl_slabg {
0a7de745 435 mcl_slab_t *slg_slab; /* group of slabs */
2d21ac55 436} mcl_slabg_t;
1c79356b 437
6d2010ae
A
438/*
439 * Number of slabs needed to control a 16KB cluster object.
440 */
0a7de745 441#define NSLABSP16KB (M16KCLBYTES >> PAGE_SHIFT)
6d2010ae 442
2d21ac55
A
443/*
444 * Per-cluster audit structure.
445 */
446typedef struct {
0a7de745 447 mcache_audit_t **cl_audit; /* array of audits */
2d21ac55 448} mcl_audit_t;
91447636 449
39236c6e 450typedef struct {
0a7de745
A
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];
39236c6e
A
459} mcl_scratch_audit_t;
460
461typedef struct {
462 /*
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.
471 */
0a7de745
A
472 u_int8_t sc_mbuf[(MSIZE - _MHLEN) + sizeof(_m_ext_t)];
473 mcl_scratch_audit_t sc_scratch __attribute__((aligned(8)));
39236c6e
A
474} mcl_saved_contents_t;
475
0a7de745 476#define AUDIT_CONTENTS_SIZE (sizeof (mcl_saved_contents_t))
39236c6e 477
0a7de745
A
478#define MCA_SAVED_MBUF_PTR(_mca) \
479 ((struct mbuf *)(void *)((mcl_saved_contents_t *) \
39236c6e 480 (_mca)->mca_contents)->sc_mbuf)
0a7de745 481#define MCA_SAVED_MBUF_SIZE \
39236c6e 482 (sizeof (((mcl_saved_contents_t *)0)->sc_mbuf))
0a7de745 483#define MCA_SAVED_SCRATCH_PTR(_mca) \
39236c6e 484 (&((mcl_saved_contents_t *)(_mca)->mca_contents)->sc_scratch)
fa4905b1 485
2d21ac55
A
486/*
487 * mbuf specific mcache audit flags
488 */
0a7de745
A
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 */
fa4905b1 492
2d21ac55
A
493/*
494 * Each of the following two arrays hold up to nmbclusters elements.
495 */
0a7de745
A
496static mcl_audit_t *mclaudit; /* array of cluster audit information */
497static unsigned int maxclaudit; /* max # of entries in audit table */
498static mcl_slabg_t **slabstbl; /* cluster slabs table */
499static unsigned int maxslabgrp; /* max # of entries in slabs table */
500static unsigned int slabgrp; /* # of entries in slabs table */
2d21ac55
A
501
502/* Globals */
0a7de745
A
503int nclusters; /* # of clusters for non-jumbo (legacy) sizes */
504int njcl; /* # of clusters for jumbo sizes */
505int njclbytes; /* size of a jumbo cluster */
506unsigned char *mbutl; /* first mapped cluster address */
507unsigned char *embutl; /* ending virtual address of mclusters */
508int _max_linkhdr; /* largest link-level header */
509int _max_protohdr; /* largest protocol header */
510int max_hdr; /* largest link+protocol header */
511int max_datalen; /* MHLEN - max_hdr */
512
513static boolean_t mclverify; /* debug: pattern-checking */
514static boolean_t mcltrace; /* debug: stack tracing */
515static boolean_t mclfindleak; /* debug: leak detection */
516static boolean_t mclexpleak; /* debug: expose leak info to user space */
517
518static struct timeval mb_start; /* beginning of time */
39236c6e 519
6d2010ae
A
520/* mbuf leak detection variables */
521static struct mleak_table mleak_table;
522static mleak_stat_t *mleak_stat;
523
0a7de745 524#define MLEAK_STAT_SIZE(n) \
5ba3f43e 525 __builtin_offsetof(mleak_stat_t, ml_trace[n])
6d2010ae
A
526
527struct mallocation {
0a7de745
A
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 */
6d2010ae
A
532};
533
534struct mtrace {
0a7de745
A
535 u_int64_t collisions;
536 u_int64_t hitcount;
537 u_int64_t allocs;
538 u_int64_t depth;
539 uintptr_t addr[MLEAK_STACK_DEPTH];
6d2010ae
A
540};
541
542/* Size must be a power of two for the zhash to be able to just mask off bits */
0a7de745
A
543#define MLEAK_ALLOCATION_MAP_NUM 512
544#define MLEAK_TRACE_MAP_NUM 256
6d2010ae
A
545
546/*
547 * Sample factor for how often to record a trace. This is overwritable
548 * by the boot-arg mleak_sample_factor.
549 */
0a7de745 550#define MLEAK_SAMPLE_FACTOR 500
6d2010ae
A
551
552/*
553 * Number of top leakers recorded.
554 */
0a7de745 555#define MLEAK_NUM_TRACES 5
6d2010ae 556
0a7de745 557#define MB_LEAK_SPACING_64 " "
316670eb
A
558#define MB_LEAK_SPACING_32 " "
559
560
0a7de745 561#define MB_LEAK_HDR_32 "\n\
316670eb
A
562 trace [1] trace [2] trace [3] trace [4] trace [5] \n\
563 ---------- ---------- ---------- ---------- ---------- \n\
564"
565
0a7de745 566#define MB_LEAK_HDR_64 "\n\
316670eb 567 trace [1] trace [2] trace [3] \
0a7de745 568 trace [4] trace [5] \n\
316670eb
A
569 ------------------ ------------------ ------------------ \
570 ------------------ ------------------ \n\
571"
572
6d2010ae
A
573static uint32_t mleak_alloc_buckets = MLEAK_ALLOCATION_MAP_NUM;
574static uint32_t mleak_trace_buckets = MLEAK_TRACE_MAP_NUM;
575
576/* Hashmaps of allocations and their corresponding traces */
577static struct mallocation *mleak_allocations;
578static struct mtrace *mleak_traces;
579static struct mtrace *mleak_top_trace[MLEAK_NUM_TRACES];
580
581/* Lock to protect mleak tables from concurrent modification */
316670eb
A
582decl_lck_mtx_data(static, mleak_lock_data);
583static lck_mtx_t *mleak_lock = &mleak_lock_data;
6d2010ae
A
584static lck_attr_t *mleak_lock_attr;
585static lck_grp_t *mleak_lock_grp;
586static lck_grp_attr_t *mleak_lock_grp_attr;
587
5c9f4661
A
588/* *Failed* large allocations. */
589struct mtracelarge {
0a7de745
A
590 uint64_t size;
591 uint64_t depth;
592 uintptr_t addr[MLEAK_STACK_DEPTH];
5c9f4661
A
593};
594
0a7de745 595#define MTRACELARGE_NUM_TRACES 5
5c9f4661
A
596static struct mtracelarge mtracelarge_table[MTRACELARGE_NUM_TRACES];
597
598static void mtracelarge_register(size_t size);
599
39037602
A
600/* Lock to protect the completion callback table */
601static lck_grp_attr_t *mbuf_tx_compl_tbl_lck_grp_attr = NULL;
602static lck_attr_t *mbuf_tx_compl_tbl_lck_attr = NULL;
603static lck_grp_t *mbuf_tx_compl_tbl_lck_grp = NULL;
604decl_lck_rw_data(, mbuf_tx_compl_tbl_lck_rw_data);
605lck_rw_t *mbuf_tx_compl_tbl_lock = &mbuf_tx_compl_tbl_lck_rw_data;
606
b0d623f7
A
607extern u_int32_t high_sb_max;
608
2d21ac55 609/* The minimum number of objects that are allocated, to start. */
0a7de745
A
610#define MINCL 32
611#define MINBIGCL (MINCL >> 1)
612#define MIN16KCL (MINCL >> 2)
2d21ac55
A
613
614/* Low watermarks (only map in pages once free counts go below) */
0a7de745
A
615#define MBIGCL_LOWAT MINBIGCL
616#define M16KCL_LOWAT MIN16KCL
2d21ac55
A
617
618typedef struct {
0a7de745
A
619 mbuf_class_t mtbl_class; /* class type */
620 mcache_t *mtbl_cache; /* mcache for this buffer class */
2d21ac55 621 TAILQ_HEAD(mcl_slhead, mcl_slab) mtbl_slablist; /* slab list */
0a7de745
A
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 */
2d21ac55
A
630} mbuf_table_t;
631
0a7de745
A
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
2d21ac55
A
655
656static mbuf_table_t mbuf_table[] = {
657 /*
658 * The caches for mbufs, regular clusters and big clusters.
fe8ab488
A
659 * The average total values were based on data gathered by actual
660 * usage patterns on iOS.
2d21ac55
A
661 */
662 { MC_MBUF, NULL, TAILQ_HEAD_INITIALIZER(m_slablist(MC_MBUF)),
0a7de745 663 NULL, NULL, 0, 0, 0, 0, 3000, 0 },
2d21ac55 664 { MC_CL, NULL, TAILQ_HEAD_INITIALIZER(m_slablist(MC_CL)),
0a7de745 665 NULL, NULL, 0, 0, 0, 0, 2000, 0 },
2d21ac55 666 { MC_BIGCL, NULL, TAILQ_HEAD_INITIALIZER(m_slablist(MC_BIGCL)),
0a7de745 667 NULL, NULL, 0, 0, 0, 0, 1000, 0 },
2d21ac55 668 { MC_16KCL, NULL, TAILQ_HEAD_INITIALIZER(m_slablist(MC_16KCL)),
0a7de745 669 NULL, NULL, 0, 0, 0, 0, 200, 0 },
2d21ac55
A
670 /*
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.
677 */
5ba3f43e
A
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 },
2d21ac55
A
681};
682
0a7de745 683#define NELEM(a) (sizeof (a) / sizeof ((a)[0]))
2d21ac55 684
a39ff7e2
A
685
686static uint32_t
687m_avgtotal(mbuf_class_t c)
688{
0a7de745 689 return mbuf_table[c].mtbl_avgtotal;
a39ff7e2
A
690}
691
0a7de745
A
692static void *mb_waitchan = &mbuf_table; /* wait channel for all caches */
693static int mb_waiters; /* number of waiters */
6d2010ae 694
fe8ab488
A
695boolean_t mb_peak_newreport = FALSE;
696boolean_t mb_peak_firstreport = FALSE;
697
698/* generate a report by default after 1 week of uptime */
0a7de745 699#define MBUF_PEAK_FIRST_REPORT_THRESHOLD 604800
fe8ab488 700
0a7de745
A
701#define MB_WDT_MAXTIME 10 /* # of secs before watchdog panic */
702static struct timeval mb_wdtstart; /* watchdog start timestamp */
316670eb
A
703static char *mbuf_dump_buf;
704
0a7de745 705#define MBUF_DUMP_BUF_SIZE 4096
6d2010ae
A
706
707/*
0a7de745
A
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.
fe8ab488 711 * mb_drain_maxint controls the amount of time to wait (in seconds) before
d9a64523 712 * consecutive calls to mbuf_drain().
6d2010ae 713 */
0a7de745 714#if CONFIG_EMBEDDED || DEVELOPMENT || DEBUG
5ba3f43e 715static unsigned int mb_watchdog = 1;
5ba3f43e 716#else
6d2010ae 717static unsigned int mb_watchdog = 0;
0a7de745
A
718#endif
719#if CONFIG_EMBEDDED
720static unsigned int mb_drain_maxint = 60;
721#else
fe8ab488 722static unsigned int mb_drain_maxint = 0;
5ba3f43e 723#endif /* CONFIG_EMBEDDED */
39236c6e 724
813fb2f6
A
725uintptr_t mb_obscure_extfree __attribute__((visibility("hidden")));
726uintptr_t mb_obscure_extref __attribute__((visibility("hidden")));
727
39236c6e
A
728/* Red zone */
729static u_int32_t mb_redzone_cookie;
730static void m_redzone_init(struct mbuf *);
731static void m_redzone_verify(struct mbuf *m);
2d21ac55
A
732
733/* The following are used to serialize m_clalloc() */
734static boolean_t mb_clalloc_busy;
735static void *mb_clalloc_waitchan = &mb_clalloc_busy;
736static int mb_clalloc_waiters;
737
6d2010ae 738static void mbuf_mtypes_sync(boolean_t);
2d21ac55 739static int mbstat_sysctl SYSCTL_HANDLER_ARGS;
6d2010ae 740static void mbuf_stat_sync(void);
2d21ac55 741static int mb_stat_sysctl SYSCTL_HANDLER_ARGS;
6d2010ae
A
742static int mleak_top_trace_sysctl SYSCTL_HANDLER_ARGS;
743static int mleak_table_sysctl SYSCTL_HANDLER_ARGS;
744static char *mbuf_dump(void);
2d21ac55
A
745static void mbuf_table_init(void);
746static inline void m_incref(struct mbuf *);
39037602 747static inline u_int16_t m_decref(struct mbuf *);
2d21ac55
A
748static int m_clalloc(const u_int32_t, const int, const u_int32_t);
749static void mbuf_worker_thread_init(void);
750static mcache_obj_t *slab_alloc(mbuf_class_t, int);
751static void slab_free(mbuf_class_t, mcache_obj_t *);
752static unsigned int mbuf_slab_alloc(void *, mcache_obj_t ***,
753 unsigned int, int);
754static void mbuf_slab_free(void *, mcache_obj_t *, int);
755static void mbuf_slab_audit(void *, mcache_obj_t *, boolean_t);
756static void mbuf_slab_notify(void *, u_int32_t);
757static unsigned int cslab_alloc(mbuf_class_t, mcache_obj_t ***,
758 unsigned int);
759static unsigned int cslab_free(mbuf_class_t, mcache_obj_t *, int);
760static unsigned int mbuf_cslab_alloc(void *, mcache_obj_t ***,
761 unsigned int, int);
762static void mbuf_cslab_free(void *, mcache_obj_t *, int);
763static void mbuf_cslab_audit(void *, mcache_obj_t *, boolean_t);
764static int freelist_populate(mbuf_class_t, unsigned int, int);
6d2010ae 765static void freelist_init(mbuf_class_t);
2d21ac55
A
766static boolean_t mbuf_cached_above(mbuf_class_t, int);
767static boolean_t mbuf_steal(mbuf_class_t, unsigned int);
768static void m_reclaim(mbuf_class_t, unsigned int, boolean_t);
769static int m_howmany(int, size_t);
770static void mbuf_worker_thread(void);
6d2010ae 771static void mbuf_watchdog(void);
2d21ac55
A
772static boolean_t mbuf_sleep(mbuf_class_t, unsigned int, int);
773
774static void mcl_audit_init(void *, mcache_audit_t **, mcache_obj_t **,
775 size_t, unsigned int);
fe8ab488 776static void mcl_audit_free(void *, unsigned int);
2d21ac55
A
777static mcache_audit_t *mcl_audit_buf2mca(mbuf_class_t, mcache_obj_t *);
778static void mcl_audit_mbuf(mcache_audit_t *, void *, boolean_t, boolean_t);
779static void mcl_audit_cluster(mcache_audit_t *, void *, size_t, boolean_t,
780 boolean_t);
781static void mcl_audit_restore_mbuf(struct mbuf *, mcache_audit_t *, boolean_t);
782static void mcl_audit_save_mbuf(struct mbuf *, mcache_audit_t *);
39236c6e 783static void mcl_audit_scratch(mcache_audit_t *);
2d21ac55
A
784static void mcl_audit_mcheck_panic(struct mbuf *);
785static void mcl_audit_verify_nextptr(void *, mcache_audit_t *);
786
6d2010ae
A
787static void mleak_activate(void);
788static void mleak_logger(u_int32_t, mcache_obj_t *, boolean_t);
789static boolean_t mleak_log(uintptr_t *, mcache_obj_t *, uint32_t, int);
790static void mleak_free(mcache_obj_t *);
316670eb
A
791static void mleak_sort_traces(void);
792static void mleak_update_stats(void);
6d2010ae 793
2d21ac55
A
794static mcl_slab_t *slab_get(void *);
795static void slab_init(mcl_slab_t *, mbuf_class_t, u_int32_t,
796 void *, void *, unsigned int, int, int);
797static void slab_insert(mcl_slab_t *, mbuf_class_t);
798static void slab_remove(mcl_slab_t *, mbuf_class_t);
799static boolean_t slab_inrange(mcl_slab_t *, void *);
800static void slab_nextptr_panic(mcl_slab_t *, void *);
801static void slab_detach(mcl_slab_t *);
802static boolean_t slab_is_detached(mcl_slab_t *);
803
b0d623f7
A
804static int m_copyback0(struct mbuf **, int, int, const void *, int, int);
805static struct mbuf *m_split0(struct mbuf *, int, int, int);
fe8ab488
A
806__private_extern__ void mbuf_report_peak_usage(void);
807static boolean_t mbuf_report_usage(mbuf_class_t);
d9a64523
A
808#if DEBUG || DEVELOPMENT
809#define mbwdog_logger(fmt, ...) _mbwdog_logger(__func__, __LINE__, fmt, ## __VA_ARGS__)
810static void _mbwdog_logger(const char *func, const int line, const char *fmt, ...);
811static char *mbwdog_logging;
812const unsigned mbwdog_logging_size = 4096;
813static size_t mbwdog_logging_used;
814#else
815#define mbwdog_logger(fmt, ...) do { } while (0)
816#endif
817static void mbuf_drain_locked(boolean_t);
b0d623f7
A
818
819/* flags for m_copyback0 */
0a7de745
A
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 */
b0d623f7 824
2d21ac55
A
825/*
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.
835 */
0a7de745 836#define EXTF_COMPOSITE 0x1
1c79356b 837
6d2010ae
A
838/*
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
841 * cleared.
842 */
0a7de745 843#define EXTF_READONLY 0x2
39037602
A
844/*
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.
849 */
0a7de745 850#define EXTF_PAIRED 0x4
39037602 851
0a7de745 852#define EXTF_MASK \
39037602 853 (EXTF_COMPOSITE | EXTF_READONLY | EXTF_PAIRED)
6d2010ae 854
0a7de745
A
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) && \
39037602
A
864 (MEXT_FLAGS(m) & EXTF_MASK) == EXTF_COMPOSITE)
865/*
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.
870 */
0a7de745
A
871#define MBUF_IS_PAIRED(m) \
872 (((m)->m_flags & M_EXT) && \
873 (MEXT_FLAGS(m) & EXTF_MASK) == EXTF_PAIRED && \
39037602 874 MEXT_PMBUF(m) == (m))
1c79356b 875
2d21ac55
A
876/*
877 * Macros used to verify the integrity of the mbuf.
878 */
0a7de745
A
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); \
884 else \
885 mcl_audit_mcheck_panic(m); \
886 } \
887}
888
889#define MBUF_IN_MAP(addr) \
890 ((unsigned char *)(addr) >= mbutl && \
3e170ce0 891 (unsigned char *)(addr) < embutl)
55e303ae 892
0a7de745
A
893#define MRANGE(addr) { \
894 if (!MBUF_IN_MAP(addr)) \
895 panic("MRANGE: address out of range 0x%p", addr); \
1c79356b
A
896}
897
898/*
2d21ac55 899 * Macro version of mtod.
1c79356b 900 */
0a7de745 901#define MTOD(m, t) ((t)((m)->m_data))
1c79356b 902
2d21ac55 903/*
3e170ce0 904 * Macros to obtain page index given a base cluster address
6d2010ae 905 */
0a7de745
A
906#define MTOPG(x) (((unsigned char *)x - mbutl) >> PAGE_SHIFT)
907#define PGTOM(x) (mbutl + (x << PAGE_SHIFT))
6d2010ae
A
908
909/*
910 * Macro to find the mbuf index relative to a base.
2d21ac55 911 */
0a7de745 912#define MBPAGEIDX(c, m) \
3e170ce0 913 (((unsigned char *)(m) - (unsigned char *)(c)) >> MSIZESHIFT)
1c79356b 914
2d21ac55 915/*
6d2010ae 916 * Same thing for 2KB cluster index.
2d21ac55 917 */
0a7de745 918#define CLPAGEIDX(c, m) \
3e170ce0
A
919 (((unsigned char *)(m) - (unsigned char *)(c)) >> MCLSHIFT)
920
921/*
922 * Macro to find 4KB cluster index relative to a base
923 */
924#define BCLPAGEIDX(c, m) \
925 (((unsigned char *)(m) - (unsigned char *)(c)) >> MBIGCLSHIFT)
91447636 926
2d21ac55
A
927/*
928 * Macros used during mbuf and cluster initialization.
929 */
0a7de745
A
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); \
938 m_tag_init(m, 1); \
939 m_scratch_init(m); \
940 m_redzone_init(m); \
941}
942
943#define MBUF_INIT(m, pkthdr, type) { \
944 _MCHECK(m); \
945 (m)->m_next = (m)->m_nextpkt = NULL; \
946 (m)->m_len = 0; \
947 (m)->m_type = type; \
948 if ((pkthdr) == 0) { \
949 (m)->m_data = (m)->m_dat; \
950 (m)->m_flags = 0; \
951 } else { \
952 (m)->m_data = (m)->m_pktdat; \
953 (m)->m_flags = M_PKTHDR; \
954 MBUF_INIT_PKTHDR(m); \
955 } \
956}
957
958#define MEXT_INIT(m, buf, size, free, arg, rfa, min, ref, pref, flag, \
959 priv, pm) { \
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); \
970}
971
972#define MBUF_CL_INIT(m, buf, rfa, ref, flag) \
973 MEXT_INIT(m, buf, m_maxsize(MC_CL), NULL, NULL, rfa, 0, \
39037602 974 ref, 0, flag, 0, NULL)
2d21ac55 975
0a7de745
A
976#define MBUF_BIGCL_INIT(m, buf, rfa, ref, flag) \
977 MEXT_INIT(m, buf, m_maxsize(MC_BIGCL), m_bigfree, NULL, rfa, 0, \
39037602 978 ref, 0, flag, 0, NULL)
2d21ac55 979
0a7de745
A
980#define MBUF_16KCL_INIT(m, buf, rfa, ref, flag) \
981 MEXT_INIT(m, buf, m_maxsize(MC_16KCL), m_16kfree, NULL, rfa, 0, \
39037602 982 ref, 0, flag, 0, NULL)
2d21ac55 983
1c79356b 984/*
2d21ac55 985 * Macro to convert BSD malloc sleep flag to mcache's
1c79356b 986 */
0a7de745 987#define MSLEEPF(f) ((!((f) & M_DONTWAIT)) ? MCR_SLEEP : MCR_NOSLEEP)
1c79356b 988
2d21ac55
A
989/*
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.
994 */
995struct mb_stat *mb_stat;
0a7de745 996struct omb_stat *omb_stat; /* For backwards compatibility */
1c79356b 997
0a7de745 998#define MB_STAT_SIZE(n) \
5ba3f43e 999 __builtin_offsetof(mb_stat_t, mbs_class[n])
0a7de745 1000#define OMB_STAT_SIZE(n) \
cb323159 1001 __builtin_offsetof(struct omb_stat, mbs_class[n])
1c79356b
A
1002
1003/*
2d21ac55
A
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.
1c79356b 1013 */
2d21ac55 1014struct mbstat mbstat;
1c79356b 1015
0a7de745 1016#define MBSTAT_MTYPES_MAX \
2d21ac55 1017 (sizeof (mbstat.m_mtypes) / sizeof (mbstat.m_mtypes[0]))
1c79356b
A
1018
1019/*
2d21ac55
A
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.
1c79356b 1029 */
2d21ac55 1030typedef struct {
0a7de745 1031 unsigned int cpu_mtypes[MT_MAX];
39236c6e 1032} __attribute__((aligned(MAX_CPU_CACHE_LINE_SIZE), packed)) mtypes_cpu_t;
1c79356b 1033
2d21ac55 1034typedef struct {
0a7de745 1035 mtypes_cpu_t mbs_cpu[1];
2d21ac55 1036} mbuf_mtypes_t;
1c79356b 1037
0a7de745 1038static mbuf_mtypes_t *mbuf_mtypes; /* per-CPU statistics */
2d21ac55 1039
0a7de745 1040#define MBUF_MTYPES_SIZE(n) \
cb323159 1041 __builtin_offsetof(mbuf_mtypes_t, mbs_cpu[n])
2d21ac55 1042
0a7de745 1043#define MTYPES_CPU(p) \
316670eb 1044 ((mtypes_cpu_t *)(void *)((char *)(p) + MBUF_MTYPES_SIZE(cpu_number())))
2d21ac55 1045
0a7de745
A
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); \
1052 } \
1c79356b
A
1053}
1054
0a7de745
A
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)
91447636 1058
6d2010ae
A
1059static void
1060mbuf_mtypes_sync(boolean_t locked)
2d21ac55 1061{
2d21ac55
A
1062 int m, n;
1063 mtypes_cpu_t mtc;
1c79356b 1064
0a7de745 1065 if (locked) {
5ba3f43e 1066 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
0a7de745 1067 }
6d2010ae 1068
0a7de745 1069 bzero(&mtc, sizeof(mtc));
2d21ac55
A
1070 for (m = 0; m < ncpu; m++) {
1071 mtypes_cpu_t *scp = &mbuf_mtypes->mbs_cpu[m];
1072 mtypes_cpu_t temp;
9bccf70c 1073
2d21ac55 1074 bcopy(&scp->cpu_mtypes, &temp.cpu_mtypes,
0a7de745 1075 sizeof(temp.cpu_mtypes));
91447636 1076
0a7de745 1077 for (n = 0; n < MT_MAX; n++) {
2d21ac55 1078 mtc.cpu_mtypes[n] += temp.cpu_mtypes[n];
0a7de745 1079 }
2d21ac55 1080 }
0a7de745 1081 if (!locked) {
6d2010ae 1082 lck_mtx_lock(mbuf_mlock);
0a7de745
A
1083 }
1084 for (n = 0; n < MT_MAX; n++) {
2d21ac55 1085 mbstat.m_mtypes[n] = mtc.cpu_mtypes[n];
0a7de745
A
1086 }
1087 if (!locked) {
6d2010ae 1088 lck_mtx_unlock(mbuf_mlock);
0a7de745 1089 }
1c79356b
A
1090}
1091
2d21ac55 1092static int
6d2010ae 1093mbstat_sysctl SYSCTL_HANDLER_ARGS
1c79356b 1094{
2d21ac55 1095#pragma unused(oidp, arg1, arg2)
6d2010ae
A
1096 mbuf_mtypes_sync(FALSE);
1097
0a7de745 1098 return SYSCTL_OUT(req, &mbstat, sizeof(mbstat));
6d2010ae
A
1099}
1100
1101static void
1102mbuf_stat_sync(void)
1103{
2d21ac55 1104 mb_class_stat_t *sp;
6d2010ae
A
1105 mcache_cpu_t *ccp;
1106 mcache_t *cp;
1107 int k, m, bktsize;
1108
5ba3f43e 1109 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
2d21ac55 1110
2d21ac55
A
1111 for (k = 0; k < NELEM(mbuf_table); k++) {
1112 cp = m_cache(k);
1113 ccp = &cp->mc_cpu[0];
1114 bktsize = ccp->cc_bktsize;
1115 sp = mbuf_table[k].mtbl_stats;
1116
0a7de745 1117 if (cp->mc_flags & MCF_NOCPUCACHE) {
2d21ac55 1118 sp->mbcl_mc_state = MCS_DISABLED;
0a7de745 1119 } else if (cp->mc_purge_cnt > 0) {
2d21ac55 1120 sp->mbcl_mc_state = MCS_PURGING;
0a7de745 1121 } else if (bktsize == 0) {
2d21ac55 1122 sp->mbcl_mc_state = MCS_OFFLINE;
0a7de745 1123 } else {
2d21ac55 1124 sp->mbcl_mc_state = MCS_ONLINE;
0a7de745 1125 }
2d21ac55
A
1126
1127 sp->mbcl_mc_cached = 0;
1128 for (m = 0; m < ncpu; m++) {
1129 ccp = &cp->mc_cpu[m];
0a7de745 1130 if (ccp->cc_objs > 0) {
2d21ac55 1131 sp->mbcl_mc_cached += ccp->cc_objs;
0a7de745
A
1132 }
1133 if (ccp->cc_pobjs > 0) {
2d21ac55 1134 sp->mbcl_mc_cached += ccp->cc_pobjs;
0a7de745 1135 }
2d21ac55
A
1136 }
1137 sp->mbcl_mc_cached += (cp->mc_full.bl_total * bktsize);
1138 sp->mbcl_active = sp->mbcl_total - sp->mbcl_mc_cached -
1139 sp->mbcl_infree;
1140
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;
1144
1145 /* Calculate total count specific to each class */
1146 sp->mbcl_ctotal = sp->mbcl_total;
1147 switch (m_class(k)) {
1148 case MC_MBUF:
1149 /* Deduct mbufs used in composite caches */
1150 sp->mbcl_ctotal -= (m_total(MC_MBUF_CL) +
1151 m_total(MC_MBUF_BIGCL));
1152 break;
91447636 1153
2d21ac55 1154 case MC_CL:
6d2010ae
A
1155 /* Deduct clusters used in composite cache */
1156 sp->mbcl_ctotal -= m_total(MC_MBUF_CL);
2d21ac55 1157 break;
91447636 1158
2d21ac55
A
1159 case MC_BIGCL:
1160 /* Deduct clusters used in composite cache */
1161 sp->mbcl_ctotal -= m_total(MC_MBUF_BIGCL);
1162 break;
1c79356b 1163
2d21ac55
A
1164 case MC_16KCL:
1165 /* Deduct clusters used in composite cache */
1166 sp->mbcl_ctotal -= m_total(MC_MBUF_16KCL);
1167 break;
1168
1169 default:
1170 break;
1171 }
1172 }
6d2010ae
A
1173}
1174
1175static int
1176mb_stat_sysctl SYSCTL_HANDLER_ARGS
1177{
1178#pragma unused(oidp, arg1, arg2)
1179 void *statp;
1180 int k, statsz, proc64 = proc_is64bit(req->p);
1181
1182 lck_mtx_lock(mbuf_mlock);
1183 mbuf_stat_sync();
b0d623f7
A
1184
1185 if (!proc64) {
1186 struct omb_class_stat *oc;
1187 struct mb_class_stat *c;
1188
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++) {
0a7de745 1193 (void) snprintf(oc->mbcl_cname, sizeof(oc->mbcl_cname),
b0d623f7
A
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;
fe8ab488 1206 oc->mbcl_release_cnt = c->mbcl_release_cnt;
b0d623f7
A
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;
1212 }
1213 statp = omb_stat;
1214 statsz = OMB_STAT_SIZE(NELEM(mbuf_table));
1215 } else {
1216 statp = mb_stat;
1217 statsz = MB_STAT_SIZE(NELEM(mbuf_table));
1218 }
1219
2d21ac55 1220 lck_mtx_unlock(mbuf_mlock);
9bccf70c 1221
0a7de745 1222 return SYSCTL_OUT(req, statp, statsz);
2d21ac55 1223}
91447636 1224
6d2010ae
A
1225static int
1226mleak_top_trace_sysctl SYSCTL_HANDLER_ARGS
1227{
1228#pragma unused(oidp, arg1, arg2)
6d2010ae
A
1229 int i;
1230
1231 /* Ensure leak tracing turned on */
0a7de745
A
1232 if (!mclfindleak || !mclexpleak) {
1233 return ENXIO;
1234 }
6d2010ae 1235
6d2010ae 1236 lck_mtx_lock(mleak_lock);
316670eb 1237 mleak_update_stats();
6d2010ae
A
1238 i = SYSCTL_OUT(req, mleak_stat, MLEAK_STAT_SIZE(MLEAK_NUM_TRACES));
1239 lck_mtx_unlock(mleak_lock);
1240
0a7de745 1241 return i;
6d2010ae
A
1242}
1243
1244static int
1245mleak_table_sysctl SYSCTL_HANDLER_ARGS
1246{
1247#pragma unused(oidp, arg1, arg2)
1248 int i = 0;
1249
1250 /* Ensure leak tracing turned on */
0a7de745
A
1251 if (!mclfindleak || !mclexpleak) {
1252 return ENXIO;
1253 }
6d2010ae
A
1254
1255 lck_mtx_lock(mleak_lock);
0a7de745 1256 i = SYSCTL_OUT(req, &mleak_table, sizeof(mleak_table));
6d2010ae
A
1257 lck_mtx_unlock(mleak_lock);
1258
0a7de745 1259 return i;
6d2010ae
A
1260}
1261
2d21ac55
A
1262static inline void
1263m_incref(struct mbuf *m)
1264{
39037602
A
1265 UInt16 old, new;
1266 volatile UInt16 *addr = (volatile UInt16 *)&MEXT_REF(m);
91447636 1267
2d21ac55
A
1268 do {
1269 old = *addr;
1270 new = old + 1;
cb323159 1271 VERIFY(new != 0);
39037602 1272 } while (!OSCompareAndSwap16(old, new, addr));
6d2010ae
A
1273
1274 /*
1275 * If cluster is shared, mark it with (sticky) EXTF_READONLY;
39037602
A
1276 * we don't clear the flag when the refcount goes back to the
1277 * minimum, to simplify code calling m_mclhasreference().
6d2010ae 1278 */
0a7de745 1279 if (new > (MEXT_MINREF(m) + 1) && !(MEXT_FLAGS(m) & EXTF_READONLY)) {
39037602 1280 (void) OSBitOrAtomic16(EXTF_READONLY, &MEXT_FLAGS(m));
0a7de745 1281 }
1c79356b
A
1282}
1283
39037602 1284static inline u_int16_t
2d21ac55 1285m_decref(struct mbuf *m)
1c79356b 1286{
39037602
A
1287 UInt16 old, new;
1288 volatile UInt16 *addr = (volatile UInt16 *)&MEXT_REF(m);
1c79356b 1289
2d21ac55
A
1290 do {
1291 old = *addr;
1292 new = old - 1;
cb323159 1293 VERIFY(old != 0);
39037602 1294 } while (!OSCompareAndSwap16(old, new, addr));
2d21ac55 1295
0a7de745 1296 return new;
1c79356b
A
1297}
1298
2d21ac55
A
1299static void
1300mbuf_table_init(void)
1c79356b 1301{
6d2010ae 1302 unsigned int b, c, s;
3e170ce0 1303 int m, config_mbuf_jumbo = 0;
91447636 1304
b0d623f7
A
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);
1308
2d21ac55
A
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);
1c79356b 1312
2d21ac55 1313 mb_stat->mbs_cnt = NELEM(mbuf_table);
0a7de745 1314 for (m = 0; m < NELEM(mbuf_table); m++) {
2d21ac55 1315 mbuf_table[m].mtbl_stats = &mb_stat->mbs_class[m];
0a7de745 1316 }
1c79356b 1317
2d21ac55 1318#if CONFIG_MBUF_JUMBO
3e170ce0 1319 config_mbuf_jumbo = 1;
2d21ac55 1320#endif /* CONFIG_MBUF_JUMBO */
9bccf70c 1321
3e170ce0
A
1322 if (config_mbuf_jumbo == 1 || PAGE_SIZE == M16KCLBYTES) {
1323 /*
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.
1327 */
1328 njcl = nmbclusters / 3;
1329 njclbytes = M16KCLBYTES;
1330 }
1331
2d21ac55 1332 /*
6d2010ae
A
1333 * nclusters holds both the 2KB and 4KB pools, so ensure it's
1334 * a multiple of 4KB clusters.
2d21ac55 1335 */
3e170ce0 1336 nclusters = P2ROUNDDOWN(nmbclusters - njcl, NCLPG);
2d21ac55
A
1337 if (njcl > 0) {
1338 /*
6d2010ae
A
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.
2d21ac55 1342 */
3e170ce0 1343 njcl = P2ROUNDDOWN(nmbclusters - nclusters, NCLPJCL);
1c79356b 1344
6d2010ae 1345 /* Update nclusters with rounded down value of njcl */
3e170ce0 1346 nclusters = P2ROUNDDOWN(nmbclusters - njcl, NCLPG);
9bccf70c 1347 }
2d21ac55
A
1348
1349 /*
3e170ce0
A
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
1356 * clusters.
6d2010ae
A
1357 *
1358 * +---+---+------------ ... -----------+------- ... -------+
1359 * | c | b | s | njcl |
1360 * +---+---+------------ ... -----------+------- ... -------+
1361 *
1362 * 1/32th of the shared region is reserved for pure 2KB and 4KB
1363 * clusters (1/64th each.)
1364 */
0a7de745 1365 c = P2ROUNDDOWN((nclusters >> 6), NCLPG); /* in 2KB unit */
3e170ce0 1366 b = P2ROUNDDOWN((nclusters >> (6 + NCLPBGSHIFT)), NBCLPG); /* in 4KB unit */
0a7de745 1367 s = nclusters - (c + (b << NCLPBGSHIFT)); /* in 2KB unit */
6d2010ae
A
1368
1369 /*
1370 * 1/64th (c) is reserved for 2KB clusters.
2d21ac55 1371 */
6d2010ae 1372 m_minlimit(MC_CL) = c;
0a7de745 1373 m_maxlimit(MC_CL) = s + c; /* in 2KB unit */
2d21ac55
A
1374 m_maxsize(MC_CL) = m_size(MC_CL) = MCLBYTES;
1375 (void) snprintf(m_cname(MC_CL), MAX_MBUF_CNAME, "cl");
1376
1377 /*
6d2010ae
A
1378 * Another 1/64th (b) of the map is reserved for 4KB clusters.
1379 * It cannot be turned into 2KB clusters or mbufs.
2d21ac55 1380 */
6d2010ae 1381 m_minlimit(MC_BIGCL) = b;
0a7de745 1382 m_maxlimit(MC_BIGCL) = (s >> NCLPBGSHIFT) + b; /* in 4KB unit */
6d2010ae
A
1383 m_maxsize(MC_BIGCL) = m_size(MC_BIGCL) = MBIGCLBYTES;
1384 (void) snprintf(m_cname(MC_BIGCL), MAX_MBUF_CNAME, "bigcl");
2d21ac55
A
1385
1386 /*
6d2010ae 1387 * The remaining 31/32ths (s) are all-purpose (mbufs, 2KB, or 4KB)
2d21ac55 1388 */
6d2010ae 1389 m_minlimit(MC_MBUF) = 0;
0a7de745 1390 m_maxlimit(MC_MBUF) = (s << NMBPCLSHIFT); /* in mbuf unit */
6d2010ae
A
1391 m_maxsize(MC_MBUF) = m_size(MC_MBUF) = MSIZE;
1392 (void) snprintf(m_cname(MC_MBUF), MAX_MBUF_CNAME, "mbuf");
2d21ac55
A
1393
1394 /*
1395 * Set limits for the composite classes.
1396 */
1397 m_minlimit(MC_MBUF_CL) = 0;
6d2010ae 1398 m_maxlimit(MC_MBUF_CL) = m_maxlimit(MC_CL);
2d21ac55
A
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");
1402
1403 m_minlimit(MC_MBUF_BIGCL) = 0;
1404 m_maxlimit(MC_MBUF_BIGCL) = m_maxlimit(MC_BIGCL);
6d2010ae 1405 m_maxsize(MC_MBUF_BIGCL) = MBIGCLBYTES;
2d21ac55
A
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");
1408
1409 /*
1410 * And for jumbo classes.
1411 */
1412 m_minlimit(MC_16KCL) = 0;
0a7de745 1413 m_maxlimit(MC_16KCL) = (njcl >> NCLPJCLSHIFT); /* in 16KB unit */
2d21ac55
A
1414 m_maxsize(MC_16KCL) = m_size(MC_16KCL) = M16KCLBYTES;
1415 (void) snprintf(m_cname(MC_16KCL), MAX_MBUF_CNAME, "16kcl");
1416
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");
1422
1423 /*
1424 * Initialize the legacy mbstat structure.
1425 */
0a7de745 1426 bzero(&mbstat, sizeof(mbstat));
2d21ac55
A
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);
1433}
1434
b0d623f7
A
1435#if defined(__LP64__)
1436typedef struct ncl_tbl {
0a7de745
A
1437 uint64_t nt_maxmem; /* memory (sane) size */
1438 uint32_t nt_mbpool; /* mbuf pool size */
b0d623f7
A
1439} ncl_tbl_t;
1440
1441/* Non-server */
1442static ncl_tbl_t ncl_table[] = {
0a7de745
A
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 */ },
b0d623f7
A
1446 { 0, 0 }
1447};
1448
1449/* Server */
1450static ncl_tbl_t ncl_table_srv[] = {
0a7de745
A
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 */ },
b0d623f7
A
1457 { 0, 0 }
1458};
1459#endif /* __LP64__ */
1460
1461__private_extern__ unsigned int
6d2010ae 1462mbuf_default_ncl(int server, uint64_t mem)
b0d623f7
A
1463{
1464#if !defined(__LP64__)
6d2010ae 1465#pragma unused(server)
b0d623f7
A
1466 unsigned int n;
1467 /*
1468 * 32-bit kernel (default to 64MB of mbuf pool for >= 1GB RAM).
1469 */
0a7de745 1470 if ((n = ((mem / 16) / MCLBYTES)) > 32768) {
6d2010ae 1471 n = 32768;
0a7de745 1472 }
b0d623f7
A
1473#else
1474 unsigned int n, i;
6d2010ae 1475 ncl_tbl_t *tbl = (server ? ncl_table_srv : ncl_table);
b0d623f7
A
1476 /*
1477 * 64-bit kernel (mbuf pool size based on table).
1478 */
1479 n = tbl[0].nt_mbpool;
1480 for (i = 0; tbl[i].nt_mbpool != 0; i++) {
0a7de745 1481 if (mem < tbl[i].nt_maxmem) {
b0d623f7 1482 break;
0a7de745 1483 }
b0d623f7
A
1484 n = tbl[i].nt_mbpool;
1485 }
1486 n >>= MCLSHIFT;
1487#endif /* !__LP64__ */
0a7de745 1488 return n;
b0d623f7
A
1489}
1490
2d21ac55
A
1491__private_extern__ void
1492mbinit(void)
1493{
1494 unsigned int m;
6d2010ae 1495 unsigned int initmcl = 0;
2d21ac55 1496 void *buf;
b0d623f7 1497 thread_t thread = THREAD_NULL;
2d21ac55 1498
39236c6e
A
1499 microuptime(&mb_start);
1500
316670eb
A
1501 /*
1502 * These MBUF_ values must be equal to their private counterparts.
1503 */
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);
1515
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);
1531
1532 _CASSERT(MBUF_TSO_IPV4 == CSUM_TSO_IPV4);
1533 _CASSERT(MBUF_TSO_IPV6 == CSUM_TSO_IPV6);
39236c6e 1534 _CASSERT(MBUF_CSUM_REQ_SUM16 == CSUM_PARTIAL);
316670eb 1535 _CASSERT(MBUF_CSUM_TCP_SUM16 == MBUF_CSUM_REQ_SUM16);
5ba3f43e 1536 _CASSERT(MBUF_CSUM_REQ_ZERO_INVERT == CSUM_ZERO_INVERT);
316670eb
A
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);
1546
1547 _CASSERT(MBUF_WAITOK == M_WAIT);
1548 _CASSERT(MBUF_DONTWAIT == M_DONTWAIT);
1549 _CASSERT(MBUF_COPYALL == M_COPYALL);
1550
316670eb
A
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);
d9a64523 1559 _CASSERT(MBUF_SC2TC(MBUF_SC_SIG) == MBUF_TC_VI);
316670eb
A
1560 _CASSERT(MBUF_SC2TC(MBUF_SC_VO) == MBUF_TC_VO);
1561 _CASSERT(MBUF_SC2TC(MBUF_SC_CTL) == MBUF_TC_VO);
1562
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);
1567
39236c6e
A
1568 /* Module specific scratch space (32-bit alignment requirement) */
1569 _CASSERT(!(offsetof(struct mbuf, m_pkthdr.pkt_mpriv) %
0a7de745 1570 sizeof(uint32_t)));
39236c6e
A
1571
1572 /* Initialize random red zone cookie value */
0a7de745
A
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));
813fb2f6
A
1578 mb_obscure_extref |= 0x3;
1579 mb_obscure_extfree |= 0x3;
39236c6e
A
1580
1581 /* Make sure we don't save more than we should */
0a7de745 1582 _CASSERT(MCA_SAVED_MBUF_SIZE <= sizeof(struct mbuf));
39236c6e 1583
0a7de745 1584 if (nmbclusters == 0) {
2d21ac55 1585 nmbclusters = NMBCLUSTERS;
0a7de745 1586 }
2d21ac55 1587
6d2010ae
A
1588 /* This should be a sane (at least even) value by now */
1589 VERIFY(nmbclusters != 0 && !(nmbclusters & 0x1));
1590
2d21ac55
A
1591 /* Setup the mbuf table */
1592 mbuf_table_init();
1593
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();
316670eb 1598 lck_mtx_init(mbuf_mlock, mbuf_mlock_grp, mbuf_mlock_attr);
2d21ac55 1599
6d2010ae
A
1600 /*
1601 * Allocate cluster slabs table:
1602 *
1603 * maxslabgrp = (N * 2048) / (1024 * 1024)
1604 *
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.
1607 */
1608 maxslabgrp =
3e170ce0 1609 (P2ROUNDUP(nmbclusters, (MBSIZE >> MCLSHIFT)) << MCLSHIFT) >> MBSHIFT;
0a7de745 1610 MALLOC(slabstbl, mcl_slabg_t * *, maxslabgrp * sizeof(mcl_slabg_t *),
2d21ac55
A
1611 M_TEMP, M_WAITOK | M_ZERO);
1612 VERIFY(slabstbl != NULL);
1613
6d2010ae
A
1614 /*
1615 * Allocate audit structures, if needed:
1616 *
3e170ce0 1617 * maxclaudit = (maxslabgrp * 1024 * 1024) / PAGE_SIZE
6d2010ae
A
1618 *
1619 * This yields mcl_audit_t units, each one representing a page.
1620 */
0a7de745 1621 PE_parse_boot_argn("mbuf_debug", &mbuf_debug, sizeof(mbuf_debug));
2d21ac55 1622 mbuf_debug |= mcache_getflags();
6d2010ae 1623 if (mbuf_debug & MCF_DEBUG) {
3e170ce0
A
1624 int l;
1625 mcl_audit_t *mclad;
1626 maxclaudit = ((maxslabgrp << MBSHIFT) >> PAGE_SHIFT);
0a7de745 1627 MALLOC(mclaudit, mcl_audit_t *, maxclaudit * sizeof(*mclaudit),
6d2010ae 1628 M_TEMP, M_WAITOK | M_ZERO);
2d21ac55 1629 VERIFY(mclaudit != NULL);
3e170ce0 1630 for (l = 0, mclad = mclaudit; l < maxclaudit; l++) {
0a7de745 1631 MALLOC(mclad[l].cl_audit, mcache_audit_t * *,
3e170ce0
A
1632 NMBPG * sizeof(mcache_audit_t *),
1633 M_TEMP, M_WAITOK | M_ZERO);
1634 VERIFY(mclad[l].cl_audit != NULL);
1635 }
2d21ac55
A
1636
1637 mcl_audit_con_cache = mcache_create("mcl_audit_contents",
0a7de745 1638 AUDIT_CONTENTS_SIZE, sizeof(u_int64_t), 0, MCR_SLEEP);
2d21ac55
A
1639 VERIFY(mcl_audit_con_cache != NULL);
1640 }
6d2010ae
A
1641 mclverify = (mbuf_debug & MCF_VERIFY);
1642 mcltrace = (mbuf_debug & MCF_TRACE);
1643 mclfindleak = !(mbuf_debug & MCF_NOLEAKLOG);
316670eb 1644 mclexpleak = mclfindleak && (mbuf_debug & MCF_EXPLEAKLOG);
6d2010ae
A
1645
1646 /* Enable mbuf leak logging, with a lock to protect the tables */
1647
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();
316670eb 1651 lck_mtx_init(mleak_lock, mleak_lock_grp, mleak_lock_attr);
6d2010ae
A
1652
1653 mleak_activate();
2d21ac55 1654
5ba3f43e
A
1655 /*
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.
1660 */
1661 ncpu = ml_get_max_cpus();
1662 MALLOC(buf, void *, MBUF_MTYPES_SIZE(ncpu) + CPU_CACHE_LINE_SIZE,
1663 M_TEMP, M_WAITOK);
1664 VERIFY(buf != NULL);
1665
1666 mbuf_mtypes = (mbuf_mtypes_t *)P2ROUNDUP((intptr_t)buf,
1667 CPU_CACHE_LINE_SIZE);
1668 bzero(mbuf_mtypes, MBUF_MTYPES_SIZE(ncpu));
1669
2d21ac55 1670 /* Calculate the number of pages assigned to the cluster pool */
3e170ce0 1671 mcl_pages = (nmbclusters << MCLSHIFT) / PAGE_SIZE;
0a7de745 1672 MALLOC(mcl_paddr, ppnum_t *, mcl_pages * sizeof(ppnum_t),
b0d623f7 1673 M_TEMP, M_WAITOK);
2d21ac55
A
1674 VERIFY(mcl_paddr != NULL);
1675
1676 /* Register with the I/O Bus mapper */
1677 mcl_paddr_base = IOMapperIOVMAlloc(mcl_pages);
0a7de745 1678 bzero((char *)mcl_paddr, mcl_pages * sizeof(ppnum_t));
2d21ac55 1679
3e170ce0
A
1680 embutl = (mbutl + (nmbclusters * MCLBYTES));
1681 VERIFY(((embutl - mbutl) % MBIGCLBYTES) == 0);
2d21ac55 1682
6d2010ae 1683 /* Prime up the freelist */
0a7de745 1684 PE_parse_boot_argn("initmcl", &initmcl, sizeof(initmcl));
6d2010ae 1685 if (initmcl != 0) {
0a7de745
A
1686 initmcl >>= NCLPBGSHIFT; /* become a 4K unit */
1687 if (initmcl > m_maxlimit(MC_BIGCL)) {
6d2010ae 1688 initmcl = m_maxlimit(MC_BIGCL);
0a7de745 1689 }
6d2010ae 1690 }
0a7de745 1691 if (initmcl < m_minlimit(MC_BIGCL)) {
6d2010ae 1692 initmcl = m_minlimit(MC_BIGCL);
0a7de745 1693 }
2d21ac55
A
1694
1695 lck_mtx_lock(mbuf_mlock);
1696
6d2010ae
A
1697 /*
1698 * For classes with non-zero minimum limits, populate their freelists
1699 * so that m_total(class) is at least m_minlimit(class).
1700 */
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));
1705
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)));
fe8ab488
A
1710
1711 /* populate the initial sizes and report from there on */
1712 m_peak(m_class(m)) = m_total(m_class(m));
6d2010ae 1713 }
fe8ab488 1714 mb_peak_newreport = FALSE;
2d21ac55
A
1715
1716 lck_mtx_unlock(mbuf_mlock);
1717
6d2010ae
A
1718 (void) kernel_thread_start((thread_continue_t)mbuf_worker_thread_init,
1719 NULL, &thread);
b0d623f7 1720 thread_deallocate(thread);
2d21ac55 1721
0a7de745 1722 ref_cache = mcache_create("mext_ref", sizeof(struct ext_ref),
2d21ac55
A
1723 0, 0, MCR_SLEEP);
1724
1725 /* Create the cache for each class */
1726 for (m = 0; m < NELEM(mbuf_table); m++) {
6d2010ae 1727 void *allocfunc, *freefunc, *auditfunc, *logfunc;
2d21ac55
A
1728 u_int32_t flags;
1729
1730 flags = mbuf_debug;
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;
6d2010ae 1736 logfunc = mleak_logger;
2d21ac55
A
1737 } else {
1738 allocfunc = mbuf_slab_alloc;
1739 freefunc = mbuf_slab_free;
1740 auditfunc = mbuf_slab_audit;
6d2010ae 1741 logfunc = mleak_logger;
2d21ac55
A
1742 }
1743
1744 /*
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.
1749 */
1750 if ((m_class(m) == MC_MBUF_16KCL || m_class(m) == MC_16KCL) &&
0a7de745 1751 njcl == 0) {
2d21ac55 1752 flags |= MCF_NOCPUCACHE;
0a7de745 1753 }
2d21ac55 1754
0a7de745 1755 if (!mclfindleak) {
6d2010ae 1756 flags |= MCF_NOLEAKLOG;
0a7de745 1757 }
6d2010ae 1758
2d21ac55 1759 m_cache(m) = mcache_create_ext(m_cname(m), m_maxsize(m),
6d2010ae 1760 allocfunc, freefunc, auditfunc, logfunc, mbuf_slab_notify,
b0d623f7 1761 (void *)(uintptr_t)m, flags, MCR_SLEEP);
2d21ac55
A
1762 }
1763
6d2010ae
A
1764 /*
1765 * Set the max limit on sb_max to be 1/16 th of the size of
b0d623f7
A
1766 * memory allocated for mbuf clusters.
1767 */
6d2010ae 1768 high_sb_max = (nmbclusters << (MCLSHIFT - 4));
b0d623f7
A
1769 if (high_sb_max < sb_max) {
1770 /* sb_max is too large for this configuration, scale it down */
6d2010ae 1771 if (high_sb_max > (1 << MBSHIFT)) {
b0d623f7
A
1772 /* We have atleast 16 M of mbuf pool */
1773 sb_max = high_sb_max;
1774 } else if ((nmbclusters << MCLSHIFT) > (1 << MBSHIFT)) {
6d2010ae
A
1775 /*
1776 * If we have more than 1M of mbufpool, cap the size of
b0d623f7 1777 * max sock buf at 1M
6d2010ae 1778 */
b0d623f7
A
1779 sb_max = high_sb_max = (1 << MBSHIFT);
1780 } else {
1781 sb_max = high_sb_max;
1782 }
1783 }
1784
316670eb
A
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);
1788
39236c6e
A
1789 if (mbuf_debug & MCF_DEBUG) {
1790 printf("%s: MLEN %d, MHLEN %d\n", __func__,
1791 (int)_MLEN, (int)_MHLEN);
1792 }
1793
1794 printf("%s: done [%d MB total pool size, (%d/%d) split]\n", __func__,
6d2010ae
A
1795 (nmbclusters << MCLSHIFT) >> MBSHIFT,
1796 (nclusters << MCLSHIFT) >> MBSHIFT,
1797 (njcl << MCLSHIFT) >> MBSHIFT);
39037602
A
1798
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__);
1803 /* NOTREACHED */
1804 }
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__);
1809 /* NOTREACHED */
1810 }
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__);
1814 /* NOTREACHED */
1815 }
1816 lck_rw_init(mbuf_tx_compl_tbl_lock, mbuf_tx_compl_tbl_lck_grp,
1817 mbuf_tx_compl_tbl_lck_attr);
2d21ac55
A
1818}
1819
1820/*
1821 * Obtain a slab of object(s) from the class's freelist.
1822 */
1823static mcache_obj_t *
1824slab_alloc(mbuf_class_t class, int wait)
1825{
1826 mcl_slab_t *sp;
1827 mcache_obj_t *buf;
1828
5ba3f43e 1829 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
2d21ac55 1830
2d21ac55
A
1831 /* This should always be NULL for us */
1832 VERIFY(m_cobjlist(class) == NULL);
1833
1834 /*
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.
1840 */
3e170ce0 1841 if ((class == MC_MBUF || class == MC_CL || class == MC_BIGCL)
0a7de745 1842 && (wait & MCR_COMP)) {
2d21ac55 1843 sp = (mcl_slab_t *)TAILQ_LAST(&m_slablist(class), mcl_slhead);
0a7de745 1844 } else {
2d21ac55 1845 sp = (mcl_slab_t *)TAILQ_FIRST(&m_slablist(class));
0a7de745 1846 }
2d21ac55
A
1847
1848 if (sp == NULL) {
1849 VERIFY(m_infree(class) == 0 && m_slab_cnt(class) == 0);
1850 /* The slab list for this class is empty */
0a7de745 1851 return NULL;
2d21ac55
A
1852 }
1853
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);
1858 buf = sp->sl_head;
1859 VERIFY(slab_inrange(sp, buf) && sp == slab_get(buf));
3e170ce0
A
1860 sp->sl_head = buf->obj_next;
1861 /* Increment slab reference */
1862 sp->sl_refcnt++;
1863
1864 VERIFY(sp->sl_head != NULL || sp->sl_refcnt == sp->sl_chunks);
2d21ac55 1865
2d21ac55
A
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));
1870 /* NOTREACHED */
1871 }
1872
2d21ac55
A
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 */
0a7de745 1877 if (class == MC_MBUF) {
2d21ac55 1878 mca->mca_uflags |= MB_SCVALID;
0a7de745 1879 }
2d21ac55
A
1880 }
1881
1882 if (class == MC_CL) {
1883 mbstat.m_clfree = (--m_infree(MC_CL)) + m_infree(MC_MBUF_CL);
1884 /*
3e170ce0 1885 * A 2K cluster slab can have at most NCLPG references.
2d21ac55 1886 */
3e170ce0
A
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);
2d21ac55 1890 } else if (class == MC_BIGCL) {
2d21ac55
A
1891 mbstat.m_bigclfree = (--m_infree(MC_BIGCL)) +
1892 m_infree(MC_MBUF_BIGCL);
1893 /*
3e170ce0 1894 * A 4K cluster slab can have NBCLPG references.
2d21ac55 1895 */
3e170ce0 1896 VERIFY(sp->sl_refcnt >= 1 && sp->sl_chunks == NBCLPG &&
39037602 1897 sp->sl_len == PAGE_SIZE &&
3e170ce0 1898 (sp->sl_refcnt < NBCLPG || sp->sl_head == NULL));
2d21ac55
A
1899 } else if (class == MC_16KCL) {
1900 mcl_slab_t *nsp;
1901 int k;
1902
1903 --m_infree(MC_16KCL);
1904 VERIFY(sp->sl_refcnt == 1 && sp->sl_chunks == 1 &&
6d2010ae 1905 sp->sl_len == m_maxsize(class) && sp->sl_head == NULL);
2d21ac55 1906 /*
6d2010ae
A
1907 * Increment 2nd-Nth slab reference, where N is NSLABSP16KB.
1908 * A 16KB big cluster takes NSLABSP16KB slabs, each having at
1909 * most 1 reference.
2d21ac55 1910 */
6d2010ae 1911 for (nsp = sp, k = 1; k < NSLABSP16KB; k++) {
2d21ac55
A
1912 nsp = nsp->sl_next;
1913 /* Next slab must already be present */
1914 VERIFY(nsp != NULL);
1915 nsp->sl_refcnt++;
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);
1922 }
1923 } else {
6d2010ae 1924 VERIFY(class == MC_MBUF);
2d21ac55
A
1925 --m_infree(MC_MBUF);
1926 /*
1927 * If auditing is turned on, this check is
1928 * deferred until later in mbuf_slab_audit().
1929 */
0a7de745 1930 if (mclaudit == NULL) {
2d21ac55 1931 _MCHECK((struct mbuf *)buf);
0a7de745 1932 }
2d21ac55
A
1933 /*
1934 * Since we have incremented the reference count above,
6d2010ae 1935 * an mbuf slab (formerly a 4KB cluster slab that was cut
2d21ac55 1936 * up into mbufs) must have a reference count between 1
3e170ce0 1937 * and NMBPG at this point.
2d21ac55 1938 */
3e170ce0
A
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);
2d21ac55
A
1943 }
1944
1945 /* If empty, remove this slab from the class's freelist */
1946 if (sp->sl_head == NULL) {
3e170ce0
A
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);
2d21ac55
A
1950 slab_remove(sp, class);
1951 }
1952
0a7de745 1953 return buf;
2d21ac55
A
1954}
1955
1956/*
1957 * Place a slab of object(s) back into a class's slab list.
1958 */
1959static void
1960slab_free(mbuf_class_t class, mcache_obj_t *buf)
1961{
1962 mcl_slab_t *sp;
3e170ce0
A
1963 boolean_t reinit_supercl = false;
1964 mbuf_class_t super_class;
2d21ac55 1965
5ba3f43e 1966 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
1967
1968 VERIFY(class != MC_16KCL || njcl > 0);
1969 VERIFY(buf->obj_next == NULL);
3e170ce0 1970
cc8bc92a
A
1971 /*
1972 * Synchronizing with m_clalloc, as it reads m_total, while we here
1973 * are modifying m_total.
1974 */
1975 while (mb_clalloc_busy) {
1976 mb_clalloc_waiters++;
1977 (void) msleep(mb_clalloc_waitchan, mbuf_mlock,
0a7de745 1978 (PZERO - 1), "m_clalloc", NULL);
cc8bc92a
A
1979 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
1980 }
1981
1982 /* We are busy now; tell everyone else to go away */
1983 mb_clalloc_busy = TRUE;
1984
2d21ac55
A
1985 sp = slab_get(buf);
1986 VERIFY(sp->sl_class == class && slab_inrange(sp, buf) &&
1987 (sp->sl_flags & (SLF_MAPPED | SLF_PARTIAL)) == SLF_MAPPED);
1988
1989 /* Decrement slab reference */
1990 sp->sl_refcnt--;
1991
6d2010ae 1992 if (class == MC_CL) {
2d21ac55
A
1993 VERIFY(IS_P2ALIGNED(buf, MCLBYTES));
1994 /*
6d2010ae
A
1995 * A slab that has been splitted for 2KB clusters can have
1996 * at most 1 outstanding reference at this point.
1997 */
3e170ce0
A
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) ||
6d2010ae
A
2001 (slab_is_detached(sp) && sp->sl_head == NULL));
2002 } else if (class == MC_BIGCL) {
3e170ce0
A
2003 VERIFY(IS_P2ALIGNED(buf, MBIGCLBYTES));
2004
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));
2d21ac55
A
2009 } else if (class == MC_16KCL) {
2010 mcl_slab_t *nsp;
2011 int k;
2012 /*
6d2010ae 2013 * A 16KB cluster takes NSLABSP16KB slabs, all must
2d21ac55
A
2014 * now have 0 reference.
2015 */
3e170ce0 2016 VERIFY(IS_P2ALIGNED(buf, PAGE_SIZE));
2d21ac55 2017 VERIFY(sp->sl_refcnt == 0 && sp->sl_chunks == 1 &&
6d2010ae 2018 sp->sl_len == m_maxsize(class) && sp->sl_head == NULL);
2d21ac55 2019 VERIFY(slab_is_detached(sp));
6d2010ae 2020 for (nsp = sp, k = 1; k < NSLABSP16KB; k++) {
2d21ac55
A
2021 nsp = nsp->sl_next;
2022 /* Next slab must already be present */
2023 VERIFY(nsp != NULL);
2024 nsp->sl_refcnt--;
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);
2031 }
2032 } else {
2033 /*
3e170ce0
A
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
2037 * NMBPG-1.
2d21ac55 2038 */
6d2010ae 2039 VERIFY(class == MC_MBUF);
3e170ce0
A
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) ||
2d21ac55
A
2045 (slab_is_detached(sp) && sp->sl_head == NULL));
2046 }
2047
2048 /*
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.
2052 */
2053 if (mclaudit != NULL) {
2054 mcache_audit_t *mca = mcl_audit_buf2mca(class, buf);
6d2010ae 2055 if (mclverify) {
3e170ce0
A
2056 mcache_audit_free_verify(mca, buf, 0,
2057 m_maxsize(class));
6d2010ae 2058 }
2d21ac55
A
2059 mca->mca_uflags &= ~MB_SCVALID;
2060 }
2061
2062 if (class == MC_CL) {
2063 mbstat.m_clfree = (++m_infree(MC_CL)) + m_infree(MC_MBUF_CL);
6d2010ae 2064 buf->obj_next = sp->sl_head;
2d21ac55
A
2065 } else if (class == MC_BIGCL) {
2066 mbstat.m_bigclfree = (++m_infree(MC_BIGCL)) +
2067 m_infree(MC_MBUF_BIGCL);
3e170ce0 2068 buf->obj_next = sp->sl_head;
2d21ac55
A
2069 } else if (class == MC_16KCL) {
2070 ++m_infree(MC_16KCL);
2071 } else {
2072 ++m_infree(MC_MBUF);
2073 buf->obj_next = sp->sl_head;
2074 }
2075 sp->sl_head = buf;
2076
6d2010ae 2077 /*
3e170ce0
A
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.
6d2010ae 2081 */
3e170ce0
A
2082 if (m_maxsize(MC_BIGCL) == PAGE_SIZE) {
2083 super_class = MC_BIGCL;
2084 } else {
2085 VERIFY(PAGE_SIZE == m_maxsize(MC_16KCL));
2086 super_class = MC_16KCL;
2087 }
6d2010ae 2088 if (class == MC_MBUF && sp->sl_refcnt == 0 &&
3e170ce0
A
2089 m_total(class) >= (m_minlimit(class) + NMBPG) &&
2090 m_total(super_class) < m_maxlimit(super_class)) {
2091 int i = NMBPG;
6d2010ae 2092
3e170ce0 2093 m_total(MC_MBUF) -= NMBPG;
2d21ac55 2094 mbstat.m_mbufs = m_total(MC_MBUF);
3e170ce0
A
2095 m_infree(MC_MBUF) -= NMBPG;
2096 mtype_stat_add(MT_FREE, -((unsigned)NMBPG));
2d21ac55
A
2097
2098 while (i--) {
2099 struct mbuf *m = sp->sl_head;
2100 VERIFY(m != NULL);
2101 sp->sl_head = m->m_next;
2102 m->m_next = NULL;
2103 }
3e170ce0 2104 reinit_supercl = true;
6d2010ae 2105 } else if (class == MC_CL && sp->sl_refcnt == 0 &&
0a7de745 2106 m_total(class) >= (m_minlimit(class) + NCLPG) &&
3e170ce0
A
2107 m_total(super_class) < m_maxlimit(super_class)) {
2108 int i = NCLPG;
6d2010ae 2109
3e170ce0 2110 m_total(MC_CL) -= NCLPG;
6d2010ae 2111 mbstat.m_clusters = m_total(MC_CL);
3e170ce0 2112 m_infree(MC_CL) -= NCLPG;
6d2010ae
A
2113
2114 while (i--) {
2115 union mcluster *c = sp->sl_head;
2116 VERIFY(c != NULL);
2117 sp->sl_head = c->mcl_next;
2118 c->mcl_next = NULL;
2119 }
3e170ce0
A
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)) {
2125 int i = NBCLPG;
2126
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;
6d2010ae 2131
3e170ce0
A
2132 while (i--) {
2133 union mbigcluster *bc = sp->sl_head;
2134 VERIFY(bc != NULL);
2135 sp->sl_head = bc->mbc_next;
2136 bc->mbc_next = NULL;
2137 }
2138 reinit_supercl = true;
2139 }
2140
2141 if (reinit_supercl) {
2142 VERIFY(sp->sl_head == NULL);
2143 VERIFY(m_total(class) >= m_minlimit(class));
6d2010ae
A
2144 slab_remove(sp, class);
2145
3e170ce0
A
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);
6d2010ae 2151
3e170ce0
A
2152 slab_init(sp, super_class, SLF_MAPPED, sp->sl_base,
2153 sp->sl_base, PAGE_SIZE, 0, 1);
0a7de745 2154 if (mclverify) {
6d2010ae 2155 mcache_set_pattern(MCACHE_FREE_PATTERN,
3e170ce0 2156 (caddr_t)sp->sl_base, sp->sl_len);
0a7de745 2157 }
3e170ce0
A
2158 ((mcache_obj_t *)(sp->sl_base))->obj_next = NULL;
2159
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);
6d2010ae 2164 }
2d21ac55
A
2165
2166 VERIFY(slab_is_detached(sp));
3e170ce0
A
2167 VERIFY(m_total(super_class) <= m_maxlimit(super_class));
2168
2d21ac55 2169 /* And finally switch class */
3e170ce0 2170 class = super_class;
2d21ac55
A
2171 }
2172
2173 /* Reinsert the slab to the class's slab list */
0a7de745 2174 if (slab_is_detached(sp)) {
2d21ac55 2175 slab_insert(sp, class);
0a7de745 2176 }
cc8bc92a
A
2177
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);
2183 }
2d21ac55
A
2184}
2185
2186/*
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.
2192 */
2193static unsigned int
2194mbuf_slab_alloc(void *arg, mcache_obj_t ***plist, unsigned int num, int wait)
2195{
2196 mbuf_class_t class = (mbuf_class_t)arg;
2197 unsigned int need = num;
2198 mcache_obj_t **list = *plist;
2199
2200 ASSERT(MBUF_CLASS_VALID(class) && !MBUF_CLASS_COMPOSITE(class));
2201 ASSERT(need > 0);
2202
2203 lck_mtx_lock(mbuf_mlock);
2204
2205 for (;;) {
2206 if ((*list = slab_alloc(class, wait)) != NULL) {
2207 (*list)->obj_next = NULL;
2208 list = *plist = &(*list)->obj_next;
2209
2210 if (--need == 0) {
2211 /*
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.
2216 */
2217 if (!mbuf_cached_above(class, wait) &&
3e170ce0 2218 m_infree(class) < (m_total(class) >> 5)) {
2d21ac55
A
2219 (void) freelist_populate(class, 1,
2220 M_DONTWAIT);
2221 }
2222 break;
2223 }
2224 } else {
2225 VERIFY(m_infree(class) == 0 || class == MC_CL);
2226
2227 (void) freelist_populate(class, 1,
2228 (wait & MCR_NOSLEEP) ? M_DONTWAIT : M_WAIT);
2229
0a7de745 2230 if (m_infree(class) > 0) {
2d21ac55 2231 continue;
0a7de745 2232 }
2d21ac55
A
2233
2234 /* Check if there's anything at the cache layer */
0a7de745 2235 if (mbuf_cached_above(class, wait)) {
2d21ac55 2236 break;
0a7de745 2237 }
2d21ac55 2238
6d2010ae
A
2239 /* watchdog checkpoint */
2240 mbuf_watchdog();
2241
2d21ac55
A
2242 /* We have nothing and cannot block; give up */
2243 if (wait & MCR_NOSLEEP) {
2244 if (!(wait & MCR_TRYHARD)) {
2245 m_fail_cnt(class)++;
2246 mbstat.m_drops++;
2247 break;
2248 }
2249 }
2250
2251 /*
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.
2257 */
2258 if (mbuf_worker_ready &&
0a7de745 2259 mbuf_sleep(class, need, wait)) {
2d21ac55 2260 break;
0a7de745 2261 }
2d21ac55 2262
5ba3f43e 2263 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
2264 }
2265 }
2266
2267 m_alloc_cnt(class) += num - need;
2268 lck_mtx_unlock(mbuf_mlock);
2269
0a7de745 2270 return num - need;
2d21ac55
A
2271}
2272
2273/*
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
2276 * global freelist.
2277 */
2278static void
2279mbuf_slab_free(void *arg, mcache_obj_t *list, __unused int purged)
2280{
2281 mbuf_class_t class = (mbuf_class_t)arg;
2282 mcache_obj_t *nlist;
2283 unsigned int num = 0;
2284 int w;
2285
2286 ASSERT(MBUF_CLASS_VALID(class) && !MBUF_CLASS_COMPOSITE(class));
2287
2288 lck_mtx_lock(mbuf_mlock);
2289
2290 for (;;) {
2291 nlist = list->obj_next;
2292 list->obj_next = NULL;
2293 slab_free(class, list);
2294 ++num;
0a7de745 2295 if ((list = nlist) == NULL) {
2d21ac55 2296 break;
0a7de745 2297 }
2d21ac55
A
2298 }
2299 m_free_cnt(class) += num;
2300
0a7de745 2301 if ((w = mb_waiters) > 0) {
2d21ac55 2302 mb_waiters = 0;
0a7de745 2303 }
d9a64523
A
2304 if (w) {
2305 mbwdog_logger("waking up all threads");
2306 }
2d21ac55
A
2307 lck_mtx_unlock(mbuf_mlock);
2308
0a7de745 2309 if (w != 0) {
2d21ac55 2310 wakeup(mb_waitchan);
0a7de745 2311 }
2d21ac55
A
2312}
2313
2314/*
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.
2321 */
2322static void
2323mbuf_slab_audit(void *arg, mcache_obj_t *list, boolean_t alloc)
2324{
2325 mbuf_class_t class = (mbuf_class_t)arg;
2326 mcache_audit_t *mca;
2327
2328 ASSERT(MBUF_CLASS_VALID(class) && !MBUF_CLASS_COMPOSITE(class));
2329
2330 while (list != NULL) {
2331 lck_mtx_lock(mbuf_mlock);
2332 mca = mcl_audit_buf2mca(class, list);
2333
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);
2338 } else {
2339 mcl_audit_cluster(mca, list, m_maxsize(class),
2340 alloc, TRUE);
2341 ASSERT(!(mca->mca_uflags & MB_SCVALID));
2342 }
2343 /* Record this transaction */
0a7de745 2344 if (mcltrace) {
39236c6e 2345 mcache_buffer_log(mca, list, m_cache(class), &mb_start);
0a7de745 2346 }
6d2010ae 2347
0a7de745 2348 if (alloc) {
2d21ac55 2349 mca->mca_uflags |= MB_INUSE;
0a7de745 2350 } else {
2d21ac55 2351 mca->mca_uflags &= ~MB_INUSE;
0a7de745 2352 }
2d21ac55
A
2353 /* Unpair the object (unconditionally) */
2354 mca->mca_uptr = NULL;
2355 lck_mtx_unlock(mbuf_mlock);
2356
2357 list = list->obj_next;
2358 }
2359}
2360
2361/*
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.
2366 */
2367static void
2368mbuf_slab_notify(void *arg, u_int32_t reason)
2369{
2370 mbuf_class_t class = (mbuf_class_t)arg;
2371 int w;
2372
2373 ASSERT(MBUF_CLASS_VALID(class));
2374
0a7de745 2375 if (reason != MCN_RETRYALLOC) {
2d21ac55 2376 return;
0a7de745 2377 }
2d21ac55
A
2378
2379 lck_mtx_lock(mbuf_mlock);
2380 if ((w = mb_waiters) > 0) {
2381 m_notified(class)++;
2382 mb_waiters = 0;
2383 }
d9a64523
A
2384 if (w) {
2385 mbwdog_logger("waking up all threads");
2386 }
2d21ac55
A
2387 lck_mtx_unlock(mbuf_mlock);
2388
0a7de745 2389 if (w != 0) {
2d21ac55 2390 wakeup(mb_waitchan);
0a7de745 2391 }
2d21ac55
A
2392}
2393
2394/*
2395 * Obtain object(s) from the composite class's freelist.
2396 */
2397static unsigned int
2398cslab_alloc(mbuf_class_t class, mcache_obj_t ***plist, unsigned int num)
2399{
2400 unsigned int need = num;
2401 mcl_slab_t *sp, *clsp, *nsp;
2402 struct mbuf *m;
2403 mcache_obj_t **list = *plist;
2404 void *cl;
2405
2406 VERIFY(need > 0);
2407 VERIFY(class != MC_MBUF_16KCL || njcl > 0);
5ba3f43e 2408 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
2409
2410 /* Get what we can from the freelist */
2411 while ((*list = m_cobjlist(class)) != NULL) {
2412 MRANGE(*list);
2413
2414 m = (struct mbuf *)*list;
2415 sp = slab_get(m);
2416 cl = m->m_ext.ext_buf;
2417 clsp = slab_get(cl);
2418 VERIFY(m->m_flags == M_EXT && cl != NULL);
813fb2f6 2419 VERIFY(m_get_rfa(m) != NULL && MBUF_IS_COMPOSITE(m));
6d2010ae
A
2420
2421 if (class == MC_MBUF_CL) {
2422 VERIFY(clsp->sl_refcnt >= 1 &&
3e170ce0 2423 clsp->sl_refcnt <= NCLPG);
6d2010ae 2424 } else {
3e170ce0
A
2425 VERIFY(clsp->sl_refcnt >= 1 &&
2426 clsp->sl_refcnt <= NBCLPG);
6d2010ae
A
2427 }
2428
2429 if (class == MC_MBUF_16KCL) {
2d21ac55 2430 int k;
6d2010ae 2431 for (nsp = clsp, k = 1; k < NSLABSP16KB; k++) {
2d21ac55
A
2432 nsp = nsp->sl_next;
2433 /* Next slab must already be present */
2434 VERIFY(nsp != NULL);
2435 VERIFY(nsp->sl_refcnt == 1);
2436 }
2437 }
2438
2439 if ((m_cobjlist(class) = (*list)->obj_next) != NULL &&
2440 !MBUF_IN_MAP(m_cobjlist(class))) {
2441 slab_nextptr_panic(sp, m_cobjlist(class));
2442 /* NOTREACHED */
2443 }
2444 (*list)->obj_next = NULL;
2445 list = *plist = &(*list)->obj_next;
2446
0a7de745 2447 if (--need == 0) {
2d21ac55 2448 break;
0a7de745 2449 }
2d21ac55
A
2450 }
2451 m_infree(class) -= (num - need);
2452
0a7de745 2453 return num - need;
2d21ac55
A
2454}
2455
2456/*
2457 * Place object(s) back into a composite class's freelist.
2458 */
2459static unsigned int
2460cslab_free(mbuf_class_t class, mcache_obj_t *list, int purged)
2461{
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;
2468 void *cl;
6d2010ae 2469 mbuf_class_t cl_class;
2d21ac55
A
2470
2471 ASSERT(MBUF_CLASS_VALID(class) && MBUF_CLASS_COMPOSITE(class));
2472 VERIFY(class != MC_MBUF_16KCL || njcl > 0);
5ba3f43e 2473 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
2d21ac55 2474
6d2010ae
A
2475 if (class == MC_MBUF_CL) {
2476 cl_class = MC_CL;
2477 } else if (class == MC_MBUF_BIGCL) {
2478 cl_class = MC_BIGCL;
2479 } else {
2480 VERIFY(class == MC_MBUF_16KCL);
2481 cl_class = MC_16KCL;
2482 }
2483
2d21ac55
A
2484 o = tail = list;
2485
2486 while ((m = ms = (struct mbuf *)o) != NULL) {
2487 mcache_obj_t *rfa, *nexto = o->obj_next;
2488
2489 /* Do the mbuf sanity checks */
2490 if (mclaudit != NULL) {
2491 mca = mcl_audit_buf2mca(MC_MBUF, (mcache_obj_t *)m);
6d2010ae
A
2492 if (mclverify) {
2493 mcache_audit_free_verify(mca, m, 0,
2494 m_maxsize(MC_MBUF));
2495 }
39236c6e 2496 ms = MCA_SAVED_MBUF_PTR(mca);
2d21ac55
A
2497 }
2498
2499 /* Do the cluster sanity checks */
2500 cl = ms->m_ext.ext_buf;
2501 clsp = slab_get(cl);
6d2010ae
A
2502 if (mclverify) {
2503 size_t size = m_maxsize(cl_class);
2504 mcache_audit_free_verify(mcl_audit_buf2mca(cl_class,
2d21ac55
A
2505 (mcache_obj_t *)cl), cl, 0, size);
2506 }
2507 VERIFY(ms->m_type == MT_FREE);
2508 VERIFY(ms->m_flags == M_EXT);
813fb2f6 2509 VERIFY(m_get_rfa(ms) != NULL && MBUF_IS_COMPOSITE(ms));
6d2010ae
A
2510 if (cl_class == MC_CL) {
2511 VERIFY(clsp->sl_refcnt >= 1 &&
3e170ce0 2512 clsp->sl_refcnt <= NCLPG);
6d2010ae 2513 } else {
39037602 2514 VERIFY(clsp->sl_refcnt >= 1 &&
3e170ce0 2515 clsp->sl_refcnt <= NBCLPG);
6d2010ae
A
2516 }
2517 if (cl_class == MC_16KCL) {
2d21ac55 2518 int k;
6d2010ae 2519 for (nsp = clsp, k = 1; k < NSLABSP16KB; k++) {
2d21ac55
A
2520 nsp = nsp->sl_next;
2521 /* Next slab must already be present */
2522 VERIFY(nsp != NULL);
2523 VERIFY(nsp->sl_refcnt == 1);
2524 }
2525 }
2526
2527 /*
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.
2532 */
2533 if (purged) {
2534 /* Restore constructed mbuf fields */
0a7de745 2535 if (mclaudit != NULL) {
2d21ac55 2536 mcl_audit_restore_mbuf(m, mca, TRUE);
0a7de745 2537 }
2d21ac55 2538
39037602 2539 MEXT_MINREF(m) = 0;
2d21ac55 2540 MEXT_REF(m) = 0;
39037602 2541 MEXT_PREF(m) = 0;
2d21ac55 2542 MEXT_FLAGS(m) = 0;
39037602
A
2543 MEXT_PRIV(m) = 0;
2544 MEXT_PMBUF(m) = NULL;
813fb2f6 2545 MEXT_TOKEN(m) = 0;
2d21ac55 2546
813fb2f6
A
2547 rfa = (mcache_obj_t *)(void *)m_get_rfa(m);
2548 m_set_ext(m, NULL, NULL, NULL);
2d21ac55
A
2549 rfa->obj_next = ref_list;
2550 ref_list = rfa;
2d21ac55
A
2551
2552 m->m_type = MT_FREE;
2553 m->m_flags = m->m_len = 0;
2554 m->m_next = m->m_nextpkt = NULL;
2555
2556 /* Save mbuf fields and make auditing happy */
0a7de745 2557 if (mclaudit != NULL) {
2d21ac55 2558 mcl_audit_mbuf(mca, o, FALSE, FALSE);
0a7de745 2559 }
2d21ac55
A
2560
2561 VERIFY(m_total(class) > 0);
2562 m_total(class)--;
2563
2564 /* Free the mbuf */
2565 o->obj_next = NULL;
2566 slab_free(MC_MBUF, o);
2567
2568 /* And free the cluster */
2569 ((mcache_obj_t *)cl)->obj_next = NULL;
0a7de745 2570 if (class == MC_MBUF_CL) {
2d21ac55 2571 slab_free(MC_CL, cl);
0a7de745 2572 } else if (class == MC_MBUF_BIGCL) {
2d21ac55 2573 slab_free(MC_BIGCL, cl);
0a7de745 2574 } else {
2d21ac55 2575 slab_free(MC_16KCL, cl);
0a7de745 2576 }
2d21ac55
A
2577 }
2578
2579 ++num;
2580 tail = o;
2581 o = nexto;
2582 }
2583
2584 if (!purged) {
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);
2590 }
2591
0a7de745 2592 return num;
2d21ac55
A
2593}
2594
2595/*
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.
2602 */
2603static unsigned int
2604mbuf_cslab_alloc(void *arg, mcache_obj_t ***plist, unsigned int needed,
2605 int wait)
2606{
2607 mbuf_class_t class = (mbuf_class_t)arg;
6d2010ae 2608 mbuf_class_t cl_class = 0;
2d21ac55
A
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;
2615 struct mbuf *m;
2616 void *cl;
2617
2618 ASSERT(MBUF_CLASS_VALID(class) && MBUF_CLASS_COMPOSITE(class));
2619 ASSERT(needed > 0);
2620
2621 VERIFY(class != MC_MBUF_16KCL || njcl > 0);
2622
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);
2627
2628 lck_mtx_lock(mbuf_mlock);
2629
2630 /* Try using the freelist first */
2631 num = cslab_alloc(class, plist, needed);
2632 list = *plist;
2633 if (num == needed) {
2634 m_alloc_cnt(class) += num;
2635 lck_mtx_unlock(mbuf_mlock);
0a7de745 2636 return needed;
2d21ac55
A
2637 }
2638
2639 lck_mtx_unlock(mbuf_mlock);
2640
2641 /*
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.
2645 */
2646 needed -= num;
2647
2648 /*
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.
2654 */
2655 wait |= MCR_COMP;
0a7de745 2656 if (!(wait & MCR_NOSLEEP)) {
2d21ac55 2657 wait |= MCR_FAILOK;
0a7de745 2658 }
2d21ac55 2659
6d2010ae 2660 /* allocate mbufs */
2d21ac55
A
2661 needed = mcache_alloc_ext(m_cache(MC_MBUF), &mp_list, needed, wait);
2662 if (needed == 0) {
2663 ASSERT(mp_list == NULL);
2664 goto fail;
2665 }
6d2010ae
A
2666
2667 /* allocate clusters */
2668 if (class == MC_MBUF_CL) {
2669 cl_class = MC_CL;
2670 } else if (class == MC_MBUF_BIGCL) {
2671 cl_class = MC_BIGCL;
2672 } else {
2673 VERIFY(class == MC_MBUF_16KCL);
2674 cl_class = MC_16KCL;
2675 }
2676 needed = mcache_alloc_ext(m_cache(cl_class), &clp_list, needed, wait);
2d21ac55
A
2677 if (needed == 0) {
2678 ASSERT(clp_list == NULL);
2679 goto fail;
2680 }
6d2010ae 2681
2d21ac55
A
2682 needed = mcache_alloc_ext(ref_cache, &ref_list, needed, wait);
2683 if (needed == 0) {
2684 ASSERT(ref_list == NULL);
2685 goto fail;
2686 }
2687
2688 /*
2689 * By this time "needed" is MIN(mbuf, cluster, ref). Any left
2690 * overs will get freed accordingly before we return to caller.
2691 */
2692 for (cnum = 0; cnum < needed; cnum++) {
2693 struct mbuf *ms;
2694
2695 m = ms = (struct mbuf *)mp_list;
2696 mp_list = mp_list->obj_next;
2697
2698 cl = clp_list;
2699 clp_list = clp_list->obj_next;
2700 ((mcache_obj_t *)cl)->obj_next = NULL;
2701
2702 rfa = (struct ext_ref *)ref_list;
2703 ref_list = ref_list->obj_next;
316670eb 2704 ((mcache_obj_t *)(void *)rfa)->obj_next = NULL;
2d21ac55
A
2705
2706 /*
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.
2711 */
2712 if (mclaudit != NULL) {
2713 mcache_audit_t *mca, *cl_mca;
2d21ac55
A
2714
2715 lck_mtx_lock(mbuf_mlock);
2716 mca = mcl_audit_buf2mca(MC_MBUF, (mcache_obj_t *)m);
39236c6e 2717 ms = MCA_SAVED_MBUF_PTR(mca);
3e170ce0
A
2718 cl_mca = mcl_audit_buf2mca(cl_class,
2719 (mcache_obj_t *)cl);
2d21ac55
A
2720
2721 /*
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.
2728 */
2729 mca->mca_uptr = cl_mca;
2730 cl_mca->mca_uptr = mca;
2731
2732 ASSERT(mca->mca_uflags & MB_SCVALID);
2733 ASSERT(!(cl_mca->mca_uflags & MB_SCVALID));
2734 lck_mtx_unlock(mbuf_mlock);
2735
2736 /* Technically, they are in the freelist */
6d2010ae
A
2737 if (mclverify) {
2738 size_t size;
2739
2740 mcache_set_pattern(MCACHE_FREE_PATTERN, m,
2741 m_maxsize(MC_MBUF));
2742
0a7de745 2743 if (class == MC_MBUF_CL) {
6d2010ae 2744 size = m_maxsize(MC_CL);
0a7de745 2745 } else if (class == MC_MBUF_BIGCL) {
6d2010ae 2746 size = m_maxsize(MC_BIGCL);
0a7de745 2747 } else {
6d2010ae 2748 size = m_maxsize(MC_16KCL);
0a7de745 2749 }
6d2010ae
A
2750
2751 mcache_set_pattern(MCACHE_FREE_PATTERN, cl,
2752 size);
2753 }
2d21ac55
A
2754 }
2755
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);
2761 } else {
2762 MBUF_CL_INIT(ms, cl, rfa, 0, EXTF_COMPOSITE);
2763 }
2764 VERIFY(ms->m_flags == M_EXT);
813fb2f6 2765 VERIFY(m_get_rfa(ms) != NULL && MBUF_IS_COMPOSITE(ms));
2d21ac55
A
2766
2767 *list = (mcache_obj_t *)m;
2768 (*list)->obj_next = NULL;
2769 list = *plist = &(*list)->obj_next;
2770 }
2771
2772fail:
2773 /*
2774 * Free up what's left of the above.
2775 */
0a7de745 2776 if (mp_list != NULL) {
2d21ac55 2777 mcache_free_ext(m_cache(MC_MBUF), mp_list);
0a7de745
A
2778 }
2779 if (clp_list != NULL) {
6d2010ae 2780 mcache_free_ext(m_cache(cl_class), clp_list);
0a7de745
A
2781 }
2782 if (ref_list != NULL) {
2d21ac55 2783 mcache_free_ext(ref_cache, ref_list);
0a7de745 2784 }
2d21ac55
A
2785
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;
2791 }
0a7de745 2792 if ((num + cnum) < want) {
2d21ac55 2793 m_fail_cnt(class) += (want - (num + cnum));
0a7de745 2794 }
2d21ac55
A
2795 lck_mtx_unlock(mbuf_mlock);
2796
0a7de745 2797 return num + cnum;
2d21ac55
A
2798}
2799
2800/*
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
2803 * global freelist.
2804 */
2805static void
2806mbuf_cslab_free(void *arg, mcache_obj_t *list, int purged)
2807{
2808 mbuf_class_t class = (mbuf_class_t)arg;
2809 unsigned int num;
2810 int w;
2811
2812 ASSERT(MBUF_CLASS_VALID(class) && MBUF_CLASS_COMPOSITE(class));
2813
2814 lck_mtx_lock(mbuf_mlock);
2815
2816 num = cslab_free(class, list, purged);
2817 m_free_cnt(class) += num;
2818
0a7de745 2819 if ((w = mb_waiters) > 0) {
2d21ac55 2820 mb_waiters = 0;
0a7de745 2821 }
d9a64523
A
2822 if (w) {
2823 mbwdog_logger("waking up all threads");
2824 }
2d21ac55
A
2825
2826 lck_mtx_unlock(mbuf_mlock);
2827
0a7de745 2828 if (w != 0) {
2d21ac55 2829 wakeup(mb_waitchan);
0a7de745 2830 }
2d21ac55
A
2831}
2832
2833/*
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.
2840 */
2841static void
2842mbuf_cslab_audit(void *arg, mcache_obj_t *list, boolean_t alloc)
2843{
3e170ce0 2844 mbuf_class_t class = (mbuf_class_t)arg, cl_class;
2d21ac55
A
2845 mcache_audit_t *mca;
2846 struct mbuf *m, *ms;
2847 mcl_slab_t *clsp, *nsp;
3e170ce0 2848 size_t cl_size;
2d21ac55
A
2849 void *cl;
2850
2851 ASSERT(MBUF_CLASS_VALID(class) && MBUF_CLASS_COMPOSITE(class));
0a7de745 2852 if (class == MC_MBUF_CL) {
3e170ce0 2853 cl_class = MC_CL;
0a7de745 2854 } else if (class == MC_MBUF_BIGCL) {
3e170ce0 2855 cl_class = MC_BIGCL;
0a7de745 2856 } else {
3e170ce0 2857 cl_class = MC_16KCL;
0a7de745 2858 }
3e170ce0 2859 cl_size = m_maxsize(cl_class);
2d21ac55
A
2860
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);
0a7de745 2866 if (mcltrace) {
39236c6e 2867 mcache_buffer_log(mca, m, m_cache(class), &mb_start);
0a7de745 2868 }
6d2010ae 2869
0a7de745 2870 if (alloc) {
2d21ac55 2871 mca->mca_uflags |= MB_COMP_INUSE;
0a7de745 2872 } else {
2d21ac55 2873 mca->mca_uflags &= ~MB_COMP_INUSE;
0a7de745 2874 }
2d21ac55
A
2875
2876 /*
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().
2880 */
0a7de745 2881 if (!alloc && mclverify) {
39236c6e 2882 ms = MCA_SAVED_MBUF_PTR(mca);
0a7de745 2883 }
2d21ac55
A
2884
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);
813fb2f6 2889 VERIFY(m_get_rfa(ms) != NULL && MBUF_IS_COMPOSITE(ms));
0a7de745 2890 if (class == MC_MBUF_CL) {
6d2010ae 2891 VERIFY(clsp->sl_refcnt >= 1 &&
3e170ce0 2892 clsp->sl_refcnt <= NCLPG);
0a7de745 2893 } else {
3e170ce0
A
2894 VERIFY(clsp->sl_refcnt >= 1 &&
2895 clsp->sl_refcnt <= NBCLPG);
0a7de745 2896 }
6d2010ae
A
2897
2898 if (class == MC_MBUF_16KCL) {
2d21ac55 2899 int k;
6d2010ae 2900 for (nsp = clsp, k = 1; k < NSLABSP16KB; k++) {
2d21ac55
A
2901 nsp = nsp->sl_next;
2902 /* Next slab must already be present */
2903 VERIFY(nsp != NULL);
2904 VERIFY(nsp->sl_refcnt == 1);
2905 }
2906 }
2907
3e170ce0
A
2908
2909 mca = mcl_audit_buf2mca(cl_class, cl);
2910 mcl_audit_cluster(mca, cl, cl_size, alloc, FALSE);
0a7de745 2911 if (mcltrace) {
39236c6e 2912 mcache_buffer_log(mca, cl, m_cache(class), &mb_start);
0a7de745 2913 }
6d2010ae 2914
0a7de745 2915 if (alloc) {
2d21ac55 2916 mca->mca_uflags |= MB_COMP_INUSE;
0a7de745 2917 } else {
2d21ac55 2918 mca->mca_uflags &= ~MB_COMP_INUSE;
0a7de745 2919 }
2d21ac55
A
2920 lck_mtx_unlock(mbuf_mlock);
2921
2922 list = list->obj_next;
2923 }
2924}
2925
cc8bc92a
A
2926static void
2927m_vm_error_stats(uint32_t *cnt, uint64_t *ts, uint64_t *size,
0a7de745 2928 uint64_t alloc_size, kern_return_t error)
cc8bc92a 2929{
cc8bc92a
A
2930 *cnt = *cnt + 1;
2931 *ts = net_uptime();
2932 if (size) {
2933 *size = alloc_size;
2934 }
2935 _CASSERT(sizeof(mb_kmem_stats) / sizeof(mb_kmem_stats[0]) ==
2936 sizeof(mb_kmem_stats_labels) / sizeof(mb_kmem_stats_labels[0]));
2937 switch (error) {
2938 case KERN_SUCCESS:
2939 break;
2940 case KERN_INVALID_ARGUMENT:
2941 mb_kmem_stats[0]++;
2942 break;
2943 case KERN_INVALID_ADDRESS:
2944 mb_kmem_stats[1]++;
2945 break;
2946 case KERN_RESOURCE_SHORTAGE:
2947 mb_kmem_stats[2]++;
2948 break;
2949 case KERN_NO_SPACE:
2950 mb_kmem_stats[3]++;
2951 break;
2952 case KERN_FAILURE:
2953 mb_kmem_stats[4]++;
2954 break;
2955 default:
2956 mb_kmem_stats[5]++;
2957 break;
2958 }
2959}
2960
2d21ac55
A
2961/*
2962 * Allocate some number of mbuf clusters and place on cluster freelist.
2963 */
2964static int
2965m_clalloc(const u_int32_t num, const int wait, const u_int32_t bufsize)
2966{
3e170ce0 2967 int i, count = 0;
2d21ac55 2968 vm_size_t size = 0;
3e170ce0 2969 int numpages = 0, large_buffer;
2d21ac55
A
2970 vm_offset_t page = 0;
2971 mcache_audit_t *mca_list = NULL;
2972 mcache_obj_t *con_list = NULL;
2973 mcl_slab_t *sp;
3e170ce0 2974 mbuf_class_t class;
cc8bc92a 2975 kern_return_t error;
2d21ac55 2976
3e170ce0
A
2977 /* Set if a buffer allocation needs allocation of multiple pages */
2978 large_buffer = ((bufsize == m_maxsize(MC_16KCL)) &&
0a7de745 2979 PAGE_SIZE < M16KCLBYTES);
6d2010ae
A
2980 VERIFY(bufsize == m_maxsize(MC_BIGCL) ||
2981 bufsize == m_maxsize(MC_16KCL));
2d21ac55 2982
3e170ce0
A
2983 VERIFY((bufsize == PAGE_SIZE) ||
2984 (bufsize > PAGE_SIZE && bufsize == m_maxsize(MC_16KCL)));
2985
0a7de745 2986 if (bufsize == m_size(MC_BIGCL)) {
3e170ce0 2987 class = MC_BIGCL;
0a7de745 2988 } else {
3e170ce0 2989 class = MC_16KCL;
0a7de745 2990 }
3e170ce0 2991
5ba3f43e 2992 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
2993
2994 /*
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.
3001 */
3002 while (mb_clalloc_busy) {
3003 mb_clalloc_waiters++;
3004 (void) msleep(mb_clalloc_waitchan, mbuf_mlock,
0a7de745 3005 (PZERO - 1), "m_clalloc", NULL);
5ba3f43e 3006 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
3007 }
3008
3009 /* We are busy now; tell everyone else to go away */
3010 mb_clalloc_busy = TRUE;
3011
3012 /*
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.
3015 */
3016 i = m_howmany(num, bufsize);
0a7de745 3017 if (i <= 0 || (wait & M_DONTWAIT)) {
2d21ac55 3018 goto out;
0a7de745 3019 }
2d21ac55
A
3020
3021 lck_mtx_unlock(mbuf_mlock);
3022
b0d623f7 3023 size = round_page(i * bufsize);
cc8bc92a 3024 page = kmem_mb_alloc(mb_map, size, large_buffer, &error);
b0d623f7
A
3025
3026 /*
6d2010ae 3027 * If we did ask for "n" 16KB physically contiguous chunks
b0d623f7
A
3028 * and didn't get them, then please try again without this
3029 * restriction.
3030 */
cc8bc92a
A
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,
3036 size, error);
3037 page = kmem_mb_alloc(mb_map, size, 0, &error);
3038 }
2d21ac55
A
3039
3040 if (page == 0) {
cc8bc92a
A
3041 m_vm_error_stats(&mb_kmem_failed,
3042 &mb_kmem_failed_ts,
3043 &mb_kmem_failed_size,
3044 size, error);
3045#if PAGE_SIZE == 4096
6d2010ae 3046 if (bufsize == m_maxsize(MC_BIGCL)) {
cc8bc92a
A
3047#else
3048 if (bufsize >= m_maxsize(MC_BIGCL)) {
3049#endif
3e170ce0
A
3050 /* Try for 1 page if failed */
3051 size = PAGE_SIZE;
cc8bc92a 3052 page = kmem_mb_alloc(mb_map, size, 0, &error);
5c9f4661
A
3053 if (page == 0) {
3054 m_vm_error_stats(&mb_kmem_one_failed,
3055 &mb_kmem_one_failed_ts,
3056 NULL, size, error);
3057 }
2d21ac55
A
3058 }
3059
3060 if (page == 0) {
3061 lck_mtx_lock(mbuf_mlock);
3062 goto out;
3063 }
3064 }
3065
3e170ce0
A
3066 VERIFY(IS_P2ALIGNED(page, PAGE_SIZE));
3067 numpages = size / PAGE_SIZE;
2d21ac55
A
3068
3069 /* If auditing is enabled, allocate the audit structures now */
3070 if (mclaudit != NULL) {
3071 int needed;
3072
3073 /*
3074 * Yes, I realize this is a waste of memory for clusters
3075 * that never get transformed into mbufs, as we may end
3e170ce0 3076 * up with NMBPG-1 unused audit structures per cluster.
2d21ac55
A
3077 * But doing so tremendously simplifies the allocation
3078 * strategy, since at this point we are not holding the
6d2010ae 3079 * mbuf lock and the caller is okay to be blocked.
2d21ac55 3080 */
3e170ce0
A
3081 if (bufsize == PAGE_SIZE) {
3082 needed = numpages * NMBPG;
2d21ac55
A
3083
3084 i = mcache_alloc_ext(mcl_audit_con_cache,
3085 &con_list, needed, MCR_SLEEP);
3086
3087 VERIFY(con_list != NULL && i == needed);
2d21ac55 3088 } else {
3e170ce0
A
3089 /*
3090 * if multiple 4K pages are being used for a
39037602
A
3091 * 16K cluster
3092 */
6d2010ae 3093 needed = numpages / NSLABSP16KB;
2d21ac55
A
3094 }
3095
3096 i = mcache_alloc_ext(mcache_audit_cache,
3097 (mcache_obj_t **)&mca_list, needed, MCR_SLEEP);
3098
3099 VERIFY(mca_list != NULL && i == needed);
3100 }
3101
3102 lck_mtx_lock(mbuf_mlock);
3103
3e170ce0
A
3104 for (i = 0; i < numpages; i++, page += PAGE_SIZE) {
3105 ppnum_t offset =
3106 ((unsigned char *)page - mbutl) >> PAGE_SHIFT;
99c3a104 3107 ppnum_t new_page = pmap_find_phys(kernel_pmap, page);
2d21ac55
A
3108
3109 /*
3e170ce0
A
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.
2d21ac55 3113 */
b0d623f7 3114 VERIFY(offset < mcl_pages);
39236c6e 3115 if (mcl_paddr_base != 0) {
3e170ce0 3116 bzero((void *)(uintptr_t) page, PAGE_SIZE);
39236c6e
A
3117 new_page = IOMapperInsertPage(mcl_paddr_base,
3118 offset, new_page);
99c3a104 3119 }
39236c6e 3120 mcl_paddr[offset] = new_page;
2d21ac55
A
3121
3122 /* Pattern-fill this fresh page */
6d2010ae 3123 if (mclverify) {
2d21ac55 3124 mcache_set_pattern(MCACHE_FREE_PATTERN,
3e170ce0 3125 (caddr_t)page, PAGE_SIZE);
6d2010ae 3126 }
3e170ce0
A
3127 if (bufsize == PAGE_SIZE) {
3128 mcache_obj_t *buf;
2d21ac55 3129 /* One for the entire page */
3e170ce0 3130 sp = slab_get((void *)page);
6d2010ae 3131 if (mclaudit != NULL) {
3e170ce0
A
3132 mcl_audit_init((void *)page,
3133 &mca_list, &con_list,
3134 AUDIT_CONTENTS_SIZE, NMBPG);
6d2010ae 3135 }
2d21ac55 3136 VERIFY(sp->sl_refcnt == 0 && sp->sl_flags == 0);
3e170ce0
A
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;
2d21ac55 3141
2d21ac55 3142 /* Insert this slab */
3e170ce0
A
3143 slab_insert(sp, class);
3144
3145 /* Update stats now since slab_get drops the lock */
3146 ++m_infree(class);
3147 ++m_total(class);
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);
3153 }
3154 ++count;
3155 } else if ((bufsize > PAGE_SIZE) &&
3156 (i % NSLABSP16KB) == 0) {
2d21ac55
A
3157 union m16kcluster *m16kcl = (union m16kcluster *)page;
3158 mcl_slab_t *nsp;
3159 int k;
39037602 3160
2d21ac55
A
3161 /* One for the entire 16KB */
3162 sp = slab_get(m16kcl);
0a7de745 3163 if (mclaudit != NULL) {
2d21ac55 3164 mcl_audit_init(m16kcl, &mca_list, NULL, 0, 1);
0a7de745 3165 }
2d21ac55
A
3166
3167 VERIFY(sp->sl_refcnt == 0 && sp->sl_flags == 0);
3168 slab_init(sp, MC_16KCL, SLF_MAPPED,
3169 m16kcl, m16kcl, bufsize, 0, 1);
3e170ce0 3170 m16kcl->m16kcl_next = NULL;
2d21ac55 3171
6d2010ae
A
3172 /*
3173 * 2nd-Nth page's slab is part of the first one,
3174 * where N is NSLABSP16KB.
3175 */
3176 for (k = 1; k < NSLABSP16KB; k++) {
3177 nsp = slab_get(((union mbigcluster *)page) + k);
2d21ac55
A
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);
3183 }
2d21ac55
A
3184 /* Insert this slab */
3185 slab_insert(sp, MC_16KCL);
3186
3e170ce0
A
3187 /* Update stats now since slab_get drops the lock */
3188 ++m_infree(MC_16KCL);
3189 ++m_total(MC_16KCL);
2d21ac55 3190 VERIFY(m_total(MC_16KCL) <= m_maxlimit(MC_16KCL));
3e170ce0 3191 ++count;
2d21ac55
A
3192 }
3193 }
3194 VERIFY(mca_list == NULL && con_list == NULL);
3195
0a7de745 3196 if (!mb_peak_newreport && mbuf_report_usage(class)) {
3e170ce0 3197 mb_peak_newreport = TRUE;
0a7de745 3198 }
3e170ce0 3199
2d21ac55
A
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);
3205 }
3206
0a7de745 3207 return count;
2d21ac55 3208out:
5ba3f43e 3209 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
2d21ac55 3210
5c9f4661
A
3211 mtracelarge_register(size);
3212
2d21ac55
A
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);
3218 }
3219
3220 /*
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.
3223 */
39037602 3224 if (i > 0 && mbuf_worker_ready && mbuf_worker_needs_wakeup) {
d9a64523
A
3225 mbwdog_logger("waking up the worker thread to to grow %s by %d",
3226 m_cname(class), i);
39037602
A
3227 wakeup((caddr_t)&mbuf_worker_needs_wakeup);
3228 mbuf_worker_needs_wakeup = FALSE;
3229 }
3e170ce0 3230 if (class == MC_BIGCL) {
2d21ac55
A
3231 if (i > 0) {
3232 /*
3233 * Remember total number of 4KB clusters needed
3234 * at this time.
3235 */
3236 i += m_total(MC_BIGCL);
5ba3f43e
A
3237 if (i > m_region_expand(MC_BIGCL)) {
3238 m_region_expand(MC_BIGCL) = i;
2d21ac55
A
3239 }
3240 }
0a7de745
A
3241 if (m_infree(MC_BIGCL) >= num) {
3242 return 1;
3243 }
2d21ac55
A
3244 } else {
3245 if (i > 0) {
3246 /*
3247 * Remember total number of 16KB clusters needed
3248 * at this time.
3249 */
3250 i += m_total(MC_16KCL);
5ba3f43e
A
3251 if (i > m_region_expand(MC_16KCL)) {
3252 m_region_expand(MC_16KCL) = i;
2d21ac55
A
3253 }
3254 }
0a7de745
A
3255 if (m_infree(MC_16KCL) >= num) {
3256 return 1;
3257 }
2d21ac55 3258 }
0a7de745 3259 return 0;
2d21ac55
A
3260}
3261
3262/*
3263 * Populate the global freelist of the corresponding buffer class.
3264 */
3265static int
3266freelist_populate(mbuf_class_t class, unsigned int num, int wait)
3267{
3268 mcache_obj_t *o = NULL;
6d2010ae 3269 int i, numpages = 0, count;
3e170ce0 3270 mbuf_class_t super_class;
2d21ac55
A
3271
3272 VERIFY(class == MC_MBUF || class == MC_CL || class == MC_BIGCL ||
3273 class == MC_16KCL);
3274
5ba3f43e 3275 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
2d21ac55 3276
3e170ce0
A
3277 VERIFY(PAGE_SIZE == m_maxsize(MC_BIGCL) ||
3278 PAGE_SIZE == m_maxsize(MC_16KCL));
2d21ac55 3279
0a7de745
A
3280 if (m_maxsize(class) >= PAGE_SIZE) {
3281 return m_clalloc(num, wait, m_maxsize(class)) != 0;
3282 }
2d21ac55 3283
3e170ce0
A
3284 /*
3285 * The rest of the function will allocate pages and will slice
3286 * them up into the right size
3287 */
2d21ac55 3288
3e170ce0
A
3289 numpages = (num * m_size(class) + PAGE_SIZE - 1) / PAGE_SIZE;
3290
3291 /* Currently assume that pages are 4K or 16K */
0a7de745 3292 if (PAGE_SIZE == m_maxsize(MC_BIGCL)) {
3e170ce0 3293 super_class = MC_BIGCL;
0a7de745 3294 } else {
3e170ce0 3295 super_class = MC_16KCL;
0a7de745 3296 }
2d21ac55 3297
3e170ce0
A
3298 i = m_clalloc(numpages, wait, m_maxsize(super_class));
3299
6d2010ae 3300 /* how many objects will we cut the page into? */
3e170ce0 3301 int numobj = PAGE_SIZE / m_maxsize(class);
6d2010ae
A
3302
3303 for (count = 0; count < numpages; count++) {
6d2010ae 3304 /* respect totals, minlimit, maxlimit */
3e170ce0 3305 if (m_total(super_class) <= m_minlimit(super_class) ||
0a7de745 3306 m_total(class) >= m_maxlimit(class)) {
6d2010ae 3307 break;
0a7de745 3308 }
6d2010ae 3309
0a7de745 3310 if ((o = slab_alloc(super_class, wait)) == NULL) {
6d2010ae 3311 break;
0a7de745 3312 }
6d2010ae 3313
2d21ac55 3314 struct mbuf *m = (struct mbuf *)o;
6d2010ae 3315 union mcluster *c = (union mcluster *)o;
3e170ce0 3316 union mbigcluster *mbc = (union mbigcluster *)o;
2d21ac55 3317 mcl_slab_t *sp = slab_get(o);
6d2010ae 3318 mcache_audit_t *mca = NULL;
2d21ac55 3319
3e170ce0
A
3320 /*
3321 * since one full page will be converted to MC_MBUF or
3322 * MC_CL, verify that the reference count will match that
3323 * assumption
3324 */
39037602 3325 VERIFY(sp->sl_refcnt == 1 && slab_is_detached(sp));
3e170ce0 3326 VERIFY((sp->sl_flags & (SLF_MAPPED | SLF_PARTIAL)) == SLF_MAPPED);
6d2010ae
A
3327 /*
3328 * Make sure that the cluster is unmolested
3329 * while in freelist
3330 */
3331 if (mclverify) {
3e170ce0
A
3332 mca = mcl_audit_buf2mca(super_class,
3333 (mcache_obj_t *)o);
3334 mcache_audit_free_verify(mca,
3335 (mcache_obj_t *)o, 0, m_maxsize(super_class));
2d21ac55
A
3336 }
3337
3e170ce0 3338 /* Reinitialize it as an mbuf or 2K or 4K slab */
6d2010ae 3339 slab_init(sp, class, sp->sl_flags,
3e170ce0 3340 sp->sl_base, NULL, PAGE_SIZE, 0, numobj);
2d21ac55 3341
2d21ac55
A
3342 VERIFY(sp->sl_head == NULL);
3343
3e170ce0
A
3344 VERIFY(m_total(super_class) >= 1);
3345 m_total(super_class)--;
3346
0a7de745 3347 if (super_class == MC_BIGCL) {
3e170ce0 3348 mbstat.m_bigclusters = m_total(MC_BIGCL);
0a7de745 3349 }
2d21ac55 3350
6d2010ae 3351 m_total(class) += numobj;
5ba3f43e 3352 VERIFY(m_total(class) <= m_maxlimit(class));
6d2010ae
A
3353 m_infree(class) += numobj;
3354
0a7de745 3355 if (!mb_peak_newreport && mbuf_report_usage(class)) {
fe8ab488 3356 mb_peak_newreport = TRUE;
0a7de745 3357 }
6d2010ae
A
3358
3359 i = numobj;
3360 if (class == MC_MBUF) {
3361 mbstat.m_mbufs = m_total(MC_MBUF);
3e170ce0 3362 mtype_stat_add(MT_FREE, NMBPG);
6d2010ae
A
3363 while (i--) {
3364 /*
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
3370 * integrity check.
3371 */
3372 if (mclaudit != NULL) {
3373 struct mbuf *ms;
3374 mca = mcl_audit_buf2mca(MC_MBUF,
3375 (mcache_obj_t *)m);
39236c6e 3376 ms = MCA_SAVED_MBUF_PTR(mca);
6d2010ae
A
3377 ms->m_type = MT_FREE;
3378 } else {
3379 m->m_type = MT_FREE;
3380 }
3381 m->m_next = sp->sl_head;
3382 sp->sl_head = (void *)m++;
3383 }
3e170ce0 3384 } else if (class == MC_CL) { /* MC_CL */
6d2010ae
A
3385 mbstat.m_clfree =
3386 m_infree(MC_CL) + m_infree(MC_MBUF_CL);
3387 mbstat.m_clusters = m_total(MC_CL);
3388 while (i--) {
3389 c->mcl_next = sp->sl_head;
3390 sp->sl_head = (void *)c++;
2d21ac55 3391 }
3e170ce0
A
3392 } else {
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);
3397 while (i--) {
3398 mbc->mbc_next = sp->sl_head;
3399 sp->sl_head = (void *)mbc++;
3400 }
2d21ac55
A
3401 }
3402
3e170ce0 3403 /* Insert into the mbuf or 2k or 4k slab list */
6d2010ae 3404 slab_insert(sp, class);
2d21ac55 3405
0a7de745 3406 if ((i = mb_waiters) > 0) {
2d21ac55 3407 mb_waiters = 0;
0a7de745 3408 }
d9a64523
A
3409 if (i != 0) {
3410 mbwdog_logger("waking up all threads");
2d21ac55 3411 wakeup(mb_waitchan);
d9a64523 3412 }
2d21ac55 3413 }
0a7de745 3414 return count != 0;
6d2010ae 3415}
2d21ac55 3416
6d2010ae
A
3417/*
3418 * For each class, initialize the freelist to hold m_minlimit() objects.
3419 */
3420static void
3421freelist_init(mbuf_class_t class)
3422{
5ba3f43e 3423 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
6d2010ae
A
3424
3425 VERIFY(class == MC_CL || class == MC_BIGCL);
3426 VERIFY(m_total(class) == 0);
3427 VERIFY(m_minlimit(class) > 0);
3428
0a7de745 3429 while (m_total(class) < m_minlimit(class)) {
6d2010ae 3430 (void) freelist_populate(class, m_minlimit(class), M_WAIT);
0a7de745 3431 }
6d2010ae
A
3432
3433 VERIFY(m_total(class) >= m_minlimit(class));
2d21ac55
A
3434}
3435
3436/*
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.
3440 */
3441static boolean_t
3442mbuf_cached_above(mbuf_class_t class, int wait)
3443{
3444 switch (class) {
3445 case MC_MBUF:
0a7de745
A
3446 if (wait & MCR_COMP) {
3447 return !mcache_bkt_isempty(m_cache(MC_MBUF_CL)) ||
3448 !mcache_bkt_isempty(m_cache(MC_MBUF_BIGCL));
3449 }
2d21ac55
A
3450 break;
3451
3452 case MC_CL:
0a7de745
A
3453 if (wait & MCR_COMP) {
3454 return !mcache_bkt_isempty(m_cache(MC_MBUF_CL));
3455 }
2d21ac55
A
3456 break;
3457
3458 case MC_BIGCL:
0a7de745
A
3459 if (wait & MCR_COMP) {
3460 return !mcache_bkt_isempty(m_cache(MC_MBUF_BIGCL));
3461 }
2d21ac55
A
3462 break;
3463
3464 case MC_16KCL:
0a7de745
A
3465 if (wait & MCR_COMP) {
3466 return !mcache_bkt_isempty(m_cache(MC_MBUF_16KCL));
3467 }
2d21ac55
A
3468 break;
3469
3470 case MC_MBUF_CL:
3471 case MC_MBUF_BIGCL:
3472 case MC_MBUF_16KCL:
3473 break;
3474
3475 default:
3476 VERIFY(0);
3477 /* NOTREACHED */
3478 }
3479
0a7de745 3480 return !mcache_bkt_isempty(m_cache(class));
2d21ac55
A
3481}
3482
3483/*
3484 * If possible, convert constructed objects to raw ones.
3485 */
3486static boolean_t
3487mbuf_steal(mbuf_class_t class, unsigned int num)
3488{
3489 mcache_obj_t *top = NULL;
3490 mcache_obj_t **list = &top;
3491 unsigned int tot = 0;
3492
5ba3f43e 3493 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
3494
3495 switch (class) {
3496 case MC_MBUF:
3497 case MC_CL:
3498 case MC_BIGCL:
3499 case MC_16KCL:
0a7de745 3500 return FALSE;
2d21ac55
A
3501
3502 case MC_MBUF_CL:
3503 case MC_MBUF_BIGCL:
3504 case MC_MBUF_16KCL:
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)));
3509 }
3510
3511 /* And destroy them to get back the raw objects */
0a7de745 3512 if (top != NULL) {
2d21ac55 3513 (void) cslab_free(class, top, 1);
0a7de745 3514 }
2d21ac55
A
3515 break;
3516
3517 default:
3518 VERIFY(0);
3519 /* NOTREACHED */
3520 }
3521
0a7de745 3522 return tot == num;
2d21ac55
A
3523}
3524
3525static void
3526m_reclaim(mbuf_class_t class, unsigned int num, boolean_t comp)
3527{
3528 int m, bmap = 0;
3529
5ba3f43e 3530 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
3531
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));
3535
3536 /*
3537 * This logic can be made smarter; for now, simply mark
3538 * all other related classes as potential victims.
3539 */
3540 switch (class) {
3541 case MC_MBUF:
3542 m_wantpurge(MC_CL)++;
6d2010ae 3543 m_wantpurge(MC_BIGCL)++;
2d21ac55
A
3544 m_wantpurge(MC_MBUF_CL)++;
3545 m_wantpurge(MC_MBUF_BIGCL)++;
3546 break;
3547
3548 case MC_CL:
3549 m_wantpurge(MC_MBUF)++;
6d2010ae
A
3550 m_wantpurge(MC_BIGCL)++;
3551 m_wantpurge(MC_MBUF_BIGCL)++;
0a7de745 3552 if (!comp) {
2d21ac55 3553 m_wantpurge(MC_MBUF_CL)++;
0a7de745 3554 }
2d21ac55
A
3555 break;
3556
3557 case MC_BIGCL:
6d2010ae
A
3558 m_wantpurge(MC_MBUF)++;
3559 m_wantpurge(MC_CL)++;
3560 m_wantpurge(MC_MBUF_CL)++;
0a7de745 3561 if (!comp) {
2d21ac55 3562 m_wantpurge(MC_MBUF_BIGCL)++;
0a7de745 3563 }
2d21ac55
A
3564 break;
3565
3566 case MC_16KCL:
0a7de745 3567 if (!comp) {
2d21ac55 3568 m_wantpurge(MC_MBUF_16KCL)++;
0a7de745 3569 }
2d21ac55
A
3570 break;
3571
3572 default:
3573 VERIFY(0);
3574 /* NOTREACHED */
3575 }
3576
3577 /*
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.
3582 */
3583 for (m = 0; m < NELEM(mbuf_table); m++) {
3584 if (m_wantpurge(m) > 0) {
3585 m_wantpurge(m) = 0;
3586 /*
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.
3591 */
0a7de745 3592 if (!mbuf_steal(m, num)) {
2d21ac55 3593 bmap |= (1 << m);
0a7de745 3594 }
2d21ac55
A
3595 }
3596 }
3597
3598 lck_mtx_unlock(mbuf_mlock);
3599
3600 if (bmap != 0) {
39236c6e
A
3601 /* signal the domains to drain */
3602 net_drain_domains();
2d21ac55
A
3603
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)) &&
fe8ab488 3607 mcache_purge_cache(m_cache(m), TRUE)) {
2d21ac55
A
3608 lck_mtx_lock(mbuf_mlock);
3609 m_purge_cnt(m)++;
3610 mbstat.m_drain++;
3611 lck_mtx_unlock(mbuf_mlock);
3612 }
3613 }
3614 } else {
3615 /*
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
3618 * interval.
3619 */
3620 mcache_reap();
3621 }
3622 lck_mtx_lock(mbuf_mlock);
3623}
3624
3625static inline struct mbuf *
3626m_get_common(int wait, short type, int hdr)
3627{
3628 struct mbuf *m;
3629 int mcflags = MSLEEPF(wait);
3630
3631 /* Is this due to a non-blocking retry? If so, then try harder */
0a7de745 3632 if (mcflags & MCR_NOSLEEP) {
2d21ac55 3633 mcflags |= MCR_TRYHARD;
0a7de745 3634 }
2d21ac55
A
3635
3636 m = mcache_alloc(m_cache(MC_MBUF), mcflags);
3637 if (m != NULL) {
3638 MBUF_INIT(m, hdr, type);
3639 mtype_stat_inc(type);
3640 mtype_stat_dec(MT_FREE);
3641#if CONFIG_MACF_NET
3642 if (hdr && mac_init_mbuf(m, wait) != 0) {
3643 m_free(m);
0a7de745 3644 return NULL;
2d21ac55
A
3645 }
3646#endif /* MAC_NET */
3647 }
0a7de745 3648 return m;
2d21ac55
A
3649}
3650
3651/*
3652 * Space allocation routines; these are also available as macros
3653 * for critical paths.
3654 */
0a7de745
A
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))
2d21ac55
A
3661
3662struct mbuf *
3663m_get(int wait, int type)
3664{
0a7de745 3665 return _M_GET(wait, type);
2d21ac55
A
3666}
3667
3668struct mbuf *
3669m_gethdr(int wait, int type)
3670{
0a7de745 3671 return _M_GETHDR(wait, type);
2d21ac55
A
3672}
3673
3674struct mbuf *
3675m_retry(int wait, int type)
3676{
0a7de745 3677 return _M_RETRY(wait, type);
2d21ac55
A
3678}
3679
3680struct mbuf *
3681m_retryhdr(int wait, int type)
3682{
0a7de745 3683 return _M_RETRYHDR(wait, type);
2d21ac55
A
3684}
3685
3686struct mbuf *
3687m_getclr(int wait, int type)
3688{
3689 struct mbuf *m;
3690
3691 _MGET(m, wait, type);
0a7de745 3692 if (m != NULL) {
2d21ac55 3693 bzero(MTOD(m, caddr_t), MLEN);
0a7de745
A
3694 }
3695 return m;
2d21ac55
A
3696}
3697
39037602
A
3698static int
3699m_free_paired(struct mbuf *m)
3700{
3701 VERIFY((m->m_flags & M_EXT) && (MEXT_FLAGS(m) & EXTF_PAIRED));
3702
3703 membar_sync();
3704 if (MEXT_PMBUF(m) == m) {
3705 volatile UInt16 *addr = (volatile UInt16 *)&MEXT_PREF(m);
3706 int16_t oprefcnt, prefcnt;
3707
3708 /*
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.
3713 */
3714 do {
3715 oprefcnt = *addr;
3716 prefcnt = oprefcnt - 1;
3717 } while (!OSCompareAndSwap16(oprefcnt, prefcnt, addr));
3718
3719 if (prefcnt > 1) {
0a7de745 3720 return 1;
39037602 3721 } else if (prefcnt == 1) {
813fb2f6
A
3722 (*(m_get_ext_free(m)))(m->m_ext.ext_buf,
3723 m->m_ext.ext_size, m_get_ext_arg(m));
0a7de745 3724 return 1;
39037602
A
3725 } else if (prefcnt == 0) {
3726 VERIFY(MBUF_IS_PAIRED(m));
3727
3728 /*
3729 * Restore minref to its natural value, so that
3730 * the caller will be able to free the cluster
3731 * as appropriate.
3732 */
3733 MEXT_MINREF(m) = 0;
3734
3735 /*
3736 * Clear MEXT_PMBUF, but leave EXTF_PAIRED intact
3737 * as it is immutable. atomic_set_ptr also causes
3738 * memory barrier sync.
3739 */
3740 atomic_set_ptr(&MEXT_PMBUF(m), NULL);
3741
3742 switch (m->m_ext.ext_size) {
3743 case MCLBYTES:
813fb2f6 3744 m_set_ext(m, m_get_rfa(m), NULL, NULL);
39037602
A
3745 break;
3746
3747 case MBIGCLBYTES:
813fb2f6 3748 m_set_ext(m, m_get_rfa(m), m_bigfree, NULL);
39037602
A
3749 break;
3750
3751 case M16KCLBYTES:
813fb2f6 3752 m_set_ext(m, m_get_rfa(m), m_16kfree, NULL);
39037602
A
3753 break;
3754
3755 default:
3756 VERIFY(0);
3757 /* NOTREACHED */
3758 }
3759 }
3760 }
3761
3762 /*
3763 * Tell caller the unpair has occurred, and that the reference
3764 * count on the external cluster held for the paired mbuf should
3765 * now be dropped.
3766 */
0a7de745 3767 return 0;
39037602
A
3768}
3769
2d21ac55
A
3770struct mbuf *
3771m_free(struct mbuf *m)
3772{
3773 struct mbuf *n = m->m_next;
3774
0a7de745 3775 if (m->m_type == MT_FREE) {
2d21ac55 3776 panic("m_free: freeing an already freed mbuf");
0a7de745 3777 }
2d21ac55 3778
2d21ac55 3779 if (m->m_flags & M_PKTHDR) {
39236c6e
A
3780 /* Check for scratch area overflow */
3781 m_redzone_verify(m);
3782 /* Free the aux data and tags if there is any */
2d21ac55 3783 m_tag_delete_chain(m, NULL);
39037602
A
3784
3785 m_do_tx_compl_callback(m, NULL);
2d21ac55
A
3786 }
3787
3788 if (m->m_flags & M_EXT) {
39037602 3789 u_int16_t refcnt;
6d2010ae 3790 u_int32_t composite;
813fb2f6 3791 m_ext_free_func_t m_free_func;
2d21ac55 3792
0a7de745
A
3793 if (MBUF_IS_PAIRED(m) && m_free_paired(m)) {
3794 return n;
3795 }
39037602 3796
2d21ac55 3797 refcnt = m_decref(m);
6d2010ae 3798 composite = (MEXT_FLAGS(m) & EXTF_COMPOSITE);
813fb2f6 3799 m_free_func = m_get_ext_free(m);
39037602
A
3800
3801 if (refcnt == MEXT_MINREF(m) && !composite) {
813fb2f6 3802 if (m_free_func == NULL) {
2d21ac55 3803 mcache_free(m_cache(MC_CL), m->m_ext.ext_buf);
813fb2f6 3804 } else if (m_free_func == m_bigfree) {
2d21ac55
A
3805 mcache_free(m_cache(MC_BIGCL),
3806 m->m_ext.ext_buf);
813fb2f6 3807 } else if (m_free_func == m_16kfree) {
2d21ac55
A
3808 mcache_free(m_cache(MC_16KCL),
3809 m->m_ext.ext_buf);
3810 } else {
813fb2f6
A
3811 (*m_free_func)(m->m_ext.ext_buf,
3812 m->m_ext.ext_size, m_get_ext_arg(m));
2d21ac55 3813 }
813fb2f6
A
3814 mcache_free(ref_cache, m_get_rfa(m));
3815 m_set_ext(m, NULL, NULL, NULL);
39037602
A
3816 } else if (refcnt == MEXT_MINREF(m) && composite) {
3817 VERIFY(!(MEXT_FLAGS(m) & EXTF_PAIRED));
2d21ac55
A
3818 VERIFY(m->m_type != MT_FREE);
3819
3820 mtype_stat_dec(m->m_type);
3821 mtype_stat_inc(MT_FREE);
3822
3823 m->m_type = MT_FREE;
3824 m->m_flags = M_EXT;
3825 m->m_len = 0;
3826 m->m_next = m->m_nextpkt = NULL;
3827
6d2010ae
A
3828 MEXT_FLAGS(m) &= ~EXTF_READONLY;
3829
2d21ac55 3830 /* "Free" into the intermediate cache */
813fb2f6 3831 if (m_free_func == NULL) {
2d21ac55 3832 mcache_free(m_cache(MC_MBUF_CL), m);
813fb2f6 3833 } else if (m_free_func == m_bigfree) {
2d21ac55
A
3834 mcache_free(m_cache(MC_MBUF_BIGCL), m);
3835 } else {
813fb2f6 3836 VERIFY(m_free_func == m_16kfree);
2d21ac55
A
3837 mcache_free(m_cache(MC_MBUF_16KCL), m);
3838 }
0a7de745 3839 return n;
2d21ac55
A
3840 }
3841 }
3842
3843 if (m->m_type != MT_FREE) {
3844 mtype_stat_dec(m->m_type);
3845 mtype_stat_inc(MT_FREE);
3846 }
3847
3848 m->m_type = MT_FREE;
3849 m->m_flags = m->m_len = 0;
3850 m->m_next = m->m_nextpkt = NULL;
3851
3852 mcache_free(m_cache(MC_MBUF), m);
3853
0a7de745 3854 return n;
2d21ac55
A
3855}
3856
3857__private_extern__ struct mbuf *
3858m_clattach(struct mbuf *m, int type, caddr_t extbuf,
3859 void (*extfree)(caddr_t, u_int, caddr_t), u_int extsize, caddr_t extarg,
39037602 3860 int wait, int pair)
2d21ac55
A
3861{
3862 struct ext_ref *rfa = NULL;
3863
39037602
A
3864 /*
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.
3868 */
3869 if ((m != NULL && MBUF_IS_PAIRED(m)) ||
0a7de745
A
3870 (m == NULL && (m = _M_GETHDR(wait, type)) == NULL)) {
3871 return NULL;
3872 }
2d21ac55
A
3873
3874 if (m->m_flags & M_EXT) {
39037602 3875 u_int16_t refcnt;
6d2010ae 3876 u_int32_t composite;
813fb2f6 3877 m_ext_free_func_t m_free_func;
2d21ac55
A
3878
3879 refcnt = m_decref(m);
6d2010ae 3880 composite = (MEXT_FLAGS(m) & EXTF_COMPOSITE);
39037602 3881 VERIFY(!(MEXT_FLAGS(m) & EXTF_PAIRED) && MEXT_PMBUF(m) == NULL);
813fb2f6 3882 m_free_func = m_get_ext_free(m);
39037602 3883 if (refcnt == MEXT_MINREF(m) && !composite) {
813fb2f6 3884 if (m_free_func == NULL) {
2d21ac55 3885 mcache_free(m_cache(MC_CL), m->m_ext.ext_buf);
813fb2f6 3886 } else if (m_free_func == m_bigfree) {
2d21ac55
A
3887 mcache_free(m_cache(MC_BIGCL),
3888 m->m_ext.ext_buf);
813fb2f6 3889 } else if (m_free_func == m_16kfree) {
2d21ac55
A
3890 mcache_free(m_cache(MC_16KCL),
3891 m->m_ext.ext_buf);
3892 } else {
813fb2f6
A
3893 (*m_free_func)(m->m_ext.ext_buf,
3894 m->m_ext.ext_size, m_get_ext_arg(m));
2d21ac55
A
3895 }
3896 /* Re-use the reference structure */
813fb2f6 3897 rfa = m_get_rfa(m);
39037602 3898 } else if (refcnt == MEXT_MINREF(m) && composite) {
2d21ac55
A
3899 VERIFY(m->m_type != MT_FREE);
3900
3901 mtype_stat_dec(m->m_type);
3902 mtype_stat_inc(MT_FREE);
3903
3904 m->m_type = MT_FREE;
3905 m->m_flags = M_EXT;
3906 m->m_len = 0;
3907 m->m_next = m->m_nextpkt = NULL;
6d2010ae
A
3908
3909 MEXT_FLAGS(m) &= ~EXTF_READONLY;
3910
2d21ac55 3911 /* "Free" into the intermediate cache */
813fb2f6 3912 if (m_free_func == NULL) {
2d21ac55 3913 mcache_free(m_cache(MC_MBUF_CL), m);
813fb2f6 3914 } else if (m_free_func == m_bigfree) {
2d21ac55
A
3915 mcache_free(m_cache(MC_MBUF_BIGCL), m);
3916 } else {
813fb2f6 3917 VERIFY(m_free_func == m_16kfree);
2d21ac55
A
3918 mcache_free(m_cache(MC_MBUF_16KCL), m);
3919 }
3920 /*
3921 * Allocate a new mbuf, since we didn't divorce
3922 * the composite mbuf + cluster pair above.
3923 */
0a7de745
A
3924 if ((m = _M_GETHDR(wait, type)) == NULL) {
3925 return NULL;
3926 }
2d21ac55
A
3927 }
3928 }
3929
3930 if (rfa == NULL &&
3931 (rfa = mcache_alloc(ref_cache, MSLEEPF(wait))) == NULL) {
3932 m_free(m);
0a7de745 3933 return NULL;
2d21ac55
A
3934 }
3935
39037602
A
3936 if (!pair) {
3937 MEXT_INIT(m, extbuf, extsize, extfree, extarg, rfa,
3938 0, 1, 0, 0, 0, NULL);
3939 } else {
3940 MEXT_INIT(m, extbuf, extsize, extfree, (caddr_t)m, rfa,
3941 1, 1, 1, EXTF_PAIRED, 0, m);
3942 }
2d21ac55 3943
0a7de745 3944 return m;
2d21ac55
A
3945}
3946
b0d623f7
A
3947/*
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.)
3950 */
3951struct mbuf *
3952m_getcl(int wait, int type, int flags)
3953{
3954 struct mbuf *m;
3955 int mcflags = MSLEEPF(wait);
3956 int hdr = (flags & M_PKTHDR);
3957
3958 /* Is this due to a non-blocking retry? If so, then try harder */
0a7de745 3959 if (mcflags & MCR_NOSLEEP) {
b0d623f7 3960 mcflags |= MCR_TRYHARD;
0a7de745 3961 }
b0d623f7 3962
6d2010ae
A
3963 m = mcache_alloc(m_cache(MC_MBUF_CL), mcflags);
3964 if (m != NULL) {
39037602 3965 u_int16_t flag;
6d2010ae
A
3966 struct ext_ref *rfa;
3967 void *cl;
3968
3969 VERIFY(m->m_type == MT_FREE && m->m_flags == M_EXT);
3970 cl = m->m_ext.ext_buf;
813fb2f6 3971 rfa = m_get_rfa(m);
6d2010ae
A
3972
3973 ASSERT(cl != NULL && rfa != NULL);
813fb2f6 3974 VERIFY(MBUF_IS_COMPOSITE(m) && m_get_ext_free(m) == NULL);
6d2010ae
A
3975
3976 flag = MEXT_FLAGS(m);
3977
b0d623f7 3978 MBUF_INIT(m, hdr, type);
6d2010ae
A
3979 MBUF_CL_INIT(m, cl, rfa, 1, flag);
3980
b0d623f7
A
3981 mtype_stat_inc(type);
3982 mtype_stat_dec(MT_FREE);
3983#if CONFIG_MACF_NET
3984 if (hdr && mac_init_mbuf(m, wait) != 0) {
6d2010ae 3985 m_freem(m);
0a7de745 3986 return NULL;
b0d623f7
A
3987 }
3988#endif /* MAC_NET */
3989 }
0a7de745 3990 return m;
b0d623f7
A
3991}
3992
2d21ac55
A
3993/* m_mclget() add an mbuf cluster to a normal mbuf */
3994struct mbuf *
3995m_mclget(struct mbuf *m, int wait)
3996{
3997 struct ext_ref *rfa;
3998
0a7de745
A
3999 if ((rfa = mcache_alloc(ref_cache, MSLEEPF(wait))) == NULL) {
4000 return m;
4001 }
2d21ac55
A
4002
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);
4006 } else {
4007 mcache_free(ref_cache, rfa);
4008 }
0a7de745 4009 return m;
2d21ac55
A
4010}
4011
4012/* Allocate an mbuf cluster */
4013caddr_t
4014m_mclalloc(int wait)
4015{
4016 int mcflags = MSLEEPF(wait);
4017
4018 /* Is this due to a non-blocking retry? If so, then try harder */
0a7de745 4019 if (mcflags & MCR_NOSLEEP) {
2d21ac55 4020 mcflags |= MCR_TRYHARD;
0a7de745 4021 }
2d21ac55 4022
0a7de745 4023 return mcache_alloc(m_cache(MC_CL), mcflags);
2d21ac55
A
4024}
4025
4026/* Free an mbuf cluster */
4027void
4028m_mclfree(caddr_t p)
4029{
4030 mcache_free(m_cache(MC_CL), p);
4031}
4032
4033/*
4034 * mcl_hasreference() checks if a cluster of an mbuf is referenced by
6d2010ae 4035 * another mbuf; see comments in m_incref() regarding EXTF_READONLY.
2d21ac55
A
4036 */
4037int
4038m_mclhasreference(struct mbuf *m)
4039{
0a7de745
A
4040 if (!(m->m_flags & M_EXT)) {
4041 return 0;
4042 }
9bccf70c 4043
813fb2f6 4044 ASSERT(m_get_rfa(m) != NULL);
2d21ac55 4045
0a7de745 4046 return (MEXT_FLAGS(m) & EXTF_READONLY) ? 1 : 0;
9bccf70c
A
4047}
4048
2d21ac55
A
4049__private_extern__ caddr_t
4050m_bigalloc(int wait)
9bccf70c 4051{
2d21ac55 4052 int mcflags = MSLEEPF(wait);
91447636 4053
2d21ac55 4054 /* Is this due to a non-blocking retry? If so, then try harder */
0a7de745 4055 if (mcflags & MCR_NOSLEEP) {
2d21ac55 4056 mcflags |= MCR_TRYHARD;
0a7de745 4057 }
91447636 4058
0a7de745 4059 return mcache_alloc(m_cache(MC_BIGCL), mcflags);
9bccf70c
A
4060}
4061
2d21ac55
A
4062__private_extern__ void
4063m_bigfree(caddr_t p, __unused u_int size, __unused caddr_t arg)
9bccf70c 4064{
2d21ac55 4065 mcache_free(m_cache(MC_BIGCL), p);
9bccf70c
A
4066}
4067
2d21ac55
A
4068/* m_mbigget() add an 4KB mbuf cluster to a normal mbuf */
4069__private_extern__ struct mbuf *
4070m_mbigget(struct mbuf *m, int wait)
4071{
4072 struct ext_ref *rfa;
4073
0a7de745
A
4074 if ((rfa = mcache_alloc(ref_cache, MSLEEPF(wait))) == NULL) {
4075 return m;
4076 }
2d21ac55
A
4077
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);
91447636 4081 } else {
2d21ac55 4082 mcache_free(ref_cache, rfa);
91447636 4083 }
0a7de745 4084 return m;
2d21ac55
A
4085}
4086
4087__private_extern__ caddr_t
4088m_16kalloc(int wait)
4089{
4090 int mcflags = MSLEEPF(wait);
4091
4092 /* Is this due to a non-blocking retry? If so, then try harder */
0a7de745 4093 if (mcflags & MCR_NOSLEEP) {
2d21ac55 4094 mcflags |= MCR_TRYHARD;
0a7de745 4095 }
2d21ac55 4096
0a7de745 4097 return mcache_alloc(m_cache(MC_16KCL), mcflags);
91447636
A
4098}
4099
4100__private_extern__ void
2d21ac55 4101m_16kfree(caddr_t p, __unused u_int size, __unused caddr_t arg)
91447636 4102{
2d21ac55 4103 mcache_free(m_cache(MC_16KCL), p);
91447636
A
4104}
4105
2d21ac55 4106/* m_m16kget() add a 16KB mbuf cluster to a normal mbuf */
91447636 4107__private_extern__ struct mbuf *
2d21ac55 4108m_m16kget(struct mbuf *m, int wait)
91447636 4109{
2d21ac55
A
4110 struct ext_ref *rfa;
4111
0a7de745
A
4112 if ((rfa = mcache_alloc(ref_cache, MSLEEPF(wait))) == NULL) {
4113 return m;
4114 }
2d21ac55
A
4115
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);
4119 } else {
4120 mcache_free(ref_cache, rfa);
91447636 4121 }
0a7de745 4122 return m;
91447636
A
4123}
4124
b0d623f7
A
4125/*
4126 * "Move" mbuf pkthdr from "from" to "to".
4127 * "from" must have M_PKTHDR set, and "to" must be empty.
4128 */
9bccf70c 4129void
2d21ac55 4130m_copy_pkthdr(struct mbuf *to, struct mbuf *from)
9bccf70c 4131{
39236c6e
A
4132 VERIFY(from->m_flags & M_PKTHDR);
4133
4134 /* Check for scratch area overflow */
4135 m_redzone_verify(from);
4136
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' */
2d21ac55 4141 m_tag_delete_chain(to, NULL);
39236c6e 4142 }
0a7de745
A
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 */
935ed37a 4147 to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
0a7de745 4148 if ((to->m_flags & M_EXT) == 0) {
935ed37a 4149 to->m_data = to->m_pktdat;
0a7de745
A
4150 }
4151 m_redzone_init(to); /* setup red zone on dst */
9bccf70c
A
4152}
4153
91447636
A
4154/*
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.
4158 */
3a60a9f5 4159static int
91447636
A
4160m_dup_pkthdr(struct mbuf *to, struct mbuf *from, int how)
4161{
39236c6e
A
4162 VERIFY(from->m_flags & M_PKTHDR);
4163
4164 /* Check for scratch area overflow */
4165 m_redzone_verify(from);
4166
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' */
2d21ac55 4171 m_tag_delete_chain(to, NULL);
39236c6e 4172 }
2d21ac55 4173 to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
0a7de745 4174 if ((to->m_flags & M_EXT) == 0) {
2d21ac55 4175 to->m_data = to->m_pktdat;
0a7de745 4176 }
2d21ac55 4177 to->m_pkthdr = from->m_pkthdr;
0a7de745
A
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);
91447636 4181}
fa4905b1 4182
316670eb
A
4183void
4184m_copy_pftag(struct mbuf *to, struct mbuf *from)
4185{
39037602 4186 memcpy(m_pftag(to), m_pftag(from), sizeof(struct pf_mtag));
39236c6e 4187#if PF_ECN
39037602 4188 m_pftag(to)->pftag_hdr = NULL;
0a7de745 4189 m_pftag(to)->pftag_flags &= ~(PF_TAG_HDR_INET | PF_TAG_HDR_INET6);
39236c6e
A
4190#endif /* PF_ECN */
4191}
4192
4193void
4194m_classifier_init(struct mbuf *m, uint32_t pktf_mask)
4195{
4196 VERIFY(m->m_flags & M_PKTHDR);
4197
4198 m->m_pkthdr.pkt_proto = 0;
4199 m->m_pkthdr.pkt_flowsrc = 0;
4200 m->m_pkthdr.pkt_flowid = 0;
0a7de745 4201 m->m_pkthdr.pkt_flags &= pktf_mask; /* caller-defined mask */
39236c6e 4202 /* preserve service class and interface info for loopback packets */
0a7de745 4203 if (!(m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
39236c6e 4204 (void) m_set_service_class(m, MBUF_SC_BE);
0a7de745
A
4205 }
4206 if (!(m->m_pkthdr.pkt_flags & PKTF_IFAINFO)) {
39236c6e 4207 m->m_pkthdr.pkt_ifainfo = 0;
0a7de745 4208 }
5ba3f43e
A
4209 /*
4210 * Preserve timestamp if requested
4211 */
0a7de745 4212 if (!(m->m_pkthdr.pkt_flags & PKTF_TS_VALID)) {
5ba3f43e 4213 m->m_pkthdr.pkt_timestamp = 0;
0a7de745 4214 }
39236c6e
A
4215}
4216
4217void
4218m_copy_classifier(struct mbuf *to, struct mbuf *from)
4219{
4220 VERIFY(to->m_flags & M_PKTHDR);
4221 VERIFY(from->m_flags & M_PKTHDR);
4222
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;
316670eb
A
4229}
4230
9bccf70c 4231/*
2d21ac55
A
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.
9bccf70c 4238 */
91447636 4239__private_extern__ struct mbuf *
2d21ac55
A
4240m_getpackets_internal(unsigned int *num_needed, int num_with_pkthdrs,
4241 int wait, int wantall, size_t bufsize)
fa4905b1
A
4242{
4243 struct mbuf *m;
4244 struct mbuf **np, *top;
2d21ac55
A
4245 unsigned int pnum, needed = *num_needed;
4246 mcache_obj_t *mp_list = NULL;
4247 int mcflags = MSLEEPF(wait);
39037602 4248 u_int16_t flag;
2d21ac55
A
4249 struct ext_ref *rfa;
4250 mcache_t *cp;
4251 void *cl;
4252
4253 ASSERT(bufsize == m_maxsize(MC_CL) ||
4254 bufsize == m_maxsize(MC_BIGCL) ||
4255 bufsize == m_maxsize(MC_16KCL));
4256
4257 /*
4258 * Caller must first check for njcl because this
4259 * routine is internal and not exposed/used via KPI.
4260 */
4261 VERIFY(bufsize != m_maxsize(MC_16KCL) || njcl > 0);
4262
fa4905b1
A
4263 top = NULL;
4264 np = &top;
2d21ac55 4265 pnum = 0;
fa4905b1 4266
2d21ac55
A
4267 /*
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.
4272 */
0a7de745 4273 if (!wantall || (mcflags & MCR_NOSLEEP)) {
2d21ac55 4274 mcflags |= MCR_TRYHARD;
0a7de745 4275 }
2d21ac55
A
4276
4277 /* Allocate the composite mbuf + cluster elements from the cache */
0a7de745 4278 if (bufsize == m_maxsize(MC_CL)) {
2d21ac55 4279 cp = m_cache(MC_MBUF_CL);
0a7de745 4280 } else if (bufsize == m_maxsize(MC_BIGCL)) {
2d21ac55 4281 cp = m_cache(MC_MBUF_BIGCL);
0a7de745 4282 } else {
2d21ac55 4283 cp = m_cache(MC_MBUF_16KCL);
0a7de745 4284 }
2d21ac55
A
4285 needed = mcache_alloc_ext(cp, &mp_list, needed, mcflags);
4286
4287 for (pnum = 0; pnum < needed; pnum++) {
4288 m = (struct mbuf *)mp_list;
4289 mp_list = mp_list->obj_next;
4290
4291 VERIFY(m->m_type == MT_FREE && m->m_flags == M_EXT);
4292 cl = m->m_ext.ext_buf;
813fb2f6 4293 rfa = m_get_rfa(m);
2d21ac55
A
4294
4295 ASSERT(cl != NULL && rfa != NULL);
4296 VERIFY(MBUF_IS_COMPOSITE(m));
4297
4298 flag = MEXT_FLAGS(m);
4299
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);
91447636 4305 } else {
2d21ac55
A
4306 MBUF_CL_INIT(m, cl, rfa, 1, flag);
4307 }
4308
4309 if (num_with_pkthdrs > 0) {
4310 --num_with_pkthdrs;
4311#if CONFIG_MACF_NET
4312 if (mac_mbuf_label_init(m, wait) != 0) {
6d2010ae 4313 m_freem(m);
2d21ac55 4314 break;
91447636 4315 }
2d21ac55 4316#endif /* MAC_NET */
91447636 4317 }
2d21ac55
A
4318
4319 *np = m;
0a7de745 4320 if (num_with_pkthdrs > 0) {
91447636 4321 np = &m->m_nextpkt;
0a7de745 4322 } else {
91447636 4323 np = &m->m_next;
0a7de745 4324 }
91447636 4325 }
2d21ac55 4326 ASSERT(pnum != *num_needed || mp_list == NULL);
0a7de745 4327 if (mp_list != NULL) {
2d21ac55 4328 mcache_free_ext(cp, mp_list);
0a7de745 4329 }
2d21ac55
A
4330
4331 if (pnum > 0) {
4332 mtype_stat_add(MT_DATA, pnum);
4333 mtype_stat_sub(MT_FREE, pnum);
4334 }
4335
4336 if (wantall && (pnum != *num_needed)) {
0a7de745 4337 if (top != NULL) {
2d21ac55 4338 m_freem_list(top);
0a7de745
A
4339 }
4340 return NULL;
91447636 4341 }
fa4905b1 4342
316670eb
A
4343 if (pnum > *num_needed) {
4344 printf("%s: File a radar related to <rdar://10146739>. \
4345 needed = %u, pnum = %u, num_needed = %u \n",
0a7de745 4346 __func__, needed, pnum, *num_needed);
39037602 4347 }
316670eb 4348
2d21ac55 4349 *num_needed = pnum;
0a7de745 4350 return top;
2d21ac55 4351}
fa4905b1 4352
91447636 4353/*
2d21ac55
A
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.
91447636 4364 */
91447636 4365__private_extern__ struct mbuf *
2d21ac55
A
4366m_allocpacket_internal(unsigned int *numlist, size_t packetlen,
4367 unsigned int *maxsegments, int wait, int wantall, size_t wantsize)
91447636 4368{
2d21ac55
A
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;
4377
0a7de745
A
4378 if (*numlist == 0) {
4379 return NULL;
4380 }
fa4905b1 4381
91447636
A
4382 top = NULL;
4383 np = &top;
2d21ac55 4384
91447636 4385 if (wantsize == 0) {
2d21ac55 4386 if (packetlen <= MINCLSIZE) {
91447636 4387 bufsize = packetlen;
2d21ac55
A
4388 } else if (packetlen > m_maxsize(MC_CL)) {
4389 /* Use 4KB if jumbo cluster pool isn't available */
0a7de745 4390 if (packetlen <= m_maxsize(MC_BIGCL) || njcl == 0) {
2d21ac55 4391 bufsize = m_maxsize(MC_BIGCL);
0a7de745 4392 } else {
2d21ac55 4393 bufsize = m_maxsize(MC_16KCL);
0a7de745 4394 }
2d21ac55
A
4395 } else {
4396 bufsize = m_maxsize(MC_CL);
4397 }
4398 } else if (wantsize == m_maxsize(MC_CL) ||
4399 wantsize == m_maxsize(MC_BIGCL) ||
4400 (wantsize == m_maxsize(MC_16KCL) && njcl > 0)) {
91447636 4401 bufsize = wantsize;
2d21ac55 4402 } else {
0a7de745 4403 return NULL;
2d21ac55 4404 }
91447636
A
4405
4406 if (bufsize <= MHLEN) {
2d21ac55 4407 nsegs = 1;
91447636
A
4408 } else if (bufsize <= MINCLSIZE) {
4409 if (maxsegments != NULL && *maxsegments == 1) {
2d21ac55
A
4410 bufsize = m_maxsize(MC_CL);
4411 nsegs = 1;
91447636 4412 } else {
2d21ac55 4413 nsegs = 2;
fa4905b1 4414 }
2d21ac55
A
4415 } else if (bufsize == m_maxsize(MC_16KCL)) {
4416 VERIFY(njcl > 0);
3e170ce0 4417 nsegs = ((packetlen - 1) >> M16KCLSHIFT) + 1;
2d21ac55 4418 } else if (bufsize == m_maxsize(MC_BIGCL)) {
3e170ce0 4419 nsegs = ((packetlen - 1) >> MBIGCLSHIFT) + 1;
91447636 4420 } else {
2d21ac55 4421 nsegs = ((packetlen - 1) >> MCLSHIFT) + 1;
91447636
A
4422 }
4423 if (maxsegments != NULL) {
2d21ac55
A
4424 if (*maxsegments && nsegs > *maxsegments) {
4425 *maxsegments = nsegs;
0a7de745 4426 return NULL;
91447636 4427 }
2d21ac55 4428 *maxsegments = nsegs;
91447636 4429 }
91447636 4430
2d21ac55
A
4431 /*
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.
4436 */
0a7de745 4437 if (!wantall || (mcflags & MCR_NOSLEEP)) {
2d21ac55 4438 mcflags |= MCR_TRYHARD;
0a7de745 4439 }
2d21ac55
A
4440
4441 /*
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.
4447 */
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);
4454
4455 /*
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.
4461 */
0a7de745 4462 if (bufsize > MHLEN && (needed & 0x1)) {
2d21ac55 4463 needed--;
0a7de745 4464 }
91447636 4465
2d21ac55
A
4466 while (num < needed) {
4467 struct mbuf *m;
91447636 4468
2d21ac55
A
4469 m = (struct mbuf *)mp_list;
4470 mp_list = mp_list->obj_next;
4471 ASSERT(m != NULL);
91447636 4472
2d21ac55
A
4473 MBUF_INIT(m, 1, MT_DATA);
4474#if CONFIG_MACF_NET
4475 if (mac_init_mbuf(m, wait) != 0) {
4476 m_free(m);
4477 break;
91447636 4478 }
2d21ac55
A
4479#endif /* MAC_NET */
4480 num++;
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);
4486
4487 MBUF_INIT(m->m_next, 0, MT_DATA);
4488 num++;
91447636 4489 }
2d21ac55
A
4490 *np = m;
4491 np = &m->m_nextpkt;
4492 }
4493 ASSERT(num != *numlist || mp_list == NULL);
4494
4495 if (num > 0) {
4496 mtype_stat_add(MT_DATA, num);
4497 mtype_stat_sub(MT_FREE, num);
4498 }
4499 num /= nsegs;
4500
4501 /* We've got them all; return to caller */
0a7de745
A
4502 if (num == *numlist) {
4503 return top;
4504 }
2d21ac55
A
4505
4506 goto fail;
4507 }
4508
4509 /*
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:
4513 *
4514 * [mbuf + cluster 1] [mbuf + cluster 2] ... [mbuf + cluster N]
4515 *
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.
4524 */
4525 r_bufsize = bufsize;
4526 resid = packetlen > bufsize ? packetlen % bufsize : 0;
4527 if (resid > 0) {
4528 /* There is residual data; figure out the cluster size */
4529 if (wantsize == 0 && packetlen > MINCLSIZE) {
4530 /*
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.
4534 */
0a7de745 4535 if (njcl > 0 && resid > m_maxsize(MC_BIGCL)) {
2d21ac55 4536 r_bufsize = m_maxsize(MC_16KCL);
0a7de745 4537 } else if (resid > m_maxsize(MC_CL)) {
2d21ac55 4538 r_bufsize = m_maxsize(MC_BIGCL);
0a7de745 4539 } else {
2d21ac55 4540 r_bufsize = m_maxsize(MC_CL);
0a7de745 4541 }
2d21ac55
A
4542 } else {
4543 /* Use the same cluster size as the other segments */
4544 resid = 0;
4545 }
4546 }
4547
4548 needed = *numlist;
4549 if (resid > 0) {
4550 /*
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.
4555 */
0a7de745 4556 if (r_bufsize <= m_maxsize(MC_CL)) {
2d21ac55 4557 rcp = m_cache(MC_MBUF_CL);
0a7de745 4558 } else if (r_bufsize <= m_maxsize(MC_BIGCL)) {
2d21ac55 4559 rcp = m_cache(MC_MBUF_BIGCL);
0a7de745 4560 } else {
2d21ac55 4561 rcp = m_cache(MC_MBUF_16KCL);
0a7de745 4562 }
2d21ac55
A
4563 needed = mcache_alloc_ext(rcp, &rmp_list, *numlist, mcflags);
4564
0a7de745 4565 if (needed == 0) {
2d21ac55 4566 goto fail;
0a7de745 4567 }
2d21ac55
A
4568
4569 /* This is temporarily reduced for calculation */
4570 ASSERT(nsegs > 1);
4571 nsegs--;
4572 }
4573
4574 /*
4575 * Attempt to allocate the rest of the composite mbuf + cluster
4576 * elements for the number of segment chains that we need.
4577 */
0a7de745 4578 if (bufsize <= m_maxsize(MC_CL)) {
2d21ac55 4579 cp = m_cache(MC_MBUF_CL);
0a7de745 4580 } else if (bufsize <= m_maxsize(MC_BIGCL)) {
2d21ac55 4581 cp = m_cache(MC_MBUF_BIGCL);
0a7de745 4582 } else {
2d21ac55 4583 cp = m_cache(MC_MBUF_16KCL);
0a7de745 4584 }
2d21ac55
A
4585 needed = mcache_alloc_ext(cp, &mp_list, needed * nsegs, mcflags);
4586
4587 /* Round it down to avoid creating a partial segment chain */
4588 needed = (needed / nsegs) * nsegs;
0a7de745 4589 if (needed == 0) {
2d21ac55 4590 goto fail;
0a7de745 4591 }
2d21ac55
A
4592
4593 if (resid > 0) {
4594 /*
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.
4599 */
4600 ASSERT(nsegs > 0);
4601 needed += needed / nsegs;
4602 nsegs++;
4603 }
4604
4605 for (;;) {
4606 struct mbuf *m;
39037602 4607 u_int16_t flag;
2d21ac55
A
4608 struct ext_ref *rfa;
4609 void *cl;
4610 int pkthdr;
813fb2f6 4611 m_ext_free_func_t m_free_func;
2d21ac55
A
4612
4613 ++num;
4614 if (nsegs == 1 || (num % nsegs) != 0 || resid == 0) {
4615 m = (struct mbuf *)mp_list;
4616 mp_list = mp_list->obj_next;
4617 } else {
4618 m = (struct mbuf *)rmp_list;
4619 rmp_list = rmp_list->obj_next;
4620 }
813fb2f6 4621 m_free_func = m_get_ext_free(m);
2d21ac55
A
4622 ASSERT(m != NULL);
4623 VERIFY(m->m_type == MT_FREE && m->m_flags == M_EXT);
813fb2f6
A
4624 VERIFY(m_free_func == NULL || m_free_func == m_bigfree ||
4625 m_free_func == m_16kfree);
2d21ac55
A
4626
4627 cl = m->m_ext.ext_buf;
813fb2f6 4628 rfa = m_get_rfa(m);
2d21ac55
A
4629
4630 ASSERT(cl != NULL && rfa != NULL);
4631 VERIFY(MBUF_IS_COMPOSITE(m));
4632
4633 flag = MEXT_FLAGS(m);
4634
4635 pkthdr = (nsegs == 1 || (num % nsegs) == 1);
0a7de745 4636 if (pkthdr) {
2d21ac55 4637 first = m;
0a7de745 4638 }
2d21ac55 4639 MBUF_INIT(m, pkthdr, MT_DATA);
813fb2f6 4640 if (m_free_func == m_16kfree) {
2d21ac55 4641 MBUF_16KCL_INIT(m, cl, rfa, 1, flag);
813fb2f6 4642 } else if (m_free_func == m_bigfree) {
2d21ac55
A
4643 MBUF_BIGCL_INIT(m, cl, rfa, 1, flag);
4644 } else {
4645 MBUF_CL_INIT(m, cl, rfa, 1, flag);
4646 }
4647#if CONFIG_MACF_NET
4648 if (pkthdr && mac_init_mbuf(m, wait) != 0) {
4649 --num;
6d2010ae 4650 m_freem(m);
2d21ac55 4651 break;
91447636 4652 }
2d21ac55
A
4653#endif /* MAC_NET */
4654
4655 *np = m;
0a7de745 4656 if ((num % nsegs) == 0) {
2d21ac55 4657 np = &first->m_nextpkt;
0a7de745 4658 } else {
2d21ac55 4659 np = &m->m_next;
0a7de745 4660 }
2d21ac55 4661
0a7de745 4662 if (num == needed) {
2d21ac55 4663 break;
0a7de745 4664 }
2d21ac55
A
4665 }
4666
4667 if (num > 0) {
4668 mtype_stat_add(MT_DATA, num);
4669 mtype_stat_sub(MT_FREE, num);
91447636 4670 }
2d21ac55
A
4671
4672 num /= nsegs;
4673
4674 /* We've got them all; return to caller */
4675 if (num == *numlist) {
4676 ASSERT(mp_list == NULL && rmp_list == NULL);
0a7de745 4677 return top;
2d21ac55
A
4678 }
4679
91447636 4680fail:
2d21ac55 4681 /* Free up what's left of the above */
0a7de745 4682 if (mp_list != NULL) {
2d21ac55 4683 mcache_free_ext(cp, mp_list);
0a7de745
A
4684 }
4685 if (rmp_list != NULL) {
2d21ac55 4686 mcache_free_ext(rcp, rmp_list);
0a7de745 4687 }
2d21ac55 4688 if (wantall && top != NULL) {
cb323159 4689 m_freem_list(top);
0a7de745 4690 return NULL;
91447636 4691 }
2d21ac55 4692 *numlist = num;
0a7de745 4693 return top;
91447636 4694}
fa4905b1 4695
2d21ac55
A
4696/*
4697 * Best effort to get a mbuf cluster + pkthdr. Used by drivers to allocated
4698 * packets on receive ring.
91447636
A
4699 */
4700__private_extern__ struct mbuf *
2d21ac55 4701m_getpacket_how(int wait)
91447636
A
4702{
4703 unsigned int num_needed = 1;
2d21ac55 4704
0a7de745
A
4705 return m_getpackets_internal(&num_needed, 1, wait, 1,
4706 m_maxsize(MC_CL));
91447636 4707}
fa4905b1 4708
2d21ac55
A
4709/*
4710 * Best effort to get a mbuf cluster + pkthdr. Used by drivers to allocated
4711 * packets on receive ring.
91447636
A
4712 */
4713struct mbuf *
4714m_getpacket(void)
4715{
4716 unsigned int num_needed = 1;
9bccf70c 4717
0a7de745
A
4718 return m_getpackets_internal(&num_needed, 1, M_WAIT, 1,
4719 m_maxsize(MC_CL));
91447636 4720}
fa4905b1 4721
91447636 4722/*
2d21ac55
A
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.
91447636
A
4728 */
4729struct mbuf *
4730m_getpackets(int num_needed, int num_with_pkthdrs, int how)
4731{
4732 unsigned int n = num_needed;
fa4905b1 4733
0a7de745
A
4734 return m_getpackets_internal(&n, num_with_pkthdrs, how, 0,
4735 m_maxsize(MC_CL));
2d21ac55 4736}
fa4905b1 4737
9bccf70c 4738/*
2d21ac55
A
4739 * Return a list of mbuf hdrs set up as packet hdrs chained together
4740 * on the m_nextpkt field
9bccf70c 4741 */
fa4905b1
A
4742struct mbuf *
4743m_getpackethdrs(int num_needed, int how)
4744{
4745 struct mbuf *m;
4746 struct mbuf **np, *top;
4747
4748 top = NULL;
4749 np = &top;
4750
fa4905b1 4751 while (num_needed--) {
2d21ac55 4752 m = _M_RETRYHDR(how, MT_DATA);
0a7de745 4753 if (m == NULL) {
2d21ac55 4754 break;
0a7de745 4755 }
2d21ac55
A
4756
4757 *np = m;
4758 np = &m->m_nextpkt;
4759 }
fa4905b1 4760
0a7de745 4761 return top;
fa4905b1
A
4762}
4763
2d21ac55
A
4764/*
4765 * Free an mbuf list (m_nextpkt) while following m_next. Returns the count
4766 * for mbufs packets freed. Used by the drivers.
1c79356b 4767 */
2d21ac55
A
4768int
4769m_freem_list(struct mbuf *m)
1c79356b
A
4770{
4771 struct mbuf *nextpkt;
2d21ac55
A
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;
4780 int pktcount = 0;
4781 int mt_free = 0, mt_data = 0, mt_header = 0, mt_soname = 0, mt_tag = 0;
4782
4783 while (m != NULL) {
4784 pktcount++;
4785
4786 nextpkt = m->m_nextpkt;
4787 m->m_nextpkt = NULL;
4788
4789 while (m != NULL) {
4790 struct mbuf *next = m->m_next;
4791 mcache_obj_t *o, *rfa;
39037602
A
4792 u_int32_t composite;
4793 u_int16_t refcnt;
813fb2f6 4794 m_ext_free_func_t m_free_func;
fa4905b1 4795
0a7de745 4796 if (m->m_type == MT_FREE) {
2d21ac55 4797 panic("m_free: freeing an already freed mbuf");
0a7de745 4798 }
9bccf70c 4799
2d21ac55 4800 if (m->m_flags & M_PKTHDR) {
39236c6e
A
4801 /* Check for scratch area overflow */
4802 m_redzone_verify(m);
4803 /* Free the aux data and tags if there is any */
91447636 4804 m_tag_delete_chain(m, NULL);
91447636 4805 }
9bccf70c 4806
39037602
A
4807 if (!(m->m_flags & M_EXT)) {
4808 mt_free++;
2d21ac55 4809 goto simple_free;
39037602
A
4810 }
4811
4812 if (MBUF_IS_PAIRED(m) && m_free_paired(m)) {
4813 m = next;
4814 continue;
4815 }
4816
4817 mt_free++;
2d21ac55 4818
316670eb 4819 o = (mcache_obj_t *)(void *)m->m_ext.ext_buf;
2d21ac55 4820 refcnt = m_decref(m);
6d2010ae 4821 composite = (MEXT_FLAGS(m) & EXTF_COMPOSITE);
813fb2f6 4822 m_free_func = m_get_ext_free(m);
39037602 4823 if (refcnt == MEXT_MINREF(m) && !composite) {
813fb2f6 4824 if (m_free_func == NULL) {
2d21ac55
A
4825 o->obj_next = mcl_list;
4826 mcl_list = o;
813fb2f6 4827 } else if (m_free_func == m_bigfree) {
2d21ac55
A
4828 o->obj_next = mbc_list;
4829 mbc_list = o;
813fb2f6 4830 } else if (m_free_func == m_16kfree) {
2d21ac55
A
4831 o->obj_next = m16k_list;
4832 m16k_list = o;
4833 } else {
813fb2f6 4834 (*(m_free_func))((caddr_t)o,
2d21ac55 4835 m->m_ext.ext_size,
813fb2f6 4836 m_get_ext_arg(m));
2d21ac55 4837 }
813fb2f6 4838 rfa = (mcache_obj_t *)(void *)m_get_rfa(m);
2d21ac55
A
4839 rfa->obj_next = ref_list;
4840 ref_list = rfa;
813fb2f6 4841 m_set_ext(m, NULL, NULL, NULL);
39037602
A
4842 } else if (refcnt == MEXT_MINREF(m) && composite) {
4843 VERIFY(!(MEXT_FLAGS(m) & EXTF_PAIRED));
2d21ac55
A
4844 VERIFY(m->m_type != MT_FREE);
4845 /*
4846 * Amortize the costs of atomic operations
4847 * by doing them at the end, if possible.
4848 */
0a7de745 4849 if (m->m_type == MT_DATA) {
2d21ac55 4850 mt_data++;
0a7de745 4851 } else if (m->m_type == MT_HEADER) {
2d21ac55 4852 mt_header++;
0a7de745 4853 } else if (m->m_type == MT_SONAME) {
2d21ac55 4854 mt_soname++;
0a7de745 4855 } else if (m->m_type == MT_TAG) {
2d21ac55 4856 mt_tag++;
0a7de745 4857 } else {
2d21ac55 4858 mtype_stat_dec(m->m_type);
0a7de745 4859 }
fa4905b1 4860
2d21ac55
A
4861 m->m_type = MT_FREE;
4862 m->m_flags = M_EXT;
4863 m->m_len = 0;
4864 m->m_next = m->m_nextpkt = NULL;
4865
6d2010ae
A
4866 MEXT_FLAGS(m) &= ~EXTF_READONLY;
4867
2d21ac55
A
4868 /* "Free" into the intermediate cache */
4869 o = (mcache_obj_t *)m;
813fb2f6 4870 if (m_free_func == NULL) {
2d21ac55
A
4871 o->obj_next = m_mcl_list;
4872 m_mcl_list = o;
813fb2f6 4873 } else if (m_free_func == m_bigfree) {
2d21ac55
A
4874 o->obj_next = m_mbc_list;
4875 m_mbc_list = o;
1c79356b 4876 } else {
813fb2f6 4877 VERIFY(m_free_func == m_16kfree);
2d21ac55
A
4878 o->obj_next = m_m16k_list;
4879 m_m16k_list = o;
1c79356b 4880 }
2d21ac55
A
4881 m = next;
4882 continue;
1c79356b 4883 }
2d21ac55
A
4884simple_free:
4885 /*
4886 * Amortize the costs of atomic operations
4887 * by doing them at the end, if possible.
4888 */
0a7de745 4889 if (m->m_type == MT_DATA) {
2d21ac55 4890 mt_data++;
0a7de745 4891 } else if (m->m_type == MT_HEADER) {
2d21ac55 4892 mt_header++;
0a7de745 4893 } else if (m->m_type == MT_SONAME) {
2d21ac55 4894 mt_soname++;
0a7de745 4895 } else if (m->m_type == MT_TAG) {
2d21ac55 4896 mt_tag++;
0a7de745 4897 } else if (m->m_type != MT_FREE) {
2d21ac55 4898 mtype_stat_dec(m->m_type);
0a7de745 4899 }
2d21ac55 4900
1c79356b 4901 m->m_type = MT_FREE;
2d21ac55
A
4902 m->m_flags = m->m_len = 0;
4903 m->m_next = m->m_nextpkt = NULL;
fa4905b1 4904
2d21ac55
A
4905 ((mcache_obj_t *)m)->obj_next = mp_list;
4906 mp_list = (mcache_obj_t *)m;
4907
4908 m = next;
4909 }
fa4905b1 4910
2d21ac55
A
4911 m = nextpkt;
4912 }
fa4905b1 4913
0a7de745 4914 if (mt_free > 0) {
2d21ac55 4915 mtype_stat_add(MT_FREE, mt_free);
0a7de745
A
4916 }
4917 if (mt_data > 0) {
2d21ac55 4918 mtype_stat_sub(MT_DATA, mt_data);
0a7de745
A
4919 }
4920 if (mt_header > 0) {
2d21ac55 4921 mtype_stat_sub(MT_HEADER, mt_header);
0a7de745
A
4922 }
4923 if (mt_soname > 0) {
2d21ac55 4924 mtype_stat_sub(MT_SONAME, mt_soname);
0a7de745
A
4925 }
4926 if (mt_tag > 0) {
2d21ac55 4927 mtype_stat_sub(MT_TAG, mt_tag);
0a7de745 4928 }
2d21ac55 4929
0a7de745 4930 if (mp_list != NULL) {
2d21ac55 4931 mcache_free_ext(m_cache(MC_MBUF), mp_list);
0a7de745
A
4932 }
4933 if (mcl_list != NULL) {
2d21ac55 4934 mcache_free_ext(m_cache(MC_CL), mcl_list);
0a7de745
A
4935 }
4936 if (mbc_list != NULL) {
2d21ac55 4937 mcache_free_ext(m_cache(MC_BIGCL), mbc_list);
0a7de745
A
4938 }
4939 if (m16k_list != NULL) {
2d21ac55 4940 mcache_free_ext(m_cache(MC_16KCL), m16k_list);
0a7de745
A
4941 }
4942 if (m_mcl_list != NULL) {
2d21ac55 4943 mcache_free_ext(m_cache(MC_MBUF_CL), m_mcl_list);
0a7de745
A
4944 }
4945 if (m_mbc_list != NULL) {
2d21ac55 4946 mcache_free_ext(m_cache(MC_MBUF_BIGCL), m_mbc_list);
0a7de745
A
4947 }
4948 if (m_m16k_list != NULL) {
2d21ac55 4949 mcache_free_ext(m_cache(MC_MBUF_16KCL), m_m16k_list);
0a7de745
A
4950 }
4951 if (ref_list != NULL) {
2d21ac55 4952 mcache_free_ext(ref_cache, ref_list);
0a7de745 4953 }
2d21ac55 4954
0a7de745 4955 return pktcount;
1c79356b
A
4956}
4957
4958void
2d21ac55 4959m_freem(struct mbuf *m)
1c79356b 4960{
0a7de745 4961 while (m != NULL) {
1c79356b 4962 m = m_free(m);
0a7de745 4963 }
1c79356b
A
4964}
4965
4966/*
4967 * Mbuffer utility routines.
4968 */
4969/*
d9a64523
A
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.
4972 *
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.
1c79356b 4978 */
d9a64523
A
4979void
4980m_align(struct mbuf *m, int len)
1c79356b 4981{
d9a64523 4982 int adjust = 0;
1c79356b 4983
d9a64523
A
4984 /* At this point data must point to start */
4985 VERIFY(m->m_data == M_START(m));
4986 VERIFY(len >= 0);
4987 VERIFY(len <= M_SIZE(m));
4988 adjust = M_SIZE(m) - len;
0a7de745 4989 m->m_data += adjust & ~(sizeof(long) - 1);
1c79356b
A
4990}
4991
4992/*
2d21ac55
A
4993 * Lesser-used path for M_PREPEND: allocate new mbuf to prepend to chain,
4994 * copy junk along. Does not adjust packet header length.
1c79356b
A
4995 */
4996struct mbuf *
2d21ac55 4997m_prepend(struct mbuf *m, int len, int how)
1c79356b
A
4998{
4999 struct mbuf *mn;
5000
2d21ac55
A
5001 _MGET(mn, how, m->m_type);
5002 if (mn == NULL) {
1c79356b 5003 m_freem(m);
0a7de745 5004 return NULL;
1c79356b
A
5005 }
5006 if (m->m_flags & M_PKTHDR) {
5007 M_COPY_PKTHDR(mn, m);
5008 m->m_flags &= ~M_PKTHDR;
5009 }
5010 mn->m_next = m;
5011 m = mn;
3e170ce0
A
5012 if (m->m_flags & M_PKTHDR) {
5013 VERIFY(len <= MHLEN);
1c79356b 5014 MH_ALIGN(m, len);
3e170ce0
A
5015 } else {
5016 VERIFY(len <= MLEN);
5017 M_ALIGN(m, len);
5018 }
1c79356b 5019 m->m_len = len;
0a7de745 5020 return m;
1c79356b
A
5021}
5022
9bccf70c 5023/*
2d21ac55
A
5024 * Replacement for old M_PREPEND macro: allocate new mbuf to prepend to
5025 * chain, copy junk along, and adjust length.
9bccf70c
A
5026 */
5027struct mbuf *
3e170ce0 5028m_prepend_2(struct mbuf *m, int len, int how, int align)
2d21ac55 5029{
3e170ce0
A
5030 if (M_LEADINGSPACE(m) >= len &&
5031 (!align || IS_P2ALIGNED((m->m_data - len), sizeof(u_int32_t)))) {
2d21ac55
A
5032 m->m_data -= len;
5033 m->m_len += len;
5034 } else {
9bccf70c 5035 m = m_prepend(m, len, how);
2d21ac55 5036 }
0a7de745 5037 if ((m) && (m->m_flags & M_PKTHDR)) {
2d21ac55 5038 m->m_pkthdr.len += len;
0a7de745
A
5039 }
5040 return m;
9bccf70c
A
5041}
5042
1c79356b
A
5043/*
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.
5047 */
5048int MCFail;
5049
5050struct mbuf *
39236c6e 5051m_copym_mode(struct mbuf *m, int off0, int len, int wait, uint32_t mode)
1c79356b 5052{
2d21ac55 5053 struct mbuf *n, *mhdr = NULL, **np;
91447636 5054 int off = off0;
1c79356b
A
5055 struct mbuf *top;
5056 int copyhdr = 0;
5057
0a7de745 5058 if (off < 0 || len < 0) {
2d21ac55 5059 panic("m_copym: invalid offset %d or len %d", off, len);
0a7de745 5060 }
2d21ac55 5061
fe8ab488
A
5062 VERIFY((mode != M_COPYM_MUST_COPY_HDR &&
5063 mode != M_COPYM_MUST_MOVE_HDR) || (m->m_flags & M_PKTHDR));
5064
5065 if ((off == 0 && (m->m_flags & M_PKTHDR)) ||
5066 mode == M_COPYM_MUST_COPY_HDR || mode == M_COPYM_MUST_MOVE_HDR) {
2d21ac55 5067 mhdr = m;
1c79356b 5068 copyhdr = 1;
2d21ac55 5069 }
fa4905b1
A
5070
5071 while (off >= m->m_len) {
0a7de745 5072 if (m->m_next == NULL) {
2d21ac55 5073 panic("m_copym: invalid mbuf chain");
0a7de745 5074 }
1c79356b
A
5075 off -= m->m_len;
5076 m = m->m_next;
5077 }
5078 np = &top;
2d21ac55 5079 top = NULL;
fa4905b1 5080
1c79356b 5081 while (len > 0) {
2d21ac55 5082 if (m == NULL) {
0a7de745 5083 if (len != M_COPYALL) {
2d21ac55 5084 panic("m_copym: len != M_COPYALL");
0a7de745 5085 }
1c79356b
A
5086 break;
5087 }
2d21ac55 5088
0a7de745 5089 if (copyhdr) {
fe8ab488 5090 n = _M_RETRYHDR(wait, m->m_type);
0a7de745 5091 } else {
fe8ab488 5092 n = _M_RETRY(wait, m->m_type);
0a7de745 5093 }
1c79356b 5094 *np = n;
fa4905b1 5095
0a7de745 5096 if (n == NULL) {
1c79356b 5097 goto nospace;
0a7de745 5098 }
2d21ac55
A
5099
5100 if (copyhdr != 0) {
fe8ab488
A
5101 if ((mode == M_COPYM_MOVE_HDR) ||
5102 (mode == M_COPYM_MUST_MOVE_HDR)) {
39236c6e 5103 M_COPY_PKTHDR(n, mhdr);
fe8ab488
A
5104 } else if ((mode == M_COPYM_COPY_HDR) ||
5105 (mode == M_COPYM_MUST_COPY_HDR)) {
0a7de745 5106 if (m_dup_pkthdr(n, mhdr, wait) == 0) {
39236c6e 5107 goto nospace;
0a7de745 5108 }
39236c6e 5109 }
0a7de745 5110 if (len == M_COPYALL) {
1c79356b 5111 n->m_pkthdr.len -= off0;
0a7de745 5112 } else {
1c79356b 5113 n->m_pkthdr.len = len;
0a7de745 5114 }
1c79356b 5115 copyhdr = 0;
fe8ab488
A
5116 /*
5117 * There is data to copy from the packet header mbuf
5118 * if it is empty or it is before the starting offset
5119 */
5120 if (mhdr != m) {
5121 np = &n->m_next;
5122 continue;
2d21ac55 5123 }
1c79356b 5124 }
2d21ac55 5125 n->m_len = MIN(len, (m->m_len - off));
1c79356b 5126 if (m->m_flags & M_EXT) {
1c79356b 5127 n->m_ext = m->m_ext;
2d21ac55 5128 m_incref(m);
1c79356b
A
5129 n->m_data = m->m_data + off;
5130 n->m_flags |= M_EXT;
fa4905b1 5131 } else {
fe8ab488
A
5132 /*
5133 * Limit to the capacity of the destination
5134 */
0a7de745 5135 if (n->m_flags & M_PKTHDR) {
fe8ab488 5136 n->m_len = MIN(n->m_len, MHLEN);
0a7de745 5137 } else {
fe8ab488 5138 n->m_len = MIN(n->m_len, MLEN);
0a7de745 5139 }
fe8ab488 5140
0a7de745 5141 if (MTOD(n, char *) + n->m_len > ((char *)n) + MSIZE) {
39037602 5142 panic("%s n %p copy overflow",
0a7de745
A
5143 __func__, n);
5144 }
fe8ab488 5145
0a7de745 5146 bcopy(MTOD(m, caddr_t) + off, MTOD(n, caddr_t),
1c79356b 5147 (unsigned)n->m_len);
fa4905b1 5148 }
0a7de745 5149 if (len != M_COPYALL) {
1c79356b 5150 len -= n->m_len;
0a7de745 5151 }
1c79356b
A
5152 off = 0;
5153 m = m->m_next;
5154 np = &n->m_next;
5155 }
fa4905b1 5156
0a7de745 5157 if (top == NULL) {
1c79356b 5158 MCFail++;
0a7de745 5159 }
fa4905b1 5160
0a7de745 5161 return top;
1c79356b 5162nospace:
fa4905b1 5163
1c79356b
A
5164 m_freem(top);
5165 MCFail++;
0a7de745 5166 return NULL;
1c79356b
A
5167}
5168
39236c6e
A
5169
5170struct mbuf *
5171m_copym(struct mbuf *m, int off0, int len, int wait)
5172{
0a7de745 5173 return m_copym_mode(m, off0, len, wait, M_COPYM_MOVE_HDR);
39236c6e
A
5174}
5175
9bccf70c 5176/*
2d21ac55
A
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)
9bccf70c 5181 */
fa4905b1 5182struct mbuf *
fe8ab488 5183m_copym_with_hdrs(struct mbuf *m0, int off0, int len0, int wait,
39236c6e 5184 struct mbuf **m_lastm, int *m_off, uint32_t mode)
2d21ac55 5185{
fe8ab488 5186 struct mbuf *m = m0, *n, **np = NULL;
2d21ac55
A
5187 int off = off0, len = len0;
5188 struct mbuf *top = NULL;
5189 int mcflags = MSLEEPF(wait);
fa4905b1 5190 int copyhdr = 0;
2d21ac55
A
5191 int type = 0;
5192 mcache_obj_t *list = NULL;
5193 int needed = 0;
fa4905b1 5194
0a7de745 5195 if (off == 0 && (m->m_flags & M_PKTHDR)) {
fa4905b1 5196 copyhdr = 1;
0a7de745 5197 }
39037602 5198
fe8ab488 5199 if (m_lastm != NULL && *m_lastm != NULL) {
6d2010ae 5200 m = *m_lastm;
fa4905b1
A
5201 off = *m_off;
5202 } else {
2d21ac55
A
5203 while (off >= m->m_len) {
5204 off -= m->m_len;
fa4905b1
A
5205 m = m->m_next;
5206 }
5207 }
91447636 5208
2d21ac55
A
5209 n = m;
5210 while (len > 0) {
5211 needed++;
5212 ASSERT(n != NULL);
5213 len -= MIN(len, (n->m_len - ((needed == 1) ? off : 0)));
5214 n = n->m_next;
5215 }
5216 needed++;
5217 len = len0;
5218
5219 /*
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
5222 * before giving up.
5223 */
0a7de745 5224 if (mcflags & MCR_NOSLEEP) {
2d21ac55 5225 mcflags |= MCR_TRYHARD;
0a7de745 5226 }
2d21ac55
A
5227
5228 if (mcache_alloc_ext(m_cache(MC_MBUF), &list, needed,
0a7de745 5229 mcflags) != needed) {
2d21ac55 5230 goto nospace;
0a7de745 5231 }
fa4905b1 5232
2d21ac55 5233 needed = 0;
fa4905b1 5234 while (len > 0) {
2d21ac55
A
5235 n = (struct mbuf *)list;
5236 list = list->obj_next;
5237 ASSERT(n != NULL && m != NULL);
5238
5239 type = (top == NULL) ? MT_HEADER : m->m_type;
5240 MBUF_INIT(n, (top == NULL), type);
5241#if CONFIG_MACF_NET
5242 if (top == NULL && mac_mbuf_label_init(n, wait) != 0) {
5243 mtype_stat_inc(MT_HEADER);
5244 mtype_stat_dec(MT_FREE);
5245 m_free(n);
fa4905b1 5246 goto nospace;
2d21ac55
A
5247 }
5248#endif /* MAC_NET */
5249
5250 if (top == NULL) {
5251 top = n;
fa4905b1
A
5252 np = &top->m_next;
5253 continue;
2d21ac55
A
5254 } else {
5255 needed++;
5256 *np = n;
5257 }
fa4905b1
A
5258
5259 if (copyhdr) {
fe8ab488
A
5260 if ((mode == M_COPYM_MOVE_HDR) ||
5261 (mode == M_COPYM_MUST_MOVE_HDR)) {
39236c6e 5262 M_COPY_PKTHDR(n, m);
fe8ab488
A
5263 } else if ((mode == M_COPYM_COPY_HDR) ||
5264 (mode == M_COPYM_MUST_COPY_HDR)) {
0a7de745 5265 if (m_dup_pkthdr(n, m, wait) == 0) {
39236c6e 5266 goto nospace;
0a7de745 5267 }
39236c6e 5268 }
fa4905b1
A
5269 n->m_pkthdr.len = len;
5270 copyhdr = 0;
5271 }
2d21ac55 5272 n->m_len = MIN(len, (m->m_len - off));
fa4905b1
A
5273
5274 if (m->m_flags & M_EXT) {
5275 n->m_ext = m->m_ext;
2d21ac55 5276 m_incref(m);
fa4905b1
A
5277 n->m_data = m->m_data + off;
5278 n->m_flags |= M_EXT;
5279 } else {
0a7de745 5280 if (MTOD(n, char *) + n->m_len > ((char *)n) + MSIZE) {
39037602 5281 panic("%s n %p copy overflow",
0a7de745
A
5282 __func__, n);
5283 }
fe8ab488 5284
0a7de745 5285 bcopy(MTOD(m, caddr_t) + off, MTOD(n, caddr_t),
fa4905b1
A
5286 (unsigned)n->m_len);
5287 }
5288 len -= n->m_len;
2d21ac55 5289
fa4905b1 5290 if (len == 0) {
fe8ab488
A
5291 if (m_lastm != NULL && m_off != NULL) {
5292 if ((off + n->m_len) == m->m_len) {
5293 *m_lastm = m->m_next;
5294 *m_off = 0;
5295 } else {
5296 *m_lastm = m;
5297 *m_off = off + n->m_len;
5298 }
fa4905b1 5299 }
2d21ac55 5300 break;
fa4905b1
A
5301 }
5302 off = 0;
5303 m = m->m_next;
5304 np = &n->m_next;
5305 }
fa4905b1 5306
2d21ac55
A
5307 mtype_stat_inc(MT_HEADER);
5308 mtype_stat_add(type, needed);
5309 mtype_stat_sub(MT_FREE, needed + 1);
5310
5311 ASSERT(list == NULL);
0a7de745 5312 return top;
fa4905b1 5313
2d21ac55 5314nospace:
0a7de745 5315 if (list != NULL) {
2d21ac55 5316 mcache_free_ext(m_cache(MC_MBUF), list);
0a7de745
A
5317 }
5318 if (top != NULL) {
2d21ac55 5319 m_freem(top);
0a7de745 5320 }
fa4905b1 5321 MCFail++;
0a7de745 5322 return NULL;
fa4905b1
A
5323}
5324
1c79356b
A
5325/*
5326 * Copy data from an mbuf chain starting "off" bytes from the beginning,
5327 * continuing for "len" bytes, into the indicated buffer.
5328 */
2d21ac55 5329void
b0d623f7 5330m_copydata(struct mbuf *m, int off, int len, void *vp)
1c79356b 5331{
5ba3f43e
A
5332 int off0 = off, len0 = len;
5333 struct mbuf *m0 = m;
91447636 5334 unsigned count;
b0d623f7 5335 char *cp = vp;
1c79356b 5336
5ba3f43e
A
5337 if (__improbable(off < 0 || len < 0)) {
5338 panic("%s: invalid offset %d or len %d", __func__, off, len);
5339 /* NOTREACHED */
5340 }
2d21ac55 5341
1c79356b 5342 while (off > 0) {
5ba3f43e
A
5343 if (__improbable(m == NULL)) {
5344 panic("%s: invalid mbuf chain %p [off %d, len %d]",
5345 __func__, m0, off0, len0);
5346 /* NOTREACHED */
5347 }
0a7de745 5348 if (off < m->m_len) {
1c79356b 5349 break;
0a7de745 5350 }
1c79356b
A
5351 off -= m->m_len;
5352 m = m->m_next;
5353 }
5354 while (len > 0) {
5ba3f43e
A
5355 if (__improbable(m == NULL)) {
5356 panic("%s: invalid mbuf chain %p [off %d, len %d]",
5357 __func__, m0, off0, len0);
5358 /* NOTREACHED */
5359 }
2d21ac55
A
5360 count = MIN(m->m_len - off, len);
5361 bcopy(MTOD(m, caddr_t) + off, cp, count);
1c79356b
A
5362 len -= count;
5363 cp += count;
5364 off = 0;
5365 m = m->m_next;
5366 }
5367}
5368
5369/*
2d21ac55
A
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.
1c79356b 5372 */
2d21ac55
A
5373void
5374m_cat(struct mbuf *m, struct mbuf *n)
1c79356b 5375{
0a7de745 5376 while (m->m_next) {
1c79356b 5377 m = m->m_next;
0a7de745 5378 }
1c79356b 5379 while (n) {
2d21ac55 5380 if ((m->m_flags & M_EXT) ||
1c79356b
A
5381 m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
5382 /* just join the two chains */
5383 m->m_next = n;
5384 return;
5385 }
5386 /* splat the data from one into the other */
2d21ac55 5387 bcopy(MTOD(n, caddr_t), MTOD(m, caddr_t) + m->m_len,
1c79356b
A
5388 (u_int)n->m_len);
5389 m->m_len += n->m_len;
5390 n = m_free(n);
5391 }
5392}
5393
5394void
2d21ac55 5395m_adj(struct mbuf *mp, int req_len)
1c79356b 5396{
91447636
A
5397 int len = req_len;
5398 struct mbuf *m;
5399 int count;
1c79356b 5400
0a7de745 5401 if ((m = mp) == NULL) {
1c79356b 5402 return;
0a7de745 5403 }
1c79356b
A
5404 if (len >= 0) {
5405 /*
5406 * Trim from head.
5407 */
5408 while (m != NULL && len > 0) {
5409 if (m->m_len <= len) {
5410 len -= m->m_len;
5411 m->m_len = 0;
5412 m = m->m_next;
5413 } else {
5414 m->m_len -= len;
5415 m->m_data += len;
5416 len = 0;
5417 }
5418 }
5419 m = mp;
0a7de745 5420 if (m->m_flags & M_PKTHDR) {
1c79356b 5421 m->m_pkthdr.len -= (req_len - len);
0a7de745 5422 }
1c79356b
A
5423 } else {
5424 /*
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.
5430 */
5431 len = -len;
5432 count = 0;
5433 for (;;) {
5434 count += m->m_len;
0a7de745 5435 if (m->m_next == (struct mbuf *)0) {
1c79356b 5436 break;
0a7de745 5437 }
1c79356b
A
5438 m = m->m_next;
5439 }
5440 if (m->m_len >= len) {
5441 m->m_len -= len;
5442 m = mp;
0a7de745 5443 if (m->m_flags & M_PKTHDR) {
1c79356b 5444 m->m_pkthdr.len -= len;
0a7de745 5445 }
1c79356b
A
5446 return;
5447 }
5448 count -= len;
0a7de745 5449 if (count < 0) {
1c79356b 5450 count = 0;
0a7de745 5451 }
1c79356b
A
5452 /*
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.
5456 */
5457 m = mp;
0a7de745 5458 if (m->m_flags & M_PKTHDR) {
1c79356b 5459 m->m_pkthdr.len = count;
0a7de745 5460 }
1c79356b
A
5461 for (; m; m = m->m_next) {
5462 if (m->m_len >= count) {
5463 m->m_len = count;
5464 break;
5465 }
5466 count -= m->m_len;
5467 }
0a7de745 5468 while ((m = m->m_next)) {
1c79356b 5469 m->m_len = 0;
0a7de745 5470 }
1c79356b
A
5471 }
5472}
5473
5474/*
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.
5481 */
5482int MPFail;
5483
5484struct mbuf *
2d21ac55 5485m_pullup(struct mbuf *n, int len)
1c79356b 5486{
91447636
A
5487 struct mbuf *m;
5488 int count;
1c79356b
A
5489 int space;
5490
a39ff7e2
A
5491 /* check invalid arguments */
5492 if (n == NULL) {
0a7de745 5493 panic("%s: n == NULL", __func__);
a39ff7e2
A
5494 }
5495 if (len < 0) {
5496 os_log_info(OS_LOG_DEFAULT, "%s: failed negative len %d",
5497 __func__, len);
5498 goto bad;
5499 }
d9a64523
A
5500 if (len > MLEN) {
5501 os_log_info(OS_LOG_DEFAULT, "%s: failed len %d too big",
5502 __func__, len);
5503 goto bad;
5504 }
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",
5508 __func__);
5509 goto bad;
5510 }
a39ff7e2 5511
1c79356b
A
5512 /*
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.
5516 */
5517 if ((n->m_flags & M_EXT) == 0 &&
d9a64523 5518 len < &n->m_dat[MLEN] - n->m_data && n->m_next != NULL) {
0a7de745
A
5519 if (n->m_len >= len) {
5520 return n;
5521 }
1c79356b
A
5522 m = n;
5523 n = n->m_next;
5524 len -= m->m_len;
5525 } else {
0a7de745 5526 if (len > MHLEN) {
1c79356b 5527 goto bad;
0a7de745 5528 }
2d21ac55 5529 _MGET(m, M_DONTWAIT, n->m_type);
0a7de745 5530 if (m == 0) {
1c79356b 5531 goto bad;
0a7de745 5532 }
1c79356b
A
5533 m->m_len = 0;
5534 if (n->m_flags & M_PKTHDR) {
5535 M_COPY_PKTHDR(m, n);
5536 n->m_flags &= ~M_PKTHDR;
5537 }
5538 }
5539 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
5540 do {
2d21ac55
A
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,
5543 (unsigned)count);
1c79356b
A
5544 len -= count;
5545 m->m_len += count;
5546 n->m_len -= count;
5547 space -= count;
0a7de745 5548 if (n->m_len != 0) {
1c79356b 5549 n->m_data += count;
0a7de745 5550 } else {
1c79356b 5551 n = m_free(n);
0a7de745 5552 }
d9a64523 5553 } while (len > 0 && n != NULL);
1c79356b
A
5554 if (len > 0) {
5555 (void) m_free(m);
5556 goto bad;
5557 }
5558 m->m_next = n;
0a7de745 5559 return m;
1c79356b
A
5560bad:
5561 m_freem(n);
5562 MPFail++;
0a7de745 5563 return 0;
1c79356b
A
5564}
5565
6d2010ae
A
5566/*
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).
5570 */
5571__private_extern__ int MSFail = 0;
5572
5573__private_extern__ struct mbuf *
5574m_copyup(struct mbuf *n, int len, int dstoff)
5575{
5576 struct mbuf *m;
5577 int count, space;
5578
cb323159
A
5579 VERIFY(len >= 0 && dstoff >= 0);
5580
0a7de745 5581 if (len > (MHLEN - dstoff)) {
6d2010ae 5582 goto bad;
0a7de745 5583 }
6d2010ae 5584 MGET(m, M_DONTWAIT, n->m_type);
0a7de745 5585 if (m == NULL) {
6d2010ae 5586 goto bad;
0a7de745 5587 }
6d2010ae
A
5588 m->m_len = 0;
5589 if (n->m_flags & M_PKTHDR) {
5590 m_copy_pkthdr(m, n);
5591 n->m_flags &= ~M_PKTHDR;
5592 }
5593 m->m_data += dstoff;
5594 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
5595 do {
5596 count = min(min(max(len, max_protohdr), space), n->m_len);
5597 memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
5598 (unsigned)count);
5599 len -= count;
5600 m->m_len += count;
5601 n->m_len -= count;
5602 space -= count;
0a7de745 5603 if (n->m_len) {
6d2010ae 5604 n->m_data += count;
0a7de745 5605 } else {
6d2010ae 5606 n = m_free(n);
0a7de745 5607 }
6d2010ae
A
5608 } while (len > 0 && n);
5609 if (len > 0) {
5610 (void) m_free(m);
5611 goto bad;
5612 }
5613 m->m_next = n;
0a7de745 5614 return m;
6d2010ae
A
5615bad:
5616 m_freem(n);
5617 MSFail++;
0a7de745 5618 return NULL;
6d2010ae
A
5619}
5620
1c79356b
A
5621/*
5622 * Partition an mbuf chain in two pieces, returning the tail --
5623 * all but the first len0 bytes. In case of failure, it returns NULL and
5624 * attempts to restore the chain to its original state.
5625 */
5626struct mbuf *
2d21ac55 5627m_split(struct mbuf *m0, int len0, int wait)
b0d623f7 5628{
0a7de745 5629 return m_split0(m0, len0, wait, 1);
b0d623f7
A
5630}
5631
5632static struct mbuf *
5633m_split0(struct mbuf *m0, int len0, int wait, int copyhdr)
1c79356b 5634{
91447636 5635 struct mbuf *m, *n;
1c79356b
A
5636 unsigned len = len0, remain;
5637
d9a64523
A
5638 /*
5639 * First iterate to the mbuf which contains the first byte of
5640 * data at offset len0
5641 */
0a7de745 5642 for (m = m0; m && len > m->m_len; m = m->m_next) {
1c79356b 5643 len -= m->m_len;
0a7de745
A
5644 }
5645 if (m == NULL) {
5646 return NULL;
5647 }
d9a64523
A
5648 /*
5649 * len effectively is now the offset in the current
5650 * mbuf where we have to perform split.
5651 *
5652 * remain becomes the tail length.
5653 * Note that len can also be == m->m_len
5654 */
1c79356b 5655 remain = m->m_len - len;
d9a64523
A
5656
5657 /*
5658 * If current mbuf len contains the entire remaining offset len,
5659 * just make the second mbuf chain pointing to next mbuf onwards
5660 * and return after making necessary adjustments
5661 */
5662 if (copyhdr && (m0->m_flags & M_PKTHDR) && remain == 0) {
5663 _MGETHDR(n, wait, m0->m_type);
0a7de745
A
5664 if (n == NULL) {
5665 return NULL;
5666 }
d9a64523
A
5667 n->m_next = m->m_next;
5668 m->m_next = NULL;
5669 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
5670 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
5671 m0->m_pkthdr.len = len0;
0a7de745
A
5672 return n;
5673 }
5674 if (copyhdr && (m0->m_flags & M_PKTHDR)) {
2d21ac55 5675 _MGETHDR(n, wait, m0->m_type);
0a7de745
A
5676 if (n == NULL) {
5677 return NULL;
5678 }
1c79356b
A
5679 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
5680 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
5681 m0->m_pkthdr.len = len0;
d9a64523
A
5682
5683 /*
5684 * If current points to external storage
5685 * then it can be shared by making last mbuf
5686 * of head chain and first mbuf of current chain
5687 * pointing to different data offsets
5688 */
0a7de745 5689 if (m->m_flags & M_EXT) {
1c79356b 5690 goto extpacket;
0a7de745 5691 }
1c79356b
A
5692 if (remain > MHLEN) {
5693 /* m can't be the lead packet */
5694 MH_ALIGN(n, 0);
5695 n->m_next = m_split(m, len, wait);
2d21ac55 5696 if (n->m_next == NULL) {
1c79356b 5697 (void) m_free(n);
0a7de745
A
5698 return NULL;
5699 } else {
5700 return n;
5701 }
5702 } else {
1c79356b 5703 MH_ALIGN(n, remain);
0a7de745 5704 }
1c79356b
A
5705 } else if (remain == 0) {
5706 n = m->m_next;
2d21ac55 5707 m->m_next = NULL;
0a7de745 5708 return n;
1c79356b 5709 } else {
2d21ac55 5710 _MGET(n, wait, m->m_type);
0a7de745
A
5711 if (n == NULL) {
5712 return NULL;
5713 }
d9a64523
A
5714
5715 if ((m->m_flags & M_EXT) == 0) {
5716 VERIFY(remain <= MLEN);
5717 M_ALIGN(n, remain);
5718 }
1c79356b
A
5719 }
5720extpacket:
5721 if (m->m_flags & M_EXT) {
5722 n->m_flags |= M_EXT;
0b4e3aa0 5723 n->m_ext = m->m_ext;
2d21ac55 5724 m_incref(m);
1c79356b
A
5725 n->m_data = m->m_data + len;
5726 } else {
2d21ac55 5727 bcopy(MTOD(m, caddr_t) + len, MTOD(n, caddr_t), remain);
1c79356b
A
5728 }
5729 n->m_len = remain;
5730 m->m_len = len;
5731 n->m_next = m->m_next;
2d21ac55 5732 m->m_next = NULL;
0a7de745 5733 return n;
1c79356b 5734}
2d21ac55 5735
1c79356b
A
5736/*
5737 * Routine to copy from device local memory into mbufs.
5738 */
5739struct mbuf *
2d21ac55
A
5740m_devget(char *buf, int totlen, int off0, struct ifnet *ifp,
5741 void (*copy)(const void *, void *, size_t))
1c79356b 5742{
91447636 5743 struct mbuf *m;
2d21ac55 5744 struct mbuf *top = NULL, **mp = &top;
91447636
A
5745 int off = off0, len;
5746 char *cp;
1c79356b
A
5747 char *epkt;
5748
5749 cp = buf;
5750 epkt = cp + totlen;
5751 if (off) {
5752 /*
5753 * If 'off' is non-zero, packet is trailer-encapsulated,
5754 * so we have to skip the type and length fields.
5755 */
0a7de745
A
5756 cp += off + 2 * sizeof(u_int16_t);
5757 totlen -= 2 * sizeof(u_int16_t);
1c79356b 5758 }
2d21ac55 5759 _MGETHDR(m, M_DONTWAIT, MT_DATA);
0a7de745
A
5760 if (m == NULL) {
5761 return NULL;
5762 }
1c79356b
A
5763 m->m_pkthdr.rcvif = ifp;
5764 m->m_pkthdr.len = totlen;
5765 m->m_len = MHLEN;
5766
5767 while (totlen > 0) {
2d21ac55
A
5768 if (top != NULL) {
5769 _MGET(m, M_DONTWAIT, MT_DATA);
5770 if (m == NULL) {
1c79356b 5771 m_freem(top);
0a7de745 5772 return NULL;
1c79356b
A
5773 }
5774 m->m_len = MLEN;
5775 }
2d21ac55 5776 len = MIN(totlen, epkt - cp);
1c79356b
A
5777 if (len >= MINCLSIZE) {
5778 MCLGET(m, M_DONTWAIT);
2d21ac55
A
5779 if (m->m_flags & M_EXT) {
5780 m->m_len = len = MIN(len, m_maxsize(MC_CL));
5781 } else {
5782 /* give up when it's out of cluster mbufs */
0a7de745 5783 if (top != NULL) {
2d21ac55 5784 m_freem(top);
0a7de745 5785 }
1c79356b 5786 m_freem(m);
0a7de745 5787 return NULL;
1c79356b
A
5788 }
5789 } else {
5790 /*
5791 * Place initial small packet/header at end of mbuf.
5792 */
5793 if (len < m->m_len) {
2d21ac55 5794 if (top == NULL &&
0a7de745 5795 len + max_linkhdr <= m->m_len) {
1c79356b 5796 m->m_data += max_linkhdr;
0a7de745 5797 }
1c79356b 5798 m->m_len = len;
2d21ac55 5799 } else {
1c79356b 5800 len = m->m_len;
2d21ac55 5801 }
1c79356b 5802 }
0a7de745 5803 if (copy) {
2d21ac55 5804 copy(cp, MTOD(m, caddr_t), (unsigned)len);
0a7de745 5805 } else {
2d21ac55 5806 bcopy(cp, MTOD(m, caddr_t), (unsigned)len);
0a7de745 5807 }
1c79356b
A
5808 cp += len;
5809 *mp = m;
5810 mp = &m->m_next;
5811 totlen -= len;
0a7de745 5812 if (cp == epkt) {
1c79356b 5813 cp = buf;
0a7de745 5814 }
1c79356b 5815 }
0a7de745 5816 return top;
1c79356b
A
5817}
5818
6d2010ae 5819#ifndef MBUF_GROWTH_NORMAL_THRESH
0a7de745 5820#define MBUF_GROWTH_NORMAL_THRESH 25
6d2010ae 5821#endif
b0d623f7 5822
1c79356b 5823/*
2d21ac55 5824 * Cluster freelist allocation check.
1c79356b
A
5825 */
5826static int
91447636 5827m_howmany(int num, size_t bufsize)
1c79356b 5828{
2d21ac55 5829 int i = 0, j = 0;
6d2010ae
A
5830 u_int32_t m_mbclusters, m_clusters, m_bigclusters, m_16kclusters;
5831 u_int32_t m_mbfree, m_clfree, m_bigclfree, m_16kclfree;
5832 u_int32_t sumclusters, freeclusters;
5833 u_int32_t percent_pool, percent_kmem;
5834 u_int32_t mb_growth, mb_growth_thresh;
5835
5836 VERIFY(bufsize == m_maxsize(MC_BIGCL) ||
5837 bufsize == m_maxsize(MC_16KCL));
2d21ac55 5838
5ba3f43e 5839 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
2d21ac55 5840
6d2010ae
A
5841 /* Numbers in 2K cluster units */
5842 m_mbclusters = m_total(MC_MBUF) >> NMBPCLSHIFT;
2d21ac55 5843 m_clusters = m_total(MC_CL);
6d2010ae 5844 m_bigclusters = m_total(MC_BIGCL) << NCLPBGSHIFT;
2d21ac55 5845 m_16kclusters = m_total(MC_16KCL);
6d2010ae
A
5846 sumclusters = m_mbclusters + m_clusters + m_bigclusters;
5847
5848 m_mbfree = m_infree(MC_MBUF) >> NMBPCLSHIFT;
2d21ac55 5849 m_clfree = m_infree(MC_CL);
6d2010ae 5850 m_bigclfree = m_infree(MC_BIGCL) << NCLPBGSHIFT;
2d21ac55 5851 m_16kclfree = m_infree(MC_16KCL);
6d2010ae 5852 freeclusters = m_mbfree + m_clfree + m_bigclfree;
2d21ac55 5853
91447636 5854 /* Bail if we've maxed out the mbuf memory map */
6d2010ae 5855 if ((bufsize == m_maxsize(MC_BIGCL) && sumclusters >= nclusters) ||
2d21ac55 5856 (njcl > 0 && bufsize == m_maxsize(MC_16KCL) &&
6d2010ae 5857 (m_16kclusters << NCLPJCLSHIFT) >= njcl)) {
d9a64523
A
5858 mbwdog_logger("maxed out nclusters (%u >= %u) or njcl (%u >= %u)",
5859 sumclusters, nclusters,
5860 (m_16kclusters << NCLPJCLSHIFT), njcl);
0a7de745 5861 return 0;
2d21ac55
A
5862 }
5863
6d2010ae 5864 if (bufsize == m_maxsize(MC_BIGCL)) {
2d21ac55 5865 /* Under minimum */
0a7de745
A
5866 if (m_bigclusters < m_minlimit(MC_BIGCL)) {
5867 return m_minlimit(MC_BIGCL) - m_bigclusters;
5868 }
6d2010ae
A
5869
5870 percent_pool =
5871 ((sumclusters - freeclusters) * 100) / sumclusters;
5872 percent_kmem = (sumclusters * 100) / nclusters;
5873
5874 /*
5875 * If a light/normal user, grow conservatively (75%)
5876 * If a heavy user, grow aggressively (50%)
5877 */
0a7de745 5878 if (percent_kmem < MBUF_GROWTH_NORMAL_THRESH) {
6d2010ae 5879 mb_growth = MB_GROWTH_NORMAL;
0a7de745 5880 } else {
6d2010ae 5881 mb_growth = MB_GROWTH_AGGRESSIVE;
0a7de745 5882 }
6d2010ae
A
5883
5884 if (percent_kmem < 5) {
5885 /* For initial allocations */
5886 i = num;
5887 } else {
5888 /* Return if >= MBIGCL_LOWAT clusters available */
5889 if (m_infree(MC_BIGCL) >= MBIGCL_LOWAT &&
5890 m_total(MC_BIGCL) >=
0a7de745
A
5891 MBIGCL_LOWAT + m_minlimit(MC_BIGCL)) {
5892 return 0;
5893 }
6d2010ae
A
5894
5895 /* Ensure at least num clusters are accessible */
0a7de745 5896 if (num >= m_infree(MC_BIGCL)) {
6d2010ae 5897 i = num - m_infree(MC_BIGCL);
0a7de745
A
5898 }
5899 if (num > m_total(MC_BIGCL) - m_minlimit(MC_BIGCL)) {
6d2010ae
A
5900 j = num - (m_total(MC_BIGCL) -
5901 m_minlimit(MC_BIGCL));
0a7de745 5902 }
6d2010ae 5903
2d21ac55 5904 i = MAX(i, j);
6d2010ae
A
5905
5906 /*
5907 * Grow pool if percent_pool > 75 (normal growth)
5908 * or percent_pool > 50 (aggressive growth).
5909 */
5910 mb_growth_thresh = 100 - (100 / (1 << mb_growth));
0a7de745 5911 if (percent_pool > mb_growth_thresh) {
6d2010ae
A
5912 j = ((sumclusters + num) >> mb_growth) -
5913 freeclusters;
0a7de745 5914 }
2d21ac55 5915 i = MAX(i, j);
2d21ac55 5916 }
6d2010ae
A
5917
5918 /* Check to ensure we didn't go over limits */
0a7de745 5919 if (i + m_bigclusters >= m_maxlimit(MC_BIGCL)) {
6d2010ae 5920 i = m_maxlimit(MC_BIGCL) - m_bigclusters;
0a7de745
A
5921 }
5922 if ((i << 1) + sumclusters >= nclusters) {
6d2010ae 5923 i = (nclusters - sumclusters) >> 1;
0a7de745 5924 }
2d21ac55 5925 VERIFY((m_total(MC_BIGCL) + i) <= m_maxlimit(MC_BIGCL));
6d2010ae 5926 VERIFY(sumclusters + (i << 1) <= nclusters);
6d2010ae 5927 } else { /* 16K CL */
2d21ac55 5928 VERIFY(njcl > 0);
6d2010ae 5929 /* Ensure at least num clusters are available */
0a7de745 5930 if (num >= m_16kclfree) {
6d2010ae 5931 i = num - m_16kclfree;
0a7de745 5932 }
6d2010ae
A
5933
5934 /* Always grow 16KCL pool aggressively */
0a7de745 5935 if (((m_16kclusters + num) >> 1) > m_16kclfree) {
6d2010ae 5936 j = ((m_16kclusters + num) >> 1) - m_16kclfree;
0a7de745 5937 }
6d2010ae
A
5938 i = MAX(i, j);
5939
5940 /* Check to ensure we don't go over limit */
0a7de745 5941 if ((i + m_total(MC_16KCL)) >= m_maxlimit(MC_16KCL)) {
5ba3f43e 5942 i = m_maxlimit(MC_16KCL) - m_total(MC_16KCL);
0a7de745 5943 }
91447636 5944 }
0a7de745 5945 return i;
1c79356b 5946}
b0d623f7
A
5947/*
5948 * Return the number of bytes in the mbuf chain, m.
6d2010ae
A
5949 */
5950unsigned int
b0d623f7
A
5951m_length(struct mbuf *m)
5952{
5953 struct mbuf *m0;
5954 unsigned int pktlen;
5955
0a7de745
A
5956 if (m->m_flags & M_PKTHDR) {
5957 return m->m_pkthdr.len;
5958 }
b0d623f7
A
5959
5960 pktlen = 0;
0a7de745 5961 for (m0 = m; m0 != NULL; m0 = m0->m_next) {
b0d623f7 5962 pktlen += m0->m_len;
0a7de745
A
5963 }
5964 return pktlen;
b0d623f7
A
5965}
5966
1c79356b
A
5967/*
5968 * Copy data from a buffer back into the indicated mbuf chain,
5969 * starting "off" bytes from the beginning, extending the mbuf
5970 * chain if necessary.
5971 */
5972void
b0d623f7 5973m_copyback(struct mbuf *m0, int off, int len, const void *cp)
1c79356b 5974{
b0d623f7
A
5975#if DEBUG
5976 struct mbuf *origm = m0;
5977 int error;
5978#endif /* DEBUG */
1c79356b 5979
0a7de745 5980 if (m0 == NULL) {
1c79356b 5981 return;
0a7de745 5982 }
b0d623f7
A
5983
5984#if DEBUG
5985 error =
5986#endif /* DEBUG */
5987 m_copyback0(&m0, off, len, cp,
5988 M_COPYBACK0_COPYBACK | M_COPYBACK0_EXTEND, M_DONTWAIT);
5989
5990#if DEBUG
0a7de745 5991 if (error != 0 || (m0 != NULL && origm != m0)) {
b0d623f7 5992 panic("m_copyback");
0a7de745 5993 }
b0d623f7
A
5994#endif /* DEBUG */
5995}
5996
5997struct mbuf *
5998m_copyback_cow(struct mbuf *m0, int off, int len, const void *cp, int how)
5999{
6000 int error;
6001
6002 /* don't support chain expansion */
6003 VERIFY(off + len <= m_length(m0));
6004
6005 error = m_copyback0(&m0, off, len, cp,
6006 M_COPYBACK0_COPYBACK | M_COPYBACK0_COW, how);
6007 if (error) {
6008 /*
6009 * no way to recover from partial success.
6010 * just free the chain.
6011 */
6012 m_freem(m0);
0a7de745 6013 return NULL;
b0d623f7 6014 }
0a7de745 6015 return m0;
b0d623f7
A
6016}
6017
6018/*
6019 * m_makewritable: ensure the specified range writable.
6020 */
6021int
6022m_makewritable(struct mbuf **mp, int off, int len, int how)
6023{
6024 int error;
6025#if DEBUG
6026 struct mbuf *n;
6027 int origlen, reslen;
6028
6029 origlen = m_length(*mp);
6030#endif /* DEBUG */
6031
6032#if 0 /* M_COPYALL is large enough */
0a7de745 6033 if (len == M_COPYALL) {
b0d623f7 6034 len = m_length(*mp) - off; /* XXX */
0a7de745 6035 }
b0d623f7
A
6036#endif
6037
6038 error = m_copyback0(mp, off, len, NULL,
6039 M_COPYBACK0_PRESERVE | M_COPYBACK0_COW, how);
6040
6041#if DEBUG
6042 reslen = 0;
0a7de745 6043 for (n = *mp; n; n = n->m_next) {
b0d623f7 6044 reslen += n->m_len;
0a7de745
A
6045 }
6046 if (origlen != reslen) {
b0d623f7 6047 panic("m_makewritable: length changed");
0a7de745
A
6048 }
6049 if (((*mp)->m_flags & M_PKTHDR) && reslen != (*mp)->m_pkthdr.len) {
b0d623f7 6050 panic("m_makewritable: inconsist");
0a7de745 6051 }
b0d623f7
A
6052#endif /* DEBUG */
6053
0a7de745 6054 return error;
b0d623f7
A
6055}
6056
6057static int
6058m_copyback0(struct mbuf **mp0, int off, int len, const void *vp, int flags,
6059 int how)
6060{
6061 int mlen;
6062 struct mbuf *m, *n;
6063 struct mbuf **mp;
6064 int totlen = 0;
6065 const char *cp = vp;
6066
6067 VERIFY(mp0 != NULL);
6068 VERIFY(*mp0 != NULL);
6069 VERIFY((flags & M_COPYBACK0_PRESERVE) == 0 || cp == NULL);
6070 VERIFY((flags & M_COPYBACK0_COPYBACK) == 0 || cp != NULL);
6071
6072 /*
6073 * we don't bother to update "totlen" in the case of M_COPYBACK0_COW,
6074 * assuming that M_COPYBACK0_EXTEND and M_COPYBACK0_COW are exclusive.
6075 */
6076
0a7de745 6077 VERIFY((~flags & (M_COPYBACK0_EXTEND | M_COPYBACK0_COW)) != 0);
b0d623f7
A
6078
6079 mp = mp0;
6080 m = *mp;
1c79356b
A
6081 while (off > (mlen = m->m_len)) {
6082 off -= mlen;
6083 totlen += mlen;
2d21ac55 6084 if (m->m_next == NULL) {
b0d623f7
A
6085 int tspace;
6086extend:
0a7de745 6087 if (!(flags & M_COPYBACK0_EXTEND)) {
1c79356b 6088 goto out;
0a7de745 6089 }
b0d623f7
A
6090
6091 /*
6092 * try to make some space at the end of "m".
6093 */
6094
6095 mlen = m->m_len;
6096 if (off + len >= MINCLSIZE &&
6097 !(m->m_flags & M_EXT) && m->m_len == 0) {
6098 MCLGET(m, how);
6099 }
6100 tspace = M_TRAILINGSPACE(m);
6101 if (tspace > 0) {
6102 tspace = MIN(tspace, off + len);
6103 VERIFY(tspace > 0);
6104 bzero(mtod(m, char *) + m->m_len,
6105 MIN(off, tspace));
6106 m->m_len += tspace;
6107 off += mlen;
6108 totlen -= mlen;
6109 continue;
6110 }
6111
6112 /*
6113 * need to allocate an mbuf.
6114 */
6115
6116 if (off + len >= MINCLSIZE) {
6117 n = m_getcl(how, m->m_type, 0);
6118 } else {
6119 n = _M_GET(how, m->m_type);
6120 }
6121 if (n == NULL) {
6122 goto out;
6123 }
6124 n->m_len = 0;
6125 n->m_len = MIN(M_TRAILINGSPACE(n), off + len);
6126 bzero(mtod(n, char *), MIN(n->m_len, off));
1c79356b
A
6127 m->m_next = n;
6128 }
b0d623f7 6129 mp = &m->m_next;
1c79356b
A
6130 m = m->m_next;
6131 }
6132 while (len > 0) {
b0d623f7
A
6133 mlen = m->m_len - off;
6134 if (mlen != 0 && m_mclhasreference(m)) {
6135 char *datap;
6136 int eatlen;
6137
6138 /*
6139 * this mbuf is read-only.
6140 * allocate a new writable mbuf and try again.
6141 */
6142
39236c6e 6143#if DIAGNOSTIC
0a7de745 6144 if (!(flags & M_COPYBACK0_COW)) {
b0d623f7 6145 panic("m_copyback0: read-only");
0a7de745 6146 }
39236c6e 6147#endif /* DIAGNOSTIC */
b0d623f7
A
6148
6149 /*
6150 * if we're going to write into the middle of
6151 * a mbuf, split it first.
6152 */
6153 if (off > 0 && len < mlen) {
6154 n = m_split0(m, off, how, 0);
0a7de745 6155 if (n == NULL) {
b0d623f7 6156 goto enobufs;
0a7de745 6157 }
b0d623f7
A
6158 m->m_next = n;
6159 mp = &m->m_next;
6160 m = n;
6161 off = 0;
6162 continue;
6163 }
6164
6165 /*
6166 * XXX TODO coalesce into the trailingspace of
6167 * the previous mbuf when possible.
6168 */
6169
6170 /*
6171 * allocate a new mbuf. copy packet header if needed.
6172 */
6173 n = _M_GET(how, m->m_type);
0a7de745 6174 if (n == NULL) {
b0d623f7 6175 goto enobufs;
0a7de745 6176 }
b0d623f7
A
6177 if (off == 0 && (m->m_flags & M_PKTHDR)) {
6178 M_COPY_PKTHDR(n, m);
6179 n->m_len = MHLEN;
6180 } else {
0a7de745 6181 if (len >= MINCLSIZE) {
b0d623f7 6182 MCLGET(n, M_DONTWAIT);
0a7de745 6183 }
b0d623f7
A
6184 n->m_len =
6185 (n->m_flags & M_EXT) ? MCLBYTES : MLEN;
6186 }
0a7de745 6187 if (n->m_len > len) {
b0d623f7 6188 n->m_len = len;
0a7de745 6189 }
b0d623f7
A
6190
6191 /*
6192 * free the region which has been overwritten.
6193 * copying data from old mbufs if requested.
6194 */
0a7de745 6195 if (flags & M_COPYBACK0_PRESERVE) {
b0d623f7 6196 datap = mtod(n, char *);
0a7de745 6197 } else {
b0d623f7 6198 datap = NULL;
0a7de745 6199 }
b0d623f7
A
6200 eatlen = n->m_len;
6201 VERIFY(off == 0 || eatlen >= mlen);
6202 if (off > 0) {
6203 VERIFY(len >= mlen);
6204 m->m_len = off;
6205 m->m_next = n;
6206 if (datap) {
6207 m_copydata(m, off, mlen, datap);
6208 datap += mlen;
6209 }
6210 eatlen -= mlen;
6211 mp = &m->m_next;
6212 m = m->m_next;
6213 }
6214 while (m != NULL && m_mclhasreference(m) &&
6215 n->m_type == m->m_type && eatlen > 0) {
6216 mlen = MIN(eatlen, m->m_len);
6217 if (datap) {
6218 m_copydata(m, 0, mlen, datap);
6219 datap += mlen;
6220 }
6221 m->m_data += mlen;
6222 m->m_len -= mlen;
6223 eatlen -= mlen;
0a7de745 6224 if (m->m_len == 0) {
b0d623f7 6225 *mp = m = m_free(m);
0a7de745 6226 }
b0d623f7 6227 }
0a7de745 6228 if (eatlen > 0) {
b0d623f7 6229 n->m_len -= eatlen;
0a7de745 6230 }
b0d623f7
A
6231 n->m_next = m;
6232 *mp = m = n;
6233 continue;
6234 }
6235 mlen = MIN(mlen, len);
6236 if (flags & M_COPYBACK0_COPYBACK) {
6237 bcopy(cp, mtod(m, caddr_t) + off, (unsigned)mlen);
6238 cp += mlen;
6239 }
1c79356b
A
6240 len -= mlen;
6241 mlen += off;
6242 off = 0;
6243 totlen += mlen;
0a7de745 6244 if (len == 0) {
1c79356b 6245 break;
0a7de745 6246 }
2d21ac55 6247 if (m->m_next == NULL) {
b0d623f7 6248 goto extend;
1c79356b 6249 }
b0d623f7 6250 mp = &m->m_next;
1c79356b
A
6251 m = m->m_next;
6252 }
2d21ac55 6253out:
b0d623f7
A
6254 if (((m = *mp0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen)) {
6255 VERIFY(flags & M_COPYBACK0_EXTEND);
1c79356b 6256 m->m_pkthdr.len = totlen;
b0d623f7
A
6257 }
6258
0a7de745 6259 return 0;
b0d623f7
A
6260
6261enobufs:
0a7de745 6262 return ENOBUFS;
1c79356b
A
6263}
6264
39236c6e 6265uint64_t
2d21ac55
A
6266mcl_to_paddr(char *addr)
6267{
b0d623f7 6268 vm_offset_t base_phys;
1c79356b 6269
0a7de745
A
6270 if (!MBUF_IN_MAP(addr)) {
6271 return 0;
6272 }
39236c6e 6273 base_phys = mcl_paddr[atop_64(addr - (char *)mbutl)];
1c79356b 6274
0a7de745
A
6275 if (base_phys == 0) {
6276 return 0;
6277 }
6278 return (uint64_t)(ptoa_64(base_phys) | ((uint64_t)addr & PAGE_MASK));
1c79356b
A
6279}
6280
6281/*
6282 * Dup the mbuf chain passed in. The whole thing. No cute additional cruft.
6283 * And really copy the thing. That way, we don't "precompute" checksums
2d21ac55
A
6284 * for unsuspecting consumers. Assumption: m->m_nextpkt == 0. Trick: for
6285 * small packets, don't dup into a cluster. That way received packets
6286 * don't take up too much room in the sockbuf (cf. sbspace()).
1c79356b
A
6287 */
6288int MDFail;
6289
6290struct mbuf *
91447636 6291m_dup(struct mbuf *m, int how)
2d21ac55 6292{
91447636 6293 struct mbuf *n, **np;
1c79356b
A
6294 struct mbuf *top;
6295 int copyhdr = 0;
6296
6297 np = &top;
2d21ac55 6298 top = NULL;
0a7de745 6299 if (m->m_flags & M_PKTHDR) {
1c79356b 6300 copyhdr = 1;
0a7de745 6301 }
1c79356b
A
6302
6303 /*
6304 * Quick check: if we have one mbuf and its data fits in an
6305 * mbuf with packet header, just copy and go.
6306 */
2d21ac55
A
6307 if (m->m_next == NULL) {
6308 /* Then just move the data into an mbuf and be done... */
6309 if (copyhdr) {
6310 if (m->m_pkthdr.len <= MHLEN && m->m_len <= MHLEN) {
0a7de745
A
6311 if ((n = _M_GETHDR(how, m->m_type)) == NULL) {
6312 return NULL;
6313 }
1c79356b 6314 n->m_len = m->m_len;
3a60a9f5
A
6315 m_dup_pkthdr(n, m, how);
6316 bcopy(m->m_data, n->m_data, m->m_len);
0a7de745 6317 return n;
1c79356b 6318 }
2d21ac55 6319 } else if (m->m_len <= MLEN) {
0a7de745
A
6320 if ((n = _M_GET(how, m->m_type)) == NULL) {
6321 return NULL;
6322 }
1c79356b
A
6323 bcopy(m->m_data, n->m_data, m->m_len);
6324 n->m_len = m->m_len;
0a7de745 6325 return n;
1c79356b
A
6326 }
6327 }
2d21ac55 6328 while (m != NULL) {
1c79356b 6329#if BLUE_DEBUG
39037602 6330 printf("<%x: %x, %x, %x\n", m, m->m_flags, m->m_len,
2d21ac55 6331 m->m_data);
1c79356b 6332#endif
0a7de745 6333 if (copyhdr) {
2d21ac55 6334 n = _M_GETHDR(how, m->m_type);
0a7de745 6335 } else {
2d21ac55 6336 n = _M_GET(how, m->m_type);
0a7de745
A
6337 }
6338 if (n == NULL) {
1c79356b 6339 goto nospace;
0a7de745 6340 }
2d21ac55 6341 if (m->m_flags & M_EXT) {
0a7de745 6342 if (m->m_len <= m_maxsize(MC_CL)) {
2d21ac55 6343 MCLGET(n, how);
0a7de745 6344 } else if (m->m_len <= m_maxsize(MC_BIGCL)) {
2d21ac55 6345 n = m_mbigget(n, how);
0a7de745 6346 } else if (m->m_len <= m_maxsize(MC_16KCL) && njcl > 0) {
2d21ac55 6347 n = m_m16kget(n, how);
0a7de745 6348 }
2d21ac55
A
6349 if (!(n->m_flags & M_EXT)) {
6350 (void) m_free(n);
1c79356b 6351 goto nospace;
2d21ac55 6352 }
cb323159
A
6353 } else {
6354 VERIFY((copyhdr == 1 && m->m_len <= MHLEN) ||
6355 (copyhdr == 0 && m->m_len <= MLEN));
1c79356b
A
6356 }
6357 *np = n;
2d21ac55
A
6358 if (copyhdr) {
6359 /* Don't use M_COPY_PKTHDR: preserve m_data */
3a60a9f5 6360 m_dup_pkthdr(n, m, how);
1c79356b 6361 copyhdr = 0;
0a7de745 6362 if (!(n->m_flags & M_EXT)) {
1c79356b 6363 n->m_data = n->m_pktdat;
0a7de745 6364 }
1c79356b
A
6365 }
6366 n->m_len = m->m_len;
6367 /*
6368 * Get the dup on the same bdry as the original
6369 * Assume that the two mbufs have the same offset to data area
2d21ac55 6370 * (up to word boundaries)
1c79356b 6371 */
2d21ac55 6372 bcopy(MTOD(m, caddr_t), MTOD(n, caddr_t), (unsigned)n->m_len);
1c79356b
A
6373 m = m->m_next;
6374 np = &n->m_next;
6375#if BLUE_DEBUG
39037602 6376 printf(">%x: %x, %x, %x\n", n, n->m_flags, n->m_len,
2d21ac55 6377 n->m_data);
1c79356b
A
6378#endif
6379 }
6380
0a7de745 6381 if (top == NULL) {
1c79356b 6382 MDFail++;
0a7de745
A
6383 }
6384 return top;
2d21ac55
A
6385
6386nospace:
1c79356b
A
6387 m_freem(top);
6388 MDFail++;
0a7de745 6389 return NULL;
1c79356b
A
6390}
6391
0a7de745
A
6392#define MBUF_MULTIPAGES(m) \
6393 (((m)->m_flags & M_EXT) && \
6394 ((IS_P2ALIGNED((m)->m_data, PAGE_SIZE) \
6395 && (m)->m_len > PAGE_SIZE) || \
6396 (!IS_P2ALIGNED((m)->m_data, PAGE_SIZE) && \
3e170ce0 6397 P2ROUNDUP((m)->m_data, PAGE_SIZE) < ((uintptr_t)(m)->m_data + (m)->m_len))))
2d21ac55
A
6398
6399static struct mbuf *
6400m_expand(struct mbuf *m, struct mbuf **last)
9bccf70c 6401{
2d21ac55
A
6402 struct mbuf *top = NULL;
6403 struct mbuf **nm = &top;
6404 uintptr_t data0, data;
6405 unsigned int len0, len;
6406
6407 VERIFY(MBUF_MULTIPAGES(m));
6408 VERIFY(m->m_next == NULL);
6409 data0 = (uintptr_t)m->m_data;
6410 len0 = m->m_len;
6411 *last = top;
6412
6413 for (;;) {
6414 struct mbuf *n;
6415
6416 data = data0;
0a7de745 6417 if (IS_P2ALIGNED(data, PAGE_SIZE) && len0 > PAGE_SIZE) {
3e170ce0 6418 len = PAGE_SIZE;
0a7de745
A
6419 } else if (!IS_P2ALIGNED(data, PAGE_SIZE) &&
6420 P2ROUNDUP(data, PAGE_SIZE) < (data + len0)) {
3e170ce0 6421 len = P2ROUNDUP(data, PAGE_SIZE) - data;
0a7de745 6422 } else {
2d21ac55 6423 len = len0;
0a7de745 6424 }
2d21ac55
A
6425
6426 VERIFY(len > 0);
6427 VERIFY(m->m_flags & M_EXT);
6428 m->m_data = (void *)data;
6429 m->m_len = len;
6430
6431 *nm = *last = m;
6432 nm = &m->m_next;
6433 m->m_next = NULL;
6434
6435 data0 += len;
6436 len0 -= len;
0a7de745 6437 if (len0 == 0) {
2d21ac55 6438 break;
0a7de745 6439 }
2d21ac55
A
6440
6441 n = _M_RETRY(M_DONTWAIT, MT_DATA);
6442 if (n == NULL) {
6443 m_freem(top);
6444 top = *last = NULL;
6445 break;
6446 }
6447
6448 n->m_ext = m->m_ext;
6449 m_incref(m);
6450 n->m_flags |= M_EXT;
6451 m = n;
6452 }
0a7de745 6453 return top;
9bccf70c
A
6454}
6455
2d21ac55
A
6456struct mbuf *
6457m_normalize(struct mbuf *m)
9bccf70c 6458{
2d21ac55
A
6459 struct mbuf *top = NULL;
6460 struct mbuf **nm = &top;
6461 boolean_t expanded = FALSE;
6462
6463 while (m != NULL) {
6464 struct mbuf *n;
6465
6466 n = m->m_next;
6467 m->m_next = NULL;
6468
6469 /* Does the data cross one or more page boundaries? */
6470 if (MBUF_MULTIPAGES(m)) {
6471 struct mbuf *last;
6472 if ((m = m_expand(m, &last)) == NULL) {
6473 m_freem(n);
6474 m_freem(top);
6475 top = NULL;
6476 break;
6477 }
6478 *nm = m;
6479 nm = &last->m_next;
6480 expanded = TRUE;
6481 } else {
6482 *nm = m;
6483 nm = &m->m_next;
6484 }
6485 m = n;
6486 }
0a7de745 6487 if (expanded) {
2d21ac55 6488 atomic_add_32(&mb_normalized, 1);
0a7de745
A
6489 }
6490 return top;
9bccf70c
A
6491}
6492
6d2010ae
A
6493/*
6494 * Append the specified data to the indicated mbuf chain,
6495 * Extend the mbuf chain if the new data does not fit in
6496 * existing space.
6497 *
6498 * Return 1 if able to complete the job; otherwise 0.
6499 */
6500int
6501m_append(struct mbuf *m0, int len, caddr_t cp)
6502{
6503 struct mbuf *m, *n;
6504 int remainder, space;
6505
0a7de745 6506 for (m = m0; m->m_next != NULL; m = m->m_next) {
6d2010ae 6507 ;
0a7de745 6508 }
6d2010ae
A
6509 remainder = len;
6510 space = M_TRAILINGSPACE(m);
6511 if (space > 0) {
6512 /*
6513 * Copy into available space.
6514 */
0a7de745 6515 if (space > remainder) {
6d2010ae 6516 space = remainder;
0a7de745 6517 }
6d2010ae
A
6518 bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
6519 m->m_len += space;
39037602
A
6520 cp += space;
6521 remainder -= space;
6d2010ae
A
6522 }
6523 while (remainder > 0) {
6524 /*
6525 * Allocate a new mbuf; could check space
6526 * and allocate a cluster instead.
6527 */
6528 n = m_get(M_WAITOK, m->m_type);
0a7de745 6529 if (n == NULL) {
6d2010ae 6530 break;
0a7de745 6531 }
6d2010ae
A
6532 n->m_len = min(MLEN, remainder);
6533 bcopy(cp, mtod(n, caddr_t), n->m_len);
6534 cp += n->m_len;
6535 remainder -= n->m_len;
6536 m->m_next = n;
6537 m = n;
6538 }
0a7de745 6539 if (m0->m_flags & M_PKTHDR) {
6d2010ae 6540 m0->m_pkthdr.len += len - remainder;
0a7de745
A
6541 }
6542 return remainder == 0;
6d2010ae
A
6543}
6544
6545struct mbuf *
6546m_last(struct mbuf *m)
6547{
0a7de745 6548 while (m->m_next != NULL) {
6d2010ae 6549 m = m->m_next;
0a7de745
A
6550 }
6551 return m;
6d2010ae
A
6552}
6553
316670eb
A
6554unsigned int
6555m_fixhdr(struct mbuf *m0)
6556{
6557 u_int len;
6558
39236c6e
A
6559 VERIFY(m0->m_flags & M_PKTHDR);
6560
316670eb
A
6561 len = m_length2(m0, NULL);
6562 m0->m_pkthdr.len = len;
0a7de745 6563 return len;
316670eb
A
6564}
6565
6566unsigned int
6567m_length2(struct mbuf *m0, struct mbuf **last)
6568{
6569 struct mbuf *m;
6570 u_int len;
6571
6572 len = 0;
6573 for (m = m0; m != NULL; m = m->m_next) {
6574 len += m->m_len;
0a7de745 6575 if (m->m_next == NULL) {
316670eb 6576 break;
0a7de745 6577 }
316670eb 6578 }
0a7de745 6579 if (last != NULL) {
316670eb 6580 *last = m;
0a7de745
A
6581 }
6582 return len;
316670eb
A
6583}
6584
6585/*
6586 * Defragment a mbuf chain, returning the shortest possible chain of mbufs
6587 * and clusters. If allocation fails and this cannot be completed, NULL will
6588 * be returned, but the passed in chain will be unchanged. Upon success,
6589 * the original chain will be freed, and the new chain will be returned.
6590 *
6591 * If a non-packet header is passed in, the original mbuf (chain?) will
6592 * be returned unharmed.
6593 *
6594 * If offset is specfied, the first mbuf in the chain will have a leading
6595 * space of the amount stated by the "off" parameter.
6596 *
6597 * This routine requires that the m_pkthdr.header field of the original
6598 * mbuf chain is cleared by the caller.
6599 */
6600struct mbuf *
6601m_defrag_offset(struct mbuf *m0, u_int32_t off, int how)
6602{
6603 struct mbuf *m_new = NULL, *m_final = NULL;
6604 int progress = 0, length, pktlen;
6605
0a7de745
A
6606 if (!(m0->m_flags & M_PKTHDR)) {
6607 return m0;
6608 }
316670eb
A
6609
6610 VERIFY(off < MHLEN);
6611 m_fixhdr(m0); /* Needed sanity check */
6612
6613 pktlen = m0->m_pkthdr.len + off;
0a7de745 6614 if (pktlen > MHLEN) {
316670eb 6615 m_final = m_getcl(how, MT_DATA, M_PKTHDR);
0a7de745 6616 } else {
316670eb 6617 m_final = m_gethdr(how, MT_DATA);
0a7de745 6618 }
316670eb 6619
0a7de745 6620 if (m_final == NULL) {
316670eb 6621 goto nospace;
0a7de745 6622 }
316670eb
A
6623
6624 if (off > 0) {
6625 pktlen -= off;
316670eb
A
6626 m_final->m_data += off;
6627 }
6628
6629 /*
6630 * Caller must have handled the contents pointed to by this
6631 * pointer before coming here, as otherwise it will point to
6632 * the original mbuf which will get freed upon success.
6633 */
39236c6e 6634 VERIFY(m0->m_pkthdr.pkt_hdr == NULL);
316670eb 6635
0a7de745 6636 if (m_dup_pkthdr(m_final, m0, how) == 0) {
316670eb 6637 goto nospace;
0a7de745 6638 }
316670eb
A
6639
6640 m_new = m_final;
6641
6642 while (progress < pktlen) {
6643 length = pktlen - progress;
0a7de745 6644 if (length > MCLBYTES) {
316670eb 6645 length = MCLBYTES;
0a7de745 6646 }
39236c6e 6647 length -= ((m_new == m_final) ? off : 0);
0a7de745 6648 if (length < 0) {
5ba3f43e 6649 goto nospace;
0a7de745 6650 }
316670eb
A
6651
6652 if (m_new == NULL) {
0a7de745 6653 if (length > MLEN) {
316670eb 6654 m_new = m_getcl(how, MT_DATA, 0);
0a7de745 6655 } else {
316670eb 6656 m_new = m_get(how, MT_DATA);
0a7de745
A
6657 }
6658 if (m_new == NULL) {
316670eb 6659 goto nospace;
0a7de745 6660 }
316670eb
A
6661 }
6662
6663 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
6664 progress += length;
6665 m_new->m_len = length;
0a7de745 6666 if (m_new != m_final) {
316670eb 6667 m_cat(m_final, m_new);
0a7de745 6668 }
316670eb
A
6669 m_new = NULL;
6670 }
6671 m_freem(m0);
6672 m0 = m_final;
0a7de745 6673 return m0;
316670eb 6674nospace:
0a7de745 6675 if (m_final) {
316670eb 6676 m_freem(m_final);
0a7de745
A
6677 }
6678 return NULL;
316670eb
A
6679}
6680
6681struct mbuf *
6682m_defrag(struct mbuf *m0, int how)
6683{
0a7de745 6684 return m_defrag_offset(m0, 0, how);
316670eb
A
6685}
6686
9bccf70c
A
6687void
6688m_mchtype(struct mbuf *m, int t)
6689{
2d21ac55
A
6690 mtype_stat_inc(t);
6691 mtype_stat_dec(m->m_type);
6692 (m)->m_type = t;
9bccf70c
A
6693}
6694
2d21ac55
A
6695void *
6696m_mtod(struct mbuf *m)
9bccf70c 6697{
0a7de745 6698 return MTOD(m, void *);
9bccf70c
A
6699}
6700
2d21ac55
A
6701struct mbuf *
6702m_dtom(void *x)
9bccf70c 6703{
0a7de745 6704 return (struct mbuf *)((uintptr_t)(x) & ~(MSIZE - 1));
9bccf70c
A
6705}
6706
2d21ac55
A
6707void
6708m_mcheck(struct mbuf *m)
9bccf70c 6709{
2d21ac55 6710 _MCHECK(m);
9bccf70c
A
6711}
6712
6d2010ae
A
6713/*
6714 * Return a pointer to mbuf/offset of location in mbuf chain.
6715 */
6716struct mbuf *
6717m_getptr(struct mbuf *m, int loc, int *off)
6718{
6d2010ae
A
6719 while (loc >= 0) {
6720 /* Normal end of search. */
6721 if (m->m_len > loc) {
6722 *off = loc;
0a7de745 6723 return m;
6d2010ae
A
6724 } else {
6725 loc -= m->m_len;
6726 if (m->m_next == NULL) {
6727 if (loc == 0) {
6728 /* Point at the end of valid data. */
6729 *off = m->m_len;
0a7de745 6730 return m;
6d2010ae 6731 }
0a7de745 6732 return NULL;
6d2010ae
A
6733 }
6734 m = m->m_next;
6735 }
6736 }
0a7de745 6737 return NULL;
6d2010ae
A
6738}
6739
2d21ac55
A
6740/*
6741 * Inform the corresponding mcache(s) that there's a waiter below.
6742 */
6743static void
6744mbuf_waiter_inc(mbuf_class_t class, boolean_t comp)
9bccf70c 6745{
2d21ac55
A
6746 mcache_waiter_inc(m_cache(class));
6747 if (comp) {
6748 if (class == MC_CL) {
6749 mcache_waiter_inc(m_cache(MC_MBUF_CL));
6750 } else if (class == MC_BIGCL) {
6751 mcache_waiter_inc(m_cache(MC_MBUF_BIGCL));
6752 } else if (class == MC_16KCL) {
6753 mcache_waiter_inc(m_cache(MC_MBUF_16KCL));
6754 } else {
6755 mcache_waiter_inc(m_cache(MC_MBUF_CL));
6756 mcache_waiter_inc(m_cache(MC_MBUF_BIGCL));
6757 }
6758 }
9bccf70c
A
6759}
6760
2d21ac55
A
6761/*
6762 * Inform the corresponding mcache(s) that there's no more waiter below.
6763 */
6764static void
6765mbuf_waiter_dec(mbuf_class_t class, boolean_t comp)
6766{
6767 mcache_waiter_dec(m_cache(class));
6768 if (comp) {
6769 if (class == MC_CL) {
6770 mcache_waiter_dec(m_cache(MC_MBUF_CL));
6771 } else if (class == MC_BIGCL) {
6772 mcache_waiter_dec(m_cache(MC_MBUF_BIGCL));
6773 } else if (class == MC_16KCL) {
6774 mcache_waiter_dec(m_cache(MC_MBUF_16KCL));
6775 } else {
6776 mcache_waiter_dec(m_cache(MC_MBUF_CL));
6777 mcache_waiter_dec(m_cache(MC_MBUF_BIGCL));
6778 }
6779 }
6780}
9bccf70c 6781
6d2010ae
A
6782/*
6783 * Called during slab (blocking and non-blocking) allocation. If there
6784 * is at least one waiter, and the time since the first waiter is blocked
6785 * is greater than the watchdog timeout, panic the system.
6786 */
6787static void
6788mbuf_watchdog(void)
6789{
6790 struct timeval now;
6791 unsigned int since;
6792
0a7de745 6793 if (mb_waiters == 0 || !mb_watchdog) {
6d2010ae 6794 return;
0a7de745 6795 }
6d2010ae
A
6796
6797 microuptime(&now);
6798 since = now.tv_sec - mb_wdtstart.tv_sec;
6799 if (since >= MB_WDT_MAXTIME) {
6800 panic_plain("%s: %d waiters stuck for %u secs\n%s", __func__,
6801 mb_waiters, since, mbuf_dump());
6802 /* NOTREACHED */
6803 }
6804}
6805
2d21ac55
A
6806/*
6807 * Called during blocking allocation. Returns TRUE if one or more objects
6808 * are available at the per-CPU caches layer and that allocation should be
6809 * retried at that level.
6810 */
6811static boolean_t
6812mbuf_sleep(mbuf_class_t class, unsigned int num, int wait)
9bccf70c 6813{
2d21ac55
A
6814 boolean_t mcache_retry = FALSE;
6815
5ba3f43e 6816 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
6817
6818 /* Check if there's anything at the cache layer */
6819 if (mbuf_cached_above(class, wait)) {
6820 mcache_retry = TRUE;
6821 goto done;
6822 }
6823
6824 /* Nothing? Then try hard to get it from somewhere */
6825 m_reclaim(class, num, (wait & MCR_COMP));
6826
6827 /* We tried hard and got something? */
6828 if (m_infree(class) > 0) {
6829 mbstat.m_wait++;
6830 goto done;
6831 } else if (mbuf_cached_above(class, wait)) {
6832 mbstat.m_wait++;
6833 mcache_retry = TRUE;
6834 goto done;
6835 } else if (wait & MCR_TRYHARD) {
6836 mcache_retry = TRUE;
6837 goto done;
6838 }
6839
6840 /*
6841 * There's really nothing for us right now; inform the
6842 * cache(s) that there is a waiter below and go to sleep.
6843 */
6844 mbuf_waiter_inc(class, (wait & MCR_COMP));
6845
6846 VERIFY(!(wait & MCR_NOSLEEP));
6d2010ae
A
6847
6848 /*
6849 * If this is the first waiter, arm the watchdog timer. Otherwise
6850 * check if we need to panic the system due to watchdog timeout.
6851 */
0a7de745 6852 if (mb_waiters == 0) {
6d2010ae 6853 microuptime(&mb_wdtstart);
0a7de745 6854 } else {
6d2010ae 6855 mbuf_watchdog();
0a7de745 6856 }
6d2010ae 6857
2d21ac55 6858 mb_waiters++;
cc8bc92a 6859 m_region_expand(class) += m_total(class) + num;
5ba3f43e 6860 /* wake up the worker thread */
a39ff7e2 6861 if (mbuf_worker_ready &&
5ba3f43e
A
6862 mbuf_worker_needs_wakeup) {
6863 wakeup((caddr_t)&mbuf_worker_needs_wakeup);
6864 mbuf_worker_needs_wakeup = FALSE;
6865 }
d9a64523 6866 mbwdog_logger("waiting (%d mbufs in class %s)", num, m_cname(class));
0a7de745 6867 (void) msleep(mb_waitchan, mbuf_mlock, (PZERO - 1), m_cname(class), NULL);
d9a64523 6868 mbwdog_logger("woke up (%d mbufs in class %s) ", num, m_cname(class));
2d21ac55
A
6869
6870 /* We are now up; stop getting notified until next round */
6871 mbuf_waiter_dec(class, (wait & MCR_COMP));
6872
6873 /* We waited and got something */
6874 if (m_infree(class) > 0) {
6875 mbstat.m_wait++;
6876 goto done;
6877 } else if (mbuf_cached_above(class, wait)) {
6878 mbstat.m_wait++;
6879 mcache_retry = TRUE;
6880 }
6881done:
0a7de745 6882 return mcache_retry;
9bccf70c
A
6883}
6884
39037602 6885__attribute__((noreturn))
91447636 6886static void
2d21ac55 6887mbuf_worker_thread(void)
1c79356b 6888{
2d21ac55
A
6889 int mbuf_expand;
6890
91447636 6891 while (1) {
2d21ac55 6892 lck_mtx_lock(mbuf_mlock);
d9a64523 6893 mbwdog_logger("worker thread running");
cc8bc92a 6894 mbuf_worker_run_cnt++;
2d21ac55 6895 mbuf_expand = 0;
d9a64523
A
6896 /*
6897 * Allocations are based on page size, so if we have depleted
6898 * the reserved spaces, try to free mbufs from the major classes.
6899 */
6900#if PAGE_SIZE == 4096
6901 uint32_t m_mbclusters = m_total(MC_MBUF) >> NMBPCLSHIFT;
6902 uint32_t m_clusters = m_total(MC_CL);
6903 uint32_t m_bigclusters = m_total(MC_BIGCL) << NCLPBGSHIFT;
6904 uint32_t sumclusters = m_mbclusters + m_clusters + m_bigclusters;
6905 if (sumclusters >= nclusters) {
6906 mbwdog_logger("reclaiming bigcl");
6907 mbuf_drain_locked(TRUE);
6908 m_reclaim(MC_BIGCL, 4, FALSE);
6909 }
6910#else
6911 uint32_t m_16kclusters = m_total(MC_16KCL);
6912 if (njcl > 0 && (m_16kclusters << NCLPJCLSHIFT) >= njcl) {
6913 mbwdog_logger("reclaiming 16kcl");
6914 mbuf_drain_locked(TRUE);
6915 m_reclaim(MC_16KCL, 4, FALSE);
6916 }
6917#endif
5ba3f43e 6918 if (m_region_expand(MC_CL) > 0) {
91447636 6919 int n;
cc8bc92a 6920 mb_expand_cl_cnt++;
2d21ac55 6921 /* Adjust to current number of cluster in use */
5ba3f43e 6922 n = m_region_expand(MC_CL) -
2d21ac55 6923 (m_total(MC_CL) - m_infree(MC_CL));
0a7de745 6924 if ((n + m_total(MC_CL)) > m_maxlimit(MC_CL)) {
2d21ac55 6925 n = m_maxlimit(MC_CL) - m_total(MC_CL);
0a7de745 6926 }
cc8bc92a
A
6927 if (n > 0) {
6928 mb_expand_cl_total += n;
6929 }
5ba3f43e 6930 m_region_expand(MC_CL) = 0;
2d21ac55 6931
d9a64523
A
6932 if (n > 0) {
6933 mbwdog_logger("expanding MC_CL by %d", n);
a39ff7e2 6934 freelist_populate(MC_CL, n, M_WAIT);
d9a64523 6935 }
91447636 6936 }
5ba3f43e 6937 if (m_region_expand(MC_BIGCL) > 0) {
91447636 6938 int n;
cc8bc92a 6939 mb_expand_bigcl_cnt++;
2d21ac55 6940 /* Adjust to current number of 4 KB cluster in use */
5ba3f43e 6941 n = m_region_expand(MC_BIGCL) -
2d21ac55 6942 (m_total(MC_BIGCL) - m_infree(MC_BIGCL));
0a7de745 6943 if ((n + m_total(MC_BIGCL)) > m_maxlimit(MC_BIGCL)) {
2d21ac55 6944 n = m_maxlimit(MC_BIGCL) - m_total(MC_BIGCL);
0a7de745 6945 }
cc8bc92a
A
6946 if (n > 0) {
6947 mb_expand_bigcl_total += n;
6948 }
5ba3f43e 6949 m_region_expand(MC_BIGCL) = 0;
2d21ac55 6950
d9a64523
A
6951 if (n > 0) {
6952 mbwdog_logger("expanding MC_BIGCL by %d", n);
a39ff7e2 6953 freelist_populate(MC_BIGCL, n, M_WAIT);
d9a64523 6954 }
2d21ac55 6955 }
5ba3f43e 6956 if (m_region_expand(MC_16KCL) > 0) {
2d21ac55 6957 int n;
cc8bc92a 6958 mb_expand_16kcl_cnt++;
2d21ac55 6959 /* Adjust to current number of 16 KB cluster in use */
5ba3f43e 6960 n = m_region_expand(MC_16KCL) -
2d21ac55 6961 (m_total(MC_16KCL) - m_infree(MC_16KCL));
0a7de745 6962 if ((n + m_total(MC_16KCL)) > m_maxlimit(MC_16KCL)) {
2d21ac55 6963 n = m_maxlimit(MC_16KCL) - m_total(MC_16KCL);
0a7de745 6964 }
cc8bc92a
A
6965 if (n > 0) {
6966 mb_expand_16kcl_total += n;
6967 }
5ba3f43e 6968 m_region_expand(MC_16KCL) = 0;
2d21ac55 6969
d9a64523
A
6970 if (n > 0) {
6971 mbwdog_logger("expanding MC_16KCL by %d", n);
2d21ac55 6972 (void) freelist_populate(MC_16KCL, n, M_WAIT);
d9a64523 6973 }
2d21ac55
A
6974 }
6975
6976 /*
6977 * Because we can run out of memory before filling the mbuf
6978 * map, we should not allocate more clusters than they are
6979 * mbufs -- otherwise we could have a large number of useless
6980 * clusters allocated.
91447636 6981 */
d9a64523
A
6982 mbwdog_logger("totals: MC_MBUF %d MC_BIGCL %d MC_CL %d MC_16KCL %d",
6983 m_total(MC_MBUF), m_total(MC_BIGCL), m_total(MC_CL),
6984 m_total(MC_16KCL));
6985 uint32_t total_mbufs = m_total(MC_MBUF);
6986 uint32_t total_clusters = m_total(MC_BIGCL) + m_total(MC_CL) +
6987 m_total(MC_16KCL);
6988 if (total_mbufs < total_clusters) {
6989 mbwdog_logger("expanding MC_MBUF by %d",
0a7de745 6990 total_clusters - total_mbufs);
d9a64523
A
6991 }
6992 while (total_mbufs < total_clusters) {
a39ff7e2 6993 mb_expand_cnt++;
0a7de745 6994 if (freelist_populate(MC_MBUF, 1, M_WAIT) == 0) {
a39ff7e2 6995 break;
0a7de745 6996 }
d9a64523
A
6997 total_mbufs = m_total(MC_MBUF);
6998 total_clusters = m_total(MC_BIGCL) + m_total(MC_CL) +
6999 m_total(MC_16KCL);
91447636 7000 }
2d21ac55 7001
39037602 7002 mbuf_worker_needs_wakeup = TRUE;
cc8bc92a
A
7003 /*
7004 * If there's a deadlock and we're not sending / receiving
7005 * packets, net_uptime() won't be updated. Update it here
7006 * so we are sure it's correct.
7007 */
7008 net_update_uptime();
7009 mbuf_worker_last_runtime = net_uptime();
39037602
A
7010 assert_wait((caddr_t)&mbuf_worker_needs_wakeup,
7011 THREAD_UNINT);
d9a64523 7012 mbwdog_logger("worker thread sleeping");
2d21ac55 7013 lck_mtx_unlock(mbuf_mlock);
2d21ac55 7014 (void) thread_block((thread_continue_t)mbuf_worker_thread);
91447636 7015 }
1c79356b
A
7016}
7017
39037602 7018__attribute__((noreturn))
91447636 7019static void
2d21ac55 7020mbuf_worker_thread_init(void)
55e303ae 7021{
2d21ac55
A
7022 mbuf_worker_ready++;
7023 mbuf_worker_thread();
55e303ae 7024}
1c79356b 7025
2d21ac55
A
7026static mcl_slab_t *
7027slab_get(void *buf)
7028{
7029 mcl_slabg_t *slg;
7030 unsigned int ix, k;
7031
5ba3f43e 7032 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
7033
7034 VERIFY(MBUF_IN_MAP(buf));
3e170ce0 7035 ix = ((unsigned char *)buf - mbutl) >> MBSHIFT;
2d21ac55
A
7036 VERIFY(ix < maxslabgrp);
7037
7038 if ((slg = slabstbl[ix]) == NULL) {
7039 /*
39037602 7040 * In the current implementation, we never shrink the slabs
fe8ab488
A
7041 * table; if we attempt to reallocate a cluster group when
7042 * it's already allocated, panic since this is a sign of a
7043 * memory corruption (slabstbl[ix] got nullified).
2d21ac55
A
7044 */
7045 ++slabgrp;
7046 VERIFY(ix < slabgrp);
7047 /*
7048 * Slabs expansion can only be done single threaded; when
7049 * we get here, it must be as a result of m_clalloc() which
7050 * is serialized and therefore mb_clalloc_busy must be set.
7051 */
7052 VERIFY(mb_clalloc_busy);
7053 lck_mtx_unlock(mbuf_mlock);
7054
7055 /* This is a new buffer; create the slabs group for it */
0a7de745 7056 MALLOC(slg, mcl_slabg_t *, sizeof(*slg), M_TEMP,
2d21ac55 7057 M_WAITOK | M_ZERO);
3e170ce0
A
7058 MALLOC(slg->slg_slab, mcl_slab_t *, sizeof(mcl_slab_t) * NSLABSPMB,
7059 M_TEMP, M_WAITOK | M_ZERO);
7060 VERIFY(slg != NULL && slg->slg_slab != NULL);
2d21ac55
A
7061
7062 lck_mtx_lock(mbuf_mlock);
7063 /*
7064 * No other thread could have gone into m_clalloc() after
7065 * we dropped the lock above, so verify that it's true.
7066 */
7067 VERIFY(mb_clalloc_busy);
7068
7069 slabstbl[ix] = slg;
7070
7071 /* Chain each slab in the group to its forward neighbor */
0a7de745 7072 for (k = 1; k < NSLABSPMB; k++) {
2d21ac55 7073 slg->slg_slab[k - 1].sl_next = &slg->slg_slab[k];
0a7de745 7074 }
2d21ac55
A
7075 VERIFY(slg->slg_slab[NSLABSPMB - 1].sl_next == NULL);
7076
7077 /* And chain the last slab in the previous group to this */
7078 if (ix > 0) {
7079 VERIFY(slabstbl[ix - 1]->
7080 slg_slab[NSLABSPMB - 1].sl_next == NULL);
7081 slabstbl[ix - 1]->slg_slab[NSLABSPMB - 1].sl_next =
7082 &slg->slg_slab[0];
7083 }
7084 }
7085
3e170ce0 7086 ix = MTOPG(buf) % NSLABSPMB;
2d21ac55
A
7087 VERIFY(ix < NSLABSPMB);
7088
0a7de745 7089 return &slg->slg_slab[ix];
2d21ac55
A
7090}
7091
7092static void
7093slab_init(mcl_slab_t *sp, mbuf_class_t class, u_int32_t flags,
7094 void *base, void *head, unsigned int len, int refcnt, int chunks)
7095{
7096 sp->sl_class = class;
7097 sp->sl_flags = flags;
7098 sp->sl_base = base;
7099 sp->sl_head = head;
7100 sp->sl_len = len;
7101 sp->sl_refcnt = refcnt;
7102 sp->sl_chunks = chunks;
7103 slab_detach(sp);
7104}
7105
7106static void
7107slab_insert(mcl_slab_t *sp, mbuf_class_t class)
7108{
7109 VERIFY(slab_is_detached(sp));
7110 m_slab_cnt(class)++;
7111 TAILQ_INSERT_TAIL(&m_slablist(class), sp, sl_link);
7112 sp->sl_flags &= ~SLF_DETACHED;
3e170ce0
A
7113
7114 /*
7115 * If a buffer spans multiple contiguous pages then mark them as
7116 * detached too
7117 */
6d2010ae 7118 if (class == MC_16KCL) {
2d21ac55 7119 int k;
6d2010ae 7120 for (k = 1; k < NSLABSP16KB; k++) {
2d21ac55
A
7121 sp = sp->sl_next;
7122 /* Next slab must already be present */
3e170ce0 7123 VERIFY(sp != NULL && slab_is_detached(sp));
2d21ac55
A
7124 sp->sl_flags &= ~SLF_DETACHED;
7125 }
7126 }
7127}
7128
7129static void
7130slab_remove(mcl_slab_t *sp, mbuf_class_t class)
7131{
3e170ce0 7132 int k;
2d21ac55
A
7133 VERIFY(!slab_is_detached(sp));
7134 VERIFY(m_slab_cnt(class) > 0);
7135 m_slab_cnt(class)--;
7136 TAILQ_REMOVE(&m_slablist(class), sp, sl_link);
7137 slab_detach(sp);
6d2010ae 7138 if (class == MC_16KCL) {
6d2010ae 7139 for (k = 1; k < NSLABSP16KB; k++) {
2d21ac55
A
7140 sp = sp->sl_next;
7141 /* Next slab must already be present */
7142 VERIFY(sp != NULL);
7143 VERIFY(!slab_is_detached(sp));
7144 slab_detach(sp);
7145 }
7146 }
7147}
7148
7149static boolean_t
7150slab_inrange(mcl_slab_t *sp, void *buf)
7151{
0a7de745
A
7152 return (uintptr_t)buf >= (uintptr_t)sp->sl_base &&
7153 (uintptr_t)buf < ((uintptr_t)sp->sl_base + sp->sl_len);
2d21ac55
A
7154}
7155
b0d623f7 7156#undef panic
2d21ac55
A
7157
7158static void
7159slab_nextptr_panic(mcl_slab_t *sp, void *addr)
7160{
7161 int i;
7162 unsigned int chunk_len = sp->sl_len / sp->sl_chunks;
7163 uintptr_t buf = (uintptr_t)sp->sl_base;
7164
7165 for (i = 0; i < sp->sl_chunks; i++, buf += chunk_len) {
7166 void *next = ((mcache_obj_t *)buf)->obj_next;
0a7de745 7167 if (next != addr) {
2d21ac55 7168 continue;
0a7de745 7169 }
6d2010ae 7170 if (!mclverify) {
2d21ac55
A
7171 if (next != NULL && !MBUF_IN_MAP(next)) {
7172 mcache_t *cp = m_cache(sp->sl_class);
7173 panic("%s: %s buffer %p in slab %p modified "
7174 "after free at offset 0: %p out of range "
7175 "[%p-%p)\n", __func__, cp->mc_name,
7176 (void *)buf, sp, next, mbutl, embutl);
7177 /* NOTREACHED */
7178 }
7179 } else {
7180 mcache_audit_t *mca = mcl_audit_buf2mca(sp->sl_class,
7181 (mcache_obj_t *)buf);
7182 mcl_audit_verify_nextptr(next, mca);
7183 }
7184 }
7185}
7186
7187static void
7188slab_detach(mcl_slab_t *sp)
7189{
7190 sp->sl_link.tqe_next = (mcl_slab_t *)-1;
7191 sp->sl_link.tqe_prev = (mcl_slab_t **)-1;
7192 sp->sl_flags |= SLF_DETACHED;
7193}
7194
7195static boolean_t
7196slab_is_detached(mcl_slab_t *sp)
7197{
0a7de745
A
7198 return (intptr_t)sp->sl_link.tqe_next == -1 &&
7199 (intptr_t)sp->sl_link.tqe_prev == -1 &&
7200 (sp->sl_flags & SLF_DETACHED);
2d21ac55
A
7201}
7202
7203static void
7204mcl_audit_init(void *buf, mcache_audit_t **mca_list,
7205 mcache_obj_t **con_list, size_t con_size, unsigned int num)
7206{
7207 mcache_audit_t *mca, *mca_tail;
7208 mcache_obj_t *con = NULL;
7209 boolean_t save_contents = (con_list != NULL);
7210 unsigned int i, ix;
7211
3e170ce0 7212 ASSERT(num <= NMBPG);
2d21ac55
A
7213 ASSERT(con_list == NULL || con_size != 0);
7214
3e170ce0 7215 ix = MTOPG(buf);
6d2010ae
A
7216 VERIFY(ix < maxclaudit);
7217
2d21ac55 7218 /* Make sure we haven't been here before */
0a7de745 7219 for (i = 0; i < num; i++) {
2d21ac55 7220 VERIFY(mclaudit[ix].cl_audit[i] == NULL);
0a7de745 7221 }
2d21ac55
A
7222
7223 mca = mca_tail = *mca_list;
0a7de745 7224 if (save_contents) {
2d21ac55 7225 con = *con_list;
0a7de745 7226 }
2d21ac55
A
7227
7228 for (i = 0; i < num; i++) {
7229 mcache_audit_t *next;
7230
7231 next = mca->mca_next;
0a7de745 7232 bzero(mca, sizeof(*mca));
2d21ac55
A
7233 mca->mca_next = next;
7234 mclaudit[ix].cl_audit[i] = mca;
7235
7236 /* Attach the contents buffer if requested */
7237 if (save_contents) {
39236c6e
A
7238 mcl_saved_contents_t *msc =
7239 (mcl_saved_contents_t *)(void *)con;
7240
7241 VERIFY(msc != NULL);
0a7de745
A
7242 VERIFY(IS_P2ALIGNED(msc, sizeof(u_int64_t)));
7243 VERIFY(con_size == sizeof(*msc));
2d21ac55 7244 mca->mca_contents_size = con_size;
39236c6e 7245 mca->mca_contents = msc;
2d21ac55
A
7246 con = con->obj_next;
7247 bzero(mca->mca_contents, mca->mca_contents_size);
7248 }
7249
7250 mca_tail = mca;
7251 mca = mca->mca_next;
7252 }
91447636 7253
0a7de745 7254 if (save_contents) {
2d21ac55 7255 *con_list = con;
0a7de745 7256 }
2d21ac55
A
7257
7258 *mca_list = mca_tail->mca_next;
7259 mca_tail->mca_next = NULL;
7260}
7261
fe8ab488
A
7262static void
7263mcl_audit_free(void *buf, unsigned int num)
7264{
7265 unsigned int i, ix;
7266 mcache_audit_t *mca, *mca_list;
7267
3e170ce0 7268 ix = MTOPG(buf);
fe8ab488 7269 VERIFY(ix < maxclaudit);
39037602 7270
fe8ab488
A
7271 if (mclaudit[ix].cl_audit[0] != NULL) {
7272 mca_list = mclaudit[ix].cl_audit[0];
7273 for (i = 0; i < num; i++) {
7274 mca = mclaudit[ix].cl_audit[i];
7275 mclaudit[ix].cl_audit[i] = NULL;
0a7de745 7276 if (mca->mca_contents) {
fe8ab488
A
7277 mcache_free(mcl_audit_con_cache,
7278 mca->mca_contents);
0a7de745 7279 }
fe8ab488
A
7280 }
7281 mcache_free_ext(mcache_audit_cache,
7282 (mcache_obj_t *)mca_list);
7283 }
7284}
7285
2d21ac55 7286/*
6d2010ae 7287 * Given an address of a buffer (mbuf/2KB/4KB/16KB), return
2d21ac55
A
7288 * the corresponding audit structure for that buffer.
7289 */
7290static mcache_audit_t *
3e170ce0 7291mcl_audit_buf2mca(mbuf_class_t class, mcache_obj_t *mobj)
2d21ac55
A
7292{
7293 mcache_audit_t *mca = NULL;
3e170ce0
A
7294 int ix = MTOPG(mobj), m_idx = 0;
7295 unsigned char *page_addr;
2d21ac55 7296
6d2010ae 7297 VERIFY(ix < maxclaudit);
3e170ce0
A
7298 VERIFY(IS_P2ALIGNED(mobj, MIN(m_maxsize(class), PAGE_SIZE)));
7299
7300 page_addr = PGTOM(ix);
2d21ac55
A
7301
7302 switch (class) {
7303 case MC_MBUF:
7304 /*
6d2010ae 7305 * For the mbuf case, find the index of the page
2d21ac55 7306 * used by the mbuf and use that index to locate the
6d2010ae
A
7307 * base address of the page. Then find out the
7308 * mbuf index relative to the page base and use
2d21ac55
A
7309 * it to locate the audit structure.
7310 */
3e170ce0
A
7311 m_idx = MBPAGEIDX(page_addr, mobj);
7312 VERIFY(m_idx < (int)NMBPG);
7313 mca = mclaudit[ix].cl_audit[m_idx];
2d21ac55
A
7314 break;
7315
7316 case MC_CL:
6d2010ae
A
7317 /*
7318 * Same thing as above, but for 2KB clusters in a page.
7319 */
3e170ce0
A
7320 m_idx = CLPAGEIDX(page_addr, mobj);
7321 VERIFY(m_idx < (int)NCLPG);
7322 mca = mclaudit[ix].cl_audit[m_idx];
6d2010ae
A
7323 break;
7324
2d21ac55 7325 case MC_BIGCL:
3e170ce0
A
7326 m_idx = BCLPAGEIDX(page_addr, mobj);
7327 VERIFY(m_idx < (int)NBCLPG);
7328 mca = mclaudit[ix].cl_audit[m_idx];
7329 break;
2d21ac55
A
7330 case MC_16KCL:
7331 /*
7332 * Same as above, but only return the first element.
7333 */
7334 mca = mclaudit[ix].cl_audit[0];
7335 break;
7336
7337 default:
7338 VERIFY(0);
7339 /* NOTREACHED */
7340 }
7341
0a7de745 7342 return mca;
2d21ac55
A
7343}
7344
7345static void
7346mcl_audit_mbuf(mcache_audit_t *mca, void *addr, boolean_t composite,
7347 boolean_t alloc)
7348{
7349 struct mbuf *m = addr;
7350 mcache_obj_t *next = ((mcache_obj_t *)m)->obj_next;
7351
7352 VERIFY(mca->mca_contents != NULL &&
7353 mca->mca_contents_size == AUDIT_CONTENTS_SIZE);
7354
0a7de745 7355 if (mclverify) {
6d2010ae 7356 mcl_audit_verify_nextptr(next, mca);
0a7de745 7357 }
2d21ac55
A
7358
7359 if (!alloc) {
7360 /* Save constructed mbuf fields */
7361 mcl_audit_save_mbuf(m, mca);
6d2010ae
A
7362 if (mclverify) {
7363 mcache_set_pattern(MCACHE_FREE_PATTERN, m,
7364 m_maxsize(MC_MBUF));
7365 }
2d21ac55
A
7366 ((mcache_obj_t *)m)->obj_next = next;
7367 return;
7368 }
7369
7370 /* Check if the buffer has been corrupted while in freelist */
6d2010ae
A
7371 if (mclverify) {
7372 mcache_audit_free_verify_set(mca, addr, 0, m_maxsize(MC_MBUF));
7373 }
2d21ac55
A
7374 /* Restore constructed mbuf fields */
7375 mcl_audit_restore_mbuf(m, mca, composite);
7376}
7377
7378static void
7379mcl_audit_restore_mbuf(struct mbuf *m, mcache_audit_t *mca, boolean_t composite)
7380{
39236c6e 7381 struct mbuf *ms = MCA_SAVED_MBUF_PTR(mca);
2d21ac55
A
7382
7383 if (composite) {
7384 struct mbuf *next = m->m_next;
813fb2f6 7385 VERIFY(ms->m_flags == M_EXT && m_get_rfa(ms) != NULL &&
2d21ac55 7386 MBUF_IS_COMPOSITE(ms));
39236c6e 7387 VERIFY(mca->mca_contents_size == AUDIT_CONTENTS_SIZE);
2d21ac55
A
7388 /*
7389 * We could have hand-picked the mbuf fields and restore
7390 * them individually, but that will be a maintenance
7391 * headache. Instead, restore everything that was saved;
7392 * the mbuf layer will recheck and reinitialize anyway.
7393 */
39236c6e 7394 bcopy(ms, m, MCA_SAVED_MBUF_SIZE);
2d21ac55
A
7395 m->m_next = next;
7396 } else {
7397 /*
7398 * For a regular mbuf (no cluster attached) there's nothing
7399 * to restore other than the type field, which is expected
7400 * to be MT_FREE.
7401 */
7402 m->m_type = ms->m_type;
7403 }
7404 _MCHECK(m);
7405}
7406
7407static void
7408mcl_audit_save_mbuf(struct mbuf *m, mcache_audit_t *mca)
7409{
39236c6e 7410 VERIFY(mca->mca_contents_size == AUDIT_CONTENTS_SIZE);
2d21ac55 7411 _MCHECK(m);
39236c6e 7412 bcopy(m, MCA_SAVED_MBUF_PTR(mca), MCA_SAVED_MBUF_SIZE);
2d21ac55
A
7413}
7414
7415static void
7416mcl_audit_cluster(mcache_audit_t *mca, void *addr, size_t size, boolean_t alloc,
7417 boolean_t save_next)
7418{
7419 mcache_obj_t *next = ((mcache_obj_t *)addr)->obj_next;
7420
7421 if (!alloc) {
6d2010ae
A
7422 if (mclverify) {
7423 mcache_set_pattern(MCACHE_FREE_PATTERN, addr, size);
7424 }
2d21ac55
A
7425 if (save_next) {
7426 mcl_audit_verify_nextptr(next, mca);
7427 ((mcache_obj_t *)addr)->obj_next = next;
7428 }
6d2010ae 7429 } else if (mclverify) {
2d21ac55
A
7430 /* Check if the buffer has been corrupted while in freelist */
7431 mcl_audit_verify_nextptr(next, mca);
7432 mcache_audit_free_verify_set(mca, addr, 0, size);
7433 }
7434}
7435
39236c6e
A
7436static void
7437mcl_audit_scratch(mcache_audit_t *mca)
7438{
7439 void *stack[MCACHE_STACK_DEPTH + 1];
7440 mcl_scratch_audit_t *msa;
7441 struct timeval now;
7442
7443 VERIFY(mca->mca_contents != NULL);
7444 msa = MCA_SAVED_SCRATCH_PTR(mca);
7445
7446 msa->msa_pthread = msa->msa_thread;
7447 msa->msa_thread = current_thread();
0a7de745 7448 bcopy(msa->msa_stack, msa->msa_pstack, sizeof(msa->msa_pstack));
39236c6e 7449 msa->msa_pdepth = msa->msa_depth;
0a7de745 7450 bzero(stack, sizeof(stack));
39236c6e 7451 msa->msa_depth = OSBacktrace(stack, MCACHE_STACK_DEPTH + 1) - 1;
0a7de745 7452 bcopy(&stack[1], msa->msa_stack, sizeof(msa->msa_stack));
39236c6e
A
7453
7454 msa->msa_ptstamp = msa->msa_tstamp;
7455 microuptime(&now);
7456 /* tstamp is in ms relative to base_ts */
7457 msa->msa_tstamp = ((now.tv_usec - mb_start.tv_usec) / 1000);
0a7de745 7458 if ((now.tv_sec - mb_start.tv_sec) > 0) {
39236c6e 7459 msa->msa_tstamp += ((now.tv_sec - mb_start.tv_sec) * 1000);
0a7de745 7460 }
39236c6e
A
7461}
7462
cb323159 7463__abortlike
2d21ac55
A
7464static void
7465mcl_audit_mcheck_panic(struct mbuf *m)
7466{
7467 mcache_audit_t *mca;
7468
7469 MRANGE(m);
7470 mca = mcl_audit_buf2mca(MC_MBUF, (mcache_obj_t *)m);
7471
7472 panic("mcl_audit: freed mbuf %p with type 0x%x (instead of 0x%x)\n%s\n",
7473 m, (u_int16_t)m->m_type, MT_FREE, mcache_dump_mca(mca));
7474 /* NOTREACHED */
7475}
7476
7477static void
7478mcl_audit_verify_nextptr(void *next, mcache_audit_t *mca)
7479{
6d2010ae
A
7480 if (next != NULL && !MBUF_IN_MAP(next) &&
7481 (next != (void *)MCACHE_FREE_PATTERN || !mclverify)) {
2d21ac55
A
7482 panic("mcl_audit: buffer %p modified after free at offset 0: "
7483 "%p out of range [%p-%p)\n%s\n",
7484 mca->mca_addr, next, mbutl, embutl, mcache_dump_mca(mca));
7485 /* NOTREACHED */
7486 }
7487}
7488
6d2010ae
A
7489/* This function turns on mbuf leak detection */
7490static void
7491mleak_activate(void)
7492{
7493 mleak_table.mleak_sample_factor = MLEAK_SAMPLE_FACTOR;
7494 PE_parse_boot_argn("mleak_sample_factor",
7495 &mleak_table.mleak_sample_factor,
0a7de745 7496 sizeof(mleak_table.mleak_sample_factor));
6d2010ae 7497
0a7de745 7498 if (mleak_table.mleak_sample_factor == 0) {
6d2010ae 7499 mclfindleak = 0;
0a7de745 7500 }
6d2010ae 7501
0a7de745 7502 if (mclfindleak == 0) {
6d2010ae 7503 return;
0a7de745 7504 }
6d2010ae
A
7505
7506 vm_size_t alloc_size =
0a7de745
A
7507 mleak_alloc_buckets * sizeof(struct mallocation);
7508 vm_size_t trace_size = mleak_trace_buckets * sizeof(struct mtrace);
6d2010ae
A
7509
7510 MALLOC(mleak_allocations, struct mallocation *, alloc_size,
7511 M_TEMP, M_WAITOK | M_ZERO);
7512 VERIFY(mleak_allocations != NULL);
7513
7514 MALLOC(mleak_traces, struct mtrace *, trace_size,
7515 M_TEMP, M_WAITOK | M_ZERO);
7516 VERIFY(mleak_traces != NULL);
7517
7518 MALLOC(mleak_stat, mleak_stat_t *, MLEAK_STAT_SIZE(MLEAK_NUM_TRACES),
7519 M_TEMP, M_WAITOK | M_ZERO);
7520 VERIFY(mleak_stat != NULL);
7521 mleak_stat->ml_cnt = MLEAK_NUM_TRACES;
7522#ifdef __LP64__
7523 mleak_stat->ml_isaddr64 = 1;
7524#endif /* __LP64__ */
7525}
7526
7527static void
7528mleak_logger(u_int32_t num, mcache_obj_t *addr, boolean_t alloc)
7529{
7530 int temp;
7531
0a7de745 7532 if (mclfindleak == 0) {
6d2010ae 7533 return;
0a7de745 7534 }
6d2010ae 7535
0a7de745
A
7536 if (!alloc) {
7537 return mleak_free(addr);
7538 }
6d2010ae
A
7539
7540 temp = atomic_add_32_ov(&mleak_table.mleak_capture, 1);
7541
7542 if ((temp % mleak_table.mleak_sample_factor) == 0 && addr != NULL) {
7543 uintptr_t bt[MLEAK_STACK_DEPTH];
cb323159 7544 int logged = backtrace(bt, MLEAK_STACK_DEPTH, NULL);
6d2010ae
A
7545 mleak_log(bt, addr, logged, num);
7546 }
7547}
7548
7549/*
7550 * This function records the allocation in the mleak_allocations table
7551 * and the backtrace in the mleak_traces table; if allocation slot is in use,
7552 * replace old allocation with new one if the trace slot is in use, return
7553 * (or increment refcount if same trace).
7554 */
7555static boolean_t
7556mleak_log(uintptr_t *bt, mcache_obj_t *addr, uint32_t depth, int num)
7557{
7558 struct mallocation *allocation;
7559 struct mtrace *trace;
7560 uint32_t trace_index;
6d2010ae
A
7561
7562 /* Quit if someone else modifying the tables */
7563 if (!lck_mtx_try_lock_spin(mleak_lock)) {
7564 mleak_table.total_conflicts++;
0a7de745 7565 return FALSE;
6d2010ae
A
7566 }
7567
7568 allocation = &mleak_allocations[hashaddr((uintptr_t)addr,
7569 mleak_alloc_buckets)];
7570 trace_index = hashbacktrace(bt, depth, mleak_trace_buckets);
7571 trace = &mleak_traces[trace_index];
7572
7573 VERIFY(allocation <= &mleak_allocations[mleak_alloc_buckets - 1]);
7574 VERIFY(trace <= &mleak_traces[mleak_trace_buckets - 1]);
7575
7576 allocation->hitcount++;
7577 trace->hitcount++;
7578
7579 /*
7580 * If the allocation bucket we want is occupied
7581 * and the occupier has the same trace, just bail.
7582 */
7583 if (allocation->element != NULL &&
7584 trace_index == allocation->trace_index) {
7585 mleak_table.alloc_collisions++;
7586 lck_mtx_unlock(mleak_lock);
0a7de745 7587 return TRUE;
6d2010ae
A
7588 }
7589
7590 /*
7591 * Store the backtrace in the traces array;
7592 * Size of zero = trace bucket is free.
7593 */
7594 if (trace->allocs > 0 &&
0a7de745 7595 bcmp(trace->addr, bt, (depth * sizeof(uintptr_t))) != 0) {
6d2010ae
A
7596 /* Different, unique trace, but the same hash! Bail out. */
7597 trace->collisions++;
7598 mleak_table.trace_collisions++;
7599 lck_mtx_unlock(mleak_lock);
0a7de745 7600 return TRUE;
6d2010ae
A
7601 } else if (trace->allocs > 0) {
7602 /* Same trace, already added, so increment refcount */
7603 trace->allocs++;
7604 } else {
7605 /* Found an unused trace bucket, so record the trace here */
7606 if (trace->depth != 0) {
7607 /* this slot previously used but not currently in use */
7608 mleak_table.trace_overwrites++;
7609 }
7610 mleak_table.trace_recorded++;
7611 trace->allocs = 1;
0a7de745 7612 memcpy(trace->addr, bt, (depth * sizeof(uintptr_t)));
6d2010ae
A
7613 trace->depth = depth;
7614 trace->collisions = 0;
7615 }
7616
7617 /* Step 2: Store the allocation record in the allocations array */
7618 if (allocation->element != NULL) {
7619 /*
7620 * Replace an existing allocation. No need to preserve
7621 * because only a subset of the allocations are being
7622 * recorded anyway.
7623 */
7624 mleak_table.alloc_collisions++;
7625 } else if (allocation->trace_index != 0) {
7626 mleak_table.alloc_overwrites++;
7627 }
7628 allocation->element = addr;
7629 allocation->trace_index = trace_index;
7630 allocation->count = num;
7631 mleak_table.alloc_recorded++;
7632 mleak_table.outstanding_allocs++;
7633
6d2010ae 7634 lck_mtx_unlock(mleak_lock);
0a7de745 7635 return TRUE;
6d2010ae
A
7636}
7637
7638static void
7639mleak_free(mcache_obj_t *addr)
7640{
7641 while (addr != NULL) {
7642 struct mallocation *allocation = &mleak_allocations
7643 [hashaddr((uintptr_t)addr, mleak_alloc_buckets)];
7644
7645 if (allocation->element == addr &&
7646 allocation->trace_index < mleak_trace_buckets) {
7647 lck_mtx_lock_spin(mleak_lock);
7648 if (allocation->element == addr &&
7649 allocation->trace_index < mleak_trace_buckets) {
7650 struct mtrace *trace;
7651 trace = &mleak_traces[allocation->trace_index];
7652 /* allocs = 0 means trace bucket is unused */
0a7de745 7653 if (trace->allocs > 0) {
6d2010ae 7654 trace->allocs--;
0a7de745
A
7655 }
7656 if (trace->allocs == 0) {
6d2010ae 7657 trace->depth = 0;
0a7de745 7658 }
6d2010ae
A
7659 /* NULL element means alloc bucket is unused */
7660 allocation->element = NULL;
7661 mleak_table.outstanding_allocs--;
7662 }
7663 lck_mtx_unlock(mleak_lock);
7664 }
7665 addr = addr->obj_next;
7666 }
7667}
7668
316670eb
A
7669static void
7670mleak_sort_traces()
7671{
7672 int i, j, k;
7673 struct mtrace *swap;
7674
0a7de745 7675 for (i = 0; i < MLEAK_NUM_TRACES; i++) {
316670eb 7676 mleak_top_trace[i] = NULL;
0a7de745 7677 }
316670eb 7678
0a7de745
A
7679 for (i = 0, j = 0; j < MLEAK_NUM_TRACES && i < mleak_trace_buckets; i++) {
7680 if (mleak_traces[i].allocs <= 0) {
316670eb 7681 continue;
0a7de745 7682 }
316670eb
A
7683
7684 mleak_top_trace[j] = &mleak_traces[i];
7685 for (k = j; k > 0; k--) {
7686 if (mleak_top_trace[k]->allocs <=
0a7de745 7687 mleak_top_trace[k - 1]->allocs) {
316670eb 7688 break;
0a7de745 7689 }
316670eb 7690
0a7de745
A
7691 swap = mleak_top_trace[k - 1];
7692 mleak_top_trace[k - 1] = mleak_top_trace[k];
316670eb
A
7693 mleak_top_trace[k] = swap;
7694 }
7695 j++;
7696 }
7697
7698 j--;
0a7de745
A
7699 for (; i < mleak_trace_buckets; i++) {
7700 if (mleak_traces[i].allocs <= mleak_top_trace[j]->allocs) {
316670eb 7701 continue;
0a7de745 7702 }
316670eb
A
7703
7704 mleak_top_trace[j] = &mleak_traces[i];
7705
7706 for (k = j; k > 0; k--) {
7707 if (mleak_top_trace[k]->allocs <=
0a7de745 7708 mleak_top_trace[k - 1]->allocs) {
316670eb 7709 break;
0a7de745 7710 }
316670eb 7711
0a7de745
A
7712 swap = mleak_top_trace[k - 1];
7713 mleak_top_trace[k - 1] = mleak_top_trace[k];
316670eb
A
7714 mleak_top_trace[k] = swap;
7715 }
7716 }
7717}
7718
7719static void
7720mleak_update_stats()
7721{
7722 mleak_trace_stat_t *mltr;
7723 int i;
7724
7725 VERIFY(mleak_stat != NULL);
7726#ifdef __LP64__
7727 VERIFY(mleak_stat->ml_isaddr64);
7728#else
7729 VERIFY(!mleak_stat->ml_isaddr64);
7730#endif /* !__LP64__ */
7731 VERIFY(mleak_stat->ml_cnt == MLEAK_NUM_TRACES);
7732
7733 mleak_sort_traces();
7734
7735 mltr = &mleak_stat->ml_trace[0];
0a7de745 7736 bzero(mltr, sizeof(*mltr) * MLEAK_NUM_TRACES);
316670eb 7737 for (i = 0; i < MLEAK_NUM_TRACES; i++) {
5c9f4661 7738 int j;
316670eb
A
7739
7740 if (mleak_top_trace[i] == NULL ||
0a7de745 7741 mleak_top_trace[i]->allocs == 0) {
316670eb 7742 continue;
0a7de745 7743 }
316670eb 7744
0a7de745
A
7745 mltr->mltr_collisions = mleak_top_trace[i]->collisions;
7746 mltr->mltr_hitcount = mleak_top_trace[i]->hitcount;
7747 mltr->mltr_allocs = mleak_top_trace[i]->allocs;
7748 mltr->mltr_depth = mleak_top_trace[i]->depth;
316670eb
A
7749
7750 VERIFY(mltr->mltr_depth <= MLEAK_STACK_DEPTH);
0a7de745 7751 for (j = 0; j < mltr->mltr_depth; j++) {
316670eb 7752 mltr->mltr_addr[j] = mleak_top_trace[i]->addr[j];
0a7de745 7753 }
316670eb
A
7754
7755 mltr++;
7756 }
7757}
7758
6d2010ae 7759static struct mbtypes {
0a7de745
A
7760 int mt_type;
7761 const char *mt_name;
6d2010ae 7762} mbtypes[] = {
0a7de745
A
7763 { MT_DATA, "data" },
7764 { MT_OOBDATA, "oob data" },
7765 { MT_CONTROL, "ancillary data" },
7766 { MT_HEADER, "packet headers" },
7767 { MT_SOCKET, "socket structures" },
7768 { MT_PCB, "protocol control blocks" },
7769 { MT_RTABLE, "routing table entries" },
7770 { MT_HTABLE, "IMP host table entries" },
7771 { MT_ATABLE, "address resolution tables" },
7772 { MT_FTABLE, "fragment reassembly queue headers" },
7773 { MT_SONAME, "socket names and addresses" },
7774 { MT_SOOPTS, "socket options" },
7775 { MT_RIGHTS, "access rights" },
7776 { MT_IFADDR, "interface addresses" },
7777 { MT_TAG, "packet tags" },
7778 { 0, NULL }
6d2010ae
A
7779};
7780
0a7de745
A
7781#define MBUF_DUMP_BUF_CHK() { \
7782 clen -= k; \
7783 if (clen < 1) \
7784 goto done; \
7785 c += k; \
6d2010ae
A
7786}
7787
7788static char *
7789mbuf_dump(void)
7790{
cc8bc92a
A
7791 unsigned long totmem = 0, totfree = 0, totmbufs, totused, totpct,
7792 totreturned = 0;
6d2010ae
A
7793 u_int32_t m_mbufs = 0, m_clfree = 0, m_bigclfree = 0;
7794 u_int32_t m_mbufclfree = 0, m_mbufbigclfree = 0;
7795 u_int32_t m_16kclusters = 0, m_16kclfree = 0, m_mbuf16kclfree = 0;
0a7de745 7796 int nmbtypes = sizeof(mbstat.m_mtypes) / sizeof(short);
6d2010ae
A
7797 uint8_t seen[256];
7798 struct mbtypes *mp;
7799 mb_class_stat_t *sp;
316670eb 7800 mleak_trace_stat_t *mltr;
6d2010ae 7801 char *c = mbuf_dump_buf;
5c9f4661 7802 int i, j, k, clen = MBUF_DUMP_BUF_SIZE;
d9a64523 7803 bool printed_banner = false;
6d2010ae
A
7804
7805 mbuf_dump_buf[0] = '\0';
7806
7807 /* synchronize all statistics in the mbuf table */
7808 mbuf_stat_sync();
7809 mbuf_mtypes_sync(TRUE);
7810
7811 sp = &mb_stat->mbs_class[0];
7812 for (i = 0; i < mb_stat->mbs_cnt; i++, sp++) {
7813 u_int32_t mem;
7814
7815 if (m_class(i) == MC_MBUF) {
7816 m_mbufs = sp->mbcl_active;
7817 } else if (m_class(i) == MC_CL) {
7818 m_clfree = sp->mbcl_total - sp->mbcl_active;
7819 } else if (m_class(i) == MC_BIGCL) {
7820 m_bigclfree = sp->mbcl_total - sp->mbcl_active;
7821 } else if (njcl > 0 && m_class(i) == MC_16KCL) {
7822 m_16kclfree = sp->mbcl_total - sp->mbcl_active;
7823 m_16kclusters = sp->mbcl_total;
7824 } else if (m_class(i) == MC_MBUF_CL) {
7825 m_mbufclfree = sp->mbcl_total - sp->mbcl_active;
7826 } else if (m_class(i) == MC_MBUF_BIGCL) {
7827 m_mbufbigclfree = sp->mbcl_total - sp->mbcl_active;
7828 } else if (njcl > 0 && m_class(i) == MC_MBUF_16KCL) {
7829 m_mbuf16kclfree = sp->mbcl_total - sp->mbcl_active;
7830 }
7831
7832 mem = sp->mbcl_ctotal * sp->mbcl_size;
7833 totmem += mem;
7834 totfree += (sp->mbcl_mc_cached + sp->mbcl_infree) *
7835 sp->mbcl_size;
cc8bc92a 7836 totreturned += sp->mbcl_release_cnt;
6d2010ae
A
7837 }
7838
7839 /* adjust free counts to include composite caches */
7840 m_clfree += m_mbufclfree;
7841 m_bigclfree += m_mbufbigclfree;
7842 m_16kclfree += m_mbuf16kclfree;
7843
7844 totmbufs = 0;
0a7de745 7845 for (mp = mbtypes; mp->mt_name != NULL; mp++) {
6d2010ae 7846 totmbufs += mbstat.m_mtypes[mp->mt_type];
0a7de745
A
7847 }
7848 if (totmbufs > m_mbufs) {
6d2010ae 7849 totmbufs = m_mbufs;
0a7de745 7850 }
6d2010ae
A
7851 k = snprintf(c, clen, "%lu/%u mbufs in use:\n", totmbufs, m_mbufs);
7852 MBUF_DUMP_BUF_CHK();
7853
0a7de745 7854 bzero(&seen, sizeof(seen));
6d2010ae
A
7855 for (mp = mbtypes; mp->mt_name != NULL; mp++) {
7856 if (mbstat.m_mtypes[mp->mt_type] != 0) {
7857 seen[mp->mt_type] = 1;
7858 k = snprintf(c, clen, "\t%u mbufs allocated to %s\n",
7859 mbstat.m_mtypes[mp->mt_type], mp->mt_name);
7860 MBUF_DUMP_BUF_CHK();
7861 }
7862 }
7863 seen[MT_FREE] = 1;
0a7de745 7864 for (i = 0; i < nmbtypes; i++) {
6d2010ae
A
7865 if (!seen[i] && mbstat.m_mtypes[i] != 0) {
7866 k = snprintf(c, clen, "\t%u mbufs allocated to "
7867 "<mbuf type %d>\n", mbstat.m_mtypes[i], i);
7868 MBUF_DUMP_BUF_CHK();
7869 }
0a7de745 7870 }
6d2010ae
A
7871 if ((m_mbufs - totmbufs) > 0) {
7872 k = snprintf(c, clen, "\t%lu mbufs allocated to caches\n",
7873 m_mbufs - totmbufs);
7874 MBUF_DUMP_BUF_CHK();
7875 }
7876 k = snprintf(c, clen, "%u/%u mbuf 2KB clusters in use\n"
7877 "%u/%u mbuf 4KB clusters in use\n",
7878 (unsigned int)(mbstat.m_clusters - m_clfree),
7879 (unsigned int)mbstat.m_clusters,
7880 (unsigned int)(mbstat.m_bigclusters - m_bigclfree),
7881 (unsigned int)mbstat.m_bigclusters);
7882 MBUF_DUMP_BUF_CHK();
7883
7884 if (njcl > 0) {
7885 k = snprintf(c, clen, "%u/%u mbuf %uKB clusters in use\n",
7886 m_16kclusters - m_16kclfree, m_16kclusters,
7887 njclbytes / 1024);
7888 MBUF_DUMP_BUF_CHK();
7889 }
7890 totused = totmem - totfree;
7891 if (totmem == 0) {
7892 totpct = 0;
7893 } else if (totused < (ULONG_MAX / 100)) {
7894 totpct = (totused * 100) / totmem;
7895 } else {
7896 u_long totmem1 = totmem / 100;
7897 u_long totused1 = totused / 100;
7898 totpct = (totused1 * 100) / totmem1;
7899 }
7900 k = snprintf(c, clen, "%lu KB allocated to network (approx. %lu%% "
7901 "in use)\n", totmem / 1024, totpct);
7902 MBUF_DUMP_BUF_CHK();
cc8bc92a
A
7903 k = snprintf(c, clen, "%lu KB returned to the system\n",
7904 totreturned / 1024);
7905 MBUF_DUMP_BUF_CHK();
7906
7907 net_update_uptime();
7908 k = snprintf(c, clen,
7909 "VM allocation failures: contiguous %u, normal %u, one page %u\n",
7910 mb_kmem_contig_failed, mb_kmem_failed, mb_kmem_one_failed);
7911 MBUF_DUMP_BUF_CHK();
7912 if (mb_kmem_contig_failed_ts || mb_kmem_failed_ts ||
7913 mb_kmem_one_failed_ts) {
7914 k = snprintf(c, clen,
7915 "VM allocation failure timestamps: contiguous %llu "
7916 "(size %llu), normal %llu (size %llu), one page %llu "
7917 "(now %llu)\n",
7918 mb_kmem_contig_failed_ts, mb_kmem_contig_failed_size,
7919 mb_kmem_failed_ts, mb_kmem_failed_size,
7920 mb_kmem_one_failed_ts, net_uptime());
7921 MBUF_DUMP_BUF_CHK();
7922 k = snprintf(c, clen,
7923 "VM return codes: ");
7924 MBUF_DUMP_BUF_CHK();
7925 for (i = 0;
0a7de745
A
7926 i < sizeof(mb_kmem_stats) / sizeof(mb_kmem_stats[0]);
7927 i++) {
cc8bc92a
A
7928 k = snprintf(c, clen, "%s: %u ", mb_kmem_stats_labels[i],
7929 mb_kmem_stats[i]);
7930 MBUF_DUMP_BUF_CHK();
7931 }
7932 k = snprintf(c, clen, "\n");
7933 MBUF_DUMP_BUF_CHK();
7934 }
7935 k = snprintf(c, clen,
7936 "worker thread runs: %u, expansions: %llu, cl %llu/%llu, "
7937 "bigcl %llu/%llu, 16k %llu/%llu\n", mbuf_worker_run_cnt,
7938 mb_expand_cnt, mb_expand_cl_cnt, mb_expand_cl_total,
7939 mb_expand_bigcl_cnt, mb_expand_bigcl_total, mb_expand_16kcl_cnt,
7940 mb_expand_16kcl_total);
7941 MBUF_DUMP_BUF_CHK();
7942 if (mbuf_worker_last_runtime != 0) {
7943 k = snprintf(c, clen, "worker thread last run time: "
7944 "%llu (%llu seconds ago)\n",
7945 mbuf_worker_last_runtime,
7946 net_uptime() - mbuf_worker_last_runtime);
7947 MBUF_DUMP_BUF_CHK();
7948 }
d9a64523
A
7949 if (mbuf_drain_last_runtime != 0) {
7950 k = snprintf(c, clen, "drain routine last run time: "
7951 "%llu (%llu seconds ago)\n",
7952 mbuf_drain_last_runtime,
7953 net_uptime() - mbuf_drain_last_runtime);
7954 MBUF_DUMP_BUF_CHK();
7955 }
6d2010ae 7956
d9a64523
A
7957#if DEBUG || DEVELOPMENT
7958 k = snprintf(c, clen, "\nworker thread log:\n%s\n", mbwdog_logging);
5c9f4661 7959 MBUF_DUMP_BUF_CHK();
d9a64523 7960#endif
5c9f4661
A
7961
7962 for (j = 0; j < MTRACELARGE_NUM_TRACES; j++) {
7963 struct mtracelarge *trace = &mtracelarge_table[j];
0a7de745 7964 if (trace->size == 0 || trace->depth == 0) {
5c9f4661 7965 continue;
0a7de745 7966 }
d9a64523
A
7967 if (printed_banner == false) {
7968 k = snprintf(c, clen,
7969 "\nlargest allocation failure backtraces:\n");
7970 MBUF_DUMP_BUF_CHK();
7971 printed_banner = true;
7972 }
5c9f4661
A
7973 k = snprintf(c, clen, "size %llu: < ", trace->size);
7974 MBUF_DUMP_BUF_CHK();
7975 for (i = 0; i < trace->depth; i++) {
7976 if (mleak_stat->ml_isaddr64) {
7977 k = snprintf(c, clen, "0x%0llx ",
7978 (uint64_t)VM_KERNEL_UNSLIDE(
7979 trace->addr[i]));
7980 } else {
7981 k = snprintf(c, clen,
7982 "0x%08x ",
7983 (uint32_t)VM_KERNEL_UNSLIDE(
7984 trace->addr[i]));
7985 }
7986 MBUF_DUMP_BUF_CHK();
7987 }
7988 k = snprintf(c, clen, ">\n");
7989 MBUF_DUMP_BUF_CHK();
7990 }
7991
316670eb
A
7992 /* mbuf leak detection statistics */
7993 mleak_update_stats();
7994
7995 k = snprintf(c, clen, "\nmbuf leak detection table:\n");
7996 MBUF_DUMP_BUF_CHK();
7997 k = snprintf(c, clen, "\ttotal captured: %u (one per %u)\n",
7998 mleak_table.mleak_capture / mleak_table.mleak_sample_factor,
7999 mleak_table.mleak_sample_factor);
8000 MBUF_DUMP_BUF_CHK();
8001 k = snprintf(c, clen, "\ttotal allocs outstanding: %llu\n",
8002 mleak_table.outstanding_allocs);
8003 MBUF_DUMP_BUF_CHK();
8004 k = snprintf(c, clen, "\tnew hash recorded: %llu allocs, %llu traces\n",
8005 mleak_table.alloc_recorded, mleak_table.trace_recorded);
8006 MBUF_DUMP_BUF_CHK();
8007 k = snprintf(c, clen, "\thash collisions: %llu allocs, %llu traces\n",
8008 mleak_table.alloc_collisions, mleak_table.trace_collisions);
8009 MBUF_DUMP_BUF_CHK();
8010 k = snprintf(c, clen, "\toverwrites: %llu allocs, %llu traces\n",
8011 mleak_table.alloc_overwrites, mleak_table.trace_overwrites);
8012 MBUF_DUMP_BUF_CHK();
8013 k = snprintf(c, clen, "\tlock conflicts: %llu\n\n",
8014 mleak_table.total_conflicts);
8015 MBUF_DUMP_BUF_CHK();
8016
8017 k = snprintf(c, clen, "top %d outstanding traces:\n",
8018 mleak_stat->ml_cnt);
8019 MBUF_DUMP_BUF_CHK();
8020 for (i = 0; i < mleak_stat->ml_cnt; i++) {
8021 mltr = &mleak_stat->ml_trace[i];
8022 k = snprintf(c, clen, "[%d] %llu outstanding alloc(s), "
8023 "%llu hit(s), %llu collision(s)\n", (i + 1),
8024 mltr->mltr_allocs, mltr->mltr_hitcount,
8025 mltr->mltr_collisions);
8026 MBUF_DUMP_BUF_CHK();
8027 }
8028
0a7de745 8029 if (mleak_stat->ml_isaddr64) {
316670eb 8030 k = snprintf(c, clen, MB_LEAK_HDR_64);
0a7de745 8031 } else {
316670eb 8032 k = snprintf(c, clen, MB_LEAK_HDR_32);
0a7de745 8033 }
316670eb
A
8034 MBUF_DUMP_BUF_CHK();
8035
8036 for (i = 0; i < MLEAK_STACK_DEPTH; i++) {
316670eb
A
8037 k = snprintf(c, clen, "%2d: ", (i + 1));
8038 MBUF_DUMP_BUF_CHK();
8039 for (j = 0; j < mleak_stat->ml_cnt; j++) {
8040 mltr = &mleak_stat->ml_trace[j];
8041 if (i < mltr->mltr_depth) {
8042 if (mleak_stat->ml_isaddr64) {
8043 k = snprintf(c, clen, "0x%0llx ",
fe8ab488 8044 (uint64_t)VM_KERNEL_UNSLIDE(
0a7de745 8045 mltr->mltr_addr[i]));
316670eb
A
8046 } else {
8047 k = snprintf(c, clen,
8048 "0x%08x ",
fe8ab488 8049 (uint32_t)VM_KERNEL_UNSLIDE(
0a7de745 8050 mltr->mltr_addr[i]));
316670eb
A
8051 }
8052 } else {
0a7de745 8053 if (mleak_stat->ml_isaddr64) {
316670eb
A
8054 k = snprintf(c, clen,
8055 MB_LEAK_SPACING_64);
0a7de745 8056 } else {
316670eb
A
8057 k = snprintf(c, clen,
8058 MB_LEAK_SPACING_32);
0a7de745 8059 }
316670eb
A
8060 }
8061 MBUF_DUMP_BUF_CHK();
8062 }
8063 k = snprintf(c, clen, "\n");
8064 MBUF_DUMP_BUF_CHK();
8065 }
6d2010ae 8066done:
0a7de745 8067 return mbuf_dump_buf;
6d2010ae
A
8068}
8069
8070#undef MBUF_DUMP_BUF_CHK
8071
39236c6e
A
8072/*
8073 * Convert between a regular and a packet header mbuf. Caller is responsible
8074 * for setting or clearing M_PKTHDR; this routine does the rest of the work.
8075 */
8076int
8077m_reinit(struct mbuf *m, int hdr)
8078{
8079 int ret = 0;
8080
8081 if (hdr) {
8082 VERIFY(!(m->m_flags & M_PKTHDR));
8083 if (!(m->m_flags & M_EXT) &&
8084 (m->m_data != m->m_dat || m->m_len > 0)) {
8085 /*
8086 * If there's no external cluster attached and the
8087 * mbuf appears to contain user data, we cannot
8088 * safely convert this to a packet header mbuf,
8089 * as the packet header structure might overlap
8090 * with the data.
8091 */
fe8ab488
A
8092 printf("%s: cannot set M_PKTHDR on altered mbuf %llx, "
8093 "m_data %llx (expected %llx), "
8094 "m_len %d (expected 0)\n",
8095 __func__,
8096 (uint64_t)VM_KERNEL_ADDRPERM(m),
8097 (uint64_t)VM_KERNEL_ADDRPERM(m->m_data),
8098 (uint64_t)VM_KERNEL_ADDRPERM(m->m_dat), m->m_len);
39236c6e
A
8099 ret = EBUSY;
8100 } else {
8101 VERIFY((m->m_flags & M_EXT) || m->m_data == m->m_dat);
8102 m->m_flags |= M_PKTHDR;
8103 MBUF_INIT_PKTHDR(m);
8104 }
8105 } else {
8106 /* Check for scratch area overflow */
8107 m_redzone_verify(m);
8108 /* Free the aux data and tags if there is any */
8109 m_tag_delete_chain(m, NULL);
8110 m->m_flags &= ~M_PKTHDR;
8111 }
8112
0a7de745 8113 return ret;
39236c6e
A
8114}
8115
39037602
A
8116int
8117m_ext_set_prop(struct mbuf *m, uint32_t o, uint32_t n)
8118{
8119 ASSERT(m->m_flags & M_EXT);
0a7de745 8120 return atomic_test_set_32(&MEXT_PRIV(m), o, n);
39037602
A
8121}
8122
8123uint32_t
8124m_ext_get_prop(struct mbuf *m)
8125{
8126 ASSERT(m->m_flags & M_EXT);
0a7de745 8127 return MEXT_PRIV(m);
39037602
A
8128}
8129
8130int
8131m_ext_paired_is_active(struct mbuf *m)
8132{
0a7de745 8133 return MBUF_IS_PAIRED(m) ? (MEXT_PREF(m) > MEXT_MINREF(m)) : 1;
39037602
A
8134}
8135
8136void
8137m_ext_paired_activate(struct mbuf *m)
8138{
8139 struct ext_ref *rfa;
8140 int hdr, type;
8141 caddr_t extbuf;
813fb2f6 8142 m_ext_free_func_t extfree;
39037602
A
8143 u_int extsize;
8144
8145 VERIFY(MBUF_IS_PAIRED(m));
8146 VERIFY(MEXT_REF(m) == MEXT_MINREF(m));
8147 VERIFY(MEXT_PREF(m) == MEXT_MINREF(m));
8148
8149 hdr = (m->m_flags & M_PKTHDR);
8150 type = m->m_type;
8151 extbuf = m->m_ext.ext_buf;
813fb2f6 8152 extfree = m_get_ext_free(m);
39037602 8153 extsize = m->m_ext.ext_size;
813fb2f6 8154 rfa = m_get_rfa(m);
39037602
A
8155
8156 VERIFY(extbuf != NULL && rfa != NULL);
8157
8158 /*
8159 * Safe to reinitialize packet header tags, since it's
8160 * already taken care of at m_free() time. Similar to
8161 * what's done in m_clattach() for the cluster. Bump
8162 * up MEXT_PREF to indicate activation.
8163 */
8164 MBUF_INIT(m, hdr, type);
8165 MEXT_INIT(m, extbuf, extsize, extfree, (caddr_t)m, rfa,
8166 1, 1, 2, EXTF_PAIRED, MEXT_PRIV(m), m);
8167}
8168
39236c6e
A
8169void
8170m_scratch_init(struct mbuf *m)
8171{
fe8ab488
A
8172 struct pkthdr *pkt = &m->m_pkthdr;
8173
39236c6e
A
8174 VERIFY(m->m_flags & M_PKTHDR);
8175
fe8ab488
A
8176 /* See comments in <rdar://problem/14040693> */
8177 if (pkt->pkt_flags & PKTF_PRIV_GUARDED) {
8178 panic_plain("Invalid attempt to modify guarded module-private "
8179 "area: mbuf %p, pkt_flags 0x%x\n", m, pkt->pkt_flags);
8180 /* NOTREACHED */
8181 }
8182
0a7de745 8183 bzero(&pkt->pkt_mpriv, sizeof(pkt->pkt_mpriv));
39236c6e
A
8184}
8185
fe8ab488
A
8186/*
8187 * This routine is reserved for mbuf_get_driver_scratch(); clients inside
8188 * xnu that intend on utilizing the module-private area should directly
8189 * refer to the pkt_mpriv structure in the pkthdr. They are also expected
8190 * to set and clear PKTF_PRIV_GUARDED, while owning the packet and prior
8191 * to handing it off to another module, respectively.
8192 */
39236c6e
A
8193u_int32_t
8194m_scratch_get(struct mbuf *m, u_int8_t **p)
8195{
fe8ab488
A
8196 struct pkthdr *pkt = &m->m_pkthdr;
8197
39236c6e
A
8198 VERIFY(m->m_flags & M_PKTHDR);
8199
fe8ab488
A
8200 /* See comments in <rdar://problem/14040693> */
8201 if (pkt->pkt_flags & PKTF_PRIV_GUARDED) {
8202 panic_plain("Invalid attempt to access guarded module-private "
8203 "area: mbuf %p, pkt_flags 0x%x\n", m, pkt->pkt_flags);
8204 /* NOTREACHED */
8205 }
8206
39236c6e
A
8207 if (mcltrace) {
8208 mcache_audit_t *mca;
8209
8210 lck_mtx_lock(mbuf_mlock);
8211 mca = mcl_audit_buf2mca(MC_MBUF, (mcache_obj_t *)m);
0a7de745 8212 if (mca->mca_uflags & MB_SCVALID) {
39236c6e 8213 mcl_audit_scratch(mca);
0a7de745 8214 }
39236c6e
A
8215 lck_mtx_unlock(mbuf_mlock);
8216 }
8217
fe8ab488 8218 *p = (u_int8_t *)&pkt->pkt_mpriv;
0a7de745 8219 return sizeof(pkt->pkt_mpriv);
39236c6e
A
8220}
8221
8222static void
8223m_redzone_init(struct mbuf *m)
8224{
8225 VERIFY(m->m_flags & M_PKTHDR);
8226 /*
8227 * Each mbuf has a unique red zone pattern, which is a XOR
8228 * of the red zone cookie and the address of the mbuf.
8229 */
8230 m->m_pkthdr.redzone = ((u_int32_t)(uintptr_t)m) ^ mb_redzone_cookie;
8231}
8232
8233static void
8234m_redzone_verify(struct mbuf *m)
8235{
8236 u_int32_t mb_redzone;
8237
8238 VERIFY(m->m_flags & M_PKTHDR);
8239
8240 mb_redzone = ((u_int32_t)(uintptr_t)m) ^ mb_redzone_cookie;
8241 if (m->m_pkthdr.redzone != mb_redzone) {
8242 panic("mbuf %p redzone violation with value 0x%x "
8243 "(instead of 0x%x, using cookie 0x%x)\n",
8244 m, m->m_pkthdr.redzone, mb_redzone, mb_redzone_cookie);
8245 /* NOTREACHED */
8246 }
8247}
8248
813fb2f6
A
8249__private_extern__ inline void
8250m_set_ext(struct mbuf *m, struct ext_ref *rfa, m_ext_free_func_t ext_free,
8251 caddr_t ext_arg)
8252{
8253 VERIFY(m->m_flags & M_EXT);
8254 if (rfa != NULL) {
8255 m->m_ext.ext_refflags =
8256 (struct ext_ref *)(((uintptr_t)rfa) ^ mb_obscure_extref);
8257 if (ext_free != NULL) {
8258 rfa->ext_token = ((uintptr_t)&rfa->ext_token) ^
8259 mb_obscure_extfree;
8260 m->m_ext.ext_free = (m_ext_free_func_t)
8261 (((uintptr_t)ext_free) ^ rfa->ext_token);
8262 if (ext_arg != NULL) {
5ba3f43e
A
8263 m->m_ext.ext_arg =
8264 (caddr_t)(((uintptr_t)ext_arg) ^ rfa->ext_token);
813fb2f6
A
8265 } else {
8266 m->m_ext.ext_arg = NULL;
8267 }
8268 } else {
8269 rfa->ext_token = 0;
8270 m->m_ext.ext_free = NULL;
8271 m->m_ext.ext_arg = NULL;
8272 }
8273 } else {
8274 /*
8275 * If we are going to loose the cookie in ext_token by
8276 * resetting the rfa, we should use the global cookie
8277 * to obscure the ext_free and ext_arg pointers.
8278 */
8279 if (ext_free != NULL) {
5ba3f43e
A
8280 m->m_ext.ext_free =
8281 (m_ext_free_func_t)((uintptr_t)ext_free ^
813fb2f6
A
8282 mb_obscure_extfree);
8283 if (ext_arg != NULL) {
5ba3f43e
A
8284 m->m_ext.ext_arg =
8285 (caddr_t)((uintptr_t)ext_arg ^
813fb2f6
A
8286 mb_obscure_extfree);
8287 } else {
8288 m->m_ext.ext_arg = NULL;
8289 }
8290 } else {
8291 m->m_ext.ext_free = NULL;
8292 m->m_ext.ext_arg = NULL;
8293 }
8294 m->m_ext.ext_refflags = NULL;
8295 }
8296}
8297
8298__private_extern__ inline struct ext_ref *
8299m_get_rfa(struct mbuf *m)
8300{
0a7de745
A
8301 if (m->m_ext.ext_refflags == NULL) {
8302 return NULL;
8303 } else {
8304 return (struct ext_ref *)(((uintptr_t)m->m_ext.ext_refflags) ^ mb_obscure_extref);
8305 }
813fb2f6
A
8306}
8307
8308__private_extern__ inline m_ext_free_func_t
8309m_get_ext_free(struct mbuf *m)
8310{
8311 struct ext_ref *rfa;
0a7de745
A
8312 if (m->m_ext.ext_free == NULL) {
8313 return NULL;
8314 }
813fb2f6
A
8315
8316 rfa = m_get_rfa(m);
0a7de745
A
8317 if (rfa == NULL) {
8318 return (m_ext_free_func_t)((uintptr_t)m->m_ext.ext_free ^ mb_obscure_extfree);
8319 } else {
8320 return (m_ext_free_func_t)(((uintptr_t)m->m_ext.ext_free)
8321 ^ rfa->ext_token);
8322 }
813fb2f6
A
8323}
8324
8325__private_extern__ inline caddr_t
8326m_get_ext_arg(struct mbuf *m)
8327{
8328 struct ext_ref *rfa;
0a7de745
A
8329 if (m->m_ext.ext_arg == NULL) {
8330 return NULL;
8331 }
813fb2f6
A
8332
8333 rfa = m_get_rfa(m);
8334 if (rfa == NULL) {
0a7de745 8335 return (caddr_t)((uintptr_t)m->m_ext.ext_arg ^ mb_obscure_extfree);
813fb2f6 8336 } else {
0a7de745
A
8337 return (caddr_t)(((uintptr_t)m->m_ext.ext_arg) ^
8338 rfa->ext_token);
813fb2f6
A
8339 }
8340}
8341
fe8ab488
A
8342/*
8343 * Send a report of mbuf usage if the usage is at least 6% of max limit
8344 * or if there has been at least 3% increase since the last report.
8345 *
8346 * The values 6% and 3% are chosen so that we can do simple arithmetic
8347 * with shift operations.
39037602 8348 */
fe8ab488
A
8349static boolean_t
8350mbuf_report_usage(mbuf_class_t cl)
8351{
8352 /* if a report is already in progress, nothing to do */
0a7de745
A
8353 if (mb_peak_newreport) {
8354 return TRUE;
8355 }
fe8ab488
A
8356
8357 if (m_total(cl) > m_peak(cl) &&
8358 m_total(cl) >= (m_maxlimit(cl) >> 4) &&
0a7de745
A
8359 (m_total(cl) - m_peak(cl)) >= (m_peak(cl) >> 5)) {
8360 return TRUE;
8361 }
8362 return FALSE;
fe8ab488
A
8363}
8364
8365__private_extern__ void
8366mbuf_report_peak_usage(void)
8367{
39037602 8368 int i = 0;
fe8ab488
A
8369 u_int64_t uptime;
8370 struct nstat_sysinfo_data ns_data;
8371 uint32_t memreleased = 0;
cc8bc92a 8372 static uint32_t prevmemreleased;
fe8ab488
A
8373
8374 uptime = net_uptime();
8375 lck_mtx_lock(mbuf_mlock);
8376
8377 /* Generate an initial report after 1 week of uptime */
39037602 8378 if (!mb_peak_firstreport &&
fe8ab488
A
8379 uptime > MBUF_PEAK_FIRST_REPORT_THRESHOLD) {
8380 mb_peak_newreport = TRUE;
8381 mb_peak_firstreport = TRUE;
8382 }
8383
8384 if (!mb_peak_newreport) {
8385 lck_mtx_unlock(mbuf_mlock);
8386 return;
8387 }
8388
8389 /*
39037602 8390 * Since a report is being generated before 1 week,
fe8ab488
A
8391 * we do not need to force another one later
8392 */
0a7de745 8393 if (uptime < MBUF_PEAK_FIRST_REPORT_THRESHOLD) {
fe8ab488 8394 mb_peak_firstreport = TRUE;
0a7de745 8395 }
fe8ab488
A
8396
8397 for (i = 0; i < NELEM(mbuf_table); i++) {
8398 m_peak(m_class(i)) = m_total(m_class(i));
8399 memreleased += m_release_cnt(i);
8400 }
cc8bc92a
A
8401 memreleased = memreleased - prevmemreleased;
8402 prevmemreleased = memreleased;
fe8ab488
A
8403 mb_peak_newreport = FALSE;
8404 lck_mtx_unlock(mbuf_mlock);
8405
8406 bzero(&ns_data, sizeof(ns_data));
8407 ns_data.flags = NSTAT_SYSINFO_MBUF_STATS;
8408 ns_data.u.mb_stats.total_256b = m_peak(MC_MBUF);
8409 ns_data.u.mb_stats.total_2kb = m_peak(MC_CL);
8410 ns_data.u.mb_stats.total_4kb = m_peak(MC_BIGCL);
3e170ce0 8411 ns_data.u.mb_stats.total_16kb = m_peak(MC_16KCL);
fe8ab488
A
8412 ns_data.u.mb_stats.sbmb_total = total_sbmb_cnt_peak;
8413 ns_data.u.mb_stats.sb_atmbuflimit = sbmb_limreached;
8414 ns_data.u.mb_stats.draincnt = mbstat.m_drain;
8415 ns_data.u.mb_stats.memreleased = memreleased;
39037602 8416 ns_data.u.mb_stats.sbmb_floor = total_sbmb_cnt_floor;
fe8ab488
A
8417
8418 nstat_sysinfo_send_data(&ns_data);
39037602
A
8419
8420 /*
8421 * Reset the floor whenever we report a new
8422 * peak to track the trend (increase peek usage
8423 * is not a leak if mbufs get released
8424 * between reports and the floor stays low)
8425 */
8426 total_sbmb_cnt_floor = total_sbmb_cnt_peak;
fe8ab488
A
8427}
8428
8429/*
d9a64523
A
8430 * Simple routine to avoid taking the lock when we can't run the
8431 * mbuf drain.
fe8ab488 8432 */
d9a64523
A
8433static int
8434mbuf_drain_checks(boolean_t ignore_waiters)
8435{
0a7de745 8436 if (mb_drain_maxint == 0) {
d9a64523 8437 return 0;
0a7de745
A
8438 }
8439 if (!ignore_waiters && mb_waiters != 0) {
d9a64523 8440 return 0;
0a7de745 8441 }
d9a64523
A
8442
8443 return 1;
8444}
8445
8446/*
8447 * Called by the VM when there's memory pressure or when we exhausted
8448 * the 4k/16k reserved space.
8449 */
8450static void
8451mbuf_drain_locked(boolean_t ignore_waiters)
fe8ab488
A
8452{
8453 mbuf_class_t mc;
8454 mcl_slab_t *sp, *sp_tmp, *nsp;
8455 unsigned int num, k, interval, released = 0;
39037602 8456 unsigned long total_mem = 0, use_mem = 0;
fe8ab488
A
8457 boolean_t ret, purge_caches = FALSE;
8458 ppnum_t offset;
8459 mcache_obj_t *obj;
39037602 8460 unsigned long per;
fe8ab488
A
8461 static unsigned char scratch[32];
8462 static ppnum_t scratch_pa = 0;
8463
d9a64523 8464 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
0a7de745 8465 if (!mbuf_drain_checks(ignore_waiters)) {
fe8ab488 8466 return;
0a7de745 8467 }
fe8ab488
A
8468 if (scratch_pa == 0) {
8469 bzero(scratch, sizeof(scratch));
8470 scratch_pa = pmap_find_phys(kernel_pmap, (addr64_t)scratch);
8471 VERIFY(scratch_pa);
8472 } else if (mclverify) {
8473 /*
8474 * Panic if a driver wrote to our scratch memory.
8475 */
0a7de745
A
8476 for (k = 0; k < sizeof(scratch); k++) {
8477 if (scratch[k]) {
fe8ab488 8478 panic("suspect DMA to freed address");
0a7de745
A
8479 }
8480 }
fe8ab488
A
8481 }
8482 /*
8483 * Don't free memory too often as that could cause excessive
8484 * waiting times for mbufs. Purge caches if we were asked to drain
8485 * in the last 5 minutes.
8486 */
d9a64523
A
8487 if (mbuf_drain_last_runtime != 0) {
8488 interval = net_uptime() - mbuf_drain_last_runtime;
8489 if (interval <= mb_drain_maxint) {
8490 return;
8491 }
0a7de745 8492 if (interval <= mb_drain_maxint * 5) {
d9a64523 8493 purge_caches = TRUE;
0a7de745 8494 }
39037602 8495 }
d9a64523 8496 mbuf_drain_last_runtime = net_uptime();
fe8ab488
A
8497 /*
8498 * Don't free any memory if we're using 60% or more.
8499 */
8500 for (mc = 0; mc < NELEM(mbuf_table); mc++) {
8501 total_mem += m_total(mc) * m_maxsize(mc);
8502 use_mem += m_active(mc) * m_maxsize(mc);
8503 }
39037602
A
8504 per = (use_mem * 100) / total_mem;
8505 if (per >= 60) {
fe8ab488
A
8506 return;
8507 }
8508 /*
8509 * Purge all the caches. This effectively disables
8510 * caching for a few seconds, but the mbuf worker thread will
8511 * re-enable them again.
8512 */
0a7de745 8513 if (purge_caches == TRUE) {
fe8ab488 8514 for (mc = 0; mc < NELEM(mbuf_table); mc++) {
0a7de745 8515 if (m_total(mc) < m_avgtotal(mc)) {
fe8ab488 8516 continue;
0a7de745 8517 }
fe8ab488
A
8518 lck_mtx_unlock(mbuf_mlock);
8519 ret = mcache_purge_cache(m_cache(mc), FALSE);
8520 lck_mtx_lock(mbuf_mlock);
0a7de745 8521 if (ret == TRUE) {
fe8ab488 8522 m_purge_cnt(mc)++;
0a7de745 8523 }
fe8ab488 8524 }
0a7de745 8525 }
fe8ab488
A
8526 /*
8527 * Move the objects from the composite class freelist to
8528 * the rudimentary slabs list, but keep at least 10% of the average
8529 * total in the freelist.
8530 */
8531 for (mc = 0; mc < NELEM(mbuf_table); mc++) {
39037602 8532 while (m_cobjlist(mc) &&
fe8ab488
A
8533 m_total(mc) < m_avgtotal(mc) &&
8534 m_infree(mc) > 0.1 * m_avgtotal(mc) + m_minlimit(mc)) {
8535 obj = m_cobjlist(mc);
8536 m_cobjlist(mc) = obj->obj_next;
8537 obj->obj_next = NULL;
8538 num = cslab_free(mc, obj, 1);
8539 VERIFY(num == 1);
8540 m_free_cnt(mc)++;
8541 m_infree(mc)--;
8542 /* cslab_free() handles m_total */
8543 }
8544 }
8545 /*
8546 * Free the buffers present in the slab list up to 10% of the total
8547 * average per class.
8548 *
8549 * We walk the list backwards in an attempt to reduce fragmentation.
8550 */
8551 for (mc = NELEM(mbuf_table) - 1; (int)mc >= 0; mc--) {
8552 TAILQ_FOREACH_SAFE(sp, &m_slablist(mc), sl_link, sp_tmp) {
8553 /*
8554 * Process only unused slabs occupying memory.
8555 */
8556 if (sp->sl_refcnt != 0 || sp->sl_len == 0 ||
0a7de745 8557 sp->sl_base == NULL) {
fe8ab488 8558 continue;
0a7de745 8559 }
fe8ab488 8560 if (m_total(mc) < m_avgtotal(mc) ||
0a7de745 8561 m_infree(mc) < 0.1 * m_avgtotal(mc) + m_minlimit(mc)) {
fe8ab488 8562 break;
0a7de745 8563 }
fe8ab488
A
8564 slab_remove(sp, mc);
8565 switch (mc) {
8566 case MC_MBUF:
3e170ce0
A
8567 m_infree(mc) -= NMBPG;
8568 m_total(mc) -= NMBPG;
0a7de745 8569 if (mclaudit != NULL) {
3e170ce0 8570 mcl_audit_free(sp->sl_base, NMBPG);
0a7de745 8571 }
fe8ab488
A
8572 break;
8573 case MC_CL:
3e170ce0
A
8574 m_infree(mc) -= NCLPG;
8575 m_total(mc) -= NCLPG;
0a7de745 8576 if (mclaudit != NULL) {
3e170ce0 8577 mcl_audit_free(sp->sl_base, NMBPG);
0a7de745 8578 }
fe8ab488
A
8579 break;
8580 case MC_BIGCL:
3e170ce0
A
8581 {
8582 m_infree(mc) -= NBCLPG;
8583 m_total(mc) -= NBCLPG;
0a7de745 8584 if (mclaudit != NULL) {
3e170ce0 8585 mcl_audit_free(sp->sl_base, NMBPG);
0a7de745 8586 }
fe8ab488 8587 break;
3e170ce0 8588 }
fe8ab488
A
8589 case MC_16KCL:
8590 m_infree(mc)--;
8591 m_total(mc)--;
8592 for (nsp = sp, k = 1; k < NSLABSP16KB; k++) {
8593 nsp = nsp->sl_next;
39037602 8594 VERIFY(nsp->sl_refcnt == 0 &&
fe8ab488
A
8595 nsp->sl_base != NULL &&
8596 nsp->sl_len == 0);
8597 slab_init(nsp, 0, 0, NULL, NULL, 0, 0,
8598 0);
8599 nsp->sl_flags = 0;
8600 }
5ba3f43e
A
8601 if (mclaudit != NULL) {
8602 if (sp->sl_len == PAGE_SIZE) {
8603 mcl_audit_free(sp->sl_base,
8604 NMBPG);
8605 } else {
8606 mcl_audit_free(sp->sl_base, 1);
8607 }
8608 }
fe8ab488
A
8609 break;
8610 default:
8611 /*
8612 * The composite classes have their own
8613 * freelist (m_cobjlist), so we only
8614 * process rudimentary classes here.
8615 */
8616 VERIFY(0);
8617 }
8618 m_release_cnt(mc) += m_size(mc);
8619 released += m_size(mc);
3e170ce0
A
8620 VERIFY(sp->sl_base != NULL &&
8621 sp->sl_len >= PAGE_SIZE);
8622 offset = MTOPG(sp->sl_base);
fe8ab488
A
8623 /*
8624 * Make sure the IOMapper points to a valid, but
8625 * bogus, address. This should prevent further DMA
8626 * accesses to freed memory.
8627 */
8628 IOMapperInsertPage(mcl_paddr_base, offset, scratch_pa);
8629 mcl_paddr[offset] = 0;
39037602 8630 kmem_free(mb_map, (vm_offset_t)sp->sl_base,
fe8ab488
A
8631 sp->sl_len);
8632 slab_init(sp, 0, 0, NULL, NULL, 0, 0, 0);
8633 sp->sl_flags = 0;
8634 }
8635 }
8636 mbstat.m_drain++;
8637 mbstat.m_bigclusters = m_total(MC_BIGCL);
8638 mbstat.m_clusters = m_total(MC_CL);
8639 mbstat.m_mbufs = m_total(MC_MBUF);
8640 mbuf_stat_sync();
8641 mbuf_mtypes_sync(TRUE);
d9a64523
A
8642}
8643
8644__private_extern__ void
8645mbuf_drain(boolean_t ignore_waiters)
8646{
8647 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_NOTOWNED);
0a7de745 8648 if (!mbuf_drain_checks(ignore_waiters)) {
d9a64523 8649 return;
0a7de745 8650 }
d9a64523
A
8651 lck_mtx_lock(mbuf_mlock);
8652 mbuf_drain_locked(ignore_waiters);
fe8ab488
A
8653 lck_mtx_unlock(mbuf_mlock);
8654}
8655
d9a64523 8656
fe8ab488
A
8657static int
8658m_drain_force_sysctl SYSCTL_HANDLER_ARGS
8659{
8660#pragma unused(arg1, arg2)
8661 int val = 0, err;
39037602 8662
fe8ab488 8663 err = sysctl_handle_int(oidp, &val, 0, req);
0a7de745
A
8664 if (err != 0 || req->newptr == USER_ADDR_NULL) {
8665 return err;
8666 }
5c9f4661 8667 if (val) {
d9a64523 8668 mbuf_drain(TRUE);
5c9f4661 8669 }
fe8ab488 8670
0a7de745 8671 return err;
fe8ab488
A
8672}
8673
cc8bc92a 8674#if DEBUG || DEVELOPMENT
d9a64523
A
8675static void
8676_mbwdog_logger(const char *func, const int line, const char *fmt, ...)
8677{
8678 va_list ap;
8679 struct timeval now;
8680 char str[384], p[256];
8681 int len;
8682
8683 LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
8684 if (mbwdog_logging == NULL) {
8685 mbwdog_logging = _MALLOC(mbwdog_logging_size,
0a7de745
A
8686 M_TEMP, M_ZERO | M_NOWAIT);
8687 if (mbwdog_logging == NULL) {
d9a64523 8688 return;
0a7de745 8689 }
d9a64523
A
8690 }
8691 va_start(ap, fmt);
8692 vsnprintf(p, sizeof(p), fmt, ap);
8693 va_end(ap);
8694 microuptime(&now);
8695 len = snprintf(str, sizeof(str),
8696 "\n%ld.%d (%d/%llx) %s:%d %s",
8697 now.tv_sec, now.tv_usec,
8698 current_proc()->p_pid,
8699 (uint64_t)VM_KERNEL_ADDRPERM(current_thread()),
8700 func, line, p);
0a7de745 8701 if (len < 0) {
d9a64523 8702 return;
0a7de745 8703 }
d9a64523
A
8704 if (mbwdog_logging_used + len > mbwdog_logging_size) {
8705 mbwdog_logging_used = mbwdog_logging_used / 2;
8706 memmove(mbwdog_logging, mbwdog_logging + mbwdog_logging_used,
8707 mbwdog_logging_size - mbwdog_logging_used);
8708 mbwdog_logging[mbwdog_logging_used] = 0;
8709 }
8710 strlcat(mbwdog_logging, str, mbwdog_logging_size);
8711 mbwdog_logging_used += len;
8712}
8713
8714static int
8715sysctl_mbwdog_log SYSCTL_HANDLER_ARGS
8716{
8717#pragma unused(oidp, arg1, arg2)
0a7de745 8718 return SYSCTL_OUT(req, mbwdog_logging, mbwdog_logging_used);
d9a64523
A
8719}
8720SYSCTL_DECL(_kern_ipc);
8721SYSCTL_PROC(_kern_ipc, OID_AUTO, mbwdog_log,
8722 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_LOCKED,
8723 0, 0, sysctl_mbwdog_log, "A", "");
cc8bc92a
A
8724
8725static int mbtest_val;
8726static int mbtest_running;
8727
0a7de745
A
8728static void
8729mbtest_thread(__unused void *arg)
cc8bc92a
A
8730{
8731 int i;
a39ff7e2
A
8732 int scale_down = 1;
8733 int iterations = 250;
8734 int allocations = nmbclusters;
8735 iterations = iterations / scale_down;
8736 allocations = allocations / scale_down;
cc8bc92a 8737 printf("%s thread starting\n", __func__);
a39ff7e2
A
8738 for (i = 0; i < iterations; i++) {
8739 unsigned int needed = allocations;
cc8bc92a
A
8740 struct mbuf *m1, *m2, *m3;
8741
8742 if (njcl > 0) {
a39ff7e2 8743 needed = allocations;
cc8bc92a
A
8744 m3 = m_getpackets_internal(&needed, 0, M_DONTWAIT, 0, M16KCLBYTES);
8745 m_freem_list(m3);
8746 }
8747
a39ff7e2 8748 needed = allocations;
cc8bc92a
A
8749 m2 = m_getpackets_internal(&needed, 0, M_DONTWAIT, 0, MBIGCLBYTES);
8750 m_freem_list(m2);
8751
8752 m1 = m_getpackets_internal(&needed, 0, M_DONTWAIT, 0, MCLBYTES);
8753 m_freem_list(m1);
8754 }
8755
8756 printf("%s thread ending\n", __func__);
8757
8758 OSDecrementAtomic(&mbtest_running);
8759 wakeup_one((caddr_t)&mbtest_running);
8760}
8761
0a7de745
A
8762static void
8763sysctl_mbtest(void)
cc8bc92a
A
8764{
8765 /* We launch three threads - wait for all of them */
8766 OSIncrementAtomic(&mbtest_running);
8767 OSIncrementAtomic(&mbtest_running);
8768 OSIncrementAtomic(&mbtest_running);
8769
8770 thread_call_func_delayed((thread_call_func_t)mbtest_thread, NULL, 10);
8771 thread_call_func_delayed((thread_call_func_t)mbtest_thread, NULL, 10);
8772 thread_call_func_delayed((thread_call_func_t)mbtest_thread, NULL, 10);
8773
8774 while (mbtest_running) {
8775 msleep((caddr_t)&mbtest_running, NULL, PUSER, "mbtest_running", NULL);
8776 }
8777}
8778
8779static int
8780mbtest SYSCTL_HANDLER_ARGS
8781{
8782#pragma unused(arg1, arg2)
8783 int error = 0, val, oldval = mbtest_val;
8784
8785 val = oldval;
8786 error = sysctl_handle_int(oidp, &val, 0, req);
0a7de745
A
8787 if (error || !req->newptr) {
8788 return error;
8789 }
cc8bc92a 8790
0a7de745 8791 if (val != oldval) {
cc8bc92a 8792 sysctl_mbtest();
0a7de745 8793 }
cc8bc92a
A
8794
8795 mbtest_val = val;
8796
0a7de745 8797 return error;
cc8bc92a 8798}
d9a64523 8799#endif // DEBUG || DEVELOPMENT
5c9f4661
A
8800
8801static void
8802mtracelarge_register(size_t size)
8803{
8804 int i;
8805 struct mtracelarge *trace;
8806 uintptr_t bt[MLEAK_STACK_DEPTH];
8807 unsigned int depth;
8808
cb323159 8809 depth = backtrace(bt, MLEAK_STACK_DEPTH, NULL);
5c9f4661
A
8810 /* Check if this entry is already on the list. */
8811 for (i = 0; i < MTRACELARGE_NUM_TRACES; i++) {
8812 trace = &mtracelarge_table[i];
8813 if (trace->size == size && trace->depth == depth &&
8814 memcmp(bt, trace->addr, depth * sizeof(uintptr_t)) == 0) {
8815 return;
8816 }
5c9f4661
A
8817 }
8818 for (i = 0; i < MTRACELARGE_NUM_TRACES; i++) {
8819 trace = &mtracelarge_table[i];
8820 if (size > trace->size) {
8821 trace->depth = depth;
8822 memcpy(trace->addr, bt, depth * sizeof(uintptr_t));
8823 trace->size = size;
8824 break;
8825 }
8826 }
8827}
8828
2d21ac55 8829SYSCTL_DECL(_kern_ipc);
cc8bc92a
A
8830#if DEBUG || DEVELOPMENT
8831SYSCTL_PROC(_kern_ipc, OID_AUTO, mbtest,
8832 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &mbtest_val, 0, &mbtest, "I",
8833 "Toggle to test mbufs");
8834#endif
6d2010ae 8835SYSCTL_PROC(_kern_ipc, KIPC_MBSTAT, mbstat,
fe8ab488 8836 CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED,
2d21ac55 8837 0, 0, mbstat_sysctl, "S,mbstat", "");
6d2010ae 8838SYSCTL_PROC(_kern_ipc, OID_AUTO, mb_stat,
fe8ab488 8839 CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED,
2d21ac55 8840 0, 0, mb_stat_sysctl, "S,mb_stat", "");
6d2010ae 8841SYSCTL_PROC(_kern_ipc, OID_AUTO, mleak_top_trace,
fe8ab488 8842 CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED,
6d2010ae
A
8843 0, 0, mleak_top_trace_sysctl, "S,mb_top_trace", "");
8844SYSCTL_PROC(_kern_ipc, OID_AUTO, mleak_table,
fe8ab488 8845 CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED,
6d2010ae
A
8846 0, 0, mleak_table_sysctl, "S,mleak_table", "");
8847SYSCTL_INT(_kern_ipc, OID_AUTO, mleak_sample_factor,
8848 CTLFLAG_RW | CTLFLAG_LOCKED, &mleak_table.mleak_sample_factor, 0, "");
8849SYSCTL_INT(_kern_ipc, OID_AUTO, mb_normalized,
8850 CTLFLAG_RD | CTLFLAG_LOCKED, &mb_normalized, 0, "");
8851SYSCTL_INT(_kern_ipc, OID_AUTO, mb_watchdog,
8852 CTLFLAG_RW | CTLFLAG_LOCKED, &mb_watchdog, 0, "");
fe8ab488 8853SYSCTL_PROC(_kern_ipc, OID_AUTO, mb_drain_force,
39037602 8854 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, NULL, 0,
fe8ab488
A
8855 m_drain_force_sysctl, "I",
8856 "Forces the mbuf garbage collection to run");
8857SYSCTL_INT(_kern_ipc, OID_AUTO, mb_drain_maxint,
8858 CTLFLAG_RW | CTLFLAG_LOCKED, &mb_drain_maxint, 0,
8859 "Minimum time interval between garbage collection");