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, "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 mjclph_cachefrac;
264 static int mjcl_cachefrac;
265 static int mclph_cachefrac;
266 static int mcl_cachefrac;
268 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RW,
269 &max_linkhdr, 0, "Max size of a link-level header");
270 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RW,
271 &max_protohdr, 0, "Max size of a protocol header");
272 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RW, &max_hdr, 0,
273 "Max size of link+protocol headers");
274 SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RW,
275 &max_datalen, 0, "Max data payload size without headers");
276 SYSCTL_INT(_kern_ipc, OID_AUTO, mbuf_wait, CTLFLAG_RW,
277 &mbuf_wait, 0, "Time in ticks to sleep after failed mbuf allocations");
278 static int do_mbstat(SYSCTL_HANDLER_ARGS);
280 SYSCTL_PROC(_kern_ipc, KIPC_MBSTAT, mbstat, CTLTYPE_STRUCT|CTLFLAG_RD,
281 0, 0, do_mbstat, "S,mbstat", "mbuf usage statistics");
283 static int do_mbtypes(SYSCTL_HANDLER_ARGS);
285 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbtypes, CTLTYPE_ULONG|CTLFLAG_RD,
286 0, 0, do_mbtypes, "LU", "");
289 do_mbstat(SYSCTL_HANDLER_ARGS)
291 struct mbstat mbstat_total;
292 struct mbstat *mbstat_totalp;
295 bzero(&mbstat_total, sizeof(mbstat_total));
296 mbstat_totalp = &mbstat_total;
298 for (i = 0; i < ncpus; i++)
300 mbstat_total.m_mbufs += mbstat[i].m_mbufs;
301 mbstat_total.m_clusters += mbstat[i].m_clusters;
302 mbstat_total.m_jclusters += mbstat[i].m_jclusters;
303 mbstat_total.m_clfree += mbstat[i].m_clfree;
304 mbstat_total.m_drops += mbstat[i].m_drops;
305 mbstat_total.m_wait += mbstat[i].m_wait;
306 mbstat_total.m_drain += mbstat[i].m_drain;
307 mbstat_total.m_mcfail += mbstat[i].m_mcfail;
308 mbstat_total.m_mpfail += mbstat[i].m_mpfail;
312 * The following fields are not cumulative fields so just
313 * get their values once.
315 mbstat_total.m_msize = mbstat[0].m_msize;
316 mbstat_total.m_mclbytes = mbstat[0].m_mclbytes;
317 mbstat_total.m_minclsize = mbstat[0].m_minclsize;
318 mbstat_total.m_mlen = mbstat[0].m_mlen;
319 mbstat_total.m_mhlen = mbstat[0].m_mhlen;
321 return(sysctl_handle_opaque(oidp, mbstat_totalp, sizeof(mbstat_total), req));
325 do_mbtypes(SYSCTL_HANDLER_ARGS)
327 u_long totals[MT_NTYPES];
330 for (i = 0; i < MT_NTYPES; i++)
333 for (i = 0; i < ncpus; i++)
335 for (j = 0; j < MT_NTYPES; j++)
336 totals[j] += mbtypes[i].stats[j];
339 return(sysctl_handle_opaque(oidp, totals, sizeof(totals), req));
343 * These are read-only because we do not currently have any code
344 * to adjust the objcache limits after the fact. The variables
345 * may only be set as boot-time tunables.
347 SYSCTL_INT(_kern_ipc, KIPC_NMBCLUSTERS, nmbclusters, CTLFLAG_RD,
348 &nmbclusters, 0, "Maximum number of mbuf clusters available");
349 SYSCTL_INT(_kern_ipc, OID_AUTO, nmbufs, CTLFLAG_RD, &nmbufs, 0,
350 "Maximum number of mbufs available");
351 SYSCTL_INT(_kern_ipc, OID_AUTO, nmbjclusters, CTLFLAG_RD, &nmbjclusters, 0,
352 "Maximum number of mbuf jclusters available");
353 SYSCTL_INT(_kern_ipc, OID_AUTO, mjclph_cachefrac, CTLFLAG_RD,
354 &mjclph_cachefrac, 0,
355 "Fraction of cacheable mbuf jclusters w/ pkthdr");
356 SYSCTL_INT(_kern_ipc, OID_AUTO, mjcl_cachefrac, CTLFLAG_RD,
358 "Fraction of cacheable mbuf jclusters");
359 SYSCTL_INT(_kern_ipc, OID_AUTO, mclph_cachefrac, CTLFLAG_RD,
361 "Fraction of cacheable mbuf clusters w/ pkthdr");
362 SYSCTL_INT(_kern_ipc, OID_AUTO, mcl_cachefrac, CTLFLAG_RD,
363 &mcl_cachefrac, 0, "Fraction of cacheable mbuf clusters");
365 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
366 &m_defragpackets, 0, "Number of defragment packets");
367 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
368 &m_defragbytes, 0, "Number of defragment bytes");
369 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
370 &m_defraguseless, 0, "Number of useless defragment mbuf chain operations");
371 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
372 &m_defragfailure, 0, "Number of failed defragment mbuf chain operations");
373 #ifdef MBUF_STRESS_TEST
374 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
375 &m_defragrandomfailures, 0, "");
378 static MALLOC_DEFINE(M_MBUF, "mbuf", "mbuf");
379 static MALLOC_DEFINE(M_MBUFCL, "mbufcl", "mbufcl");
380 static MALLOC_DEFINE(M_MCLMETA, "mclmeta", "mclmeta");
382 static void m_reclaim (void);
383 static void m_mclref(void *arg);
384 static void m_mclfree(void *arg);
385 static void m_mjclfree(void *arg);
388 * NOTE: Default NMBUFS must take into account a possible DOS attack
389 * using fd passing on unix domain sockets.
392 #define NMBCLUSTERS (512 + maxusers * 16)
394 #ifndef MJCLPH_CACHEFRAC
395 #define MJCLPH_CACHEFRAC 16
397 #ifndef MJCL_CACHEFRAC
398 #define MJCL_CACHEFRAC 4
400 #ifndef MCLPH_CACHEFRAC
401 #define MCLPH_CACHEFRAC 16
403 #ifndef MCL_CACHEFRAC
404 #define MCL_CACHEFRAC 4
407 #define NMBJCLUSTERS (NMBCLUSTERS / 2)
410 #define NMBUFS (nmbclusters * 2 + maxfiles)
414 * Perform sanity checks of tunables declared above.
417 tunable_mbinit(void *dummy)
420 * This has to be done before VM init.
422 nmbclusters = NMBCLUSTERS;
423 TUNABLE_INT_FETCH("kern.ipc.nmbclusters", &nmbclusters);
424 mjclph_cachefrac = MJCLPH_CACHEFRAC;
425 TUNABLE_INT_FETCH("kern.ipc.mjclph_cachefrac", &mjclph_cachefrac);
426 mjcl_cachefrac = MJCL_CACHEFRAC;
427 TUNABLE_INT_FETCH("kern.ipc.mjcl_cachefrac", &mjcl_cachefrac);
428 mclph_cachefrac = MCLPH_CACHEFRAC;
429 TUNABLE_INT_FETCH("kern.ipc.mclph_cachefrac", &mclph_cachefrac);
430 mcl_cachefrac = MCL_CACHEFRAC;
431 TUNABLE_INT_FETCH("kern.ipc.mcl_cachefrac", &mcl_cachefrac);
434 * WARNING! each mcl cache feeds two mbuf caches, so the minimum
435 * cachefrac is 2. For safety, use 3.
437 if (mjclph_cachefrac < 3)
438 mjclph_cachefrac = 3;
439 if (mjcl_cachefrac < 3)
441 if (mclph_cachefrac < 3)
443 if (mcl_cachefrac < 3)
446 nmbjclusters = NMBJCLUSTERS;
447 TUNABLE_INT_FETCH("kern.ipc.nmbjclusters", &nmbjclusters);
450 TUNABLE_INT_FETCH("kern.ipc.nmbufs", &nmbufs);
453 if (nmbufs < nmbclusters * 2)
454 nmbufs = nmbclusters * 2;
456 SYSINIT(tunable_mbinit, SI_BOOT1_TUNABLES, SI_ORDER_ANY,
457 tunable_mbinit, NULL);
459 /* "number of clusters of pages" */
465 * The mbuf object cache only guarantees that m_next and m_nextpkt are
466 * NULL and that m_data points to the beginning of the data area. In
467 * particular, m_len and m_pkthdr.len are uninitialized. It is the
468 * responsibility of the caller to initialize those fields before use.
471 static __inline boolean_t
472 mbuf_ctor(void *obj, void *private, int ocflags)
474 struct mbuf *m = obj;
478 m->m_data = m->m_dat;
485 * Initialize the mbuf and the packet header fields.
488 mbufphdr_ctor(void *obj, void *private, int ocflags)
490 struct mbuf *m = obj;
494 m->m_data = m->m_pktdat;
495 m->m_flags = M_PKTHDR | M_PHCACHE;
497 m->m_pkthdr.rcvif = NULL; /* eliminate XXX JH */
498 SLIST_INIT(&m->m_pkthdr.tags);
499 m->m_pkthdr.csum_flags = 0; /* eliminate XXX JH */
500 m->m_pkthdr.fw_flags = 0; /* eliminate XXX JH */
506 * A mbcluster object consists of 2K (MCLBYTES) cluster and a refcount.
509 mclmeta_ctor(void *obj, void *private, int ocflags)
511 struct mbcluster *cl = obj;
514 if (ocflags & M_NOWAIT)
515 buf = kmalloc(MCLBYTES, M_MBUFCL, M_NOWAIT | M_ZERO);
517 buf = kmalloc(MCLBYTES, M_MBUFCL, M_INTWAIT | M_ZERO);
526 mjclmeta_ctor(void *obj, void *private, int ocflags)
528 struct mbcluster *cl = obj;
531 if (ocflags & M_NOWAIT)
532 buf = kmalloc(MJUMPAGESIZE, M_MBUFCL, M_NOWAIT | M_ZERO);
534 buf = kmalloc(MJUMPAGESIZE, M_MBUFCL, M_INTWAIT | M_ZERO);
543 mclmeta_dtor(void *obj, void *private)
545 struct mbcluster *mcl = obj;
547 KKASSERT(mcl->mcl_refs == 0);
548 kfree(mcl->mcl_data, M_MBUFCL);
552 linkjcluster(struct mbuf *m, struct mbcluster *cl, uint size)
555 * Add the cluster to the mbuf. The caller will detect that the
556 * mbuf now has an attached cluster.
558 m->m_ext.ext_arg = cl;
559 m->m_ext.ext_buf = cl->mcl_data;
560 m->m_ext.ext_ref = m_mclref;
561 if (size != MCLBYTES)
562 m->m_ext.ext_free = m_mjclfree;
564 m->m_ext.ext_free = m_mclfree;
565 m->m_ext.ext_size = size;
566 atomic_add_int(&cl->mcl_refs, 1);
568 m->m_data = m->m_ext.ext_buf;
569 m->m_flags |= M_EXT | M_EXT_CLUSTER;
573 linkcluster(struct mbuf *m, struct mbcluster *cl)
575 linkjcluster(m, cl, MCLBYTES);
579 mbufphdrcluster_ctor(void *obj, void *private, int ocflags)
581 struct mbuf *m = obj;
582 struct mbcluster *cl;
584 mbufphdr_ctor(obj, private, ocflags);
585 cl = objcache_get(mclmeta_cache, ocflags);
587 ++mbstat[mycpu->gd_cpuid].m_drops;
590 m->m_flags |= M_CLCACHE;
596 mbufphdrjcluster_ctor(void *obj, void *private, int ocflags)
598 struct mbuf *m = obj;
599 struct mbcluster *cl;
601 mbufphdr_ctor(obj, private, ocflags);
602 cl = objcache_get(mjclmeta_cache, ocflags);
604 ++mbstat[mycpu->gd_cpuid].m_drops;
607 m->m_flags |= M_CLCACHE;
608 linkjcluster(m, cl, MJUMPAGESIZE);
613 mbufcluster_ctor(void *obj, void *private, int ocflags)
615 struct mbuf *m = obj;
616 struct mbcluster *cl;
618 mbuf_ctor(obj, private, ocflags);
619 cl = objcache_get(mclmeta_cache, ocflags);
621 ++mbstat[mycpu->gd_cpuid].m_drops;
624 m->m_flags |= M_CLCACHE;
630 mbufjcluster_ctor(void *obj, void *private, int ocflags)
632 struct mbuf *m = obj;
633 struct mbcluster *cl;
635 mbuf_ctor(obj, private, ocflags);
636 cl = objcache_get(mjclmeta_cache, ocflags);
638 ++mbstat[mycpu->gd_cpuid].m_drops;
641 m->m_flags |= M_CLCACHE;
642 linkjcluster(m, cl, MJUMPAGESIZE);
647 * Used for both the cluster and cluster PHDR caches.
649 * The mbuf may have lost its cluster due to sharing, deal
650 * with the situation by checking M_EXT.
653 mbufcluster_dtor(void *obj, void *private)
655 struct mbuf *m = obj;
656 struct mbcluster *mcl;
658 if (m->m_flags & M_EXT) {
659 KKASSERT((m->m_flags & M_EXT_CLUSTER) != 0);
660 mcl = m->m_ext.ext_arg;
661 KKASSERT(mcl->mcl_refs == 1);
663 if (m->m_flags & M_EXT && m->m_ext.ext_size != MCLBYTES)
664 objcache_put(mjclmeta_cache, mcl);
666 objcache_put(mclmeta_cache, mcl);
670 struct objcache_malloc_args mbuf_malloc_args = { MSIZE, M_MBUF };
671 struct objcache_malloc_args mclmeta_malloc_args =
672 { sizeof(struct mbcluster), M_MCLMETA };
678 int mb_limit, cl_limit, ncl_limit, jcl_limit;
683 * Initialize statistics
685 for (i = 0; i < ncpus; i++) {
686 mbstat[i].m_msize = MSIZE;
687 mbstat[i].m_mclbytes = MCLBYTES;
688 mbstat[i].m_mjumpagesize = MJUMPAGESIZE;
689 mbstat[i].m_minclsize = MINCLSIZE;
690 mbstat[i].m_mlen = MLEN;
691 mbstat[i].m_mhlen = MHLEN;
695 * Create objtect caches and save cluster limits, which will
696 * be used to adjust backing kmalloc pools' limit later.
699 mb_limit = cl_limit = 0;
702 mbuf_cache = objcache_create("mbuf",
704 mbuf_ctor, NULL, NULL,
705 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
709 mbufphdr_cache = objcache_create("mbuf pkt hdr",
711 mbufphdr_ctor, NULL, NULL,
712 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
715 ncl_limit = nmbclusters;
716 mclmeta_cache = objcache_create("cluster mbuf",
717 ncl_limit, nmbclusters / 4,
718 mclmeta_ctor, mclmeta_dtor, NULL,
719 objcache_malloc_alloc, objcache_malloc_free, &mclmeta_malloc_args);
720 cl_limit += ncl_limit;
722 jcl_limit = nmbjclusters;
723 mjclmeta_cache = objcache_create("jcluster mbuf",
724 jcl_limit, nmbjclusters / 4,
725 mjclmeta_ctor, mclmeta_dtor, NULL,
726 objcache_malloc_alloc, objcache_malloc_free, &mclmeta_malloc_args);
727 cl_limit += jcl_limit;
730 mbufcluster_cache = objcache_create("mbuf + cluster",
731 limit, nmbclusters / mcl_cachefrac,
732 mbufcluster_ctor, mbufcluster_dtor, NULL,
733 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
737 mbufphdrcluster_cache = objcache_create("mbuf pkt hdr + cluster",
738 limit, nmbclusters / mclph_cachefrac,
739 mbufphdrcluster_ctor, mbufcluster_dtor, NULL,
740 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
743 limit = nmbjclusters;
744 mbufjcluster_cache = objcache_create("mbuf + jcluster",
745 limit, nmbjclusters / mjcl_cachefrac,
746 mbufjcluster_ctor, mbufcluster_dtor, NULL,
747 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
750 limit = nmbjclusters;
751 mbufphdrjcluster_cache = objcache_create("mbuf pkt hdr + jcluster",
752 limit, nmbjclusters / mjclph_cachefrac,
753 mbufphdrjcluster_ctor, mbufcluster_dtor, NULL,
754 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
758 * Adjust backing kmalloc pools' limit
760 * NOTE: We raise the limit by another 1/8 to take the effect
761 * of loosememuse into account.
763 cl_limit += cl_limit / 8;
764 kmalloc_raise_limit(mclmeta_malloc_args.mtype,
765 mclmeta_malloc_args.objsize * (size_t)cl_limit);
766 kmalloc_raise_limit(M_MBUFCL,
767 (MCLBYTES * (size_t)ncl_limit) +
768 (MJUMPAGESIZE * (size_t)jcl_limit));
770 mb_limit += mb_limit / 8;
771 kmalloc_raise_limit(mbuf_malloc_args.mtype,
772 mbuf_malloc_args.objsize * (size_t)mb_limit);
776 * Return the number of references to this mbuf's data. 0 is returned
777 * if the mbuf is not M_EXT, a reference count is returned if it is
778 * M_EXT | M_EXT_CLUSTER, and 99 is returned if it is a special M_EXT.
781 m_sharecount(struct mbuf *m)
783 switch (m->m_flags & (M_EXT | M_EXT_CLUSTER)) {
788 case M_EXT | M_EXT_CLUSTER:
789 return (((struct mbcluster *)m->m_ext.ext_arg)->mcl_refs);
792 return (0); /* to shut up compiler */
796 * change mbuf to new type
799 m_chtype(struct mbuf *m, int type)
801 struct globaldata *gd = mycpu;
803 ++mbtypes[gd->gd_cpuid].stats[type];
804 --mbtypes[gd->gd_cpuid].stats[m->m_type];
814 kprintf("Debug: m_reclaim() called\n");
816 SLIST_FOREACH(dp, &domains, dom_next) {
817 for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++) {
822 ++mbstat[mycpu->gd_cpuid].m_drain;
826 updatestats(struct mbuf *m, int type)
828 struct globaldata *gd = mycpu;
833 KASSERT(m->m_next == NULL, ("mbuf %p: bad m_next in get", m));
834 KASSERT(m->m_nextpkt == NULL, ("mbuf %p: bad m_nextpkt in get", m));
837 ++mbtypes[gd->gd_cpuid].stats[type];
838 ++mbstat[gd->gd_cpuid].m_mbufs;
846 m_get(int how, int type)
850 int ocf = MB_OCFLAG(how);
854 m = objcache_get(mbuf_cache, ocf);
857 if ((ocf & M_WAITOK) && ntries++ == 0) {
858 struct objcache *reclaimlist[] = {
861 mbufphdrcluster_cache,
863 mbufphdrjcluster_cache
865 const int nreclaims = NELEM(reclaimlist);
867 if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
871 ++mbstat[mycpu->gd_cpuid].m_drops;
875 KASSERT(m->m_data == m->m_dat, ("mbuf %p: bad m_data in get", m));
879 updatestats(m, type);
884 m_gethdr(int how, int type)
887 int ocf = MB_OCFLAG(how);
892 m = objcache_get(mbufphdr_cache, ocf);
895 if ((ocf & M_WAITOK) && ntries++ == 0) {
896 struct objcache *reclaimlist[] = {
898 mbufcluster_cache, mbufphdrcluster_cache,
899 mbufjcluster_cache, mbufphdrjcluster_cache
901 const int nreclaims = NELEM(reclaimlist);
903 if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
907 ++mbstat[mycpu->gd_cpuid].m_drops;
911 KASSERT(m->m_data == m->m_pktdat, ("mbuf %p: bad m_data in get", m));
916 updatestats(m, type);
921 * Get a mbuf (not a mbuf cluster!) and zero it.
925 m_getclr(int how, int type)
929 m = m_get(how, type);
931 bzero(m->m_data, MLEN);
936 m_getcl_cache(int how, short type, int flags, struct objcache *mbclc,
937 struct objcache *mbphclc, u_long *cl_stats)
939 struct mbuf *m = NULL;
940 int ocflags = MB_OCFLAG(how);
945 if (flags & M_PKTHDR)
946 m = objcache_get(mbphclc, ocflags);
948 m = objcache_get(mbclc, ocflags);
951 if ((ocflags & M_WAITOK) && ntries++ == 0) {
952 struct objcache *reclaimlist[1];
954 if (flags & M_PKTHDR)
955 reclaimlist[0] = mbclc;
957 reclaimlist[0] = mbphclc;
958 if (!objcache_reclaimlist(reclaimlist, 1, ocflags))
962 ++mbstat[mycpu->gd_cpuid].m_drops;
967 KASSERT(m->m_data == m->m_ext.ext_buf,
968 ("mbuf %p: bad m_data in get", m));
972 m->m_pkthdr.len = 0; /* just do it unconditonally */
976 ++mbtypes[mycpu->gd_cpuid].stats[type];
982 m_getjcl(int how, short type, int flags, size_t size)
984 struct objcache *mbclc, *mbphclc;
989 mbclc = mbufcluster_cache;
990 mbphclc = mbufphdrcluster_cache;
991 cl_stats = &mbstat[mycpu->gd_cpuid].m_clusters;
995 mbclc = mbufjcluster_cache;
996 mbphclc = mbufphdrjcluster_cache;
997 cl_stats = &mbstat[mycpu->gd_cpuid].m_jclusters;
1000 return m_getcl_cache(how, type, flags, mbclc, mbphclc, cl_stats);
1004 * Returns an mbuf with an attached cluster.
1005 * Because many network drivers use this kind of buffers a lot, it is
1006 * convenient to keep a small pool of free buffers of this kind.
1007 * Even a small size such as 10 gives about 10% improvement in the
1008 * forwarding rate in a bridge or router.
1011 m_getcl(int how, short type, int flags)
1013 return m_getcl_cache(how, type, flags,
1014 mbufcluster_cache, mbufphdrcluster_cache,
1015 &mbstat[mycpu->gd_cpuid].m_clusters);
1019 * Allocate chain of requested length.
1022 m_getc(int len, int how, int type)
1024 struct mbuf *n, *nfirst = NULL, **ntail = &nfirst;
1028 n = m_getl(len, how, type, 0, &nsize);
1044 * Allocate len-worth of mbufs and/or mbuf clusters (whatever fits best)
1045 * and return a pointer to the head of the allocated chain. If m0 is
1046 * non-null, then we assume that it is a single mbuf or an mbuf chain to
1047 * which we want len bytes worth of mbufs and/or clusters attached, and so
1048 * if we succeed in allocating it, we will just return a pointer to m0.
1050 * If we happen to fail at any point during the allocation, we will free
1051 * up everything we have already allocated and return NULL.
1053 * Deprecated. Use m_getc() and m_cat() instead.
1056 m_getm(struct mbuf *m0, int len, int type, int how)
1058 struct mbuf *nfirst;
1060 nfirst = m_getc(len, how, type);
1063 m_last(m0)->m_next = nfirst;
1071 * Adds a cluster to a normal mbuf, M_EXT is set on success.
1072 * Deprecated. Use m_getcl() instead.
1075 m_mclget(struct mbuf *m, int how)
1077 struct mbcluster *mcl;
1079 KKASSERT((m->m_flags & M_EXT) == 0);
1080 mcl = objcache_get(mclmeta_cache, MB_OCFLAG(how));
1082 linkcluster(m, mcl);
1083 ++mbstat[mycpu->gd_cpuid].m_clusters;
1085 ++mbstat[mycpu->gd_cpuid].m_drops;
1090 * Updates to mbcluster must be MPSAFE. Only an entity which already has
1091 * a reference to the cluster can ref it, so we are in no danger of
1092 * racing an add with a subtract. But the operation must still be atomic
1093 * since multiple entities may have a reference on the cluster.
1095 * m_mclfree() is almost the same but it must contend with two entities
1096 * freeing the cluster at the same time.
1101 struct mbcluster *mcl = arg;
1103 atomic_add_int(&mcl->mcl_refs, 1);
1107 * When dereferencing a cluster we have to deal with a N->0 race, where
1108 * N entities free their references simultaniously. To do this we use
1109 * atomic_fetchadd_int().
1112 m_mclfree(void *arg)
1114 struct mbcluster *mcl = arg;
1116 if (atomic_fetchadd_int(&mcl->mcl_refs, -1) == 1) {
1117 --mbstat[mycpu->gd_cpuid].m_clusters;
1118 objcache_put(mclmeta_cache, mcl);
1123 m_mjclfree(void *arg)
1125 struct mbcluster *mcl = arg;
1127 if (atomic_fetchadd_int(&mcl->mcl_refs, -1) == 1) {
1128 --mbstat[mycpu->gd_cpuid].m_jclusters;
1129 objcache_put(mjclmeta_cache, mcl);
1134 * Free a single mbuf and any associated external storage. The successor,
1135 * if any, is returned.
1137 * We do need to check non-first mbuf for m_aux, since some of existing
1138 * code does not call M_PREPEND properly.
1139 * (example: call to bpf_mtap from drivers)
1145 _m_free(struct mbuf *m, const char *func)
1150 m_free(struct mbuf *m)
1155 struct globaldata *gd = mycpu;
1157 KASSERT(m->m_type != MT_FREE, ("freeing free mbuf %p", m));
1158 KASSERT(M_TRAILINGSPACE(m) >= 0, ("overflowed mbuf %p", m));
1159 --mbtypes[gd->gd_cpuid].stats[m->m_type];
1164 * Make sure the mbuf is in constructed state before returning it
1170 m->m_hdr.mh_lastfunc = func;
1173 KKASSERT(m->m_nextpkt == NULL);
1175 if (m->m_nextpkt != NULL) {
1176 static int afewtimes = 10;
1178 if (afewtimes-- > 0) {
1179 kprintf("mfree: m->m_nextpkt != NULL\n");
1180 print_backtrace(-1);
1182 m->m_nextpkt = NULL;
1185 if (m->m_flags & M_PKTHDR) {
1186 m_tag_delete_chain(m); /* eliminate XXX JH */
1189 m->m_flags &= (M_EXT | M_EXT_CLUSTER | M_CLCACHE | M_PHCACHE);
1192 * Clean the M_PKTHDR state so we can return the mbuf to its original
1193 * cache. This is based on the PHCACHE flag which tells us whether
1194 * the mbuf was originally allocated out of a packet-header cache
1195 * or a non-packet-header cache.
1197 if (m->m_flags & M_PHCACHE) {
1198 m->m_flags |= M_PKTHDR;
1199 m->m_pkthdr.rcvif = NULL; /* eliminate XXX JH */
1200 m->m_pkthdr.csum_flags = 0; /* eliminate XXX JH */
1201 m->m_pkthdr.fw_flags = 0; /* eliminate XXX JH */
1202 SLIST_INIT(&m->m_pkthdr.tags);
1206 * Handle remaining flags combinations. M_CLCACHE tells us whether
1207 * the mbuf was originally allocated from a cluster cache or not,
1208 * and is totally separate from whether the mbuf is currently
1209 * associated with a cluster.
1211 switch(m->m_flags & (M_CLCACHE | M_EXT | M_EXT_CLUSTER)) {
1212 case M_CLCACHE | M_EXT | M_EXT_CLUSTER:
1214 * mbuf+cluster cache case. The mbuf was allocated from the
1215 * combined mbuf_cluster cache and can be returned to the
1216 * cache if the cluster hasn't been shared.
1218 if (m_sharecount(m) == 1) {
1220 * The cluster has not been shared, we can just
1221 * reset the data pointer and return the mbuf
1222 * to the cluster cache. Note that the reference
1223 * count is left intact (it is still associated with
1226 m->m_data = m->m_ext.ext_buf;
1227 if (m->m_flags & M_EXT && m->m_ext.ext_size != MCLBYTES) {
1228 if (m->m_flags & M_PHCACHE)
1229 objcache_put(mbufphdrjcluster_cache, m);
1231 objcache_put(mbufjcluster_cache, m);
1232 --mbstat[mycpu->gd_cpuid].m_jclusters;
1234 if (m->m_flags & M_PHCACHE)
1235 objcache_put(mbufphdrcluster_cache, m);
1237 objcache_put(mbufcluster_cache, m);
1238 --mbstat[mycpu->gd_cpuid].m_clusters;
1242 * Hell. Someone else has a ref on this cluster,
1243 * we have to disconnect it which means we can't
1244 * put it back into the mbufcluster_cache, we
1245 * have to destroy the mbuf.
1247 * Other mbuf references to the cluster will typically
1248 * be M_EXT | M_EXT_CLUSTER but without M_CLCACHE.
1250 * XXX we could try to connect another cluster to
1253 m->m_ext.ext_free(m->m_ext.ext_arg);
1254 m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
1255 if (m->m_ext.ext_size == MCLBYTES) {
1256 if (m->m_flags & M_PHCACHE)
1257 objcache_dtor(mbufphdrcluster_cache, m);
1259 objcache_dtor(mbufcluster_cache, m);
1261 if (m->m_flags & M_PHCACHE)
1262 objcache_dtor(mbufphdrjcluster_cache, m);
1264 objcache_dtor(mbufjcluster_cache, m);
1268 case M_EXT | M_EXT_CLUSTER:
1271 * Normal cluster association case, disconnect the cluster from
1272 * the mbuf. The cluster may or may not be custom.
1274 m->m_ext.ext_free(m->m_ext.ext_arg);
1275 m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
1279 * return the mbuf to the mbuf cache.
1281 if (m->m_flags & M_PHCACHE) {
1282 m->m_data = m->m_pktdat;
1283 objcache_put(mbufphdr_cache, m);
1285 m->m_data = m->m_dat;
1286 objcache_put(mbuf_cache, m);
1288 --mbstat[mycpu->gd_cpuid].m_mbufs;
1292 panic("bad mbuf flags %p %08x", m, m->m_flags);
1301 _m_freem(struct mbuf *m, const char *func)
1304 m = _m_free(m, func);
1310 m_freem(struct mbuf *m)
1319 m_extadd(struct mbuf *m, caddr_t buf, u_int size, void (*reff)(void *),
1320 void (*freef)(void *), void *arg)
1322 m->m_ext.ext_arg = arg;
1323 m->m_ext.ext_buf = buf;
1324 m->m_ext.ext_ref = reff;
1325 m->m_ext.ext_free = freef;
1326 m->m_ext.ext_size = size;
1329 m->m_flags |= M_EXT;
1333 * mbuf utility routines
1337 * Lesser-used path for M_PREPEND: allocate new mbuf to prepend to chain and
1341 m_prepend(struct mbuf *m, int len, int how)
1345 if (m->m_flags & M_PKTHDR)
1346 mn = m_gethdr(how, m->m_type);
1348 mn = m_get(how, m->m_type);
1353 if (m->m_flags & M_PKTHDR)
1354 M_MOVE_PKTHDR(mn, m);
1364 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
1365 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
1366 * The wait parameter is a choice of M_WAITOK/M_NOWAIT from caller.
1367 * Note that the copy is read-only, because clusters are not copied,
1368 * only their reference counts are incremented.
1371 m_copym(const struct mbuf *m, int off0, int len, int wait)
1373 struct mbuf *n, **np;
1378 KASSERT(off >= 0, ("m_copym, negative off %d", off));
1379 KASSERT(len >= 0, ("m_copym, negative len %d", len));
1380 if (off == 0 && (m->m_flags & M_PKTHDR))
1383 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
1393 KASSERT(len == M_COPYALL,
1394 ("m_copym, length > size of mbuf chain"));
1398 * Because we are sharing any cluster attachment below,
1399 * be sure to get an mbuf that does not have a cluster
1400 * associated with it.
1403 n = m_gethdr(wait, m->m_type);
1405 n = m_get(wait, m->m_type);
1410 if (!m_dup_pkthdr(n, m, wait))
1412 if (len == M_COPYALL)
1413 n->m_pkthdr.len -= off0;
1415 n->m_pkthdr.len = len;
1418 n->m_len = min(len, m->m_len - off);
1419 if (m->m_flags & M_EXT) {
1420 KKASSERT((n->m_flags & M_EXT) == 0);
1421 n->m_data = m->m_data + off;
1422 m->m_ext.ext_ref(m->m_ext.ext_arg);
1423 n->m_ext = m->m_ext;
1424 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1426 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
1427 (unsigned)n->m_len);
1429 if (len != M_COPYALL)
1436 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1440 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1445 * Copy an entire packet, including header (which must be present).
1446 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
1447 * Note that the copy is read-only, because clusters are not copied,
1448 * only their reference counts are incremented.
1449 * Preserve alignment of the first mbuf so if the creator has left
1450 * some room at the beginning (e.g. for inserting protocol headers)
1451 * the copies also have the room available.
1454 m_copypacket(struct mbuf *m, int how)
1456 struct mbuf *top, *n, *o;
1458 n = m_gethdr(how, m->m_type);
1463 if (!m_dup_pkthdr(n, m, how))
1465 n->m_len = m->m_len;
1466 if (m->m_flags & M_EXT) {
1467 KKASSERT((n->m_flags & M_EXT) == 0);
1468 n->m_data = m->m_data;
1469 m->m_ext.ext_ref(m->m_ext.ext_arg);
1470 n->m_ext = m->m_ext;
1471 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1473 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
1474 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1479 o = m_get(how, m->m_type);
1486 n->m_len = m->m_len;
1487 if (m->m_flags & M_EXT) {
1488 KKASSERT((n->m_flags & M_EXT) == 0);
1489 n->m_data = m->m_data;
1490 m->m_ext.ext_ref(m->m_ext.ext_arg);
1491 n->m_ext = m->m_ext;
1492 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1494 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1502 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1507 * Copy data from an mbuf chain starting "off" bytes from the beginning,
1508 * continuing for "len" bytes, into the indicated buffer.
1511 m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
1515 KASSERT(off >= 0, ("m_copydata, negative off %d", off));
1516 KASSERT(len >= 0, ("m_copydata, negative len %d", len));
1518 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
1525 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
1526 count = min(m->m_len - off, len);
1527 bcopy(mtod(m, caddr_t) + off, cp, count);
1536 * Copy a packet header mbuf chain into a completely new chain, including
1537 * copying any mbuf clusters. Use this instead of m_copypacket() when
1538 * you need a writable copy of an mbuf chain.
1541 m_dup(struct mbuf *m, int how)
1543 struct mbuf **p, *top = NULL;
1544 int remain, moff, nsize;
1549 KASSERT((m->m_flags & M_PKTHDR) != 0, ("%s: !PKTHDR", __func__));
1551 /* While there's more data, get a new mbuf, tack it on, and fill it */
1552 remain = m->m_pkthdr.len;
1555 while (remain > 0 || top == NULL) { /* allow m->m_pkthdr.len == 0 */
1558 /* Get the next new mbuf */
1559 n = m_getl(remain, how, m->m_type, top == NULL ? M_PKTHDR : 0,
1564 if (!m_dup_pkthdr(n, m, how))
1567 /* Link it into the new chain */
1571 /* Copy data from original mbuf(s) into new mbuf */
1573 while (n->m_len < nsize && m != NULL) {
1574 int chunk = min(nsize - n->m_len, m->m_len - moff);
1576 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1580 if (moff == m->m_len) {
1586 /* Check correct total mbuf length */
1587 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
1588 ("%s: bogus m_pkthdr.len", __func__));
1595 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1600 * Copy the non-packet mbuf data chain into a new set of mbufs, including
1601 * copying any mbuf clusters. This is typically used to realign a data
1602 * chain by nfs_realign().
1604 * The original chain is left intact. how should be M_WAITOK or M_NOWAIT
1605 * and NULL can be returned if M_NOWAIT is passed.
1607 * Be careful to use cluster mbufs, a large mbuf chain converted to non
1608 * cluster mbufs can exhaust our supply of mbufs.
1611 m_dup_data(struct mbuf *m, int how)
1613 struct mbuf **p, *n, *top = NULL;
1614 int mlen, moff, chunk, gsize, nsize;
1623 * Optimize the mbuf allocation but do not get too carried away.
1625 if (m->m_next || m->m_len > MLEN)
1626 if (m->m_flags & M_EXT && m->m_ext.ext_size == MCLBYTES)
1629 gsize = MJUMPAGESIZE;
1639 * Scan the mbuf chain until nothing is left, the new mbuf chain
1640 * will be allocated on the fly as needed.
1647 KKASSERT(m->m_type == MT_DATA);
1649 n = m_getl(gsize, how, MT_DATA, 0, &nsize);
1656 chunk = imin(mlen, nsize);
1657 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1672 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1677 * Concatenate mbuf chain n to m.
1678 * Both chains must be of the same type (e.g. MT_DATA).
1679 * Any m_pkthdr is not updated.
1682 m_cat(struct mbuf *m, struct mbuf *n)
1686 if (m->m_flags & M_EXT ||
1687 m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
1688 /* just join the two chains */
1692 /* splat the data from one into the other */
1693 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1695 m->m_len += n->m_len;
1701 m_adj(struct mbuf *mp, int req_len)
1707 if ((m = mp) == NULL)
1713 while (m != NULL && len > 0) {
1714 if (m->m_len <= len) {
1725 if (mp->m_flags & M_PKTHDR)
1726 m->m_pkthdr.len -= (req_len - len);
1729 * Trim from tail. Scan the mbuf chain,
1730 * calculating its length and finding the last mbuf.
1731 * If the adjustment only affects this mbuf, then just
1732 * adjust and return. Otherwise, rescan and truncate
1733 * after the remaining size.
1739 if (m->m_next == NULL)
1743 if (m->m_len >= len) {
1745 if (mp->m_flags & M_PKTHDR)
1746 mp->m_pkthdr.len -= len;
1753 * Correct length for chain is "count".
1754 * Find the mbuf with last data, adjust its length,
1755 * and toss data from remaining mbufs on chain.
1758 if (m->m_flags & M_PKTHDR)
1759 m->m_pkthdr.len = count;
1760 for (; m; m = m->m_next) {
1761 if (m->m_len >= count) {
1768 (m = m->m_next) ->m_len = 0;
1773 * Set the m_data pointer of a newly-allocated mbuf
1774 * to place an object of the specified size at the
1775 * end of the mbuf, longword aligned.
1778 m_align(struct mbuf *m, int len)
1782 if (m->m_flags & M_EXT)
1783 adjust = m->m_ext.ext_size - len;
1784 else if (m->m_flags & M_PKTHDR)
1785 adjust = MHLEN - len;
1787 adjust = MLEN - len;
1788 m->m_data += adjust &~ (sizeof(long)-1);
1792 * Create a writable copy of the mbuf chain. While doing this
1793 * we compact the chain with a goal of producing a chain with
1794 * at most two mbufs. The second mbuf in this chain is likely
1795 * to be a cluster. The primary purpose of this work is to create
1796 * a writable packet for encryption, compression, etc. The
1797 * secondary goal is to linearize the data so the data can be
1798 * passed to crypto hardware in the most efficient manner possible.
1801 m_unshare(struct mbuf *m0, int how)
1803 struct mbuf *m, *mprev;
1804 struct mbuf *n, *mfirst, *mlast;
1808 for (m = m0; m != NULL; m = mprev->m_next) {
1810 * Regular mbufs are ignored unless there's a cluster
1811 * in front of it that we can use to coalesce. We do
1812 * the latter mainly so later clusters can be coalesced
1813 * also w/o having to handle them specially (i.e. convert
1814 * mbuf+cluster -> cluster). This optimization is heavily
1815 * influenced by the assumption that we're running over
1816 * Ethernet where MCLBYTES is large enough that the max
1817 * packet size will permit lots of coalescing into a
1818 * single cluster. This in turn permits efficient
1819 * crypto operations, especially when using hardware.
1821 if ((m->m_flags & M_EXT) == 0) {
1822 if (mprev && (mprev->m_flags & M_EXT) &&
1823 m->m_len <= M_TRAILINGSPACE(mprev)) {
1824 /* XXX: this ignores mbuf types */
1825 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1826 mtod(m, caddr_t), m->m_len);
1827 mprev->m_len += m->m_len;
1828 mprev->m_next = m->m_next; /* unlink from chain */
1829 m_free(m); /* reclaim mbuf */
1836 * Writable mbufs are left alone (for now).
1838 if (M_WRITABLE(m)) {
1844 * Not writable, replace with a copy or coalesce with
1845 * the previous mbuf if possible (since we have to copy
1846 * it anyway, we try to reduce the number of mbufs and
1847 * clusters so that future work is easier).
1849 KASSERT(m->m_flags & M_EXT, ("m_flags 0x%x", m->m_flags));
1850 /* NB: we only coalesce into a cluster or larger */
1851 if (mprev != NULL && (mprev->m_flags & M_EXT) &&
1852 m->m_len <= M_TRAILINGSPACE(mprev)) {
1853 /* XXX: this ignores mbuf types */
1854 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1855 mtod(m, caddr_t), m->m_len);
1856 mprev->m_len += m->m_len;
1857 mprev->m_next = m->m_next; /* unlink from chain */
1858 m_free(m); /* reclaim mbuf */
1863 * Allocate new space to hold the copy...
1865 /* XXX why can M_PKTHDR be set past the first mbuf? */
1866 if (mprev == NULL && (m->m_flags & M_PKTHDR)) {
1868 * NB: if a packet header is present we must
1869 * allocate the mbuf separately from any cluster
1870 * because M_MOVE_PKTHDR will smash the data
1871 * pointer and drop the M_EXT marker.
1873 MGETHDR(n, how, m->m_type);
1878 M_MOVE_PKTHDR(n, m);
1880 if ((n->m_flags & M_EXT) == 0) {
1886 n = m_getcl(how, m->m_type, m->m_flags);
1893 * ... and copy the data. We deal with jumbo mbufs
1894 * (i.e. m_len > MCLBYTES) by splitting them into
1895 * clusters. We could just malloc a buffer and make
1896 * it external but too many device drivers don't know
1897 * how to break up the non-contiguous memory when
1905 int cc = min(len, MCLBYTES);
1906 memcpy(mtod(n, caddr_t), mtod(m, caddr_t) + off, cc);
1917 n = m_getcl(how, m->m_type, m->m_flags);
1924 n->m_next = m->m_next;
1926 m0 = mfirst; /* new head of chain */
1928 mprev->m_next = mfirst; /* replace old mbuf */
1929 m_free(m); /* release old mbuf */
1936 * Rearrange an mbuf chain so that len bytes are contiguous
1937 * and in the data area of an mbuf (so that mtod will work for a structure
1938 * of size len). Returns the resulting mbuf chain on success, frees it and
1939 * returns null on failure. If there is room, it will add up to
1940 * max_protohdr-len extra bytes to the contiguous region in an attempt to
1941 * avoid being called next time.
1944 m_pullup(struct mbuf *n, int len)
1951 * If first mbuf has no cluster, and has room for len bytes
1952 * without shifting current data, pullup into it,
1953 * otherwise allocate a new mbuf to prepend to the chain.
1955 if (!(n->m_flags & M_EXT) &&
1956 n->m_data + len < &n->m_dat[MLEN] &&
1958 if (n->m_len >= len)
1966 if (n->m_flags & M_PKTHDR)
1967 m = m_gethdr(M_NOWAIT, n->m_type);
1969 m = m_get(M_NOWAIT, n->m_type);
1973 if (n->m_flags & M_PKTHDR)
1974 M_MOVE_PKTHDR(m, n);
1976 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1978 count = min(min(max(len, max_protohdr), space), n->m_len);
1979 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1989 } while (len > 0 && n);
1998 ++mbstat[mycpu->gd_cpuid].m_mcfail;
2003 * Partition an mbuf chain in two pieces, returning the tail --
2004 * all but the first len0 bytes. In case of failure, it returns NULL and
2005 * attempts to restore the chain to its original state.
2007 * Note that the resulting mbufs might be read-only, because the new
2008 * mbuf can end up sharing an mbuf cluster with the original mbuf if
2009 * the "breaking point" happens to lie within a cluster mbuf. Use the
2010 * M_WRITABLE() macro to check for this case.
2013 m_split(struct mbuf *m0, int len0, int wait)
2016 unsigned len = len0, remain;
2018 for (m = m0; m && len > m->m_len; m = m->m_next)
2022 remain = m->m_len - len;
2023 if (m0->m_flags & M_PKTHDR) {
2024 n = m_gethdr(wait, m0->m_type);
2027 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
2028 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
2029 m0->m_pkthdr.len = len0;
2030 if (m->m_flags & M_EXT)
2032 if (remain > MHLEN) {
2033 /* m can't be the lead packet */
2035 n->m_next = m_split(m, len, wait);
2036 if (n->m_next == NULL) {
2044 MH_ALIGN(n, remain);
2045 } else if (remain == 0) {
2050 n = m_get(wait, m->m_type);
2056 if (m->m_flags & M_EXT) {
2057 KKASSERT((n->m_flags & M_EXT) == 0);
2058 n->m_data = m->m_data + len;
2059 m->m_ext.ext_ref(m->m_ext.ext_arg);
2060 n->m_ext = m->m_ext;
2061 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
2063 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
2067 n->m_next = m->m_next;
2073 * Routine to copy from device local memory into mbufs.
2074 * Note: "offset" is ill-defined and always called as 0, so ignore it.
2077 m_devget(char *buf, int len, int offset, struct ifnet *ifp,
2078 void (*copy)(volatile const void *from, volatile void *to, size_t length))
2080 struct mbuf *m, *mfirst = NULL, **mtail;
2089 m = m_getl(len, M_NOWAIT, MT_DATA, flags, &nsize);
2094 m->m_len = min(len, nsize);
2096 if (flags & M_PKTHDR) {
2097 if (len + max_linkhdr <= nsize)
2098 m->m_data += max_linkhdr;
2099 m->m_pkthdr.rcvif = ifp;
2100 m->m_pkthdr.len = len;
2104 copy(buf, m->m_data, (unsigned)m->m_len);
2115 * Routine to pad mbuf to the specified length 'padto'.
2118 m_devpad(struct mbuf *m, int padto)
2120 struct mbuf *last = NULL;
2123 if (padto <= m->m_pkthdr.len)
2126 padlen = padto - m->m_pkthdr.len;
2128 /* if there's only the packet-header and we can pad there, use it. */
2129 if (m->m_pkthdr.len == m->m_len && M_TRAILINGSPACE(m) >= padlen) {
2133 * Walk packet chain to find last mbuf. We will either
2134 * pad there, or append a new mbuf and pad it
2136 for (last = m; last->m_next != NULL; last = last->m_next)
2139 /* `last' now points to last in chain. */
2140 if (M_TRAILINGSPACE(last) < padlen) {
2143 /* Allocate new empty mbuf, pad it. Compact later. */
2144 MGET(n, M_NOWAIT, MT_DATA);
2152 KKASSERT(M_TRAILINGSPACE(last) >= padlen);
2153 KKASSERT(M_WRITABLE(last));
2155 /* Now zero the pad area */
2156 bzero(mtod(last, char *) + last->m_len, padlen);
2157 last->m_len += padlen;
2158 m->m_pkthdr.len += padlen;
2163 * Copy data from a buffer back into the indicated mbuf chain,
2164 * starting "off" bytes from the beginning, extending the mbuf
2165 * chain if necessary.
2168 m_copyback(struct mbuf *m0, int off, int len, caddr_t cp)
2171 struct mbuf *m = m0, *n;
2176 while (off > (mlen = m->m_len)) {
2179 if (m->m_next == NULL) {
2180 n = m_getclr(M_NOWAIT, m->m_type);
2183 n->m_len = min(MLEN, len + off);
2189 mlen = min (m->m_len - off, len);
2190 bcopy(cp, off + mtod(m, caddr_t), (unsigned)mlen);
2198 if (m->m_next == NULL) {
2199 n = m_get(M_NOWAIT, m->m_type);
2202 n->m_len = min(MLEN, len);
2207 out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
2208 m->m_pkthdr.len = totlen;
2212 * Append the specified data to the indicated mbuf chain,
2213 * Extend the mbuf chain if the new data does not fit in
2216 * Return 1 if able to complete the job; otherwise 0.
2219 m_append(struct mbuf *m0, int len, c_caddr_t cp)
2222 int remainder, space;
2224 for (m = m0; m->m_next != NULL; m = m->m_next)
2227 space = M_TRAILINGSPACE(m);
2230 * Copy into available space.
2232 if (space > remainder)
2234 bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
2236 cp += space, remainder -= space;
2238 while (remainder > 0) {
2240 * Allocate a new mbuf; could check space
2241 * and allocate a cluster instead.
2243 n = m_get(M_NOWAIT, m->m_type);
2246 n->m_len = min(MLEN, remainder);
2247 bcopy(cp, mtod(n, caddr_t), n->m_len);
2248 cp += n->m_len, remainder -= n->m_len;
2252 if (m0->m_flags & M_PKTHDR)
2253 m0->m_pkthdr.len += len - remainder;
2254 return (remainder == 0);
2258 * Apply function f to the data in an mbuf chain starting "off" bytes from
2259 * the beginning, continuing for "len" bytes.
2262 m_apply(struct mbuf *m, int off, int len,
2263 int (*f)(void *, void *, u_int), void *arg)
2268 KASSERT(off >= 0, ("m_apply, negative off %d", off));
2269 KASSERT(len >= 0, ("m_apply, negative len %d", len));
2271 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
2278 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
2279 count = min(m->m_len - off, len);
2280 rval = (*f)(arg, mtod(m, caddr_t) + off, count);
2291 * Return a pointer to mbuf/offset of location in mbuf chain.
2294 m_getptr(struct mbuf *m, int loc, int *off)
2298 /* Normal end of search. */
2299 if (m->m_len > loc) {
2304 if (m->m_next == NULL) {
2306 /* Point at the end of valid data. */
2319 m_print(const struct mbuf *m)
2322 const struct mbuf *m2;
2325 len = m->m_pkthdr.len;
2327 hexstr = kmalloc(HEX_NCPYLEN(len), M_TEMP, M_ZERO | M_WAITOK);
2329 kprintf("%p %s\n", m2, hexncpy(m2->m_data, m2->m_len, hexstr,
2330 HEX_NCPYLEN(m2->m_len), "-"));
2334 kfree(hexstr, M_TEMP);
2339 * "Move" mbuf pkthdr from "from" to "to".
2340 * "from" must have M_PKTHDR set, and "to" must be empty.
2343 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
2345 KASSERT((to->m_flags & M_PKTHDR), ("m_move_pkthdr: not packet header"));
2347 to->m_flags |= from->m_flags & M_COPYFLAGS;
2348 to->m_pkthdr = from->m_pkthdr; /* especially tags */
2349 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
2353 * Duplicate "from"'s mbuf pkthdr in "to".
2354 * "from" must have M_PKTHDR set, and "to" must be empty.
2355 * In particular, this does a deep copy of the packet tags.
2358 m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
2360 KASSERT((to->m_flags & M_PKTHDR), ("m_dup_pkthdr: not packet header"));
2362 to->m_flags = (from->m_flags & M_COPYFLAGS) |
2363 (to->m_flags & ~M_COPYFLAGS);
2364 to->m_pkthdr = from->m_pkthdr;
2365 SLIST_INIT(&to->m_pkthdr.tags);
2366 return (m_tag_copy_chain(to, from, how));
2370 * Defragment a mbuf chain, returning the shortest possible
2371 * chain of mbufs and clusters. If allocation fails and
2372 * this cannot be completed, NULL will be returned, but
2373 * the passed in chain will be unchanged. Upon success,
2374 * the original chain will be freed, and the new chain
2377 * If a non-packet header is passed in, the original
2378 * mbuf (chain?) will be returned unharmed.
2380 * m_defrag_nofree doesn't free the passed in mbuf.
2383 m_defrag(struct mbuf *m0, int how)
2387 if ((m_new = m_defrag_nofree(m0, how)) == NULL)
2395 m_defrag_nofree(struct mbuf *m0, int how)
2397 struct mbuf *m_new = NULL, *m_final = NULL;
2398 int progress = 0, length, nsize;
2400 if (!(m0->m_flags & M_PKTHDR))
2403 #ifdef MBUF_STRESS_TEST
2404 if (m_defragrandomfailures) {
2405 int temp = karc4random() & 0xff;
2411 m_final = m_getl(m0->m_pkthdr.len, how, MT_DATA, M_PKTHDR, &nsize);
2412 if (m_final == NULL)
2414 m_final->m_len = 0; /* in case m0->m_pkthdr.len is zero */
2416 if (m_dup_pkthdr(m_final, m0, how) == 0)
2421 while (progress < m0->m_pkthdr.len) {
2422 length = m0->m_pkthdr.len - progress;
2423 if (length > MCLBYTES)
2426 if (m_new == NULL) {
2427 m_new = m_getl(length, how, MT_DATA, 0, &nsize);
2432 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
2434 m_new->m_len = length;
2435 if (m_new != m_final)
2436 m_cat(m_final, m_new);
2439 if (m0->m_next == NULL)
2442 m_defragbytes += m_final->m_pkthdr.len;
2453 * Move data from uio into mbufs.
2456 m_uiomove(struct uio *uio)
2458 struct mbuf *m; /* current working mbuf */
2459 struct mbuf *head = NULL; /* result mbuf chain */
2460 struct mbuf **mp = &head;
2461 int flags = M_PKTHDR;
2467 if (uio->uio_resid > INT_MAX)
2470 resid = (int)uio->uio_resid;
2471 m = m_getl(resid, M_WAITOK, MT_DATA, flags, &nsize);
2473 m->m_pkthdr.len = 0;
2474 /* Leave room for protocol headers. */
2479 m->m_len = imin(nsize, resid);
2480 error = uiomove(mtod(m, caddr_t), m->m_len, uio);
2487 head->m_pkthdr.len += m->m_len;
2488 } while (uio->uio_resid > 0);
2498 m_last(struct mbuf *m)
2506 * Return the number of bytes in an mbuf chain.
2507 * If lastm is not NULL, also return the last mbuf.
2510 m_lengthm(struct mbuf *m, struct mbuf **lastm)
2513 struct mbuf *prev = m;
2526 * Like m_lengthm(), except also keep track of mbuf usage.
2529 m_countm(struct mbuf *m, struct mbuf **lastm, u_int *pmbcnt)
2531 u_int len = 0, mbcnt = 0;
2532 struct mbuf *prev = m;
2537 if (m->m_flags & M_EXT)
2538 mbcnt += m->m_ext.ext_size;