xref: /freebsd/sys/kern/kern_mbuf.c (revision acd3428b7d3e94cef0e1881c868cb4b131d4ff41)
1 /*-
2  * Copyright (c) 2004, 2005,
3  * 	Bosko Milekic <bmilekic@FreeBSD.org>.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice unmodified, this list of conditions and the following
10  *    disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include "opt_mac.h"
32 #include "opt_param.h"
33 
34 #include <sys/param.h>
35 #include <sys/malloc.h>
36 #include <sys/systm.h>
37 #include <sys/mbuf.h>
38 #include <sys/domain.h>
39 #include <sys/eventhandler.h>
40 #include <sys/kernel.h>
41 #include <sys/protosw.h>
42 #include <sys/smp.h>
43 #include <sys/sysctl.h>
44 
45 #include <security/mac/mac_framework.h>
46 
47 #include <vm/vm.h>
48 #include <vm/vm_page.h>
49 #include <vm/uma.h>
50 #include <vm/uma_int.h>
51 #include <vm/uma_dbg.h>
52 
53 /*
54  * In FreeBSD, Mbufs and Mbuf Clusters are allocated from UMA
55  * Zones.
56  *
57  * Mbuf Clusters (2K, contiguous) are allocated from the Cluster
58  * Zone.  The Zone can be capped at kern.ipc.nmbclusters, if the
59  * administrator so desires.
60  *
61  * Mbufs are allocated from a UMA Master Zone called the Mbuf
62  * Zone.
63  *
64  * Additionally, FreeBSD provides a Packet Zone, which it
65  * configures as a Secondary Zone to the Mbuf Master Zone,
66  * thus sharing backend Slab kegs with the Mbuf Master Zone.
67  *
68  * Thus common-case allocations and locking are simplified:
69  *
70  *  m_clget()                m_getcl()
71  *    |                         |
72  *    |   .------------>[(Packet Cache)]    m_get(), m_gethdr()
73  *    |   |             [     Packet   ]            |
74  *  [(Cluster Cache)]   [    Secondary ]   [ (Mbuf Cache)     ]
75  *  [ Cluster Zone  ]   [     Zone     ]   [ Mbuf Master Zone ]
76  *        |                       \________         |
77  *  [ Cluster Keg   ]                      \       /
78  *        |    	                         [ Mbuf Keg   ]
79  *  [ Cluster Slabs ]                         |
80  *        |                              [ Mbuf Slabs ]
81  *         \____________(VM)_________________/
82  *
83  *
84  * Whenever an object is allocated with uma_zalloc() out of
85  * one of the Zones its _ctor_ function is executed.  The same
86  * for any deallocation through uma_zfree() the _dtor_ function
87  * is executed.
88  *
89  * Caches are per-CPU and are filled from the Master Zone.
90  *
91  * Whenever an object is allocated from the underlying global
92  * memory pool it gets pre-initialized with the _zinit_ functions.
93  * When the Keg's are overfull objects get decomissioned with
94  * _zfini_ functions and free'd back to the global memory pool.
95  *
96  */
97 
98 int nmbclusters;		/* limits number of mbuf clusters */
99 int nmbjumbop;			/* limits number of page size jumbo clusters */
100 int nmbjumbo9;			/* limits number of 9k jumbo clusters */
101 int nmbjumbo16;			/* limits number of 16k jumbo clusters */
102 struct mbstat mbstat;
103 
104 static void
105 tunable_mbinit(void *dummy)
106 {
107 
108 	/* This has to be done before VM init. */
109 	nmbclusters = 1024 + maxusers * 64;
110 	TUNABLE_INT_FETCH("kern.ipc.nmbclusters", &nmbclusters);
111 }
112 SYSINIT(tunable_mbinit, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_mbinit, NULL);
113 
114 /* XXX: These should be tuneables. Can't change UMA limits on the fly. */
115 static int
116 sysctl_nmbclusters(SYSCTL_HANDLER_ARGS)
117 {
118 	int error, newnmbclusters;
119 
120 	newnmbclusters = nmbclusters;
121 	error = sysctl_handle_int(oidp, &newnmbclusters, sizeof(int), req);
122 	if (error == 0 && req->newptr) {
123 		if (newnmbclusters > nmbclusters) {
124 			nmbclusters = newnmbclusters;
125 			uma_zone_set_max(zone_clust, nmbclusters);
126 			EVENTHANDLER_INVOKE(nmbclusters_change);
127 		} else
128 			error = EINVAL;
129 	}
130 	return (error);
131 }
132 SYSCTL_PROC(_kern_ipc, OID_AUTO, nmbclusters, CTLTYPE_INT|CTLFLAG_RW,
133 &nmbclusters, 0, sysctl_nmbclusters, "IU",
134     "Maximum number of mbuf clusters allowed");
135 SYSCTL_INT(_kern_ipc, OID_AUTO, nmbjumbop, CTLFLAG_RW, &nmbjumbop, 0,
136     "Maximum number of mbuf page size jumbo clusters allowed");
137 SYSCTL_INT(_kern_ipc, OID_AUTO, nmbjumbo9, CTLFLAG_RW, &nmbjumbo9, 0,
138     "Maximum number of mbuf 9k jumbo clusters allowed");
139 SYSCTL_INT(_kern_ipc, OID_AUTO, nmbjumbo16, CTLFLAG_RW, &nmbjumbo16, 0,
140     "Maximum number of mbuf 16k jumbo clusters allowed");
141 SYSCTL_STRUCT(_kern_ipc, OID_AUTO, mbstat, CTLFLAG_RD, &mbstat, mbstat,
142     "Mbuf general information and statistics");
143 
144 /*
145  * Zones from which we allocate.
146  */
147 uma_zone_t	zone_mbuf;
148 uma_zone_t	zone_clust;
149 uma_zone_t	zone_pack;
150 uma_zone_t	zone_jumbop;
151 uma_zone_t	zone_jumbo9;
152 uma_zone_t	zone_jumbo16;
153 uma_zone_t	zone_ext_refcnt;
154 
155 /*
156  * Local prototypes.
157  */
158 static int	mb_ctor_mbuf(void *, int, void *, int);
159 static int	mb_ctor_clust(void *, int, void *, int);
160 static int	mb_ctor_pack(void *, int, void *, int);
161 static void	mb_dtor_mbuf(void *, int, void *);
162 static void	mb_dtor_clust(void *, int, void *);
163 static void	mb_dtor_pack(void *, int, void *);
164 static int	mb_zinit_pack(void *, int, int);
165 static void	mb_zfini_pack(void *, int);
166 
167 static void	mb_reclaim(void *);
168 static void	mbuf_init(void *);
169 
170 /* Ensure that MSIZE doesn't break dtom() - it must be a power of 2 */
171 CTASSERT((((MSIZE - 1) ^ MSIZE) + 1) >> 1 == MSIZE);
172 
173 /*
174  * Initialize FreeBSD Network buffer allocation.
175  */
176 SYSINIT(mbuf, SI_SUB_MBUF, SI_ORDER_FIRST, mbuf_init, NULL)
177 static void
178 mbuf_init(void *dummy)
179 {
180 
181 	/*
182 	 * Configure UMA zones for Mbufs, Clusters, and Packets.
183 	 */
184 	zone_mbuf = uma_zcreate(MBUF_MEM_NAME, MSIZE,
185 	    mb_ctor_mbuf, mb_dtor_mbuf,
186 #ifdef INVARIANTS
187 	    trash_init, trash_fini,
188 #else
189 	    NULL, NULL,
190 #endif
191 	    MSIZE - 1, UMA_ZONE_MAXBUCKET);
192 
193 	zone_clust = uma_zcreate(MBUF_CLUSTER_MEM_NAME, MCLBYTES,
194 	    mb_ctor_clust, mb_dtor_clust,
195 #ifdef INVARIANTS
196 	    trash_init, trash_fini,
197 #else
198 	    NULL, NULL,
199 #endif
200 	    UMA_ALIGN_PTR, UMA_ZONE_REFCNT);
201 	if (nmbclusters > 0)
202 		uma_zone_set_max(zone_clust, nmbclusters);
203 
204 	zone_pack = uma_zsecond_create(MBUF_PACKET_MEM_NAME, mb_ctor_pack,
205 	    mb_dtor_pack, mb_zinit_pack, mb_zfini_pack, zone_mbuf);
206 
207 	/* Make jumbo frame zone too. Page size, 9k and 16k. */
208 	zone_jumbop = uma_zcreate(MBUF_JUMBOP_MEM_NAME, MJUMPAGESIZE,
209 	    mb_ctor_clust, mb_dtor_clust,
210 #ifdef INVARIANTS
211 	    trash_init, trash_fini,
212 #else
213 	    NULL, NULL,
214 #endif
215 	    UMA_ALIGN_PTR, UMA_ZONE_REFCNT);
216 	if (nmbjumbop > 0)
217 		uma_zone_set_max(zone_jumbop, nmbjumbop);
218 
219 	zone_jumbo9 = uma_zcreate(MBUF_JUMBO9_MEM_NAME, MJUM9BYTES,
220 	    mb_ctor_clust, mb_dtor_clust,
221 #ifdef INVARIANTS
222 	    trash_init, trash_fini,
223 #else
224 	    NULL, NULL,
225 #endif
226 	    UMA_ALIGN_PTR, UMA_ZONE_REFCNT);
227 	if (nmbjumbo9 > 0)
228 		uma_zone_set_max(zone_jumbo9, nmbjumbo9);
229 
230 	zone_jumbo16 = uma_zcreate(MBUF_JUMBO16_MEM_NAME, MJUM16BYTES,
231 	    mb_ctor_clust, mb_dtor_clust,
232 #ifdef INVARIANTS
233 	    trash_init, trash_fini,
234 #else
235 	    NULL, NULL,
236 #endif
237 	    UMA_ALIGN_PTR, UMA_ZONE_REFCNT);
238 	if (nmbjumbo16 > 0)
239 		uma_zone_set_max(zone_jumbo16, nmbjumbo16);
240 
241 	zone_ext_refcnt = uma_zcreate(MBUF_EXTREFCNT_MEM_NAME, sizeof(u_int),
242 	    NULL, NULL,
243 	    NULL, NULL,
244 	    UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
245 
246 	/* uma_prealloc() goes here... */
247 
248 	/*
249 	 * Hook event handler for low-memory situation, used to
250 	 * drain protocols and push data back to the caches (UMA
251 	 * later pushes it back to VM).
252 	 */
253 	EVENTHANDLER_REGISTER(vm_lowmem, mb_reclaim, NULL,
254 	    EVENTHANDLER_PRI_FIRST);
255 
256 	/*
257 	 * [Re]set counters and local statistics knobs.
258 	 * XXX Some of these should go and be replaced, but UMA stat
259 	 * gathering needs to be revised.
260 	 */
261 	mbstat.m_mbufs = 0;
262 	mbstat.m_mclusts = 0;
263 	mbstat.m_drain = 0;
264 	mbstat.m_msize = MSIZE;
265 	mbstat.m_mclbytes = MCLBYTES;
266 	mbstat.m_minclsize = MINCLSIZE;
267 	mbstat.m_mlen = MLEN;
268 	mbstat.m_mhlen = MHLEN;
269 	mbstat.m_numtypes = MT_NTYPES;
270 
271 	mbstat.m_mcfail = mbstat.m_mpfail = 0;
272 	mbstat.sf_iocnt = 0;
273 	mbstat.sf_allocwait = mbstat.sf_allocfail = 0;
274 }
275 
276 /*
277  * Constructor for Mbuf master zone.
278  *
279  * The 'arg' pointer points to a mb_args structure which
280  * contains call-specific information required to support the
281  * mbuf allocation API.  See mbuf.h.
282  */
283 static int
284 mb_ctor_mbuf(void *mem, int size, void *arg, int how)
285 {
286 	struct mbuf *m;
287 	struct mb_args *args;
288 #ifdef MAC
289 	int error;
290 #endif
291 	int flags;
292 	short type;
293 
294 #ifdef INVARIANTS
295 	trash_ctor(mem, size, arg, how);
296 #endif
297 	m = (struct mbuf *)mem;
298 	args = (struct mb_args *)arg;
299 	flags = args->flags;
300 	type = args->type;
301 
302 	/*
303 	 * The mbuf is initialized later.  The caller has the
304 	 * responsibility to set up any MAC labels too.
305 	 */
306 	if (type == MT_NOINIT)
307 		return (0);
308 
309 	m->m_next = NULL;
310 	m->m_nextpkt = NULL;
311 	m->m_len = 0;
312 	m->m_flags = flags;
313 	m->m_type = type;
314 	if (flags & M_PKTHDR) {
315 		m->m_data = m->m_pktdat;
316 		m->m_pkthdr.rcvif = NULL;
317 		m->m_pkthdr.len = 0;
318 		m->m_pkthdr.header = NULL;
319 		m->m_pkthdr.csum_flags = 0;
320 		m->m_pkthdr.csum_data = 0;
321 		m->m_pkthdr.tso_segsz = 0;
322 		m->m_pkthdr.ether_vtag = 0;
323 		SLIST_INIT(&m->m_pkthdr.tags);
324 #ifdef MAC
325 		/* If the label init fails, fail the alloc */
326 		error = mac_init_mbuf(m, how);
327 		if (error)
328 			return (error);
329 #endif
330 	} else
331 		m->m_data = m->m_dat;
332 	return (0);
333 }
334 
335 /*
336  * The Mbuf master zone destructor.
337  */
338 static void
339 mb_dtor_mbuf(void *mem, int size, void *arg)
340 {
341 	struct mbuf *m;
342 
343 	m = (struct mbuf *)mem;
344 	if ((m->m_flags & M_PKTHDR) != 0)
345 		m_tag_delete_chain(m, NULL);
346 	KASSERT((m->m_flags & M_EXT) == 0, ("%s: M_EXT set", __func__));
347 #ifdef INVARIANTS
348 	trash_dtor(mem, size, arg);
349 #endif
350 }
351 
352 /*
353  * The Mbuf Packet zone destructor.
354  */
355 static void
356 mb_dtor_pack(void *mem, int size, void *arg)
357 {
358 	struct mbuf *m;
359 
360 	m = (struct mbuf *)mem;
361 	if ((m->m_flags & M_PKTHDR) != 0)
362 		m_tag_delete_chain(m, NULL);
363 
364 	/* Make sure we've got a clean cluster back. */
365 	KASSERT((m->m_flags & M_EXT) == M_EXT, ("%s: M_EXT not set", __func__));
366 	KASSERT(m->m_ext.ext_buf != NULL, ("%s: ext_buf == NULL", __func__));
367 	KASSERT(m->m_ext.ext_free == NULL, ("%s: ext_free != NULL", __func__));
368 	KASSERT(m->m_ext.ext_args == NULL, ("%s: ext_args != NULL", __func__));
369 	KASSERT(m->m_ext.ext_size == MCLBYTES, ("%s: ext_size != MCLBYTES", __func__));
370 	KASSERT(m->m_ext.ext_type == EXT_PACKET, ("%s: ext_type != EXT_PACKET", __func__));
371 	KASSERT(*m->m_ext.ref_cnt == 1, ("%s: ref_cnt != 1", __func__));
372 #ifdef INVARIANTS
373 	trash_dtor(m->m_ext.ext_buf, MCLBYTES, arg);
374 #endif
375 }
376 
377 /*
378  * The Cluster and Jumbo[PAGESIZE|9|16] zone constructor.
379  *
380  * Here the 'arg' pointer points to the Mbuf which we
381  * are configuring cluster storage for.  If 'arg' is
382  * empty we allocate just the cluster without setting
383  * the mbuf to it.  See mbuf.h.
384  */
385 static int
386 mb_ctor_clust(void *mem, int size, void *arg, int how)
387 {
388 	struct mbuf *m;
389 	u_int *refcnt;
390 	int type = 0;
391 
392 #ifdef INVARIANTS
393 	trash_ctor(mem, size, arg, how);
394 #endif
395 	m = (struct mbuf *)arg;
396 	if (m != NULL) {
397 		switch (size) {
398 		case MCLBYTES:
399 			type = EXT_CLUSTER;
400 			break;
401 #if MJUMPAGESIZE != MCLBYTES
402 		case MJUMPAGESIZE:
403 			type = EXT_JUMBOP;
404 			break;
405 #endif
406 		case MJUM9BYTES:
407 			type = EXT_JUMBO9;
408 			break;
409 		case MJUM16BYTES:
410 			type = EXT_JUMBO16;
411 			break;
412 		default:
413 			panic("unknown cluster size");
414 			break;
415 		}
416 		m->m_ext.ext_buf = (caddr_t)mem;
417 		m->m_data = m->m_ext.ext_buf;
418 		m->m_flags |= M_EXT;
419 		m->m_ext.ext_free = NULL;
420 		m->m_ext.ext_args = NULL;
421 		m->m_ext.ext_size = size;
422 		m->m_ext.ext_type = type;
423 		m->m_ext.ref_cnt = uma_find_refcnt(zone_clust, mem);
424 		*m->m_ext.ref_cnt = 1;
425 	} else {
426 		refcnt =  uma_find_refcnt(zone_clust, mem);
427 		*refcnt = 1;
428 	}
429 	return (0);
430 }
431 
432 /*
433  * The Mbuf Cluster zone destructor.
434  */
435 static void
436 mb_dtor_clust(void *mem, int size, void *arg)
437 {
438 
439 	KASSERT(*(uma_find_refcnt(zone_clust, mem)) <= 1,
440 		("%s: refcnt incorrect %u", __func__,
441 		 *(uma_find_refcnt(zone_clust, mem))) );
442 #ifdef INVARIANTS
443 	trash_dtor(mem, size, arg);
444 #endif
445 }
446 
447 /*
448  * The Packet secondary zone's init routine, executed on the
449  * object's transition from mbuf keg slab to zone cache.
450  */
451 static int
452 mb_zinit_pack(void *mem, int size, int how)
453 {
454 	struct mbuf *m;
455 
456 	m = (struct mbuf *)mem;		/* m is virgin. */
457 	if (uma_zalloc_arg(zone_clust, m, how) == NULL ||
458 	    m->m_ext.ext_buf == NULL)
459 		return (ENOMEM);
460 	m->m_ext.ext_type = EXT_PACKET;	/* Override. */
461 #ifdef INVARIANTS
462 	trash_init(m->m_ext.ext_buf, MCLBYTES, how);
463 #endif
464 	return (0);
465 }
466 
467 /*
468  * The Packet secondary zone's fini routine, executed on the
469  * object's transition from zone cache to keg slab.
470  */
471 static void
472 mb_zfini_pack(void *mem, int size)
473 {
474 	struct mbuf *m;
475 
476 	m = (struct mbuf *)mem;
477 #ifdef INVARIANTS
478 	trash_fini(m->m_ext.ext_buf, MCLBYTES);
479 #endif
480 	uma_zfree_arg(zone_clust, m->m_ext.ext_buf, NULL);
481 #ifdef INVARIANTS
482 	trash_dtor(mem, size, NULL);
483 #endif
484 }
485 
486 /*
487  * The "packet" keg constructor.
488  */
489 static int
490 mb_ctor_pack(void *mem, int size, void *arg, int how)
491 {
492 	struct mbuf *m;
493 	struct mb_args *args;
494 #ifdef MAC
495 	int error;
496 #endif
497 	int flags;
498 	short type;
499 
500 	m = (struct mbuf *)mem;
501 	args = (struct mb_args *)arg;
502 	flags = args->flags;
503 	type = args->type;
504 
505 #ifdef INVARIANTS
506 	trash_ctor(m->m_ext.ext_buf, MCLBYTES, arg, how);
507 #endif
508 	m->m_next = NULL;
509 	m->m_nextpkt = NULL;
510 	m->m_data = m->m_ext.ext_buf;
511 	m->m_len = 0;
512 	m->m_flags = (flags | M_EXT);
513 	m->m_type = type;
514 
515 	if (flags & M_PKTHDR) {
516 		m->m_pkthdr.rcvif = NULL;
517 		m->m_pkthdr.len = 0;
518 		m->m_pkthdr.header = NULL;
519 		m->m_pkthdr.csum_flags = 0;
520 		m->m_pkthdr.csum_data = 0;
521 		m->m_pkthdr.tso_segsz = 0;
522 		m->m_pkthdr.ether_vtag = 0;
523 		SLIST_INIT(&m->m_pkthdr.tags);
524 #ifdef MAC
525 		/* If the label init fails, fail the alloc */
526 		error = mac_init_mbuf(m, how);
527 		if (error)
528 			return (error);
529 #endif
530 	}
531 	/* m_ext is already initialized. */
532 
533 	return (0);
534 }
535 
536 /*
537  * This is the protocol drain routine.
538  *
539  * No locks should be held when this is called.  The drain routines have to
540  * presently acquire some locks which raises the possibility of lock order
541  * reversal.
542  */
543 static void
544 mb_reclaim(void *junk)
545 {
546 	struct domain *dp;
547 	struct protosw *pr;
548 
549 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK | WARN_PANIC, NULL,
550 	    "mb_reclaim()");
551 
552 	for (dp = domains; dp != NULL; dp = dp->dom_next)
553 		for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++)
554 			if (pr->pr_drain != NULL)
555 				(*pr->pr_drain)();
556 }
557