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