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