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