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