xref: /freebsd/sys/kern/kern_mbuf.c (revision 282a3889ebf826db9839be296ff1dd903f6d6d6e)
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, 0, 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 	 * If there are processes blocked on zone_clust, waiting for pages to be freed up,
377 	 * cause them to be woken up by draining the packet zone. We are exposed to a race here
378 	 * (in the check for the UMA_ZFLAG_FULL) where we might miss the flag set, but that is
379 	 * deliberate. We don't want to acquire the zone lock for every mbuf free.
380 	 */
381  	if (uma_zone_exhausted_nolock(zone_clust))
382  		zone_drain(zone_pack);
383 }
384 
385 /*
386  * The Cluster and Jumbo[PAGESIZE|9|16] zone constructor.
387  *
388  * Here the 'arg' pointer points to the Mbuf which we
389  * are configuring cluster storage for.  If 'arg' is
390  * empty we allocate just the cluster without setting
391  * the mbuf to it.  See mbuf.h.
392  */
393 static int
394 mb_ctor_clust(void *mem, int size, void *arg, int how)
395 {
396 	struct mbuf *m;
397 	u_int *refcnt;
398 	int type;
399 	uma_zone_t zone;
400 
401 #ifdef INVARIANTS
402 	trash_ctor(mem, size, arg, how);
403 #endif
404 	switch (size) {
405 	case MCLBYTES:
406 		type = EXT_CLUSTER;
407 		zone = zone_clust;
408 		break;
409 #if MJUMPAGESIZE != MCLBYTES
410 	case MJUMPAGESIZE:
411 		type = EXT_JUMBOP;
412 		zone = zone_jumbop;
413 		break;
414 #endif
415 	case MJUM9BYTES:
416 		type = EXT_JUMBO9;
417 		zone = zone_jumbo9;
418 		break;
419 	case MJUM16BYTES:
420 		type = EXT_JUMBO16;
421 		zone = zone_jumbo16;
422 		break;
423 	default:
424 		panic("unknown cluster size");
425 		break;
426 	}
427 
428 	m = (struct mbuf *)arg;
429 	refcnt = uma_find_refcnt(zone, mem);
430 	*refcnt = 1;
431 	if (m != NULL) {
432 		m->m_ext.ext_buf = (caddr_t)mem;
433 		m->m_data = m->m_ext.ext_buf;
434 		m->m_flags |= M_EXT;
435 		m->m_ext.ext_free = NULL;
436 		m->m_ext.ext_args = NULL;
437 		m->m_ext.ext_size = size;
438 		m->m_ext.ext_type = type;
439 		m->m_ext.ref_cnt = refcnt;
440 	}
441 
442 	return (0);
443 }
444 
445 /*
446  * The Mbuf Cluster zone destructor.
447  */
448 static void
449 mb_dtor_clust(void *mem, int size, void *arg)
450 {
451 #ifdef INVARIANTS
452 	uma_zone_t zone;
453 
454 	zone = m_getzone(size);
455 	KASSERT(*(uma_find_refcnt(zone, mem)) <= 1,
456 		("%s: refcnt incorrect %u", __func__,
457 		 *(uma_find_refcnt(zone, mem))) );
458 
459 	trash_dtor(mem, size, arg);
460 #endif
461 }
462 
463 /*
464  * The Packet secondary zone's init routine, executed on the
465  * object's transition from mbuf keg slab to zone cache.
466  */
467 static int
468 mb_zinit_pack(void *mem, int size, int how)
469 {
470 	struct mbuf *m;
471 
472 	m = (struct mbuf *)mem;		/* m is virgin. */
473 	if (uma_zalloc_arg(zone_clust, m, how) == NULL ||
474 	    m->m_ext.ext_buf == NULL)
475 		return (ENOMEM);
476 	m->m_ext.ext_type = EXT_PACKET;	/* Override. */
477 #ifdef INVARIANTS
478 	trash_init(m->m_ext.ext_buf, MCLBYTES, how);
479 #endif
480 	return (0);
481 }
482 
483 /*
484  * The Packet secondary zone's fini routine, executed on the
485  * object's transition from zone cache to keg slab.
486  */
487 static void
488 mb_zfini_pack(void *mem, int size)
489 {
490 	struct mbuf *m;
491 
492 	m = (struct mbuf *)mem;
493 #ifdef INVARIANTS
494 	trash_fini(m->m_ext.ext_buf, MCLBYTES);
495 #endif
496 	uma_zfree_arg(zone_clust, m->m_ext.ext_buf, NULL);
497 #ifdef INVARIANTS
498 	trash_dtor(mem, size, NULL);
499 #endif
500 }
501 
502 /*
503  * The "packet" keg constructor.
504  */
505 static int
506 mb_ctor_pack(void *mem, int size, void *arg, int how)
507 {
508 	struct mbuf *m;
509 	struct mb_args *args;
510 #ifdef MAC
511 	int error;
512 #endif
513 	int flags;
514 	short type;
515 
516 	m = (struct mbuf *)mem;
517 	args = (struct mb_args *)arg;
518 	flags = args->flags;
519 	type = args->type;
520 
521 #ifdef INVARIANTS
522 	trash_ctor(m->m_ext.ext_buf, MCLBYTES, arg, how);
523 #endif
524 	m->m_next = NULL;
525 	m->m_nextpkt = NULL;
526 	m->m_data = m->m_ext.ext_buf;
527 	m->m_len = 0;
528 	m->m_flags = (flags | M_EXT);
529 	m->m_type = type;
530 
531 	if (flags & M_PKTHDR) {
532 		m->m_pkthdr.rcvif = NULL;
533 		m->m_pkthdr.len = 0;
534 		m->m_pkthdr.header = NULL;
535 		m->m_pkthdr.csum_flags = 0;
536 		m->m_pkthdr.csum_data = 0;
537 		m->m_pkthdr.tso_segsz = 0;
538 		m->m_pkthdr.ether_vtag = 0;
539 		SLIST_INIT(&m->m_pkthdr.tags);
540 #ifdef MAC
541 		/* If the label init fails, fail the alloc */
542 		error = mac_init_mbuf(m, how);
543 		if (error)
544 			return (error);
545 #endif
546 	}
547 	/* m_ext is already initialized. */
548 
549 	return (0);
550 }
551 
552 /*
553  * This is the protocol drain routine.
554  *
555  * No locks should be held when this is called.  The drain routines have to
556  * presently acquire some locks which raises the possibility of lock order
557  * reversal.
558  */
559 static void
560 mb_reclaim(void *junk)
561 {
562 	struct domain *dp;
563 	struct protosw *pr;
564 
565 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK | WARN_PANIC, NULL,
566 	    "mb_reclaim()");
567 
568 	for (dp = domains; dp != NULL; dp = dp->dom_next)
569 		for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++)
570 			if (pr->pr_drain != NULL)
571 				(*pr->pr_drain)();
572 }
573