Home | History | Annotate | Line # | Download | only in kern
uipc_mbuf.c revision 1.191
      1 /*	$NetBSD: uipc_mbuf.c,v 1.191 2018/04/17 07:58:31 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.191 2018/04/17 07:58:31 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 	if (M_READONLY(m)) {
    464 		/* Nothing we can do. */
    465 		return;
    466 	}
    467 
    468 	m_tag_delete_chain(m, NULL);
    469 	m->m_flags &= ~M_PKTHDR;
    470 	memset(&m->m_pkthdr, 0, sizeof(m->m_pkthdr));
    471 }
    472 
    473 /*
    474  * Add mbuf to the end of a chain
    475  */
    476 struct mbuf *
    477 m_add(struct mbuf *c, struct mbuf *m)
    478 {
    479 	struct mbuf *n;
    480 
    481 	if (c == NULL)
    482 		return m;
    483 
    484 	for (n = c; n->m_next != NULL; n = n->m_next)
    485 		continue;
    486 	n->m_next = m;
    487 	return c;
    488 }
    489 
    490 /*
    491  * Set the m_data pointer of a newly-allocated mbuf
    492  * to place an object of the specified size at the
    493  * end of the mbuf, longword aligned.
    494  */
    495 void
    496 m_align(struct mbuf *m, int len)
    497 {
    498 	int adjust;
    499 
    500 	KASSERT(len != M_COPYALL);
    501 
    502 	if (m->m_flags & M_EXT)
    503 		adjust = m->m_ext.ext_size - len;
    504 	else if (m->m_flags & M_PKTHDR)
    505 		adjust = MHLEN - len;
    506 	else
    507 		adjust = MLEN - len;
    508 	m->m_data += adjust &~ (sizeof(long)-1);
    509 }
    510 
    511 /*
    512  * Append the specified data to the indicated mbuf chain,
    513  * Extend the mbuf chain if the new data does not fit in
    514  * existing space.
    515  *
    516  * Return 1 if able to complete the job; otherwise 0.
    517  */
    518 int
    519 m_append(struct mbuf *m0, int len, const void *cpv)
    520 {
    521 	struct mbuf *m, *n;
    522 	int remainder, space;
    523 	const char *cp = cpv;
    524 
    525 	KASSERT(len != M_COPYALL);
    526 	for (m = m0; m->m_next != NULL; m = m->m_next)
    527 		continue;
    528 	remainder = len;
    529 	space = M_TRAILINGSPACE(m);
    530 	if (space > 0) {
    531 		/*
    532 		 * Copy into available space.
    533 		 */
    534 		if (space > remainder)
    535 			space = remainder;
    536 		memmove(mtod(m, char *) + m->m_len, cp, space);
    537 		m->m_len += space;
    538 		cp = cp + space, remainder -= space;
    539 	}
    540 	while (remainder > 0) {
    541 		/*
    542 		 * Allocate a new mbuf; could check space
    543 		 * and allocate a cluster instead.
    544 		 */
    545 		n = m_get(M_DONTWAIT, m->m_type);
    546 		if (n == NULL)
    547 			break;
    548 		n->m_len = min(MLEN, remainder);
    549 		memmove(mtod(n, void *), cp, n->m_len);
    550 		cp += n->m_len, remainder -= n->m_len;
    551 		m->m_next = n;
    552 		m = n;
    553 	}
    554 	if (m0->m_flags & M_PKTHDR)
    555 		m0->m_pkthdr.len += len - remainder;
    556 	return (remainder == 0);
    557 }
    558 
    559 void
    560 m_reclaim(void *arg, int flags)
    561 {
    562 	struct domain *dp;
    563 	const struct protosw *pr;
    564 	struct ifnet *ifp;
    565 	int s;
    566 
    567 	KERNEL_LOCK(1, NULL);
    568 	s = splvm();
    569 	DOMAIN_FOREACH(dp) {
    570 		for (pr = dp->dom_protosw;
    571 		     pr < dp->dom_protoswNPROTOSW; pr++)
    572 			if (pr->pr_drain)
    573 				(*pr->pr_drain)();
    574 	}
    575 	/* XXX we cannot use psref in H/W interrupt */
    576 	if (!cpu_intr_p()) {
    577 		int bound = curlwp_bind();
    578 		IFNET_READER_FOREACH(ifp) {
    579 			struct psref psref;
    580 
    581 			if_acquire(ifp, &psref);
    582 
    583 			if (ifp->if_drain)
    584 				(*ifp->if_drain)(ifp);
    585 
    586 			if_release(ifp, &psref);
    587 		}
    588 		curlwp_bindx(bound);
    589 	}
    590 	splx(s);
    591 	mbstat.m_drain++;
    592 	KERNEL_UNLOCK_ONE(NULL);
    593 }
    594 
    595 /*
    596  * Space allocation routines.
    597  * These are also available as macros
    598  * for critical paths.
    599  */
    600 struct mbuf *
    601 m_get(int nowait, int type)
    602 {
    603 	struct mbuf *m;
    604 
    605 	KASSERT(type != MT_FREE);
    606 
    607 	m = pool_cache_get(mb_cache,
    608 	    nowait == M_WAIT ? PR_WAITOK|PR_LIMITFAIL : PR_NOWAIT);
    609 	if (m == NULL)
    610 		return NULL;
    611 
    612 	mbstat_type_add(type, 1);
    613 
    614 	mowner_init(m, type);
    615 	m->m_ext_ref = m; /* default */
    616 	m->m_type = type;
    617 	m->m_len = 0;
    618 	m->m_next = NULL;
    619 	m->m_nextpkt = NULL; /* default */
    620 	m->m_data = m->m_dat;
    621 	m->m_flags = 0; /* default */
    622 
    623 	return m;
    624 }
    625 
    626 struct mbuf *
    627 m_gethdr(int nowait, int type)
    628 {
    629 	struct mbuf *m;
    630 
    631 	m = m_get(nowait, type);
    632 	if (m == NULL)
    633 		return NULL;
    634 
    635 	m->m_data = m->m_pktdat;
    636 	m->m_flags = M_PKTHDR;
    637 
    638 	m_reset_rcvif(m);
    639 	m->m_pkthdr.len = 0;
    640 	m->m_pkthdr.csum_flags = 0;
    641 	m->m_pkthdr.csum_data = 0;
    642 	SLIST_INIT(&m->m_pkthdr.tags);
    643 
    644 	m->m_pkthdr.pattr_class = NULL;
    645 	m->m_pkthdr.pattr_af = AF_UNSPEC;
    646 	m->m_pkthdr.pattr_hdr = NULL;
    647 
    648 	return m;
    649 }
    650 
    651 void
    652 m_clget(struct mbuf *m, int nowait)
    653 {
    654 
    655 	MCLGET(m, nowait);
    656 }
    657 
    658 #ifdef MBUFTRACE
    659 /*
    660  * Walk a chain of mbufs, claiming ownership of each mbuf in the chain.
    661  */
    662 void
    663 m_claimm(struct mbuf *m, struct mowner *mo)
    664 {
    665 
    666 	for (; m != NULL; m = m->m_next)
    667 		MCLAIM(m, mo);
    668 }
    669 #endif
    670 
    671 /*
    672  * Mbuffer utility routines.
    673  */
    674 
    675 /*
    676  * Lesser-used path for M_PREPEND:
    677  * allocate new mbuf to prepend to chain,
    678  * copy junk along.
    679  */
    680 struct mbuf *
    681 m_prepend(struct mbuf *m, int len, int how)
    682 {
    683 	struct mbuf *mn;
    684 
    685 	if (__predict_false(len > MHLEN)) {
    686 		panic("%s: len > MHLEN", __func__);
    687 	}
    688 
    689 	KASSERT(len != M_COPYALL);
    690 	mn = m_get(how, m->m_type);
    691 	if (mn == NULL) {
    692 		m_freem(m);
    693 		return NULL;
    694 	}
    695 
    696 	if (m->m_flags & M_PKTHDR) {
    697 		M_MOVE_PKTHDR(mn, m);
    698 	} else {
    699 		MCLAIM(mn, m->m_owner);
    700 	}
    701 	mn->m_next = m;
    702 	m = mn;
    703 
    704 	if (m->m_flags & M_PKTHDR) {
    705 		if (len < MHLEN)
    706 			MH_ALIGN(m, len);
    707 	} else {
    708 		if (len < MLEN)
    709 			M_ALIGN(m, len);
    710 	}
    711 
    712 	m->m_len = len;
    713 	return m;
    714 }
    715 
    716 /*
    717  * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
    718  * continuing for "len" bytes.  If len is M_COPYALL, copy to end of mbuf.
    719  * The wait parameter is a choice of M_WAIT/M_DONTWAIT from caller.
    720  */
    721 struct mbuf *
    722 m_copym(struct mbuf *m, int off0, int len, int wait)
    723 {
    724 
    725 	return m_copym0(m, off0, len, wait, false); /* shallow copy on M_EXT */
    726 }
    727 
    728 struct mbuf *
    729 m_dup(struct mbuf *m, int off0, int len, int wait)
    730 {
    731 
    732 	return m_copym0(m, off0, len, wait, true); /* deep copy */
    733 }
    734 
    735 static inline int
    736 m_copylen(int len, int copylen)
    737 {
    738 	return (len == M_COPYALL) ? copylen : min(len, copylen);
    739 }
    740 
    741 static struct mbuf *
    742 m_copym0(struct mbuf *m, int off0, int len, int wait, bool deep)
    743 {
    744 	struct mbuf *n, **np;
    745 	int off = off0;
    746 	struct mbuf *top;
    747 	int copyhdr = 0;
    748 
    749 	if (off < 0 || (len != M_COPYALL && len < 0))
    750 		panic("m_copym: off %d, len %d", off, len);
    751 	if (off == 0 && m->m_flags & M_PKTHDR)
    752 		copyhdr = 1;
    753 	while (off > 0) {
    754 		if (m == NULL)
    755 			panic("m_copym: m == 0, off %d", off);
    756 		if (off < m->m_len)
    757 			break;
    758 		off -= m->m_len;
    759 		m = m->m_next;
    760 	}
    761 
    762 	np = &top;
    763 	top = NULL;
    764 	while (len == M_COPYALL || len > 0) {
    765 		if (m == NULL) {
    766 			if (len != M_COPYALL)
    767 				panic("m_copym: m == 0, len %d [!COPYALL]",
    768 				    len);
    769 			break;
    770 		}
    771 
    772 		n = m_get(wait, m->m_type);
    773 		*np = n;
    774 		if (n == NULL)
    775 			goto nospace;
    776 		MCLAIM(n, m->m_owner);
    777 
    778 		if (copyhdr) {
    779 			M_COPY_PKTHDR(n, m);
    780 			if (len == M_COPYALL)
    781 				n->m_pkthdr.len -= off0;
    782 			else
    783 				n->m_pkthdr.len = len;
    784 			copyhdr = 0;
    785 		}
    786 		n->m_len = m_copylen(len, m->m_len - off);
    787 
    788 		if (m->m_flags & M_EXT) {
    789 			if (!deep) {
    790 				n->m_data = m->m_data + off;
    791 				MCLADDREFERENCE(m, n);
    792 			} else {
    793 				/*
    794 				 * We don't care if MCLGET fails. n->m_len is
    795 				 * recomputed and handles that.
    796 				 */
    797 				MCLGET(n, wait);
    798 				n->m_len = 0;
    799 				n->m_len = M_TRAILINGSPACE(n);
    800 				n->m_len = m_copylen(len, n->m_len);
    801 				n->m_len = min(n->m_len, m->m_len - off);
    802 				memcpy(mtod(n, void *), mtod(m, char *) + off,
    803 				    (unsigned)n->m_len);
    804 			}
    805 		} else {
    806 			memcpy(mtod(n, void *), mtod(m, char *) + off,
    807 			    (unsigned)n->m_len);
    808 		}
    809 
    810 		if (len != M_COPYALL)
    811 			len -= n->m_len;
    812 		off += n->m_len;
    813 #ifdef DIAGNOSTIC
    814 		if (off > m->m_len)
    815 			panic("m_copym0 overrun %d %d", off, m->m_len);
    816 #endif
    817 		if (off == m->m_len) {
    818 			m = m->m_next;
    819 			off = 0;
    820 		}
    821 		np = &n->m_next;
    822 	}
    823 
    824 	return top;
    825 
    826 nospace:
    827 	m_freem(top);
    828 	return NULL;
    829 }
    830 
    831 /*
    832  * Copy an entire packet, including header (which must be present).
    833  * An optimization of the common case 'm_copym(m, 0, M_COPYALL, how)'.
    834  */
    835 struct mbuf *
    836 m_copypacket(struct mbuf *m, int how)
    837 {
    838 	struct mbuf *top, *n, *o;
    839 
    840 	n = m_get(how, m->m_type);
    841 	top = n;
    842 	if (!n)
    843 		goto nospace;
    844 
    845 	MCLAIM(n, m->m_owner);
    846 	M_COPY_PKTHDR(n, m);
    847 	n->m_len = m->m_len;
    848 	if (m->m_flags & M_EXT) {
    849 		n->m_data = m->m_data;
    850 		MCLADDREFERENCE(m, n);
    851 	} else {
    852 		memcpy(mtod(n, char *), mtod(m, char *), n->m_len);
    853 	}
    854 
    855 	m = m->m_next;
    856 	while (m) {
    857 		o = m_get(how, m->m_type);
    858 		if (!o)
    859 			goto nospace;
    860 
    861 		MCLAIM(o, m->m_owner);
    862 		n->m_next = o;
    863 		n = n->m_next;
    864 
    865 		n->m_len = m->m_len;
    866 		if (m->m_flags & M_EXT) {
    867 			n->m_data = m->m_data;
    868 			MCLADDREFERENCE(m, n);
    869 		} else {
    870 			memcpy(mtod(n, char *), mtod(m, char *), n->m_len);
    871 		}
    872 
    873 		m = m->m_next;
    874 	}
    875 	return top;
    876 
    877 nospace:
    878 	m_freem(top);
    879 	return NULL;
    880 }
    881 
    882 /*
    883  * Copy data from an mbuf chain starting "off" bytes from the beginning,
    884  * continuing for "len" bytes, into the indicated buffer.
    885  */
    886 void
    887 m_copydata(struct mbuf *m, int off, int len, void *vp)
    888 {
    889 	unsigned count;
    890 	void *cp = vp;
    891 	struct mbuf *m0 = m;
    892 	int len0 = len;
    893 	int off0 = off;
    894 	void *vp0 = vp;
    895 
    896 	KASSERT(len != M_COPYALL);
    897 	if (off < 0 || len < 0)
    898 		panic("m_copydata: off %d, len %d", off, len);
    899 	while (off > 0) {
    900 		if (m == NULL)
    901 			panic("m_copydata(%p,%d,%d,%p): m=NULL, off=%d (%d)",
    902 			    m0, len0, off0, vp0, off, off0 - off);
    903 		if (off < m->m_len)
    904 			break;
    905 		off -= m->m_len;
    906 		m = m->m_next;
    907 	}
    908 	while (len > 0) {
    909 		if (m == NULL)
    910 			panic("m_copydata(%p,%d,%d,%p): "
    911 			    "m=NULL, off=%d (%d), len=%d (%d)",
    912 			    m0, len0, off0, vp0,
    913 			    off, off0 - off, len, len0 - len);
    914 		count = min(m->m_len - off, len);
    915 		memcpy(cp, mtod(m, char *) + off, count);
    916 		len -= count;
    917 		cp = (char *)cp + count;
    918 		off = 0;
    919 		m = m->m_next;
    920 	}
    921 }
    922 
    923 /*
    924  * Concatenate mbuf chain n to m.
    925  * n might be copied into m (when n->m_len is small), therefore data portion of
    926  * n could be copied into an mbuf of different mbuf type.
    927  * Any m_pkthdr is not updated.
    928  */
    929 void
    930 m_cat(struct mbuf *m, struct mbuf *n)
    931 {
    932 
    933 	while (m->m_next)
    934 		m = m->m_next;
    935 	while (n) {
    936 		if (M_READONLY(m) || n->m_len > M_TRAILINGSPACE(m)) {
    937 			/* just join the two chains */
    938 			m->m_next = n;
    939 			return;
    940 		}
    941 		/* splat the data from one into the other */
    942 		memcpy(mtod(m, char *) + m->m_len, mtod(n, void *),
    943 		    (u_int)n->m_len);
    944 		m->m_len += n->m_len;
    945 		n = m_free(n);
    946 	}
    947 }
    948 
    949 void
    950 m_adj(struct mbuf *mp, int req_len)
    951 {
    952 	int len = req_len;
    953 	struct mbuf *m;
    954 	int count;
    955 
    956 	if ((m = mp) == NULL)
    957 		return;
    958 	if (len >= 0) {
    959 		/*
    960 		 * Trim from head.
    961 		 */
    962 		while (m != NULL && len > 0) {
    963 			if (m->m_len <= len) {
    964 				len -= m->m_len;
    965 				m->m_len = 0;
    966 				m = m->m_next;
    967 			} else {
    968 				m->m_len -= len;
    969 				m->m_data += len;
    970 				len = 0;
    971 			}
    972 		}
    973 		if (mp->m_flags & M_PKTHDR)
    974 			mp->m_pkthdr.len -= (req_len - len);
    975 	} else {
    976 		/*
    977 		 * Trim from tail.  Scan the mbuf chain,
    978 		 * calculating its length and finding the last mbuf.
    979 		 * If the adjustment only affects this mbuf, then just
    980 		 * adjust and return.  Otherwise, rescan and truncate
    981 		 * after the remaining size.
    982 		 */
    983 		len = -len;
    984 		count = 0;
    985 		for (;;) {
    986 			count += m->m_len;
    987 			if (m->m_next == NULL)
    988 				break;
    989 			m = m->m_next;
    990 		}
    991 		if (m->m_len >= len) {
    992 			m->m_len -= len;
    993 			if (mp->m_flags & M_PKTHDR)
    994 				mp->m_pkthdr.len -= len;
    995 			return;
    996 		}
    997 
    998 		count -= len;
    999 		if (count < 0)
   1000 			count = 0;
   1001 
   1002 		/*
   1003 		 * Correct length for chain is "count".
   1004 		 * Find the mbuf with last data, adjust its length,
   1005 		 * and toss data from remaining mbufs on chain.
   1006 		 */
   1007 		m = mp;
   1008 		if (m->m_flags & M_PKTHDR)
   1009 			m->m_pkthdr.len = count;
   1010 		for (; m; m = m->m_next) {
   1011 			if (m->m_len >= count) {
   1012 				m->m_len = count;
   1013 				break;
   1014 			}
   1015 			count -= m->m_len;
   1016 		}
   1017 		if (m) {
   1018 			while (m->m_next)
   1019 				(m = m->m_next)->m_len = 0;
   1020 		}
   1021 	}
   1022 }
   1023 
   1024 /*
   1025  * m_ensure_contig: rearrange an mbuf chain that given length of bytes
   1026  * would be contiguous and in the data area of an mbuf (therefore, mtod()
   1027  * would work for a structure of given length).
   1028  *
   1029  * => On success, returns true and the resulting mbuf chain; false otherwise.
   1030  * => The mbuf chain may change, but is always preserved valid.
   1031  */
   1032 bool
   1033 m_ensure_contig(struct mbuf **m0, int len)
   1034 {
   1035 	struct mbuf *n = *m0, *m;
   1036 	size_t count, space;
   1037 
   1038 	KASSERT(len != M_COPYALL);
   1039 	/*
   1040 	 * If first mbuf has no cluster, and has room for len bytes
   1041 	 * without shifting current data, pullup into it,
   1042 	 * otherwise allocate a new mbuf to prepend to the chain.
   1043 	 */
   1044 	if ((n->m_flags & M_EXT) == 0 &&
   1045 	    n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
   1046 		if (n->m_len >= len) {
   1047 			return true;
   1048 		}
   1049 		m = n;
   1050 		n = n->m_next;
   1051 		len -= m->m_len;
   1052 	} else {
   1053 		if (len > MHLEN) {
   1054 			return false;
   1055 		}
   1056 		m = m_get(M_DONTWAIT, n->m_type);
   1057 		if (m == NULL) {
   1058 			return false;
   1059 		}
   1060 		MCLAIM(m, n->m_owner);
   1061 		if (n->m_flags & M_PKTHDR) {
   1062 			M_MOVE_PKTHDR(m, n);
   1063 		}
   1064 	}
   1065 	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
   1066 	do {
   1067 		count = MIN(MIN(MAX(len, max_protohdr), space), n->m_len);
   1068 		memcpy(mtod(m, char *) + m->m_len, mtod(n, void *),
   1069 		  (unsigned)count);
   1070 		len -= count;
   1071 		m->m_len += count;
   1072 		n->m_len -= count;
   1073 		space -= count;
   1074 		if (n->m_len)
   1075 			n->m_data += count;
   1076 		else
   1077 			n = m_free(n);
   1078 	} while (len > 0 && n);
   1079 
   1080 	m->m_next = n;
   1081 	*m0 = m;
   1082 
   1083 	return len <= 0;
   1084 }
   1085 
   1086 /*
   1087  * m_pullup: same as m_ensure_contig(), but destroys mbuf chain on error.
   1088  */
   1089 struct mbuf *
   1090 m_pullup(struct mbuf *n, int len)
   1091 {
   1092 	struct mbuf *m = n;
   1093 
   1094 	KASSERT(len != M_COPYALL);
   1095 	if (!m_ensure_contig(&m, len)) {
   1096 		KASSERT(m != NULL);
   1097 		m_freem(m);
   1098 		m = NULL;
   1099 	}
   1100 	return m;
   1101 }
   1102 
   1103 /*
   1104  * Like m_pullup(), except a new mbuf is always allocated, and we allow
   1105  * the amount of empty space before the data in the new mbuf to be specified
   1106  * (in the event that the caller expects to prepend later).
   1107  */
   1108 struct mbuf *
   1109 m_copyup(struct mbuf *n, int len, int dstoff)
   1110 {
   1111 	struct mbuf *m;
   1112 	int count, space;
   1113 
   1114 	KASSERT(len != M_COPYALL);
   1115 	if (len > (MHLEN - dstoff))
   1116 		goto bad;
   1117 	m = m_get(M_DONTWAIT, n->m_type);
   1118 	if (m == NULL)
   1119 		goto bad;
   1120 	MCLAIM(m, n->m_owner);
   1121 	if (n->m_flags & M_PKTHDR) {
   1122 		M_MOVE_PKTHDR(m, n);
   1123 	}
   1124 	m->m_data += dstoff;
   1125 	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
   1126 	do {
   1127 		count = min(min(max(len, max_protohdr), space), n->m_len);
   1128 		memcpy(mtod(m, char *) + m->m_len, mtod(n, void *),
   1129 		    (unsigned)count);
   1130 		len -= count;
   1131 		m->m_len += count;
   1132 		n->m_len -= count;
   1133 		space -= count;
   1134 		if (n->m_len)
   1135 			n->m_data += count;
   1136 		else
   1137 			n = m_free(n);
   1138 	} while (len > 0 && n);
   1139 	if (len > 0) {
   1140 		(void) m_free(m);
   1141 		goto bad;
   1142 	}
   1143 	m->m_next = n;
   1144 	return (m);
   1145  bad:
   1146 	m_freem(n);
   1147 	return (NULL);
   1148 }
   1149 
   1150 /*
   1151  * Partition an mbuf chain in two pieces, returning the tail --
   1152  * all but the first len0 bytes.  In case of failure, it returns NULL and
   1153  * attempts to restore the chain to its original state.
   1154  */
   1155 struct mbuf *
   1156 m_split(struct mbuf *m0, int len0, int wait)
   1157 {
   1158 
   1159 	return m_split0(m0, len0, wait, true);
   1160 }
   1161 
   1162 static struct mbuf *
   1163 m_split0(struct mbuf *m0, int len0, int wait, bool copyhdr)
   1164 {
   1165 	struct mbuf *m, *n;
   1166 	unsigned len = len0, remain, len_save;
   1167 
   1168 	KASSERT(len0 != M_COPYALL);
   1169 	for (m = m0; m && len > m->m_len; m = m->m_next)
   1170 		len -= m->m_len;
   1171 	if (m == NULL)
   1172 		return NULL;
   1173 
   1174 	remain = m->m_len - len;
   1175 	if (copyhdr && (m0->m_flags & M_PKTHDR)) {
   1176 		n = m_gethdr(wait, m0->m_type);
   1177 		if (n == NULL)
   1178 			return NULL;
   1179 
   1180 		MCLAIM(n, m0->m_owner);
   1181 		m_copy_rcvif(n, m0);
   1182 		n->m_pkthdr.len = m0->m_pkthdr.len - len0;
   1183 		len_save = m0->m_pkthdr.len;
   1184 		m0->m_pkthdr.len = len0;
   1185 
   1186 		if (m->m_flags & M_EXT)
   1187 			goto extpacket;
   1188 
   1189 		if (remain > MHLEN) {
   1190 			/* m can't be the lead packet */
   1191 			MH_ALIGN(n, 0);
   1192 			n->m_len = 0;
   1193 			n->m_next = m_split(m, len, wait);
   1194 			if (n->m_next == NULL) {
   1195 				(void)m_free(n);
   1196 				m0->m_pkthdr.len = len_save;
   1197 				return NULL;
   1198 			}
   1199 			return n;
   1200 		} else {
   1201 			MH_ALIGN(n, remain);
   1202 		}
   1203 	} else if (remain == 0) {
   1204 		n = m->m_next;
   1205 		m->m_next = NULL;
   1206 		return n;
   1207 	} else {
   1208 		n = m_get(wait, m->m_type);
   1209 		if (n == NULL)
   1210 			return NULL;
   1211 		MCLAIM(n, m->m_owner);
   1212 		M_ALIGN(n, remain);
   1213 	}
   1214 
   1215 extpacket:
   1216 	if (m->m_flags & M_EXT) {
   1217 		n->m_data = m->m_data + len;
   1218 		MCLADDREFERENCE(m, n);
   1219 	} else {
   1220 		memcpy(mtod(n, void *), mtod(m, char *) + len, remain);
   1221 	}
   1222 
   1223 	n->m_len = remain;
   1224 	m->m_len = len;
   1225 	n->m_next = m->m_next;
   1226 	m->m_next = NULL;
   1227 	return n;
   1228 }
   1229 
   1230 /*
   1231  * Routine to copy from device local memory into mbufs.
   1232  */
   1233 struct mbuf *
   1234 m_devget(char *buf, int totlen, int off0, struct ifnet *ifp,
   1235     void (*copy)(const void *from, void *to, size_t len))
   1236 {
   1237 	struct mbuf *m;
   1238 	struct mbuf *top = NULL, **mp = &top;
   1239 	int off = off0, len;
   1240 	char *cp, *epkt;
   1241 
   1242 	cp = buf;
   1243 	epkt = cp + totlen;
   1244 	if (off) {
   1245 		/*
   1246 		 * If 'off' is non-zero, packet is trailer-encapsulated,
   1247 		 * so we have to skip the type and length fields.
   1248 		 */
   1249 		cp += off + 2 * sizeof(uint16_t);
   1250 		totlen -= 2 * sizeof(uint16_t);
   1251 	}
   1252 
   1253 	m = m_gethdr(M_DONTWAIT, MT_DATA);
   1254 	if (m == NULL)
   1255 		return NULL;
   1256 	m_set_rcvif(m, ifp);
   1257 	m->m_pkthdr.len = totlen;
   1258 	m->m_len = MHLEN;
   1259 
   1260 	while (totlen > 0) {
   1261 		if (top) {
   1262 			m = m_get(M_DONTWAIT, MT_DATA);
   1263 			if (m == NULL) {
   1264 				m_freem(top);
   1265 				return NULL;
   1266 			}
   1267 			m->m_len = MLEN;
   1268 		}
   1269 
   1270 		len = min(totlen, epkt - cp);
   1271 
   1272 		if (len >= MINCLSIZE) {
   1273 			MCLGET(m, M_DONTWAIT);
   1274 			if ((m->m_flags & M_EXT) == 0) {
   1275 				m_free(m);
   1276 				m_freem(top);
   1277 				return NULL;
   1278 			}
   1279 			m->m_len = len = min(len, MCLBYTES);
   1280 		} else {
   1281 			/*
   1282 			 * Place initial small packet/header at end of mbuf.
   1283 			 */
   1284 			if (len < m->m_len) {
   1285 				if (top == 0 && len + max_linkhdr <= m->m_len)
   1286 					m->m_data += max_linkhdr;
   1287 				m->m_len = len;
   1288 			} else
   1289 				len = m->m_len;
   1290 		}
   1291 
   1292 		if (copy)
   1293 			copy(cp, mtod(m, void *), (size_t)len);
   1294 		else
   1295 			memcpy(mtod(m, void *), cp, (size_t)len);
   1296 
   1297 		cp += len;
   1298 		*mp = m;
   1299 		mp = &m->m_next;
   1300 		totlen -= len;
   1301 		if (cp == epkt)
   1302 			cp = buf;
   1303 	}
   1304 
   1305 	return top;
   1306 }
   1307 
   1308 /*
   1309  * Copy data from a buffer back into the indicated mbuf chain,
   1310  * starting "off" bytes from the beginning, extending the mbuf
   1311  * chain if necessary.
   1312  */
   1313 void
   1314 m_copyback(struct mbuf *m0, int off, int len, const void *cp)
   1315 {
   1316 #if defined(DEBUG)
   1317 	struct mbuf *origm = m0;
   1318 	int error;
   1319 #endif
   1320 
   1321 	if (m0 == NULL)
   1322 		return;
   1323 
   1324 #if defined(DEBUG)
   1325 	error =
   1326 #endif
   1327 	m_copyback0(&m0, off, len, cp,
   1328 	    M_COPYBACK0_COPYBACK|M_COPYBACK0_EXTEND, M_DONTWAIT);
   1329 
   1330 #if defined(DEBUG)
   1331 	if (error != 0 || (m0 != NULL && origm != m0))
   1332 		panic("m_copyback");
   1333 #endif
   1334 }
   1335 
   1336 struct mbuf *
   1337 m_copyback_cow(struct mbuf *m0, int off, int len, const void *cp, int how)
   1338 {
   1339 	int error;
   1340 
   1341 	/* don't support chain expansion */
   1342 	KASSERT(len != M_COPYALL);
   1343 	KDASSERT(off + len <= m_length(m0));
   1344 
   1345 	error = m_copyback0(&m0, off, len, cp,
   1346 	    M_COPYBACK0_COPYBACK|M_COPYBACK0_COW, how);
   1347 	if (error) {
   1348 		/*
   1349 		 * no way to recover from partial success.
   1350 		 * just free the chain.
   1351 		 */
   1352 		m_freem(m0);
   1353 		return NULL;
   1354 	}
   1355 	return m0;
   1356 }
   1357 
   1358 /*
   1359  * m_makewritable: ensure the specified range writable.
   1360  */
   1361 int
   1362 m_makewritable(struct mbuf **mp, int off, int len, int how)
   1363 {
   1364 	int error;
   1365 #if defined(DEBUG)
   1366 	int origlen = m_length(*mp);
   1367 #endif
   1368 
   1369 	error = m_copyback0(mp, off, len, NULL,
   1370 	    M_COPYBACK0_PRESERVE|M_COPYBACK0_COW, how);
   1371 
   1372 	if (error)
   1373 		return error;
   1374 
   1375 #if defined(DEBUG)
   1376 	int reslen = 0;
   1377 	for (struct mbuf *n = *mp; n; n = n->m_next)
   1378 		reslen += n->m_len;
   1379 	if (origlen != reslen)
   1380 		panic("m_makewritable: length changed");
   1381 	if (((*mp)->m_flags & M_PKTHDR) != 0 && reslen != (*mp)->m_pkthdr.len)
   1382 		panic("m_makewritable: inconsist");
   1383 #endif
   1384 
   1385 	return 0;
   1386 }
   1387 
   1388 /*
   1389  * Copy the mbuf chain to a new mbuf chain that is as short as possible.
   1390  * Return the new mbuf chain on success, NULL on failure.  On success,
   1391  * free the old mbuf chain.
   1392  */
   1393 struct mbuf *
   1394 m_defrag(struct mbuf *mold, int flags)
   1395 {
   1396 	struct mbuf *m0, *mn, *n;
   1397 	size_t sz = mold->m_pkthdr.len;
   1398 
   1399 	KASSERT((mold->m_flags & M_PKTHDR) != 0);
   1400 
   1401 	m0 = m_gethdr(flags, MT_DATA);
   1402 	if (m0 == NULL)
   1403 		return NULL;
   1404 	M_COPY_PKTHDR(m0, mold);
   1405 	mn = m0;
   1406 
   1407 	do {
   1408 		if (sz > MHLEN) {
   1409 			MCLGET(mn, M_DONTWAIT);
   1410 			if ((mn->m_flags & M_EXT) == 0) {
   1411 				m_freem(m0);
   1412 				return NULL;
   1413 			}
   1414 		}
   1415 
   1416 		mn->m_len = MIN(sz, MCLBYTES);
   1417 
   1418 		m_copydata(mold, mold->m_pkthdr.len - sz, mn->m_len,
   1419 		     mtod(mn, void *));
   1420 
   1421 		sz -= mn->m_len;
   1422 
   1423 		if (sz > 0) {
   1424 			/* need more mbufs */
   1425 			n = m_get(M_NOWAIT, MT_DATA);
   1426 			if (n == NULL) {
   1427 				m_freem(m0);
   1428 				return NULL;
   1429 			}
   1430 
   1431 			mn->m_next = n;
   1432 			mn = n;
   1433 		}
   1434 	} while (sz > 0);
   1435 
   1436 	m_freem(mold);
   1437 
   1438 	return m0;
   1439 }
   1440 
   1441 int
   1442 m_copyback0(struct mbuf **mp0, int off, int len, const void *vp, int flags,
   1443     int how)
   1444 {
   1445 	int mlen;
   1446 	struct mbuf *m, *n;
   1447 	struct mbuf **mp;
   1448 	int totlen = 0;
   1449 	const char *cp = vp;
   1450 
   1451 	KASSERT(mp0 != NULL);
   1452 	KASSERT(*mp0 != NULL);
   1453 	KASSERT((flags & M_COPYBACK0_PRESERVE) == 0 || cp == NULL);
   1454 	KASSERT((flags & M_COPYBACK0_COPYBACK) == 0 || cp != NULL);
   1455 
   1456 	if (len == M_COPYALL)
   1457 		len = m_length(*mp0) - off;
   1458 
   1459 	/*
   1460 	 * we don't bother to update "totlen" in the case of M_COPYBACK0_COW,
   1461 	 * assuming that M_COPYBACK0_EXTEND and M_COPYBACK0_COW are exclusive.
   1462 	 */
   1463 
   1464 	KASSERT((~flags & (M_COPYBACK0_EXTEND|M_COPYBACK0_COW)) != 0);
   1465 
   1466 	mp = mp0;
   1467 	m = *mp;
   1468 	while (off > (mlen = m->m_len)) {
   1469 		off -= mlen;
   1470 		totlen += mlen;
   1471 		if (m->m_next == NULL) {
   1472 			int tspace;
   1473 extend:
   1474 			if ((flags & M_COPYBACK0_EXTEND) == 0)
   1475 				goto out;
   1476 
   1477 			/*
   1478 			 * try to make some space at the end of "m".
   1479 			 */
   1480 
   1481 			mlen = m->m_len;
   1482 			if (off + len >= MINCLSIZE &&
   1483 			    (m->m_flags & M_EXT) == 0 && m->m_len == 0) {
   1484 				MCLGET(m, how);
   1485 			}
   1486 			tspace = M_TRAILINGSPACE(m);
   1487 			if (tspace > 0) {
   1488 				tspace = min(tspace, off + len);
   1489 				KASSERT(tspace > 0);
   1490 				memset(mtod(m, char *) + m->m_len, 0,
   1491 				    min(off, tspace));
   1492 				m->m_len += tspace;
   1493 				off += mlen;
   1494 				totlen -= mlen;
   1495 				continue;
   1496 			}
   1497 
   1498 			/*
   1499 			 * need to allocate an mbuf.
   1500 			 */
   1501 
   1502 			if (off + len >= MINCLSIZE) {
   1503 				n = m_getcl(how, m->m_type, 0);
   1504 			} else {
   1505 				n = m_get(how, m->m_type);
   1506 			}
   1507 			if (n == NULL) {
   1508 				goto out;
   1509 			}
   1510 			n->m_len = min(M_TRAILINGSPACE(n), off + len);
   1511 			memset(mtod(n, char *), 0, min(n->m_len, off));
   1512 			m->m_next = n;
   1513 		}
   1514 		mp = &m->m_next;
   1515 		m = m->m_next;
   1516 	}
   1517 	while (len > 0) {
   1518 		mlen = m->m_len - off;
   1519 		if (mlen != 0 && M_READONLY(m)) {
   1520 			char *datap;
   1521 			int eatlen;
   1522 
   1523 			/*
   1524 			 * this mbuf is read-only.
   1525 			 * allocate a new writable mbuf and try again.
   1526 			 */
   1527 
   1528 #if defined(DIAGNOSTIC)
   1529 			if ((flags & M_COPYBACK0_COW) == 0)
   1530 				panic("m_copyback0: read-only");
   1531 #endif /* defined(DIAGNOSTIC) */
   1532 
   1533 			/*
   1534 			 * if we're going to write into the middle of
   1535 			 * a mbuf, split it first.
   1536 			 */
   1537 			if (off > 0) {
   1538 				n = m_split0(m, off, how, false);
   1539 				if (n == NULL)
   1540 					goto enobufs;
   1541 				m->m_next = n;
   1542 				mp = &m->m_next;
   1543 				m = n;
   1544 				off = 0;
   1545 				continue;
   1546 			}
   1547 
   1548 			/*
   1549 			 * XXX TODO coalesce into the trailingspace of
   1550 			 * the previous mbuf when possible.
   1551 			 */
   1552 
   1553 			/*
   1554 			 * allocate a new mbuf.  copy packet header if needed.
   1555 			 */
   1556 			n = m_get(how, m->m_type);
   1557 			if (n == NULL)
   1558 				goto enobufs;
   1559 			MCLAIM(n, m->m_owner);
   1560 			if (off == 0 && (m->m_flags & M_PKTHDR) != 0) {
   1561 				M_MOVE_PKTHDR(n, m);
   1562 				n->m_len = MHLEN;
   1563 			} else {
   1564 				if (len >= MINCLSIZE)
   1565 					MCLGET(n, M_DONTWAIT);
   1566 				n->m_len =
   1567 				    (n->m_flags & M_EXT) ? MCLBYTES : MLEN;
   1568 			}
   1569 			if (n->m_len > len)
   1570 				n->m_len = len;
   1571 
   1572 			/*
   1573 			 * free the region which has been overwritten.
   1574 			 * copying data from old mbufs if requested.
   1575 			 */
   1576 			if (flags & M_COPYBACK0_PRESERVE)
   1577 				datap = mtod(n, char *);
   1578 			else
   1579 				datap = NULL;
   1580 			eatlen = n->m_len;
   1581 			while (m != NULL && M_READONLY(m) &&
   1582 			    n->m_type == m->m_type && eatlen > 0) {
   1583 				mlen = min(eatlen, m->m_len);
   1584 				if (datap) {
   1585 					m_copydata(m, 0, mlen, datap);
   1586 					datap += mlen;
   1587 				}
   1588 				m->m_data += mlen;
   1589 				m->m_len -= mlen;
   1590 				eatlen -= mlen;
   1591 				if (m->m_len == 0)
   1592 					*mp = m = m_free(m);
   1593 			}
   1594 			if (eatlen > 0)
   1595 				n->m_len -= eatlen;
   1596 			n->m_next = m;
   1597 			*mp = m = n;
   1598 			continue;
   1599 		}
   1600 		mlen = min(mlen, len);
   1601 		if (flags & M_COPYBACK0_COPYBACK) {
   1602 			memcpy(mtod(m, char *) + off, cp, (unsigned)mlen);
   1603 			cp += mlen;
   1604 		}
   1605 		len -= mlen;
   1606 		mlen += off;
   1607 		off = 0;
   1608 		totlen += mlen;
   1609 		if (len == 0)
   1610 			break;
   1611 		if (m->m_next == NULL) {
   1612 			goto extend;
   1613 		}
   1614 		mp = &m->m_next;
   1615 		m = m->m_next;
   1616 	}
   1617 out:	if (((m = *mp0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen)) {
   1618 		KASSERT((flags & M_COPYBACK0_EXTEND) != 0);
   1619 		m->m_pkthdr.len = totlen;
   1620 	}
   1621 
   1622 	return 0;
   1623 
   1624 enobufs:
   1625 	return ENOBUFS;
   1626 }
   1627 
   1628 void
   1629 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
   1630 {
   1631 
   1632 	KASSERT((to->m_flags & M_EXT) == 0);
   1633 	KASSERT((to->m_flags & M_PKTHDR) == 0 || m_tag_first(to) == NULL);
   1634 	KASSERT((from->m_flags & M_PKTHDR) != 0);
   1635 
   1636 	to->m_pkthdr = from->m_pkthdr;
   1637 	to->m_flags = from->m_flags & M_COPYFLAGS;
   1638 	to->m_data = to->m_pktdat;
   1639 
   1640 	from->m_flags &= ~M_PKTHDR;
   1641 }
   1642 
   1643 /*
   1644  * Apply function f to the data in an mbuf chain starting "off" bytes from the
   1645  * beginning, continuing for "len" bytes.
   1646  */
   1647 int
   1648 m_apply(struct mbuf *m, int off, int len,
   1649     int (*f)(void *, void *, unsigned int), void *arg)
   1650 {
   1651 	unsigned int count;
   1652 	int rval;
   1653 
   1654 	KASSERT(len != M_COPYALL);
   1655 	KASSERT(len >= 0);
   1656 	KASSERT(off >= 0);
   1657 
   1658 	while (off > 0) {
   1659 		KASSERT(m != NULL);
   1660 		if (off < m->m_len)
   1661 			break;
   1662 		off -= m->m_len;
   1663 		m = m->m_next;
   1664 	}
   1665 	while (len > 0) {
   1666 		KASSERT(m != NULL);
   1667 		count = min(m->m_len - off, len);
   1668 
   1669 		rval = (*f)(arg, mtod(m, char *) + off, count);
   1670 		if (rval)
   1671 			return rval;
   1672 
   1673 		len -= count;
   1674 		off = 0;
   1675 		m = m->m_next;
   1676 	}
   1677 
   1678 	return 0;
   1679 }
   1680 
   1681 /*
   1682  * Return a pointer to mbuf/offset of location in mbuf chain.
   1683  */
   1684 struct mbuf *
   1685 m_getptr(struct mbuf *m, int loc, int *off)
   1686 {
   1687 
   1688 	while (loc >= 0) {
   1689 		/* Normal end of search */
   1690 		if (m->m_len > loc) {
   1691 			*off = loc;
   1692 			return m;
   1693 		}
   1694 
   1695 		loc -= m->m_len;
   1696 
   1697 		if (m->m_next == NULL) {
   1698 			if (loc == 0) {
   1699 				/* Point at the end of valid data */
   1700 				*off = m->m_len;
   1701 				return m;
   1702 			}
   1703 			return NULL;
   1704 		} else {
   1705 			m = m->m_next;
   1706 		}
   1707 	}
   1708 
   1709 	return NULL;
   1710 }
   1711 
   1712 #if defined(DDB)
   1713 void
   1714 m_print(const struct mbuf *m, const char *modif, void (*pr)(const char *, ...))
   1715 {
   1716 	char ch;
   1717 	bool opt_c = false;
   1718 	char buf[512];
   1719 
   1720 	while ((ch = *(modif++)) != '\0') {
   1721 		switch (ch) {
   1722 		case 'c':
   1723 			opt_c = true;
   1724 			break;
   1725 		}
   1726 	}
   1727 
   1728 nextchain:
   1729 	(*pr)("MBUF %p\n", m);
   1730 	snprintb(buf, sizeof(buf), M_FLAGS_BITS, (u_int)m->m_flags);
   1731 	(*pr)("  data=%p, len=%d, type=%d, flags=%s\n",
   1732 	    m->m_data, m->m_len, m->m_type, buf);
   1733 	(*pr)("  owner=%p, next=%p, nextpkt=%p\n", m->m_owner, m->m_next,
   1734 	    m->m_nextpkt);
   1735 	(*pr)("  leadingspace=%u, trailingspace=%u, readonly=%u\n",
   1736 	    (int)M_LEADINGSPACE(m), (int)M_TRAILINGSPACE(m),
   1737 	    (int)M_READONLY(m));
   1738 	if ((m->m_flags & M_PKTHDR) != 0) {
   1739 		snprintb(buf, sizeof(buf), M_CSUM_BITS, m->m_pkthdr.csum_flags);
   1740 		(*pr)("  pktlen=%d, rcvif=%p, csum_flags=%s, csum_data=0x%"
   1741 		    PRIx32 ", segsz=%u\n",
   1742 		    m->m_pkthdr.len, m_get_rcvif_NOMPSAFE(m),
   1743 		    buf, m->m_pkthdr.csum_data, m->m_pkthdr.segsz);
   1744 	}
   1745 	if ((m->m_flags & M_EXT)) {
   1746 		(*pr)("  ext_refcnt=%u, ext_buf=%p, ext_size=%zd, "
   1747 		    "ext_free=%p, ext_arg=%p\n",
   1748 		    m->m_ext.ext_refcnt,
   1749 		    m->m_ext.ext_buf, m->m_ext.ext_size,
   1750 		    m->m_ext.ext_free, m->m_ext.ext_arg);
   1751 	}
   1752 	if ((~m->m_flags & (M_EXT|M_EXT_PAGES)) == 0) {
   1753 		vaddr_t sva = (vaddr_t)m->m_ext.ext_buf;
   1754 		vaddr_t eva = sva + m->m_ext.ext_size;
   1755 		int n = (round_page(eva) - trunc_page(sva)) >> PAGE_SHIFT;
   1756 		int i;
   1757 
   1758 		(*pr)("  pages:");
   1759 		for (i = 0; i < n; i ++) {
   1760 			(*pr)(" %p", m->m_ext.ext_pgs[i]);
   1761 		}
   1762 		(*pr)("\n");
   1763 	}
   1764 
   1765 	if (opt_c) {
   1766 		m = m->m_next;
   1767 		if (m != NULL) {
   1768 			goto nextchain;
   1769 		}
   1770 	}
   1771 }
   1772 #endif /* defined(DDB) */
   1773 
   1774 void
   1775 mbstat_type_add(int type, int diff)
   1776 {
   1777 	struct mbstat_cpu *mb;
   1778 	int s;
   1779 
   1780 	s = splvm();
   1781 	mb = percpu_getref(mbstat_percpu);
   1782 	mb->m_mtypes[type] += diff;
   1783 	percpu_putref(mbstat_percpu);
   1784 	splx(s);
   1785 }
   1786 
   1787 #if defined(MBUFTRACE)
   1788 void
   1789 mowner_attach(struct mowner *mo)
   1790 {
   1791 
   1792 	KASSERT(mo->mo_counters == NULL);
   1793 	mo->mo_counters = percpu_alloc(sizeof(struct mowner_counter));
   1794 
   1795 	/* XXX lock */
   1796 	LIST_INSERT_HEAD(&mowners, mo, mo_link);
   1797 }
   1798 
   1799 void
   1800 mowner_detach(struct mowner *mo)
   1801 {
   1802 
   1803 	KASSERT(mo->mo_counters != NULL);
   1804 
   1805 	/* XXX lock */
   1806 	LIST_REMOVE(mo, mo_link);
   1807 
   1808 	percpu_free(mo->mo_counters, sizeof(struct mowner_counter));
   1809 	mo->mo_counters = NULL;
   1810 }
   1811 
   1812 void
   1813 mowner_init(struct mbuf *m, int type)
   1814 {
   1815 	struct mowner_counter *mc;
   1816 	struct mowner *mo;
   1817 	int s;
   1818 
   1819 	m->m_owner = mo = &unknown_mowners[type];
   1820 	s = splvm();
   1821 	mc = percpu_getref(mo->mo_counters);
   1822 	mc->mc_counter[MOWNER_COUNTER_CLAIMS]++;
   1823 	percpu_putref(mo->mo_counters);
   1824 	splx(s);
   1825 }
   1826 
   1827 void
   1828 mowner_ref(struct mbuf *m, int flags)
   1829 {
   1830 	struct mowner *mo = m->m_owner;
   1831 	struct mowner_counter *mc;
   1832 	int s;
   1833 
   1834 	s = splvm();
   1835 	mc = percpu_getref(mo->mo_counters);
   1836 	if ((flags & M_EXT) != 0)
   1837 		mc->mc_counter[MOWNER_COUNTER_EXT_CLAIMS]++;
   1838 	if ((flags & M_CLUSTER) != 0)
   1839 		mc->mc_counter[MOWNER_COUNTER_CLUSTER_CLAIMS]++;
   1840 	percpu_putref(mo->mo_counters);
   1841 	splx(s);
   1842 }
   1843 
   1844 void
   1845 mowner_revoke(struct mbuf *m, bool all, int flags)
   1846 {
   1847 	struct mowner *mo = m->m_owner;
   1848 	struct mowner_counter *mc;
   1849 	int s;
   1850 
   1851 	s = splvm();
   1852 	mc = percpu_getref(mo->mo_counters);
   1853 	if ((flags & M_EXT) != 0)
   1854 		mc->mc_counter[MOWNER_COUNTER_EXT_RELEASES]++;
   1855 	if ((flags & M_CLUSTER) != 0)
   1856 		mc->mc_counter[MOWNER_COUNTER_CLUSTER_RELEASES]++;
   1857 	if (all)
   1858 		mc->mc_counter[MOWNER_COUNTER_RELEASES]++;
   1859 	percpu_putref(mo->mo_counters);
   1860 	splx(s);
   1861 	if (all)
   1862 		m->m_owner = &revoked_mowner;
   1863 }
   1864 
   1865 static void
   1866 mowner_claim(struct mbuf *m, struct mowner *mo)
   1867 {
   1868 	struct mowner_counter *mc;
   1869 	int flags = m->m_flags;
   1870 	int s;
   1871 
   1872 	s = splvm();
   1873 	mc = percpu_getref(mo->mo_counters);
   1874 	mc->mc_counter[MOWNER_COUNTER_CLAIMS]++;
   1875 	if ((flags & M_EXT) != 0)
   1876 		mc->mc_counter[MOWNER_COUNTER_EXT_CLAIMS]++;
   1877 	if ((flags & M_CLUSTER) != 0)
   1878 		mc->mc_counter[MOWNER_COUNTER_CLUSTER_CLAIMS]++;
   1879 	percpu_putref(mo->mo_counters);
   1880 	splx(s);
   1881 	m->m_owner = mo;
   1882 }
   1883 
   1884 void
   1885 m_claim(struct mbuf *m, struct mowner *mo)
   1886 {
   1887 
   1888 	if (m->m_owner == mo || mo == NULL)
   1889 		return;
   1890 
   1891 	mowner_revoke(m, true, m->m_flags);
   1892 	mowner_claim(m, mo);
   1893 }
   1894 #endif /* defined(MBUFTRACE) */
   1895 
   1896 #ifdef DIAGNOSTIC
   1897 /*
   1898  * Verify that the mbuf chain is not malformed. Used only for diagnostic.
   1899  * Panics on error.
   1900  */
   1901 void
   1902 m_verify_packet(struct mbuf *m)
   1903 {
   1904 	struct mbuf *n = m;
   1905 	char *low, *high, *dat;
   1906 	int totlen = 0, len;
   1907 
   1908 	if (__predict_false((m->m_flags & M_PKTHDR) == 0)) {
   1909 		panic("%s: mbuf doesn't have M_PKTHDR", __func__);
   1910 	}
   1911 
   1912 	while (n != NULL) {
   1913 		if (__predict_false(n->m_type == MT_FREE)) {
   1914 			panic("%s: mbuf already freed (n = %p)", __func__, n);
   1915 		}
   1916 #if 0
   1917 		/*
   1918 		 * This ought to be a rule of the mbuf API. Unfortunately,
   1919 		 * many places don't respect that rule.
   1920 		 */
   1921 		if (__predict_false((n != m) && (n->m_flags & M_PKTHDR) != 0)) {
   1922 			panic("%s: M_PKTHDR set on secondary mbuf", __func__);
   1923 		}
   1924 #endif
   1925 		if (__predict_false(n->m_nextpkt != NULL)) {
   1926 			panic("%s: m_nextpkt not null (m_nextpkt = %p)",
   1927 			    __func__, n->m_nextpkt);
   1928 		}
   1929 
   1930 		dat = n->m_data;
   1931 		len = n->m_len;
   1932 
   1933 		if (n->m_flags & M_EXT) {
   1934 			low = n->m_ext.ext_buf;
   1935 			high = low + n->m_ext.ext_size;
   1936 		} else if (n->m_flags & M_PKTHDR) {
   1937 			low = n->m_pktdat;
   1938 			high = low + MHLEN;
   1939 		} else {
   1940 			low = n->m_dat;
   1941 			high = low + MLEN;
   1942 		}
   1943 		if (__predict_false(dat + len <= dat)) {
   1944 			panic("%s: incorrect length (len = %d)", __func__, len);
   1945 		}
   1946 		if (__predict_false((dat < low) || (dat + len > high))) {
   1947 			panic("%s: m_data not in packet"
   1948 			    "(dat = %p, len = %d, low = %p, high = %p)",
   1949 			    __func__, dat, len, low, high);
   1950 		}
   1951 
   1952 		totlen += len;
   1953 		n = n->m_next;
   1954 	}
   1955 
   1956 	if (__predict_false(totlen != m->m_pkthdr.len)) {
   1957 		panic("%s: inconsistent mbuf length (%d != %d)", __func__,
   1958 		    totlen, m->m_pkthdr.len);
   1959 	}
   1960 }
   1961 #endif
   1962 
   1963 /*
   1964  * Release a reference to the mbuf external storage.
   1965  *
   1966  * => free the mbuf m itself as well.
   1967  */
   1968 static void
   1969 m_ext_free(struct mbuf *m)
   1970 {
   1971 	const bool embedded = MEXT_ISEMBEDDED(m);
   1972 	bool dofree = true;
   1973 	u_int refcnt;
   1974 
   1975 	KASSERT((m->m_flags & M_EXT) != 0);
   1976 	KASSERT(MEXT_ISEMBEDDED(m->m_ext_ref));
   1977 	KASSERT((m->m_ext_ref->m_flags & M_EXT) != 0);
   1978 	KASSERT((m->m_flags & M_EXT_CLUSTER) ==
   1979 	    (m->m_ext_ref->m_flags & M_EXT_CLUSTER));
   1980 
   1981 	if (__predict_false(m->m_type == MT_FREE)) {
   1982 		panic("mbuf %p already freed", m);
   1983 	}
   1984 
   1985 	if (__predict_true(m->m_ext.ext_refcnt == 1)) {
   1986 		refcnt = m->m_ext.ext_refcnt = 0;
   1987 	} else {
   1988 		refcnt = atomic_dec_uint_nv(&m->m_ext.ext_refcnt);
   1989 	}
   1990 
   1991 	if (refcnt > 0) {
   1992 		if (embedded) {
   1993 			/*
   1994 			 * other mbuf's m_ext_ref still points to us.
   1995 			 */
   1996 			dofree = false;
   1997 		} else {
   1998 			m->m_ext_ref = m;
   1999 		}
   2000 	} else {
   2001 		/*
   2002 		 * dropping the last reference
   2003 		 */
   2004 		if (!embedded) {
   2005 			m->m_ext.ext_refcnt++; /* XXX */
   2006 			m_ext_free(m->m_ext_ref);
   2007 			m->m_ext_ref = m;
   2008 		} else if ((m->m_flags & M_EXT_CLUSTER) != 0) {
   2009 			pool_cache_put_paddr((struct pool_cache *)
   2010 			    m->m_ext.ext_arg,
   2011 			    m->m_ext.ext_buf, m->m_ext.ext_paddr);
   2012 		} else if (m->m_ext.ext_free) {
   2013 			(*m->m_ext.ext_free)(m,
   2014 			    m->m_ext.ext_buf, m->m_ext.ext_size,
   2015 			    m->m_ext.ext_arg);
   2016 			/*
   2017 			 * 'm' is already freed by the ext_free callback.
   2018 			 */
   2019 			dofree = false;
   2020 		} else {
   2021 			free(m->m_ext.ext_buf, m->m_ext.ext_type);
   2022 		}
   2023 	}
   2024 
   2025 	if (dofree) {
   2026 		m->m_type = MT_FREE;
   2027 		m->m_data = NULL;
   2028 		pool_cache_put(mb_cache, m);
   2029 	}
   2030 }
   2031 
   2032 /*
   2033  * Free a single mbuf and associated external storage. Return the
   2034  * successor, if any.
   2035  */
   2036 struct mbuf *
   2037 m_free(struct mbuf *m)
   2038 {
   2039 	struct mbuf *n;
   2040 
   2041 	mowner_revoke(m, 1, m->m_flags);
   2042 	mbstat_type_add(m->m_type, -1);
   2043 
   2044 	if (m->m_flags & M_PKTHDR)
   2045 		m_tag_delete_chain(m, NULL);
   2046 
   2047 	n = m->m_next;
   2048 
   2049 	if (m->m_flags & M_EXT) {
   2050 		m_ext_free(m);
   2051 	} else {
   2052 		if (__predict_false(m->m_type == MT_FREE)) {
   2053 			panic("mbuf %p already freed", m);
   2054 		}
   2055 		m->m_type = MT_FREE;
   2056 		m->m_data = NULL;
   2057 		pool_cache_put(mb_cache, m);
   2058 	}
   2059 
   2060 	return n;
   2061 }
   2062 
   2063 void
   2064 m_freem(struct mbuf *m)
   2065 {
   2066 	if (m == NULL)
   2067 		return;
   2068 	do {
   2069 		m = m_free(m);
   2070 	} while (m);
   2071 }
   2072