xref: /freebsd/sys/kern/kern_mbuf.c (revision da759cfa320d5076b075d15ff3f00ab3ba5634fd)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2004, 2005,
5  *	Bosko Milekic <bmilekic@FreeBSD.org>.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice unmodified, this list of conditions and the following
12  *    disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include "opt_param.h"
34 #include "opt_kern_tls.h"
35 
36 #include <sys/param.h>
37 #include <sys/conf.h>
38 #include <sys/domainset.h>
39 #include <sys/malloc.h>
40 #include <sys/systm.h>
41 #include <sys/mbuf.h>
42 #include <sys/domain.h>
43 #include <sys/eventhandler.h>
44 #include <sys/kernel.h>
45 #include <sys/ktls.h>
46 #include <sys/limits.h>
47 #include <sys/lock.h>
48 #include <sys/mutex.h>
49 #include <sys/protosw.h>
50 #include <sys/refcount.h>
51 #include <sys/sf_buf.h>
52 #include <sys/smp.h>
53 #include <sys/socket.h>
54 #include <sys/sysctl.h>
55 
56 #include <net/if.h>
57 #include <net/if_var.h>
58 
59 #include <vm/vm.h>
60 #include <vm/vm_extern.h>
61 #include <vm/vm_kern.h>
62 #include <vm/vm_page.h>
63 #include <vm/vm_map.h>
64 #include <vm/uma.h>
65 #include <vm/uma_dbg.h>
66 
67 /*
68  * In FreeBSD, Mbufs and Mbuf Clusters are allocated from UMA
69  * Zones.
70  *
71  * Mbuf Clusters (2K, contiguous) are allocated from the Cluster
72  * Zone.  The Zone can be capped at kern.ipc.nmbclusters, if the
73  * administrator so desires.
74  *
75  * Mbufs are allocated from a UMA Master Zone called the Mbuf
76  * Zone.
77  *
78  * Additionally, FreeBSD provides a Packet Zone, which it
79  * configures as a Secondary Zone to the Mbuf Master Zone,
80  * thus sharing backend Slab kegs with the Mbuf Master Zone.
81  *
82  * Thus common-case allocations and locking are simplified:
83  *
84  *  m_clget()                m_getcl()
85  *    |                         |
86  *    |   .------------>[(Packet Cache)]    m_get(), m_gethdr()
87  *    |   |             [     Packet   ]            |
88  *  [(Cluster Cache)]   [    Secondary ]   [ (Mbuf Cache)     ]
89  *  [ Cluster Zone  ]   [     Zone     ]   [ Mbuf Master Zone ]
90  *        |                       \________         |
91  *  [ Cluster Keg   ]                      \       /
92  *        |	                         [ Mbuf Keg   ]
93  *  [ Cluster Slabs ]                         |
94  *        |                              [ Mbuf Slabs ]
95  *         \____________(VM)_________________/
96  *
97  *
98  * Whenever an object is allocated with uma_zalloc() out of
99  * one of the Zones its _ctor_ function is executed.  The same
100  * for any deallocation through uma_zfree() the _dtor_ function
101  * is executed.
102  *
103  * Caches are per-CPU and are filled from the Master Zone.
104  *
105  * Whenever an object is allocated from the underlying global
106  * memory pool it gets pre-initialized with the _zinit_ functions.
107  * When the Keg's are overfull objects get decommissioned with
108  * _zfini_ functions and free'd back to the global memory pool.
109  *
110  */
111 
112 int nmbufs;			/* limits number of mbufs */
113 int nmbclusters;		/* limits number of mbuf clusters */
114 int nmbjumbop;			/* limits number of page size jumbo clusters */
115 int nmbjumbo9;			/* limits number of 9k jumbo clusters */
116 int nmbjumbo16;			/* limits number of 16k jumbo clusters */
117 
118 bool mb_use_ext_pgs;		/* use EXT_PGS mbufs for sendfile & TLS */
119 SYSCTL_BOOL(_kern_ipc, OID_AUTO, mb_use_ext_pgs, CTLFLAG_RWTUN,
120     &mb_use_ext_pgs, 0,
121     "Use unmapped mbufs for sendfile(2) and TLS offload");
122 
123 static quad_t maxmbufmem;	/* overall real memory limit for all mbufs */
124 
125 SYSCTL_QUAD(_kern_ipc, OID_AUTO, maxmbufmem, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &maxmbufmem, 0,
126     "Maximum real memory allocatable to various mbuf types");
127 
128 static counter_u64_t snd_tag_count;
129 SYSCTL_COUNTER_U64(_kern_ipc, OID_AUTO, num_snd_tags, CTLFLAG_RW,
130     &snd_tag_count, "# of active mbuf send tags");
131 
132 /*
133  * tunable_mbinit() has to be run before any mbuf allocations are done.
134  */
135 static void
136 tunable_mbinit(void *dummy)
137 {
138 	quad_t realmem;
139 
140 	/*
141 	 * The default limit for all mbuf related memory is 1/2 of all
142 	 * available kernel memory (physical or kmem).
143 	 * At most it can be 3/4 of available kernel memory.
144 	 */
145 	realmem = qmin((quad_t)physmem * PAGE_SIZE, vm_kmem_size);
146 	maxmbufmem = realmem / 2;
147 	TUNABLE_QUAD_FETCH("kern.ipc.maxmbufmem", &maxmbufmem);
148 	if (maxmbufmem > realmem / 4 * 3)
149 		maxmbufmem = realmem / 4 * 3;
150 
151 	TUNABLE_INT_FETCH("kern.ipc.nmbclusters", &nmbclusters);
152 	if (nmbclusters == 0)
153 		nmbclusters = maxmbufmem / MCLBYTES / 4;
154 
155 	TUNABLE_INT_FETCH("kern.ipc.nmbjumbop", &nmbjumbop);
156 	if (nmbjumbop == 0)
157 		nmbjumbop = maxmbufmem / MJUMPAGESIZE / 4;
158 
159 	TUNABLE_INT_FETCH("kern.ipc.nmbjumbo9", &nmbjumbo9);
160 	if (nmbjumbo9 == 0)
161 		nmbjumbo9 = maxmbufmem / MJUM9BYTES / 6;
162 
163 	TUNABLE_INT_FETCH("kern.ipc.nmbjumbo16", &nmbjumbo16);
164 	if (nmbjumbo16 == 0)
165 		nmbjumbo16 = maxmbufmem / MJUM16BYTES / 6;
166 
167 	/*
168 	 * We need at least as many mbufs as we have clusters of
169 	 * the various types added together.
170 	 */
171 	TUNABLE_INT_FETCH("kern.ipc.nmbufs", &nmbufs);
172 	if (nmbufs < nmbclusters + nmbjumbop + nmbjumbo9 + nmbjumbo16)
173 		nmbufs = lmax(maxmbufmem / MSIZE / 5,
174 		    nmbclusters + nmbjumbop + nmbjumbo9 + nmbjumbo16);
175 }
176 SYSINIT(tunable_mbinit, SI_SUB_KMEM, SI_ORDER_MIDDLE, tunable_mbinit, NULL);
177 
178 static int
179 sysctl_nmbclusters(SYSCTL_HANDLER_ARGS)
180 {
181 	int error, newnmbclusters;
182 
183 	newnmbclusters = nmbclusters;
184 	error = sysctl_handle_int(oidp, &newnmbclusters, 0, req);
185 	if (error == 0 && req->newptr && newnmbclusters != nmbclusters) {
186 		if (newnmbclusters > nmbclusters &&
187 		    nmbufs >= nmbclusters + nmbjumbop + nmbjumbo9 + nmbjumbo16) {
188 			nmbclusters = newnmbclusters;
189 			nmbclusters = uma_zone_set_max(zone_clust, nmbclusters);
190 			EVENTHANDLER_INVOKE(nmbclusters_change);
191 		} else
192 			error = EINVAL;
193 	}
194 	return (error);
195 }
196 SYSCTL_PROC(_kern_ipc, OID_AUTO, nmbclusters,
197     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, &nmbclusters, 0,
198     sysctl_nmbclusters, "IU",
199     "Maximum number of mbuf clusters allowed");
200 
201 static int
202 sysctl_nmbjumbop(SYSCTL_HANDLER_ARGS)
203 {
204 	int error, newnmbjumbop;
205 
206 	newnmbjumbop = nmbjumbop;
207 	error = sysctl_handle_int(oidp, &newnmbjumbop, 0, req);
208 	if (error == 0 && req->newptr && newnmbjumbop != nmbjumbop) {
209 		if (newnmbjumbop > nmbjumbop &&
210 		    nmbufs >= nmbclusters + nmbjumbop + nmbjumbo9 + nmbjumbo16) {
211 			nmbjumbop = newnmbjumbop;
212 			nmbjumbop = uma_zone_set_max(zone_jumbop, nmbjumbop);
213 		} else
214 			error = EINVAL;
215 	}
216 	return (error);
217 }
218 SYSCTL_PROC(_kern_ipc, OID_AUTO, nmbjumbop,
219     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, &nmbjumbop, 0,
220     sysctl_nmbjumbop, "IU",
221     "Maximum number of mbuf page size jumbo clusters allowed");
222 
223 static int
224 sysctl_nmbjumbo9(SYSCTL_HANDLER_ARGS)
225 {
226 	int error, newnmbjumbo9;
227 
228 	newnmbjumbo9 = nmbjumbo9;
229 	error = sysctl_handle_int(oidp, &newnmbjumbo9, 0, req);
230 	if (error == 0 && req->newptr && newnmbjumbo9 != nmbjumbo9) {
231 		if (newnmbjumbo9 > nmbjumbo9 &&
232 		    nmbufs >= nmbclusters + nmbjumbop + nmbjumbo9 + nmbjumbo16) {
233 			nmbjumbo9 = newnmbjumbo9;
234 			nmbjumbo9 = uma_zone_set_max(zone_jumbo9, nmbjumbo9);
235 		} else
236 			error = EINVAL;
237 	}
238 	return (error);
239 }
240 SYSCTL_PROC(_kern_ipc, OID_AUTO, nmbjumbo9,
241     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, &nmbjumbo9, 0,
242     sysctl_nmbjumbo9, "IU",
243     "Maximum number of mbuf 9k jumbo clusters allowed");
244 
245 static int
246 sysctl_nmbjumbo16(SYSCTL_HANDLER_ARGS)
247 {
248 	int error, newnmbjumbo16;
249 
250 	newnmbjumbo16 = nmbjumbo16;
251 	error = sysctl_handle_int(oidp, &newnmbjumbo16, 0, req);
252 	if (error == 0 && req->newptr && newnmbjumbo16 != nmbjumbo16) {
253 		if (newnmbjumbo16 > nmbjumbo16 &&
254 		    nmbufs >= nmbclusters + nmbjumbop + nmbjumbo9 + nmbjumbo16) {
255 			nmbjumbo16 = newnmbjumbo16;
256 			nmbjumbo16 = uma_zone_set_max(zone_jumbo16, nmbjumbo16);
257 		} else
258 			error = EINVAL;
259 	}
260 	return (error);
261 }
262 SYSCTL_PROC(_kern_ipc, OID_AUTO, nmbjumbo16,
263     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, &nmbjumbo16, 0,
264     sysctl_nmbjumbo16, "IU",
265     "Maximum number of mbuf 16k jumbo clusters allowed");
266 
267 static int
268 sysctl_nmbufs(SYSCTL_HANDLER_ARGS)
269 {
270 	int error, newnmbufs;
271 
272 	newnmbufs = nmbufs;
273 	error = sysctl_handle_int(oidp, &newnmbufs, 0, req);
274 	if (error == 0 && req->newptr && newnmbufs != nmbufs) {
275 		if (newnmbufs > nmbufs) {
276 			nmbufs = newnmbufs;
277 			nmbufs = uma_zone_set_max(zone_mbuf, nmbufs);
278 			EVENTHANDLER_INVOKE(nmbufs_change);
279 		} else
280 			error = EINVAL;
281 	}
282 	return (error);
283 }
284 SYSCTL_PROC(_kern_ipc, OID_AUTO, nmbufs,
285     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
286     &nmbufs, 0, sysctl_nmbufs, "IU",
287     "Maximum number of mbufs allowed");
288 
289 /*
290  * Zones from which we allocate.
291  */
292 uma_zone_t	zone_mbuf;
293 uma_zone_t	zone_clust;
294 uma_zone_t	zone_pack;
295 uma_zone_t	zone_jumbop;
296 uma_zone_t	zone_jumbo9;
297 uma_zone_t	zone_jumbo16;
298 uma_zone_t	zone_extpgs;
299 
300 /*
301  * Local prototypes.
302  */
303 static int	mb_ctor_mbuf(void *, int, void *, int);
304 static int	mb_ctor_clust(void *, int, void *, int);
305 static int	mb_ctor_pack(void *, int, void *, int);
306 static void	mb_dtor_mbuf(void *, int, void *);
307 static void	mb_dtor_pack(void *, int, void *);
308 static int	mb_zinit_pack(void *, int, int);
309 static void	mb_zfini_pack(void *, int);
310 static void	mb_reclaim(uma_zone_t, int);
311 
312 /* Ensure that MSIZE is a power of 2. */
313 CTASSERT((((MSIZE - 1) ^ MSIZE) + 1) >> 1 == MSIZE);
314 
315 _Static_assert(sizeof(struct mbuf_ext_pgs) == 256,
316     "mbuf_ext_pgs size mismatch");
317 
318 /*
319  * Initialize FreeBSD Network buffer allocation.
320  */
321 static void
322 mbuf_init(void *dummy)
323 {
324 
325 	/*
326 	 * Configure UMA zones for Mbufs, Clusters, and Packets.
327 	 */
328 	zone_mbuf = uma_zcreate(MBUF_MEM_NAME, MSIZE,
329 	    mb_ctor_mbuf, mb_dtor_mbuf, NULL, NULL,
330 	    MSIZE - 1, UMA_ZONE_CONTIG | UMA_ZONE_MAXBUCKET);
331 	if (nmbufs > 0)
332 		nmbufs = uma_zone_set_max(zone_mbuf, nmbufs);
333 	uma_zone_set_warning(zone_mbuf, "kern.ipc.nmbufs limit reached");
334 	uma_zone_set_maxaction(zone_mbuf, mb_reclaim);
335 
336 	zone_clust = uma_zcreate(MBUF_CLUSTER_MEM_NAME, MCLBYTES,
337 	    mb_ctor_clust, NULL, NULL, NULL,
338 	    UMA_ALIGN_PTR, UMA_ZONE_CONTIG);
339 	if (nmbclusters > 0)
340 		nmbclusters = uma_zone_set_max(zone_clust, nmbclusters);
341 	uma_zone_set_warning(zone_clust, "kern.ipc.nmbclusters limit reached");
342 	uma_zone_set_maxaction(zone_clust, mb_reclaim);
343 
344 	zone_pack = uma_zsecond_create(MBUF_PACKET_MEM_NAME, mb_ctor_pack,
345 	    mb_dtor_pack, mb_zinit_pack, mb_zfini_pack, zone_mbuf);
346 
347 	/* Make jumbo frame zone too. Page size, 9k and 16k. */
348 	zone_jumbop = uma_zcreate(MBUF_JUMBOP_MEM_NAME, MJUMPAGESIZE,
349 	    mb_ctor_clust, NULL, NULL, NULL,
350 	    UMA_ALIGN_PTR, UMA_ZONE_CONTIG);
351 	if (nmbjumbop > 0)
352 		nmbjumbop = uma_zone_set_max(zone_jumbop, nmbjumbop);
353 	uma_zone_set_warning(zone_jumbop, "kern.ipc.nmbjumbop limit reached");
354 	uma_zone_set_maxaction(zone_jumbop, mb_reclaim);
355 
356 	zone_jumbo9 = uma_zcreate(MBUF_JUMBO9_MEM_NAME, MJUM9BYTES,
357 	    mb_ctor_clust, NULL, NULL, NULL,
358 	    UMA_ALIGN_PTR, UMA_ZONE_CONTIG);
359 	if (nmbjumbo9 > 0)
360 		nmbjumbo9 = uma_zone_set_max(zone_jumbo9, nmbjumbo9);
361 	uma_zone_set_warning(zone_jumbo9, "kern.ipc.nmbjumbo9 limit reached");
362 	uma_zone_set_maxaction(zone_jumbo9, mb_reclaim);
363 
364 	zone_jumbo16 = uma_zcreate(MBUF_JUMBO16_MEM_NAME, MJUM16BYTES,
365 	    mb_ctor_clust, NULL, NULL, NULL,
366 	    UMA_ALIGN_PTR, UMA_ZONE_CONTIG);
367 	if (nmbjumbo16 > 0)
368 		nmbjumbo16 = uma_zone_set_max(zone_jumbo16, nmbjumbo16);
369 	uma_zone_set_warning(zone_jumbo16, "kern.ipc.nmbjumbo16 limit reached");
370 	uma_zone_set_maxaction(zone_jumbo16, mb_reclaim);
371 
372 	zone_extpgs = uma_zcreate(MBUF_EXTPGS_MEM_NAME,
373 	    sizeof(struct mbuf_ext_pgs),
374 	    NULL, NULL, NULL, NULL,
375 	    UMA_ALIGN_CACHE, 0);
376 
377 	/*
378 	 * Hook event handler for low-memory situation, used to
379 	 * drain protocols and push data back to the caches (UMA
380 	 * later pushes it back to VM).
381 	 */
382 	EVENTHANDLER_REGISTER(vm_lowmem, mb_reclaim, NULL,
383 	    EVENTHANDLER_PRI_FIRST);
384 
385 	snd_tag_count = counter_u64_alloc(M_WAITOK);
386 }
387 SYSINIT(mbuf, SI_SUB_MBUF, SI_ORDER_FIRST, mbuf_init, NULL);
388 
389 #ifdef DEBUGNET
390 /*
391  * debugnet makes use of a pre-allocated pool of mbufs and clusters.  When
392  * debugnet is configured, we initialize a set of UMA cache zones which return
393  * items from this pool.  At panic-time, the regular UMA zone pointers are
394  * overwritten with those of the cache zones so that drivers may allocate and
395  * free mbufs and clusters without attempting to allocate physical memory.
396  *
397  * We keep mbufs and clusters in a pair of mbuf queues.  In particular, for
398  * the purpose of caching clusters, we treat them as mbufs.
399  */
400 static struct mbufq dn_mbufq =
401     { STAILQ_HEAD_INITIALIZER(dn_mbufq.mq_head), 0, INT_MAX };
402 static struct mbufq dn_clustq =
403     { STAILQ_HEAD_INITIALIZER(dn_clustq.mq_head), 0, INT_MAX };
404 
405 static int dn_clsize;
406 static uma_zone_t dn_zone_mbuf;
407 static uma_zone_t dn_zone_clust;
408 static uma_zone_t dn_zone_pack;
409 
410 static struct debugnet_saved_zones {
411 	uma_zone_t dsz_mbuf;
412 	uma_zone_t dsz_clust;
413 	uma_zone_t dsz_pack;
414 	uma_zone_t dsz_jumbop;
415 	uma_zone_t dsz_jumbo9;
416 	uma_zone_t dsz_jumbo16;
417 	bool dsz_debugnet_zones_enabled;
418 } dn_saved_zones;
419 
420 static int
421 dn_buf_import(void *arg, void **store, int count, int domain __unused,
422     int flags)
423 {
424 	struct mbufq *q;
425 	struct mbuf *m;
426 	int i;
427 
428 	q = arg;
429 
430 	for (i = 0; i < count; i++) {
431 		m = mbufq_dequeue(q);
432 		if (m == NULL)
433 			break;
434 		trash_init(m, q == &dn_mbufq ? MSIZE : dn_clsize, flags);
435 		store[i] = m;
436 	}
437 	KASSERT((flags & M_WAITOK) == 0 || i == count,
438 	    ("%s: ran out of pre-allocated mbufs", __func__));
439 	return (i);
440 }
441 
442 static void
443 dn_buf_release(void *arg, void **store, int count)
444 {
445 	struct mbufq *q;
446 	struct mbuf *m;
447 	int i;
448 
449 	q = arg;
450 
451 	for (i = 0; i < count; i++) {
452 		m = store[i];
453 		(void)mbufq_enqueue(q, m);
454 	}
455 }
456 
457 static int
458 dn_pack_import(void *arg __unused, void **store, int count, int domain __unused,
459     int flags __unused)
460 {
461 	struct mbuf *m;
462 	void *clust;
463 	int i;
464 
465 	for (i = 0; i < count; i++) {
466 		m = m_get(MT_DATA, M_NOWAIT);
467 		if (m == NULL)
468 			break;
469 		clust = uma_zalloc(dn_zone_clust, M_NOWAIT);
470 		if (clust == NULL) {
471 			m_free(m);
472 			break;
473 		}
474 		mb_ctor_clust(clust, dn_clsize, m, 0);
475 		store[i] = m;
476 	}
477 	KASSERT((flags & M_WAITOK) == 0 || i == count,
478 	    ("%s: ran out of pre-allocated mbufs", __func__));
479 	return (i);
480 }
481 
482 static void
483 dn_pack_release(void *arg __unused, void **store, int count)
484 {
485 	struct mbuf *m;
486 	void *clust;
487 	int i;
488 
489 	for (i = 0; i < count; i++) {
490 		m = store[i];
491 		clust = m->m_ext.ext_buf;
492 		uma_zfree(dn_zone_clust, clust);
493 		uma_zfree(dn_zone_mbuf, m);
494 	}
495 }
496 
497 /*
498  * Free the pre-allocated mbufs and clusters reserved for debugnet, and destroy
499  * the corresponding UMA cache zones.
500  */
501 void
502 debugnet_mbuf_drain(void)
503 {
504 	struct mbuf *m;
505 	void *item;
506 
507 	if (dn_zone_mbuf != NULL) {
508 		uma_zdestroy(dn_zone_mbuf);
509 		dn_zone_mbuf = NULL;
510 	}
511 	if (dn_zone_clust != NULL) {
512 		uma_zdestroy(dn_zone_clust);
513 		dn_zone_clust = NULL;
514 	}
515 	if (dn_zone_pack != NULL) {
516 		uma_zdestroy(dn_zone_pack);
517 		dn_zone_pack = NULL;
518 	}
519 
520 	while ((m = mbufq_dequeue(&dn_mbufq)) != NULL)
521 		m_free(m);
522 	while ((item = mbufq_dequeue(&dn_clustq)) != NULL)
523 		uma_zfree(m_getzone(dn_clsize), item);
524 }
525 
526 /*
527  * Callback invoked immediately prior to starting a debugnet connection.
528  */
529 void
530 debugnet_mbuf_start(void)
531 {
532 
533 	MPASS(!dn_saved_zones.dsz_debugnet_zones_enabled);
534 
535 	/* Save the old zone pointers to restore when debugnet is closed. */
536 	dn_saved_zones = (struct debugnet_saved_zones) {
537 		.dsz_debugnet_zones_enabled = true,
538 		.dsz_mbuf = zone_mbuf,
539 		.dsz_clust = zone_clust,
540 		.dsz_pack = zone_pack,
541 		.dsz_jumbop = zone_jumbop,
542 		.dsz_jumbo9 = zone_jumbo9,
543 		.dsz_jumbo16 = zone_jumbo16,
544 	};
545 
546 	/*
547 	 * All cluster zones return buffers of the size requested by the
548 	 * drivers.  It's up to the driver to reinitialize the zones if the
549 	 * MTU of a debugnet-enabled interface changes.
550 	 */
551 	printf("debugnet: overwriting mbuf zone pointers\n");
552 	zone_mbuf = dn_zone_mbuf;
553 	zone_clust = dn_zone_clust;
554 	zone_pack = dn_zone_pack;
555 	zone_jumbop = dn_zone_clust;
556 	zone_jumbo9 = dn_zone_clust;
557 	zone_jumbo16 = dn_zone_clust;
558 }
559 
560 /*
561  * Callback invoked when a debugnet connection is closed/finished.
562  */
563 void
564 debugnet_mbuf_finish(void)
565 {
566 
567 	MPASS(dn_saved_zones.dsz_debugnet_zones_enabled);
568 
569 	printf("debugnet: restoring mbuf zone pointers\n");
570 	zone_mbuf = dn_saved_zones.dsz_mbuf;
571 	zone_clust = dn_saved_zones.dsz_clust;
572 	zone_pack = dn_saved_zones.dsz_pack;
573 	zone_jumbop = dn_saved_zones.dsz_jumbop;
574 	zone_jumbo9 = dn_saved_zones.dsz_jumbo9;
575 	zone_jumbo16 = dn_saved_zones.dsz_jumbo16;
576 
577 	memset(&dn_saved_zones, 0, sizeof(dn_saved_zones));
578 }
579 
580 /*
581  * Reinitialize the debugnet mbuf+cluster pool and cache zones.
582  */
583 void
584 debugnet_mbuf_reinit(int nmbuf, int nclust, int clsize)
585 {
586 	struct mbuf *m;
587 	void *item;
588 
589 	debugnet_mbuf_drain();
590 
591 	dn_clsize = clsize;
592 
593 	dn_zone_mbuf = uma_zcache_create("debugnet_" MBUF_MEM_NAME,
594 	    MSIZE, mb_ctor_mbuf, mb_dtor_mbuf, NULL, NULL,
595 	    dn_buf_import, dn_buf_release,
596 	    &dn_mbufq, UMA_ZONE_NOBUCKET);
597 
598 	dn_zone_clust = uma_zcache_create("debugnet_" MBUF_CLUSTER_MEM_NAME,
599 	    clsize, mb_ctor_clust, NULL, NULL, NULL,
600 	    dn_buf_import, dn_buf_release,
601 	    &dn_clustq, UMA_ZONE_NOBUCKET);
602 
603 	dn_zone_pack = uma_zcache_create("debugnet_" MBUF_PACKET_MEM_NAME,
604 	    MCLBYTES, mb_ctor_pack, mb_dtor_pack, NULL, NULL,
605 	    dn_pack_import, dn_pack_release,
606 	    NULL, UMA_ZONE_NOBUCKET);
607 
608 	while (nmbuf-- > 0) {
609 		m = m_get(MT_DATA, M_WAITOK);
610 		uma_zfree(dn_zone_mbuf, m);
611 	}
612 	while (nclust-- > 0) {
613 		item = uma_zalloc(m_getzone(dn_clsize), M_WAITOK);
614 		uma_zfree(dn_zone_clust, item);
615 	}
616 }
617 #endif /* DEBUGNET */
618 
619 /*
620  * Constructor for Mbuf master zone.
621  *
622  * The 'arg' pointer points to a mb_args structure which
623  * contains call-specific information required to support the
624  * mbuf allocation API.  See mbuf.h.
625  */
626 static int
627 mb_ctor_mbuf(void *mem, int size, void *arg, int how)
628 {
629 	struct mbuf *m;
630 	struct mb_args *args;
631 	int error;
632 	int flags;
633 	short type;
634 
635 	args = (struct mb_args *)arg;
636 	type = args->type;
637 
638 	/*
639 	 * The mbuf is initialized later.  The caller has the
640 	 * responsibility to set up any MAC labels too.
641 	 */
642 	if (type == MT_NOINIT)
643 		return (0);
644 
645 	m = (struct mbuf *)mem;
646 	flags = args->flags;
647 	MPASS((flags & M_NOFREE) == 0);
648 
649 	error = m_init(m, how, type, flags);
650 
651 	return (error);
652 }
653 
654 /*
655  * The Mbuf master zone destructor.
656  */
657 static void
658 mb_dtor_mbuf(void *mem, int size, void *arg)
659 {
660 	struct mbuf *m;
661 	unsigned long flags;
662 
663 	m = (struct mbuf *)mem;
664 	flags = (unsigned long)arg;
665 
666 	KASSERT((m->m_flags & M_NOFREE) == 0, ("%s: M_NOFREE set", __func__));
667 	if (!(flags & MB_DTOR_SKIP) && (m->m_flags & M_PKTHDR) && !SLIST_EMPTY(&m->m_pkthdr.tags))
668 		m_tag_delete_chain(m, NULL);
669 }
670 
671 /*
672  * The Mbuf Packet zone destructor.
673  */
674 static void
675 mb_dtor_pack(void *mem, int size, void *arg)
676 {
677 	struct mbuf *m;
678 
679 	m = (struct mbuf *)mem;
680 	if ((m->m_flags & M_PKTHDR) != 0)
681 		m_tag_delete_chain(m, NULL);
682 
683 	/* Make sure we've got a clean cluster back. */
684 	KASSERT((m->m_flags & M_EXT) == M_EXT, ("%s: M_EXT not set", __func__));
685 	KASSERT(m->m_ext.ext_buf != NULL, ("%s: ext_buf == NULL", __func__));
686 	KASSERT(m->m_ext.ext_free == NULL, ("%s: ext_free != NULL", __func__));
687 	KASSERT(m->m_ext.ext_arg1 == NULL, ("%s: ext_arg1 != NULL", __func__));
688 	KASSERT(m->m_ext.ext_arg2 == NULL, ("%s: ext_arg2 != NULL", __func__));
689 	KASSERT(m->m_ext.ext_size == MCLBYTES, ("%s: ext_size != MCLBYTES", __func__));
690 	KASSERT(m->m_ext.ext_type == EXT_PACKET, ("%s: ext_type != EXT_PACKET", __func__));
691 #ifdef INVARIANTS
692 	trash_dtor(m->m_ext.ext_buf, MCLBYTES, arg);
693 #endif
694 	/*
695 	 * If there are processes blocked on zone_clust, waiting for pages
696 	 * to be freed up, cause them to be woken up by draining the
697 	 * packet zone.  We are exposed to a race here (in the check for
698 	 * the UMA_ZFLAG_FULL) where we might miss the flag set, but that
699 	 * is deliberate. We don't want to acquire the zone lock for every
700 	 * mbuf free.
701 	 */
702 	if (uma_zone_exhausted(zone_clust))
703 		uma_zone_reclaim(zone_pack, UMA_RECLAIM_DRAIN);
704 }
705 
706 /*
707  * The Cluster and Jumbo[PAGESIZE|9|16] zone constructor.
708  *
709  * Here the 'arg' pointer points to the Mbuf which we
710  * are configuring cluster storage for.  If 'arg' is
711  * empty we allocate just the cluster without setting
712  * the mbuf to it.  See mbuf.h.
713  */
714 static int
715 mb_ctor_clust(void *mem, int size, void *arg, int how)
716 {
717 	struct mbuf *m;
718 
719 	m = (struct mbuf *)arg;
720 	if (m != NULL) {
721 		m->m_ext.ext_buf = (char *)mem;
722 		m->m_data = m->m_ext.ext_buf;
723 		m->m_flags |= M_EXT;
724 		m->m_ext.ext_free = NULL;
725 		m->m_ext.ext_arg1 = NULL;
726 		m->m_ext.ext_arg2 = NULL;
727 		m->m_ext.ext_size = size;
728 		m->m_ext.ext_type = m_gettype(size);
729 		m->m_ext.ext_flags = EXT_FLAG_EMBREF;
730 		m->m_ext.ext_count = 1;
731 	}
732 
733 	return (0);
734 }
735 
736 /*
737  * The Packet secondary zone's init routine, executed on the
738  * object's transition from mbuf keg slab to zone cache.
739  */
740 static int
741 mb_zinit_pack(void *mem, int size, int how)
742 {
743 	struct mbuf *m;
744 
745 	m = (struct mbuf *)mem;		/* m is virgin. */
746 	if (uma_zalloc_arg(zone_clust, m, how) == NULL ||
747 	    m->m_ext.ext_buf == NULL)
748 		return (ENOMEM);
749 	m->m_ext.ext_type = EXT_PACKET;	/* Override. */
750 #ifdef INVARIANTS
751 	trash_init(m->m_ext.ext_buf, MCLBYTES, how);
752 #endif
753 	return (0);
754 }
755 
756 /*
757  * The Packet secondary zone's fini routine, executed on the
758  * object's transition from zone cache to keg slab.
759  */
760 static void
761 mb_zfini_pack(void *mem, int size)
762 {
763 	struct mbuf *m;
764 
765 	m = (struct mbuf *)mem;
766 #ifdef INVARIANTS
767 	trash_fini(m->m_ext.ext_buf, MCLBYTES);
768 #endif
769 	uma_zfree_arg(zone_clust, m->m_ext.ext_buf, NULL);
770 #ifdef INVARIANTS
771 	trash_dtor(mem, size, NULL);
772 #endif
773 }
774 
775 /*
776  * The "packet" keg constructor.
777  */
778 static int
779 mb_ctor_pack(void *mem, int size, void *arg, int how)
780 {
781 	struct mbuf *m;
782 	struct mb_args *args;
783 	int error, flags;
784 	short type;
785 
786 	m = (struct mbuf *)mem;
787 	args = (struct mb_args *)arg;
788 	flags = args->flags;
789 	type = args->type;
790 	MPASS((flags & M_NOFREE) == 0);
791 
792 #ifdef INVARIANTS
793 	trash_ctor(m->m_ext.ext_buf, MCLBYTES, arg, how);
794 #endif
795 
796 	error = m_init(m, how, type, flags);
797 
798 	/* m_ext is already initialized. */
799 	m->m_data = m->m_ext.ext_buf;
800  	m->m_flags = (flags | M_EXT);
801 
802 	return (error);
803 }
804 
805 /*
806  * This is the protocol drain routine.  Called by UMA whenever any of the
807  * mbuf zones is closed to its limit.
808  *
809  * No locks should be held when this is called.  The drain routines have to
810  * presently acquire some locks which raises the possibility of lock order
811  * reversal.
812  */
813 static void
814 mb_reclaim(uma_zone_t zone __unused, int pending __unused)
815 {
816 	struct epoch_tracker et;
817 	struct domain *dp;
818 	struct protosw *pr;
819 
820 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK | WARN_PANIC, NULL, __func__);
821 
822 	NET_EPOCH_ENTER(et);
823 	for (dp = domains; dp != NULL; dp = dp->dom_next)
824 		for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++)
825 			if (pr->pr_drain != NULL)
826 				(*pr->pr_drain)();
827 	NET_EPOCH_EXIT(et);
828 }
829 
830 /*
831  * Free "count" units of I/O from an mbuf chain.  They could be held
832  * in EXT_PGS or just as a normal mbuf.  This code is intended to be
833  * called in an error path (I/O error, closed connection, etc).
834  */
835 void
836 mb_free_notready(struct mbuf *m, int count)
837 {
838 	int i;
839 
840 	for (i = 0; i < count && m != NULL; i++) {
841 		if ((m->m_flags & M_EXT) != 0 &&
842 		    m->m_ext.ext_type == EXT_PGS) {
843 			m->m_ext.ext_pgs->nrdy--;
844 			if (m->m_ext.ext_pgs->nrdy != 0)
845 				continue;
846 		}
847 		m = m_free(m);
848 	}
849 	KASSERT(i == count, ("Removed only %d items from %p", i, m));
850 }
851 
852 /*
853  * Compress an unmapped mbuf into a simple mbuf when it holds a small
854  * amount of data.  This is used as a DOS defense to avoid having
855  * small packets tie up wired pages, an ext_pgs structure, and an
856  * mbuf.  Since this converts the existing mbuf in place, it can only
857  * be used if there are no other references to 'm'.
858  */
859 int
860 mb_unmapped_compress(struct mbuf *m)
861 {
862 	volatile u_int *refcnt;
863 	struct mbuf m_temp;
864 
865 	/*
866 	 * Assert that 'm' does not have a packet header.  If 'm' had
867 	 * a packet header, it would only be able to hold MHLEN bytes
868 	 * and m_data would have to be initialized differently.
869 	 */
870 	KASSERT((m->m_flags & M_PKTHDR) == 0 && (m->m_flags & M_EXT) &&
871 	    m->m_ext.ext_type == EXT_PGS,
872             ("%s: m %p !M_EXT or !EXT_PGS or M_PKTHDR", __func__, m));
873 	KASSERT(m->m_len <= MLEN, ("m_len too large %p", m));
874 
875 	if (m->m_ext.ext_flags & EXT_FLAG_EMBREF) {
876 		refcnt = &m->m_ext.ext_count;
877 	} else {
878 		KASSERT(m->m_ext.ext_cnt != NULL,
879 		    ("%s: no refcounting pointer on %p", __func__, m));
880 		refcnt = m->m_ext.ext_cnt;
881 	}
882 
883 	if (*refcnt != 1)
884 		return (EBUSY);
885 
886 	/*
887 	 * Copy mbuf header and m_ext portion of 'm' to 'm_temp' to
888 	 * create a "fake" EXT_PGS mbuf that can be used with
889 	 * m_copydata() as well as the ext_free callback.
890 	 */
891 	memcpy(&m_temp, m, offsetof(struct mbuf, m_ext) + sizeof (m->m_ext));
892 	m_temp.m_next = NULL;
893 	m_temp.m_nextpkt = NULL;
894 
895 	/* Turn 'm' into a "normal" mbuf. */
896 	m->m_flags &= ~(M_EXT | M_RDONLY | M_NOMAP);
897 	m->m_data = m->m_dat;
898 
899 	/* Copy data from template's ext_pgs. */
900 	m_copydata(&m_temp, 0, m_temp.m_len, mtod(m, caddr_t));
901 
902 	/* Free the backing pages. */
903 	m_temp.m_ext.ext_free(&m_temp);
904 
905 	/* Finally, free the ext_pgs struct. */
906 	uma_zfree(zone_extpgs, m_temp.m_ext.ext_pgs);
907 	return (0);
908 }
909 
910 /*
911  * These next few routines are used to permit downgrading an unmapped
912  * mbuf to a chain of mapped mbufs.  This is used when an interface
913  * doesn't supported unmapped mbufs or if checksums need to be
914  * computed in software.
915  *
916  * Each unmapped mbuf is converted to a chain of mbufs.  First, any
917  * TLS header data is stored in a regular mbuf.  Second, each page of
918  * unmapped data is stored in an mbuf with an EXT_SFBUF external
919  * cluster.  These mbufs use an sf_buf to provide a valid KVA for the
920  * associated physical page.  They also hold a reference on the
921  * original EXT_PGS mbuf to ensure the physical page doesn't go away.
922  * Finally, any TLS trailer data is stored in a regular mbuf.
923  *
924  * mb_unmapped_free_mext() is the ext_free handler for the EXT_SFBUF
925  * mbufs.  It frees the associated sf_buf and releases its reference
926  * on the original EXT_PGS mbuf.
927  *
928  * _mb_unmapped_to_ext() is a helper function that converts a single
929  * unmapped mbuf into a chain of mbufs.
930  *
931  * mb_unmapped_to_ext() is the public function that walks an mbuf
932  * chain converting any unmapped mbufs to mapped mbufs.  It returns
933  * the new chain of unmapped mbufs on success.  On failure it frees
934  * the original mbuf chain and returns NULL.
935  */
936 static void
937 mb_unmapped_free_mext(struct mbuf *m)
938 {
939 	struct sf_buf *sf;
940 	struct mbuf *old_m;
941 
942 	sf = m->m_ext.ext_arg1;
943 	sf_buf_free(sf);
944 
945 	/* Drop the reference on the backing EXT_PGS mbuf. */
946 	old_m = m->m_ext.ext_arg2;
947 	mb_free_ext(old_m);
948 }
949 
950 static struct mbuf *
951 _mb_unmapped_to_ext(struct mbuf *m)
952 {
953 	struct mbuf_ext_pgs *ext_pgs;
954 	struct mbuf *m_new, *top, *prev, *mref;
955 	struct sf_buf *sf;
956 	vm_page_t pg;
957 	int i, len, off, pglen, pgoff, seglen, segoff;
958 	volatile u_int *refcnt;
959 	u_int ref_inc = 0;
960 
961 	MBUF_EXT_PGS_ASSERT(m);
962 	ext_pgs = m->m_ext.ext_pgs;
963 	len = m->m_len;
964 	KASSERT(ext_pgs->tls == NULL, ("%s: can't convert TLS mbuf %p",
965 	    __func__, m));
966 
967 	/* See if this is the mbuf that holds the embedded refcount. */
968 	if (m->m_ext.ext_flags & EXT_FLAG_EMBREF) {
969 		refcnt = &m->m_ext.ext_count;
970 		mref = m;
971 	} else {
972 		KASSERT(m->m_ext.ext_cnt != NULL,
973 		    ("%s: no refcounting pointer on %p", __func__, m));
974 		refcnt = m->m_ext.ext_cnt;
975 		mref = __containerof(refcnt, struct mbuf, m_ext.ext_count);
976 	}
977 
978 	/* Skip over any data removed from the front. */
979 	off = mtod(m, vm_offset_t);
980 
981 	top = NULL;
982 	if (ext_pgs->hdr_len != 0) {
983 		if (off >= ext_pgs->hdr_len) {
984 			off -= ext_pgs->hdr_len;
985 		} else {
986 			seglen = ext_pgs->hdr_len - off;
987 			segoff = off;
988 			seglen = min(seglen, len);
989 			off = 0;
990 			len -= seglen;
991 			m_new = m_get(M_NOWAIT, MT_DATA);
992 			if (m_new == NULL)
993 				goto fail;
994 			m_new->m_len = seglen;
995 			prev = top = m_new;
996 			memcpy(mtod(m_new, void *), &ext_pgs->hdr[segoff],
997 			    seglen);
998 		}
999 	}
1000 	pgoff = ext_pgs->first_pg_off;
1001 	for (i = 0; i < ext_pgs->npgs && len > 0; i++) {
1002 		pglen = mbuf_ext_pg_len(ext_pgs, i, pgoff);
1003 		if (off >= pglen) {
1004 			off -= pglen;
1005 			pgoff = 0;
1006 			continue;
1007 		}
1008 		seglen = pglen - off;
1009 		segoff = pgoff + off;
1010 		off = 0;
1011 		seglen = min(seglen, len);
1012 		len -= seglen;
1013 
1014 		pg = PHYS_TO_VM_PAGE(ext_pgs->pa[i]);
1015 		m_new = m_get(M_NOWAIT, MT_DATA);
1016 		if (m_new == NULL)
1017 			goto fail;
1018 		if (top == NULL) {
1019 			top = prev = m_new;
1020 		} else {
1021 			prev->m_next = m_new;
1022 			prev = m_new;
1023 		}
1024 		sf = sf_buf_alloc(pg, SFB_NOWAIT);
1025 		if (sf == NULL)
1026 			goto fail;
1027 
1028 		ref_inc++;
1029 		m_extadd(m_new, (char *)sf_buf_kva(sf), PAGE_SIZE,
1030 		    mb_unmapped_free_mext, sf, mref, M_RDONLY, EXT_SFBUF);
1031 		m_new->m_data += segoff;
1032 		m_new->m_len = seglen;
1033 
1034 		pgoff = 0;
1035 	};
1036 	if (len != 0) {
1037 		KASSERT((off + len) <= ext_pgs->trail_len,
1038 		    ("off + len > trail (%d + %d > %d)", off, len,
1039 		    ext_pgs->trail_len));
1040 		m_new = m_get(M_NOWAIT, MT_DATA);
1041 		if (m_new == NULL)
1042 			goto fail;
1043 		if (top == NULL)
1044 			top = m_new;
1045 		else
1046 			prev->m_next = m_new;
1047 		m_new->m_len = len;
1048 		memcpy(mtod(m_new, void *), &ext_pgs->trail[off], len);
1049 	}
1050 
1051 	if (ref_inc != 0) {
1052 		/*
1053 		 * Obtain an additional reference on the old mbuf for
1054 		 * each created EXT_SFBUF mbuf.  They will be dropped
1055 		 * in mb_unmapped_free_mext().
1056 		 */
1057 		if (*refcnt == 1)
1058 			*refcnt += ref_inc;
1059 		else
1060 			atomic_add_int(refcnt, ref_inc);
1061 	}
1062 	m_free(m);
1063 	return (top);
1064 
1065 fail:
1066 	if (ref_inc != 0) {
1067 		/*
1068 		 * Obtain an additional reference on the old mbuf for
1069 		 * each created EXT_SFBUF mbuf.  They will be
1070 		 * immediately dropped when these mbufs are freed
1071 		 * below.
1072 		 */
1073 		if (*refcnt == 1)
1074 			*refcnt += ref_inc;
1075 		else
1076 			atomic_add_int(refcnt, ref_inc);
1077 	}
1078 	m_free(m);
1079 	m_freem(top);
1080 	return (NULL);
1081 }
1082 
1083 struct mbuf *
1084 mb_unmapped_to_ext(struct mbuf *top)
1085 {
1086 	struct mbuf *m, *next, *prev = NULL;
1087 
1088 	prev = NULL;
1089 	for (m = top; m != NULL; m = next) {
1090 		/* m might be freed, so cache the next pointer. */
1091 		next = m->m_next;
1092 		if (m->m_flags & M_NOMAP) {
1093 			if (prev != NULL) {
1094 				/*
1095 				 * Remove 'm' from the new chain so
1096 				 * that the 'top' chain terminates
1097 				 * before 'm' in case 'top' is freed
1098 				 * due to an error.
1099 				 */
1100 				prev->m_next = NULL;
1101 			}
1102 			m = _mb_unmapped_to_ext(m);
1103 			if (m == NULL) {
1104 				m_freem(top);
1105 				m_freem(next);
1106 				return (NULL);
1107 			}
1108 			if (prev == NULL) {
1109 				top = m;
1110 			} else {
1111 				prev->m_next = m;
1112 			}
1113 
1114 			/*
1115 			 * Replaced one mbuf with a chain, so we must
1116 			 * find the end of chain.
1117 			 */
1118 			prev = m_last(m);
1119 		} else {
1120 			if (prev != NULL) {
1121 				prev->m_next = m;
1122 			}
1123 			prev = m;
1124 		}
1125 	}
1126 	return (top);
1127 }
1128 
1129 /*
1130  * Allocate an empty EXT_PGS mbuf.  The ext_free routine is
1131  * responsible for freeing any pages backing this mbuf when it is
1132  * freed.
1133  */
1134 struct mbuf *
1135 mb_alloc_ext_pgs(int how, bool pkthdr, m_ext_free_t ext_free)
1136 {
1137 	struct mbuf *m;
1138 	struct mbuf_ext_pgs *ext_pgs;
1139 
1140 	if (pkthdr)
1141 		m = m_gethdr(how, MT_DATA);
1142 	else
1143 		m = m_get(how, MT_DATA);
1144 	if (m == NULL)
1145 		return (NULL);
1146 
1147 	ext_pgs = uma_zalloc(zone_extpgs, how);
1148 	if (ext_pgs == NULL) {
1149 		m_free(m);
1150 		return (NULL);
1151 	}
1152 	ext_pgs->npgs = 0;
1153 	ext_pgs->nrdy = 0;
1154 	ext_pgs->first_pg_off = 0;
1155 	ext_pgs->last_pg_len = 0;
1156 	ext_pgs->flags = 0;
1157 	ext_pgs->hdr_len = 0;
1158 	ext_pgs->trail_len = 0;
1159 	ext_pgs->tls = NULL;
1160 	ext_pgs->so = NULL;
1161 	m->m_data = NULL;
1162 	m->m_flags |= (M_EXT | M_RDONLY | M_NOMAP);
1163 	m->m_ext.ext_type = EXT_PGS;
1164 	m->m_ext.ext_flags = EXT_FLAG_EMBREF;
1165 	m->m_ext.ext_count = 1;
1166 	m->m_ext.ext_pgs = ext_pgs;
1167 	m->m_ext.ext_size = 0;
1168 	m->m_ext.ext_free = ext_free;
1169 	return (m);
1170 }
1171 
1172 #ifdef INVARIANT_SUPPORT
1173 void
1174 mb_ext_pgs_check(struct mbuf_ext_pgs *ext_pgs)
1175 {
1176 
1177 	/*
1178 	 * NB: This expects a non-empty buffer (npgs > 0 and
1179 	 * last_pg_len > 0).
1180 	 */
1181 	KASSERT(ext_pgs->npgs > 0,
1182 	    ("ext_pgs with no valid pages: %p", ext_pgs));
1183 	KASSERT(ext_pgs->npgs <= nitems(ext_pgs->pa),
1184 	    ("ext_pgs with too many pages: %p", ext_pgs));
1185 	KASSERT(ext_pgs->nrdy <= ext_pgs->npgs,
1186 	    ("ext_pgs with too many ready pages: %p", ext_pgs));
1187 	KASSERT(ext_pgs->first_pg_off < PAGE_SIZE,
1188 	    ("ext_pgs with too large page offset: %p", ext_pgs));
1189 	KASSERT(ext_pgs->last_pg_len > 0,
1190 	    ("ext_pgs with zero last page length: %p", ext_pgs));
1191 	KASSERT(ext_pgs->last_pg_len <= PAGE_SIZE,
1192 	    ("ext_pgs with too large last page length: %p", ext_pgs));
1193 	if (ext_pgs->npgs == 1) {
1194 		KASSERT(ext_pgs->first_pg_off + ext_pgs->last_pg_len <=
1195 		    PAGE_SIZE, ("ext_pgs with single page too large: %p",
1196 		    ext_pgs));
1197 	}
1198 	KASSERT(ext_pgs->hdr_len <= sizeof(ext_pgs->hdr),
1199 	    ("ext_pgs with too large header length: %p", ext_pgs));
1200 	KASSERT(ext_pgs->trail_len <= sizeof(ext_pgs->trail),
1201 	    ("ext_pgs with too large header length: %p", ext_pgs));
1202 }
1203 #endif
1204 
1205 /*
1206  * Clean up after mbufs with M_EXT storage attached to them if the
1207  * reference count hits 1.
1208  */
1209 void
1210 mb_free_ext(struct mbuf *m)
1211 {
1212 	volatile u_int *refcnt;
1213 	struct mbuf *mref;
1214 	int freembuf;
1215 
1216 	KASSERT(m->m_flags & M_EXT, ("%s: M_EXT not set on %p", __func__, m));
1217 
1218 	/* See if this is the mbuf that holds the embedded refcount. */
1219 	if (m->m_ext.ext_flags & EXT_FLAG_EMBREF) {
1220 		refcnt = &m->m_ext.ext_count;
1221 		mref = m;
1222 	} else {
1223 		KASSERT(m->m_ext.ext_cnt != NULL,
1224 		    ("%s: no refcounting pointer on %p", __func__, m));
1225 		refcnt = m->m_ext.ext_cnt;
1226 		mref = __containerof(refcnt, struct mbuf, m_ext.ext_count);
1227 	}
1228 
1229 	/*
1230 	 * Check if the header is embedded in the cluster.  It is
1231 	 * important that we can't touch any of the mbuf fields
1232 	 * after we have freed the external storage, since mbuf
1233 	 * could have been embedded in it.  For now, the mbufs
1234 	 * embedded into the cluster are always of type EXT_EXTREF,
1235 	 * and for this type we won't free the mref.
1236 	 */
1237 	if (m->m_flags & M_NOFREE) {
1238 		freembuf = 0;
1239 		KASSERT(m->m_ext.ext_type == EXT_EXTREF ||
1240 		    m->m_ext.ext_type == EXT_RXRING,
1241 		    ("%s: no-free mbuf %p has wrong type", __func__, m));
1242 	} else
1243 		freembuf = 1;
1244 
1245 	/* Free attached storage if this mbuf is the only reference to it. */
1246 	if (*refcnt == 1 || atomic_fetchadd_int(refcnt, -1) == 1) {
1247 		switch (m->m_ext.ext_type) {
1248 		case EXT_PACKET:
1249 			/* The packet zone is special. */
1250 			if (*refcnt == 0)
1251 				*refcnt = 1;
1252 			uma_zfree(zone_pack, mref);
1253 			break;
1254 		case EXT_CLUSTER:
1255 			uma_zfree(zone_clust, m->m_ext.ext_buf);
1256 			uma_zfree(zone_mbuf, mref);
1257 			break;
1258 		case EXT_JUMBOP:
1259 			uma_zfree(zone_jumbop, m->m_ext.ext_buf);
1260 			uma_zfree(zone_mbuf, mref);
1261 			break;
1262 		case EXT_JUMBO9:
1263 			uma_zfree(zone_jumbo9, m->m_ext.ext_buf);
1264 			uma_zfree(zone_mbuf, mref);
1265 			break;
1266 		case EXT_JUMBO16:
1267 			uma_zfree(zone_jumbo16, m->m_ext.ext_buf);
1268 			uma_zfree(zone_mbuf, mref);
1269 			break;
1270 		case EXT_PGS: {
1271 #ifdef KERN_TLS
1272 			struct mbuf_ext_pgs *pgs;
1273 			struct ktls_session *tls;
1274 #endif
1275 
1276 			KASSERT(mref->m_ext.ext_free != NULL,
1277 			    ("%s: ext_free not set", __func__));
1278 			mref->m_ext.ext_free(mref);
1279 #ifdef KERN_TLS
1280 			pgs = mref->m_ext.ext_pgs;
1281 			tls = pgs->tls;
1282 			if (tls != NULL &&
1283 			    !refcount_release_if_not_last(&tls->refcount))
1284 				ktls_enqueue_to_free(pgs);
1285 			else
1286 #endif
1287 				uma_zfree(zone_extpgs, mref->m_ext.ext_pgs);
1288 			uma_zfree(zone_mbuf, mref);
1289 			break;
1290 		}
1291 		case EXT_SFBUF:
1292 		case EXT_NET_DRV:
1293 		case EXT_MOD_TYPE:
1294 		case EXT_DISPOSABLE:
1295 			KASSERT(mref->m_ext.ext_free != NULL,
1296 			    ("%s: ext_free not set", __func__));
1297 			mref->m_ext.ext_free(mref);
1298 			uma_zfree(zone_mbuf, mref);
1299 			break;
1300 		case EXT_EXTREF:
1301 			KASSERT(m->m_ext.ext_free != NULL,
1302 			    ("%s: ext_free not set", __func__));
1303 			m->m_ext.ext_free(m);
1304 			break;
1305 		case EXT_RXRING:
1306 			KASSERT(m->m_ext.ext_free == NULL,
1307 			    ("%s: ext_free is set", __func__));
1308 			break;
1309 		default:
1310 			KASSERT(m->m_ext.ext_type == 0,
1311 			    ("%s: unknown ext_type", __func__));
1312 		}
1313 	}
1314 
1315 	if (freembuf && m != mref)
1316 		uma_zfree(zone_mbuf, m);
1317 }
1318 
1319 /*
1320  * Official mbuf(9) allocation KPI for stack and drivers:
1321  *
1322  * m_get()	- a single mbuf without any attachments, sys/mbuf.h.
1323  * m_gethdr()	- a single mbuf initialized as M_PKTHDR, sys/mbuf.h.
1324  * m_getcl()	- an mbuf + 2k cluster, sys/mbuf.h.
1325  * m_clget()	- attach cluster to already allocated mbuf.
1326  * m_cljget()	- attach jumbo cluster to already allocated mbuf.
1327  * m_get2()	- allocate minimum mbuf that would fit size argument.
1328  * m_getm2()	- allocate a chain of mbufs/clusters.
1329  * m_extadd()	- attach external cluster to mbuf.
1330  *
1331  * m_free()	- free single mbuf with its tags and ext, sys/mbuf.h.
1332  * m_freem()	- free chain of mbufs.
1333  */
1334 
1335 int
1336 m_clget(struct mbuf *m, int how)
1337 {
1338 
1339 	KASSERT((m->m_flags & M_EXT) == 0, ("%s: mbuf %p has M_EXT",
1340 	    __func__, m));
1341 	m->m_ext.ext_buf = (char *)NULL;
1342 	uma_zalloc_arg(zone_clust, m, how);
1343 	/*
1344 	 * On a cluster allocation failure, drain the packet zone and retry,
1345 	 * we might be able to loosen a few clusters up on the drain.
1346 	 */
1347 	if ((how & M_NOWAIT) && (m->m_ext.ext_buf == NULL)) {
1348 		uma_zone_reclaim(zone_pack, UMA_RECLAIM_DRAIN);
1349 		uma_zalloc_arg(zone_clust, m, how);
1350 	}
1351 	MBUF_PROBE2(m__clget, m, how);
1352 	return (m->m_flags & M_EXT);
1353 }
1354 
1355 /*
1356  * m_cljget() is different from m_clget() as it can allocate clusters without
1357  * attaching them to an mbuf.  In that case the return value is the pointer
1358  * to the cluster of the requested size.  If an mbuf was specified, it gets
1359  * the cluster attached to it and the return value can be safely ignored.
1360  * For size it takes MCLBYTES, MJUMPAGESIZE, MJUM9BYTES, MJUM16BYTES.
1361  */
1362 void *
1363 m_cljget(struct mbuf *m, int how, int size)
1364 {
1365 	uma_zone_t zone;
1366 	void *retval;
1367 
1368 	if (m != NULL) {
1369 		KASSERT((m->m_flags & M_EXT) == 0, ("%s: mbuf %p has M_EXT",
1370 		    __func__, m));
1371 		m->m_ext.ext_buf = NULL;
1372 	}
1373 
1374 	zone = m_getzone(size);
1375 	retval = uma_zalloc_arg(zone, m, how);
1376 
1377 	MBUF_PROBE4(m__cljget, m, how, size, retval);
1378 
1379 	return (retval);
1380 }
1381 
1382 /*
1383  * m_get2() allocates minimum mbuf that would fit "size" argument.
1384  */
1385 struct mbuf *
1386 m_get2(int size, int how, short type, int flags)
1387 {
1388 	struct mb_args args;
1389 	struct mbuf *m, *n;
1390 
1391 	args.flags = flags;
1392 	args.type = type;
1393 
1394 	if (size <= MHLEN || (size <= MLEN && (flags & M_PKTHDR) == 0))
1395 		return (uma_zalloc_arg(zone_mbuf, &args, how));
1396 	if (size <= MCLBYTES)
1397 		return (uma_zalloc_arg(zone_pack, &args, how));
1398 
1399 	if (size > MJUMPAGESIZE)
1400 		return (NULL);
1401 
1402 	m = uma_zalloc_arg(zone_mbuf, &args, how);
1403 	if (m == NULL)
1404 		return (NULL);
1405 
1406 	n = uma_zalloc_arg(zone_jumbop, m, how);
1407 	if (n == NULL) {
1408 		uma_zfree(zone_mbuf, m);
1409 		return (NULL);
1410 	}
1411 
1412 	return (m);
1413 }
1414 
1415 /*
1416  * m_getjcl() returns an mbuf with a cluster of the specified size attached.
1417  * For size it takes MCLBYTES, MJUMPAGESIZE, MJUM9BYTES, MJUM16BYTES.
1418  */
1419 struct mbuf *
1420 m_getjcl(int how, short type, int flags, int size)
1421 {
1422 	struct mb_args args;
1423 	struct mbuf *m, *n;
1424 	uma_zone_t zone;
1425 
1426 	if (size == MCLBYTES)
1427 		return m_getcl(how, type, flags);
1428 
1429 	args.flags = flags;
1430 	args.type = type;
1431 
1432 	m = uma_zalloc_arg(zone_mbuf, &args, how);
1433 	if (m == NULL)
1434 		return (NULL);
1435 
1436 	zone = m_getzone(size);
1437 	n = uma_zalloc_arg(zone, m, how);
1438 	if (n == NULL) {
1439 		uma_zfree(zone_mbuf, m);
1440 		return (NULL);
1441 	}
1442 	return (m);
1443 }
1444 
1445 /*
1446  * Allocate a given length worth of mbufs and/or clusters (whatever fits
1447  * best) and return a pointer to the top of the allocated chain.  If an
1448  * existing mbuf chain is provided, then we will append the new chain
1449  * to the existing one and return a pointer to the provided mbuf.
1450  */
1451 struct mbuf *
1452 m_getm2(struct mbuf *m, int len, int how, short type, int flags)
1453 {
1454 	struct mbuf *mb, *nm = NULL, *mtail = NULL;
1455 
1456 	KASSERT(len >= 0, ("%s: len is < 0", __func__));
1457 
1458 	/* Validate flags. */
1459 	flags &= (M_PKTHDR | M_EOR);
1460 
1461 	/* Packet header mbuf must be first in chain. */
1462 	if ((flags & M_PKTHDR) && m != NULL)
1463 		flags &= ~M_PKTHDR;
1464 
1465 	/* Loop and append maximum sized mbufs to the chain tail. */
1466 	while (len > 0) {
1467 		if (len > MCLBYTES)
1468 			mb = m_getjcl(how, type, (flags & M_PKTHDR),
1469 			    MJUMPAGESIZE);
1470 		else if (len >= MINCLSIZE)
1471 			mb = m_getcl(how, type, (flags & M_PKTHDR));
1472 		else if (flags & M_PKTHDR)
1473 			mb = m_gethdr(how, type);
1474 		else
1475 			mb = m_get(how, type);
1476 
1477 		/* Fail the whole operation if one mbuf can't be allocated. */
1478 		if (mb == NULL) {
1479 			if (nm != NULL)
1480 				m_freem(nm);
1481 			return (NULL);
1482 		}
1483 
1484 		/* Book keeping. */
1485 		len -= M_SIZE(mb);
1486 		if (mtail != NULL)
1487 			mtail->m_next = mb;
1488 		else
1489 			nm = mb;
1490 		mtail = mb;
1491 		flags &= ~M_PKTHDR;	/* Only valid on the first mbuf. */
1492 	}
1493 	if (flags & M_EOR)
1494 		mtail->m_flags |= M_EOR;  /* Only valid on the last mbuf. */
1495 
1496 	/* If mbuf was supplied, append new chain to the end of it. */
1497 	if (m != NULL) {
1498 		for (mtail = m; mtail->m_next != NULL; mtail = mtail->m_next)
1499 			;
1500 		mtail->m_next = nm;
1501 		mtail->m_flags &= ~M_EOR;
1502 	} else
1503 		m = nm;
1504 
1505 	return (m);
1506 }
1507 
1508 /*-
1509  * Configure a provided mbuf to refer to the provided external storage
1510  * buffer and setup a reference count for said buffer.
1511  *
1512  * Arguments:
1513  *    mb     The existing mbuf to which to attach the provided buffer.
1514  *    buf    The address of the provided external storage buffer.
1515  *    size   The size of the provided buffer.
1516  *    freef  A pointer to a routine that is responsible for freeing the
1517  *           provided external storage buffer.
1518  *    args   A pointer to an argument structure (of any type) to be passed
1519  *           to the provided freef routine (may be NULL).
1520  *    flags  Any other flags to be passed to the provided mbuf.
1521  *    type   The type that the external storage buffer should be
1522  *           labeled with.
1523  *
1524  * Returns:
1525  *    Nothing.
1526  */
1527 void
1528 m_extadd(struct mbuf *mb, char *buf, u_int size, m_ext_free_t freef,
1529     void *arg1, void *arg2, int flags, int type)
1530 {
1531 
1532 	KASSERT(type != EXT_CLUSTER, ("%s: EXT_CLUSTER not allowed", __func__));
1533 
1534 	mb->m_flags |= (M_EXT | flags);
1535 	mb->m_ext.ext_buf = buf;
1536 	mb->m_data = mb->m_ext.ext_buf;
1537 	mb->m_ext.ext_size = size;
1538 	mb->m_ext.ext_free = freef;
1539 	mb->m_ext.ext_arg1 = arg1;
1540 	mb->m_ext.ext_arg2 = arg2;
1541 	mb->m_ext.ext_type = type;
1542 
1543 	if (type != EXT_EXTREF) {
1544 		mb->m_ext.ext_count = 1;
1545 		mb->m_ext.ext_flags = EXT_FLAG_EMBREF;
1546 	} else
1547 		mb->m_ext.ext_flags = 0;
1548 }
1549 
1550 /*
1551  * Free an entire chain of mbufs and associated external buffers, if
1552  * applicable.
1553  */
1554 void
1555 m_freem(struct mbuf *mb)
1556 {
1557 
1558 	MBUF_PROBE1(m__freem, mb);
1559 	while (mb != NULL)
1560 		mb = m_free(mb);
1561 }
1562 
1563 void
1564 m_snd_tag_init(struct m_snd_tag *mst, struct ifnet *ifp)
1565 {
1566 
1567 	if_ref(ifp);
1568 	mst->ifp = ifp;
1569 	refcount_init(&mst->refcount, 1);
1570 	counter_u64_add(snd_tag_count, 1);
1571 }
1572 
1573 void
1574 m_snd_tag_destroy(struct m_snd_tag *mst)
1575 {
1576 	struct ifnet *ifp;
1577 
1578 	ifp = mst->ifp;
1579 	ifp->if_snd_tag_free(mst);
1580 	if_rele(ifp);
1581 	counter_u64_add(snd_tag_count, -1);
1582 }
1583