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