2 * Copyright (c) 2004 Jeffrey M. Hsu. All rights reserved.
3 * Copyright (c) 2004 The DragonFly Project. All rights reserved.
5 * This code is derived from software contributed to The DragonFly Project
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of The DragonFly Project nor the names of its
17 * contributors may be used to endorse or promote products derived
18 * from this software without specific, prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * Copyright (c) 1982, 1986, 1988, 1991, 1993
36 * The Regents of the University of California. All rights reserved.
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. All advertising materials mentioning features or use of this software
47 * must display the following acknowledgement:
48 * This product includes software developed by the University of
49 * California, Berkeley and its contributors.
50 * 4. Neither the name of the University nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
54 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66 * @(#)uipc_mbuf.c 8.2 (Berkeley) 1/4/94
67 * $FreeBSD: src/sys/kern/uipc_mbuf.c,v 1.51.2.24 2003/04/15 06:59:29 silby Exp $
68 * $DragonFly: src/sys/kern/uipc_mbuf.c,v 1.65 2007/08/12 01:46:26 dillon Exp $
71 #include "opt_param.h"
73 #include "opt_mbuf_stress_test.h"
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/malloc.h>
78 #include <sys/kernel.h>
79 #include <sys/sysctl.h>
80 #include <sys/domain.h>
81 #include <sys/objcache.h>
83 #include <sys/protosw.h>
85 #include <sys/thread.h>
86 #include <sys/globaldata.h>
87 #include <sys/thread2.h>
89 #include <machine/atomic.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;
139 mbuftrack(struct mbuf *m)
144 mbt = kmalloc(sizeof(*mbt), M_MTRACK, M_INTWAIT|M_ZERO);
146 if (mbuf_rb_tree_RB_INSERT(&mbuf_track_root, mbt))
147 panic("mbuftrack: mbuf %p already being tracked\n", m);
152 mbufuntrack(struct mbuf *m)
157 mbt = mbuf_rb_tree_RB_LOOKUP(&mbuf_track_root, m);
159 kprintf("mbufuntrack: mbuf %p was not tracked\n", m);
161 mbuf_rb_tree_RB_REMOVE(&mbuf_track_root, mbt);
162 kfree(mbt, M_MTRACK);
168 mbuftrackid(struct mbuf *m, int trackid)
177 mbt = mbuf_rb_tree_RB_LOOKUP(&mbuf_track_root, m);
179 mbt->trackid = trackid;
188 mbuftrack_callback(struct mbtrack *mbt, void *arg)
190 struct sysctl_req *req = arg;
194 ksnprintf(buf, sizeof(buf), "mbuf %p track %d\n", mbt->m, mbt->trackid);
196 error = SYSCTL_OUT(req, buf, strlen(buf));
203 mbuftrack_show(SYSCTL_HANDLER_ARGS)
208 error = mbuf_rb_tree_RB_SCAN(&mbuf_track_root, NULL,
209 mbuftrack_callback, req);
213 SYSCTL_PROC(_kern_ipc, OID_AUTO, showmbufs, CTLFLAG_RD|CTLTYPE_STRING,
214 0, 0, mbuftrack_show, "A", "Show all in-use mbufs");
219 #define mbufuntrack(m)
223 static void mbinit(void *);
224 SYSINIT(mbuf, SI_BOOT2_MACHDEP, SI_ORDER_FIRST, mbinit, NULL)
226 static u_long mbtypes[SMP_MAXCPU][MT_NTYPES];
228 static struct mbstat mbstat[SMP_MAXCPU];
237 #ifdef MBUF_STRESS_TEST
238 int m_defragrandomfailures;
241 struct objcache *mbuf_cache, *mbufphdr_cache;
242 struct objcache *mclmeta_cache;
243 struct objcache *mbufcluster_cache, *mbufphdrcluster_cache;
248 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RW,
249 &max_linkhdr, 0, "");
250 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RW,
251 &max_protohdr, 0, "");
252 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RW, &max_hdr, 0, "");
253 SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RW,
254 &max_datalen, 0, "");
255 SYSCTL_INT(_kern_ipc, OID_AUTO, mbuf_wait, CTLFLAG_RW,
257 static int do_mbstat(SYSCTL_HANDLER_ARGS);
259 SYSCTL_PROC(_kern_ipc, KIPC_MBSTAT, mbstat, CTLTYPE_STRUCT|CTLFLAG_RD,
260 0, 0, do_mbstat, "S,mbstat", "");
262 static int do_mbtypes(SYSCTL_HANDLER_ARGS);
264 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbtypes, CTLTYPE_ULONG|CTLFLAG_RD,
265 0, 0, do_mbtypes, "LU", "");
268 do_mbstat(SYSCTL_HANDLER_ARGS)
270 struct mbstat mbstat_total;
271 struct mbstat *mbstat_totalp;
274 bzero(&mbstat_total, sizeof(mbstat_total));
275 mbstat_totalp = &mbstat_total;
277 for (i = 0; i < ncpus; i++)
279 mbstat_total.m_mbufs += mbstat[i].m_mbufs;
280 mbstat_total.m_clusters += mbstat[i].m_clusters;
281 mbstat_total.m_spare += mbstat[i].m_spare;
282 mbstat_total.m_clfree += mbstat[i].m_clfree;
283 mbstat_total.m_drops += mbstat[i].m_drops;
284 mbstat_total.m_wait += mbstat[i].m_wait;
285 mbstat_total.m_drain += mbstat[i].m_drain;
286 mbstat_total.m_mcfail += mbstat[i].m_mcfail;
287 mbstat_total.m_mpfail += mbstat[i].m_mpfail;
291 * The following fields are not cumulative fields so just
292 * get their values once.
294 mbstat_total.m_msize = mbstat[0].m_msize;
295 mbstat_total.m_mclbytes = mbstat[0].m_mclbytes;
296 mbstat_total.m_minclsize = mbstat[0].m_minclsize;
297 mbstat_total.m_mlen = mbstat[0].m_mlen;
298 mbstat_total.m_mhlen = mbstat[0].m_mhlen;
300 return(sysctl_handle_opaque(oidp, mbstat_totalp, sizeof(mbstat_total), req));
304 do_mbtypes(SYSCTL_HANDLER_ARGS)
306 u_long totals[MT_NTYPES];
309 for (i = 0; i < MT_NTYPES; i++)
312 for (i = 0; i < ncpus; i++)
314 for (j = 0; j < MT_NTYPES; j++)
315 totals[j] += mbtypes[i][j];
318 return(sysctl_handle_opaque(oidp, totals, sizeof(totals), req));
322 * These are read-only because we do not currently have any code
323 * to adjust the objcache limits after the fact. The variables
324 * may only be set as boot-time tunables.
326 SYSCTL_INT(_kern_ipc, KIPC_NMBCLUSTERS, nmbclusters, CTLFLAG_RD,
327 &nmbclusters, 0, "Maximum number of mbuf clusters available");
328 SYSCTL_INT(_kern_ipc, OID_AUTO, nmbufs, CTLFLAG_RD, &nmbufs, 0,
329 "Maximum number of mbufs available");
331 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
332 &m_defragpackets, 0, "");
333 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
334 &m_defragbytes, 0, "");
335 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
336 &m_defraguseless, 0, "");
337 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
338 &m_defragfailure, 0, "");
339 #ifdef MBUF_STRESS_TEST
340 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
341 &m_defragrandomfailures, 0, "");
344 static MALLOC_DEFINE(M_MBUF, "mbuf", "mbuf");
345 static MALLOC_DEFINE(M_MBUFCL, "mbufcl", "mbufcl");
346 static MALLOC_DEFINE(M_MCLMETA, "mclmeta", "mclmeta");
348 static void m_reclaim (void);
349 static void m_mclref(void *arg);
350 static void m_mclfree(void *arg);
353 #define NMBCLUSTERS (512 + maxusers * 16)
356 #define NMBUFS (nmbclusters * 2)
360 * Perform sanity checks of tunables declared above.
363 tunable_mbinit(void *dummy)
366 * This has to be done before VM init.
368 nmbclusters = NMBCLUSTERS;
369 TUNABLE_INT_FETCH("kern.ipc.nmbclusters", &nmbclusters);
371 TUNABLE_INT_FETCH("kern.ipc.nmbufs", &nmbufs);
373 if (nmbufs < nmbclusters * 2)
374 nmbufs = nmbclusters * 2;
376 SYSINIT(tunable_mbinit, SI_BOOT1_TUNABLES, SI_ORDER_ANY,
377 tunable_mbinit, NULL);
379 /* "number of clusters of pages" */
385 * The mbuf object cache only guarantees that m_next and m_nextpkt are
386 * NULL and that m_data points to the beginning of the data area. In
387 * particular, m_len and m_pkthdr.len are uninitialized. It is the
388 * responsibility of the caller to initialize those fields before use.
391 static boolean_t __inline
392 mbuf_ctor(void *obj, void *private, int ocflags)
394 struct mbuf *m = obj;
398 m->m_data = m->m_dat;
405 * Initialize the mbuf and the packet header fields.
408 mbufphdr_ctor(void *obj, void *private, int ocflags)
410 struct mbuf *m = obj;
414 m->m_data = m->m_pktdat;
415 m->m_flags = M_PKTHDR | M_PHCACHE;
417 m->m_pkthdr.rcvif = NULL; /* eliminate XXX JH */
418 SLIST_INIT(&m->m_pkthdr.tags);
419 m->m_pkthdr.csum_flags = 0; /* eliminate XXX JH */
420 m->m_pkthdr.fw_flags = 0; /* eliminate XXX JH */
426 * A mbcluster object consists of 2K (MCLBYTES) cluster and a refcount.
429 mclmeta_ctor(void *obj, void *private, int ocflags)
431 struct mbcluster *cl = obj;
434 if (ocflags & M_NOWAIT)
435 buf = kmalloc(MCLBYTES, M_MBUFCL, M_NOWAIT | M_ZERO);
437 buf = kmalloc(MCLBYTES, M_MBUFCL, M_INTWAIT | M_ZERO);
446 mclmeta_dtor(void *obj, void *private)
448 struct mbcluster *mcl = obj;
450 KKASSERT(mcl->mcl_refs == 0);
451 kfree(mcl->mcl_data, M_MBUFCL);
455 linkcluster(struct mbuf *m, struct mbcluster *cl)
458 * Add the cluster to the mbuf. The caller will detect that the
459 * mbuf now has an attached cluster.
461 m->m_ext.ext_arg = cl;
462 m->m_ext.ext_buf = cl->mcl_data;
463 m->m_ext.ext_ref = m_mclref;
464 m->m_ext.ext_free = m_mclfree;
465 m->m_ext.ext_size = MCLBYTES;
466 atomic_add_int(&cl->mcl_refs, 1);
468 m->m_data = m->m_ext.ext_buf;
469 m->m_flags |= M_EXT | M_EXT_CLUSTER;
473 mbufphdrcluster_ctor(void *obj, void *private, int ocflags)
475 struct mbuf *m = obj;
476 struct mbcluster *cl;
478 mbufphdr_ctor(obj, private, ocflags);
479 cl = objcache_get(mclmeta_cache, ocflags);
482 m->m_flags |= M_CLCACHE;
488 mbufcluster_ctor(void *obj, void *private, int ocflags)
490 struct mbuf *m = obj;
491 struct mbcluster *cl;
493 mbuf_ctor(obj, private, ocflags);
494 cl = objcache_get(mclmeta_cache, ocflags);
497 m->m_flags |= M_CLCACHE;
503 * Used for both the cluster and cluster PHDR caches.
505 * The mbuf may have lost its cluster due to sharing, deal
506 * with the situation by checking M_EXT.
509 mbufcluster_dtor(void *obj, void *private)
511 struct mbuf *m = obj;
512 struct mbcluster *mcl;
514 if (m->m_flags & M_EXT) {
515 KKASSERT((m->m_flags & M_EXT_CLUSTER) != 0);
516 mcl = m->m_ext.ext_arg;
517 KKASSERT(mcl->mcl_refs == 1);
519 objcache_put(mclmeta_cache, mcl);
523 struct objcache_malloc_args mbuf_malloc_args = { MSIZE, M_MBUF };
524 struct objcache_malloc_args mclmeta_malloc_args =
525 { sizeof(struct mbcluster), M_MCLMETA };
533 for (i = 0; i < ncpus; i++)
535 atomic_set_long_nonlocked(&mbstat[i].m_msize, MSIZE);
536 atomic_set_long_nonlocked(&mbstat[i].m_mclbytes, MCLBYTES);
537 atomic_set_long_nonlocked(&mbstat[i].m_minclsize, MINCLSIZE);
538 atomic_set_long_nonlocked(&mbstat[i].m_mlen, MLEN);
539 atomic_set_long_nonlocked(&mbstat[i].m_mhlen, MHLEN);
542 mbuf_cache = objcache_create("mbuf", nmbufs, 0,
543 mbuf_ctor, NULL, NULL,
544 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
545 mbufphdr_cache = objcache_create("mbuf pkt hdr", nmbufs, 64,
546 mbufphdr_ctor, NULL, NULL,
547 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
548 mclmeta_cache = objcache_create("cluster mbuf", nmbclusters , 0,
549 mclmeta_ctor, mclmeta_dtor, NULL,
550 objcache_malloc_alloc, objcache_malloc_free, &mclmeta_malloc_args);
551 mbufcluster_cache = objcache_create("mbuf + cluster", nmbclusters, 0,
552 mbufcluster_ctor, mbufcluster_dtor, NULL,
553 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
554 mbufphdrcluster_cache = objcache_create("mbuf pkt hdr + cluster",
555 nmbclusters, 64, mbufphdrcluster_ctor, mbufcluster_dtor, NULL,
556 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
561 * Return the number of references to this mbuf's data. 0 is returned
562 * if the mbuf is not M_EXT, a reference count is returned if it is
563 * M_EXT | M_EXT_CLUSTER, and 99 is returned if it is a special M_EXT.
566 m_sharecount(struct mbuf *m)
568 switch (m->m_flags & (M_EXT | M_EXT_CLUSTER)) {
573 case M_EXT | M_EXT_CLUSTER:
574 return (((struct mbcluster *)m->m_ext.ext_arg)->mcl_refs);
577 return (0); /* to shut up compiler */
581 * change mbuf to new type
584 m_chtype(struct mbuf *m, int type)
586 struct globaldata *gd = mycpu;
588 atomic_add_long_nonlocked(&mbtypes[gd->gd_cpuid][type], 1);
589 atomic_subtract_long_nonlocked(&mbtypes[gd->gd_cpuid][m->m_type], 1);
590 atomic_set_short_nonlocked(&m->m_type, type);
600 SLIST_FOREACH(dp, &domains, dom_next) {
601 for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++) {
607 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_drain, 1);
611 updatestats(struct mbuf *m, int type)
613 struct globaldata *gd = mycpu;
618 atomic_add_long_nonlocked(&mbtypes[gd->gd_cpuid][type], 1);
619 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mbufs, 1);
627 m_get(int how, int type)
631 int ocf = MBTOM(how);
635 m = objcache_get(mbuf_cache, ocf);
638 if ((how & MB_TRYWAIT) && ntries++ == 0) {
639 struct objcache *reclaimlist[] = {
641 mbufcluster_cache, mbufphdrcluster_cache
643 const int nreclaims = __arysize(reclaimlist);
645 if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
652 updatestats(m, type);
657 m_gethdr(int how, int type)
660 int ocf = MBTOM(how);
665 m = objcache_get(mbufphdr_cache, ocf);
668 if ((how & MB_TRYWAIT) && ntries++ == 0) {
669 struct objcache *reclaimlist[] = {
671 mbufcluster_cache, mbufphdrcluster_cache
673 const int nreclaims = __arysize(reclaimlist);
675 if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
682 updatestats(m, type);
687 * Get a mbuf (not a mbuf cluster!) and zero it.
691 m_getclr(int how, int type)
695 m = m_get(how, type);
697 bzero(m->m_data, MLEN);
702 * Returns an mbuf with an attached cluster.
703 * Because many network drivers use this kind of buffers a lot, it is
704 * convenient to keep a small pool of free buffers of this kind.
705 * Even a small size such as 10 gives about 10% improvement in the
706 * forwarding rate in a bridge or router.
709 m_getcl(int how, short type, int flags)
712 int ocflags = MBTOM(how);
717 if (flags & M_PKTHDR)
718 m = objcache_get(mbufphdrcluster_cache, ocflags);
720 m = objcache_get(mbufcluster_cache, ocflags);
723 if ((how & MB_TRYWAIT) && ntries++ == 0) {
724 struct objcache *reclaimlist[1];
726 if (flags & M_PKTHDR)
727 reclaimlist[0] = mbufcluster_cache;
729 reclaimlist[0] = mbufphdrcluster_cache;
730 if (!objcache_reclaimlist(reclaimlist, 1, ocflags))
741 atomic_add_long_nonlocked(&mbtypes[mycpu->gd_cpuid][type], 1);
742 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_clusters, 1);
747 * Allocate chain of requested length.
750 m_getc(int len, int how, int type)
752 struct mbuf *n, *nfirst = NULL, **ntail = &nfirst;
756 n = m_getl(len, how, type, 0, &nsize);
772 * Allocate len-worth of mbufs and/or mbuf clusters (whatever fits best)
773 * and return a pointer to the head of the allocated chain. If m0 is
774 * non-null, then we assume that it is a single mbuf or an mbuf chain to
775 * which we want len bytes worth of mbufs and/or clusters attached, and so
776 * if we succeed in allocating it, we will just return a pointer to m0.
778 * If we happen to fail at any point during the allocation, we will free
779 * up everything we have already allocated and return NULL.
781 * Deprecated. Use m_getc() and m_cat() instead.
784 m_getm(struct mbuf *m0, int len, int type, int how)
788 nfirst = m_getc(len, how, type);
791 m_last(m0)->m_next = nfirst;
799 * Adds a cluster to a normal mbuf, M_EXT is set on success.
800 * Deprecated. Use m_getcl() instead.
803 m_mclget(struct mbuf *m, int how)
805 struct mbcluster *mcl;
807 KKASSERT((m->m_flags & M_EXT) == 0);
808 mcl = objcache_get(mclmeta_cache, MBTOM(how));
811 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_clusters, 1);
816 * Updates to mbcluster must be MPSAFE. Only an entity which already has
817 * a reference to the cluster can ref it, so we are in no danger of
818 * racing an add with a subtract. But the operation must still be atomic
819 * since multiple entities may have a reference on the cluster.
821 * m_mclfree() is almost the same but it must contend with two entities
822 * freeing the cluster at the same time. If there is only one reference
823 * count we are the only entity referencing the cluster and no further
824 * locking is required. Otherwise we must protect against a race to 0
825 * with the serializer.
830 struct mbcluster *mcl = arg;
832 atomic_add_int(&mcl->mcl_refs, 1);
836 * When dereferencing a cluster we have to deal with a N->0 race, where
837 * N entities free their references simultaniously. To do this we use
838 * atomic_cmpset_int().
843 struct mbcluster *mcl = arg;
847 refs = mcl->mcl_refs;
848 } while (atomic_cmpset_int(&mcl->mcl_refs, refs, refs - 1) == 0);
850 objcache_put(mclmeta_cache, mcl);
853 extern void db_print_backtrace(void);
856 * Free a single mbuf and any associated external storage. The successor,
857 * if any, is returned.
859 * We do need to check non-first mbuf for m_aux, since some of existing
860 * code does not call M_PREPEND properly.
861 * (example: call to bpf_mtap from drivers)
864 m_free(struct mbuf *m)
867 struct globaldata *gd = mycpu;
869 KASSERT(m->m_type != MT_FREE, ("freeing free mbuf %p", m));
870 atomic_subtract_long_nonlocked(&mbtypes[gd->gd_cpuid][m->m_type], 1);
875 * Make sure the mbuf is in constructed state before returning it
881 KKASSERT(m->m_nextpkt == NULL);
883 if (m->m_nextpkt != NULL) {
885 static int afewtimes = 10;
887 if (afewtimes-- > 0) {
888 kprintf("mfree: m->m_nextpkt != NULL\n");
889 db_print_backtrace();
895 if (m->m_flags & M_PKTHDR) {
896 m_tag_delete_chain(m); /* eliminate XXX JH */
899 m->m_flags &= (M_EXT | M_EXT_CLUSTER | M_CLCACHE | M_PHCACHE);
902 * Clean the M_PKTHDR state so we can return the mbuf to its original
903 * cache. This is based on the PHCACHE flag which tells us whether
904 * the mbuf was originally allocated out of a packet-header cache
905 * or a non-packet-header cache.
907 if (m->m_flags & M_PHCACHE) {
908 m->m_flags |= M_PKTHDR;
909 m->m_pkthdr.rcvif = NULL; /* eliminate XXX JH */
910 m->m_pkthdr.csum_flags = 0; /* eliminate XXX JH */
911 m->m_pkthdr.fw_flags = 0; /* eliminate XXX JH */
912 SLIST_INIT(&m->m_pkthdr.tags);
916 * Handle remaining flags combinations. M_CLCACHE tells us whether
917 * the mbuf was originally allocated from a cluster cache or not,
918 * and is totally separate from whether the mbuf is currently
919 * associated with a cluster.
922 switch(m->m_flags & (M_CLCACHE | M_EXT | M_EXT_CLUSTER)) {
923 case M_CLCACHE | M_EXT | M_EXT_CLUSTER:
925 * mbuf+cluster cache case. The mbuf was allocated from the
926 * combined mbuf_cluster cache and can be returned to the
927 * cache if the cluster hasn't been shared.
929 if (m_sharecount(m) == 1) {
931 * The cluster has not been shared, we can just
932 * reset the data pointer and return the mbuf
933 * to the cluster cache. Note that the reference
934 * count is left intact (it is still associated with
937 m->m_data = m->m_ext.ext_buf;
938 if (m->m_flags & M_PHCACHE)
939 objcache_put(mbufphdrcluster_cache, m);
941 objcache_put(mbufcluster_cache, m);
942 atomic_subtract_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_clusters, 1);
945 * Hell. Someone else has a ref on this cluster,
946 * we have to disconnect it which means we can't
947 * put it back into the mbufcluster_cache, we
948 * have to destroy the mbuf.
950 * Other mbuf references to the cluster will typically
951 * be M_EXT | M_EXT_CLUSTER but without M_CLCACHE.
953 * XXX we could try to connect another cluster to
956 m->m_ext.ext_free(m->m_ext.ext_arg);
957 m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
958 if (m->m_flags & M_PHCACHE)
959 objcache_dtor(mbufphdrcluster_cache, m);
961 objcache_dtor(mbufcluster_cache, m);
964 case M_EXT | M_EXT_CLUSTER:
966 * Normal cluster associated with an mbuf that was allocated
967 * from the normal mbuf pool rather then the cluster pool.
968 * The cluster has to be independantly disassociated from the
971 if (m_sharecount(m) == 1)
972 atomic_subtract_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_clusters, 1);
976 * Normal cluster association case, disconnect the cluster from
977 * the mbuf. The cluster may or may not be custom.
979 m->m_ext.ext_free(m->m_ext.ext_arg);
980 m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
984 * return the mbuf to the mbuf cache.
986 if (m->m_flags & M_PHCACHE) {
987 m->m_data = m->m_pktdat;
988 objcache_put(mbufphdr_cache, m);
990 m->m_data = m->m_dat;
991 objcache_put(mbuf_cache, m);
993 atomic_subtract_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mbufs, 1);
997 panic("bad mbuf flags %p %08x\n", m, m->m_flags);
1005 m_freem(struct mbuf *m)
1014 * mbuf utility routines
1018 * Lesser-used path for M_PREPEND: allocate new mbuf to prepend to chain and
1022 m_prepend(struct mbuf *m, int len, int how)
1026 if (m->m_flags & M_PKTHDR)
1027 mn = m_gethdr(how, m->m_type);
1029 mn = m_get(how, m->m_type);
1034 if (m->m_flags & M_PKTHDR)
1035 M_MOVE_PKTHDR(mn, m);
1045 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
1046 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
1047 * The wait parameter is a choice of MB_WAIT/MB_DONTWAIT from caller.
1048 * Note that the copy is read-only, because clusters are not copied,
1049 * only their reference counts are incremented.
1052 m_copym(const struct mbuf *m, int off0, int len, int wait)
1054 struct mbuf *n, **np;
1059 KASSERT(off >= 0, ("m_copym, negative off %d", off));
1060 KASSERT(len >= 0, ("m_copym, negative len %d", len));
1061 if (off == 0 && m->m_flags & M_PKTHDR)
1064 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
1074 KASSERT(len == M_COPYALL,
1075 ("m_copym, length > size of mbuf chain"));
1079 * Because we are sharing any cluster attachment below,
1080 * be sure to get an mbuf that does not have a cluster
1081 * associated with it.
1084 n = m_gethdr(wait, m->m_type);
1086 n = m_get(wait, m->m_type);
1091 if (!m_dup_pkthdr(n, m, wait))
1093 if (len == M_COPYALL)
1094 n->m_pkthdr.len -= off0;
1096 n->m_pkthdr.len = len;
1099 n->m_len = min(len, m->m_len - off);
1100 if (m->m_flags & M_EXT) {
1101 KKASSERT((n->m_flags & M_EXT) == 0);
1102 n->m_data = m->m_data + off;
1103 m->m_ext.ext_ref(m->m_ext.ext_arg);
1104 n->m_ext = m->m_ext;
1105 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1107 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
1108 (unsigned)n->m_len);
1110 if (len != M_COPYALL)
1117 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mcfail, 1);
1121 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mcfail, 1);
1126 * Copy an entire packet, including header (which must be present).
1127 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
1128 * Note that the copy is read-only, because clusters are not copied,
1129 * only their reference counts are incremented.
1130 * Preserve alignment of the first mbuf so if the creator has left
1131 * some room at the beginning (e.g. for inserting protocol headers)
1132 * the copies also have the room available.
1135 m_copypacket(struct mbuf *m, int how)
1137 struct mbuf *top, *n, *o;
1139 n = m_gethdr(how, m->m_type);
1144 if (!m_dup_pkthdr(n, m, how))
1146 n->m_len = m->m_len;
1147 if (m->m_flags & M_EXT) {
1148 KKASSERT((n->m_flags & M_EXT) == 0);
1149 n->m_data = m->m_data;
1150 m->m_ext.ext_ref(m->m_ext.ext_arg);
1151 n->m_ext = m->m_ext;
1152 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1154 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
1155 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1160 o = m_get(how, m->m_type);
1167 n->m_len = m->m_len;
1168 if (m->m_flags & M_EXT) {
1169 KKASSERT((n->m_flags & M_EXT) == 0);
1170 n->m_data = m->m_data;
1171 m->m_ext.ext_ref(m->m_ext.ext_arg);
1172 n->m_ext = m->m_ext;
1173 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1175 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1183 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mcfail, 1);
1188 * Copy data from an mbuf chain starting "off" bytes from the beginning,
1189 * continuing for "len" bytes, into the indicated buffer.
1192 m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
1196 KASSERT(off >= 0, ("m_copydata, negative off %d", off));
1197 KASSERT(len >= 0, ("m_copydata, negative len %d", len));
1199 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
1206 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
1207 count = min(m->m_len - off, len);
1208 bcopy(mtod(m, caddr_t) + off, cp, count);
1217 * Copy a packet header mbuf chain into a completely new chain, including
1218 * copying any mbuf clusters. Use this instead of m_copypacket() when
1219 * you need a writable copy of an mbuf chain.
1222 m_dup(struct mbuf *m, int how)
1224 struct mbuf **p, *top = NULL;
1225 int remain, moff, nsize;
1230 KASSERT((m->m_flags & M_PKTHDR) != 0, ("%s: !PKTHDR", __func__));
1232 /* While there's more data, get a new mbuf, tack it on, and fill it */
1233 remain = m->m_pkthdr.len;
1236 while (remain > 0 || top == NULL) { /* allow m->m_pkthdr.len == 0 */
1239 /* Get the next new mbuf */
1240 n = m_getl(remain, how, m->m_type, top == NULL ? M_PKTHDR : 0,
1245 if (!m_dup_pkthdr(n, m, how))
1248 /* Link it into the new chain */
1252 /* Copy data from original mbuf(s) into new mbuf */
1254 while (n->m_len < nsize && m != NULL) {
1255 int chunk = min(nsize - n->m_len, m->m_len - moff);
1257 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1261 if (moff == m->m_len) {
1267 /* Check correct total mbuf length */
1268 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
1269 ("%s: bogus m_pkthdr.len", __func__));
1276 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mcfail, 1);
1281 * Concatenate mbuf chain n to m.
1282 * Both chains must be of the same type (e.g. MT_DATA).
1283 * Any m_pkthdr is not updated.
1286 m_cat(struct mbuf *m, struct mbuf *n)
1290 if (m->m_flags & M_EXT ||
1291 m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
1292 /* just join the two chains */
1296 /* splat the data from one into the other */
1297 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1299 m->m_len += n->m_len;
1305 m_adj(struct mbuf *mp, int req_len)
1311 if ((m = mp) == NULL)
1317 while (m != NULL && len > 0) {
1318 if (m->m_len <= len) {
1329 if (mp->m_flags & M_PKTHDR)
1330 m->m_pkthdr.len -= (req_len - len);
1333 * Trim from tail. Scan the mbuf chain,
1334 * calculating its length and finding the last mbuf.
1335 * If the adjustment only affects this mbuf, then just
1336 * adjust and return. Otherwise, rescan and truncate
1337 * after the remaining size.
1343 if (m->m_next == (struct mbuf *)0)
1347 if (m->m_len >= len) {
1349 if (mp->m_flags & M_PKTHDR)
1350 mp->m_pkthdr.len -= len;
1357 * Correct length for chain is "count".
1358 * Find the mbuf with last data, adjust its length,
1359 * and toss data from remaining mbufs on chain.
1362 if (m->m_flags & M_PKTHDR)
1363 m->m_pkthdr.len = count;
1364 for (; m; m = m->m_next) {
1365 if (m->m_len >= count) {
1372 (m = m->m_next) ->m_len = 0;
1377 * Rearrange an mbuf chain so that len bytes are contiguous
1378 * and in the data area of an mbuf (so that mtod will work for a structure
1379 * of size len). Returns the resulting mbuf chain on success, frees it and
1380 * returns null on failure. If there is room, it will add up to
1381 * max_protohdr-len extra bytes to the contiguous region in an attempt to
1382 * avoid being called next time.
1385 m_pullup(struct mbuf *n, int len)
1392 * If first mbuf has no cluster, and has room for len bytes
1393 * without shifting current data, pullup into it,
1394 * otherwise allocate a new mbuf to prepend to the chain.
1396 if (!(n->m_flags & M_EXT) &&
1397 n->m_data + len < &n->m_dat[MLEN] &&
1399 if (n->m_len >= len)
1407 if (n->m_flags & M_PKTHDR)
1408 m = m_gethdr(MB_DONTWAIT, n->m_type);
1410 m = m_get(MB_DONTWAIT, n->m_type);
1414 if (n->m_flags & M_PKTHDR)
1415 M_MOVE_PKTHDR(m, n);
1417 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1419 count = min(min(max(len, max_protohdr), space), n->m_len);
1420 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1430 } while (len > 0 && n);
1439 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mcfail, 1);
1444 * Partition an mbuf chain in two pieces, returning the tail --
1445 * all but the first len0 bytes. In case of failure, it returns NULL and
1446 * attempts to restore the chain to its original state.
1448 * Note that the resulting mbufs might be read-only, because the new
1449 * mbuf can end up sharing an mbuf cluster with the original mbuf if
1450 * the "breaking point" happens to lie within a cluster mbuf. Use the
1451 * M_WRITABLE() macro to check for this case.
1454 m_split(struct mbuf *m0, int len0, int wait)
1457 unsigned len = len0, remain;
1459 for (m = m0; m && len > m->m_len; m = m->m_next)
1463 remain = m->m_len - len;
1464 if (m0->m_flags & M_PKTHDR) {
1465 n = m_gethdr(wait, m0->m_type);
1468 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1469 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1470 m0->m_pkthdr.len = len0;
1471 if (m->m_flags & M_EXT)
1473 if (remain > MHLEN) {
1474 /* m can't be the lead packet */
1476 n->m_next = m_split(m, len, wait);
1477 if (n->m_next == NULL) {
1485 MH_ALIGN(n, remain);
1486 } else if (remain == 0) {
1491 n = m_get(wait, m->m_type);
1497 if (m->m_flags & M_EXT) {
1498 KKASSERT((n->m_flags & M_EXT) == 0);
1499 n->m_data = m->m_data + len;
1500 m->m_ext.ext_ref(m->m_ext.ext_arg);
1501 n->m_ext = m->m_ext;
1502 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1504 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1508 n->m_next = m->m_next;
1514 * Routine to copy from device local memory into mbufs.
1515 * Note: "offset" is ill-defined and always called as 0, so ignore it.
1518 m_devget(char *buf, int len, int offset, struct ifnet *ifp,
1519 void (*copy)(volatile const void *from, volatile void *to, size_t length))
1521 struct mbuf *m, *mfirst = NULL, **mtail;
1530 m = m_getl(len, MB_DONTWAIT, MT_DATA, flags, &nsize);
1535 m->m_len = min(len, nsize);
1537 if (flags & M_PKTHDR) {
1538 if (len + max_linkhdr <= nsize)
1539 m->m_data += max_linkhdr;
1540 m->m_pkthdr.rcvif = ifp;
1541 m->m_pkthdr.len = len;
1545 copy(buf, m->m_data, (unsigned)m->m_len);
1556 * Copy data from a buffer back into the indicated mbuf chain,
1557 * starting "off" bytes from the beginning, extending the mbuf
1558 * chain if necessary.
1561 m_copyback(struct mbuf *m0, int off, int len, caddr_t cp)
1564 struct mbuf *m = m0, *n;
1569 while (off > (mlen = m->m_len)) {
1572 if (m->m_next == NULL) {
1573 n = m_getclr(MB_DONTWAIT, m->m_type);
1576 n->m_len = min(MLEN, len + off);
1582 mlen = min (m->m_len - off, len);
1583 bcopy(cp, off + mtod(m, caddr_t), (unsigned)mlen);
1591 if (m->m_next == NULL) {
1592 n = m_get(MB_DONTWAIT, m->m_type);
1595 n->m_len = min(MLEN, len);
1600 out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1601 m->m_pkthdr.len = totlen;
1605 m_print(const struct mbuf *m)
1608 const struct mbuf *m2;
1610 len = m->m_pkthdr.len;
1613 kprintf("%p %*D\n", m2, m2->m_len, (u_char *)m2->m_data, "-");
1621 * "Move" mbuf pkthdr from "from" to "to".
1622 * "from" must have M_PKTHDR set, and "to" must be empty.
1625 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
1627 KASSERT((to->m_flags & M_PKTHDR), ("m_move_pkthdr: not packet header"));
1629 to->m_flags |= from->m_flags & M_COPYFLAGS;
1630 to->m_pkthdr = from->m_pkthdr; /* especially tags */
1631 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
1635 * Duplicate "from"'s mbuf pkthdr in "to".
1636 * "from" must have M_PKTHDR set, and "to" must be empty.
1637 * In particular, this does a deep copy of the packet tags.
1640 m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
1642 KASSERT((to->m_flags & M_PKTHDR), ("m_dup_pkthdr: not packet header"));
1644 to->m_flags = (from->m_flags & M_COPYFLAGS) |
1645 (to->m_flags & ~M_COPYFLAGS);
1646 to->m_pkthdr = from->m_pkthdr;
1647 SLIST_INIT(&to->m_pkthdr.tags);
1648 return (m_tag_copy_chain(to, from, how));
1652 * Defragment a mbuf chain, returning the shortest possible
1653 * chain of mbufs and clusters. If allocation fails and
1654 * this cannot be completed, NULL will be returned, but
1655 * the passed in chain will be unchanged. Upon success,
1656 * the original chain will be freed, and the new chain
1659 * If a non-packet header is passed in, the original
1660 * mbuf (chain?) will be returned unharmed.
1662 * m_defrag_nofree doesn't free the passed in mbuf.
1665 m_defrag(struct mbuf *m0, int how)
1669 if ((m_new = m_defrag_nofree(m0, how)) == NULL)
1677 m_defrag_nofree(struct mbuf *m0, int how)
1679 struct mbuf *m_new = NULL, *m_final = NULL;
1680 int progress = 0, length, nsize;
1682 if (!(m0->m_flags & M_PKTHDR))
1685 #ifdef MBUF_STRESS_TEST
1686 if (m_defragrandomfailures) {
1687 int temp = karc4random() & 0xff;
1693 m_final = m_getl(m0->m_pkthdr.len, how, MT_DATA, M_PKTHDR, &nsize);
1694 if (m_final == NULL)
1696 m_final->m_len = 0; /* in case m0->m_pkthdr.len is zero */
1698 if (m_dup_pkthdr(m_final, m0, how) == NULL)
1703 while (progress < m0->m_pkthdr.len) {
1704 length = m0->m_pkthdr.len - progress;
1705 if (length > MCLBYTES)
1708 if (m_new == NULL) {
1709 m_new = m_getl(length, how, MT_DATA, 0, &nsize);
1714 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1716 m_new->m_len = length;
1717 if (m_new != m_final)
1718 m_cat(m_final, m_new);
1721 if (m0->m_next == NULL)
1724 m_defragbytes += m_final->m_pkthdr.len;
1735 * Move data from uio into mbufs.
1738 m_uiomove(struct uio *uio)
1740 struct mbuf *m; /* current working mbuf */
1741 struct mbuf *head = NULL; /* result mbuf chain */
1742 struct mbuf **mp = &head;
1743 int resid = uio->uio_resid, nsize, flags = M_PKTHDR, error;
1746 m = m_getl(resid, MB_WAIT, MT_DATA, flags, &nsize);
1748 m->m_pkthdr.len = 0;
1749 /* Leave room for protocol headers. */
1754 m->m_len = min(nsize, resid);
1755 error = uiomove(mtod(m, caddr_t), m->m_len, uio);
1762 head->m_pkthdr.len += m->m_len;
1764 } while (resid > 0);
1774 m_last(struct mbuf *m)
1782 * Return the number of bytes in an mbuf chain.
1783 * If lastm is not NULL, also return the last mbuf.
1786 m_lengthm(struct mbuf *m, struct mbuf **lastm)
1789 struct mbuf *prev = m;
1802 * Like m_lengthm(), except also keep track of mbuf usage.
1805 m_countm(struct mbuf *m, struct mbuf **lastm, u_int *pmbcnt)
1807 u_int len = 0, mbcnt = 0;
1808 struct mbuf *prev = m;
1813 if (m->m_flags & M_EXT)
1814 mbcnt += m->m_ext.ext_size;