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. All advertising materials mentioning features or use of this software
49 * must display the following acknowledgement:
50 * This product includes software developed by the University of
51 * California, Berkeley and its contributors.
52 * 4. Neither the name of the University nor the names of its contributors
53 * may be used to endorse or promote products derived from this software
54 * without specific prior written permission.
56 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
57 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
58 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
59 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
60 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
61 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
62 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
63 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
64 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
65 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68 * @(#)uipc_mbuf.c 8.2 (Berkeley) 1/4/94
69 * $FreeBSD: src/sys/kern/uipc_mbuf.c,v 1.51.2.24 2003/04/15 06:59:29 silby Exp $
72 #include "opt_param.h"
73 #include "opt_mbuf_stress_test.h"
74 #include <sys/param.h>
75 #include <sys/systm.h>
77 #include <sys/malloc.h>
79 #include <sys/kernel.h>
80 #include <sys/sysctl.h>
81 #include <sys/domain.h>
82 #include <sys/objcache.h>
84 #include <sys/protosw.h>
86 #include <sys/thread.h>
87 #include <sys/globaldata.h>
89 #include <sys/thread2.h>
90 #include <sys/spinlock2.h>
92 #include <machine/atomic.h>
93 #include <machine/limits.h>
96 #include <vm/vm_kern.h>
97 #include <vm/vm_extern.h>
100 #include <machine/cpu.h>
104 * mbuf cluster meta-data
112 * mbuf tracking for debugging purposes
116 static MALLOC_DEFINE(M_MTRACK, "mtrack", "mtrack");
119 RB_HEAD(mbuf_rb_tree, mbtrack);
120 RB_PROTOTYPE2(mbuf_rb_tree, mbtrack, rb_node, mbtrack_cmp, struct mbuf *);
123 RB_ENTRY(mbtrack) rb_node;
129 mbtrack_cmp(struct mbtrack *mb1, struct mbtrack *mb2)
138 RB_GENERATE2(mbuf_rb_tree, mbtrack, rb_node, mbtrack_cmp, struct mbuf *, m);
140 struct mbuf_rb_tree mbuf_track_root;
141 static struct spinlock mbuf_track_spin = SPINLOCK_INITIALIZER(mbuf_track_spin);
144 mbuftrack(struct mbuf *m)
148 mbt = kmalloc(sizeof(*mbt), M_MTRACK, M_INTWAIT|M_ZERO);
149 spin_lock(&mbuf_track_spin);
151 if (mbuf_rb_tree_RB_INSERT(&mbuf_track_root, mbt)) {
152 spin_unlock(&mbuf_track_spin);
153 panic("mbuftrack: mbuf %p already being tracked\n", m);
155 spin_unlock(&mbuf_track_spin);
159 mbufuntrack(struct mbuf *m)
163 spin_lock(&mbuf_track_spin);
164 mbt = mbuf_rb_tree_RB_LOOKUP(&mbuf_track_root, m);
166 spin_unlock(&mbuf_track_spin);
167 panic("mbufuntrack: mbuf %p was not tracked\n", m);
169 mbuf_rb_tree_RB_REMOVE(&mbuf_track_root, mbt);
170 spin_unlock(&mbuf_track_spin);
171 kfree(mbt, M_MTRACK);
176 mbuftrackid(struct mbuf *m, int trackid)
181 spin_lock(&mbuf_track_spin);
185 mbt = mbuf_rb_tree_RB_LOOKUP(&mbuf_track_root, m);
187 spin_unlock(&mbuf_track_spin);
188 panic("mbuftrackid: mbuf %p not tracked", m);
190 mbt->trackid = trackid;
195 spin_unlock(&mbuf_track_spin);
199 mbuftrack_callback(struct mbtrack *mbt, void *arg)
201 struct sysctl_req *req = arg;
205 ksnprintf(buf, sizeof(buf), "mbuf %p track %d\n", mbt->m, mbt->trackid);
207 spin_unlock(&mbuf_track_spin);
208 error = SYSCTL_OUT(req, buf, strlen(buf));
209 spin_lock(&mbuf_track_spin);
216 mbuftrack_show(SYSCTL_HANDLER_ARGS)
220 spin_lock(&mbuf_track_spin);
221 error = mbuf_rb_tree_RB_SCAN(&mbuf_track_root, NULL,
222 mbuftrack_callback, req);
223 spin_unlock(&mbuf_track_spin);
226 SYSCTL_PROC(_kern_ipc, OID_AUTO, showmbufs, CTLFLAG_RD|CTLTYPE_STRING,
227 0, 0, mbuftrack_show, "A", "Show all in-use mbufs");
232 #define mbufuntrack(m)
236 static void mbinit(void *);
237 SYSINIT(mbuf, SI_BOOT2_MACHDEP, SI_ORDER_FIRST, mbinit, NULL)
239 static u_long mbtypes[SMP_MAXCPU][MT_NTYPES];
241 static struct mbstat mbstat[SMP_MAXCPU];
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;
262 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RW,
263 &max_linkhdr, 0, "Max size of a link-level header");
264 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RW,
265 &max_protohdr, 0, "Max size of a protocol header");
266 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RW, &max_hdr, 0,
267 "Max size of link+protocol headers");
268 SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RW,
269 &max_datalen, 0, "Max data payload size without headers");
270 SYSCTL_INT(_kern_ipc, OID_AUTO, mbuf_wait, CTLFLAG_RW,
271 &mbuf_wait, 0, "Time in ticks to sleep after failed mbuf allocations");
272 static int do_mbstat(SYSCTL_HANDLER_ARGS);
274 SYSCTL_PROC(_kern_ipc, KIPC_MBSTAT, mbstat, CTLTYPE_STRUCT|CTLFLAG_RD,
275 0, 0, do_mbstat, "S,mbstat", "mbuf usage statistics");
277 static int do_mbtypes(SYSCTL_HANDLER_ARGS);
279 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbtypes, CTLTYPE_ULONG|CTLFLAG_RD,
280 0, 0, do_mbtypes, "LU", "");
283 do_mbstat(SYSCTL_HANDLER_ARGS)
285 struct mbstat mbstat_total;
286 struct mbstat *mbstat_totalp;
289 bzero(&mbstat_total, sizeof(mbstat_total));
290 mbstat_totalp = &mbstat_total;
292 for (i = 0; i < ncpus; i++)
294 mbstat_total.m_mbufs += mbstat[i].m_mbufs;
295 mbstat_total.m_clusters += mbstat[i].m_clusters;
296 mbstat_total.m_spare += mbstat[i].m_spare;
297 mbstat_total.m_clfree += mbstat[i].m_clfree;
298 mbstat_total.m_drops += mbstat[i].m_drops;
299 mbstat_total.m_wait += mbstat[i].m_wait;
300 mbstat_total.m_drain += mbstat[i].m_drain;
301 mbstat_total.m_mcfail += mbstat[i].m_mcfail;
302 mbstat_total.m_mpfail += mbstat[i].m_mpfail;
306 * The following fields are not cumulative fields so just
307 * get their values once.
309 mbstat_total.m_msize = mbstat[0].m_msize;
310 mbstat_total.m_mclbytes = mbstat[0].m_mclbytes;
311 mbstat_total.m_minclsize = mbstat[0].m_minclsize;
312 mbstat_total.m_mlen = mbstat[0].m_mlen;
313 mbstat_total.m_mhlen = mbstat[0].m_mhlen;
315 return(sysctl_handle_opaque(oidp, mbstat_totalp, sizeof(mbstat_total), req));
319 do_mbtypes(SYSCTL_HANDLER_ARGS)
321 u_long totals[MT_NTYPES];
324 for (i = 0; i < MT_NTYPES; i++)
327 for (i = 0; i < ncpus; i++)
329 for (j = 0; j < MT_NTYPES; j++)
330 totals[j] += mbtypes[i][j];
333 return(sysctl_handle_opaque(oidp, totals, sizeof(totals), req));
337 * These are read-only because we do not currently have any code
338 * to adjust the objcache limits after the fact. The variables
339 * may only be set as boot-time tunables.
341 SYSCTL_INT(_kern_ipc, KIPC_NMBCLUSTERS, nmbclusters, CTLFLAG_RD,
342 &nmbclusters, 0, "Maximum number of mbuf clusters available");
343 SYSCTL_INT(_kern_ipc, OID_AUTO, nmbufs, CTLFLAG_RD, &nmbufs, 0,
344 "Maximum number of mbufs available");
346 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
347 &m_defragpackets, 0, "Number of defragment packets");
348 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
349 &m_defragbytes, 0, "Number of defragment bytes");
350 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
351 &m_defraguseless, 0, "Number of useless defragment mbuf chain operations");
352 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
353 &m_defragfailure, 0, "Number of failed defragment mbuf chain operations");
354 #ifdef MBUF_STRESS_TEST
355 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
356 &m_defragrandomfailures, 0, "");
359 static MALLOC_DEFINE(M_MBUF, "mbuf", "mbuf");
360 static MALLOC_DEFINE(M_MBUFCL, "mbufcl", "mbufcl");
361 static MALLOC_DEFINE(M_MJBUFCL, "mbufcl", "mbufcl");
362 static MALLOC_DEFINE(M_MCLMETA, "mclmeta", "mclmeta");
363 static MALLOC_DEFINE(M_MJCLMETA, "mjclmeta", "mjclmeta");
365 static void m_reclaim (void);
366 static void m_mclref(void *arg);
367 static void m_mclfree(void *arg);
370 * NOTE: Default NMBUFS must take into account a possible DOS attack
371 * using fd passing on unix domain sockets.
374 #define NMBCLUSTERS (512 + maxusers * 16)
377 #define NMBUFS (nmbclusters * 2 + maxfiles)
381 * Perform sanity checks of tunables declared above.
384 tunable_mbinit(void *dummy)
387 * This has to be done before VM init.
389 nmbclusters = NMBCLUSTERS;
390 TUNABLE_INT_FETCH("kern.ipc.nmbclusters", &nmbclusters);
392 TUNABLE_INT_FETCH("kern.ipc.nmbufs", &nmbufs);
394 if (nmbufs < nmbclusters * 2)
395 nmbufs = nmbclusters * 2;
397 SYSINIT(tunable_mbinit, SI_BOOT1_TUNABLES, SI_ORDER_ANY,
398 tunable_mbinit, NULL);
400 /* "number of clusters of pages" */
406 * The mbuf object cache only guarantees that m_next and m_nextpkt are
407 * NULL and that m_data points to the beginning of the data area. In
408 * particular, m_len and m_pkthdr.len are uninitialized. It is the
409 * responsibility of the caller to initialize those fields before use.
412 static __inline boolean_t
413 mbuf_ctor(void *obj, void *private, int ocflags)
415 struct mbuf *m = obj;
419 m->m_data = m->m_dat;
426 * Initialize the mbuf and the packet header fields.
429 mbufphdr_ctor(void *obj, void *private, int ocflags)
431 struct mbuf *m = obj;
435 m->m_data = m->m_pktdat;
436 m->m_flags = M_PKTHDR | M_PHCACHE;
438 m->m_pkthdr.rcvif = NULL; /* eliminate XXX JH */
439 SLIST_INIT(&m->m_pkthdr.tags);
440 m->m_pkthdr.csum_flags = 0; /* eliminate XXX JH */
441 m->m_pkthdr.fw_flags = 0; /* eliminate XXX JH */
447 * A mbcluster object consists of 2K (MCLBYTES) cluster and a refcount.
450 mclmeta_ctor(void *obj, void *private, int ocflags)
452 struct mbcluster *cl = obj;
455 if (ocflags & M_NOWAIT)
456 buf = kmalloc(MCLBYTES, M_MBUFCL, M_NOWAIT | M_ZERO);
458 buf = kmalloc(MCLBYTES, M_MBUFCL, M_INTWAIT | M_ZERO);
467 mjclmeta_ctor(void *obj, void *private, int ocflags)
469 struct mbcluster *cl = obj;
472 if (ocflags & M_NOWAIT)
473 buf = kmalloc(MJUMPAGESIZE, M_MBUFCL, M_NOWAIT | M_ZERO);
475 buf = kmalloc(MJUMPAGESIZE, M_MBUFCL, M_INTWAIT | M_ZERO);
484 mclmeta_dtor(void *obj, void *private)
486 struct mbcluster *mcl = obj;
488 KKASSERT(mcl->mcl_refs == 0);
489 kfree(mcl->mcl_data, M_MBUFCL);
493 linkjcluster(struct mbuf *m, struct mbcluster *cl, uint size)
496 * Add the cluster to the mbuf. The caller will detect that the
497 * mbuf now has an attached cluster.
499 m->m_ext.ext_arg = cl;
500 m->m_ext.ext_buf = cl->mcl_data;
501 m->m_ext.ext_ref = m_mclref;
502 m->m_ext.ext_free = m_mclfree;
503 m->m_ext.ext_size = size;
504 atomic_add_int(&cl->mcl_refs, 1);
506 m->m_data = m->m_ext.ext_buf;
507 m->m_flags |= M_EXT | M_EXT_CLUSTER;
511 linkcluster(struct mbuf *m, struct mbcluster *cl)
513 linkjcluster(m, cl, MCLBYTES);
517 mbufphdrcluster_ctor(void *obj, void *private, int ocflags)
519 struct mbuf *m = obj;
520 struct mbcluster *cl;
522 mbufphdr_ctor(obj, private, ocflags);
523 cl = objcache_get(mclmeta_cache, ocflags);
525 ++mbstat[mycpu->gd_cpuid].m_drops;
528 m->m_flags |= M_CLCACHE;
534 mbufphdrjcluster_ctor(void *obj, void *private, int ocflags)
536 struct mbuf *m = obj;
537 struct mbcluster *cl;
539 mbufphdr_ctor(obj, private, ocflags);
540 cl = objcache_get(mjclmeta_cache, ocflags);
542 ++mbstat[mycpu->gd_cpuid].m_drops;
545 m->m_flags |= M_CLCACHE;
546 linkjcluster(m, cl, MJUMPAGESIZE);
551 mbufcluster_ctor(void *obj, void *private, int ocflags)
553 struct mbuf *m = obj;
554 struct mbcluster *cl;
556 mbuf_ctor(obj, private, ocflags);
557 cl = objcache_get(mclmeta_cache, ocflags);
559 ++mbstat[mycpu->gd_cpuid].m_drops;
562 m->m_flags |= M_CLCACHE;
568 mbufjcluster_ctor(void *obj, void *private, int ocflags)
570 struct mbuf *m = obj;
571 struct mbcluster *cl;
573 mbuf_ctor(obj, private, ocflags);
574 cl = objcache_get(mjclmeta_cache, ocflags);
576 ++mbstat[mycpu->gd_cpuid].m_drops;
579 m->m_flags |= M_CLCACHE;
580 linkjcluster(m, cl, MJUMPAGESIZE);
585 * Used for both the cluster and cluster PHDR caches.
587 * The mbuf may have lost its cluster due to sharing, deal
588 * with the situation by checking M_EXT.
591 mbufcluster_dtor(void *obj, void *private)
593 struct mbuf *m = obj;
594 struct mbcluster *mcl;
596 if (m->m_flags & M_EXT) {
597 KKASSERT((m->m_flags & M_EXT_CLUSTER) != 0);
598 mcl = m->m_ext.ext_arg;
599 KKASSERT(mcl->mcl_refs == 1);
601 if (m->m_flags & M_EXT && m->m_ext.ext_size != MCLBYTES)
602 objcache_put(mjclmeta_cache, mcl);
604 objcache_put(mclmeta_cache, mcl);
608 struct objcache_malloc_args mbuf_malloc_args = { MSIZE, M_MBUF };
609 struct objcache_malloc_args mclmeta_malloc_args =
610 { sizeof(struct mbcluster), M_MCLMETA };
616 int mb_limit, cl_limit;
621 * Initialize statistics
623 for (i = 0; i < ncpus; i++) {
624 mbstat[i].m_msize = MSIZE;
625 mbstat[i].m_mclbytes = MCLBYTES;
626 mbstat[i].m_mjumpagesize = MJUMPAGESIZE;
627 mbstat[i].m_minclsize = MINCLSIZE;
628 mbstat[i].m_mlen = MLEN;
629 mbstat[i].m_mhlen = MHLEN;
633 * Create objtect caches and save cluster limits, which will
634 * be used to adjust backing kmalloc pools' limit later.
637 mb_limit = cl_limit = 0;
640 mbuf_cache = objcache_create("mbuf",
642 mbuf_ctor, NULL, NULL,
643 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
647 mbufphdr_cache = objcache_create("mbuf pkt hdr",
649 mbufphdr_ctor, NULL, NULL,
650 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
653 cl_limit = nmbclusters;
654 mclmeta_cache = objcache_create("cluster mbuf",
656 mclmeta_ctor, mclmeta_dtor, NULL,
657 objcache_malloc_alloc, objcache_malloc_free, &mclmeta_malloc_args);
659 cl_limit = nmbclusters;
660 mjclmeta_cache = objcache_create("jcluster mbuf",
662 mjclmeta_ctor, mclmeta_dtor, NULL,
663 objcache_malloc_alloc, objcache_malloc_free, &mclmeta_malloc_args);
666 mbufcluster_cache = objcache_create("mbuf + cluster",
668 mbufcluster_ctor, mbufcluster_dtor, NULL,
669 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
673 mbufphdrcluster_cache = objcache_create("mbuf pkt hdr + cluster",
674 &limit, nmbclusters / 16,
675 mbufphdrcluster_ctor, mbufcluster_dtor, NULL,
676 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
680 mbufjcluster_cache = objcache_create("mbuf + jcluster",
682 mbufjcluster_ctor, mbufcluster_dtor, NULL,
683 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
686 mbufphdrjcluster_cache = objcache_create("mbuf pkt hdr + jcluster",
687 &limit, nmbclusters / 16,
688 mbufphdrjcluster_ctor, mbufcluster_dtor, NULL,
689 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
692 * Adjust backing kmalloc pools' limit
694 * NOTE: We raise the limit by another 1/8 to take the effect
695 * of loosememuse into account.
697 cl_limit += cl_limit / 8;
698 kmalloc_raise_limit(mclmeta_malloc_args.mtype,
699 mclmeta_malloc_args.objsize * (size_t)cl_limit);
700 kmalloc_raise_limit(M_MBUFCL,
701 ((MCLBYTES * (size_t)cl_limit * 3) / 4) +
702 ((MJUMPAGESIZE * (size_t)cl_limit) / 4));
704 mb_limit += mb_limit / 8;
705 kmalloc_raise_limit(mbuf_malloc_args.mtype,
706 mbuf_malloc_args.objsize * (size_t)mb_limit);
710 * Return the number of references to this mbuf's data. 0 is returned
711 * if the mbuf is not M_EXT, a reference count is returned if it is
712 * M_EXT | M_EXT_CLUSTER, and 99 is returned if it is a special M_EXT.
715 m_sharecount(struct mbuf *m)
717 switch (m->m_flags & (M_EXT | M_EXT_CLUSTER)) {
722 case M_EXT | M_EXT_CLUSTER:
723 return (((struct mbcluster *)m->m_ext.ext_arg)->mcl_refs);
726 return (0); /* to shut up compiler */
730 * change mbuf to new type
733 m_chtype(struct mbuf *m, int type)
735 struct globaldata *gd = mycpu;
737 ++mbtypes[gd->gd_cpuid][type];
738 --mbtypes[gd->gd_cpuid][m->m_type];
748 kprintf("Debug: m_reclaim() called\n");
750 SLIST_FOREACH(dp, &domains, dom_next) {
751 for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++) {
756 ++mbstat[mycpu->gd_cpuid].m_drain;
760 updatestats(struct mbuf *m, int type)
762 struct globaldata *gd = mycpu;
767 KASSERT(m->m_next == NULL, ("mbuf %p: bad m_next in get", m));
768 KASSERT(m->m_nextpkt == NULL, ("mbuf %p: bad m_nextpkt in get", m));
771 ++mbtypes[gd->gd_cpuid][type];
772 ++mbstat[gd->gd_cpuid].m_mbufs;
780 m_get(int how, int type)
784 int ocf = MBTOM(how);
788 m = objcache_get(mbuf_cache, ocf);
791 if ((how & MB_TRYWAIT) && ntries++ == 0) {
792 struct objcache *reclaimlist[] = {
795 mbufphdrcluster_cache,
797 mbufphdrjcluster_cache
799 const int nreclaims = NELEM(reclaimlist);
801 if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
805 ++mbstat[mycpu->gd_cpuid].m_drops;
809 KASSERT(m->m_data == m->m_dat, ("mbuf %p: bad m_data in get", m));
813 updatestats(m, type);
818 m_gethdr(int how, int type)
821 int ocf = MBTOM(how);
826 m = objcache_get(mbufphdr_cache, ocf);
829 if ((how & MB_TRYWAIT) && ntries++ == 0) {
830 struct objcache *reclaimlist[] = {
832 mbufcluster_cache, mbufphdrcluster_cache,
833 mbufjcluster_cache, mbufphdrjcluster_cache
835 const int nreclaims = NELEM(reclaimlist);
837 if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
841 ++mbstat[mycpu->gd_cpuid].m_drops;
845 KASSERT(m->m_data == m->m_pktdat, ("mbuf %p: bad m_data in get", m));
850 updatestats(m, type);
855 * Get a mbuf (not a mbuf cluster!) and zero it.
859 m_getclr(int how, int type)
863 m = m_get(how, type);
865 bzero(m->m_data, MLEN);
870 m_getjcl(int how, short type, int flags, size_t size)
872 struct mbuf *m = NULL;
873 struct objcache *mbclc, *mbphclc;
874 int ocflags = MBTOM(how);
879 mbclc = mbufcluster_cache;
880 mbphclc = mbufphdrcluster_cache;
883 mbclc = mbufjcluster_cache;
884 mbphclc = mbufphdrjcluster_cache;
890 if (flags & M_PKTHDR)
891 m = objcache_get(mbphclc, ocflags);
893 m = objcache_get(mbclc, ocflags);
896 if ((how & MB_TRYWAIT) && ntries++ == 0) {
897 struct objcache *reclaimlist[1];
899 if (flags & M_PKTHDR)
900 reclaimlist[0] = mbclc;
902 reclaimlist[0] = mbphclc;
903 if (!objcache_reclaimlist(reclaimlist, 1, ocflags))
907 ++mbstat[mycpu->gd_cpuid].m_drops;
912 KASSERT(m->m_data == m->m_ext.ext_buf,
913 ("mbuf %p: bad m_data in get", m));
917 m->m_pkthdr.len = 0; /* just do it unconditonally */
921 ++mbtypes[mycpu->gd_cpuid][type];
922 ++mbstat[mycpu->gd_cpuid].m_clusters;
927 * Returns an mbuf with an attached cluster.
928 * Because many network drivers use this kind of buffers a lot, it is
929 * convenient to keep a small pool of free buffers of this kind.
930 * Even a small size such as 10 gives about 10% improvement in the
931 * forwarding rate in a bridge or router.
934 m_getcl(int how, short type, int flags)
936 return (m_getjcl(how, type, flags, MCLBYTES));
940 * Allocate chain of requested length.
943 m_getc(int len, int how, int type)
945 struct mbuf *n, *nfirst = NULL, **ntail = &nfirst;
949 n = m_getl(len, how, type, 0, &nsize);
965 * Allocate len-worth of mbufs and/or mbuf clusters (whatever fits best)
966 * and return a pointer to the head of the allocated chain. If m0 is
967 * non-null, then we assume that it is a single mbuf or an mbuf chain to
968 * which we want len bytes worth of mbufs and/or clusters attached, and so
969 * if we succeed in allocating it, we will just return a pointer to m0.
971 * If we happen to fail at any point during the allocation, we will free
972 * up everything we have already allocated and return NULL.
974 * Deprecated. Use m_getc() and m_cat() instead.
977 m_getm(struct mbuf *m0, int len, int type, int how)
981 nfirst = m_getc(len, how, type);
984 m_last(m0)->m_next = nfirst;
992 * Adds a cluster to a normal mbuf, M_EXT is set on success.
993 * Deprecated. Use m_getcl() instead.
996 m_mclget(struct mbuf *m, int how)
998 struct mbcluster *mcl;
1000 KKASSERT((m->m_flags & M_EXT) == 0);
1001 mcl = objcache_get(mclmeta_cache, MBTOM(how));
1003 linkcluster(m, mcl);
1004 ++mbstat[mycpu->gd_cpuid].m_clusters;
1006 ++mbstat[mycpu->gd_cpuid].m_drops;
1011 * Updates to mbcluster must be MPSAFE. Only an entity which already has
1012 * a reference to the cluster can ref it, so we are in no danger of
1013 * racing an add with a subtract. But the operation must still be atomic
1014 * since multiple entities may have a reference on the cluster.
1016 * m_mclfree() is almost the same but it must contend with two entities
1017 * freeing the cluster at the same time.
1022 struct mbcluster *mcl = arg;
1024 atomic_add_int(&mcl->mcl_refs, 1);
1028 * When dereferencing a cluster we have to deal with a N->0 race, where
1029 * N entities free their references simultaniously. To do this we use
1030 * atomic_fetchadd_int().
1033 m_mclfree(void *arg)
1035 struct mbcluster *mcl = arg;
1037 if (atomic_fetchadd_int(&mcl->mcl_refs, -1) == 1) {
1038 --mbstat[mycpu->gd_cpuid].m_clusters;
1039 objcache_put(mclmeta_cache, mcl);
1044 * Free a single mbuf and any associated external storage. The successor,
1045 * if any, is returned.
1047 * We do need to check non-first mbuf for m_aux, since some of existing
1048 * code does not call M_PREPEND properly.
1049 * (example: call to bpf_mtap from drivers)
1055 _m_free(struct mbuf *m, const char *func)
1060 m_free(struct mbuf *m)
1065 struct globaldata *gd = mycpu;
1067 KASSERT(m->m_type != MT_FREE, ("freeing free mbuf %p", m));
1068 KASSERT(M_TRAILINGSPACE(m) >= 0, ("overflowed mbuf %p", m));
1069 --mbtypes[gd->gd_cpuid][m->m_type];
1074 * Make sure the mbuf is in constructed state before returning it
1080 m->m_hdr.mh_lastfunc = func;
1083 KKASSERT(m->m_nextpkt == NULL);
1085 if (m->m_nextpkt != NULL) {
1086 static int afewtimes = 10;
1088 if (afewtimes-- > 0) {
1089 kprintf("mfree: m->m_nextpkt != NULL\n");
1090 print_backtrace(-1);
1092 m->m_nextpkt = NULL;
1095 if (m->m_flags & M_PKTHDR) {
1096 m_tag_delete_chain(m); /* eliminate XXX JH */
1099 m->m_flags &= (M_EXT | M_EXT_CLUSTER | M_CLCACHE | M_PHCACHE);
1102 * Clean the M_PKTHDR state so we can return the mbuf to its original
1103 * cache. This is based on the PHCACHE flag which tells us whether
1104 * the mbuf was originally allocated out of a packet-header cache
1105 * or a non-packet-header cache.
1107 if (m->m_flags & M_PHCACHE) {
1108 m->m_flags |= M_PKTHDR;
1109 m->m_pkthdr.rcvif = NULL; /* eliminate XXX JH */
1110 m->m_pkthdr.csum_flags = 0; /* eliminate XXX JH */
1111 m->m_pkthdr.fw_flags = 0; /* eliminate XXX JH */
1112 SLIST_INIT(&m->m_pkthdr.tags);
1116 * Handle remaining flags combinations. M_CLCACHE tells us whether
1117 * the mbuf was originally allocated from a cluster cache or not,
1118 * and is totally separate from whether the mbuf is currently
1119 * associated with a cluster.
1121 switch(m->m_flags & (M_CLCACHE | M_EXT | M_EXT_CLUSTER)) {
1122 case M_CLCACHE | M_EXT | M_EXT_CLUSTER:
1124 * mbuf+cluster cache case. The mbuf was allocated from the
1125 * combined mbuf_cluster cache and can be returned to the
1126 * cache if the cluster hasn't been shared.
1128 if (m_sharecount(m) == 1) {
1130 * The cluster has not been shared, we can just
1131 * reset the data pointer and return the mbuf
1132 * to the cluster cache. Note that the reference
1133 * count is left intact (it is still associated with
1136 m->m_data = m->m_ext.ext_buf;
1137 if (m->m_flags & M_EXT && m->m_ext.ext_size != MCLBYTES) {
1138 if (m->m_flags & M_PHCACHE)
1139 objcache_put(mbufphdrjcluster_cache, m);
1141 objcache_put(mbufjcluster_cache, m);
1143 if (m->m_flags & M_PHCACHE)
1144 objcache_put(mbufphdrcluster_cache, m);
1146 objcache_put(mbufcluster_cache, m);
1148 --mbstat[mycpu->gd_cpuid].m_clusters;
1151 * Hell. Someone else has a ref on this cluster,
1152 * we have to disconnect it which means we can't
1153 * put it back into the mbufcluster_cache, we
1154 * have to destroy the mbuf.
1156 * Other mbuf references to the cluster will typically
1157 * be M_EXT | M_EXT_CLUSTER but without M_CLCACHE.
1159 * XXX we could try to connect another cluster to
1162 m->m_ext.ext_free(m->m_ext.ext_arg);
1163 m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
1164 if (m->m_ext.ext_size == MCLBYTES) {
1165 if (m->m_flags & M_PHCACHE)
1166 objcache_dtor(mbufphdrcluster_cache, m);
1168 objcache_dtor(mbufcluster_cache, m);
1170 if (m->m_flags & M_PHCACHE)
1171 objcache_dtor(mbufphdrjcluster_cache, m);
1173 objcache_dtor(mbufjcluster_cache, m);
1177 case M_EXT | M_EXT_CLUSTER:
1180 * Normal cluster association case, disconnect the cluster from
1181 * the mbuf. The cluster may or may not be custom.
1183 m->m_ext.ext_free(m->m_ext.ext_arg);
1184 m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
1188 * return the mbuf to the mbuf cache.
1190 if (m->m_flags & M_PHCACHE) {
1191 m->m_data = m->m_pktdat;
1192 objcache_put(mbufphdr_cache, m);
1194 m->m_data = m->m_dat;
1195 objcache_put(mbuf_cache, m);
1197 --mbstat[mycpu->gd_cpuid].m_mbufs;
1201 panic("bad mbuf flags %p %08x\n", m, m->m_flags);
1210 _m_freem(struct mbuf *m, const char *func)
1213 m = _m_free(m, func);
1219 m_freem(struct mbuf *m)
1228 m_extadd(struct mbuf *m, caddr_t buf, u_int size, void (*reff)(void *),
1229 void (*freef)(void *), void *arg)
1231 m->m_ext.ext_arg = arg;
1232 m->m_ext.ext_buf = buf;
1233 m->m_ext.ext_ref = reff;
1234 m->m_ext.ext_free = freef;
1235 m->m_ext.ext_size = size;
1238 m->m_flags |= M_EXT;
1242 * mbuf utility routines
1246 * Lesser-used path for M_PREPEND: allocate new mbuf to prepend to chain and
1250 m_prepend(struct mbuf *m, int len, int how)
1254 if (m->m_flags & M_PKTHDR)
1255 mn = m_gethdr(how, m->m_type);
1257 mn = m_get(how, m->m_type);
1262 if (m->m_flags & M_PKTHDR)
1263 M_MOVE_PKTHDR(mn, m);
1273 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
1274 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
1275 * The wait parameter is a choice of MB_WAIT/MB_DONTWAIT from caller.
1276 * Note that the copy is read-only, because clusters are not copied,
1277 * only their reference counts are incremented.
1280 m_copym(const struct mbuf *m, int off0, int len, int wait)
1282 struct mbuf *n, **np;
1287 KASSERT(off >= 0, ("m_copym, negative off %d", off));
1288 KASSERT(len >= 0, ("m_copym, negative len %d", len));
1289 if (off == 0 && (m->m_flags & M_PKTHDR))
1292 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
1302 KASSERT(len == M_COPYALL,
1303 ("m_copym, length > size of mbuf chain"));
1307 * Because we are sharing any cluster attachment below,
1308 * be sure to get an mbuf that does not have a cluster
1309 * associated with it.
1312 n = m_gethdr(wait, m->m_type);
1314 n = m_get(wait, m->m_type);
1319 if (!m_dup_pkthdr(n, m, wait))
1321 if (len == M_COPYALL)
1322 n->m_pkthdr.len -= off0;
1324 n->m_pkthdr.len = len;
1327 n->m_len = min(len, m->m_len - off);
1328 if (m->m_flags & M_EXT) {
1329 KKASSERT((n->m_flags & M_EXT) == 0);
1330 n->m_data = m->m_data + off;
1331 m->m_ext.ext_ref(m->m_ext.ext_arg);
1332 n->m_ext = m->m_ext;
1333 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1335 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
1336 (unsigned)n->m_len);
1338 if (len != M_COPYALL)
1345 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1349 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1354 * Copy an entire packet, including header (which must be present).
1355 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
1356 * Note that the copy is read-only, because clusters are not copied,
1357 * only their reference counts are incremented.
1358 * Preserve alignment of the first mbuf so if the creator has left
1359 * some room at the beginning (e.g. for inserting protocol headers)
1360 * the copies also have the room available.
1363 m_copypacket(struct mbuf *m, int how)
1365 struct mbuf *top, *n, *o;
1367 n = m_gethdr(how, m->m_type);
1372 if (!m_dup_pkthdr(n, m, how))
1374 n->m_len = m->m_len;
1375 if (m->m_flags & M_EXT) {
1376 KKASSERT((n->m_flags & M_EXT) == 0);
1377 n->m_data = m->m_data;
1378 m->m_ext.ext_ref(m->m_ext.ext_arg);
1379 n->m_ext = m->m_ext;
1380 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1382 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
1383 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1388 o = m_get(how, m->m_type);
1395 n->m_len = m->m_len;
1396 if (m->m_flags & M_EXT) {
1397 KKASSERT((n->m_flags & M_EXT) == 0);
1398 n->m_data = m->m_data;
1399 m->m_ext.ext_ref(m->m_ext.ext_arg);
1400 n->m_ext = m->m_ext;
1401 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1403 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1411 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1416 * Copy data from an mbuf chain starting "off" bytes from the beginning,
1417 * continuing for "len" bytes, into the indicated buffer.
1420 m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
1424 KASSERT(off >= 0, ("m_copydata, negative off %d", off));
1425 KASSERT(len >= 0, ("m_copydata, negative len %d", len));
1427 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
1434 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
1435 count = min(m->m_len - off, len);
1436 bcopy(mtod(m, caddr_t) + off, cp, count);
1445 * Copy a packet header mbuf chain into a completely new chain, including
1446 * copying any mbuf clusters. Use this instead of m_copypacket() when
1447 * you need a writable copy of an mbuf chain.
1450 m_dup(struct mbuf *m, int how)
1452 struct mbuf **p, *top = NULL;
1453 int remain, moff, nsize;
1458 KASSERT((m->m_flags & M_PKTHDR) != 0, ("%s: !PKTHDR", __func__));
1460 /* While there's more data, get a new mbuf, tack it on, and fill it */
1461 remain = m->m_pkthdr.len;
1464 while (remain > 0 || top == NULL) { /* allow m->m_pkthdr.len == 0 */
1467 /* Get the next new mbuf */
1468 n = m_getl(remain, how, m->m_type, top == NULL ? M_PKTHDR : 0,
1473 if (!m_dup_pkthdr(n, m, how))
1476 /* Link it into the new chain */
1480 /* Copy data from original mbuf(s) into new mbuf */
1482 while (n->m_len < nsize && m != NULL) {
1483 int chunk = min(nsize - n->m_len, m->m_len - moff);
1485 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1489 if (moff == m->m_len) {
1495 /* Check correct total mbuf length */
1496 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
1497 ("%s: bogus m_pkthdr.len", __func__));
1504 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1509 * Copy the non-packet mbuf data chain into a new set of mbufs, including
1510 * copying any mbuf clusters. This is typically used to realign a data
1511 * chain by nfs_realign().
1513 * The original chain is left intact. how should be MB_WAIT or MB_DONTWAIT
1514 * and NULL can be returned if MB_DONTWAIT is passed.
1516 * Be careful to use cluster mbufs, a large mbuf chain converted to non
1517 * cluster mbufs can exhaust our supply of mbufs.
1520 m_dup_data(struct mbuf *m, int how)
1522 struct mbuf **p, *n, *top = NULL;
1523 int mlen, moff, chunk, gsize, nsize;
1532 * Optimize the mbuf allocation but do not get too carried away.
1534 if (m->m_next || m->m_len > MLEN)
1535 if (m->m_flags & M_EXT && m->m_ext.ext_size == MCLBYTES)
1538 gsize = MJUMPAGESIZE;
1548 * Scan the mbuf chain until nothing is left, the new mbuf chain
1549 * will be allocated on the fly as needed.
1556 KKASSERT(m->m_type == MT_DATA);
1558 n = m_getl(gsize, how, MT_DATA, 0, &nsize);
1565 chunk = imin(mlen, nsize);
1566 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1581 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1586 * Concatenate mbuf chain n to m.
1587 * Both chains must be of the same type (e.g. MT_DATA).
1588 * Any m_pkthdr is not updated.
1591 m_cat(struct mbuf *m, struct mbuf *n)
1595 if (m->m_flags & M_EXT ||
1596 m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
1597 /* just join the two chains */
1601 /* splat the data from one into the other */
1602 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1604 m->m_len += n->m_len;
1610 m_adj(struct mbuf *mp, int req_len)
1616 if ((m = mp) == NULL)
1622 while (m != NULL && len > 0) {
1623 if (m->m_len <= len) {
1634 if (mp->m_flags & M_PKTHDR)
1635 m->m_pkthdr.len -= (req_len - len);
1638 * Trim from tail. Scan the mbuf chain,
1639 * calculating its length and finding the last mbuf.
1640 * If the adjustment only affects this mbuf, then just
1641 * adjust and return. Otherwise, rescan and truncate
1642 * after the remaining size.
1648 if (m->m_next == NULL)
1652 if (m->m_len >= len) {
1654 if (mp->m_flags & M_PKTHDR)
1655 mp->m_pkthdr.len -= len;
1662 * Correct length for chain is "count".
1663 * Find the mbuf with last data, adjust its length,
1664 * and toss data from remaining mbufs on chain.
1667 if (m->m_flags & M_PKTHDR)
1668 m->m_pkthdr.len = count;
1669 for (; m; m = m->m_next) {
1670 if (m->m_len >= count) {
1677 (m = m->m_next) ->m_len = 0;
1682 * Set the m_data pointer of a newly-allocated mbuf
1683 * to place an object of the specified size at the
1684 * end of the mbuf, longword aligned.
1687 m_align(struct mbuf *m, int len)
1691 if (m->m_flags & M_EXT)
1692 adjust = m->m_ext.ext_size - len;
1693 else if (m->m_flags & M_PKTHDR)
1694 adjust = MHLEN - len;
1696 adjust = MLEN - len;
1697 m->m_data += adjust &~ (sizeof(long)-1);
1701 * Create a writable copy of the mbuf chain. While doing this
1702 * we compact the chain with a goal of producing a chain with
1703 * at most two mbufs. The second mbuf in this chain is likely
1704 * to be a cluster. The primary purpose of this work is to create
1705 * a writable packet for encryption, compression, etc. The
1706 * secondary goal is to linearize the data so the data can be
1707 * passed to crypto hardware in the most efficient manner possible.
1710 m_unshare(struct mbuf *m0, int how)
1712 struct mbuf *m, *mprev;
1713 struct mbuf *n, *mfirst, *mlast;
1717 for (m = m0; m != NULL; m = mprev->m_next) {
1719 * Regular mbufs are ignored unless there's a cluster
1720 * in front of it that we can use to coalesce. We do
1721 * the latter mainly so later clusters can be coalesced
1722 * also w/o having to handle them specially (i.e. convert
1723 * mbuf+cluster -> cluster). This optimization is heavily
1724 * influenced by the assumption that we're running over
1725 * Ethernet where MCLBYTES is large enough that the max
1726 * packet size will permit lots of coalescing into a
1727 * single cluster. This in turn permits efficient
1728 * crypto operations, especially when using hardware.
1730 if ((m->m_flags & M_EXT) == 0) {
1731 if (mprev && (mprev->m_flags & M_EXT) &&
1732 m->m_len <= M_TRAILINGSPACE(mprev)) {
1733 /* XXX: this ignores mbuf types */
1734 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1735 mtod(m, caddr_t), m->m_len);
1736 mprev->m_len += m->m_len;
1737 mprev->m_next = m->m_next; /* unlink from chain */
1738 m_free(m); /* reclaim mbuf */
1745 * Writable mbufs are left alone (for now).
1747 if (M_WRITABLE(m)) {
1753 * Not writable, replace with a copy or coalesce with
1754 * the previous mbuf if possible (since we have to copy
1755 * it anyway, we try to reduce the number of mbufs and
1756 * clusters so that future work is easier).
1758 KASSERT(m->m_flags & M_EXT, ("m_flags 0x%x", m->m_flags));
1759 /* NB: we only coalesce into a cluster or larger */
1760 if (mprev != NULL && (mprev->m_flags & M_EXT) &&
1761 m->m_len <= M_TRAILINGSPACE(mprev)) {
1762 /* XXX: this ignores mbuf types */
1763 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1764 mtod(m, caddr_t), m->m_len);
1765 mprev->m_len += m->m_len;
1766 mprev->m_next = m->m_next; /* unlink from chain */
1767 m_free(m); /* reclaim mbuf */
1772 * Allocate new space to hold the copy...
1774 /* XXX why can M_PKTHDR be set past the first mbuf? */
1775 if (mprev == NULL && (m->m_flags & M_PKTHDR)) {
1777 * NB: if a packet header is present we must
1778 * allocate the mbuf separately from any cluster
1779 * because M_MOVE_PKTHDR will smash the data
1780 * pointer and drop the M_EXT marker.
1782 MGETHDR(n, how, m->m_type);
1787 M_MOVE_PKTHDR(n, m);
1789 if ((n->m_flags & M_EXT) == 0) {
1795 n = m_getcl(how, m->m_type, m->m_flags);
1802 * ... and copy the data. We deal with jumbo mbufs
1803 * (i.e. m_len > MCLBYTES) by splitting them into
1804 * clusters. We could just malloc a buffer and make
1805 * it external but too many device drivers don't know
1806 * how to break up the non-contiguous memory when
1814 int cc = min(len, MCLBYTES);
1815 memcpy(mtod(n, caddr_t), mtod(m, caddr_t) + off, cc);
1826 n = m_getcl(how, m->m_type, m->m_flags);
1833 n->m_next = m->m_next;
1835 m0 = mfirst; /* new head of chain */
1837 mprev->m_next = mfirst; /* replace old mbuf */
1838 m_free(m); /* release old mbuf */
1845 * Rearrange an mbuf chain so that len bytes are contiguous
1846 * and in the data area of an mbuf (so that mtod will work for a structure
1847 * of size len). Returns the resulting mbuf chain on success, frees it and
1848 * returns null on failure. If there is room, it will add up to
1849 * max_protohdr-len extra bytes to the contiguous region in an attempt to
1850 * avoid being called next time.
1853 m_pullup(struct mbuf *n, int len)
1860 * If first mbuf has no cluster, and has room for len bytes
1861 * without shifting current data, pullup into it,
1862 * otherwise allocate a new mbuf to prepend to the chain.
1864 if (!(n->m_flags & M_EXT) &&
1865 n->m_data + len < &n->m_dat[MLEN] &&
1867 if (n->m_len >= len)
1875 if (n->m_flags & M_PKTHDR)
1876 m = m_gethdr(MB_DONTWAIT, n->m_type);
1878 m = m_get(MB_DONTWAIT, n->m_type);
1882 if (n->m_flags & M_PKTHDR)
1883 M_MOVE_PKTHDR(m, n);
1885 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1887 count = min(min(max(len, max_protohdr), space), n->m_len);
1888 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1898 } while (len > 0 && n);
1907 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1912 * Partition an mbuf chain in two pieces, returning the tail --
1913 * all but the first len0 bytes. In case of failure, it returns NULL and
1914 * attempts to restore the chain to its original state.
1916 * Note that the resulting mbufs might be read-only, because the new
1917 * mbuf can end up sharing an mbuf cluster with the original mbuf if
1918 * the "breaking point" happens to lie within a cluster mbuf. Use the
1919 * M_WRITABLE() macro to check for this case.
1922 m_split(struct mbuf *m0, int len0, int wait)
1925 unsigned len = len0, remain;
1927 for (m = m0; m && len > m->m_len; m = m->m_next)
1931 remain = m->m_len - len;
1932 if (m0->m_flags & M_PKTHDR) {
1933 n = m_gethdr(wait, m0->m_type);
1936 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1937 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1938 m0->m_pkthdr.len = len0;
1939 if (m->m_flags & M_EXT)
1941 if (remain > MHLEN) {
1942 /* m can't be the lead packet */
1944 n->m_next = m_split(m, len, wait);
1945 if (n->m_next == NULL) {
1953 MH_ALIGN(n, remain);
1954 } else if (remain == 0) {
1959 n = m_get(wait, m->m_type);
1965 if (m->m_flags & M_EXT) {
1966 KKASSERT((n->m_flags & M_EXT) == 0);
1967 n->m_data = m->m_data + len;
1968 m->m_ext.ext_ref(m->m_ext.ext_arg);
1969 n->m_ext = m->m_ext;
1970 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1972 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1976 n->m_next = m->m_next;
1982 * Routine to copy from device local memory into mbufs.
1983 * Note: "offset" is ill-defined and always called as 0, so ignore it.
1986 m_devget(char *buf, int len, int offset, struct ifnet *ifp,
1987 void (*copy)(volatile const void *from, volatile void *to, size_t length))
1989 struct mbuf *m, *mfirst = NULL, **mtail;
1998 m = m_getl(len, MB_DONTWAIT, MT_DATA, flags, &nsize);
2003 m->m_len = min(len, nsize);
2005 if (flags & M_PKTHDR) {
2006 if (len + max_linkhdr <= nsize)
2007 m->m_data += max_linkhdr;
2008 m->m_pkthdr.rcvif = ifp;
2009 m->m_pkthdr.len = len;
2013 copy(buf, m->m_data, (unsigned)m->m_len);
2024 * Routine to pad mbuf to the specified length 'padto'.
2027 m_devpad(struct mbuf *m, int padto)
2029 struct mbuf *last = NULL;
2032 if (padto <= m->m_pkthdr.len)
2035 padlen = padto - m->m_pkthdr.len;
2037 /* if there's only the packet-header and we can pad there, use it. */
2038 if (m->m_pkthdr.len == m->m_len && M_TRAILINGSPACE(m) >= padlen) {
2042 * Walk packet chain to find last mbuf. We will either
2043 * pad there, or append a new mbuf and pad it
2045 for (last = m; last->m_next != NULL; last = last->m_next)
2048 /* `last' now points to last in chain. */
2049 if (M_TRAILINGSPACE(last) < padlen) {
2052 /* Allocate new empty mbuf, pad it. Compact later. */
2053 MGET(n, MB_DONTWAIT, MT_DATA);
2061 KKASSERT(M_TRAILINGSPACE(last) >= padlen);
2062 KKASSERT(M_WRITABLE(last));
2064 /* Now zero the pad area */
2065 bzero(mtod(last, char *) + last->m_len, padlen);
2066 last->m_len += padlen;
2067 m->m_pkthdr.len += padlen;
2072 * Copy data from a buffer back into the indicated mbuf chain,
2073 * starting "off" bytes from the beginning, extending the mbuf
2074 * chain if necessary.
2077 m_copyback(struct mbuf *m0, int off, int len, caddr_t cp)
2080 struct mbuf *m = m0, *n;
2085 while (off > (mlen = m->m_len)) {
2088 if (m->m_next == NULL) {
2089 n = m_getclr(MB_DONTWAIT, m->m_type);
2092 n->m_len = min(MLEN, len + off);
2098 mlen = min (m->m_len - off, len);
2099 bcopy(cp, off + mtod(m, caddr_t), (unsigned)mlen);
2107 if (m->m_next == NULL) {
2108 n = m_get(MB_DONTWAIT, m->m_type);
2111 n->m_len = min(MLEN, len);
2116 out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
2117 m->m_pkthdr.len = totlen;
2121 * Append the specified data to the indicated mbuf chain,
2122 * Extend the mbuf chain if the new data does not fit in
2125 * Return 1 if able to complete the job; otherwise 0.
2128 m_append(struct mbuf *m0, int len, c_caddr_t cp)
2131 int remainder, space;
2133 for (m = m0; m->m_next != NULL; m = m->m_next)
2136 space = M_TRAILINGSPACE(m);
2139 * Copy into available space.
2141 if (space > remainder)
2143 bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
2145 cp += space, remainder -= space;
2147 while (remainder > 0) {
2149 * Allocate a new mbuf; could check space
2150 * and allocate a cluster instead.
2152 n = m_get(MB_DONTWAIT, m->m_type);
2155 n->m_len = min(MLEN, remainder);
2156 bcopy(cp, mtod(n, caddr_t), n->m_len);
2157 cp += n->m_len, remainder -= n->m_len;
2161 if (m0->m_flags & M_PKTHDR)
2162 m0->m_pkthdr.len += len - remainder;
2163 return (remainder == 0);
2167 * Apply function f to the data in an mbuf chain starting "off" bytes from
2168 * the beginning, continuing for "len" bytes.
2171 m_apply(struct mbuf *m, int off, int len,
2172 int (*f)(void *, void *, u_int), void *arg)
2177 KASSERT(off >= 0, ("m_apply, negative off %d", off));
2178 KASSERT(len >= 0, ("m_apply, negative len %d", len));
2180 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
2187 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
2188 count = min(m->m_len - off, len);
2189 rval = (*f)(arg, mtod(m, caddr_t) + off, count);
2200 * Return a pointer to mbuf/offset of location in mbuf chain.
2203 m_getptr(struct mbuf *m, int loc, int *off)
2207 /* Normal end of search. */
2208 if (m->m_len > loc) {
2213 if (m->m_next == NULL) {
2215 /* Point at the end of valid data. */
2228 m_print(const struct mbuf *m)
2231 const struct mbuf *m2;
2233 len = m->m_pkthdr.len;
2236 kprintf("%p %*D\n", m2, m2->m_len, (u_char *)m2->m_data, "-");
2244 * "Move" mbuf pkthdr from "from" to "to".
2245 * "from" must have M_PKTHDR set, and "to" must be empty.
2248 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
2250 KASSERT((to->m_flags & M_PKTHDR), ("m_move_pkthdr: not packet header"));
2252 to->m_flags |= from->m_flags & M_COPYFLAGS;
2253 to->m_pkthdr = from->m_pkthdr; /* especially tags */
2254 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
2258 * Duplicate "from"'s mbuf pkthdr in "to".
2259 * "from" must have M_PKTHDR set, and "to" must be empty.
2260 * In particular, this does a deep copy of the packet tags.
2263 m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
2265 KASSERT((to->m_flags & M_PKTHDR), ("m_dup_pkthdr: not packet header"));
2267 to->m_flags = (from->m_flags & M_COPYFLAGS) |
2268 (to->m_flags & ~M_COPYFLAGS);
2269 to->m_pkthdr = from->m_pkthdr;
2270 SLIST_INIT(&to->m_pkthdr.tags);
2271 return (m_tag_copy_chain(to, from, how));
2275 * Defragment a mbuf chain, returning the shortest possible
2276 * chain of mbufs and clusters. If allocation fails and
2277 * this cannot be completed, NULL will be returned, but
2278 * the passed in chain will be unchanged. Upon success,
2279 * the original chain will be freed, and the new chain
2282 * If a non-packet header is passed in, the original
2283 * mbuf (chain?) will be returned unharmed.
2285 * m_defrag_nofree doesn't free the passed in mbuf.
2288 m_defrag(struct mbuf *m0, int how)
2292 if ((m_new = m_defrag_nofree(m0, how)) == NULL)
2300 m_defrag_nofree(struct mbuf *m0, int how)
2302 struct mbuf *m_new = NULL, *m_final = NULL;
2303 int progress = 0, length, nsize;
2305 if (!(m0->m_flags & M_PKTHDR))
2308 #ifdef MBUF_STRESS_TEST
2309 if (m_defragrandomfailures) {
2310 int temp = karc4random() & 0xff;
2316 m_final = m_getl(m0->m_pkthdr.len, how, MT_DATA, M_PKTHDR, &nsize);
2317 if (m_final == NULL)
2319 m_final->m_len = 0; /* in case m0->m_pkthdr.len is zero */
2321 if (m_dup_pkthdr(m_final, m0, how) == 0)
2326 while (progress < m0->m_pkthdr.len) {
2327 length = m0->m_pkthdr.len - progress;
2328 if (length > MCLBYTES)
2331 if (m_new == NULL) {
2332 m_new = m_getl(length, how, MT_DATA, 0, &nsize);
2337 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
2339 m_new->m_len = length;
2340 if (m_new != m_final)
2341 m_cat(m_final, m_new);
2344 if (m0->m_next == NULL)
2347 m_defragbytes += m_final->m_pkthdr.len;
2358 * Move data from uio into mbufs.
2361 m_uiomove(struct uio *uio)
2363 struct mbuf *m; /* current working mbuf */
2364 struct mbuf *head = NULL; /* result mbuf chain */
2365 struct mbuf **mp = &head;
2366 int flags = M_PKTHDR;
2372 if (uio->uio_resid > INT_MAX)
2375 resid = (int)uio->uio_resid;
2376 m = m_getl(resid, MB_WAIT, MT_DATA, flags, &nsize);
2378 m->m_pkthdr.len = 0;
2379 /* Leave room for protocol headers. */
2384 m->m_len = imin(nsize, resid);
2385 error = uiomove(mtod(m, caddr_t), m->m_len, uio);
2392 head->m_pkthdr.len += m->m_len;
2393 } while (uio->uio_resid > 0);
2403 m_last(struct mbuf *m)
2411 * Return the number of bytes in an mbuf chain.
2412 * If lastm is not NULL, also return the last mbuf.
2415 m_lengthm(struct mbuf *m, struct mbuf **lastm)
2418 struct mbuf *prev = m;
2431 * Like m_lengthm(), except also keep track of mbuf usage.
2434 m_countm(struct mbuf *m, struct mbuf **lastm, u_int *pmbcnt)
2436 u_int len = 0, mbcnt = 0;
2437 struct mbuf *prev = m;
2442 if (m->m_flags & M_EXT)
2443 mbcnt += m->m_ext.ext_size;