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