Home | History | Annotate | Line # | Download | only in kern
uipc_mbuf.c revision 1.64
      1 /*	$NetBSD: uipc_mbuf.c,v 1.64 2003/02/26 06:31:11 matt 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. All advertising materials mentioning features or use of this software
     53  *    must display the following acknowledgement:
     54  *	This product includes software developed by the University of
     55  *	California, Berkeley and its contributors.
     56  * 4. Neither the name of the University nor the names of its contributors
     57  *    may be used to endorse or promote products derived from this software
     58  *    without specific prior written permission.
     59  *
     60  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     61  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     62  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     63  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     64  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     65  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     66  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     67  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     68  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     69  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     70  * SUCH DAMAGE.
     71  *
     72  *	@(#)uipc_mbuf.c	8.4 (Berkeley) 2/14/95
     73  */
     74 
     75 #include <sys/cdefs.h>
     76 __KERNEL_RCSID(0, "$NetBSD: uipc_mbuf.c,v 1.64 2003/02/26 06:31:11 matt Exp $");
     77 
     78 #include <sys/param.h>
     79 #include <sys/systm.h>
     80 #include <sys/proc.h>
     81 #include <sys/malloc.h>
     82 #define MBTYPES
     83 #include <sys/mbuf.h>
     84 #include <sys/kernel.h>
     85 #include <sys/syslog.h>
     86 #include <sys/domain.h>
     87 #include <sys/protosw.h>
     88 #include <sys/pool.h>
     89 #include <sys/socket.h>
     90 #include <sys/sysctl.h>
     91 
     92 #include <net/if.h>
     93 
     94 #include <uvm/uvm_extern.h>
     95 
     96 
     97 struct	pool mbpool;		/* mbuf pool */
     98 struct	pool mclpool;		/* mbuf cluster pool */
     99 
    100 struct pool_cache mbpool_cache;
    101 struct pool_cache mclpool_cache;
    102 
    103 struct mbstat mbstat;
    104 int	max_linkhdr;
    105 int	max_protohdr;
    106 int	max_hdr;
    107 int	max_datalen;
    108 
    109 void	*mclpool_alloc(struct pool *, int);
    110 void	mclpool_release(struct pool *, void *);
    111 
    112 struct pool_allocator mclpool_allocator = {
    113 	mclpool_alloc, mclpool_release, 0,
    114 };
    115 
    116 static struct mbuf *m_copym0 __P((struct mbuf *, int, int, int, int));
    117 
    118 const char mclpool_warnmsg[] =
    119     "WARNING: mclpool limit reached; increase NMBCLUSTERS";
    120 
    121 MALLOC_DEFINE(M_MBUF, "mbuf", "mbuf");
    122 
    123 #ifdef MBUFTRACE
    124 struct mownerhead mowners = LIST_HEAD_INITIALIZER(mowners);
    125 struct mowner unknown_mowners[] = {
    126 	{ "unknown", "free" },
    127 	{ "unknown", "data" },
    128 	{ "unknown", "header" },
    129 	{ "unknown", "soname" },
    130 	{ "unknown", "soopts" },
    131 	{ "unknown", "ftable" },
    132 	{ "unknown", "control" },
    133 	{ "unknown", "oobdata" },
    134 };
    135 struct mowner revoked_mowner = { "revoked", "" };
    136 #endif
    137 
    138 /*
    139  * Initialize the mbuf allcator.
    140  */
    141 void
    142 mbinit(void)
    143 {
    144 	pool_init(&mbpool, msize, 0, 0, 0, "mbpl", NULL);
    145 	pool_init(&mclpool, mclbytes, 0, 0, 0, "mclpl", &mclpool_allocator);
    146 
    147 	pool_set_drain_hook(&mbpool, m_reclaim, NULL);
    148 	pool_set_drain_hook(&mclpool, m_reclaim, NULL);
    149 
    150 	pool_cache_init(&mbpool_cache, &mbpool, NULL, NULL, NULL);
    151 	pool_cache_init(&mclpool_cache, &mclpool, NULL, NULL, NULL);
    152 
    153 	/*
    154 	 * Set the hard limit on the mclpool to the number of
    155 	 * mbuf clusters the kernel is to support.  Log the limit
    156 	 * reached message max once a minute.
    157 	 */
    158 	pool_sethardlimit(&mclpool, nmbclusters, mclpool_warnmsg, 60);
    159 
    160 	/*
    161 	 * Set a low water mark for both mbufs and clusters.  This should
    162 	 * help ensure that they can be allocated in a memory starvation
    163 	 * situation.  This is important for e.g. diskless systems which
    164 	 * must allocate mbufs in order for the pagedaemon to clean pages.
    165 	 */
    166 	pool_setlowat(&mbpool, mblowat);
    167 	pool_setlowat(&mclpool, mcllowat);
    168 
    169 #ifdef MBUFTRACE
    170 	{
    171 		/*
    172 		 * Attach the unknown mowners.
    173 		 */
    174 		int i;
    175 		MOWNER_ATTACH(&revoked_mowner);
    176 		for (i = sizeof(unknown_mowners)/sizeof(unknown_mowners[0]);
    177 		     i-- > 0; )
    178 			MOWNER_ATTACH(&unknown_mowners[i]);
    179 	}
    180 #endif
    181 }
    182 
    183 int
    184 sysctl_dombuf(int *name, u_int namelen, void *oldp, size_t *oldlenp,
    185     void *newp, size_t newlen)
    186 {
    187 	int error, newval;
    188 
    189 	/* All sysctl names at this level are terminal. */
    190 	if (namelen != 1)
    191 		return (ENOTDIR);		/* overloaded */
    192 
    193 	switch (name[0]) {
    194 	case MBUF_MSIZE:
    195 		return (sysctl_rdint(oldp, oldlenp, newp, msize));
    196 	case MBUF_MCLBYTES:
    197 		return (sysctl_rdint(oldp, oldlenp, newp, mclbytes));
    198 	case MBUF_NMBCLUSTERS:
    199 		/*
    200 		 * If we have direct-mapped pool pages, we can adjust this
    201 		 * number on the fly.  If not, we're limited by the size
    202 		 * of mb_map, and cannot change this value.
    203 		 *
    204 		 * Note: we only allow the value to be increased, never
    205 		 * decreased.
    206 		 */
    207 		if (mb_map == NULL) {
    208 			newval = nmbclusters;
    209 			error = sysctl_int(oldp, oldlenp, newp, newlen,
    210 			    &newval);
    211 			if (error != 0)
    212 				return (error);
    213 			if (newp != NULL) {
    214 				if (newval >= nmbclusters) {
    215 					nmbclusters = newval;
    216 					pool_sethardlimit(&mclpool,
    217 					    nmbclusters, mclpool_warnmsg, 60);
    218 				} else
    219 					error = EINVAL;
    220 			}
    221 			return (error);
    222 		} else
    223 			return (sysctl_rdint(oldp, oldlenp, newp, nmbclusters));
    224 	case MBUF_MBLOWAT:
    225 	case MBUF_MCLLOWAT:
    226 		/* New value must be >= 0. */
    227 		newval = (name[0] == MBUF_MBLOWAT) ? mblowat : mcllowat;
    228 		error = sysctl_int(oldp, oldlenp, newp, newlen, &newval);
    229 		if (error != 0)
    230 			return (error);
    231 		if (newp != NULL) {
    232 			if (newval >= 0) {
    233 				if (name[0] == MBUF_MBLOWAT) {
    234 					mblowat = newval;
    235 					pool_setlowat(&mbpool, newval);
    236 				} else {
    237 					mcllowat = newval;
    238 					pool_setlowat(&mclpool, newval);
    239 				}
    240 			} else
    241 				error = EINVAL;
    242 		}
    243 		return (error);
    244 	case MBUF_STATS:
    245 		return (sysctl_rdstruct(oldp, oldlenp, newp,
    246 		    &mbstat, sizeof(mbstat)));
    247 #ifdef MBUFTRACE
    248 	case MBUF_MOWNERS: {
    249 		struct mowner *mo;
    250 		size_t len = 0;
    251 		if (newp != NULL)
    252 			return (EPERM);
    253 		error = 0;
    254 		LIST_FOREACH(mo, &mowners, mo_link) {
    255 			if (oldp != NULL) {
    256 				if (*oldlenp - len < sizeof(*mo)) {
    257 					error = ENOMEM;
    258 					break;
    259 				}
    260 				error = copyout(mo, (caddr_t) oldp + len,
    261 					sizeof(*mo));
    262 				if (error)
    263 					break;
    264 			}
    265 			len += sizeof(*mo);
    266 		}
    267 		*oldlenp = len;
    268 		return (error);
    269 	}
    270 #endif
    271 	default:
    272 		return (EOPNOTSUPP);
    273 	}
    274 	/* NOTREACHED */
    275 }
    276 
    277 void *
    278 mclpool_alloc(struct pool *pp, int flags)
    279 {
    280 	boolean_t waitok = (flags & PR_WAITOK) ? TRUE : FALSE;
    281 
    282 	return ((void *)uvm_km_alloc_poolpage1(mb_map, NULL, waitok));
    283 }
    284 
    285 void
    286 mclpool_release(struct pool *pp, void *v)
    287 {
    288 
    289 	uvm_km_free_poolpage1(mb_map, (vaddr_t)v);
    290 }
    291 
    292 void
    293 m_reclaim(void *arg, int flags)
    294 {
    295 	struct domain *dp;
    296 	struct protosw *pr;
    297 	struct ifnet *ifp;
    298 	int s = splvm();
    299 
    300 	for (dp = domains; dp; dp = dp->dom_next)
    301 		for (pr = dp->dom_protosw;
    302 		     pr < dp->dom_protoswNPROTOSW; pr++)
    303 			if (pr->pr_drain)
    304 				(*pr->pr_drain)();
    305 	for (ifp = TAILQ_FIRST(&ifnet); ifp; ifp = TAILQ_NEXT(ifp, if_list))
    306 		if (ifp->if_drain)
    307 			(*ifp->if_drain)(ifp);
    308 	splx(s);
    309 	mbstat.m_drain++;
    310 }
    311 
    312 /*
    313  * Space allocation routines.
    314  * These are also available as macros
    315  * for critical paths.
    316  */
    317 struct mbuf *
    318 m_get(int nowait, int type)
    319 {
    320 	struct mbuf *m;
    321 
    322 	MGET(m, nowait, type);
    323 	return (m);
    324 }
    325 
    326 struct mbuf *
    327 m_gethdr(int nowait, int type)
    328 {
    329 	struct mbuf *m;
    330 
    331 	MGETHDR(m, nowait, type);
    332 	return (m);
    333 }
    334 
    335 struct mbuf *
    336 m_getclr(int nowait, int type)
    337 {
    338 	struct mbuf *m;
    339 
    340 	MGET(m, nowait, type);
    341 	if (m == 0)
    342 		return (0);
    343 	memset(mtod(m, caddr_t), 0, MLEN);
    344 	return (m);
    345 }
    346 
    347 void
    348 m_clget(struct mbuf *m, int nowait)
    349 {
    350 	MCLGET(m, nowait);
    351 }
    352 
    353 struct mbuf *
    354 m_free(struct mbuf *m)
    355 {
    356 	struct mbuf *n;
    357 
    358 	MFREE(m, n);
    359 	return (n);
    360 }
    361 
    362 void
    363 m_freem(struct mbuf *m)
    364 {
    365 	struct mbuf *n;
    366 
    367 	if (m == NULL)
    368 		return;
    369 	do {
    370 		MFREE(m, n);
    371 		m = n;
    372 	} while (m);
    373 }
    374 
    375 #ifdef MBUFTRACE
    376 void
    377 m_claim(struct mbuf *m, struct mowner *mo)
    378 {
    379 	for (; m != NULL; m = m->m_next)
    380 		MCLAIM(m, mo);
    381 }
    382 #endif
    383 
    384 /*
    385  * Mbuffer utility routines.
    386  */
    387 
    388 /*
    389  * Lesser-used path for M_PREPEND:
    390  * allocate new mbuf to prepend to chain,
    391  * copy junk along.
    392  */
    393 struct mbuf *
    394 m_prepend(struct mbuf *m, int len, int how)
    395 {
    396 	struct mbuf *mn;
    397 
    398 	MGET(mn, how, m->m_type);
    399 	if (mn == (struct mbuf *)NULL) {
    400 		m_freem(m);
    401 		return ((struct mbuf *)NULL);
    402 	}
    403 	if (m->m_flags & M_PKTHDR) {
    404 		M_COPY_PKTHDR(mn, m);
    405 		m->m_flags &= ~M_PKTHDR;
    406 	} else {
    407 		MCLAIM(mn, m->m_owner);
    408 	}
    409 	mn->m_next = m;
    410 	m = mn;
    411 	if (len < MHLEN)
    412 		MH_ALIGN(m, len);
    413 	m->m_len = len;
    414 	return (m);
    415 }
    416 
    417 /*
    418  * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
    419  * continuing for "len" bytes.  If len is M_COPYALL, copy to end of mbuf.
    420  * The wait parameter is a choice of M_WAIT/M_DONTWAIT from caller.
    421  */
    422 int MCFail;
    423 
    424 struct mbuf *
    425 m_copym(struct mbuf *m, int off0, int len, int wait)
    426 {
    427 	return m_copym0(m, off0, len, wait, 0);	/* shallow copy on M_EXT */
    428 }
    429 
    430 struct mbuf *
    431 m_dup(struct mbuf *m, int off0, int len, int wait)
    432 {
    433 	return m_copym0(m, off0, len, wait, 1);	/* deep copy */
    434 }
    435 
    436 static struct mbuf *
    437 m_copym0(struct mbuf *m, int off0, int len, int wait, int deep)
    438 {
    439 	struct mbuf *n, **np;
    440 	int off = off0;
    441 	struct mbuf *top;
    442 	int copyhdr = 0;
    443 
    444 	if (off < 0 || len < 0)
    445 		panic("m_copym: off %d, len %d", off, len);
    446 	if (off == 0 && m->m_flags & M_PKTHDR)
    447 		copyhdr = 1;
    448 	while (off > 0) {
    449 		if (m == 0)
    450 			panic("m_copym: m == 0");
    451 		if (off < m->m_len)
    452 			break;
    453 		off -= m->m_len;
    454 		m = m->m_next;
    455 	}
    456 	np = &top;
    457 	top = 0;
    458 	while (len > 0) {
    459 		if (m == 0) {
    460 			if (len != M_COPYALL)
    461 				panic("m_copym: m == 0 and not COPYALL");
    462 			break;
    463 		}
    464 		MGET(n, wait, m->m_type);
    465 		*np = n;
    466 		if (n == 0)
    467 			goto nospace;
    468 		MCLAIM(n, m->m_owner);
    469 		if (copyhdr) {
    470 			M_COPY_PKTHDR(n, m);
    471 			if (len == M_COPYALL)
    472 				n->m_pkthdr.len -= off0;
    473 			else
    474 				n->m_pkthdr.len = len;
    475 			copyhdr = 0;
    476 		}
    477 		n->m_len = min(len, m->m_len - off);
    478 		if (m->m_flags & M_EXT) {
    479 			if (!deep) {
    480 				n->m_data = m->m_data + off;
    481 				n->m_ext = m->m_ext;
    482 				MCLADDREFERENCE(m, n);
    483 			} else {
    484 				/*
    485 				 * we are unsure about the way m was allocated.
    486 				 * copy into multiple MCLBYTES cluster mbufs.
    487 				 */
    488 				MCLGET(n, wait);
    489 				n->m_len = 0;
    490 				n->m_len = M_TRAILINGSPACE(n);
    491 				n->m_len = min(n->m_len, len);
    492 				n->m_len = min(n->m_len, m->m_len - off);
    493 				memcpy(mtod(n, caddr_t), mtod(m, caddr_t) + off,
    494 				    (unsigned)n->m_len);
    495 			}
    496 		} else
    497 			memcpy(mtod(n, caddr_t), mtod(m, caddr_t)+off,
    498 			    (unsigned)n->m_len);
    499 		if (len != M_COPYALL)
    500 			len -= n->m_len;
    501 		off += n->m_len;
    502 #ifdef DIAGNOSTIC
    503 		if (off > m->m_len)
    504 			panic("m_copym0 overrun");
    505 #endif
    506 		if (off == m->m_len) {
    507 			m = m->m_next;
    508 			off = 0;
    509 		}
    510 		np = &n->m_next;
    511 	}
    512 	if (top == 0)
    513 		MCFail++;
    514 	return (top);
    515 nospace:
    516 	m_freem(top);
    517 	MCFail++;
    518 	return (0);
    519 }
    520 
    521 /*
    522  * Copy an entire packet, including header (which must be present).
    523  * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
    524  */
    525 struct mbuf *
    526 m_copypacket(struct mbuf *m, int how)
    527 {
    528 	struct mbuf *top, *n, *o;
    529 
    530 	MGET(n, how, m->m_type);
    531 	top = n;
    532 	if (!n)
    533 		goto nospace;
    534 
    535 	MCLAIM(n, m->m_owner);
    536 	M_COPY_PKTHDR(n, m);
    537 	n->m_len = m->m_len;
    538 	if (m->m_flags & M_EXT) {
    539 		n->m_data = m->m_data;
    540 		n->m_ext = m->m_ext;
    541 		MCLADDREFERENCE(m, n);
    542 	} else {
    543 		memcpy(mtod(n, char *), mtod(m, char *), n->m_len);
    544 	}
    545 
    546 	m = m->m_next;
    547 	while (m) {
    548 		MGET(o, how, m->m_type);
    549 		if (!o)
    550 			goto nospace;
    551 
    552 		MCLAIM(o, m->m_owner);
    553 		n->m_next = o;
    554 		n = n->m_next;
    555 
    556 		n->m_len = m->m_len;
    557 		if (m->m_flags & M_EXT) {
    558 			n->m_data = m->m_data;
    559 			n->m_ext = m->m_ext;
    560 			MCLADDREFERENCE(m, n);
    561 		} else {
    562 			memcpy(mtod(n, char *), mtod(m, char *), n->m_len);
    563 		}
    564 
    565 		m = m->m_next;
    566 	}
    567 	return top;
    568 nospace:
    569 	m_freem(top);
    570 	MCFail++;
    571 	return 0;
    572 }
    573 
    574 /*
    575  * Copy data from an mbuf chain starting "off" bytes from the beginning,
    576  * continuing for "len" bytes, into the indicated buffer.
    577  */
    578 void
    579 m_copydata(struct mbuf *m, int off, int len, caddr_t cp)
    580 {
    581 	unsigned count;
    582 
    583 	if (off < 0 || len < 0)
    584 		panic("m_copydata");
    585 	while (off > 0) {
    586 		if (m == 0)
    587 			panic("m_copydata");
    588 		if (off < m->m_len)
    589 			break;
    590 		off -= m->m_len;
    591 		m = m->m_next;
    592 	}
    593 	while (len > 0) {
    594 		if (m == 0)
    595 			panic("m_copydata");
    596 		count = min(m->m_len - off, len);
    597 		memcpy(cp, mtod(m, caddr_t) + off, count);
    598 		len -= count;
    599 		cp += count;
    600 		off = 0;
    601 		m = m->m_next;
    602 	}
    603 }
    604 
    605 /*
    606  * Concatenate mbuf chain n to m.
    607  * Both chains must be of the same type (e.g. MT_DATA).
    608  * Any m_pkthdr is not updated.
    609  */
    610 void
    611 m_cat(struct mbuf *m, struct mbuf *n)
    612 {
    613 	while (m->m_next)
    614 		m = m->m_next;
    615 	while (n) {
    616 		if (m->m_flags & M_EXT ||
    617 		    m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
    618 			/* just join the two chains */
    619 			m->m_next = n;
    620 			return;
    621 		}
    622 		/* splat the data from one into the other */
    623 		memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
    624 		    (u_int)n->m_len);
    625 		m->m_len += n->m_len;
    626 		n = m_free(n);
    627 	}
    628 }
    629 
    630 void
    631 m_adj(struct mbuf *mp, int req_len)
    632 {
    633 	int len = req_len;
    634 	struct mbuf *m;
    635 	int count;
    636 
    637 	if ((m = mp) == NULL)
    638 		return;
    639 	if (len >= 0) {
    640 		/*
    641 		 * Trim from head.
    642 		 */
    643 		while (m != NULL && len > 0) {
    644 			if (m->m_len <= len) {
    645 				len -= m->m_len;
    646 				m->m_len = 0;
    647 				m = m->m_next;
    648 			} else {
    649 				m->m_len -= len;
    650 				m->m_data += len;
    651 				len = 0;
    652 			}
    653 		}
    654 		m = mp;
    655 		if (mp->m_flags & M_PKTHDR)
    656 			m->m_pkthdr.len -= (req_len - len);
    657 	} else {
    658 		/*
    659 		 * Trim from tail.  Scan the mbuf chain,
    660 		 * calculating its length and finding the last mbuf.
    661 		 * If the adjustment only affects this mbuf, then just
    662 		 * adjust and return.  Otherwise, rescan and truncate
    663 		 * after the remaining size.
    664 		 */
    665 		len = -len;
    666 		count = 0;
    667 		for (;;) {
    668 			count += m->m_len;
    669 			if (m->m_next == (struct mbuf *)0)
    670 				break;
    671 			m = m->m_next;
    672 		}
    673 		if (m->m_len >= len) {
    674 			m->m_len -= len;
    675 			if (mp->m_flags & M_PKTHDR)
    676 				mp->m_pkthdr.len -= len;
    677 			return;
    678 		}
    679 		count -= len;
    680 		if (count < 0)
    681 			count = 0;
    682 		/*
    683 		 * Correct length for chain is "count".
    684 		 * Find the mbuf with last data, adjust its length,
    685 		 * and toss data from remaining mbufs on chain.
    686 		 */
    687 		m = mp;
    688 		if (m->m_flags & M_PKTHDR)
    689 			m->m_pkthdr.len = count;
    690 		for (; m; m = m->m_next) {
    691 			if (m->m_len >= count) {
    692 				m->m_len = count;
    693 				break;
    694 			}
    695 			count -= m->m_len;
    696 		}
    697 		while (m->m_next)
    698 			(m = m->m_next) ->m_len = 0;
    699 	}
    700 }
    701 
    702 /*
    703  * Rearange an mbuf chain so that len bytes are contiguous
    704  * and in the data area of an mbuf (so that mtod and dtom
    705  * will work for a structure of size len).  Returns the resulting
    706  * mbuf chain on success, frees it and returns null on failure.
    707  * If there is room, it will add up to max_protohdr-len extra bytes to the
    708  * contiguous region in an attempt to avoid being called next time.
    709  */
    710 int MPFail;
    711 
    712 struct mbuf *
    713 m_pullup(struct mbuf *n, int len)
    714 {
    715 	struct mbuf *m;
    716 	int count;
    717 	int space;
    718 
    719 	/*
    720 	 * If first mbuf has no cluster, and has room for len bytes
    721 	 * without shifting current data, pullup into it,
    722 	 * otherwise allocate a new mbuf to prepend to the chain.
    723 	 */
    724 	if ((n->m_flags & M_EXT) == 0 &&
    725 	    n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
    726 		if (n->m_len >= len)
    727 			return (n);
    728 		m = n;
    729 		n = n->m_next;
    730 		len -= m->m_len;
    731 	} else {
    732 		if (len > MHLEN)
    733 			goto bad;
    734 		MGET(m, M_DONTWAIT, n->m_type);
    735 		if (m == 0)
    736 			goto bad;
    737 		MCLAIM(m, n->m_owner);
    738 		m->m_len = 0;
    739 		if (n->m_flags & M_PKTHDR) {
    740 			M_COPY_PKTHDR(m, n);
    741 			n->m_flags &= ~M_PKTHDR;
    742 		}
    743 	}
    744 	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
    745 	do {
    746 		count = min(min(max(len, max_protohdr), space), n->m_len);
    747 		memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
    748 		  (unsigned)count);
    749 		len -= count;
    750 		m->m_len += count;
    751 		n->m_len -= count;
    752 		space -= count;
    753 		if (n->m_len)
    754 			n->m_data += count;
    755 		else
    756 			n = m_free(n);
    757 	} while (len > 0 && n);
    758 	if (len > 0) {
    759 		(void) m_free(m);
    760 		goto bad;
    761 	}
    762 	m->m_next = n;
    763 	return (m);
    764 bad:
    765 	m_freem(n);
    766 	MPFail++;
    767 	return (0);
    768 }
    769 
    770 /*
    771  * Like m_pullup(), except a new mbuf is always allocated, and we allow
    772  * the amount of empty space before the data in the new mbuf to be specified
    773  * (in the event that the caller expects to prepend later).
    774  */
    775 int MSFail;
    776 
    777 struct mbuf *
    778 m_copyup(struct mbuf *n, int len, int dstoff)
    779 {
    780 	struct mbuf *m;
    781 	int count, space;
    782 
    783 	if (len > (MHLEN - dstoff))
    784 		goto bad;
    785 	MGET(m, M_DONTWAIT, n->m_type);
    786 	if (m == NULL)
    787 		goto bad;
    788 	MCLAIM(m, n->m_owner);
    789 	m->m_len = 0;
    790 	if (n->m_flags & M_PKTHDR) {
    791 		M_COPY_PKTHDR(m, n);
    792 		n->m_flags &= ~M_PKTHDR;
    793 	}
    794 	m->m_data += dstoff;
    795 	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
    796 	do {
    797 		count = min(min(max(len, max_protohdr), space), n->m_len);
    798 		memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
    799 		    (unsigned)count);
    800 		len -= count;
    801 		m->m_len += count;
    802 		n->m_len -= count;
    803 		space -= count;
    804 		if (n->m_len)
    805 			n->m_data += count;
    806 		else
    807 			n = m_free(n);
    808 	} while (len > 0 && n);
    809 	if (len > 0) {
    810 		(void) m_free(m);
    811 		goto bad;
    812 	}
    813 	m->m_next = n;
    814 	return (m);
    815  bad:
    816 	m_freem(n);
    817 	MSFail++;
    818 	return (NULL);
    819 }
    820 
    821 /*
    822  * Partition an mbuf chain in two pieces, returning the tail --
    823  * all but the first len0 bytes.  In case of failure, it returns NULL and
    824  * attempts to restore the chain to its original state.
    825  */
    826 struct mbuf *
    827 m_split(struct mbuf *m0, int len0, int wait)
    828 {
    829 	struct mbuf *m, *n;
    830 	unsigned len = len0, remain, len_save;
    831 
    832 	for (m = m0; m && len > m->m_len; m = m->m_next)
    833 		len -= m->m_len;
    834 	if (m == 0)
    835 		return (0);
    836 	remain = m->m_len - len;
    837 	if (m0->m_flags & M_PKTHDR) {
    838 		MGETHDR(n, wait, m0->m_type);
    839 		if (n == 0)
    840 			return (0);
    841 		MCLAIM(m, m0->m_owner);
    842 		n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
    843 		n->m_pkthdr.len = m0->m_pkthdr.len - len0;
    844 		len_save = m0->m_pkthdr.len;
    845 		m0->m_pkthdr.len = len0;
    846 		if (m->m_flags & M_EXT)
    847 			goto extpacket;
    848 		if (remain > MHLEN) {
    849 			/* m can't be the lead packet */
    850 			MH_ALIGN(n, 0);
    851 			n->m_next = m_split(m, len, wait);
    852 			if (n->m_next == 0) {
    853 				(void) m_free(n);
    854 				m0->m_pkthdr.len = len_save;
    855 				return (0);
    856 			} else
    857 				return (n);
    858 		} else
    859 			MH_ALIGN(n, remain);
    860 	} else if (remain == 0) {
    861 		n = m->m_next;
    862 		m->m_next = 0;
    863 		return (n);
    864 	} else {
    865 		MGET(n, wait, m->m_type);
    866 		if (n == 0)
    867 			return (0);
    868 		MCLAIM(n, m->m_owner);
    869 		M_ALIGN(n, remain);
    870 	}
    871 extpacket:
    872 	if (m->m_flags & M_EXT) {
    873 		n->m_ext = m->m_ext;
    874 		MCLADDREFERENCE(m, n);
    875 		n->m_data = m->m_data + len;
    876 	} else {
    877 		memcpy(mtod(n, caddr_t), mtod(m, caddr_t) + len, remain);
    878 	}
    879 	n->m_len = remain;
    880 	m->m_len = len;
    881 	n->m_next = m->m_next;
    882 	m->m_next = 0;
    883 	return (n);
    884 }
    885 /*
    886  * Routine to copy from device local memory into mbufs.
    887  */
    888 struct mbuf *
    889 m_devget(char *buf, int totlen, int off0, struct ifnet *ifp,
    890     void (*copy)(const void *from, void *to, size_t len))
    891 {
    892 	struct mbuf *m;
    893 	struct mbuf *top = 0, **mp = &top;
    894 	int off = off0, len;
    895 	char *cp;
    896 	char *epkt;
    897 
    898 	cp = buf;
    899 	epkt = cp + totlen;
    900 	if (off) {
    901 		/*
    902 		 * If 'off' is non-zero, packet is trailer-encapsulated,
    903 		 * so we have to skip the type and length fields.
    904 		 */
    905 		cp += off + 2 * sizeof(u_int16_t);
    906 		totlen -= 2 * sizeof(u_int16_t);
    907 	}
    908 	MGETHDR(m, M_DONTWAIT, MT_DATA);
    909 	if (m == 0)
    910 		return (0);
    911 	m->m_pkthdr.rcvif = ifp;
    912 	m->m_pkthdr.len = totlen;
    913 	m->m_len = MHLEN;
    914 
    915 	while (totlen > 0) {
    916 		if (top) {
    917 			MGET(m, M_DONTWAIT, MT_DATA);
    918 			if (m == 0) {
    919 				m_freem(top);
    920 				return (0);
    921 			}
    922 			m->m_len = MLEN;
    923 		}
    924 		len = min(totlen, epkt - cp);
    925 		if (len >= MINCLSIZE) {
    926 			MCLGET(m, M_DONTWAIT);
    927 			if ((m->m_flags & M_EXT) == 0) {
    928 				m_free(m);
    929 				m_freem(top);
    930 				return (0);
    931 			}
    932 			m->m_len = len = min(len, MCLBYTES);
    933 		} else {
    934 			/*
    935 			 * Place initial small packet/header at end of mbuf.
    936 			 */
    937 			if (len < m->m_len) {
    938 				if (top == 0 && len + max_linkhdr <= m->m_len)
    939 					m->m_data += max_linkhdr;
    940 				m->m_len = len;
    941 			} else
    942 				len = m->m_len;
    943 		}
    944 		if (copy)
    945 			copy(cp, mtod(m, caddr_t), (size_t)len);
    946 		else
    947 			memcpy(mtod(m, caddr_t), cp, (size_t)len);
    948 		cp += len;
    949 		*mp = m;
    950 		mp = &m->m_next;
    951 		totlen -= len;
    952 		if (cp == epkt)
    953 			cp = buf;
    954 	}
    955 	return (top);
    956 }
    957 
    958 /*
    959  * Copy data from a buffer back into the indicated mbuf chain,
    960  * starting "off" bytes from the beginning, extending the mbuf
    961  * chain if necessary.
    962  */
    963 void
    964 m_copyback(struct mbuf *m0, int off, int len, caddr_t cp)
    965 {
    966 	int mlen;
    967 	struct mbuf *m = m0, *n;
    968 	int totlen = 0;
    969 
    970 	if (m0 == 0)
    971 		return;
    972 	while (off > (mlen = m->m_len)) {
    973 		off -= mlen;
    974 		totlen += mlen;
    975 		if (m->m_next == 0) {
    976 			n = m_getclr(M_DONTWAIT, m->m_type);
    977 			if (n == 0)
    978 				goto out;
    979 			n->m_len = min(MLEN, len + off);
    980 			m->m_next = n;
    981 		}
    982 		m = m->m_next;
    983 	}
    984 	while (len > 0) {
    985 		mlen = min (m->m_len - off, len);
    986 		memcpy(mtod(m, caddr_t) + off, cp, (unsigned)mlen);
    987 		cp += mlen;
    988 		len -= mlen;
    989 		mlen += off;
    990 		off = 0;
    991 		totlen += mlen;
    992 		if (len == 0)
    993 			break;
    994 		if (m->m_next == 0) {
    995 			n = m_get(M_DONTWAIT, m->m_type);
    996 			if (n == 0)
    997 				break;
    998 			n->m_len = min(MLEN, len);
    999 			m->m_next = n;
   1000 		}
   1001 		m = m->m_next;
   1002 	}
   1003 out:	if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
   1004 		m->m_pkthdr.len = totlen;
   1005 }
   1006