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