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