4 * Copyright (c) 2004 Jeffrey M. Hsu. All rights reserved.
5 * Copyright (c) 2004 The DragonFly Project. All rights reserved.
7 * This code is derived from software contributed to The DragonFly Project
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of The DragonFly Project nor the names of its
19 * contributors may be used to endorse or promote products derived
20 * from this software without specific, prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * Copyright (c) 1982, 1986, 1988, 1991, 1993
38 * The Regents of the University of California. All rights reserved.
40 * Redistribution and use in source and binary forms, with or without
41 * modification, are permitted provided that the following conditions
43 * 1. Redistributions of source code must retain the above copyright
44 * notice, this list of conditions and the following disclaimer.
45 * 2. Redistributions in binary form must reproduce the above copyright
46 * notice, this list of conditions and the following disclaimer in the
47 * documentation and/or other materials provided with the distribution.
48 * 3. Neither the name of the University nor the names of its contributors
49 * may be used to endorse or promote products derived from this software
50 * without specific prior written permission.
52 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
53 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
55 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
56 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
57 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
58 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
59 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
60 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
61 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64 * @(#)uipc_mbuf.c 8.2 (Berkeley) 1/4/94
65 * $FreeBSD: src/sys/kern/uipc_mbuf.c,v 1.51.2.24 2003/04/15 06:59:29 silby Exp $
68 #include "opt_param.h"
69 #include "opt_mbuf_stress_test.h"
70 #include <sys/param.h>
71 #include <sys/systm.h>
73 #include <sys/malloc.h>
75 #include <sys/kernel.h>
76 #include <sys/sysctl.h>
77 #include <sys/domain.h>
78 #include <sys/objcache.h>
80 #include <sys/protosw.h>
82 #include <sys/thread.h>
83 #include <sys/globaldata.h>
85 #include <sys/thread2.h>
86 #include <sys/spinlock2.h>
88 #include <machine/atomic.h>
89 #include <machine/limits.h>
92 #include <vm/vm_kern.h>
93 #include <vm/vm_extern.h>
96 #include <machine/cpu.h>
100 * mbuf cluster meta-data
108 * mbuf tracking for debugging purposes
112 static MALLOC_DEFINE(M_MTRACK, "mtrack", "mtrack");
115 RB_HEAD(mbuf_rb_tree, mbtrack);
116 RB_PROTOTYPE2(mbuf_rb_tree, mbtrack, rb_node, mbtrack_cmp, struct mbuf *);
119 RB_ENTRY(mbtrack) rb_node;
125 mbtrack_cmp(struct mbtrack *mb1, struct mbtrack *mb2)
134 RB_GENERATE2(mbuf_rb_tree, mbtrack, rb_node, mbtrack_cmp, struct mbuf *, m);
136 struct mbuf_rb_tree mbuf_track_root;
137 static struct spinlock mbuf_track_spin = SPINLOCK_INITIALIZER(mbuf_track_spin);
140 mbuftrack(struct mbuf *m)
144 mbt = kmalloc(sizeof(*mbt), M_MTRACK, M_INTWAIT|M_ZERO);
145 spin_lock(&mbuf_track_spin);
147 if (mbuf_rb_tree_RB_INSERT(&mbuf_track_root, mbt)) {
148 spin_unlock(&mbuf_track_spin);
149 panic("mbuftrack: mbuf %p already being tracked", m);
151 spin_unlock(&mbuf_track_spin);
155 mbufuntrack(struct mbuf *m)
159 spin_lock(&mbuf_track_spin);
160 mbt = mbuf_rb_tree_RB_LOOKUP(&mbuf_track_root, m);
162 spin_unlock(&mbuf_track_spin);
163 panic("mbufuntrack: mbuf %p was not tracked", m);
165 mbuf_rb_tree_RB_REMOVE(&mbuf_track_root, mbt);
166 spin_unlock(&mbuf_track_spin);
167 kfree(mbt, M_MTRACK);
172 mbuftrackid(struct mbuf *m, int trackid)
177 spin_lock(&mbuf_track_spin);
181 mbt = mbuf_rb_tree_RB_LOOKUP(&mbuf_track_root, m);
183 spin_unlock(&mbuf_track_spin);
184 panic("mbuftrackid: mbuf %p not tracked", m);
186 mbt->trackid = trackid;
191 spin_unlock(&mbuf_track_spin);
195 mbuftrack_callback(struct mbtrack *mbt, void *arg)
197 struct sysctl_req *req = arg;
201 ksnprintf(buf, sizeof(buf), "mbuf %p track %d\n", mbt->m, mbt->trackid);
203 spin_unlock(&mbuf_track_spin);
204 error = SYSCTL_OUT(req, buf, strlen(buf));
205 spin_lock(&mbuf_track_spin);
212 mbuftrack_show(SYSCTL_HANDLER_ARGS)
216 spin_lock(&mbuf_track_spin);
217 error = mbuf_rb_tree_RB_SCAN(&mbuf_track_root, NULL,
218 mbuftrack_callback, req);
219 spin_unlock(&mbuf_track_spin);
222 SYSCTL_PROC(_kern_ipc, OID_AUTO, showmbufs, CTLFLAG_RD|CTLTYPE_STRING,
223 0, 0, mbuftrack_show, "A", "Show all in-use mbufs");
228 #define mbufuntrack(m)
232 static void mbinit(void *);
233 SYSINIT(mbuf, SI_BOOT2_MACHDEP, SI_ORDER_FIRST, mbinit, NULL)
235 struct mbtypes_stat {
236 u_long stats[MT_NTYPES];
239 static struct mbtypes_stat mbtypes[SMP_MAXCPU];
241 static struct mbstat mbstat[SMP_MAXCPU] __cachealign;
250 #ifdef MBUF_STRESS_TEST
251 int m_defragrandomfailures;
254 struct objcache *mbuf_cache, *mbufphdr_cache;
255 struct objcache *mclmeta_cache, *mjclmeta_cache;
256 struct objcache *mbufcluster_cache, *mbufphdrcluster_cache;
257 struct objcache *mbufjcluster_cache, *mbufphdrjcluster_cache;
260 static int nmbjclusters;
263 static int mclph_cachefrac;
264 static int mcl_cachefrac;
266 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RW,
267 &max_linkhdr, 0, "Max size of a link-level header");
268 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RW,
269 &max_protohdr, 0, "Max size of a protocol header");
270 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RW, &max_hdr, 0,
271 "Max size of link+protocol headers");
272 SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RW,
273 &max_datalen, 0, "Max data payload size without headers");
274 SYSCTL_INT(_kern_ipc, OID_AUTO, mbuf_wait, CTLFLAG_RW,
275 &mbuf_wait, 0, "Time in ticks to sleep after failed mbuf allocations");
276 static int do_mbstat(SYSCTL_HANDLER_ARGS);
278 SYSCTL_PROC(_kern_ipc, KIPC_MBSTAT, mbstat, CTLTYPE_STRUCT|CTLFLAG_RD,
279 0, 0, do_mbstat, "S,mbstat", "mbuf usage statistics");
281 static int do_mbtypes(SYSCTL_HANDLER_ARGS);
283 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbtypes, CTLTYPE_ULONG|CTLFLAG_RD,
284 0, 0, do_mbtypes, "LU", "");
287 do_mbstat(SYSCTL_HANDLER_ARGS)
289 struct mbstat mbstat_total;
290 struct mbstat *mbstat_totalp;
293 bzero(&mbstat_total, sizeof(mbstat_total));
294 mbstat_totalp = &mbstat_total;
296 for (i = 0; i < ncpus; i++)
298 mbstat_total.m_mbufs += mbstat[i].m_mbufs;
299 mbstat_total.m_clusters += mbstat[i].m_clusters;
300 mbstat_total.m_jclusters += mbstat[i].m_jclusters;
301 mbstat_total.m_clfree += mbstat[i].m_clfree;
302 mbstat_total.m_drops += mbstat[i].m_drops;
303 mbstat_total.m_wait += mbstat[i].m_wait;
304 mbstat_total.m_drain += mbstat[i].m_drain;
305 mbstat_total.m_mcfail += mbstat[i].m_mcfail;
306 mbstat_total.m_mpfail += mbstat[i].m_mpfail;
310 * The following fields are not cumulative fields so just
311 * get their values once.
313 mbstat_total.m_msize = mbstat[0].m_msize;
314 mbstat_total.m_mclbytes = mbstat[0].m_mclbytes;
315 mbstat_total.m_minclsize = mbstat[0].m_minclsize;
316 mbstat_total.m_mlen = mbstat[0].m_mlen;
317 mbstat_total.m_mhlen = mbstat[0].m_mhlen;
319 return(sysctl_handle_opaque(oidp, mbstat_totalp, sizeof(mbstat_total), req));
323 do_mbtypes(SYSCTL_HANDLER_ARGS)
325 u_long totals[MT_NTYPES];
328 for (i = 0; i < MT_NTYPES; i++)
331 for (i = 0; i < ncpus; i++)
333 for (j = 0; j < MT_NTYPES; j++)
334 totals[j] += mbtypes[i].stats[j];
337 return(sysctl_handle_opaque(oidp, totals, sizeof(totals), req));
341 * These are read-only because we do not currently have any code
342 * to adjust the objcache limits after the fact. The variables
343 * may only be set as boot-time tunables.
345 SYSCTL_INT(_kern_ipc, KIPC_NMBCLUSTERS, nmbclusters, CTLFLAG_RD,
346 &nmbclusters, 0, "Maximum number of mbuf clusters available");
347 SYSCTL_INT(_kern_ipc, OID_AUTO, nmbufs, CTLFLAG_RD, &nmbufs, 0,
348 "Maximum number of mbufs available");
349 SYSCTL_INT(_kern_ipc, OID_AUTO, nmbjclusters, CTLFLAG_RD, &nmbjclusters, 0,
350 "Maximum number of mbuf jclusters available");
351 SYSCTL_INT(_kern_ipc, OID_AUTO, mclph_cachefrac, CTLFLAG_RD,
353 "Fraction of cacheable mbuf clusters w/ pkthdr");
354 SYSCTL_INT(_kern_ipc, OID_AUTO, mcl_cachefrac, CTLFLAG_RD,
355 &mcl_cachefrac, 0, "Fraction of cacheable mbuf clusters");
357 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
358 &m_defragpackets, 0, "Number of defragment packets");
359 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
360 &m_defragbytes, 0, "Number of defragment bytes");
361 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
362 &m_defraguseless, 0, "Number of useless defragment mbuf chain operations");
363 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
364 &m_defragfailure, 0, "Number of failed defragment mbuf chain operations");
365 #ifdef MBUF_STRESS_TEST
366 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
367 &m_defragrandomfailures, 0, "");
370 static MALLOC_DEFINE(M_MBUF, "mbuf", "mbuf");
371 static MALLOC_DEFINE(M_MBUFCL, "mbufcl", "mbufcl");
372 static MALLOC_DEFINE(M_MCLMETA, "mclmeta", "mclmeta");
374 static void m_reclaim (void);
375 static void m_mclref(void *arg);
376 static void m_mclfree(void *arg);
377 static void m_mjclfree(void *arg);
380 * NOTE: Default NMBUFS must take into account a possible DOS attack
381 * using fd passing on unix domain sockets.
384 #define NMBCLUSTERS (512 + maxusers * 16)
386 #ifndef MCLPH_CACHEFRAC
387 #define MCLPH_CACHEFRAC 16
389 #ifndef MCL_CACHEFRAC
390 #define MCL_CACHEFRAC 4
393 #define NMBJCLUSTERS (NMBCLUSTERS / 2)
396 #define NMBUFS (nmbclusters * 2 + maxfiles)
400 * Perform sanity checks of tunables declared above.
403 tunable_mbinit(void *dummy)
406 * This has to be done before VM init.
408 nmbclusters = NMBCLUSTERS;
409 TUNABLE_INT_FETCH("kern.ipc.nmbclusters", &nmbclusters);
410 mclph_cachefrac = MCLPH_CACHEFRAC;
411 TUNABLE_INT_FETCH("kern.ipc.mclph_cachefrac", &mclph_cachefrac);
412 mcl_cachefrac = MCL_CACHEFRAC;
413 TUNABLE_INT_FETCH("kern.ipc.mcl_cachefrac", &mcl_cachefrac);
415 nmbjclusters = NMBJCLUSTERS;
416 TUNABLE_INT_FETCH("kern.ipc.nmbjclusters", &nmbjclusters);
419 TUNABLE_INT_FETCH("kern.ipc.nmbufs", &nmbufs);
422 if (nmbufs < nmbclusters * 2)
423 nmbufs = nmbclusters * 2;
425 SYSINIT(tunable_mbinit, SI_BOOT1_TUNABLES, SI_ORDER_ANY,
426 tunable_mbinit, NULL);
428 /* "number of clusters of pages" */
434 * The mbuf object cache only guarantees that m_next and m_nextpkt are
435 * NULL and that m_data points to the beginning of the data area. In
436 * particular, m_len and m_pkthdr.len are uninitialized. It is the
437 * responsibility of the caller to initialize those fields before use.
440 static __inline boolean_t
441 mbuf_ctor(void *obj, void *private, int ocflags)
443 struct mbuf *m = obj;
447 m->m_data = m->m_dat;
454 * Initialize the mbuf and the packet header fields.
457 mbufphdr_ctor(void *obj, void *private, int ocflags)
459 struct mbuf *m = obj;
463 m->m_data = m->m_pktdat;
464 m->m_flags = M_PKTHDR | M_PHCACHE;
466 m->m_pkthdr.rcvif = NULL; /* eliminate XXX JH */
467 SLIST_INIT(&m->m_pkthdr.tags);
468 m->m_pkthdr.csum_flags = 0; /* eliminate XXX JH */
469 m->m_pkthdr.fw_flags = 0; /* eliminate XXX JH */
475 * A mbcluster object consists of 2K (MCLBYTES) cluster and a refcount.
478 mclmeta_ctor(void *obj, void *private, int ocflags)
480 struct mbcluster *cl = obj;
483 if (ocflags & M_NOWAIT)
484 buf = kmalloc(MCLBYTES, M_MBUFCL, M_NOWAIT | M_ZERO);
486 buf = kmalloc(MCLBYTES, M_MBUFCL, M_INTWAIT | M_ZERO);
495 mjclmeta_ctor(void *obj, void *private, int ocflags)
497 struct mbcluster *cl = obj;
500 if (ocflags & M_NOWAIT)
501 buf = kmalloc(MJUMPAGESIZE, M_MBUFCL, M_NOWAIT | M_ZERO);
503 buf = kmalloc(MJUMPAGESIZE, M_MBUFCL, M_INTWAIT | M_ZERO);
512 mclmeta_dtor(void *obj, void *private)
514 struct mbcluster *mcl = obj;
516 KKASSERT(mcl->mcl_refs == 0);
517 kfree(mcl->mcl_data, M_MBUFCL);
521 linkjcluster(struct mbuf *m, struct mbcluster *cl, uint size)
524 * Add the cluster to the mbuf. The caller will detect that the
525 * mbuf now has an attached cluster.
527 m->m_ext.ext_arg = cl;
528 m->m_ext.ext_buf = cl->mcl_data;
529 m->m_ext.ext_ref = m_mclref;
530 if (size != MCLBYTES)
531 m->m_ext.ext_free = m_mjclfree;
533 m->m_ext.ext_free = m_mclfree;
534 m->m_ext.ext_size = size;
535 atomic_add_int(&cl->mcl_refs, 1);
537 m->m_data = m->m_ext.ext_buf;
538 m->m_flags |= M_EXT | M_EXT_CLUSTER;
542 linkcluster(struct mbuf *m, struct mbcluster *cl)
544 linkjcluster(m, cl, MCLBYTES);
548 mbufphdrcluster_ctor(void *obj, void *private, int ocflags)
550 struct mbuf *m = obj;
551 struct mbcluster *cl;
553 mbufphdr_ctor(obj, private, ocflags);
554 cl = objcache_get(mclmeta_cache, ocflags);
556 ++mbstat[mycpu->gd_cpuid].m_drops;
559 m->m_flags |= M_CLCACHE;
565 mbufphdrjcluster_ctor(void *obj, void *private, int ocflags)
567 struct mbuf *m = obj;
568 struct mbcluster *cl;
570 mbufphdr_ctor(obj, private, ocflags);
571 cl = objcache_get(mjclmeta_cache, ocflags);
573 ++mbstat[mycpu->gd_cpuid].m_drops;
576 m->m_flags |= M_CLCACHE;
577 linkjcluster(m, cl, MJUMPAGESIZE);
582 mbufcluster_ctor(void *obj, void *private, int ocflags)
584 struct mbuf *m = obj;
585 struct mbcluster *cl;
587 mbuf_ctor(obj, private, ocflags);
588 cl = objcache_get(mclmeta_cache, ocflags);
590 ++mbstat[mycpu->gd_cpuid].m_drops;
593 m->m_flags |= M_CLCACHE;
599 mbufjcluster_ctor(void *obj, void *private, int ocflags)
601 struct mbuf *m = obj;
602 struct mbcluster *cl;
604 mbuf_ctor(obj, private, ocflags);
605 cl = objcache_get(mjclmeta_cache, ocflags);
607 ++mbstat[mycpu->gd_cpuid].m_drops;
610 m->m_flags |= M_CLCACHE;
611 linkjcluster(m, cl, MJUMPAGESIZE);
616 * Used for both the cluster and cluster PHDR caches.
618 * The mbuf may have lost its cluster due to sharing, deal
619 * with the situation by checking M_EXT.
622 mbufcluster_dtor(void *obj, void *private)
624 struct mbuf *m = obj;
625 struct mbcluster *mcl;
627 if (m->m_flags & M_EXT) {
628 KKASSERT((m->m_flags & M_EXT_CLUSTER) != 0);
629 mcl = m->m_ext.ext_arg;
630 KKASSERT(mcl->mcl_refs == 1);
632 if (m->m_flags & M_EXT && m->m_ext.ext_size != MCLBYTES)
633 objcache_put(mjclmeta_cache, mcl);
635 objcache_put(mclmeta_cache, mcl);
639 struct objcache_malloc_args mbuf_malloc_args = { MSIZE, M_MBUF };
640 struct objcache_malloc_args mclmeta_malloc_args =
641 { sizeof(struct mbcluster), M_MCLMETA };
647 int mb_limit, cl_limit, ncl_limit, jcl_limit;
652 * Initialize statistics
654 for (i = 0; i < ncpus; i++) {
655 mbstat[i].m_msize = MSIZE;
656 mbstat[i].m_mclbytes = MCLBYTES;
657 mbstat[i].m_mjumpagesize = MJUMPAGESIZE;
658 mbstat[i].m_minclsize = MINCLSIZE;
659 mbstat[i].m_mlen = MLEN;
660 mbstat[i].m_mhlen = MHLEN;
664 * Create objtect caches and save cluster limits, which will
665 * be used to adjust backing kmalloc pools' limit later.
668 mb_limit = cl_limit = 0;
671 mbuf_cache = objcache_create("mbuf",
673 mbuf_ctor, NULL, NULL,
674 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
678 mbufphdr_cache = objcache_create("mbuf pkt hdr",
680 mbufphdr_ctor, NULL, NULL,
681 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
684 ncl_limit = nmbclusters;
685 mclmeta_cache = objcache_create("cluster mbuf",
687 mclmeta_ctor, mclmeta_dtor, NULL,
688 objcache_malloc_alloc, objcache_malloc_free, &mclmeta_malloc_args);
689 cl_limit += ncl_limit;
691 jcl_limit = nmbjclusters;
692 mjclmeta_cache = objcache_create("jcluster mbuf",
694 mjclmeta_ctor, mclmeta_dtor, NULL,
695 objcache_malloc_alloc, objcache_malloc_free, &mclmeta_malloc_args);
696 cl_limit += jcl_limit;
699 mbufcluster_cache = objcache_create("mbuf + cluster",
700 limit, nmbclusters / mcl_cachefrac,
701 mbufcluster_ctor, mbufcluster_dtor, NULL,
702 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
706 mbufphdrcluster_cache = objcache_create("mbuf pkt hdr + cluster",
707 limit, nmbclusters / mclph_cachefrac,
708 mbufphdrcluster_ctor, mbufcluster_dtor, NULL,
709 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
712 limit = nmbjclusters;
713 mbufjcluster_cache = objcache_create("mbuf + jcluster",
715 mbufjcluster_ctor, mbufcluster_dtor, NULL,
716 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
719 limit = nmbjclusters;
720 mbufphdrjcluster_cache = objcache_create("mbuf pkt hdr + jcluster",
722 mbufphdrjcluster_ctor, mbufcluster_dtor, NULL,
723 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
727 * Adjust backing kmalloc pools' limit
729 * NOTE: We raise the limit by another 1/8 to take the effect
730 * of loosememuse into account.
732 cl_limit += cl_limit / 8;
733 kmalloc_raise_limit(mclmeta_malloc_args.mtype,
734 mclmeta_malloc_args.objsize * (size_t)cl_limit);
735 kmalloc_raise_limit(M_MBUFCL,
736 (MCLBYTES * (size_t)ncl_limit) +
737 (MJUMPAGESIZE * (size_t)jcl_limit));
739 mb_limit += mb_limit / 8;
740 kmalloc_raise_limit(mbuf_malloc_args.mtype,
741 mbuf_malloc_args.objsize * (size_t)mb_limit);
745 * Return the number of references to this mbuf's data. 0 is returned
746 * if the mbuf is not M_EXT, a reference count is returned if it is
747 * M_EXT | M_EXT_CLUSTER, and 99 is returned if it is a special M_EXT.
750 m_sharecount(struct mbuf *m)
752 switch (m->m_flags & (M_EXT | M_EXT_CLUSTER)) {
757 case M_EXT | M_EXT_CLUSTER:
758 return (((struct mbcluster *)m->m_ext.ext_arg)->mcl_refs);
761 return (0); /* to shut up compiler */
765 * change mbuf to new type
768 m_chtype(struct mbuf *m, int type)
770 struct globaldata *gd = mycpu;
772 ++mbtypes[gd->gd_cpuid].stats[type];
773 --mbtypes[gd->gd_cpuid].stats[m->m_type];
783 kprintf("Debug: m_reclaim() called\n");
785 SLIST_FOREACH(dp, &domains, dom_next) {
786 for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++) {
791 ++mbstat[mycpu->gd_cpuid].m_drain;
795 updatestats(struct mbuf *m, int type)
797 struct globaldata *gd = mycpu;
802 KASSERT(m->m_next == NULL, ("mbuf %p: bad m_next in get", m));
803 KASSERT(m->m_nextpkt == NULL, ("mbuf %p: bad m_nextpkt in get", m));
806 ++mbtypes[gd->gd_cpuid].stats[type];
807 ++mbstat[gd->gd_cpuid].m_mbufs;
815 m_get(int how, int type)
819 int ocf = MBTOM(how);
823 m = objcache_get(mbuf_cache, ocf);
826 if ((how & MB_TRYWAIT) && ntries++ == 0) {
827 struct objcache *reclaimlist[] = {
830 mbufphdrcluster_cache,
832 mbufphdrjcluster_cache
834 const int nreclaims = NELEM(reclaimlist);
836 if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
840 ++mbstat[mycpu->gd_cpuid].m_drops;
844 KASSERT(m->m_data == m->m_dat, ("mbuf %p: bad m_data in get", m));
848 updatestats(m, type);
853 m_gethdr(int how, int type)
856 int ocf = MBTOM(how);
861 m = objcache_get(mbufphdr_cache, ocf);
864 if ((how & MB_TRYWAIT) && ntries++ == 0) {
865 struct objcache *reclaimlist[] = {
867 mbufcluster_cache, mbufphdrcluster_cache,
868 mbufjcluster_cache, mbufphdrjcluster_cache
870 const int nreclaims = NELEM(reclaimlist);
872 if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
876 ++mbstat[mycpu->gd_cpuid].m_drops;
880 KASSERT(m->m_data == m->m_pktdat, ("mbuf %p: bad m_data in get", m));
885 updatestats(m, type);
890 * Get a mbuf (not a mbuf cluster!) and zero it.
894 m_getclr(int how, int type)
898 m = m_get(how, type);
900 bzero(m->m_data, MLEN);
905 m_getcl_cache(int how, short type, int flags, struct objcache *mbclc,
906 struct objcache *mbphclc, u_long *cl_stats)
908 struct mbuf *m = NULL;
909 int ocflags = MBTOM(how);
914 if (flags & M_PKTHDR)
915 m = objcache_get(mbphclc, ocflags);
917 m = objcache_get(mbclc, ocflags);
920 if ((how & MB_TRYWAIT) && ntries++ == 0) {
921 struct objcache *reclaimlist[1];
923 if (flags & M_PKTHDR)
924 reclaimlist[0] = mbclc;
926 reclaimlist[0] = mbphclc;
927 if (!objcache_reclaimlist(reclaimlist, 1, ocflags))
931 ++mbstat[mycpu->gd_cpuid].m_drops;
936 KASSERT(m->m_data == m->m_ext.ext_buf,
937 ("mbuf %p: bad m_data in get", m));
941 m->m_pkthdr.len = 0; /* just do it unconditonally */
945 ++mbtypes[mycpu->gd_cpuid].stats[type];
951 m_getjcl(int how, short type, int flags, size_t size)
953 struct objcache *mbclc, *mbphclc;
958 mbclc = mbufcluster_cache;
959 mbphclc = mbufphdrcluster_cache;
960 cl_stats = &mbstat[mycpu->gd_cpuid].m_clusters;
964 mbclc = mbufjcluster_cache;
965 mbphclc = mbufphdrjcluster_cache;
966 cl_stats = &mbstat[mycpu->gd_cpuid].m_jclusters;
969 return m_getcl_cache(how, type, flags, mbclc, mbphclc, cl_stats);
973 * Returns an mbuf with an attached cluster.
974 * Because many network drivers use this kind of buffers a lot, it is
975 * convenient to keep a small pool of free buffers of this kind.
976 * Even a small size such as 10 gives about 10% improvement in the
977 * forwarding rate in a bridge or router.
980 m_getcl(int how, short type, int flags)
982 return m_getcl_cache(how, type, flags,
983 mbufcluster_cache, mbufphdrcluster_cache,
984 &mbstat[mycpu->gd_cpuid].m_clusters);
988 * Allocate chain of requested length.
991 m_getc(int len, int how, int type)
993 struct mbuf *n, *nfirst = NULL, **ntail = &nfirst;
997 n = m_getl(len, how, type, 0, &nsize);
1013 * Allocate len-worth of mbufs and/or mbuf clusters (whatever fits best)
1014 * and return a pointer to the head of the allocated chain. If m0 is
1015 * non-null, then we assume that it is a single mbuf or an mbuf chain to
1016 * which we want len bytes worth of mbufs and/or clusters attached, and so
1017 * if we succeed in allocating it, we will just return a pointer to m0.
1019 * If we happen to fail at any point during the allocation, we will free
1020 * up everything we have already allocated and return NULL.
1022 * Deprecated. Use m_getc() and m_cat() instead.
1025 m_getm(struct mbuf *m0, int len, int type, int how)
1027 struct mbuf *nfirst;
1029 nfirst = m_getc(len, how, type);
1032 m_last(m0)->m_next = nfirst;
1040 * Adds a cluster to a normal mbuf, M_EXT is set on success.
1041 * Deprecated. Use m_getcl() instead.
1044 m_mclget(struct mbuf *m, int how)
1046 struct mbcluster *mcl;
1048 KKASSERT((m->m_flags & M_EXT) == 0);
1049 mcl = objcache_get(mclmeta_cache, MBTOM(how));
1051 linkcluster(m, mcl);
1052 ++mbstat[mycpu->gd_cpuid].m_clusters;
1054 ++mbstat[mycpu->gd_cpuid].m_drops;
1059 * Updates to mbcluster must be MPSAFE. Only an entity which already has
1060 * a reference to the cluster can ref it, so we are in no danger of
1061 * racing an add with a subtract. But the operation must still be atomic
1062 * since multiple entities may have a reference on the cluster.
1064 * m_mclfree() is almost the same but it must contend with two entities
1065 * freeing the cluster at the same time.
1070 struct mbcluster *mcl = arg;
1072 atomic_add_int(&mcl->mcl_refs, 1);
1076 * When dereferencing a cluster we have to deal with a N->0 race, where
1077 * N entities free their references simultaniously. To do this we use
1078 * atomic_fetchadd_int().
1081 m_mclfree(void *arg)
1083 struct mbcluster *mcl = arg;
1085 if (atomic_fetchadd_int(&mcl->mcl_refs, -1) == 1) {
1086 --mbstat[mycpu->gd_cpuid].m_clusters;
1087 objcache_put(mclmeta_cache, mcl);
1092 m_mjclfree(void *arg)
1094 struct mbcluster *mcl = arg;
1096 if (atomic_fetchadd_int(&mcl->mcl_refs, -1) == 1) {
1097 --mbstat[mycpu->gd_cpuid].m_jclusters;
1098 objcache_put(mjclmeta_cache, mcl);
1103 * Free a single mbuf and any associated external storage. The successor,
1104 * if any, is returned.
1106 * We do need to check non-first mbuf for m_aux, since some of existing
1107 * code does not call M_PREPEND properly.
1108 * (example: call to bpf_mtap from drivers)
1114 _m_free(struct mbuf *m, const char *func)
1119 m_free(struct mbuf *m)
1124 struct globaldata *gd = mycpu;
1126 KASSERT(m->m_type != MT_FREE, ("freeing free mbuf %p", m));
1127 KASSERT(M_TRAILINGSPACE(m) >= 0, ("overflowed mbuf %p", m));
1128 --mbtypes[gd->gd_cpuid].stats[m->m_type];
1133 * Make sure the mbuf is in constructed state before returning it
1139 m->m_hdr.mh_lastfunc = func;
1142 KKASSERT(m->m_nextpkt == NULL);
1144 if (m->m_nextpkt != NULL) {
1145 static int afewtimes = 10;
1147 if (afewtimes-- > 0) {
1148 kprintf("mfree: m->m_nextpkt != NULL\n");
1149 print_backtrace(-1);
1151 m->m_nextpkt = NULL;
1154 if (m->m_flags & M_PKTHDR) {
1155 m_tag_delete_chain(m); /* eliminate XXX JH */
1158 m->m_flags &= (M_EXT | M_EXT_CLUSTER | M_CLCACHE | M_PHCACHE);
1161 * Clean the M_PKTHDR state so we can return the mbuf to its original
1162 * cache. This is based on the PHCACHE flag which tells us whether
1163 * the mbuf was originally allocated out of a packet-header cache
1164 * or a non-packet-header cache.
1166 if (m->m_flags & M_PHCACHE) {
1167 m->m_flags |= M_PKTHDR;
1168 m->m_pkthdr.rcvif = NULL; /* eliminate XXX JH */
1169 m->m_pkthdr.csum_flags = 0; /* eliminate XXX JH */
1170 m->m_pkthdr.fw_flags = 0; /* eliminate XXX JH */
1171 SLIST_INIT(&m->m_pkthdr.tags);
1175 * Handle remaining flags combinations. M_CLCACHE tells us whether
1176 * the mbuf was originally allocated from a cluster cache or not,
1177 * and is totally separate from whether the mbuf is currently
1178 * associated with a cluster.
1180 switch(m->m_flags & (M_CLCACHE | M_EXT | M_EXT_CLUSTER)) {
1181 case M_CLCACHE | M_EXT | M_EXT_CLUSTER:
1183 * mbuf+cluster cache case. The mbuf was allocated from the
1184 * combined mbuf_cluster cache and can be returned to the
1185 * cache if the cluster hasn't been shared.
1187 if (m_sharecount(m) == 1) {
1189 * The cluster has not been shared, we can just
1190 * reset the data pointer and return the mbuf
1191 * to the cluster cache. Note that the reference
1192 * count is left intact (it is still associated with
1195 m->m_data = m->m_ext.ext_buf;
1196 if (m->m_flags & M_EXT && m->m_ext.ext_size != MCLBYTES) {
1197 if (m->m_flags & M_PHCACHE)
1198 objcache_put(mbufphdrjcluster_cache, m);
1200 objcache_put(mbufjcluster_cache, m);
1201 --mbstat[mycpu->gd_cpuid].m_jclusters;
1203 if (m->m_flags & M_PHCACHE)
1204 objcache_put(mbufphdrcluster_cache, m);
1206 objcache_put(mbufcluster_cache, m);
1207 --mbstat[mycpu->gd_cpuid].m_clusters;
1211 * Hell. Someone else has a ref on this cluster,
1212 * we have to disconnect it which means we can't
1213 * put it back into the mbufcluster_cache, we
1214 * have to destroy the mbuf.
1216 * Other mbuf references to the cluster will typically
1217 * be M_EXT | M_EXT_CLUSTER but without M_CLCACHE.
1219 * XXX we could try to connect another cluster to
1222 m->m_ext.ext_free(m->m_ext.ext_arg);
1223 m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
1224 if (m->m_ext.ext_size == MCLBYTES) {
1225 if (m->m_flags & M_PHCACHE)
1226 objcache_dtor(mbufphdrcluster_cache, m);
1228 objcache_dtor(mbufcluster_cache, m);
1230 if (m->m_flags & M_PHCACHE)
1231 objcache_dtor(mbufphdrjcluster_cache, m);
1233 objcache_dtor(mbufjcluster_cache, m);
1237 case M_EXT | M_EXT_CLUSTER:
1240 * Normal cluster association case, disconnect the cluster from
1241 * the mbuf. The cluster may or may not be custom.
1243 m->m_ext.ext_free(m->m_ext.ext_arg);
1244 m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
1248 * return the mbuf to the mbuf cache.
1250 if (m->m_flags & M_PHCACHE) {
1251 m->m_data = m->m_pktdat;
1252 objcache_put(mbufphdr_cache, m);
1254 m->m_data = m->m_dat;
1255 objcache_put(mbuf_cache, m);
1257 --mbstat[mycpu->gd_cpuid].m_mbufs;
1261 panic("bad mbuf flags %p %08x", m, m->m_flags);
1270 _m_freem(struct mbuf *m, const char *func)
1273 m = _m_free(m, func);
1279 m_freem(struct mbuf *m)
1288 m_extadd(struct mbuf *m, caddr_t buf, u_int size, void (*reff)(void *),
1289 void (*freef)(void *), void *arg)
1291 m->m_ext.ext_arg = arg;
1292 m->m_ext.ext_buf = buf;
1293 m->m_ext.ext_ref = reff;
1294 m->m_ext.ext_free = freef;
1295 m->m_ext.ext_size = size;
1298 m->m_flags |= M_EXT;
1302 * mbuf utility routines
1306 * Lesser-used path for M_PREPEND: allocate new mbuf to prepend to chain and
1310 m_prepend(struct mbuf *m, int len, int how)
1314 if (m->m_flags & M_PKTHDR)
1315 mn = m_gethdr(how, m->m_type);
1317 mn = m_get(how, m->m_type);
1322 if (m->m_flags & M_PKTHDR)
1323 M_MOVE_PKTHDR(mn, m);
1333 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
1334 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
1335 * The wait parameter is a choice of MB_WAIT/MB_DONTWAIT from caller.
1336 * Note that the copy is read-only, because clusters are not copied,
1337 * only their reference counts are incremented.
1340 m_copym(const struct mbuf *m, int off0, int len, int wait)
1342 struct mbuf *n, **np;
1347 KASSERT(off >= 0, ("m_copym, negative off %d", off));
1348 KASSERT(len >= 0, ("m_copym, negative len %d", len));
1349 if (off == 0 && (m->m_flags & M_PKTHDR))
1352 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
1362 KASSERT(len == M_COPYALL,
1363 ("m_copym, length > size of mbuf chain"));
1367 * Because we are sharing any cluster attachment below,
1368 * be sure to get an mbuf that does not have a cluster
1369 * associated with it.
1372 n = m_gethdr(wait, m->m_type);
1374 n = m_get(wait, m->m_type);
1379 if (!m_dup_pkthdr(n, m, wait))
1381 if (len == M_COPYALL)
1382 n->m_pkthdr.len -= off0;
1384 n->m_pkthdr.len = len;
1387 n->m_len = min(len, m->m_len - off);
1388 if (m->m_flags & M_EXT) {
1389 KKASSERT((n->m_flags & M_EXT) == 0);
1390 n->m_data = m->m_data + off;
1391 m->m_ext.ext_ref(m->m_ext.ext_arg);
1392 n->m_ext = m->m_ext;
1393 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1395 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
1396 (unsigned)n->m_len);
1398 if (len != M_COPYALL)
1405 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1409 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1414 * Copy an entire packet, including header (which must be present).
1415 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
1416 * Note that the copy is read-only, because clusters are not copied,
1417 * only their reference counts are incremented.
1418 * Preserve alignment of the first mbuf so if the creator has left
1419 * some room at the beginning (e.g. for inserting protocol headers)
1420 * the copies also have the room available.
1423 m_copypacket(struct mbuf *m, int how)
1425 struct mbuf *top, *n, *o;
1427 n = m_gethdr(how, m->m_type);
1432 if (!m_dup_pkthdr(n, m, how))
1434 n->m_len = m->m_len;
1435 if (m->m_flags & M_EXT) {
1436 KKASSERT((n->m_flags & M_EXT) == 0);
1437 n->m_data = m->m_data;
1438 m->m_ext.ext_ref(m->m_ext.ext_arg);
1439 n->m_ext = m->m_ext;
1440 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1442 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
1443 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1448 o = m_get(how, m->m_type);
1455 n->m_len = m->m_len;
1456 if (m->m_flags & M_EXT) {
1457 KKASSERT((n->m_flags & M_EXT) == 0);
1458 n->m_data = m->m_data;
1459 m->m_ext.ext_ref(m->m_ext.ext_arg);
1460 n->m_ext = m->m_ext;
1461 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1463 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1471 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1476 * Copy data from an mbuf chain starting "off" bytes from the beginning,
1477 * continuing for "len" bytes, into the indicated buffer.
1480 m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
1484 KASSERT(off >= 0, ("m_copydata, negative off %d", off));
1485 KASSERT(len >= 0, ("m_copydata, negative len %d", len));
1487 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
1494 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
1495 count = min(m->m_len - off, len);
1496 bcopy(mtod(m, caddr_t) + off, cp, count);
1505 * Copy a packet header mbuf chain into a completely new chain, including
1506 * copying any mbuf clusters. Use this instead of m_copypacket() when
1507 * you need a writable copy of an mbuf chain.
1510 m_dup(struct mbuf *m, int how)
1512 struct mbuf **p, *top = NULL;
1513 int remain, moff, nsize;
1518 KASSERT((m->m_flags & M_PKTHDR) != 0, ("%s: !PKTHDR", __func__));
1520 /* While there's more data, get a new mbuf, tack it on, and fill it */
1521 remain = m->m_pkthdr.len;
1524 while (remain > 0 || top == NULL) { /* allow m->m_pkthdr.len == 0 */
1527 /* Get the next new mbuf */
1528 n = m_getl(remain, how, m->m_type, top == NULL ? M_PKTHDR : 0,
1533 if (!m_dup_pkthdr(n, m, how))
1536 /* Link it into the new chain */
1540 /* Copy data from original mbuf(s) into new mbuf */
1542 while (n->m_len < nsize && m != NULL) {
1543 int chunk = min(nsize - n->m_len, m->m_len - moff);
1545 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1549 if (moff == m->m_len) {
1555 /* Check correct total mbuf length */
1556 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
1557 ("%s: bogus m_pkthdr.len", __func__));
1564 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1569 * Copy the non-packet mbuf data chain into a new set of mbufs, including
1570 * copying any mbuf clusters. This is typically used to realign a data
1571 * chain by nfs_realign().
1573 * The original chain is left intact. how should be MB_WAIT or MB_DONTWAIT
1574 * and NULL can be returned if MB_DONTWAIT is passed.
1576 * Be careful to use cluster mbufs, a large mbuf chain converted to non
1577 * cluster mbufs can exhaust our supply of mbufs.
1580 m_dup_data(struct mbuf *m, int how)
1582 struct mbuf **p, *n, *top = NULL;
1583 int mlen, moff, chunk, gsize, nsize;
1592 * Optimize the mbuf allocation but do not get too carried away.
1594 if (m->m_next || m->m_len > MLEN)
1595 if (m->m_flags & M_EXT && m->m_ext.ext_size == MCLBYTES)
1598 gsize = MJUMPAGESIZE;
1608 * Scan the mbuf chain until nothing is left, the new mbuf chain
1609 * will be allocated on the fly as needed.
1616 KKASSERT(m->m_type == MT_DATA);
1618 n = m_getl(gsize, how, MT_DATA, 0, &nsize);
1625 chunk = imin(mlen, nsize);
1626 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1641 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1646 * Concatenate mbuf chain n to m.
1647 * Both chains must be of the same type (e.g. MT_DATA).
1648 * Any m_pkthdr is not updated.
1651 m_cat(struct mbuf *m, struct mbuf *n)
1655 if (m->m_flags & M_EXT ||
1656 m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
1657 /* just join the two chains */
1661 /* splat the data from one into the other */
1662 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1664 m->m_len += n->m_len;
1670 m_adj(struct mbuf *mp, int req_len)
1676 if ((m = mp) == NULL)
1682 while (m != NULL && len > 0) {
1683 if (m->m_len <= len) {
1694 if (mp->m_flags & M_PKTHDR)
1695 m->m_pkthdr.len -= (req_len - len);
1698 * Trim from tail. Scan the mbuf chain,
1699 * calculating its length and finding the last mbuf.
1700 * If the adjustment only affects this mbuf, then just
1701 * adjust and return. Otherwise, rescan and truncate
1702 * after the remaining size.
1708 if (m->m_next == NULL)
1712 if (m->m_len >= len) {
1714 if (mp->m_flags & M_PKTHDR)
1715 mp->m_pkthdr.len -= len;
1722 * Correct length for chain is "count".
1723 * Find the mbuf with last data, adjust its length,
1724 * and toss data from remaining mbufs on chain.
1727 if (m->m_flags & M_PKTHDR)
1728 m->m_pkthdr.len = count;
1729 for (; m; m = m->m_next) {
1730 if (m->m_len >= count) {
1737 (m = m->m_next) ->m_len = 0;
1742 * Set the m_data pointer of a newly-allocated mbuf
1743 * to place an object of the specified size at the
1744 * end of the mbuf, longword aligned.
1747 m_align(struct mbuf *m, int len)
1751 if (m->m_flags & M_EXT)
1752 adjust = m->m_ext.ext_size - len;
1753 else if (m->m_flags & M_PKTHDR)
1754 adjust = MHLEN - len;
1756 adjust = MLEN - len;
1757 m->m_data += adjust &~ (sizeof(long)-1);
1761 * Create a writable copy of the mbuf chain. While doing this
1762 * we compact the chain with a goal of producing a chain with
1763 * at most two mbufs. The second mbuf in this chain is likely
1764 * to be a cluster. The primary purpose of this work is to create
1765 * a writable packet for encryption, compression, etc. The
1766 * secondary goal is to linearize the data so the data can be
1767 * passed to crypto hardware in the most efficient manner possible.
1770 m_unshare(struct mbuf *m0, int how)
1772 struct mbuf *m, *mprev;
1773 struct mbuf *n, *mfirst, *mlast;
1777 for (m = m0; m != NULL; m = mprev->m_next) {
1779 * Regular mbufs are ignored unless there's a cluster
1780 * in front of it that we can use to coalesce. We do
1781 * the latter mainly so later clusters can be coalesced
1782 * also w/o having to handle them specially (i.e. convert
1783 * mbuf+cluster -> cluster). This optimization is heavily
1784 * influenced by the assumption that we're running over
1785 * Ethernet where MCLBYTES is large enough that the max
1786 * packet size will permit lots of coalescing into a
1787 * single cluster. This in turn permits efficient
1788 * crypto operations, especially when using hardware.
1790 if ((m->m_flags & M_EXT) == 0) {
1791 if (mprev && (mprev->m_flags & M_EXT) &&
1792 m->m_len <= M_TRAILINGSPACE(mprev)) {
1793 /* XXX: this ignores mbuf types */
1794 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1795 mtod(m, caddr_t), m->m_len);
1796 mprev->m_len += m->m_len;
1797 mprev->m_next = m->m_next; /* unlink from chain */
1798 m_free(m); /* reclaim mbuf */
1805 * Writable mbufs are left alone (for now).
1807 if (M_WRITABLE(m)) {
1813 * Not writable, replace with a copy or coalesce with
1814 * the previous mbuf if possible (since we have to copy
1815 * it anyway, we try to reduce the number of mbufs and
1816 * clusters so that future work is easier).
1818 KASSERT(m->m_flags & M_EXT, ("m_flags 0x%x", m->m_flags));
1819 /* NB: we only coalesce into a cluster or larger */
1820 if (mprev != NULL && (mprev->m_flags & M_EXT) &&
1821 m->m_len <= M_TRAILINGSPACE(mprev)) {
1822 /* XXX: this ignores mbuf types */
1823 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1824 mtod(m, caddr_t), m->m_len);
1825 mprev->m_len += m->m_len;
1826 mprev->m_next = m->m_next; /* unlink from chain */
1827 m_free(m); /* reclaim mbuf */
1832 * Allocate new space to hold the copy...
1834 /* XXX why can M_PKTHDR be set past the first mbuf? */
1835 if (mprev == NULL && (m->m_flags & M_PKTHDR)) {
1837 * NB: if a packet header is present we must
1838 * allocate the mbuf separately from any cluster
1839 * because M_MOVE_PKTHDR will smash the data
1840 * pointer and drop the M_EXT marker.
1842 MGETHDR(n, how, m->m_type);
1847 M_MOVE_PKTHDR(n, m);
1849 if ((n->m_flags & M_EXT) == 0) {
1855 n = m_getcl(how, m->m_type, m->m_flags);
1862 * ... and copy the data. We deal with jumbo mbufs
1863 * (i.e. m_len > MCLBYTES) by splitting them into
1864 * clusters. We could just malloc a buffer and make
1865 * it external but too many device drivers don't know
1866 * how to break up the non-contiguous memory when
1874 int cc = min(len, MCLBYTES);
1875 memcpy(mtod(n, caddr_t), mtod(m, caddr_t) + off, cc);
1886 n = m_getcl(how, m->m_type, m->m_flags);
1893 n->m_next = m->m_next;
1895 m0 = mfirst; /* new head of chain */
1897 mprev->m_next = mfirst; /* replace old mbuf */
1898 m_free(m); /* release old mbuf */
1905 * Rearrange an mbuf chain so that len bytes are contiguous
1906 * and in the data area of an mbuf (so that mtod will work for a structure
1907 * of size len). Returns the resulting mbuf chain on success, frees it and
1908 * returns null on failure. If there is room, it will add up to
1909 * max_protohdr-len extra bytes to the contiguous region in an attempt to
1910 * avoid being called next time.
1913 m_pullup(struct mbuf *n, int len)
1920 * If first mbuf has no cluster, and has room for len bytes
1921 * without shifting current data, pullup into it,
1922 * otherwise allocate a new mbuf to prepend to the chain.
1924 if (!(n->m_flags & M_EXT) &&
1925 n->m_data + len < &n->m_dat[MLEN] &&
1927 if (n->m_len >= len)
1935 if (n->m_flags & M_PKTHDR)
1936 m = m_gethdr(MB_DONTWAIT, n->m_type);
1938 m = m_get(MB_DONTWAIT, n->m_type);
1942 if (n->m_flags & M_PKTHDR)
1943 M_MOVE_PKTHDR(m, n);
1945 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1947 count = min(min(max(len, max_protohdr), space), n->m_len);
1948 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1958 } while (len > 0 && n);
1967 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1972 * Partition an mbuf chain in two pieces, returning the tail --
1973 * all but the first len0 bytes. In case of failure, it returns NULL and
1974 * attempts to restore the chain to its original state.
1976 * Note that the resulting mbufs might be read-only, because the new
1977 * mbuf can end up sharing an mbuf cluster with the original mbuf if
1978 * the "breaking point" happens to lie within a cluster mbuf. Use the
1979 * M_WRITABLE() macro to check for this case.
1982 m_split(struct mbuf *m0, int len0, int wait)
1985 unsigned len = len0, remain;
1987 for (m = m0; m && len > m->m_len; m = m->m_next)
1991 remain = m->m_len - len;
1992 if (m0->m_flags & M_PKTHDR) {
1993 n = m_gethdr(wait, m0->m_type);
1996 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1997 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1998 m0->m_pkthdr.len = len0;
1999 if (m->m_flags & M_EXT)
2001 if (remain > MHLEN) {
2002 /* m can't be the lead packet */
2004 n->m_next = m_split(m, len, wait);
2005 if (n->m_next == NULL) {
2013 MH_ALIGN(n, remain);
2014 } else if (remain == 0) {
2019 n = m_get(wait, m->m_type);
2025 if (m->m_flags & M_EXT) {
2026 KKASSERT((n->m_flags & M_EXT) == 0);
2027 n->m_data = m->m_data + len;
2028 m->m_ext.ext_ref(m->m_ext.ext_arg);
2029 n->m_ext = m->m_ext;
2030 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
2032 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
2036 n->m_next = m->m_next;
2042 * Routine to copy from device local memory into mbufs.
2043 * Note: "offset" is ill-defined and always called as 0, so ignore it.
2046 m_devget(char *buf, int len, int offset, struct ifnet *ifp,
2047 void (*copy)(volatile const void *from, volatile void *to, size_t length))
2049 struct mbuf *m, *mfirst = NULL, **mtail;
2058 m = m_getl(len, MB_DONTWAIT, MT_DATA, flags, &nsize);
2063 m->m_len = min(len, nsize);
2065 if (flags & M_PKTHDR) {
2066 if (len + max_linkhdr <= nsize)
2067 m->m_data += max_linkhdr;
2068 m->m_pkthdr.rcvif = ifp;
2069 m->m_pkthdr.len = len;
2073 copy(buf, m->m_data, (unsigned)m->m_len);
2084 * Routine to pad mbuf to the specified length 'padto'.
2087 m_devpad(struct mbuf *m, int padto)
2089 struct mbuf *last = NULL;
2092 if (padto <= m->m_pkthdr.len)
2095 padlen = padto - m->m_pkthdr.len;
2097 /* if there's only the packet-header and we can pad there, use it. */
2098 if (m->m_pkthdr.len == m->m_len && M_TRAILINGSPACE(m) >= padlen) {
2102 * Walk packet chain to find last mbuf. We will either
2103 * pad there, or append a new mbuf and pad it
2105 for (last = m; last->m_next != NULL; last = last->m_next)
2108 /* `last' now points to last in chain. */
2109 if (M_TRAILINGSPACE(last) < padlen) {
2112 /* Allocate new empty mbuf, pad it. Compact later. */
2113 MGET(n, MB_DONTWAIT, MT_DATA);
2121 KKASSERT(M_TRAILINGSPACE(last) >= padlen);
2122 KKASSERT(M_WRITABLE(last));
2124 /* Now zero the pad area */
2125 bzero(mtod(last, char *) + last->m_len, padlen);
2126 last->m_len += padlen;
2127 m->m_pkthdr.len += padlen;
2132 * Copy data from a buffer back into the indicated mbuf chain,
2133 * starting "off" bytes from the beginning, extending the mbuf
2134 * chain if necessary.
2137 m_copyback(struct mbuf *m0, int off, int len, caddr_t cp)
2140 struct mbuf *m = m0, *n;
2145 while (off > (mlen = m->m_len)) {
2148 if (m->m_next == NULL) {
2149 n = m_getclr(MB_DONTWAIT, m->m_type);
2152 n->m_len = min(MLEN, len + off);
2158 mlen = min (m->m_len - off, len);
2159 bcopy(cp, off + mtod(m, caddr_t), (unsigned)mlen);
2167 if (m->m_next == NULL) {
2168 n = m_get(MB_DONTWAIT, m->m_type);
2171 n->m_len = min(MLEN, len);
2176 out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
2177 m->m_pkthdr.len = totlen;
2181 * Append the specified data to the indicated mbuf chain,
2182 * Extend the mbuf chain if the new data does not fit in
2185 * Return 1 if able to complete the job; otherwise 0.
2188 m_append(struct mbuf *m0, int len, c_caddr_t cp)
2191 int remainder, space;
2193 for (m = m0; m->m_next != NULL; m = m->m_next)
2196 space = M_TRAILINGSPACE(m);
2199 * Copy into available space.
2201 if (space > remainder)
2203 bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
2205 cp += space, remainder -= space;
2207 while (remainder > 0) {
2209 * Allocate a new mbuf; could check space
2210 * and allocate a cluster instead.
2212 n = m_get(MB_DONTWAIT, m->m_type);
2215 n->m_len = min(MLEN, remainder);
2216 bcopy(cp, mtod(n, caddr_t), n->m_len);
2217 cp += n->m_len, remainder -= n->m_len;
2221 if (m0->m_flags & M_PKTHDR)
2222 m0->m_pkthdr.len += len - remainder;
2223 return (remainder == 0);
2227 * Apply function f to the data in an mbuf chain starting "off" bytes from
2228 * the beginning, continuing for "len" bytes.
2231 m_apply(struct mbuf *m, int off, int len,
2232 int (*f)(void *, void *, u_int), void *arg)
2237 KASSERT(off >= 0, ("m_apply, negative off %d", off));
2238 KASSERT(len >= 0, ("m_apply, negative len %d", len));
2240 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
2247 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
2248 count = min(m->m_len - off, len);
2249 rval = (*f)(arg, mtod(m, caddr_t) + off, count);
2260 * Return a pointer to mbuf/offset of location in mbuf chain.
2263 m_getptr(struct mbuf *m, int loc, int *off)
2267 /* Normal end of search. */
2268 if (m->m_len > loc) {
2273 if (m->m_next == NULL) {
2275 /* Point at the end of valid data. */
2288 m_print(const struct mbuf *m)
2291 const struct mbuf *m2;
2294 len = m->m_pkthdr.len;
2296 hexstr = kmalloc(HEX_NCPYLEN(len), M_TEMP, M_ZERO | M_WAITOK);
2298 kprintf("%p %s\n", m2, hexncpy(m2->m_data, m2->m_len, hexstr,
2299 HEX_NCPYLEN(m2->m_len), "-"));
2303 kfree(hexstr, M_TEMP);
2308 * "Move" mbuf pkthdr from "from" to "to".
2309 * "from" must have M_PKTHDR set, and "to" must be empty.
2312 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
2314 KASSERT((to->m_flags & M_PKTHDR), ("m_move_pkthdr: not packet header"));
2316 to->m_flags |= from->m_flags & M_COPYFLAGS;
2317 to->m_pkthdr = from->m_pkthdr; /* especially tags */
2318 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
2322 * Duplicate "from"'s mbuf pkthdr in "to".
2323 * "from" must have M_PKTHDR set, and "to" must be empty.
2324 * In particular, this does a deep copy of the packet tags.
2327 m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
2329 KASSERT((to->m_flags & M_PKTHDR), ("m_dup_pkthdr: not packet header"));
2331 to->m_flags = (from->m_flags & M_COPYFLAGS) |
2332 (to->m_flags & ~M_COPYFLAGS);
2333 to->m_pkthdr = from->m_pkthdr;
2334 SLIST_INIT(&to->m_pkthdr.tags);
2335 return (m_tag_copy_chain(to, from, how));
2339 * Defragment a mbuf chain, returning the shortest possible
2340 * chain of mbufs and clusters. If allocation fails and
2341 * this cannot be completed, NULL will be returned, but
2342 * the passed in chain will be unchanged. Upon success,
2343 * the original chain will be freed, and the new chain
2346 * If a non-packet header is passed in, the original
2347 * mbuf (chain?) will be returned unharmed.
2349 * m_defrag_nofree doesn't free the passed in mbuf.
2352 m_defrag(struct mbuf *m0, int how)
2356 if ((m_new = m_defrag_nofree(m0, how)) == NULL)
2364 m_defrag_nofree(struct mbuf *m0, int how)
2366 struct mbuf *m_new = NULL, *m_final = NULL;
2367 int progress = 0, length, nsize;
2369 if (!(m0->m_flags & M_PKTHDR))
2372 #ifdef MBUF_STRESS_TEST
2373 if (m_defragrandomfailures) {
2374 int temp = karc4random() & 0xff;
2380 m_final = m_getl(m0->m_pkthdr.len, how, MT_DATA, M_PKTHDR, &nsize);
2381 if (m_final == NULL)
2383 m_final->m_len = 0; /* in case m0->m_pkthdr.len is zero */
2385 if (m_dup_pkthdr(m_final, m0, how) == 0)
2390 while (progress < m0->m_pkthdr.len) {
2391 length = m0->m_pkthdr.len - progress;
2392 if (length > MCLBYTES)
2395 if (m_new == NULL) {
2396 m_new = m_getl(length, how, MT_DATA, 0, &nsize);
2401 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
2403 m_new->m_len = length;
2404 if (m_new != m_final)
2405 m_cat(m_final, m_new);
2408 if (m0->m_next == NULL)
2411 m_defragbytes += m_final->m_pkthdr.len;
2422 * Move data from uio into mbufs.
2425 m_uiomove(struct uio *uio)
2427 struct mbuf *m; /* current working mbuf */
2428 struct mbuf *head = NULL; /* result mbuf chain */
2429 struct mbuf **mp = &head;
2430 int flags = M_PKTHDR;
2436 if (uio->uio_resid > INT_MAX)
2439 resid = (int)uio->uio_resid;
2440 m = m_getl(resid, MB_WAIT, MT_DATA, flags, &nsize);
2442 m->m_pkthdr.len = 0;
2443 /* Leave room for protocol headers. */
2448 m->m_len = imin(nsize, resid);
2449 error = uiomove(mtod(m, caddr_t), m->m_len, uio);
2456 head->m_pkthdr.len += m->m_len;
2457 } while (uio->uio_resid > 0);
2467 m_last(struct mbuf *m)
2475 * Return the number of bytes in an mbuf chain.
2476 * If lastm is not NULL, also return the last mbuf.
2479 m_lengthm(struct mbuf *m, struct mbuf **lastm)
2482 struct mbuf *prev = m;
2495 * Like m_lengthm(), except also keep track of mbuf usage.
2498 m_countm(struct mbuf *m, struct mbuf **lastm, u_int *pmbcnt)
2500 u_int len = 0, mbcnt = 0;
2501 struct mbuf *prev = m;
2506 if (m->m_flags & M_EXT)
2507 mbcnt += m->m_ext.ext_size;