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