Home | History | Annotate | Line # | Download | only in kern
uipc_mbuf.c revision 1.100.2.8
      1 /*	$NetBSD: uipc_mbuf.c,v 1.100.2.8 2006/07/06 12:32:31 yamt 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  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *	This product includes software developed by the NetBSD
     22  *	Foundation, Inc. and its contributors.
     23  * 4. Neither the name of The NetBSD Foundation nor the names of its
     24  *    contributors may be used to endorse or promote products derived
     25  *    from this software without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     37  * POSSIBILITY OF SUCH DAMAGE.
     38  */
     39 
     40 /*
     41  * Copyright (c) 1982, 1986, 1988, 1991, 1993
     42  *	The Regents of the University of California.  All rights reserved.
     43  *
     44  * Redistribution and use in source and binary forms, with or without
     45  * modification, are permitted provided that the following conditions
     46  * are met:
     47  * 1. Redistributions of source code must retain the above copyright
     48  *    notice, this list of conditions and the following disclaimer.
     49  * 2. Redistributions in binary form must reproduce the above copyright
     50  *    notice, this list of conditions and the following disclaimer in the
     51  *    documentation and/or other materials provided with the distribution.
     52  * 3. Neither the name of the University nor the names of its contributors
     53  *    may be used to endorse or promote products derived from this software
     54  *    without specific prior written permission.
     55  *
     56  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     57  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     58  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     59  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     60  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     61  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     62  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     63  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     64  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     65  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     66  * SUCH DAMAGE.
     67  *
     68  *	@(#)uipc_mbuf.c	8.4 (Berkeley) 2/14/95
     69  */
     70 
     71 #include <sys/cdefs.h>
     72 __KERNEL_RCSID(0, "$NetBSD: uipc_mbuf.c,v 1.100.2.8 2006/07/06 12:32:31 yamt Exp $");
     73 
     74 #include "opt_mbuftrace.h"
     75 #include "opt_ddb.h"
     76 
     77 #include <sys/param.h>
     78 #include <sys/systm.h>
     79 #include <sys/proc.h>
     80 #include <sys/malloc.h>
     81 #define MBTYPES
     82 #include <sys/mbuf.h>
     83 #include <sys/kernel.h>
     84 #include <sys/syslog.h>
     85 #include <sys/domain.h>
     86 #include <sys/protosw.h>
     87 #include <sys/pool.h>
     88 #include <sys/socket.h>
     89 #include <sys/sysctl.h>
     90 
     91 #include <net/if.h>
     92 
     93 #include <uvm/uvm.h>
     94 
     95 
     96 struct	pool mbpool;		/* mbuf pool */
     97 struct	pool mclpool;		/* mbuf cluster pool */
     98 
     99 struct pool_cache mbpool_cache;
    100 struct pool_cache mclpool_cache;
    101 
    102 struct mbstat mbstat;
    103 int	max_linkhdr;
    104 int	max_protohdr;
    105 int	max_hdr;
    106 int	max_datalen;
    107 
    108 static int mb_ctor(void *, void *, int);
    109 
    110 static void	*mclpool_alloc(struct pool *, int);
    111 static void	mclpool_release(struct pool *, void *);
    112 
    113 static struct pool_allocator mclpool_allocator = {
    114 	mclpool_alloc, mclpool_release, 0,
    115 };
    116 
    117 static struct mbuf *m_copym0(struct mbuf *, int, int, int, int);
    118 static struct mbuf *m_split0(struct mbuf *, int, int, int);
    119 static int m_copyback0(struct mbuf **, int, int, const void *, int, int);
    120 
    121 /* flags for m_copyback0 */
    122 #define	M_COPYBACK0_COPYBACK	0x0001	/* copyback from cp */
    123 #define	M_COPYBACK0_PRESERVE	0x0002	/* preserve original data */
    124 #define	M_COPYBACK0_COW		0x0004	/* do copy-on-write */
    125 #define	M_COPYBACK0_EXTEND	0x0008	/* extend chain */
    126 
    127 static const char mclpool_warnmsg[] =
    128     "WARNING: mclpool limit reached; increase NMBCLUSTERS";
    129 
    130 MALLOC_DEFINE(M_MBUF, "mbuf", "mbuf");
    131 
    132 #ifdef MBUFTRACE
    133 struct mownerhead mowners = LIST_HEAD_INITIALIZER(mowners);
    134 struct mowner unknown_mowners[] = {
    135 	{ "unknown", "free" },
    136 	{ "unknown", "data" },
    137 	{ "unknown", "header" },
    138 	{ "unknown", "soname" },
    139 	{ "unknown", "soopts" },
    140 	{ "unknown", "ftable" },
    141 	{ "unknown", "control" },
    142 	{ "unknown", "oobdata" },
    143 };
    144 struct mowner revoked_mowner = { "revoked", "" };
    145 #endif
    146 
    147 #define	MEXT_LOCK(m)	simple_lock(&(m)->m_ext.ext_lock)
    148 #define	MEXT_UNLOCK(m)	simple_unlock(&(m)->m_ext.ext_lock)
    149 #define	MEXT_ISEMBEDDED(m) ((m)->m_ext_ref == (m))
    150 
    151 static inline void
    152 mcl_inc_reference(struct mbuf *m)
    153 {
    154 	int s;
    155 
    156 	s = splvm();
    157 	MEXT_LOCK(o);
    158 	(o)->m_ext.ext_refcnt++;
    159 	MEXT_UNLOCK(o);
    160 	splx(s);
    161 }
    162 
    163 static inline boolean_t
    164 mcl_dec_and_test_reference(struct mbuf *m)
    165 {
    166 	boolean_t isref;
    167 	int s;
    168 
    169 	s = splvm();
    170 	MEXT_LOCK(m);
    171 	KASSERT(m->m_ext.ext_refcnt > 1);
    172 	isref = MCLISREFERENCED(m);
    173 	m->m_ext.ext_refcnt--;
    174 	MEXT_UNLOCK(m);
    175 	splx(s);
    176 
    177 	return isref;
    178 }
    179 
    180 #define	_MCLADDREFERENCE(o, n)						\
    181 do {									\
    182 	KASSERT(((o)->m_flags & M_EXT) != 0);				\
    183 	KASSERT(((n)->m_flags & M_EXT) == 0);				\
    184 	KASSERT((o)->m_ext.ext_refcnt >= 1);				\
    185 	(n)->m_flags |= ((o)->m_flags & M_EXTCOPYFLAGS);		\
    186 	mcl_inc_reference((o));						\
    187 	(n)->m_ext_ref = (o)->m_ext_ref;				\
    188 	_MOWNERREF((n), (n)->m_flags);					\
    189 	MCLREFDEBUGN((n), __FILE__, __LINE__);				\
    190 } while (/* CONSTCOND */ 0)
    191 
    192 /*
    193  * Initialize the mbuf allocator.
    194  */
    195 void
    196 mbinit(void)
    197 {
    198 
    199 	KASSERT(sizeof(struct _m_ext) <= MHLEN);
    200 	KASSERT(sizeof(struct mbuf) == MSIZE);
    201 
    202 	mclpool_allocator.pa_backingmap = mb_map;
    203 	pool_init(&mbpool, msize, 0, 0, 0, "mbpl", NULL);
    204 	pool_init(&mclpool, mclbytes, 0, 0, 0, "mclpl", &mclpool_allocator);
    205 
    206 	pool_set_drain_hook(&mbpool, m_reclaim, NULL);
    207 	pool_set_drain_hook(&mclpool, m_reclaim, NULL);
    208 
    209 	pool_cache_init(&mbpool_cache, &mbpool, mb_ctor, NULL, NULL);
    210 	pool_cache_init(&mclpool_cache, &mclpool, NULL, NULL, NULL);
    211 
    212 	/*
    213 	 * Set the hard limit on the mclpool to the number of
    214 	 * mbuf clusters the kernel is to support.  Log the limit
    215 	 * reached message max once a minute.
    216 	 */
    217 	pool_sethardlimit(&mclpool, nmbclusters, mclpool_warnmsg, 60);
    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_setlowat(&mbpool, mblowat);
    226 	pool_setlowat(&mclpool, 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 /*
    243  * sysctl helper routine for the kern.mbuf subtree.  nmbclusters may
    244  * or may not be writable, and mblowat and mcllowat need range
    245  * checking and pool tweaking after being reset.
    246  */
    247 static int
    248 sysctl_kern_mbuf(SYSCTLFN_ARGS)
    249 {
    250 	int error, newval;
    251 	struct sysctlnode node;
    252 
    253 	node = *rnode;
    254 	node.sysctl_data = &newval;
    255 	switch (rnode->sysctl_num) {
    256 	case MBUF_NMBCLUSTERS:
    257 		if (mb_map != NULL) {
    258 			node.sysctl_flags &= ~CTLFLAG_READWRITE;
    259 			node.sysctl_flags |= CTLFLAG_READONLY;
    260 		}
    261 		/* FALLTHROUGH */
    262 	case MBUF_MBLOWAT:
    263 	case MBUF_MCLLOWAT:
    264 		newval = *(int*)rnode->sysctl_data;
    265 		break;
    266 	default:
    267 		return (EOPNOTSUPP);
    268 	}
    269 
    270 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    271 	if (error || newp == NULL)
    272 		return (error);
    273 	if (newval < 0)
    274 		return (EINVAL);
    275 
    276 	switch (node.sysctl_num) {
    277 	case MBUF_NMBCLUSTERS:
    278 		if (newval < nmbclusters)
    279 			return (EINVAL);
    280 		nmbclusters = newval;
    281 		pool_sethardlimit(&mclpool, nmbclusters, mclpool_warnmsg, 60);
    282 		break;
    283 	case MBUF_MBLOWAT:
    284 		mblowat = newval;
    285 		pool_setlowat(&mbpool, mblowat);
    286 		break;
    287 	case MBUF_MCLLOWAT:
    288 		mcllowat = newval;
    289 		pool_setlowat(&mclpool, mcllowat);
    290 		break;
    291 	}
    292 
    293 	return (0);
    294 }
    295 
    296 #ifdef MBUFTRACE
    297 static int
    298 sysctl_kern_mbuf_mowners(SYSCTLFN_ARGS)
    299 {
    300 	struct mowner *mo;
    301 	size_t len = 0;
    302 	int error = 0;
    303 
    304 	if (namelen != 0)
    305 		return (EINVAL);
    306 	if (newp != NULL)
    307 		return (EPERM);
    308 
    309 	LIST_FOREACH(mo, &mowners, mo_link) {
    310 		if (oldp != NULL) {
    311 			if (*oldlenp - len < sizeof(*mo)) {
    312 				error = ENOMEM;
    313 				break;
    314 			}
    315 			error = copyout(mo, (caddr_t) oldp + len,
    316 					sizeof(*mo));
    317 			if (error)
    318 				break;
    319 		}
    320 		len += sizeof(*mo);
    321 	}
    322 
    323 	if (error == 0)
    324 		*oldlenp = len;
    325 
    326 	return (error);
    327 }
    328 #endif /* MBUFTRACE */
    329 
    330 SYSCTL_SETUP(sysctl_kern_mbuf_setup, "sysctl kern.mbuf subtree setup")
    331 {
    332 
    333 	sysctl_createv(clog, 0, NULL, NULL,
    334 		       CTLFLAG_PERMANENT,
    335 		       CTLTYPE_NODE, "kern", NULL,
    336 		       NULL, 0, NULL, 0,
    337 		       CTL_KERN, CTL_EOL);
    338 	sysctl_createv(clog, 0, NULL, NULL,
    339 		       CTLFLAG_PERMANENT,
    340 		       CTLTYPE_NODE, "mbuf",
    341 		       SYSCTL_DESCR("mbuf control variables"),
    342 		       NULL, 0, NULL, 0,
    343 		       CTL_KERN, KERN_MBUF, CTL_EOL);
    344 
    345 	sysctl_createv(clog, 0, NULL, NULL,
    346 		       CTLFLAG_PERMANENT|CTLFLAG_IMMEDIATE,
    347 		       CTLTYPE_INT, "msize",
    348 		       SYSCTL_DESCR("mbuf base size"),
    349 		       NULL, msize, NULL, 0,
    350 		       CTL_KERN, KERN_MBUF, MBUF_MSIZE, CTL_EOL);
    351 	sysctl_createv(clog, 0, NULL, NULL,
    352 		       CTLFLAG_PERMANENT|CTLFLAG_IMMEDIATE,
    353 		       CTLTYPE_INT, "mclbytes",
    354 		       SYSCTL_DESCR("mbuf cluster size"),
    355 		       NULL, mclbytes, NULL, 0,
    356 		       CTL_KERN, KERN_MBUF, MBUF_MCLBYTES, CTL_EOL);
    357 	sysctl_createv(clog, 0, NULL, NULL,
    358 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    359 		       CTLTYPE_INT, "nmbclusters",
    360 		       SYSCTL_DESCR("Limit on the number of mbuf clusters"),
    361 		       sysctl_kern_mbuf, 0, &nmbclusters, 0,
    362 		       CTL_KERN, KERN_MBUF, MBUF_NMBCLUSTERS, CTL_EOL);
    363 	sysctl_createv(clog, 0, NULL, NULL,
    364 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    365 		       CTLTYPE_INT, "mblowat",
    366 		       SYSCTL_DESCR("mbuf low water mark"),
    367 		       sysctl_kern_mbuf, 0, &mblowat, 0,
    368 		       CTL_KERN, KERN_MBUF, MBUF_MBLOWAT, CTL_EOL);
    369 	sysctl_createv(clog, 0, NULL, NULL,
    370 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    371 		       CTLTYPE_INT, "mcllowat",
    372 		       SYSCTL_DESCR("mbuf cluster low water mark"),
    373 		       sysctl_kern_mbuf, 0, &mcllowat, 0,
    374 		       CTL_KERN, KERN_MBUF, MBUF_MCLLOWAT, CTL_EOL);
    375 	sysctl_createv(clog, 0, NULL, NULL,
    376 		       CTLFLAG_PERMANENT,
    377 		       CTLTYPE_STRUCT, "stats",
    378 		       SYSCTL_DESCR("mbuf allocation statistics"),
    379 		       NULL, 0, &mbstat, sizeof(mbstat),
    380 		       CTL_KERN, KERN_MBUF, MBUF_STATS, CTL_EOL);
    381 #ifdef MBUFTRACE
    382 	sysctl_createv(clog, 0, NULL, NULL,
    383 		       CTLFLAG_PERMANENT,
    384 		       CTLTYPE_STRUCT, "mowners",
    385 		       SYSCTL_DESCR("Information about mbuf owners"),
    386 		       sysctl_kern_mbuf_mowners, 0, NULL, 0,
    387 		       CTL_KERN, KERN_MBUF, MBUF_MOWNERS, CTL_EOL);
    388 #endif /* MBUFTRACE */
    389 }
    390 
    391 static void *
    392 mclpool_alloc(struct pool *pp, int flags)
    393 {
    394 	boolean_t waitok = (flags & PR_WAITOK) ? TRUE : FALSE;
    395 
    396 	return ((void *)uvm_km_alloc_poolpage(mb_map, waitok));
    397 }
    398 
    399 static void
    400 mclpool_release(struct pool *pp, void *v)
    401 {
    402 
    403 	uvm_km_free_poolpage(mb_map, (vaddr_t)v);
    404 }
    405 
    406 /*ARGSUSED*/
    407 static int
    408 mb_ctor(void *arg, void *object, int flags)
    409 {
    410 	struct mbuf *m = object;
    411 
    412 #ifdef POOL_VTOPHYS
    413 	m->m_paddr = POOL_VTOPHYS(m);
    414 #else
    415 	m->m_paddr = M_PADDR_INVALID;
    416 #endif
    417 	return (0);
    418 }
    419 
    420 void
    421 m_reclaim(void *arg, int flags)
    422 {
    423 	struct domain *dp;
    424 	const struct protosw *pr;
    425 	struct ifnet *ifp;
    426 	int s = splvm();
    427 
    428 	DOMAIN_FOREACH(dp) {
    429 		for (pr = dp->dom_protosw;
    430 		     pr < dp->dom_protoswNPROTOSW; pr++)
    431 			if (pr->pr_drain)
    432 				(*pr->pr_drain)();
    433 	}
    434 	IFNET_FOREACH(ifp) {
    435 		if (ifp->if_drain)
    436 			(*ifp->if_drain)(ifp);
    437 	}
    438 	splx(s);
    439 	mbstat.m_drain++;
    440 }
    441 
    442 /*
    443  * Space allocation routines.
    444  * These are also available as macros
    445  * for critical paths.
    446  */
    447 struct mbuf *
    448 m_get(int nowait, int type)
    449 {
    450 	struct mbuf *m;
    451 
    452 	MGET(m, nowait, type);
    453 	return (m);
    454 }
    455 
    456 struct mbuf *
    457 m_gethdr(int nowait, int type)
    458 {
    459 	struct mbuf *m;
    460 
    461 	MGETHDR(m, nowait, type);
    462 	return (m);
    463 }
    464 
    465 struct mbuf *
    466 m_getclr(int nowait, int type)
    467 {
    468 	struct mbuf *m;
    469 
    470 	MGET(m, nowait, type);
    471 	if (m == 0)
    472 		return (NULL);
    473 	memset(mtod(m, caddr_t), 0, MLEN);
    474 	return (m);
    475 }
    476 
    477 void
    478 m_clget(struct mbuf *m, int nowait)
    479 {
    480 
    481 	MCLGET(m, nowait);
    482 }
    483 
    484 struct mbuf *
    485 m_free(struct mbuf *m)
    486 {
    487 	struct mbuf *n;
    488 
    489 	MFREE(m, n);
    490 	return (n);
    491 }
    492 
    493 void
    494 m_freem(struct mbuf *m)
    495 {
    496 	struct mbuf *n;
    497 
    498 	if (m == NULL)
    499 		return;
    500 	do {
    501 		MFREE(m, n);
    502 		m = n;
    503 	} while (m);
    504 }
    505 
    506 #ifdef MBUFTRACE
    507 /*
    508  * Walk a chain of mbufs, claiming ownership of each mbuf in the chain.
    509  */
    510 void
    511 m_claimm(struct mbuf *m, struct mowner *mo)
    512 {
    513 
    514 	for (; m != NULL; m = m->m_next)
    515 		MCLAIM(m, mo);
    516 }
    517 #endif
    518 
    519 /*
    520  * Mbuffer utility routines.
    521  */
    522 
    523 /*
    524  * Lesser-used path for M_PREPEND:
    525  * allocate new mbuf to prepend to chain,
    526  * copy junk along.
    527  */
    528 struct mbuf *
    529 m_prepend(struct mbuf *m, int len, int how)
    530 {
    531 	struct mbuf *mn;
    532 
    533 	MGET(mn, how, m->m_type);
    534 	if (mn == (struct mbuf *)NULL) {
    535 		m_freem(m);
    536 		return ((struct mbuf *)NULL);
    537 	}
    538 	if (m->m_flags & M_PKTHDR) {
    539 		M_MOVE_PKTHDR(mn, m);
    540 	} else {
    541 		MCLAIM(mn, m->m_owner);
    542 	}
    543 	mn->m_next = m;
    544 	m = mn;
    545 	if (len < MHLEN)
    546 		MH_ALIGN(m, len);
    547 	m->m_len = len;
    548 	return (m);
    549 }
    550 
    551 /*
    552  * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
    553  * continuing for "len" bytes.  If len is M_COPYALL, copy to end of mbuf.
    554  * The wait parameter is a choice of M_WAIT/M_DONTWAIT from caller.
    555  */
    556 int MCFail;
    557 
    558 struct mbuf *
    559 m_copym(struct mbuf *m, int off0, int len, int wait)
    560 {
    561 
    562 	return m_copym0(m, off0, len, wait, 0);	/* shallow copy on M_EXT */
    563 }
    564 
    565 struct mbuf *
    566 m_dup(struct mbuf *m, int off0, int len, int wait)
    567 {
    568 
    569 	return m_copym0(m, off0, len, wait, 1);	/* deep copy */
    570 }
    571 
    572 static struct mbuf *
    573 m_copym0(struct mbuf *m, int off0, int len, int wait, int deep)
    574 {
    575 	struct mbuf *n, **np;
    576 	int off = off0;
    577 	struct mbuf *top;
    578 	int copyhdr = 0;
    579 
    580 	if (off < 0 || len < 0)
    581 		panic("m_copym: off %d, len %d", off, len);
    582 	if (off == 0 && m->m_flags & M_PKTHDR)
    583 		copyhdr = 1;
    584 	while (off > 0) {
    585 		if (m == 0)
    586 			panic("m_copym: m == 0, off %d", off);
    587 		if (off < m->m_len)
    588 			break;
    589 		off -= m->m_len;
    590 		m = m->m_next;
    591 	}
    592 	np = &top;
    593 	top = 0;
    594 	while (len > 0) {
    595 		if (m == 0) {
    596 			if (len != M_COPYALL)
    597 				panic("m_copym: m == 0, len %d [!COPYALL]",
    598 				    len);
    599 			break;
    600 		}
    601 		MGET(n, wait, m->m_type);
    602 		*np = n;
    603 		if (n == 0)
    604 			goto nospace;
    605 		MCLAIM(n, m->m_owner);
    606 		if (copyhdr) {
    607 			M_COPY_PKTHDR(n, m);
    608 			if (len == M_COPYALL)
    609 				n->m_pkthdr.len -= off0;
    610 			else
    611 				n->m_pkthdr.len = len;
    612 			copyhdr = 0;
    613 		}
    614 		n->m_len = min(len, m->m_len - off);
    615 		if (m->m_flags & M_EXT) {
    616 			if (!deep) {
    617 				n->m_data = m->m_data + off;
    618 				MCLADDREFERENCE(m, n);
    619 			} else {
    620 				/*
    621 				 * we are unsure about the way m was allocated.
    622 				 * copy into multiple MCLBYTES cluster mbufs.
    623 				 */
    624 				MCLGET(n, wait);
    625 				n->m_len = 0;
    626 				n->m_len = M_TRAILINGSPACE(n);
    627 				n->m_len = min(n->m_len, len);
    628 				n->m_len = min(n->m_len, m->m_len - off);
    629 				memcpy(mtod(n, caddr_t), mtod(m, caddr_t) + off,
    630 				    (unsigned)n->m_len);
    631 			}
    632 		} else
    633 			memcpy(mtod(n, caddr_t), mtod(m, caddr_t)+off,
    634 			    (unsigned)n->m_len);
    635 		if (len != M_COPYALL)
    636 			len -= n->m_len;
    637 		off += n->m_len;
    638 #ifdef DIAGNOSTIC
    639 		if (off > m->m_len)
    640 			panic("m_copym0 overrun");
    641 #endif
    642 		if (off == m->m_len) {
    643 			m = m->m_next;
    644 			off = 0;
    645 		}
    646 		np = &n->m_next;
    647 	}
    648 	if (top == 0)
    649 		MCFail++;
    650 	return (top);
    651 nospace:
    652 	m_freem(top);
    653 	MCFail++;
    654 	return (NULL);
    655 }
    656 
    657 /*
    658  * Copy an entire packet, including header (which must be present).
    659  * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
    660  */
    661 struct mbuf *
    662 m_copypacket(struct mbuf *m, int how)
    663 {
    664 	struct mbuf *top, *n, *o;
    665 
    666 	MGET(n, how, m->m_type);
    667 	top = n;
    668 	if (!n)
    669 		goto nospace;
    670 
    671 	MCLAIM(n, m->m_owner);
    672 	M_COPY_PKTHDR(n, m);
    673 	n->m_len = m->m_len;
    674 	if (m->m_flags & M_EXT) {
    675 		n->m_data = m->m_data;
    676 		MCLADDREFERENCE(m, n);
    677 	} else {
    678 		memcpy(mtod(n, char *), mtod(m, char *), n->m_len);
    679 	}
    680 
    681 	m = m->m_next;
    682 	while (m) {
    683 		MGET(o, how, m->m_type);
    684 		if (!o)
    685 			goto nospace;
    686 
    687 		MCLAIM(o, m->m_owner);
    688 		n->m_next = o;
    689 		n = n->m_next;
    690 
    691 		n->m_len = m->m_len;
    692 		if (m->m_flags & M_EXT) {
    693 			n->m_data = m->m_data;
    694 			MCLADDREFERENCE(m, n);
    695 		} else {
    696 			memcpy(mtod(n, char *), mtod(m, char *), n->m_len);
    697 		}
    698 
    699 		m = m->m_next;
    700 	}
    701 	return top;
    702 nospace:
    703 	m_freem(top);
    704 	MCFail++;
    705 	return NULL;
    706 }
    707 
    708 /*
    709  * Copy data from an mbuf chain starting "off" bytes from the beginning,
    710  * continuing for "len" bytes, into the indicated buffer.
    711  */
    712 void
    713 m_copydata(struct mbuf *m, int off, int len, void *vp)
    714 {
    715 	unsigned	count;
    716 	caddr_t		cp = vp;
    717 
    718 	if (off < 0 || len < 0)
    719 		panic("m_copydata: off %d, len %d", off, len);
    720 	while (off > 0) {
    721 		if (m == NULL)
    722 			panic("m_copydata: m == NULL, off %d", off);
    723 		if (off < m->m_len)
    724 			break;
    725 		off -= m->m_len;
    726 		m = m->m_next;
    727 	}
    728 	while (len > 0) {
    729 		if (m == NULL)
    730 			panic("m_copydata: m == NULL, len %d", len);
    731 		count = min(m->m_len - off, len);
    732 		memcpy(cp, mtod(m, caddr_t) + off, count);
    733 		len -= count;
    734 		cp += count;
    735 		off = 0;
    736 		m = m->m_next;
    737 	}
    738 }
    739 
    740 /*
    741  * Concatenate mbuf chain n to m.
    742  * n might be copied into m (when n->m_len is small), therefore data portion of
    743  * n could be copied into an mbuf of different mbuf type.
    744  * Any m_pkthdr is not updated.
    745  */
    746 void
    747 m_cat(struct mbuf *m, struct mbuf *n)
    748 {
    749 
    750 	while (m->m_next)
    751 		m = m->m_next;
    752 	while (n) {
    753 		if (M_READONLY(m) || n->m_len > M_TRAILINGSPACE(m)) {
    754 			/* just join the two chains */
    755 			m->m_next = n;
    756 			return;
    757 		}
    758 		/* splat the data from one into the other */
    759 		memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
    760 		    (u_int)n->m_len);
    761 		m->m_len += n->m_len;
    762 		n = m_free(n);
    763 	}
    764 }
    765 
    766 void
    767 m_adj(struct mbuf *mp, int req_len)
    768 {
    769 	int len = req_len;
    770 	struct mbuf *m;
    771 	int count;
    772 
    773 	if ((m = mp) == NULL)
    774 		return;
    775 	if (len >= 0) {
    776 		/*
    777 		 * Trim from head.
    778 		 */
    779 		while (m != NULL && len > 0) {
    780 			if (m->m_len <= len) {
    781 				len -= m->m_len;
    782 				m->m_len = 0;
    783 				m = m->m_next;
    784 			} else {
    785 				m->m_len -= len;
    786 				m->m_data += len;
    787 				len = 0;
    788 			}
    789 		}
    790 		m = mp;
    791 		if (mp->m_flags & M_PKTHDR)
    792 			m->m_pkthdr.len -= (req_len - len);
    793 	} else {
    794 		/*
    795 		 * Trim from tail.  Scan the mbuf chain,
    796 		 * calculating its length and finding the last mbuf.
    797 		 * If the adjustment only affects this mbuf, then just
    798 		 * adjust and return.  Otherwise, rescan and truncate
    799 		 * after the remaining size.
    800 		 */
    801 		len = -len;
    802 		count = 0;
    803 		for (;;) {
    804 			count += m->m_len;
    805 			if (m->m_next == (struct mbuf *)0)
    806 				break;
    807 			m = m->m_next;
    808 		}
    809 		if (m->m_len >= len) {
    810 			m->m_len -= len;
    811 			if (mp->m_flags & M_PKTHDR)
    812 				mp->m_pkthdr.len -= len;
    813 			return;
    814 		}
    815 		count -= len;
    816 		if (count < 0)
    817 			count = 0;
    818 		/*
    819 		 * Correct length for chain is "count".
    820 		 * Find the mbuf with last data, adjust its length,
    821 		 * and toss data from remaining mbufs on chain.
    822 		 */
    823 		m = mp;
    824 		if (m->m_flags & M_PKTHDR)
    825 			m->m_pkthdr.len = count;
    826 		for (; m; m = m->m_next) {
    827 			if (m->m_len >= count) {
    828 				m->m_len = count;
    829 				break;
    830 			}
    831 			count -= m->m_len;
    832 		}
    833 		if (m)
    834 			while (m->m_next)
    835 				(m = m->m_next)->m_len = 0;
    836 	}
    837 }
    838 
    839 /*
    840  * Rearrange an mbuf chain so that len bytes are contiguous
    841  * and in the data area of an mbuf (so that mtod and dtom
    842  * will work for a structure of size len).  Returns the resulting
    843  * mbuf chain on success, frees it and returns null on failure.
    844  * If there is room, it will add up to max_protohdr-len extra bytes to the
    845  * contiguous region in an attempt to avoid being called next time.
    846  */
    847 int MPFail;
    848 
    849 struct mbuf *
    850 m_pullup(struct mbuf *n, int len)
    851 {
    852 	struct mbuf *m;
    853 	int count;
    854 	int space;
    855 
    856 	/*
    857 	 * If first mbuf has no cluster, and has room for len bytes
    858 	 * without shifting current data, pullup into it,
    859 	 * otherwise allocate a new mbuf to prepend to the chain.
    860 	 */
    861 	if ((n->m_flags & M_EXT) == 0 &&
    862 	    n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
    863 		if (n->m_len >= len)
    864 			return (n);
    865 		m = n;
    866 		n = n->m_next;
    867 		len -= m->m_len;
    868 	} else {
    869 		if (len > MHLEN)
    870 			goto bad;
    871 		MGET(m, M_DONTWAIT, n->m_type);
    872 		if (m == 0)
    873 			goto bad;
    874 		MCLAIM(m, n->m_owner);
    875 		m->m_len = 0;
    876 		if (n->m_flags & M_PKTHDR) {
    877 			M_MOVE_PKTHDR(m, n);
    878 		}
    879 	}
    880 	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
    881 	do {
    882 		count = min(min(max(len, max_protohdr), space), n->m_len);
    883 		memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
    884 		  (unsigned)count);
    885 		len -= count;
    886 		m->m_len += count;
    887 		n->m_len -= count;
    888 		space -= count;
    889 		if (n->m_len)
    890 			n->m_data += count;
    891 		else
    892 			n = m_free(n);
    893 	} while (len > 0 && n);
    894 	if (len > 0) {
    895 		(void) m_free(m);
    896 		goto bad;
    897 	}
    898 	m->m_next = n;
    899 	return (m);
    900 bad:
    901 	m_freem(n);
    902 	MPFail++;
    903 	return (NULL);
    904 }
    905 
    906 /*
    907  * Like m_pullup(), except a new mbuf is always allocated, and we allow
    908  * the amount of empty space before the data in the new mbuf to be specified
    909  * (in the event that the caller expects to prepend later).
    910  */
    911 int MSFail;
    912 
    913 struct mbuf *
    914 m_copyup(struct mbuf *n, int len, int dstoff)
    915 {
    916 	struct mbuf *m;
    917 	int count, space;
    918 
    919 	if (len > (MHLEN - dstoff))
    920 		goto bad;
    921 	MGET(m, M_DONTWAIT, n->m_type);
    922 	if (m == NULL)
    923 		goto bad;
    924 	MCLAIM(m, n->m_owner);
    925 	m->m_len = 0;
    926 	if (n->m_flags & M_PKTHDR) {
    927 		M_MOVE_PKTHDR(m, n);
    928 	}
    929 	m->m_data += dstoff;
    930 	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
    931 	do {
    932 		count = min(min(max(len, max_protohdr), space), n->m_len);
    933 		memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
    934 		    (unsigned)count);
    935 		len -= count;
    936 		m->m_len += count;
    937 		n->m_len -= count;
    938 		space -= count;
    939 		if (n->m_len)
    940 			n->m_data += count;
    941 		else
    942 			n = m_free(n);
    943 	} while (len > 0 && n);
    944 	if (len > 0) {
    945 		(void) m_free(m);
    946 		goto bad;
    947 	}
    948 	m->m_next = n;
    949 	return (m);
    950  bad:
    951 	m_freem(n);
    952 	MSFail++;
    953 	return (NULL);
    954 }
    955 
    956 /*
    957  * Partition an mbuf chain in two pieces, returning the tail --
    958  * all but the first len0 bytes.  In case of failure, it returns NULL and
    959  * attempts to restore the chain to its original state.
    960  */
    961 struct mbuf *
    962 m_split(struct mbuf *m0, int len0, int wait)
    963 {
    964 
    965 	return m_split0(m0, len0, wait, 1);
    966 }
    967 
    968 static struct mbuf *
    969 m_split0(struct mbuf *m0, int len0, int wait, int copyhdr)
    970 {
    971 	struct mbuf *m, *n;
    972 	unsigned len = len0, remain, len_save;
    973 
    974 	for (m = m0; m && len > m->m_len; m = m->m_next)
    975 		len -= m->m_len;
    976 	if (m == 0)
    977 		return (NULL);
    978 	remain = m->m_len - len;
    979 	if (copyhdr && (m0->m_flags & M_PKTHDR)) {
    980 		MGETHDR(n, wait, m0->m_type);
    981 		if (n == 0)
    982 			return (NULL);
    983 		MCLAIM(m, m0->m_owner);
    984 		n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
    985 		n->m_pkthdr.len = m0->m_pkthdr.len - len0;
    986 		len_save = m0->m_pkthdr.len;
    987 		m0->m_pkthdr.len = len0;
    988 		if (m->m_flags & M_EXT)
    989 			goto extpacket;
    990 		if (remain > MHLEN) {
    991 			/* m can't be the lead packet */
    992 			MH_ALIGN(n, 0);
    993 			n->m_next = m_split(m, len, wait);
    994 			if (n->m_next == 0) {
    995 				(void) m_free(n);
    996 				m0->m_pkthdr.len = len_save;
    997 				return (NULL);
    998 			} else
    999 				return (n);
   1000 		} else
   1001 			MH_ALIGN(n, remain);
   1002 	} else if (remain == 0) {
   1003 		n = m->m_next;
   1004 		m->m_next = 0;
   1005 		return (n);
   1006 	} else {
   1007 		MGET(n, wait, m->m_type);
   1008 		if (n == 0)
   1009 			return (NULL);
   1010 		MCLAIM(n, m->m_owner);
   1011 		M_ALIGN(n, remain);
   1012 	}
   1013 extpacket:
   1014 	if (m->m_flags & M_EXT) {
   1015 		n->m_data = m->m_data + len;
   1016 		MCLADDREFERENCE(m, n);
   1017 	} else {
   1018 		memcpy(mtod(n, caddr_t), mtod(m, caddr_t) + len, remain);
   1019 	}
   1020 	n->m_len = remain;
   1021 	m->m_len = len;
   1022 	n->m_next = m->m_next;
   1023 	m->m_next = 0;
   1024 	return (n);
   1025 }
   1026 /*
   1027  * Routine to copy from device local memory into mbufs.
   1028  */
   1029 struct mbuf *
   1030 m_devget(char *buf, int totlen, int off0, struct ifnet *ifp,
   1031     void (*copy)(const void *from, void *to, size_t len))
   1032 {
   1033 	struct mbuf *m;
   1034 	struct mbuf *top = 0, **mp = &top;
   1035 	int off = off0, len;
   1036 	char *cp;
   1037 	char *epkt;
   1038 
   1039 	cp = buf;
   1040 	epkt = cp + totlen;
   1041 	if (off) {
   1042 		/*
   1043 		 * If 'off' is non-zero, packet is trailer-encapsulated,
   1044 		 * so we have to skip the type and length fields.
   1045 		 */
   1046 		cp += off + 2 * sizeof(uint16_t);
   1047 		totlen -= 2 * sizeof(uint16_t);
   1048 	}
   1049 	MGETHDR(m, M_DONTWAIT, MT_DATA);
   1050 	if (m == 0)
   1051 		return (NULL);
   1052 	m->m_pkthdr.rcvif = ifp;
   1053 	m->m_pkthdr.len = totlen;
   1054 	m->m_len = MHLEN;
   1055 
   1056 	while (totlen > 0) {
   1057 		if (top) {
   1058 			MGET(m, M_DONTWAIT, MT_DATA);
   1059 			if (m == 0) {
   1060 				m_freem(top);
   1061 				return (NULL);
   1062 			}
   1063 			m->m_len = MLEN;
   1064 		}
   1065 		len = min(totlen, epkt - cp);
   1066 		if (len >= MINCLSIZE) {
   1067 			MCLGET(m, M_DONTWAIT);
   1068 			if ((m->m_flags & M_EXT) == 0) {
   1069 				m_free(m);
   1070 				m_freem(top);
   1071 				return (NULL);
   1072 			}
   1073 			m->m_len = len = min(len, MCLBYTES);
   1074 		} else {
   1075 			/*
   1076 			 * Place initial small packet/header at end of mbuf.
   1077 			 */
   1078 			if (len < m->m_len) {
   1079 				if (top == 0 && len + max_linkhdr <= m->m_len)
   1080 					m->m_data += max_linkhdr;
   1081 				m->m_len = len;
   1082 			} else
   1083 				len = m->m_len;
   1084 		}
   1085 		if (copy)
   1086 			copy(cp, mtod(m, caddr_t), (size_t)len);
   1087 		else
   1088 			memcpy(mtod(m, caddr_t), cp, (size_t)len);
   1089 		cp += len;
   1090 		*mp = m;
   1091 		mp = &m->m_next;
   1092 		totlen -= len;
   1093 		if (cp == epkt)
   1094 			cp = buf;
   1095 	}
   1096 	return (top);
   1097 }
   1098 
   1099 /*
   1100  * Copy data from a buffer back into the indicated mbuf chain,
   1101  * starting "off" bytes from the beginning, extending the mbuf
   1102  * chain if necessary.
   1103  */
   1104 void
   1105 m_copyback(struct mbuf *m0, int off, int len, const void *cp)
   1106 {
   1107 #if defined(DEBUG)
   1108 	struct mbuf *origm = m0;
   1109 	int error;
   1110 #endif /* defined(DEBUG) */
   1111 
   1112 	if (m0 == NULL)
   1113 		return;
   1114 
   1115 #if defined(DEBUG)
   1116 	error =
   1117 #endif /* defined(DEBUG) */
   1118 	m_copyback0(&m0, off, len, cp,
   1119 	    M_COPYBACK0_COPYBACK|M_COPYBACK0_EXTEND, M_DONTWAIT);
   1120 
   1121 #if defined(DEBUG)
   1122 	if (error != 0 || (m0 != NULL && origm != m0))
   1123 		panic("m_copyback");
   1124 #endif /* defined(DEBUG) */
   1125 }
   1126 
   1127 struct mbuf *
   1128 m_copyback_cow(struct mbuf *m0, int off, int len, const void *cp, int how)
   1129 {
   1130 	int error;
   1131 
   1132 	/* don't support chain expansion */
   1133 	KDASSERT(off + len <= m_length(m0));
   1134 
   1135 	error = m_copyback0(&m0, off, len, cp,
   1136 	    M_COPYBACK0_COPYBACK|M_COPYBACK0_COW, how);
   1137 	if (error) {
   1138 		/*
   1139 		 * no way to recover from partial success.
   1140 		 * just free the chain.
   1141 		 */
   1142 		m_freem(m0);
   1143 		return NULL;
   1144 	}
   1145 	return m0;
   1146 }
   1147 
   1148 /*
   1149  * m_makewritable: ensure the specified range writable.
   1150  */
   1151 int
   1152 m_makewritable(struct mbuf **mp, int off, int len, int how)
   1153 {
   1154 	int error;
   1155 #if defined(DEBUG)
   1156 	struct mbuf *n;
   1157 	int origlen, reslen;
   1158 
   1159 	origlen = m_length(*mp);
   1160 #endif /* defined(DEBUG) */
   1161 
   1162 #if 0 /* M_COPYALL is large enough */
   1163 	if (len == M_COPYALL)
   1164 		len = m_length(*mp) - off; /* XXX */
   1165 #endif
   1166 
   1167 	error = m_copyback0(mp, off, len, NULL,
   1168 	    M_COPYBACK0_PRESERVE|M_COPYBACK0_COW, how);
   1169 
   1170 #if defined(DEBUG)
   1171 	reslen = 0;
   1172 	for (n = *mp; n; n = n->m_next)
   1173 		reslen += n->m_len;
   1174 	if (origlen != reslen)
   1175 		panic("m_makewritable: length changed");
   1176 	if (((*mp)->m_flags & M_PKTHDR) != 0 && reslen != (*mp)->m_pkthdr.len)
   1177 		panic("m_makewritable: inconsist");
   1178 #endif /* defined(DEBUG) */
   1179 
   1180 	return error;
   1181 }
   1182 
   1183 int
   1184 m_copyback0(struct mbuf **mp0, int off, int len, const void *vp, int flags,
   1185     int how)
   1186 {
   1187 	int mlen;
   1188 	struct mbuf *m, *n;
   1189 	struct mbuf **mp;
   1190 	int totlen = 0;
   1191 	const char *cp = vp;
   1192 
   1193 	KASSERT(mp0 != NULL);
   1194 	KASSERT(*mp0 != NULL);
   1195 	KASSERT((flags & M_COPYBACK0_PRESERVE) == 0 || cp == NULL);
   1196 	KASSERT((flags & M_COPYBACK0_COPYBACK) == 0 || cp != NULL);
   1197 
   1198 	/*
   1199 	 * we don't bother to update "totlen" in the case of M_COPYBACK0_COW,
   1200 	 * assuming that M_COPYBACK0_EXTEND and M_COPYBACK0_COW are exclusive.
   1201 	 */
   1202 
   1203 	KASSERT((~flags & (M_COPYBACK0_EXTEND|M_COPYBACK0_COW)) != 0);
   1204 
   1205 	mp = mp0;
   1206 	m = *mp;
   1207 	while (off > (mlen = m->m_len)) {
   1208 		off -= mlen;
   1209 		totlen += mlen;
   1210 		if (m->m_next == NULL) {
   1211 			int tspace;
   1212 extend:
   1213 			if ((flags & M_COPYBACK0_EXTEND) == 0)
   1214 				goto out;
   1215 
   1216 			/*
   1217 			 * try to make some space at the end of "m".
   1218 			 */
   1219 
   1220 			mlen = m->m_len;
   1221 			if (off + len >= MINCLSIZE &&
   1222 			    (m->m_flags & M_EXT) == 0 && m->m_len == 0) {
   1223 				MCLGET(m, how);
   1224 			}
   1225 			tspace = M_TRAILINGSPACE(m);
   1226 			if (tspace > 0) {
   1227 				tspace = min(tspace, off + len);
   1228 				KASSERT(tspace > 0);
   1229 				memset(mtod(m, char *) + m->m_len, 0,
   1230 				    min(off, tspace));
   1231 				m->m_len += tspace;
   1232 				off += mlen;
   1233 				totlen -= mlen;
   1234 				continue;
   1235 			}
   1236 
   1237 			/*
   1238 			 * need to allocate an mbuf.
   1239 			 */
   1240 
   1241 			if (off + len >= MINCLSIZE) {
   1242 				n = m_getcl(how, m->m_type, 0);
   1243 			} else {
   1244 				n = m_get(how, m->m_type);
   1245 			}
   1246 			if (n == NULL) {
   1247 				goto out;
   1248 			}
   1249 			n->m_len = 0;
   1250 			n->m_len = min(M_TRAILINGSPACE(n), off + len);
   1251 			memset(mtod(n, char *), 0, min(n->m_len, off));
   1252 			m->m_next = n;
   1253 		}
   1254 		mp = &m->m_next;
   1255 		m = m->m_next;
   1256 	}
   1257 	while (len > 0) {
   1258 		mlen = m->m_len - off;
   1259 		if (mlen != 0 && M_READONLY(m)) {
   1260 			char *datap;
   1261 			int eatlen;
   1262 
   1263 			/*
   1264 			 * this mbuf is read-only.
   1265 			 * allocate a new writable mbuf and try again.
   1266 			 */
   1267 
   1268 #if defined(DIAGNOSTIC)
   1269 			if ((flags & M_COPYBACK0_COW) == 0)
   1270 				panic("m_copyback0: read-only");
   1271 #endif /* defined(DIAGNOSTIC) */
   1272 
   1273 			/*
   1274 			 * if we're going to write into the middle of
   1275 			 * a mbuf, split it first.
   1276 			 */
   1277 			if (off > 0 && len < mlen) {
   1278 				n = m_split0(m, off, how, 0);
   1279 				if (n == NULL)
   1280 					goto enobufs;
   1281 				m->m_next = n;
   1282 				mp = &m->m_next;
   1283 				m = n;
   1284 				off = 0;
   1285 				continue;
   1286 			}
   1287 
   1288 			/*
   1289 			 * XXX TODO coalesce into the trailingspace of
   1290 			 * the previous mbuf when possible.
   1291 			 */
   1292 
   1293 			/*
   1294 			 * allocate a new mbuf.  copy packet header if needed.
   1295 			 */
   1296 			MGET(n, how, m->m_type);
   1297 			if (n == NULL)
   1298 				goto enobufs;
   1299 			MCLAIM(n, m->m_owner);
   1300 			if (off == 0 && (m->m_flags & M_PKTHDR) != 0) {
   1301 				M_MOVE_PKTHDR(n, m);
   1302 				n->m_len = MHLEN;
   1303 			} else {
   1304 				if (len >= MINCLSIZE)
   1305 					MCLGET(n, M_DONTWAIT);
   1306 				n->m_len =
   1307 				    (n->m_flags & M_EXT) ? MCLBYTES : MLEN;
   1308 			}
   1309 			if (n->m_len > len)
   1310 				n->m_len = len;
   1311 
   1312 			/*
   1313 			 * free the region which has been overwritten.
   1314 			 * copying data from old mbufs if requested.
   1315 			 */
   1316 			if (flags & M_COPYBACK0_PRESERVE)
   1317 				datap = mtod(n, char *);
   1318 			else
   1319 				datap = NULL;
   1320 			eatlen = n->m_len;
   1321 			KDASSERT(off == 0 || eatlen >= mlen);
   1322 			if (off > 0) {
   1323 				KDASSERT(len >= mlen);
   1324 				m->m_len = off;
   1325 				m->m_next = n;
   1326 				if (datap) {
   1327 					m_copydata(m, off, mlen, datap);
   1328 					datap += mlen;
   1329 				}
   1330 				eatlen -= mlen;
   1331 				mp = &m->m_next;
   1332 				m = m->m_next;
   1333 			}
   1334 			while (m != NULL && M_READONLY(m) &&
   1335 			    n->m_type == m->m_type && eatlen > 0) {
   1336 				mlen = min(eatlen, m->m_len);
   1337 				if (datap) {
   1338 					m_copydata(m, 0, mlen, datap);
   1339 					datap += mlen;
   1340 				}
   1341 				m->m_data += mlen;
   1342 				m->m_len -= mlen;
   1343 				eatlen -= mlen;
   1344 				if (m->m_len == 0)
   1345 					*mp = m = m_free(m);
   1346 			}
   1347 			if (eatlen > 0)
   1348 				n->m_len -= eatlen;
   1349 			n->m_next = m;
   1350 			*mp = m = n;
   1351 			continue;
   1352 		}
   1353 		mlen = min(mlen, len);
   1354 		if (flags & M_COPYBACK0_COPYBACK) {
   1355 			memcpy(mtod(m, caddr_t) + off, cp, (unsigned)mlen);
   1356 			cp += mlen;
   1357 		}
   1358 		len -= mlen;
   1359 		mlen += off;
   1360 		off = 0;
   1361 		totlen += mlen;
   1362 		if (len == 0)
   1363 			break;
   1364 		if (m->m_next == NULL) {
   1365 			goto extend;
   1366 		}
   1367 		mp = &m->m_next;
   1368 		m = m->m_next;
   1369 	}
   1370 out:	if (((m = *mp0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen)) {
   1371 		KASSERT((flags & M_COPYBACK0_EXTEND) != 0);
   1372 		m->m_pkthdr.len = totlen;
   1373 	}
   1374 
   1375 	return 0;
   1376 
   1377 enobufs:
   1378 	return ENOBUFS;
   1379 }
   1380 
   1381 void
   1382 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
   1383 {
   1384 
   1385 	KASSERT((to->m_flags & M_EXT) == 0);
   1386 	KASSERT((to->m_flags & M_PKTHDR) == 0 || m_tag_first(to) == NULL);
   1387 	KASSERT((from->m_flags & M_PKTHDR) != 0);
   1388 
   1389 	to->m_pkthdr = from->m_pkthdr;
   1390 	to->m_flags = from->m_flags & M_COPYFLAGS;
   1391 	to->m_data = to->m_pktdat;
   1392 
   1393 	from->m_flags &= ~M_PKTHDR;
   1394 }
   1395 
   1396 /*
   1397  * Apply function f to the data in an mbuf chain starting "off" bytes from the
   1398  * beginning, continuing for "len" bytes.
   1399  */
   1400 int
   1401 m_apply(struct mbuf *m, int off, int len,
   1402     int (*f)(void *, caddr_t, unsigned int), void *arg)
   1403 {
   1404 	unsigned int count;
   1405 	int rval;
   1406 
   1407 	KASSERT(len >= 0);
   1408 	KASSERT(off >= 0);
   1409 
   1410 	while (off > 0) {
   1411 		KASSERT(m != NULL);
   1412 		if (off < m->m_len)
   1413 			break;
   1414 		off -= m->m_len;
   1415 		m = m->m_next;
   1416 	}
   1417 	while (len > 0) {
   1418 		KASSERT(m != NULL);
   1419 		count = min(m->m_len - off, len);
   1420 
   1421 		rval = (*f)(arg, mtod(m, caddr_t) + off, count);
   1422 		if (rval)
   1423 			return (rval);
   1424 
   1425 		len -= count;
   1426 		off = 0;
   1427 		m = m->m_next;
   1428 	}
   1429 
   1430 	return (0);
   1431 }
   1432 
   1433 /*
   1434  * Return a pointer to mbuf/offset of location in mbuf chain.
   1435  */
   1436 struct mbuf *
   1437 m_getptr(struct mbuf *m, int loc, int *off)
   1438 {
   1439 
   1440 	while (loc >= 0) {
   1441 		/* Normal end of search */
   1442 		if (m->m_len > loc) {
   1443 	    		*off = loc;
   1444 	    		return (m);
   1445 		} else {
   1446 	    		loc -= m->m_len;
   1447 
   1448 	    		if (m->m_next == NULL) {
   1449 				if (loc == 0) {
   1450  					/* Point at the end of valid data */
   1451 		    			*off = m->m_len;
   1452 		    			return (m);
   1453 				} else
   1454 		  			return (NULL);
   1455 	    		} else
   1456 	      			m = m->m_next;
   1457 		}
   1458     	}
   1459 
   1460 	return (NULL);
   1461 }
   1462 
   1463 /*
   1464  * m_ext_free: release a reference to the mbuf external storage.
   1465  *
   1466  * => free the mbuf m itsself as well.
   1467  * => called at splvm.
   1468  */
   1469 
   1470 void
   1471 m_ext_free(struct mbuf *m)
   1472 {
   1473 	boolean_t embedded = MEXT_ISEMBEDDED(m);
   1474 	boolean_t dofree = TRUE;
   1475 
   1476 	KASSERT((m->m_flags & M_EXT) != 0);
   1477 	KASSERT(MEXT_ISEMBEDDED(m->m_ext_ref));
   1478 	KASSERT((m->m_ext_ref->m_flags & M_EXT) != 0);
   1479 	KASSERT((m->m_flags & M_EXT_CLUSTER) ==
   1480 	    (m->m_ext_ref->m_flags & M_EXT_CLUSTER));
   1481 
   1482 	if (mcl_del_and_test_reference(m)) {
   1483 		if (embedded) {
   1484 			dofree = FALSE;
   1485 		} else {
   1486 			m->m_ext_ref = m;
   1487 		}
   1488 	} else {
   1489 		/*
   1490 		 * dropping the last reference
   1491 		 */
   1492 		if (!embedded) {
   1493 			m_ext_free(m->m_ext_ref);
   1494 			m->m_ext_ref = m;
   1495 		} else if ((m->m_flags & M_EXT_CLUSTER) != 0) {
   1496 			pool_cache_put_paddr((struct pool_cache *)
   1497 			    m->m_ext.ext_arg,
   1498 			    m->m_ext.ext_buf, m->m_ext.ext_paddr);
   1499 		} else if (m->m_ext.ext_free) {
   1500 			(*m->m_ext.ext_free)(m,
   1501 			    m->m_ext.ext_buf, m->m_ext.ext_size,
   1502 			    m->m_ext.ext_arg);
   1503 			/*
   1504 			 * 'm' is already freed by the ext_free callback.
   1505 			 */
   1506 			dofree = FALSE;
   1507 		} else {
   1508 			free(m->m_ext.ext_buf, m->m_ext.ext_type);
   1509 		}
   1510 	}
   1511 	if (dofree) {
   1512 		pool_cache_put(&mbpool_cache, m);
   1513 	}
   1514 }
   1515 
   1516 #if defined(__HAVE_LAZY_MBUF) || defined(DEBUG)
   1517 caddr_t
   1518 m_mapin(struct mbuf *m)
   1519 {
   1520 #if defined(__HAVE_LAZY_MBUF)
   1521 	int s;
   1522 
   1523 	KASSERT((~m->m_flags & (M_EXT|M_EXT_PAGES|M_EXT_LAZY)) == 0);
   1524 
   1525 	s = splvm();
   1526 	MEXT_LOCK(m);
   1527 	if (m->m_ext.ext_flags & M_EXT_LAZY) {
   1528 		vaddr_t buf = (vaddr_t)m->m_ext.ext_buf;
   1529 		vsize_t size = (vsize_t)m->m_ext.ext_size;
   1530 		vaddr_t va, sva, eva;
   1531 		int i;
   1532 
   1533 		sva = trunc_page(buf);
   1534 		eva = round_page(buf + size);
   1535 
   1536 		for (i = 0, va = sva; va < eva; i++, va += PAGE_SIZE) {
   1537 			pmap_kenter_pa(va, VM_PAGE_TO_PHYS(m->m_ext.ext_pgs[i]),
   1538 			    VM_PROT_READ);
   1539 		}
   1540 		pmap_update(pmap_kernel());
   1541 		m->m_ext.ext_flags &= ~M_EXT_LAZY;
   1542 	}
   1543 	MEXT_UNLOCK(m);
   1544 	splx(s);
   1545 
   1546 	m->m_flags &= ~M_EXT_LAZY;
   1547 	return m->m_data;
   1548 #else /* defined(__HAVE_LAZY_MBUF) */
   1549 	panic("m_mapin");
   1550 #endif /* defined(__HAVE_LAZY_MBUF) */
   1551 }
   1552 #endif /* defined(__HAVE_LAZY_MBUF) || defined(DEBUG) */
   1553 
   1554 #if defined(DDB)
   1555 void
   1556 m_print(const struct mbuf *m, const char *modif, void (*pr)(const char *, ...))
   1557 {
   1558 	char ch;
   1559 	boolean_t opt_c = FALSE;
   1560 	char buf[512];
   1561 
   1562 	while ((ch = *(modif++)) != '\0') {
   1563 		switch (ch) {
   1564 		case 'c':
   1565 			opt_c = TRUE;
   1566 			break;
   1567 		}
   1568 	}
   1569 
   1570 nextchain:
   1571 	(*pr)("MBUF %p\n", m);
   1572 	bitmask_snprintf(m->m_flags, M_FLAGS_BITS, buf, sizeof(buf));
   1573 	(*pr)("  data=%p, len=%d, type=%d, flags=0x%s\n",
   1574 	    m->m_data, m->m_len, m->m_type, buf);
   1575 	(*pr)("  owner=%p, next=%p, nextpkt=%p\n", m->m_owner, m->m_next,
   1576 	    m->m_nextpkt);
   1577 	(*pr)("  leadingspace=%u, trailingspace=%u, readonly=%u\n",
   1578 	    (int)M_LEADINGSPACE(m), (int)M_TRAILINGSPACE(m),
   1579 	    (int)M_READONLY(m));
   1580 	if ((m->m_flags & M_PKTHDR) != 0) {
   1581 		bitmask_snprintf(m->m_pkthdr.csum_flags, M_CSUM_BITS, buf,
   1582 		    sizeof(buf));
   1583 		(*pr)("  pktlen=%d, rcvif=%p, csum_flags=0x%s, csum_data=0x%"
   1584 		    PRIx32 ", segsz=%u\n",
   1585 		    m->m_pkthdr.len, m->m_pkthdr.rcvif,
   1586 		    buf, m->m_pkthdr.csum_data, m->m_pkthdr.segsz);
   1587 	}
   1588 	if ((m->m_flags & M_EXT)) {
   1589 		(*pr)("  shared=%u, ext_buf=%p, ext_size=%zd, "
   1590 		    "ext_free=%p, ext_arg=%p\n",
   1591 		    (int)MCLISREFERENCED(m),
   1592 		    m->m_ext.ext_buf, m->m_ext.ext_size,
   1593 		    m->m_ext.ext_free, m->m_ext.ext_arg);
   1594 	}
   1595 	if ((~m->m_flags & (M_EXT|M_EXT_PAGES)) == 0) {
   1596 		vaddr_t sva = (vaddr_t)m->m_ext.ext_buf;
   1597 		vaddr_t eva = sva + m->m_ext.ext_size;
   1598 		int n = (round_page(eva) - trunc_page(sva)) >> PAGE_SHIFT;
   1599 		int i;
   1600 
   1601 		(*pr)("  pages:");
   1602 		for (i = 0; i < n; i ++) {
   1603 			(*pr)(" %p", m->m_ext.ext_pgs[i]);
   1604 		}
   1605 		(*pr)("\n");
   1606 	}
   1607 
   1608 	if (opt_c) {
   1609 		m = m->m_next;
   1610 		if (m != NULL) {
   1611 			goto nextchain;
   1612 		}
   1613 	}
   1614 }
   1615 #endif /* defined(DDB) */
   1616