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