Home | History | Annotate | Line # | Download | only in kern
uipc_mbuf.c revision 1.184
      1 /*	$NetBSD: uipc_mbuf.c,v 1.184 2018/03/21 17:03:09 maxv Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1999, 2001 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
      9  * NASA Ames Research Center.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     30  * POSSIBILITY OF SUCH DAMAGE.
     31  */
     32 
     33 /*
     34  * Copyright (c) 1982, 1986, 1988, 1991, 1993
     35  *	The Regents of the University of California.  All rights reserved.
     36  *
     37  * Redistribution and use in source and binary forms, with or without
     38  * modification, are permitted provided that the following conditions
     39  * are met:
     40  * 1. Redistributions of source code must retain the above copyright
     41  *    notice, this list of conditions and the following disclaimer.
     42  * 2. Redistributions in binary form must reproduce the above copyright
     43  *    notice, this list of conditions and the following disclaimer in the
     44  *    documentation and/or other materials provided with the distribution.
     45  * 3. Neither the name of the University nor the names of its contributors
     46  *    may be used to endorse or promote products derived from this software
     47  *    without specific prior written permission.
     48  *
     49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     59  * SUCH DAMAGE.
     60  *
     61  *	@(#)uipc_mbuf.c	8.4 (Berkeley) 2/14/95
     62  */
     63 
     64 #include <sys/cdefs.h>
     65 __KERNEL_RCSID(0, "$NetBSD: uipc_mbuf.c,v 1.184 2018/03/21 17:03:09 maxv Exp $");
     66 
     67 #ifdef _KERNEL_OPT
     68 #include "opt_mbuftrace.h"
     69 #include "opt_nmbclusters.h"
     70 #include "opt_ddb.h"
     71 #endif
     72 
     73 #include <sys/param.h>
     74 #include <sys/systm.h>
     75 #include <sys/atomic.h>
     76 #include <sys/cpu.h>
     77 #include <sys/proc.h>
     78 #include <sys/mbuf.h>
     79 #include <sys/kernel.h>
     80 #include <sys/syslog.h>
     81 #include <sys/domain.h>
     82 #include <sys/protosw.h>
     83 #include <sys/percpu.h>
     84 #include <sys/pool.h>
     85 #include <sys/socket.h>
     86 #include <sys/sysctl.h>
     87 
     88 #include <net/if.h>
     89 
     90 pool_cache_t mb_cache;	/* mbuf cache */
     91 pool_cache_t mcl_cache;	/* mbuf cluster cache */
     92 
     93 struct mbstat mbstat;
     94 int	max_linkhdr;
     95 int	max_protohdr;
     96 int	max_hdr;
     97 int	max_datalen;
     98 
     99 static int mb_ctor(void *, void *, int);
    100 
    101 static void	sysctl_kern_mbuf_setup(void);
    102 
    103 static struct sysctllog *mbuf_sysctllog;
    104 
    105 static struct mbuf *m_copym0(struct mbuf *, int, int, int, bool);
    106 static struct mbuf *m_split0(struct mbuf *, int, int, bool);
    107 static int m_copyback0(struct mbuf **, int, int, const void *, int, int);
    108 
    109 /* flags for m_copyback0 */
    110 #define	M_COPYBACK0_COPYBACK	0x0001	/* copyback from cp */
    111 #define	M_COPYBACK0_PRESERVE	0x0002	/* preserve original data */
    112 #define	M_COPYBACK0_COW		0x0004	/* do copy-on-write */
    113 #define	M_COPYBACK0_EXTEND	0x0008	/* extend chain */
    114 
    115 static const char mclpool_warnmsg[] =
    116     "WARNING: mclpool limit reached; increase kern.mbuf.nmbclusters";
    117 
    118 MALLOC_DEFINE(M_MBUF, "mbuf", "mbuf");
    119 
    120 static percpu_t *mbstat_percpu;
    121 
    122 #ifdef MBUFTRACE
    123 struct mownerhead mowners = LIST_HEAD_INITIALIZER(mowners);
    124 struct mowner unknown_mowners[] = {
    125 	MOWNER_INIT("unknown", "free"),
    126 	MOWNER_INIT("unknown", "data"),
    127 	MOWNER_INIT("unknown", "header"),
    128 	MOWNER_INIT("unknown", "soname"),
    129 	MOWNER_INIT("unknown", "soopts"),
    130 	MOWNER_INIT("unknown", "ftable"),
    131 	MOWNER_INIT("unknown", "control"),
    132 	MOWNER_INIT("unknown", "oobdata"),
    133 };
    134 struct mowner revoked_mowner = MOWNER_INIT("revoked", "");
    135 #endif
    136 
    137 #define	MEXT_ISEMBEDDED(m) ((m)->m_ext_ref == (m))
    138 
    139 #define	MCLADDREFERENCE(o, n)						\
    140 do {									\
    141 	KASSERT(((o)->m_flags & M_EXT) != 0);				\
    142 	KASSERT(((n)->m_flags & M_EXT) == 0);				\
    143 	KASSERT((o)->m_ext.ext_refcnt >= 1);				\
    144 	(n)->m_flags |= ((o)->m_flags & M_EXTCOPYFLAGS);		\
    145 	atomic_inc_uint(&(o)->m_ext.ext_refcnt);			\
    146 	(n)->m_ext_ref = (o)->m_ext_ref;				\
    147 	mowner_ref((n), (n)->m_flags);					\
    148 	MCLREFDEBUGN((n), __FILE__, __LINE__);				\
    149 } while (/* CONSTCOND */ 0)
    150 
    151 static int
    152 nmbclusters_limit(void)
    153 {
    154 #if defined(PMAP_MAP_POOLPAGE)
    155 	/* direct mapping, doesn't use space in kmem_arena */
    156 	vsize_t max_size = physmem / 4;
    157 #else
    158 	vsize_t max_size = MIN(physmem / 4, nkmempages / 4);
    159 #endif
    160 
    161 	max_size = max_size * PAGE_SIZE / MCLBYTES;
    162 #ifdef NMBCLUSTERS_MAX
    163 	max_size = MIN(max_size, NMBCLUSTERS_MAX);
    164 #endif
    165 
    166 #ifdef NMBCLUSTERS
    167 	return MIN(max_size, NMBCLUSTERS);
    168 #else
    169 	return max_size;
    170 #endif
    171 }
    172 
    173 /*
    174  * Initialize the mbuf allocator.
    175  */
    176 void
    177 mbinit(void)
    178 {
    179 
    180 	CTASSERT(sizeof(struct _m_ext) <= MHLEN);
    181 	CTASSERT(sizeof(struct mbuf) == MSIZE);
    182 
    183 	sysctl_kern_mbuf_setup();
    184 
    185 	mb_cache = pool_cache_init(msize, 0, 0, 0, "mbpl",
    186 	    NULL, IPL_VM, mb_ctor, NULL, NULL);
    187 	KASSERT(mb_cache != NULL);
    188 
    189 	mcl_cache = pool_cache_init(mclbytes, 0, 0, 0, "mclpl", NULL,
    190 	    IPL_VM, NULL, NULL, NULL);
    191 	KASSERT(mcl_cache != NULL);
    192 
    193 	pool_cache_set_drain_hook(mb_cache, m_reclaim, NULL);
    194 	pool_cache_set_drain_hook(mcl_cache, m_reclaim, NULL);
    195 
    196 	/*
    197 	 * Set an arbitrary default limit on the number of mbuf clusters.
    198 	 */
    199 #ifdef NMBCLUSTERS
    200 	nmbclusters = nmbclusters_limit();
    201 #else
    202 	nmbclusters = MAX(1024,
    203 	    (vsize_t)physmem * PAGE_SIZE / MCLBYTES / 16);
    204 	nmbclusters = MIN(nmbclusters, nmbclusters_limit());
    205 #endif
    206 
    207 	/*
    208 	 * Set the hard limit on the mclpool to the number of
    209 	 * mbuf clusters the kernel is to support.  Log the limit
    210 	 * reached message max once a minute.
    211 	 */
    212 	pool_cache_sethardlimit(mcl_cache, nmbclusters, mclpool_warnmsg, 60);
    213 
    214 	mbstat_percpu = percpu_alloc(sizeof(struct mbstat_cpu));
    215 
    216 	/*
    217 	 * Set a low water mark for both mbufs and clusters.  This should
    218 	 * help ensure that they can be allocated in a memory starvation
    219 	 * situation.  This is important for e.g. diskless systems which
    220 	 * must allocate mbufs in order for the pagedaemon to clean pages.
    221 	 */
    222 	pool_cache_setlowat(mb_cache, mblowat);
    223 	pool_cache_setlowat(mcl_cache, mcllowat);
    224 
    225 #ifdef MBUFTRACE
    226 	{
    227 		/*
    228 		 * Attach the unknown mowners.
    229 		 */
    230 		int i;
    231 		MOWNER_ATTACH(&revoked_mowner);
    232 		for (i = sizeof(unknown_mowners)/sizeof(unknown_mowners[0]);
    233 		     i-- > 0; )
    234 			MOWNER_ATTACH(&unknown_mowners[i]);
    235 	}
    236 #endif
    237 }
    238 
    239 /*
    240  * sysctl helper routine for the kern.mbuf subtree.
    241  * nmbclusters, mblowat and mcllowat need range
    242  * checking and pool tweaking after being reset.
    243  */
    244 static int
    245 sysctl_kern_mbuf(SYSCTLFN_ARGS)
    246 {
    247 	int error, newval;
    248 	struct sysctlnode node;
    249 
    250 	node = *rnode;
    251 	node.sysctl_data = &newval;
    252 	switch (rnode->sysctl_num) {
    253 	case MBUF_NMBCLUSTERS:
    254 	case MBUF_MBLOWAT:
    255 	case MBUF_MCLLOWAT:
    256 		newval = *(int*)rnode->sysctl_data;
    257 		break;
    258 	default:
    259 		return (EOPNOTSUPP);
    260 	}
    261 
    262 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    263 	if (error || newp == NULL)
    264 		return (error);
    265 	if (newval < 0)
    266 		return (EINVAL);
    267 
    268 	switch (node.sysctl_num) {
    269 	case MBUF_NMBCLUSTERS:
    270 		if (newval < nmbclusters)
    271 			return (EINVAL);
    272 		if (newval > nmbclusters_limit())
    273 			return (EINVAL);
    274 		nmbclusters = newval;
    275 		pool_cache_sethardlimit(mcl_cache, nmbclusters,
    276 		    mclpool_warnmsg, 60);
    277 		break;
    278 	case MBUF_MBLOWAT:
    279 		mblowat = newval;
    280 		pool_cache_setlowat(mb_cache, mblowat);
    281 		break;
    282 	case MBUF_MCLLOWAT:
    283 		mcllowat = newval;
    284 		pool_cache_setlowat(mcl_cache, mcllowat);
    285 		break;
    286 	}
    287 
    288 	return (0);
    289 }
    290 
    291 #ifdef MBUFTRACE
    292 static void
    293 mowner_conver_to_user_cb(void *v1, void *v2, struct cpu_info *ci)
    294 {
    295 	struct mowner_counter *mc = v1;
    296 	struct mowner_user *mo_user = v2;
    297 	int i;
    298 
    299 	for (i = 0; i < MOWNER_COUNTER_NCOUNTERS; i++) {
    300 		mo_user->mo_counter[i] += mc->mc_counter[i];
    301 	}
    302 }
    303 
    304 static void
    305 mowner_convert_to_user(struct mowner *mo, struct mowner_user *mo_user)
    306 {
    307 
    308 	memset(mo_user, 0, sizeof(*mo_user));
    309 	CTASSERT(sizeof(mo_user->mo_name) == sizeof(mo->mo_name));
    310 	CTASSERT(sizeof(mo_user->mo_descr) == sizeof(mo->mo_descr));
    311 	memcpy(mo_user->mo_name, mo->mo_name, sizeof(mo->mo_name));
    312 	memcpy(mo_user->mo_descr, mo->mo_descr, sizeof(mo->mo_descr));
    313 	percpu_foreach(mo->mo_counters, mowner_conver_to_user_cb, mo_user);
    314 }
    315 
    316 static int
    317 sysctl_kern_mbuf_mowners(SYSCTLFN_ARGS)
    318 {
    319 	struct mowner *mo;
    320 	size_t len = 0;
    321 	int error = 0;
    322 
    323 	if (namelen != 0)
    324 		return (EINVAL);
    325 	if (newp != NULL)
    326 		return (EPERM);
    327 
    328 	LIST_FOREACH(mo, &mowners, mo_link) {
    329 		struct mowner_user mo_user;
    330 
    331 		mowner_convert_to_user(mo, &mo_user);
    332 
    333 		if (oldp != NULL) {
    334 			if (*oldlenp - len < sizeof(mo_user)) {
    335 				error = ENOMEM;
    336 				break;
    337 			}
    338 			error = copyout(&mo_user, (char *)oldp + len,
    339 			    sizeof(mo_user));
    340 			if (error)
    341 				break;
    342 		}
    343 		len += sizeof(mo_user);
    344 	}
    345 
    346 	if (error == 0)
    347 		*oldlenp = len;
    348 
    349 	return (error);
    350 }
    351 #endif /* MBUFTRACE */
    352 
    353 static void
    354 mbstat_conver_to_user_cb(void *v1, void *v2, struct cpu_info *ci)
    355 {
    356 	struct mbstat_cpu *mbsc = v1;
    357 	struct mbstat *mbs = v2;
    358 	int i;
    359 
    360 	for (i = 0; i < __arraycount(mbs->m_mtypes); i++) {
    361 		mbs->m_mtypes[i] += mbsc->m_mtypes[i];
    362 	}
    363 }
    364 
    365 static void
    366 mbstat_convert_to_user(struct mbstat *mbs)
    367 {
    368 
    369 	memset(mbs, 0, sizeof(*mbs));
    370 	mbs->m_drain = mbstat.m_drain;
    371 	percpu_foreach(mbstat_percpu, mbstat_conver_to_user_cb, mbs);
    372 }
    373 
    374 static int
    375 sysctl_kern_mbuf_stats(SYSCTLFN_ARGS)
    376 {
    377 	struct sysctlnode node;
    378 	struct mbstat mbs;
    379 
    380 	mbstat_convert_to_user(&mbs);
    381 	node = *rnode;
    382 	node.sysctl_data = &mbs;
    383 	node.sysctl_size = sizeof(mbs);
    384 	return sysctl_lookup(SYSCTLFN_CALL(&node));
    385 }
    386 
    387 static void
    388 sysctl_kern_mbuf_setup(void)
    389 {
    390 
    391 	KASSERT(mbuf_sysctllog == NULL);
    392 	sysctl_createv(&mbuf_sysctllog, 0, NULL, NULL,
    393 		       CTLFLAG_PERMANENT,
    394 		       CTLTYPE_NODE, "mbuf",
    395 		       SYSCTL_DESCR("mbuf control variables"),
    396 		       NULL, 0, NULL, 0,
    397 		       CTL_KERN, KERN_MBUF, CTL_EOL);
    398 
    399 	sysctl_createv(&mbuf_sysctllog, 0, NULL, NULL,
    400 		       CTLFLAG_PERMANENT|CTLFLAG_IMMEDIATE,
    401 		       CTLTYPE_INT, "msize",
    402 		       SYSCTL_DESCR("mbuf base size"),
    403 		       NULL, msize, NULL, 0,
    404 		       CTL_KERN, KERN_MBUF, MBUF_MSIZE, CTL_EOL);
    405 	sysctl_createv(&mbuf_sysctllog, 0, NULL, NULL,
    406 		       CTLFLAG_PERMANENT|CTLFLAG_IMMEDIATE,
    407 		       CTLTYPE_INT, "mclbytes",
    408 		       SYSCTL_DESCR("mbuf cluster size"),
    409 		       NULL, mclbytes, NULL, 0,
    410 		       CTL_KERN, KERN_MBUF, MBUF_MCLBYTES, CTL_EOL);
    411 	sysctl_createv(&mbuf_sysctllog, 0, NULL, NULL,
    412 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    413 		       CTLTYPE_INT, "nmbclusters",
    414 		       SYSCTL_DESCR("Limit on the number of mbuf clusters"),
    415 		       sysctl_kern_mbuf, 0, &nmbclusters, 0,
    416 		       CTL_KERN, KERN_MBUF, MBUF_NMBCLUSTERS, CTL_EOL);
    417 	sysctl_createv(&mbuf_sysctllog, 0, NULL, NULL,
    418 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    419 		       CTLTYPE_INT, "mblowat",
    420 		       SYSCTL_DESCR("mbuf low water mark"),
    421 		       sysctl_kern_mbuf, 0, &mblowat, 0,
    422 		       CTL_KERN, KERN_MBUF, MBUF_MBLOWAT, CTL_EOL);
    423 	sysctl_createv(&mbuf_sysctllog, 0, NULL, NULL,
    424 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    425 		       CTLTYPE_INT, "mcllowat",
    426 		       SYSCTL_DESCR("mbuf cluster low water mark"),
    427 		       sysctl_kern_mbuf, 0, &mcllowat, 0,
    428 		       CTL_KERN, KERN_MBUF, MBUF_MCLLOWAT, CTL_EOL);
    429 	sysctl_createv(&mbuf_sysctllog, 0, NULL, NULL,
    430 		       CTLFLAG_PERMANENT,
    431 		       CTLTYPE_STRUCT, "stats",
    432 		       SYSCTL_DESCR("mbuf allocation statistics"),
    433 		       sysctl_kern_mbuf_stats, 0, NULL, 0,
    434 		       CTL_KERN, KERN_MBUF, MBUF_STATS, CTL_EOL);
    435 #ifdef MBUFTRACE
    436 	sysctl_createv(&mbuf_sysctllog, 0, NULL, NULL,
    437 		       CTLFLAG_PERMANENT,
    438 		       CTLTYPE_STRUCT, "mowners",
    439 		       SYSCTL_DESCR("Information about mbuf owners"),
    440 		       sysctl_kern_mbuf_mowners, 0, NULL, 0,
    441 		       CTL_KERN, KERN_MBUF, MBUF_MOWNERS, CTL_EOL);
    442 #endif /* MBUFTRACE */
    443 }
    444 
    445 static int
    446 mb_ctor(void *arg, void *object, int flags)
    447 {
    448 	struct mbuf *m = object;
    449 
    450 #ifdef POOL_VTOPHYS
    451 	m->m_paddr = POOL_VTOPHYS(m);
    452 #else
    453 	m->m_paddr = M_PADDR_INVALID;
    454 #endif
    455 	return (0);
    456 }
    457 
    458 void
    459 m_pkthdr_remove(struct mbuf *m)
    460 {
    461 	KASSERT(m->m_flags & M_PKTHDR);
    462 
    463 	m_tag_delete_chain(m, NULL);
    464 	m->m_flags &= ~M_PKTHDR;
    465 	memset(&m->m_pkthdr, 0, sizeof(m->m_pkthdr));
    466 }
    467 
    468 /*
    469  * Add mbuf to the end of a chain
    470  */
    471 struct mbuf *
    472 m_add(struct mbuf *c, struct mbuf *m)
    473 {
    474 	struct mbuf *n;
    475 
    476 	if (c == NULL)
    477 		return m;
    478 
    479 	for (n = c; n->m_next != NULL; n = n->m_next)
    480 		continue;
    481 	n->m_next = m;
    482 	return c;
    483 }
    484 
    485 /*
    486  * Set the m_data pointer of a newly-allocated mbuf
    487  * to place an object of the specified size at the
    488  * end of the mbuf, longword aligned.
    489  */
    490 void
    491 m_align(struct mbuf *m, int len)
    492 {
    493 	int adjust;
    494 
    495 	KASSERT(len != M_COPYALL);
    496 
    497 	if (m->m_flags & M_EXT)
    498 		adjust = m->m_ext.ext_size - len;
    499 	else if (m->m_flags & M_PKTHDR)
    500 		adjust = MHLEN - len;
    501 	else
    502 		adjust = MLEN - len;
    503 	m->m_data += adjust &~ (sizeof(long)-1);
    504 }
    505 
    506 /*
    507  * Append the specified data to the indicated mbuf chain,
    508  * Extend the mbuf chain if the new data does not fit in
    509  * existing space.
    510  *
    511  * Return 1 if able to complete the job; otherwise 0.
    512  */
    513 int
    514 m_append(struct mbuf *m0, int len, const void *cpv)
    515 {
    516 	struct mbuf *m, *n;
    517 	int remainder, space;
    518 	const char *cp = cpv;
    519 
    520 	KASSERT(len != M_COPYALL);
    521 	for (m = m0; m->m_next != NULL; m = m->m_next)
    522 		continue;
    523 	remainder = len;
    524 	space = M_TRAILINGSPACE(m);
    525 	if (space > 0) {
    526 		/*
    527 		 * Copy into available space.
    528 		 */
    529 		if (space > remainder)
    530 			space = remainder;
    531 		memmove(mtod(m, char *) + m->m_len, cp, space);
    532 		m->m_len += space;
    533 		cp = cp + space, remainder -= space;
    534 	}
    535 	while (remainder > 0) {
    536 		/*
    537 		 * Allocate a new mbuf; could check space
    538 		 * and allocate a cluster instead.
    539 		 */
    540 		n = m_get(M_DONTWAIT, m->m_type);
    541 		if (n == NULL)
    542 			break;
    543 		n->m_len = min(MLEN, remainder);
    544 		memmove(mtod(n, void *), cp, n->m_len);
    545 		cp += n->m_len, remainder -= n->m_len;
    546 		m->m_next = n;
    547 		m = n;
    548 	}
    549 	if (m0->m_flags & M_PKTHDR)
    550 		m0->m_pkthdr.len += len - remainder;
    551 	return (remainder == 0);
    552 }
    553 
    554 void
    555 m_reclaim(void *arg, int flags)
    556 {
    557 	struct domain *dp;
    558 	const struct protosw *pr;
    559 	struct ifnet *ifp;
    560 	int s;
    561 
    562 	KERNEL_LOCK(1, NULL);
    563 	s = splvm();
    564 	DOMAIN_FOREACH(dp) {
    565 		for (pr = dp->dom_protosw;
    566 		     pr < dp->dom_protoswNPROTOSW; pr++)
    567 			if (pr->pr_drain)
    568 				(*pr->pr_drain)();
    569 	}
    570 	/* XXX we cannot use psref in H/W interrupt */
    571 	if (!cpu_intr_p()) {
    572 		int bound = curlwp_bind();
    573 		IFNET_READER_FOREACH(ifp) {
    574 			struct psref psref;
    575 
    576 			if_acquire(ifp, &psref);
    577 
    578 			if (ifp->if_drain)
    579 				(*ifp->if_drain)(ifp);
    580 
    581 			if_release(ifp, &psref);
    582 		}
    583 		curlwp_bindx(bound);
    584 	}
    585 	splx(s);
    586 	mbstat.m_drain++;
    587 	KERNEL_UNLOCK_ONE(NULL);
    588 }
    589 
    590 /*
    591  * Space allocation routines.
    592  * These are also available as macros
    593  * for critical paths.
    594  */
    595 struct mbuf *
    596 m_get(int nowait, int type)
    597 {
    598 	struct mbuf *m;
    599 
    600 	KASSERT(type != MT_FREE);
    601 
    602 	m = pool_cache_get(mb_cache,
    603 	    nowait == M_WAIT ? PR_WAITOK|PR_LIMITFAIL : PR_NOWAIT);
    604 	if (m == NULL)
    605 		return NULL;
    606 
    607 	mbstat_type_add(type, 1);
    608 
    609 	mowner_init(m, type);
    610 	m->m_ext_ref = m; /* default */
    611 	m->m_type = type;
    612 	m->m_len = 0;
    613 	m->m_next = NULL;
    614 	m->m_nextpkt = NULL; /* default */
    615 	m->m_data = m->m_dat;
    616 	m->m_flags = 0; /* default */
    617 
    618 	return m;
    619 }
    620 
    621 struct mbuf *
    622 m_gethdr(int nowait, int type)
    623 {
    624 	struct mbuf *m;
    625 
    626 	m = m_get(nowait, type);
    627 	if (m == NULL)
    628 		return NULL;
    629 
    630 	m->m_data = m->m_pktdat;
    631 	m->m_flags = M_PKTHDR;
    632 
    633 	m_reset_rcvif(m);
    634 	m->m_pkthdr.len = 0;
    635 	m->m_pkthdr.csum_flags = 0;
    636 	m->m_pkthdr.csum_data = 0;
    637 	SLIST_INIT(&m->m_pkthdr.tags);
    638 
    639 	m->m_pkthdr.pattr_class = NULL;
    640 	m->m_pkthdr.pattr_af = AF_UNSPEC;
    641 	m->m_pkthdr.pattr_hdr = NULL;
    642 
    643 	return m;
    644 }
    645 
    646 struct mbuf *
    647 m_getclr(int nowait, int type)
    648 {
    649 	struct mbuf *m;
    650 
    651 	m = m_get(nowait, type);
    652 	if (m == NULL)
    653 		return NULL;
    654 	memset(mtod(m, void *), 0, MLEN);
    655 	return m;
    656 }
    657 
    658 void
    659 m_clget(struct mbuf *m, int nowait)
    660 {
    661 
    662 	MCLGET(m, nowait);
    663 }
    664 
    665 #ifdef MBUFTRACE
    666 /*
    667  * Walk a chain of mbufs, claiming ownership of each mbuf in the chain.
    668  */
    669 void
    670 m_claimm(struct mbuf *m, struct mowner *mo)
    671 {
    672 
    673 	for (; m != NULL; m = m->m_next)
    674 		MCLAIM(m, mo);
    675 }
    676 #endif
    677 
    678 /*
    679  * Mbuffer utility routines.
    680  */
    681 
    682 /*
    683  * Lesser-used path for M_PREPEND:
    684  * allocate new mbuf to prepend to chain,
    685  * copy junk along.
    686  */
    687 struct mbuf *
    688 m_prepend(struct mbuf *m, int len, int how)
    689 {
    690 	struct mbuf *mn;
    691 
    692 	if (__predict_false(len > MHLEN)) {
    693 		panic("%s: len > MHLEN", __func__);
    694 	}
    695 
    696 	KASSERT(len != M_COPYALL);
    697 	mn = m_get(how, m->m_type);
    698 	if (mn == NULL) {
    699 		m_freem(m);
    700 		return NULL;
    701 	}
    702 
    703 	if (m->m_flags & M_PKTHDR) {
    704 		M_MOVE_PKTHDR(mn, m);
    705 	} else {
    706 		MCLAIM(mn, m->m_owner);
    707 	}
    708 	mn->m_next = m;
    709 	m = mn;
    710 
    711 	if (m->m_flags & M_PKTHDR) {
    712 		if (len < MHLEN)
    713 			MH_ALIGN(m, len);
    714 	} else {
    715 		if (len < MLEN)
    716 			M_ALIGN(m, len);
    717 	}
    718 
    719 	m->m_len = len;
    720 	return m;
    721 }
    722 
    723 /*
    724  * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
    725  * continuing for "len" bytes.  If len is M_COPYALL, copy to end of mbuf.
    726  * The wait parameter is a choice of M_WAIT/M_DONTWAIT from caller.
    727  */
    728 struct mbuf *
    729 m_copym(struct mbuf *m, int off0, int len, int wait)
    730 {
    731 
    732 	return m_copym0(m, off0, len, wait, false); /* shallow copy on M_EXT */
    733 }
    734 
    735 struct mbuf *
    736 m_dup(struct mbuf *m, int off0, int len, int wait)
    737 {
    738 
    739 	return m_copym0(m, off0, len, wait, true); /* deep copy */
    740 }
    741 
    742 static inline int
    743 m_copylen(int len, int copylen)
    744 {
    745 	return (len == M_COPYALL) ? copylen : min(len, copylen);
    746 }
    747 
    748 static struct mbuf *
    749 m_copym0(struct mbuf *m, int off0, int len, int wait, bool deep)
    750 {
    751 	struct mbuf *n, **np;
    752 	int off = off0;
    753 	struct mbuf *top;
    754 	int copyhdr = 0;
    755 
    756 	if (off < 0 || (len != M_COPYALL && len < 0))
    757 		panic("m_copym: off %d, len %d", off, len);
    758 	if (off == 0 && m->m_flags & M_PKTHDR)
    759 		copyhdr = 1;
    760 	while (off > 0) {
    761 		if (m == NULL)
    762 			panic("m_copym: m == 0, off %d", off);
    763 		if (off < m->m_len)
    764 			break;
    765 		off -= m->m_len;
    766 		m = m->m_next;
    767 	}
    768 
    769 	np = &top;
    770 	top = NULL;
    771 	while (len == M_COPYALL || len > 0) {
    772 		if (m == NULL) {
    773 			if (len != M_COPYALL)
    774 				panic("m_copym: m == 0, len %d [!COPYALL]",
    775 				    len);
    776 			break;
    777 		}
    778 
    779 		n = m_get(wait, m->m_type);
    780 		*np = n;
    781 		if (n == NULL)
    782 			goto nospace;
    783 		MCLAIM(n, m->m_owner);
    784 
    785 		if (copyhdr) {
    786 			M_COPY_PKTHDR(n, m);
    787 			if (len == M_COPYALL)
    788 				n->m_pkthdr.len -= off0;
    789 			else
    790 				n->m_pkthdr.len = len;
    791 			copyhdr = 0;
    792 		}
    793 		n->m_len = m_copylen(len, m->m_len - off);
    794 
    795 		if (m->m_flags & M_EXT) {
    796 			if (!deep) {
    797 				n->m_data = m->m_data + off;
    798 				MCLADDREFERENCE(m, n);
    799 			} else {
    800 				/*
    801 				 * We don't care if MCLGET fails. n->m_len is
    802 				 * recomputed and handles that.
    803 				 */
    804 				MCLGET(n, wait);
    805 				n->m_len = 0;
    806 				n->m_len = M_TRAILINGSPACE(n);
    807 				n->m_len = m_copylen(len, n->m_len);
    808 				n->m_len = min(n->m_len, m->m_len - off);
    809 				memcpy(mtod(n, void *), mtod(m, char *) + off,
    810 				    (unsigned)n->m_len);
    811 			}
    812 		} else {
    813 			memcpy(mtod(n, void *), mtod(m, char *) + off,
    814 			    (unsigned)n->m_len);
    815 		}
    816 
    817 		if (len != M_COPYALL)
    818 			len -= n->m_len;
    819 		off += n->m_len;
    820 #ifdef DIAGNOSTIC
    821 		if (off > m->m_len)
    822 			panic("m_copym0 overrun %d %d", off, m->m_len);
    823 #endif
    824 		if (off == m->m_len) {
    825 			m = m->m_next;
    826 			off = 0;
    827 		}
    828 		np = &n->m_next;
    829 	}
    830 
    831 	return top;
    832 
    833 nospace:
    834 	m_freem(top);
    835 	return NULL;
    836 }
    837 
    838 /*
    839  * Copy an entire packet, including header (which must be present).
    840  * An optimization of the common case 'm_copym(m, 0, M_COPYALL, how)'.
    841  */
    842 struct mbuf *
    843 m_copypacket(struct mbuf *m, int how)
    844 {
    845 	struct mbuf *top, *n, *o;
    846 
    847 	n = m_get(how, m->m_type);
    848 	top = n;
    849 	if (!n)
    850 		goto nospace;
    851 
    852 	MCLAIM(n, m->m_owner);
    853 	M_COPY_PKTHDR(n, m);
    854 	n->m_len = m->m_len;
    855 	if (m->m_flags & M_EXT) {
    856 		n->m_data = m->m_data;
    857 		MCLADDREFERENCE(m, n);
    858 	} else {
    859 		memcpy(mtod(n, char *), mtod(m, char *), n->m_len);
    860 	}
    861 
    862 	m = m->m_next;
    863 	while (m) {
    864 		o = m_get(how, m->m_type);
    865 		if (!o)
    866 			goto nospace;
    867 
    868 		MCLAIM(o, m->m_owner);
    869 		n->m_next = o;
    870 		n = n->m_next;
    871 
    872 		n->m_len = m->m_len;
    873 		if (m->m_flags & M_EXT) {
    874 			n->m_data = m->m_data;
    875 			MCLADDREFERENCE(m, n);
    876 		} else {
    877 			memcpy(mtod(n, char *), mtod(m, char *), n->m_len);
    878 		}
    879 
    880 		m = m->m_next;
    881 	}
    882 	return top;
    883 
    884 nospace:
    885 	m_freem(top);
    886 	return NULL;
    887 }
    888 
    889 /*
    890  * Copy data from an mbuf chain starting "off" bytes from the beginning,
    891  * continuing for "len" bytes, into the indicated buffer.
    892  */
    893 void
    894 m_copydata(struct mbuf *m, int off, int len, void *vp)
    895 {
    896 	unsigned count;
    897 	void *cp = vp;
    898 	struct mbuf *m0 = m;
    899 	int len0 = len;
    900 	int off0 = off;
    901 	void *vp0 = vp;
    902 
    903 	KASSERT(len != M_COPYALL);
    904 	if (off < 0 || len < 0)
    905 		panic("m_copydata: off %d, len %d", off, len);
    906 	while (off > 0) {
    907 		if (m == NULL)
    908 			panic("m_copydata(%p,%d,%d,%p): m=NULL, off=%d (%d)",
    909 			    m0, len0, off0, vp0, off, off0 - off);
    910 		if (off < m->m_len)
    911 			break;
    912 		off -= m->m_len;
    913 		m = m->m_next;
    914 	}
    915 	while (len > 0) {
    916 		if (m == NULL)
    917 			panic("m_copydata(%p,%d,%d,%p): "
    918 			    "m=NULL, off=%d (%d), len=%d (%d)",
    919 			    m0, len0, off0, vp0,
    920 			    off, off0 - off, len, len0 - len);
    921 		count = min(m->m_len - off, len);
    922 		memcpy(cp, mtod(m, char *) + off, count);
    923 		len -= count;
    924 		cp = (char *)cp + count;
    925 		off = 0;
    926 		m = m->m_next;
    927 	}
    928 }
    929 
    930 /*
    931  * Concatenate mbuf chain n to m.
    932  * n might be copied into m (when n->m_len is small), therefore data portion of
    933  * n could be copied into an mbuf of different mbuf type.
    934  * Any m_pkthdr is not updated.
    935  */
    936 void
    937 m_cat(struct mbuf *m, struct mbuf *n)
    938 {
    939 
    940 	while (m->m_next)
    941 		m = m->m_next;
    942 	while (n) {
    943 		if (M_READONLY(m) || n->m_len > M_TRAILINGSPACE(m)) {
    944 			/* just join the two chains */
    945 			m->m_next = n;
    946 			return;
    947 		}
    948 		/* splat the data from one into the other */
    949 		memcpy(mtod(m, char *) + m->m_len, mtod(n, void *),
    950 		    (u_int)n->m_len);
    951 		m->m_len += n->m_len;
    952 		n = m_free(n);
    953 	}
    954 }
    955 
    956 void
    957 m_adj(struct mbuf *mp, int req_len)
    958 {
    959 	int len = req_len;
    960 	struct mbuf *m;
    961 	int count;
    962 
    963 	if ((m = mp) == NULL)
    964 		return;
    965 	if (len >= 0) {
    966 		/*
    967 		 * Trim from head.
    968 		 */
    969 		while (m != NULL && len > 0) {
    970 			if (m->m_len <= len) {
    971 				len -= m->m_len;
    972 				m->m_len = 0;
    973 				m = m->m_next;
    974 			} else {
    975 				m->m_len -= len;
    976 				m->m_data += len;
    977 				len = 0;
    978 			}
    979 		}
    980 		if (mp->m_flags & M_PKTHDR)
    981 			mp->m_pkthdr.len -= (req_len - len);
    982 	} else {
    983 		/*
    984 		 * Trim from tail.  Scan the mbuf chain,
    985 		 * calculating its length and finding the last mbuf.
    986 		 * If the adjustment only affects this mbuf, then just
    987 		 * adjust and return.  Otherwise, rescan and truncate
    988 		 * after the remaining size.
    989 		 */
    990 		len = -len;
    991 		count = 0;
    992 		for (;;) {
    993 			count += m->m_len;
    994 			if (m->m_next == NULL)
    995 				break;
    996 			m = m->m_next;
    997 		}
    998 		if (m->m_len >= len) {
    999 			m->m_len -= len;
   1000 			if (mp->m_flags & M_PKTHDR)
   1001 				mp->m_pkthdr.len -= len;
   1002 			return;
   1003 		}
   1004 
   1005 		count -= len;
   1006 		if (count < 0)
   1007 			count = 0;
   1008 
   1009 		/*
   1010 		 * Correct length for chain is "count".
   1011 		 * Find the mbuf with last data, adjust its length,
   1012 		 * and toss data from remaining mbufs on chain.
   1013 		 */
   1014 		m = mp;
   1015 		if (m->m_flags & M_PKTHDR)
   1016 			m->m_pkthdr.len = count;
   1017 		for (; m; m = m->m_next) {
   1018 			if (m->m_len >= count) {
   1019 				m->m_len = count;
   1020 				break;
   1021 			}
   1022 			count -= m->m_len;
   1023 		}
   1024 		if (m) {
   1025 			while (m->m_next)
   1026 				(m = m->m_next)->m_len = 0;
   1027 		}
   1028 	}
   1029 }
   1030 
   1031 /*
   1032  * m_ensure_contig: rearrange an mbuf chain that given length of bytes
   1033  * would be contiguous and in the data area of an mbuf (therefore, mtod()
   1034  * would work for a structure of given length).
   1035  *
   1036  * => On success, returns true and the resulting mbuf chain; false otherwise.
   1037  * => The mbuf chain may change, but is always preserved valid.
   1038  */
   1039 bool
   1040 m_ensure_contig(struct mbuf **m0, int len)
   1041 {
   1042 	struct mbuf *n = *m0, *m;
   1043 	size_t count, space;
   1044 
   1045 	KASSERT(len != M_COPYALL);
   1046 	/*
   1047 	 * If first mbuf has no cluster, and has room for len bytes
   1048 	 * without shifting current data, pullup into it,
   1049 	 * otherwise allocate a new mbuf to prepend to the chain.
   1050 	 */
   1051 	if ((n->m_flags & M_EXT) == 0 &&
   1052 	    n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
   1053 		if (n->m_len >= len) {
   1054 			return true;
   1055 		}
   1056 		m = n;
   1057 		n = n->m_next;
   1058 		len -= m->m_len;
   1059 	} else {
   1060 		if (len > MHLEN) {
   1061 			return false;
   1062 		}
   1063 		m = m_get(M_DONTWAIT, n->m_type);
   1064 		if (m == NULL) {
   1065 			return false;
   1066 		}
   1067 		MCLAIM(m, n->m_owner);
   1068 		if (n->m_flags & M_PKTHDR) {
   1069 			M_MOVE_PKTHDR(m, n);
   1070 		}
   1071 	}
   1072 	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
   1073 	do {
   1074 		count = MIN(MIN(MAX(len, max_protohdr), space), n->m_len);
   1075 		memcpy(mtod(m, char *) + m->m_len, mtod(n, void *),
   1076 		  (unsigned)count);
   1077 		len -= count;
   1078 		m->m_len += count;
   1079 		n->m_len -= count;
   1080 		space -= count;
   1081 		if (n->m_len)
   1082 			n->m_data += count;
   1083 		else
   1084 			n = m_free(n);
   1085 	} while (len > 0 && n);
   1086 
   1087 	m->m_next = n;
   1088 	*m0 = m;
   1089 
   1090 	return len <= 0;
   1091 }
   1092 
   1093 /*
   1094  * m_pullup: same as m_ensure_contig(), but destroys mbuf chain on error.
   1095  */
   1096 struct mbuf *
   1097 m_pullup(struct mbuf *n, int len)
   1098 {
   1099 	struct mbuf *m = n;
   1100 
   1101 	KASSERT(len != M_COPYALL);
   1102 	if (!m_ensure_contig(&m, len)) {
   1103 		KASSERT(m != NULL);
   1104 		m_freem(m);
   1105 		m = NULL;
   1106 	}
   1107 	return m;
   1108 }
   1109 
   1110 /*
   1111  * Like m_pullup(), except a new mbuf is always allocated, and we allow
   1112  * the amount of empty space before the data in the new mbuf to be specified
   1113  * (in the event that the caller expects to prepend later).
   1114  */
   1115 struct mbuf *
   1116 m_copyup(struct mbuf *n, int len, int dstoff)
   1117 {
   1118 	struct mbuf *m;
   1119 	int count, space;
   1120 
   1121 	KASSERT(len != M_COPYALL);
   1122 	if (len > (MHLEN - dstoff))
   1123 		goto bad;
   1124 	m = m_get(M_DONTWAIT, n->m_type);
   1125 	if (m == NULL)
   1126 		goto bad;
   1127 	MCLAIM(m, n->m_owner);
   1128 	if (n->m_flags & M_PKTHDR) {
   1129 		M_MOVE_PKTHDR(m, n);
   1130 	}
   1131 	m->m_data += dstoff;
   1132 	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
   1133 	do {
   1134 		count = min(min(max(len, max_protohdr), space), n->m_len);
   1135 		memcpy(mtod(m, char *) + m->m_len, mtod(n, void *),
   1136 		    (unsigned)count);
   1137 		len -= count;
   1138 		m->m_len += count;
   1139 		n->m_len -= count;
   1140 		space -= count;
   1141 		if (n->m_len)
   1142 			n->m_data += count;
   1143 		else
   1144 			n = m_free(n);
   1145 	} while (len > 0 && n);
   1146 	if (len > 0) {
   1147 		(void) m_free(m);
   1148 		goto bad;
   1149 	}
   1150 	m->m_next = n;
   1151 	return (m);
   1152  bad:
   1153 	m_freem(n);
   1154 	return (NULL);
   1155 }
   1156 
   1157 /*
   1158  * Partition an mbuf chain in two pieces, returning the tail --
   1159  * all but the first len0 bytes.  In case of failure, it returns NULL and
   1160  * attempts to restore the chain to its original state.
   1161  */
   1162 struct mbuf *
   1163 m_split(struct mbuf *m0, int len0, int wait)
   1164 {
   1165 
   1166 	return m_split0(m0, len0, wait, true);
   1167 }
   1168 
   1169 static struct mbuf *
   1170 m_split0(struct mbuf *m0, int len0, int wait, bool copyhdr)
   1171 {
   1172 	struct mbuf *m, *n;
   1173 	unsigned len = len0, remain, len_save;
   1174 
   1175 	KASSERT(len0 != M_COPYALL);
   1176 	for (m = m0; m && len > m->m_len; m = m->m_next)
   1177 		len -= m->m_len;
   1178 	if (m == NULL)
   1179 		return NULL;
   1180 
   1181 	remain = m->m_len - len;
   1182 	if (copyhdr && (m0->m_flags & M_PKTHDR)) {
   1183 		n = m_gethdr(wait, m0->m_type);
   1184 		if (n == NULL)
   1185 			return NULL;
   1186 
   1187 		MCLAIM(n, m0->m_owner);
   1188 		m_copy_rcvif(n, m0);
   1189 		n->m_pkthdr.len = m0->m_pkthdr.len - len0;
   1190 		len_save = m0->m_pkthdr.len;
   1191 		m0->m_pkthdr.len = len0;
   1192 
   1193 		if (m->m_flags & M_EXT)
   1194 			goto extpacket;
   1195 
   1196 		if (remain > MHLEN) {
   1197 			/* m can't be the lead packet */
   1198 			MH_ALIGN(n, 0);
   1199 			n->m_len = 0;
   1200 			n->m_next = m_split(m, len, wait);
   1201 			if (n->m_next == NULL) {
   1202 				(void)m_free(n);
   1203 				m0->m_pkthdr.len = len_save;
   1204 				return NULL;
   1205 			}
   1206 			return n;
   1207 		} else {
   1208 			MH_ALIGN(n, remain);
   1209 		}
   1210 	} else if (remain == 0) {
   1211 		n = m->m_next;
   1212 		m->m_next = NULL;
   1213 		return n;
   1214 	} else {
   1215 		n = m_get(wait, m->m_type);
   1216 		if (n == NULL)
   1217 			return NULL;
   1218 		MCLAIM(n, m->m_owner);
   1219 		M_ALIGN(n, remain);
   1220 	}
   1221 
   1222 extpacket:
   1223 	if (m->m_flags & M_EXT) {
   1224 		n->m_data = m->m_data + len;
   1225 		MCLADDREFERENCE(m, n);
   1226 	} else {
   1227 		memcpy(mtod(n, void *), mtod(m, char *) + len, remain);
   1228 	}
   1229 
   1230 	n->m_len = remain;
   1231 	m->m_len = len;
   1232 	n->m_next = m->m_next;
   1233 	m->m_next = NULL;
   1234 	return n;
   1235 }
   1236 
   1237 /*
   1238  * Routine to copy from device local memory into mbufs.
   1239  */
   1240 struct mbuf *
   1241 m_devget(char *buf, int totlen, int off0, struct ifnet *ifp,
   1242     void (*copy)(const void *from, void *to, size_t len))
   1243 {
   1244 	struct mbuf *m;
   1245 	struct mbuf *top = NULL, **mp = &top;
   1246 	int off = off0, len;
   1247 	char *cp, *epkt;
   1248 
   1249 	cp = buf;
   1250 	epkt = cp + totlen;
   1251 	if (off) {
   1252 		/*
   1253 		 * If 'off' is non-zero, packet is trailer-encapsulated,
   1254 		 * so we have to skip the type and length fields.
   1255 		 */
   1256 		cp += off + 2 * sizeof(uint16_t);
   1257 		totlen -= 2 * sizeof(uint16_t);
   1258 	}
   1259 
   1260 	m = m_gethdr(M_DONTWAIT, MT_DATA);
   1261 	if (m == NULL)
   1262 		return NULL;
   1263 	m_set_rcvif(m, ifp);
   1264 	m->m_pkthdr.len = totlen;
   1265 	m->m_len = MHLEN;
   1266 
   1267 	while (totlen > 0) {
   1268 		if (top) {
   1269 			m = m_get(M_DONTWAIT, MT_DATA);
   1270 			if (m == NULL) {
   1271 				m_freem(top);
   1272 				return NULL;
   1273 			}
   1274 			m->m_len = MLEN;
   1275 		}
   1276 
   1277 		len = min(totlen, epkt - cp);
   1278 
   1279 		if (len >= MINCLSIZE) {
   1280 			MCLGET(m, M_DONTWAIT);
   1281 			if ((m->m_flags & M_EXT) == 0) {
   1282 				m_free(m);
   1283 				m_freem(top);
   1284 				return NULL;
   1285 			}
   1286 			m->m_len = len = min(len, MCLBYTES);
   1287 		} else {
   1288 			/*
   1289 			 * Place initial small packet/header at end of mbuf.
   1290 			 */
   1291 			if (len < m->m_len) {
   1292 				if (top == 0 && len + max_linkhdr <= m->m_len)
   1293 					m->m_data += max_linkhdr;
   1294 				m->m_len = len;
   1295 			} else
   1296 				len = m->m_len;
   1297 		}
   1298 
   1299 		if (copy)
   1300 			copy(cp, mtod(m, void *), (size_t)len);
   1301 		else
   1302 			memcpy(mtod(m, void *), cp, (size_t)len);
   1303 
   1304 		cp += len;
   1305 		*mp = m;
   1306 		mp = &m->m_next;
   1307 		totlen -= len;
   1308 		if (cp == epkt)
   1309 			cp = buf;
   1310 	}
   1311 
   1312 	return top;
   1313 }
   1314 
   1315 /*
   1316  * Copy data from a buffer back into the indicated mbuf chain,
   1317  * starting "off" bytes from the beginning, extending the mbuf
   1318  * chain if necessary.
   1319  */
   1320 void
   1321 m_copyback(struct mbuf *m0, int off, int len, const void *cp)
   1322 {
   1323 #if defined(DEBUG)
   1324 	struct mbuf *origm = m0;
   1325 	int error;
   1326 #endif
   1327 
   1328 	if (m0 == NULL)
   1329 		return;
   1330 
   1331 #if defined(DEBUG)
   1332 	error =
   1333 #endif
   1334 	m_copyback0(&m0, off, len, cp,
   1335 	    M_COPYBACK0_COPYBACK|M_COPYBACK0_EXTEND, M_DONTWAIT);
   1336 
   1337 #if defined(DEBUG)
   1338 	if (error != 0 || (m0 != NULL && origm != m0))
   1339 		panic("m_copyback");
   1340 #endif
   1341 }
   1342 
   1343 struct mbuf *
   1344 m_copyback_cow(struct mbuf *m0, int off, int len, const void *cp, int how)
   1345 {
   1346 	int error;
   1347 
   1348 	/* don't support chain expansion */
   1349 	KASSERT(len != M_COPYALL);
   1350 	KDASSERT(off + len <= m_length(m0));
   1351 
   1352 	error = m_copyback0(&m0, off, len, cp,
   1353 	    M_COPYBACK0_COPYBACK|M_COPYBACK0_COW, how);
   1354 	if (error) {
   1355 		/*
   1356 		 * no way to recover from partial success.
   1357 		 * just free the chain.
   1358 		 */
   1359 		m_freem(m0);
   1360 		return NULL;
   1361 	}
   1362 	return m0;
   1363 }
   1364 
   1365 /*
   1366  * m_makewritable: ensure the specified range writable.
   1367  */
   1368 int
   1369 m_makewritable(struct mbuf **mp, int off, int len, int how)
   1370 {
   1371 	int error;
   1372 #if defined(DEBUG)
   1373 	int origlen = m_length(*mp);
   1374 #endif
   1375 
   1376 	error = m_copyback0(mp, off, len, NULL,
   1377 	    M_COPYBACK0_PRESERVE|M_COPYBACK0_COW, how);
   1378 
   1379 	if (error)
   1380 		return error;
   1381 
   1382 #if defined(DEBUG)
   1383 	int reslen = 0;
   1384 	for (struct mbuf *n = *mp; n; n = n->m_next)
   1385 		reslen += n->m_len;
   1386 	if (origlen != reslen)
   1387 		panic("m_makewritable: length changed");
   1388 	if (((*mp)->m_flags & M_PKTHDR) != 0 && reslen != (*mp)->m_pkthdr.len)
   1389 		panic("m_makewritable: inconsist");
   1390 #endif
   1391 
   1392 	return 0;
   1393 }
   1394 
   1395 /*
   1396  * Copy the mbuf chain to a new mbuf chain that is as short as possible.
   1397  * Return the new mbuf chain on success, NULL on failure.  On success,
   1398  * free the old mbuf chain.
   1399  */
   1400 struct mbuf *
   1401 m_defrag(struct mbuf *mold, int flags)
   1402 {
   1403 	struct mbuf *m0, *mn, *n;
   1404 	size_t sz = mold->m_pkthdr.len;
   1405 
   1406 	KASSERT((mold->m_flags & M_PKTHDR) != 0);
   1407 
   1408 	m0 = m_gethdr(flags, MT_DATA);
   1409 	if (m0 == NULL)
   1410 		return NULL;
   1411 	M_COPY_PKTHDR(m0, mold);
   1412 	mn = m0;
   1413 
   1414 	do {
   1415 		if (sz > MHLEN) {
   1416 			MCLGET(mn, M_DONTWAIT);
   1417 			if ((mn->m_flags & M_EXT) == 0) {
   1418 				m_freem(m0);
   1419 				return NULL;
   1420 			}
   1421 		}
   1422 
   1423 		mn->m_len = MIN(sz, MCLBYTES);
   1424 
   1425 		m_copydata(mold, mold->m_pkthdr.len - sz, mn->m_len,
   1426 		     mtod(mn, void *));
   1427 
   1428 		sz -= mn->m_len;
   1429 
   1430 		if (sz > 0) {
   1431 			/* need more mbufs */
   1432 			n = m_get(M_NOWAIT, MT_DATA);
   1433 			if (n == NULL) {
   1434 				m_freem(m0);
   1435 				return NULL;
   1436 			}
   1437 
   1438 			mn->m_next = n;
   1439 			mn = n;
   1440 		}
   1441 	} while (sz > 0);
   1442 
   1443 	m_freem(mold);
   1444 
   1445 	return m0;
   1446 }
   1447 
   1448 int
   1449 m_copyback0(struct mbuf **mp0, int off, int len, const void *vp, int flags,
   1450     int how)
   1451 {
   1452 	int mlen;
   1453 	struct mbuf *m, *n;
   1454 	struct mbuf **mp;
   1455 	int totlen = 0;
   1456 	const char *cp = vp;
   1457 
   1458 	KASSERT(mp0 != NULL);
   1459 	KASSERT(*mp0 != NULL);
   1460 	KASSERT((flags & M_COPYBACK0_PRESERVE) == 0 || cp == NULL);
   1461 	KASSERT((flags & M_COPYBACK0_COPYBACK) == 0 || cp != NULL);
   1462 
   1463 	if (len == M_COPYALL)
   1464 		len = m_length(*mp0) - off;
   1465 
   1466 	/*
   1467 	 * we don't bother to update "totlen" in the case of M_COPYBACK0_COW,
   1468 	 * assuming that M_COPYBACK0_EXTEND and M_COPYBACK0_COW are exclusive.
   1469 	 */
   1470 
   1471 	KASSERT((~flags & (M_COPYBACK0_EXTEND|M_COPYBACK0_COW)) != 0);
   1472 
   1473 	mp = mp0;
   1474 	m = *mp;
   1475 	while (off > (mlen = m->m_len)) {
   1476 		off -= mlen;
   1477 		totlen += mlen;
   1478 		if (m->m_next == NULL) {
   1479 			int tspace;
   1480 extend:
   1481 			if ((flags & M_COPYBACK0_EXTEND) == 0)
   1482 				goto out;
   1483 
   1484 			/*
   1485 			 * try to make some space at the end of "m".
   1486 			 */
   1487 
   1488 			mlen = m->m_len;
   1489 			if (off + len >= MINCLSIZE &&
   1490 			    (m->m_flags & M_EXT) == 0 && m->m_len == 0) {
   1491 				MCLGET(m, how);
   1492 			}
   1493 			tspace = M_TRAILINGSPACE(m);
   1494 			if (tspace > 0) {
   1495 				tspace = min(tspace, off + len);
   1496 				KASSERT(tspace > 0);
   1497 				memset(mtod(m, char *) + m->m_len, 0,
   1498 				    min(off, tspace));
   1499 				m->m_len += tspace;
   1500 				off += mlen;
   1501 				totlen -= mlen;
   1502 				continue;
   1503 			}
   1504 
   1505 			/*
   1506 			 * need to allocate an mbuf.
   1507 			 */
   1508 
   1509 			if (off + len >= MINCLSIZE) {
   1510 				n = m_getcl(how, m->m_type, 0);
   1511 			} else {
   1512 				n = m_get(how, m->m_type);
   1513 			}
   1514 			if (n == NULL) {
   1515 				goto out;
   1516 			}
   1517 			n->m_len = min(M_TRAILINGSPACE(n), off + len);
   1518 			memset(mtod(n, char *), 0, min(n->m_len, off));
   1519 			m->m_next = n;
   1520 		}
   1521 		mp = &m->m_next;
   1522 		m = m->m_next;
   1523 	}
   1524 	while (len > 0) {
   1525 		mlen = m->m_len - off;
   1526 		if (mlen != 0 && M_READONLY(m)) {
   1527 			char *datap;
   1528 			int eatlen;
   1529 
   1530 			/*
   1531 			 * this mbuf is read-only.
   1532 			 * allocate a new writable mbuf and try again.
   1533 			 */
   1534 
   1535 #if defined(DIAGNOSTIC)
   1536 			if ((flags & M_COPYBACK0_COW) == 0)
   1537 				panic("m_copyback0: read-only");
   1538 #endif /* defined(DIAGNOSTIC) */
   1539 
   1540 			/*
   1541 			 * if we're going to write into the middle of
   1542 			 * a mbuf, split it first.
   1543 			 */
   1544 			if (off > 0) {
   1545 				n = m_split0(m, off, how, false);
   1546 				if (n == NULL)
   1547 					goto enobufs;
   1548 				m->m_next = n;
   1549 				mp = &m->m_next;
   1550 				m = n;
   1551 				off = 0;
   1552 				continue;
   1553 			}
   1554 
   1555 			/*
   1556 			 * XXX TODO coalesce into the trailingspace of
   1557 			 * the previous mbuf when possible.
   1558 			 */
   1559 
   1560 			/*
   1561 			 * allocate a new mbuf.  copy packet header if needed.
   1562 			 */
   1563 			n = m_get(how, m->m_type);
   1564 			if (n == NULL)
   1565 				goto enobufs;
   1566 			MCLAIM(n, m->m_owner);
   1567 			if (off == 0 && (m->m_flags & M_PKTHDR) != 0) {
   1568 				M_MOVE_PKTHDR(n, m);
   1569 				n->m_len = MHLEN;
   1570 			} else {
   1571 				if (len >= MINCLSIZE)
   1572 					MCLGET(n, M_DONTWAIT);
   1573 				n->m_len =
   1574 				    (n->m_flags & M_EXT) ? MCLBYTES : MLEN;
   1575 			}
   1576 			if (n->m_len > len)
   1577 				n->m_len = len;
   1578 
   1579 			/*
   1580 			 * free the region which has been overwritten.
   1581 			 * copying data from old mbufs if requested.
   1582 			 */
   1583 			if (flags & M_COPYBACK0_PRESERVE)
   1584 				datap = mtod(n, char *);
   1585 			else
   1586 				datap = NULL;
   1587 			eatlen = n->m_len;
   1588 			while (m != NULL && M_READONLY(m) &&
   1589 			    n->m_type == m->m_type && eatlen > 0) {
   1590 				mlen = min(eatlen, m->m_len);
   1591 				if (datap) {
   1592 					m_copydata(m, 0, mlen, datap);
   1593 					datap += mlen;
   1594 				}
   1595 				m->m_data += mlen;
   1596 				m->m_len -= mlen;
   1597 				eatlen -= mlen;
   1598 				if (m->m_len == 0)
   1599 					*mp = m = m_free(m);
   1600 			}
   1601 			if (eatlen > 0)
   1602 				n->m_len -= eatlen;
   1603 			n->m_next = m;
   1604 			*mp = m = n;
   1605 			continue;
   1606 		}
   1607 		mlen = min(mlen, len);
   1608 		if (flags & M_COPYBACK0_COPYBACK) {
   1609 			memcpy(mtod(m, char *) + off, cp, (unsigned)mlen);
   1610 			cp += mlen;
   1611 		}
   1612 		len -= mlen;
   1613 		mlen += off;
   1614 		off = 0;
   1615 		totlen += mlen;
   1616 		if (len == 0)
   1617 			break;
   1618 		if (m->m_next == NULL) {
   1619 			goto extend;
   1620 		}
   1621 		mp = &m->m_next;
   1622 		m = m->m_next;
   1623 	}
   1624 out:	if (((m = *mp0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen)) {
   1625 		KASSERT((flags & M_COPYBACK0_EXTEND) != 0);
   1626 		m->m_pkthdr.len = totlen;
   1627 	}
   1628 
   1629 	return 0;
   1630 
   1631 enobufs:
   1632 	return ENOBUFS;
   1633 }
   1634 
   1635 void
   1636 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
   1637 {
   1638 
   1639 	KASSERT((to->m_flags & M_EXT) == 0);
   1640 	KASSERT((to->m_flags & M_PKTHDR) == 0 || m_tag_first(to) == NULL);
   1641 	KASSERT((from->m_flags & M_PKTHDR) != 0);
   1642 
   1643 	to->m_pkthdr = from->m_pkthdr;
   1644 	to->m_flags = from->m_flags & M_COPYFLAGS;
   1645 	to->m_data = to->m_pktdat;
   1646 
   1647 	from->m_flags &= ~M_PKTHDR;
   1648 }
   1649 
   1650 /*
   1651  * Apply function f to the data in an mbuf chain starting "off" bytes from the
   1652  * beginning, continuing for "len" bytes.
   1653  */
   1654 int
   1655 m_apply(struct mbuf *m, int off, int len,
   1656     int (*f)(void *, void *, unsigned int), void *arg)
   1657 {
   1658 	unsigned int count;
   1659 	int rval;
   1660 
   1661 	KASSERT(len != M_COPYALL);
   1662 	KASSERT(len >= 0);
   1663 	KASSERT(off >= 0);
   1664 
   1665 	while (off > 0) {
   1666 		KASSERT(m != NULL);
   1667 		if (off < m->m_len)
   1668 			break;
   1669 		off -= m->m_len;
   1670 		m = m->m_next;
   1671 	}
   1672 	while (len > 0) {
   1673 		KASSERT(m != NULL);
   1674 		count = min(m->m_len - off, len);
   1675 
   1676 		rval = (*f)(arg, mtod(m, char *) + off, count);
   1677 		if (rval)
   1678 			return rval;
   1679 
   1680 		len -= count;
   1681 		off = 0;
   1682 		m = m->m_next;
   1683 	}
   1684 
   1685 	return 0;
   1686 }
   1687 
   1688 /*
   1689  * Return a pointer to mbuf/offset of location in mbuf chain.
   1690  */
   1691 struct mbuf *
   1692 m_getptr(struct mbuf *m, int loc, int *off)
   1693 {
   1694 
   1695 	while (loc >= 0) {
   1696 		/* Normal end of search */
   1697 		if (m->m_len > loc) {
   1698 			*off = loc;
   1699 			return m;
   1700 		}
   1701 
   1702 		loc -= m->m_len;
   1703 
   1704 		if (m->m_next == NULL) {
   1705 			if (loc == 0) {
   1706 				/* Point at the end of valid data */
   1707 				*off = m->m_len;
   1708 				return m;
   1709 			}
   1710 			return NULL;
   1711 		} else {
   1712 			m = m->m_next;
   1713 		}
   1714 	}
   1715 
   1716 	return NULL;
   1717 }
   1718 
   1719 /*
   1720  * m_ext_free: release a reference to the mbuf external storage.
   1721  *
   1722  * => free the mbuf m itself as well.
   1723  */
   1724 
   1725 void
   1726 m_ext_free(struct mbuf *m)
   1727 {
   1728 	const bool embedded = MEXT_ISEMBEDDED(m);
   1729 	bool dofree = true;
   1730 	u_int refcnt;
   1731 
   1732 	KASSERT((m->m_flags & M_EXT) != 0);
   1733 	KASSERT(MEXT_ISEMBEDDED(m->m_ext_ref));
   1734 	KASSERT((m->m_ext_ref->m_flags & M_EXT) != 0);
   1735 	KASSERT((m->m_flags & M_EXT_CLUSTER) ==
   1736 	    (m->m_ext_ref->m_flags & M_EXT_CLUSTER));
   1737 
   1738 	if (__predict_false(m->m_type == MT_FREE)) {
   1739 		panic("mbuf %p already freed", m);
   1740 	}
   1741 
   1742 	if (__predict_true(m->m_ext.ext_refcnt == 1)) {
   1743 		refcnt = m->m_ext.ext_refcnt = 0;
   1744 	} else {
   1745 		refcnt = atomic_dec_uint_nv(&m->m_ext.ext_refcnt);
   1746 	}
   1747 
   1748 	if (refcnt > 0) {
   1749 		if (embedded) {
   1750 			/*
   1751 			 * other mbuf's m_ext_ref still points to us.
   1752 			 */
   1753 			dofree = false;
   1754 		} else {
   1755 			m->m_ext_ref = m;
   1756 		}
   1757 	} else {
   1758 		/*
   1759 		 * dropping the last reference
   1760 		 */
   1761 		if (!embedded) {
   1762 			m->m_ext.ext_refcnt++; /* XXX */
   1763 			m_ext_free(m->m_ext_ref);
   1764 			m->m_ext_ref = m;
   1765 		} else if ((m->m_flags & M_EXT_CLUSTER) != 0) {
   1766 			pool_cache_put_paddr((struct pool_cache *)
   1767 			    m->m_ext.ext_arg,
   1768 			    m->m_ext.ext_buf, m->m_ext.ext_paddr);
   1769 		} else if (m->m_ext.ext_free) {
   1770 			(*m->m_ext.ext_free)(m,
   1771 			    m->m_ext.ext_buf, m->m_ext.ext_size,
   1772 			    m->m_ext.ext_arg);
   1773 			/*
   1774 			 * 'm' is already freed by the ext_free callback.
   1775 			 */
   1776 			dofree = false;
   1777 		} else {
   1778 			free(m->m_ext.ext_buf, m->m_ext.ext_type);
   1779 		}
   1780 	}
   1781 
   1782 	if (dofree) {
   1783 		m->m_type = MT_FREE;
   1784 		m->m_data = NULL;
   1785 		pool_cache_put(mb_cache, m);
   1786 	}
   1787 }
   1788 
   1789 #if defined(DDB)
   1790 void
   1791 m_print(const struct mbuf *m, const char *modif, void (*pr)(const char *, ...))
   1792 {
   1793 	char ch;
   1794 	bool opt_c = false;
   1795 	char buf[512];
   1796 
   1797 	while ((ch = *(modif++)) != '\0') {
   1798 		switch (ch) {
   1799 		case 'c':
   1800 			opt_c = true;
   1801 			break;
   1802 		}
   1803 	}
   1804 
   1805 nextchain:
   1806 	(*pr)("MBUF %p\n", m);
   1807 	snprintb(buf, sizeof(buf), M_FLAGS_BITS, (u_int)m->m_flags);
   1808 	(*pr)("  data=%p, len=%d, type=%d, flags=%s\n",
   1809 	    m->m_data, m->m_len, m->m_type, buf);
   1810 	(*pr)("  owner=%p, next=%p, nextpkt=%p\n", m->m_owner, m->m_next,
   1811 	    m->m_nextpkt);
   1812 	(*pr)("  leadingspace=%u, trailingspace=%u, readonly=%u\n",
   1813 	    (int)M_LEADINGSPACE(m), (int)M_TRAILINGSPACE(m),
   1814 	    (int)M_READONLY(m));
   1815 	if ((m->m_flags & M_PKTHDR) != 0) {
   1816 		snprintb(buf, sizeof(buf), M_CSUM_BITS, m->m_pkthdr.csum_flags);
   1817 		(*pr)("  pktlen=%d, rcvif=%p, csum_flags=%s, csum_data=0x%"
   1818 		    PRIx32 ", segsz=%u\n",
   1819 		    m->m_pkthdr.len, m_get_rcvif_NOMPSAFE(m),
   1820 		    buf, m->m_pkthdr.csum_data, m->m_pkthdr.segsz);
   1821 	}
   1822 	if ((m->m_flags & M_EXT)) {
   1823 		(*pr)("  ext_refcnt=%u, ext_buf=%p, ext_size=%zd, "
   1824 		    "ext_free=%p, ext_arg=%p\n",
   1825 		    m->m_ext.ext_refcnt,
   1826 		    m->m_ext.ext_buf, m->m_ext.ext_size,
   1827 		    m->m_ext.ext_free, m->m_ext.ext_arg);
   1828 	}
   1829 	if ((~m->m_flags & (M_EXT|M_EXT_PAGES)) == 0) {
   1830 		vaddr_t sva = (vaddr_t)m->m_ext.ext_buf;
   1831 		vaddr_t eva = sva + m->m_ext.ext_size;
   1832 		int n = (round_page(eva) - trunc_page(sva)) >> PAGE_SHIFT;
   1833 		int i;
   1834 
   1835 		(*pr)("  pages:");
   1836 		for (i = 0; i < n; i ++) {
   1837 			(*pr)(" %p", m->m_ext.ext_pgs[i]);
   1838 		}
   1839 		(*pr)("\n");
   1840 	}
   1841 
   1842 	if (opt_c) {
   1843 		m = m->m_next;
   1844 		if (m != NULL) {
   1845 			goto nextchain;
   1846 		}
   1847 	}
   1848 }
   1849 #endif /* defined(DDB) */
   1850 
   1851 void
   1852 mbstat_type_add(int type, int diff)
   1853 {
   1854 	struct mbstat_cpu *mb;
   1855 	int s;
   1856 
   1857 	s = splvm();
   1858 	mb = percpu_getref(mbstat_percpu);
   1859 	mb->m_mtypes[type] += diff;
   1860 	percpu_putref(mbstat_percpu);
   1861 	splx(s);
   1862 }
   1863 
   1864 #if defined(MBUFTRACE)
   1865 void
   1866 mowner_attach(struct mowner *mo)
   1867 {
   1868 
   1869 	KASSERT(mo->mo_counters == NULL);
   1870 	mo->mo_counters = percpu_alloc(sizeof(struct mowner_counter));
   1871 
   1872 	/* XXX lock */
   1873 	LIST_INSERT_HEAD(&mowners, mo, mo_link);
   1874 }
   1875 
   1876 void
   1877 mowner_detach(struct mowner *mo)
   1878 {
   1879 
   1880 	KASSERT(mo->mo_counters != NULL);
   1881 
   1882 	/* XXX lock */
   1883 	LIST_REMOVE(mo, mo_link);
   1884 
   1885 	percpu_free(mo->mo_counters, sizeof(struct mowner_counter));
   1886 	mo->mo_counters = NULL;
   1887 }
   1888 
   1889 void
   1890 mowner_init(struct mbuf *m, int type)
   1891 {
   1892 	struct mowner_counter *mc;
   1893 	struct mowner *mo;
   1894 	int s;
   1895 
   1896 	m->m_owner = mo = &unknown_mowners[type];
   1897 	s = splvm();
   1898 	mc = percpu_getref(mo->mo_counters);
   1899 	mc->mc_counter[MOWNER_COUNTER_CLAIMS]++;
   1900 	percpu_putref(mo->mo_counters);
   1901 	splx(s);
   1902 }
   1903 
   1904 void
   1905 mowner_ref(struct mbuf *m, int flags)
   1906 {
   1907 	struct mowner *mo = m->m_owner;
   1908 	struct mowner_counter *mc;
   1909 	int s;
   1910 
   1911 	s = splvm();
   1912 	mc = percpu_getref(mo->mo_counters);
   1913 	if ((flags & M_EXT) != 0)
   1914 		mc->mc_counter[MOWNER_COUNTER_EXT_CLAIMS]++;
   1915 	if ((flags & M_CLUSTER) != 0)
   1916 		mc->mc_counter[MOWNER_COUNTER_CLUSTER_CLAIMS]++;
   1917 	percpu_putref(mo->mo_counters);
   1918 	splx(s);
   1919 }
   1920 
   1921 void
   1922 mowner_revoke(struct mbuf *m, bool all, int flags)
   1923 {
   1924 	struct mowner *mo = m->m_owner;
   1925 	struct mowner_counter *mc;
   1926 	int s;
   1927 
   1928 	s = splvm();
   1929 	mc = percpu_getref(mo->mo_counters);
   1930 	if ((flags & M_EXT) != 0)
   1931 		mc->mc_counter[MOWNER_COUNTER_EXT_RELEASES]++;
   1932 	if ((flags & M_CLUSTER) != 0)
   1933 		mc->mc_counter[MOWNER_COUNTER_CLUSTER_RELEASES]++;
   1934 	if (all)
   1935 		mc->mc_counter[MOWNER_COUNTER_RELEASES]++;
   1936 	percpu_putref(mo->mo_counters);
   1937 	splx(s);
   1938 	if (all)
   1939 		m->m_owner = &revoked_mowner;
   1940 }
   1941 
   1942 static void
   1943 mowner_claim(struct mbuf *m, struct mowner *mo)
   1944 {
   1945 	struct mowner_counter *mc;
   1946 	int flags = m->m_flags;
   1947 	int s;
   1948 
   1949 	s = splvm();
   1950 	mc = percpu_getref(mo->mo_counters);
   1951 	mc->mc_counter[MOWNER_COUNTER_CLAIMS]++;
   1952 	if ((flags & M_EXT) != 0)
   1953 		mc->mc_counter[MOWNER_COUNTER_EXT_CLAIMS]++;
   1954 	if ((flags & M_CLUSTER) != 0)
   1955 		mc->mc_counter[MOWNER_COUNTER_CLUSTER_CLAIMS]++;
   1956 	percpu_putref(mo->mo_counters);
   1957 	splx(s);
   1958 	m->m_owner = mo;
   1959 }
   1960 
   1961 void
   1962 m_claim(struct mbuf *m, struct mowner *mo)
   1963 {
   1964 
   1965 	if (m->m_owner == mo || mo == NULL)
   1966 		return;
   1967 
   1968 	mowner_revoke(m, true, m->m_flags);
   1969 	mowner_claim(m, mo);
   1970 }
   1971 #endif /* defined(MBUFTRACE) */
   1972 
   1973 /*
   1974  * Free a single mbuf and associated external storage. Return the
   1975  * successor, if any.
   1976  */
   1977 struct mbuf *
   1978 m_free(struct mbuf *m)
   1979 {
   1980 	struct mbuf *n;
   1981 
   1982 	mowner_revoke(m, 1, m->m_flags);
   1983 	mbstat_type_add(m->m_type, -1);
   1984 
   1985 	if (m->m_flags & M_PKTHDR)
   1986 		m_tag_delete_chain(m, NULL);
   1987 
   1988 	n = m->m_next;
   1989 
   1990 	if (m->m_flags & M_EXT) {
   1991 		m_ext_free(m);
   1992 	} else {
   1993 		if (__predict_false(m->m_type == MT_FREE)) {
   1994 			panic("mbuf %p already freed", m);
   1995 		}
   1996 		m->m_type = MT_FREE;
   1997 		m->m_data = NULL;
   1998 		pool_cache_put(mb_cache, m);
   1999 	}
   2000 
   2001 	return n;
   2002 }
   2003 
   2004 void
   2005 m_freem(struct mbuf *m)
   2006 {
   2007 	if (m == NULL)
   2008 		return;
   2009 	do {
   2010 		m = m_free(m);
   2011 	} while (m);
   2012 }
   2013