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