uipc_mbuf.c revision 149598
1/*-
2 * Copyright (c) 1982, 1986, 1988, 1991, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 *    may be used to endorse or promote products derived from this software
15 *    without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 *	@(#)uipc_mbuf.c	8.2 (Berkeley) 1/4/94
30 */
31
32#include <sys/cdefs.h>
33__FBSDID("$FreeBSD: head/sys/kern/uipc_mbuf.c 149598 2005-08-29 19:45:39Z andre $");
34
35#include "opt_mac.h"
36#include "opt_param.h"
37#include "opt_mbuf_stress_test.h"
38
39#include <sys/param.h>
40#include <sys/systm.h>
41#include <sys/kernel.h>
42#include <sys/limits.h>
43#include <sys/lock.h>
44#include <sys/mac.h>
45#include <sys/malloc.h>
46#include <sys/mbuf.h>
47#include <sys/sysctl.h>
48#include <sys/domain.h>
49#include <sys/protosw.h>
50#include <sys/uio.h>
51
52int	max_linkhdr;
53int	max_protohdr;
54int	max_hdr;
55int	max_datalen;
56#ifdef MBUF_STRESS_TEST
57int	m_defragpackets;
58int	m_defragbytes;
59int	m_defraguseless;
60int	m_defragfailure;
61int	m_defragrandomfailures;
62#endif
63
64/*
65 * sysctl(8) exported objects
66 */
67SYSCTL_DECL(_kern_ipc);
68SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RW,
69	   &max_linkhdr, 0, "");
70SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RW,
71	   &max_protohdr, 0, "");
72SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RW, &max_hdr, 0, "");
73SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RW,
74	   &max_datalen, 0, "");
75#ifdef MBUF_STRESS_TEST
76SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
77	   &m_defragpackets, 0, "");
78SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
79	   &m_defragbytes, 0, "");
80SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
81	   &m_defraguseless, 0, "");
82SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
83	   &m_defragfailure, 0, "");
84SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
85	   &m_defragrandomfailures, 0, "");
86#endif
87
88/*
89 * Malloc-type for external ext_buf ref counts.
90 */
91static MALLOC_DEFINE(M_MBUF, "mbextcnt", "mbuf external ref counts");
92
93/*
94 * Allocate a given length worth of mbufs and/or clusters (whatever fits
95 * best) and return a pointer to the top of the allocated chain.  If an
96 * existing mbuf chain is provided, then we will append the new chain
97 * to the existing one but still return the top of the newly allocated
98 * chain.
99 */
100struct mbuf *
101m_getm(struct mbuf *m, int len, int how, short type)
102{
103	struct mbuf *mb, *top, *cur, *mtail;
104	int num, rem;
105	int i;
106
107	KASSERT(len >= 0, ("m_getm(): len is < 0"));
108
109	/* If m != NULL, we will append to the end of that chain. */
110	if (m != NULL)
111		for (mtail = m; mtail->m_next != NULL; mtail = mtail->m_next);
112	else
113		mtail = NULL;
114
115	/*
116	 * Calculate how many mbufs+clusters ("packets") we need and how much
117	 * leftover there is after that and allocate the first mbuf+cluster
118	 * if required.
119	 */
120	num = len / MCLBYTES;
121	rem = len % MCLBYTES;
122	top = cur = NULL;
123	if (num > 0) {
124		if ((top = cur = m_getcl(how, type, 0)) == NULL)
125			goto failed;
126		top->m_len = 0;
127	}
128	num--;
129
130	for (i = 0; i < num; i++) {
131		mb = m_getcl(how, type, 0);
132		if (mb == NULL)
133			goto failed;
134		mb->m_len = 0;
135		cur = (cur->m_next = mb);
136	}
137	if (rem > 0) {
138		mb = (rem > MINCLSIZE) ?
139		    m_getcl(how, type, 0) : m_get(how, type);
140		if (mb == NULL)
141			goto failed;
142		mb->m_len = 0;
143		if (cur == NULL)
144			top = mb;
145		else
146			cur->m_next = mb;
147	}
148
149	if (mtail != NULL)
150		mtail->m_next = top;
151	return top;
152failed:
153	if (top != NULL)
154		m_freem(top);
155	return NULL;
156}
157
158/*
159 * Free an entire chain of mbufs and associated external buffers, if
160 * applicable.
161 */
162void
163m_freem(struct mbuf *mb)
164{
165
166	while (mb != NULL)
167		mb = m_free(mb);
168}
169
170/*-
171 * Configure a provided mbuf to refer to the provided external storage
172 * buffer and setup a reference count for said buffer.  If the setting
173 * up of the reference count fails, the M_EXT bit will not be set.  If
174 * successfull, the M_EXT bit is set in the mbuf's flags.
175 *
176 * Arguments:
177 *    mb     The existing mbuf to which to attach the provided buffer.
178 *    buf    The address of the provided external storage buffer.
179 *    size   The size of the provided buffer.
180 *    freef  A pointer to a routine that is responsible for freeing the
181 *           provided external storage buffer.
182 *    args   A pointer to an argument structure (of any type) to be passed
183 *           to the provided freef routine (may be NULL).
184 *    flags  Any other flags to be passed to the provided mbuf.
185 *    type   The type that the external storage buffer should be
186 *           labeled with.
187 *
188 * Returns:
189 *    Nothing.
190 */
191void
192m_extadd(struct mbuf *mb, caddr_t buf, u_int size,
193    void (*freef)(void *, void *), void *args, int flags, int type)
194{
195	u_int *ref_cnt = NULL;
196
197	/* XXX Shouldn't be adding EXT_CLUSTER with this API */
198	if (type == EXT_CLUSTER)
199		ref_cnt = (u_int *)uma_find_refcnt(zone_clust,
200		    mb->m_ext.ext_buf);
201	else if (type == EXT_EXTREF)
202		ref_cnt = __DEVOLATILE(u_int *, mb->m_ext.ref_cnt);
203	mb->m_ext.ref_cnt = (ref_cnt == NULL) ?
204	    malloc(sizeof(u_int), M_MBUF, M_NOWAIT) : (u_int *)ref_cnt;
205	if (mb->m_ext.ref_cnt != NULL) {
206		*(mb->m_ext.ref_cnt) = 1;
207		mb->m_flags |= (M_EXT | flags);
208		mb->m_ext.ext_buf = buf;
209		mb->m_data = mb->m_ext.ext_buf;
210		mb->m_ext.ext_size = size;
211		mb->m_ext.ext_free = freef;
212		mb->m_ext.ext_args = args;
213		mb->m_ext.ext_type = type;
214        }
215}
216
217/*
218 * Non-directly-exported function to clean up after mbufs with M_EXT
219 * storage attached to them if the reference count hits 0.
220 */
221void
222mb_free_ext(struct mbuf *m)
223{
224	u_int cnt;
225	int dofree;
226
227	/* Account for lazy ref count assign. */
228	if (m->m_ext.ref_cnt == NULL)
229		dofree = 1;
230	else
231		dofree = 0;
232
233	/*
234	 * This is tricky.  We need to make sure to decrement the
235	 * refcount in a safe way but to also clean up if we're the
236	 * last reference.  This method seems to do it without race.
237	 */
238	while (dofree == 0) {
239		cnt = *(m->m_ext.ref_cnt);
240		if (atomic_cmpset_int(m->m_ext.ref_cnt, cnt, cnt - 1)) {
241			if (cnt == 1)
242				dofree = 1;
243			break;
244		}
245	}
246
247	if (dofree) {
248		/*
249		 * Do the free, should be safe.
250		 */
251		if (m->m_ext.ext_type == EXT_PACKET) {
252			uma_zfree(zone_pack, m);
253			return;
254		} else if (m->m_ext.ext_type == EXT_CLUSTER) {
255			uma_zfree(zone_clust, m->m_ext.ext_buf);
256			m->m_ext.ext_buf = NULL;
257		} else {
258			(*(m->m_ext.ext_free))(m->m_ext.ext_buf,
259			    m->m_ext.ext_args);
260			if (m->m_ext.ext_type != EXT_EXTREF) {
261				if (m->m_ext.ref_cnt != NULL)
262					free(__DEVOLATILE(u_int *,
263					    m->m_ext.ref_cnt), M_MBUF);
264				m->m_ext.ref_cnt = NULL;
265			}
266			m->m_ext.ext_buf = NULL;
267		}
268	}
269	uma_zfree(zone_mbuf, m);
270}
271
272/*
273 * Clean up mbuf (chain) from any tags and packet headers.
274 * If "all" is set then the first mbuf in the chain will be
275 * cleaned too.
276 */
277void
278m_demote(struct mbuf *m0, int all)
279{
280	struct mbuf *m;
281
282	for (m = all ? m0 : m0->m_next; m != NULL; m = m->m_next) {
283		if (m->m_flags & M_PKTHDR) {
284			m_tag_delete_chain(m, NULL);
285			m->m_flags &= ~M_PKTHDR;
286			bzero(&m->m_pkthdr, sizeof(struct pkthdr));
287		}
288		if (m->m_type & MT_HEADER)
289			m->m_type = MT_DATA;
290		if (m != m0 && m->m_nextpkt)
291			m->m_nextpkt = NULL;
292		m->m_flags = m->m_flags & (M_EXT|M_EOR|M_RDONLY|M_FREELIST);
293	}
294}
295
296/*
297 * "Move" mbuf pkthdr from "from" to "to".
298 * "from" must have M_PKTHDR set, and "to" must be empty.
299 */
300void
301m_move_pkthdr(struct mbuf *to, struct mbuf *from)
302{
303
304#if 0
305	/* see below for why these are not enabled */
306	M_ASSERTPKTHDR(to);
307	/* Note: with MAC, this may not be a good assertion. */
308	KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags),
309	    ("m_move_pkthdr: to has tags"));
310#endif
311#ifdef MAC
312	/*
313	 * XXXMAC: It could be this should also occur for non-MAC?
314	 */
315	if (to->m_flags & M_PKTHDR)
316		m_tag_delete_chain(to, NULL);
317#endif
318	to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
319	if ((to->m_flags & M_EXT) == 0)
320		to->m_data = to->m_pktdat;
321	to->m_pkthdr = from->m_pkthdr;		/* especially tags */
322	SLIST_INIT(&from->m_pkthdr.tags);	/* purge tags from src */
323	from->m_flags &= ~M_PKTHDR;
324}
325
326/*
327 * Duplicate "from"'s mbuf pkthdr in "to".
328 * "from" must have M_PKTHDR set, and "to" must be empty.
329 * In particular, this does a deep copy of the packet tags.
330 */
331int
332m_dup_pkthdr(struct mbuf *to, struct mbuf *from, int how)
333{
334
335#if 0
336	/*
337	 * The mbuf allocator only initializes the pkthdr
338	 * when the mbuf is allocated with MGETHDR. Many users
339	 * (e.g. m_copy*, m_prepend) use MGET and then
340	 * smash the pkthdr as needed causing these
341	 * assertions to trip.  For now just disable them.
342	 */
343	M_ASSERTPKTHDR(to);
344	/* Note: with MAC, this may not be a good assertion. */
345	KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags), ("m_dup_pkthdr: to has tags"));
346#endif
347	MBUF_CHECKSLEEP(how);
348#ifdef MAC
349	if (to->m_flags & M_PKTHDR)
350		m_tag_delete_chain(to, NULL);
351#endif
352	to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
353	if ((to->m_flags & M_EXT) == 0)
354		to->m_data = to->m_pktdat;
355	to->m_pkthdr = from->m_pkthdr;
356	SLIST_INIT(&to->m_pkthdr.tags);
357	return (m_tag_copy_chain(to, from, MBTOM(how)));
358}
359
360/*
361 * Lesser-used path for M_PREPEND:
362 * allocate new mbuf to prepend to chain,
363 * copy junk along.
364 */
365struct mbuf *
366m_prepend(struct mbuf *m, int len, int how)
367{
368	struct mbuf *mn;
369
370	if (m->m_flags & M_PKTHDR)
371		MGETHDR(mn, how, m->m_type);
372	else
373		MGET(mn, how, m->m_type);
374	if (mn == NULL) {
375		m_freem(m);
376		return (NULL);
377	}
378	if (m->m_flags & M_PKTHDR)
379		M_MOVE_PKTHDR(mn, m);
380	mn->m_next = m;
381	m = mn;
382	if (len < MHLEN)
383		MH_ALIGN(m, len);
384	m->m_len = len;
385	return (m);
386}
387
388/*
389 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
390 * continuing for "len" bytes.  If len is M_COPYALL, copy to end of mbuf.
391 * The wait parameter is a choice of M_TRYWAIT/M_DONTWAIT from caller.
392 * Note that the copy is read-only, because clusters are not copied,
393 * only their reference counts are incremented.
394 */
395struct mbuf *
396m_copym(struct mbuf *m, int off0, int len, int wait)
397{
398	struct mbuf *n, **np;
399	int off = off0;
400	struct mbuf *top;
401	int copyhdr = 0;
402
403	KASSERT(off >= 0, ("m_copym, negative off %d", off));
404	KASSERT(len >= 0, ("m_copym, negative len %d", len));
405	MBUF_CHECKSLEEP(wait);
406	if (off == 0 && m->m_flags & M_PKTHDR)
407		copyhdr = 1;
408	while (off > 0) {
409		KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
410		if (off < m->m_len)
411			break;
412		off -= m->m_len;
413		m = m->m_next;
414	}
415	np = &top;
416	top = 0;
417	while (len > 0) {
418		if (m == NULL) {
419			KASSERT(len == M_COPYALL,
420			    ("m_copym, length > size of mbuf chain"));
421			break;
422		}
423		if (copyhdr)
424			MGETHDR(n, wait, m->m_type);
425		else
426			MGET(n, wait, m->m_type);
427		*np = n;
428		if (n == NULL)
429			goto nospace;
430		if (copyhdr) {
431			if (!m_dup_pkthdr(n, m, wait))
432				goto nospace;
433			if (len == M_COPYALL)
434				n->m_pkthdr.len -= off0;
435			else
436				n->m_pkthdr.len = len;
437			copyhdr = 0;
438		}
439		n->m_len = min(len, m->m_len - off);
440		if (m->m_flags & M_EXT) {
441			n->m_data = m->m_data + off;
442			n->m_ext = m->m_ext;
443			n->m_flags |= M_EXT;
444			MEXT_ADD_REF(m);
445			n->m_ext.ref_cnt = m->m_ext.ref_cnt;
446		} else
447			bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
448			    (u_int)n->m_len);
449		if (len != M_COPYALL)
450			len -= n->m_len;
451		off = 0;
452		m = m->m_next;
453		np = &n->m_next;
454	}
455	if (top == NULL)
456		mbstat.m_mcfail++;	/* XXX: No consistency. */
457
458	return (top);
459nospace:
460	m_freem(top);
461	mbstat.m_mcfail++;	/* XXX: No consistency. */
462	return (NULL);
463}
464
465/*
466 * Copy an entire packet, including header (which must be present).
467 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
468 * Note that the copy is read-only, because clusters are not copied,
469 * only their reference counts are incremented.
470 * Preserve alignment of the first mbuf so if the creator has left
471 * some room at the beginning (e.g. for inserting protocol headers)
472 * the copies still have the room available.
473 */
474struct mbuf *
475m_copypacket(struct mbuf *m, int how)
476{
477	struct mbuf *top, *n, *o;
478
479	MBUF_CHECKSLEEP(how);
480	MGET(n, how, m->m_type);
481	top = n;
482	if (n == NULL)
483		goto nospace;
484
485	if (!m_dup_pkthdr(n, m, how))
486		goto nospace;
487	n->m_len = m->m_len;
488	if (m->m_flags & M_EXT) {
489		n->m_data = m->m_data;
490		n->m_ext = m->m_ext;
491		n->m_flags |= M_EXT;
492		MEXT_ADD_REF(m);
493		n->m_ext.ref_cnt = m->m_ext.ref_cnt;
494	} else {
495		n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
496		bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
497	}
498
499	m = m->m_next;
500	while (m) {
501		MGET(o, how, m->m_type);
502		if (o == NULL)
503			goto nospace;
504
505		n->m_next = o;
506		n = n->m_next;
507
508		n->m_len = m->m_len;
509		if (m->m_flags & M_EXT) {
510			n->m_data = m->m_data;
511			n->m_ext = m->m_ext;
512			n->m_flags |= M_EXT;
513			MEXT_ADD_REF(m);
514			n->m_ext.ref_cnt = m->m_ext.ref_cnt;
515		} else {
516			bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
517		}
518
519		m = m->m_next;
520	}
521	return top;
522nospace:
523	m_freem(top);
524	mbstat.m_mcfail++;	/* XXX: No consistency. */
525	return (NULL);
526}
527
528/*
529 * Copy data from an mbuf chain starting "off" bytes from the beginning,
530 * continuing for "len" bytes, into the indicated buffer.
531 */
532void
533m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
534{
535	u_int count;
536
537	KASSERT(off >= 0, ("m_copydata, negative off %d", off));
538	KASSERT(len >= 0, ("m_copydata, negative len %d", len));
539	while (off > 0) {
540		KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
541		if (off < m->m_len)
542			break;
543		off -= m->m_len;
544		m = m->m_next;
545	}
546	while (len > 0) {
547		KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
548		count = min(m->m_len - off, len);
549		bcopy(mtod(m, caddr_t) + off, cp, count);
550		len -= count;
551		cp += count;
552		off = 0;
553		m = m->m_next;
554	}
555}
556
557/*
558 * Copy a packet header mbuf chain into a completely new chain, including
559 * copying any mbuf clusters.  Use this instead of m_copypacket() when
560 * you need a writable copy of an mbuf chain.
561 */
562struct mbuf *
563m_dup(struct mbuf *m, int how)
564{
565	struct mbuf **p, *top = NULL;
566	int remain, moff, nsize;
567
568	MBUF_CHECKSLEEP(how);
569	/* Sanity check */
570	if (m == NULL)
571		return (NULL);
572	M_ASSERTPKTHDR(m);
573
574	/* While there's more data, get a new mbuf, tack it on, and fill it */
575	remain = m->m_pkthdr.len;
576	moff = 0;
577	p = &top;
578	while (remain > 0 || top == NULL) {	/* allow m->m_pkthdr.len == 0 */
579		struct mbuf *n;
580
581		/* Get the next new mbuf */
582		if (remain >= MINCLSIZE) {
583			n = m_getcl(how, m->m_type, 0);
584			nsize = MCLBYTES;
585		} else {
586			n = m_get(how, m->m_type);
587			nsize = MLEN;
588		}
589		if (n == NULL)
590			goto nospace;
591
592		if (top == NULL) {		/* First one, must be PKTHDR */
593			if (!m_dup_pkthdr(n, m, how)) {
594				m_free(n);
595				goto nospace;
596			}
597			nsize = MHLEN;
598		}
599		n->m_len = 0;
600
601		/* Link it into the new chain */
602		*p = n;
603		p = &n->m_next;
604
605		/* Copy data from original mbuf(s) into new mbuf */
606		while (n->m_len < nsize && m != NULL) {
607			int chunk = min(nsize - n->m_len, m->m_len - moff);
608
609			bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
610			moff += chunk;
611			n->m_len += chunk;
612			remain -= chunk;
613			if (moff == m->m_len) {
614				m = m->m_next;
615				moff = 0;
616			}
617		}
618
619		/* Check correct total mbuf length */
620		KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
621		    	("%s: bogus m_pkthdr.len", __func__));
622	}
623	return (top);
624
625nospace:
626	m_freem(top);
627	mbstat.m_mcfail++;	/* XXX: No consistency. */
628	return (NULL);
629}
630
631/*
632 * Concatenate mbuf chain n to m.
633 * Both chains must be of the same type (e.g. MT_DATA).
634 * Any m_pkthdr is not updated.
635 */
636void
637m_cat(struct mbuf *m, struct mbuf *n)
638{
639	while (m->m_next)
640		m = m->m_next;
641	while (n) {
642		if (m->m_flags & M_EXT ||
643		    m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
644			/* just join the two chains */
645			m->m_next = n;
646			return;
647		}
648		/* splat the data from one into the other */
649		bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
650		    (u_int)n->m_len);
651		m->m_len += n->m_len;
652		n = m_free(n);
653	}
654}
655
656void
657m_adj(struct mbuf *mp, int req_len)
658{
659	int len = req_len;
660	struct mbuf *m;
661	int count;
662
663	if ((m = mp) == NULL)
664		return;
665	if (len >= 0) {
666		/*
667		 * Trim from head.
668		 */
669		while (m != NULL && len > 0) {
670			if (m->m_len <= len) {
671				len -= m->m_len;
672				m->m_len = 0;
673				m = m->m_next;
674			} else {
675				m->m_len -= len;
676				m->m_data += len;
677				len = 0;
678			}
679		}
680		m = mp;
681		if (mp->m_flags & M_PKTHDR)
682			m->m_pkthdr.len -= (req_len - len);
683	} else {
684		/*
685		 * Trim from tail.  Scan the mbuf chain,
686		 * calculating its length and finding the last mbuf.
687		 * If the adjustment only affects this mbuf, then just
688		 * adjust and return.  Otherwise, rescan and truncate
689		 * after the remaining size.
690		 */
691		len = -len;
692		count = 0;
693		for (;;) {
694			count += m->m_len;
695			if (m->m_next == (struct mbuf *)0)
696				break;
697			m = m->m_next;
698		}
699		if (m->m_len >= len) {
700			m->m_len -= len;
701			if (mp->m_flags & M_PKTHDR)
702				mp->m_pkthdr.len -= len;
703			return;
704		}
705		count -= len;
706		if (count < 0)
707			count = 0;
708		/*
709		 * Correct length for chain is "count".
710		 * Find the mbuf with last data, adjust its length,
711		 * and toss data from remaining mbufs on chain.
712		 */
713		m = mp;
714		if (m->m_flags & M_PKTHDR)
715			m->m_pkthdr.len = count;
716		for (; m; m = m->m_next) {
717			if (m->m_len >= count) {
718				m->m_len = count;
719				if (m->m_next != NULL) {
720					m_freem(m->m_next);
721					m->m_next = NULL;
722				}
723				break;
724			}
725			count -= m->m_len;
726		}
727	}
728}
729
730/*
731 * Rearange an mbuf chain so that len bytes are contiguous
732 * and in the data area of an mbuf (so that mtod and dtom
733 * will work for a structure of size len).  Returns the resulting
734 * mbuf chain on success, frees it and returns null on failure.
735 * If there is room, it will add up to max_protohdr-len extra bytes to the
736 * contiguous region in an attempt to avoid being called next time.
737 */
738struct mbuf *
739m_pullup(struct mbuf *n, int len)
740{
741	struct mbuf *m;
742	int count;
743	int space;
744
745	/*
746	 * If first mbuf has no cluster, and has room for len bytes
747	 * without shifting current data, pullup into it,
748	 * otherwise allocate a new mbuf to prepend to the chain.
749	 */
750	if ((n->m_flags & M_EXT) == 0 &&
751	    n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
752		if (n->m_len >= len)
753			return (n);
754		m = n;
755		n = n->m_next;
756		len -= m->m_len;
757	} else {
758		if (len > MHLEN)
759			goto bad;
760		MGET(m, M_DONTWAIT, n->m_type);
761		if (m == NULL)
762			goto bad;
763		m->m_len = 0;
764		if (n->m_flags & M_PKTHDR)
765			M_MOVE_PKTHDR(m, n);
766	}
767	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
768	do {
769		count = min(min(max(len, max_protohdr), space), n->m_len);
770		bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
771		  (u_int)count);
772		len -= count;
773		m->m_len += count;
774		n->m_len -= count;
775		space -= count;
776		if (n->m_len)
777			n->m_data += count;
778		else
779			n = m_free(n);
780	} while (len > 0 && n);
781	if (len > 0) {
782		(void) m_free(m);
783		goto bad;
784	}
785	m->m_next = n;
786	return (m);
787bad:
788	m_freem(n);
789	mbstat.m_mpfail++;	/* XXX: No consistency. */
790	return (NULL);
791}
792
793/*
794 * Like m_pullup(), except a new mbuf is always allocated, and we allow
795 * the amount of empty space before the data in the new mbuf to be specified
796 * (in the event that the caller expects to prepend later).
797 */
798int MSFail;
799
800struct mbuf *
801m_copyup(struct mbuf *n, int len, int dstoff)
802{
803	struct mbuf *m;
804	int count, space;
805
806	if (len > (MHLEN - dstoff))
807		goto bad;
808	MGET(m, M_DONTWAIT, n->m_type);
809	if (m == NULL)
810		goto bad;
811	m->m_len = 0;
812	if (n->m_flags & M_PKTHDR)
813		M_MOVE_PKTHDR(m, n);
814	m->m_data += dstoff;
815	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
816	do {
817		count = min(min(max(len, max_protohdr), space), n->m_len);
818		memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
819		    (unsigned)count);
820		len -= count;
821		m->m_len += count;
822		n->m_len -= count;
823		space -= count;
824		if (n->m_len)
825			n->m_data += count;
826		else
827			n = m_free(n);
828	} while (len > 0 && n);
829	if (len > 0) {
830		(void) m_free(m);
831		goto bad;
832	}
833	m->m_next = n;
834	return (m);
835 bad:
836	m_freem(n);
837	MSFail++;
838	return (NULL);
839}
840
841/*
842 * Partition an mbuf chain in two pieces, returning the tail --
843 * all but the first len0 bytes.  In case of failure, it returns NULL and
844 * attempts to restore the chain to its original state.
845 *
846 * Note that the resulting mbufs might be read-only, because the new
847 * mbuf can end up sharing an mbuf cluster with the original mbuf if
848 * the "breaking point" happens to lie within a cluster mbuf. Use the
849 * M_WRITABLE() macro to check for this case.
850 */
851struct mbuf *
852m_split(struct mbuf *m0, int len0, int wait)
853{
854	struct mbuf *m, *n;
855	u_int len = len0, remain;
856
857	MBUF_CHECKSLEEP(wait);
858	for (m = m0; m && len > m->m_len; m = m->m_next)
859		len -= m->m_len;
860	if (m == NULL)
861		return (NULL);
862	remain = m->m_len - len;
863	if (m0->m_flags & M_PKTHDR) {
864		MGETHDR(n, wait, m0->m_type);
865		if (n == NULL)
866			return (NULL);
867		n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
868		n->m_pkthdr.len = m0->m_pkthdr.len - len0;
869		m0->m_pkthdr.len = len0;
870		if (m->m_flags & M_EXT)
871			goto extpacket;
872		if (remain > MHLEN) {
873			/* m can't be the lead packet */
874			MH_ALIGN(n, 0);
875			n->m_next = m_split(m, len, wait);
876			if (n->m_next == NULL) {
877				(void) m_free(n);
878				return (NULL);
879			} else {
880				n->m_len = 0;
881				return (n);
882			}
883		} else
884			MH_ALIGN(n, remain);
885	} else if (remain == 0) {
886		n = m->m_next;
887		m->m_next = NULL;
888		return (n);
889	} else {
890		MGET(n, wait, m->m_type);
891		if (n == NULL)
892			return (NULL);
893		M_ALIGN(n, remain);
894	}
895extpacket:
896	if (m->m_flags & M_EXT) {
897		n->m_flags |= M_EXT;
898		n->m_ext = m->m_ext;
899		MEXT_ADD_REF(m);
900		n->m_ext.ref_cnt = m->m_ext.ref_cnt;
901		n->m_data = m->m_data + len;
902	} else {
903		bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
904	}
905	n->m_len = remain;
906	m->m_len = len;
907	n->m_next = m->m_next;
908	m->m_next = NULL;
909	return (n);
910}
911/*
912 * Routine to copy from device local memory into mbufs.
913 * Note that `off' argument is offset into first mbuf of target chain from
914 * which to begin copying the data to.
915 */
916struct mbuf *
917m_devget(char *buf, int totlen, int off, struct ifnet *ifp,
918	 void (*copy)(char *from, caddr_t to, u_int len))
919{
920	struct mbuf *m;
921	struct mbuf *top = NULL, **mp = &top;
922	int len;
923
924	if (off < 0 || off > MHLEN)
925		return (NULL);
926
927	while (totlen > 0) {
928		if (top == NULL) {	/* First one, must be PKTHDR */
929			if (totlen + off >= MINCLSIZE) {
930				m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
931				len = MCLBYTES;
932			} else {
933				m = m_gethdr(M_DONTWAIT, MT_DATA);
934				len = MHLEN;
935
936				/* Place initial small packet/header at end of mbuf */
937				if (m && totlen + off + max_linkhdr <= MLEN) {
938					m->m_data += max_linkhdr;
939					len -= max_linkhdr;
940				}
941			}
942			if (m == NULL)
943				return NULL;
944			m->m_pkthdr.rcvif = ifp;
945			m->m_pkthdr.len = totlen;
946		} else {
947			if (totlen + off >= MINCLSIZE) {
948				m = m_getcl(M_DONTWAIT, MT_DATA, 0);
949				len = MCLBYTES;
950			} else {
951				m = m_get(M_DONTWAIT, MT_DATA);
952				len = MLEN;
953			}
954			if (m == NULL) {
955				m_freem(top);
956				return NULL;
957			}
958		}
959		if (off) {
960			m->m_data += off;
961			len -= off;
962			off = 0;
963		}
964		m->m_len = len = min(totlen, len);
965		if (copy)
966			copy(buf, mtod(m, caddr_t), (u_int)len);
967		else
968			bcopy(buf, mtod(m, caddr_t), (u_int)len);
969		buf += len;
970		*mp = m;
971		mp = &m->m_next;
972		totlen -= len;
973	}
974	return (top);
975}
976
977/*
978 * Copy data from a buffer back into the indicated mbuf chain,
979 * starting "off" bytes from the beginning, extending the mbuf
980 * chain if necessary.
981 */
982void
983m_copyback(struct mbuf *m0, int off, int len, c_caddr_t cp)
984{
985	int mlen;
986	struct mbuf *m = m0, *n;
987	int totlen = 0;
988
989	if (m0 == NULL)
990		return;
991	while (off > (mlen = m->m_len)) {
992		off -= mlen;
993		totlen += mlen;
994		if (m->m_next == NULL) {
995			n = m_get(M_DONTWAIT, m->m_type);
996			if (n == NULL)
997				goto out;
998			bzero(mtod(n, caddr_t), MLEN);
999			n->m_len = min(MLEN, len + off);
1000			m->m_next = n;
1001		}
1002		m = m->m_next;
1003	}
1004	while (len > 0) {
1005		mlen = min (m->m_len - off, len);
1006		bcopy(cp, off + mtod(m, caddr_t), (u_int)mlen);
1007		cp += mlen;
1008		len -= mlen;
1009		mlen += off;
1010		off = 0;
1011		totlen += mlen;
1012		if (len == 0)
1013			break;
1014		if (m->m_next == NULL) {
1015			n = m_get(M_DONTWAIT, m->m_type);
1016			if (n == NULL)
1017				break;
1018			n->m_len = min(MLEN, len);
1019			m->m_next = n;
1020		}
1021		m = m->m_next;
1022	}
1023out:	if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1024		m->m_pkthdr.len = totlen;
1025}
1026
1027/*
1028 * Append the specified data to the indicated mbuf chain,
1029 * Extend the mbuf chain if the new data does not fit in
1030 * existing space.
1031 *
1032 * Return 1 if able to complete the job; otherwise 0.
1033 */
1034int
1035m_append(struct mbuf *m0, int len, c_caddr_t cp)
1036{
1037	struct mbuf *m, *n;
1038	int remainder, space;
1039
1040	for (m = m0; m->m_next != NULL; m = m->m_next)
1041		;
1042	remainder = len;
1043	space = M_TRAILINGSPACE(m);
1044	if (space > 0) {
1045		/*
1046		 * Copy into available space.
1047		 */
1048		if (space > remainder)
1049			space = remainder;
1050		bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
1051		m->m_len += space;
1052		cp += space, remainder -= space;
1053	}
1054	while (remainder > 0) {
1055		/*
1056		 * Allocate a new mbuf; could check space
1057		 * and allocate a cluster instead.
1058		 */
1059		n = m_get(M_DONTWAIT, m->m_type);
1060		if (n == NULL)
1061			break;
1062		n->m_len = min(MLEN, remainder);
1063		bcopy(cp, mtod(n, caddr_t), n->m_len);
1064		cp += n->m_len, remainder -= n->m_len;
1065		m->m_next = n;
1066		m = n;
1067	}
1068	if (m0->m_flags & M_PKTHDR)
1069		m0->m_pkthdr.len += len - remainder;
1070	return (remainder == 0);
1071}
1072
1073/*
1074 * Apply function f to the data in an mbuf chain starting "off" bytes from
1075 * the beginning, continuing for "len" bytes.
1076 */
1077int
1078m_apply(struct mbuf *m, int off, int len,
1079    int (*f)(void *, void *, u_int), void *arg)
1080{
1081	u_int count;
1082	int rval;
1083
1084	KASSERT(off >= 0, ("m_apply, negative off %d", off));
1085	KASSERT(len >= 0, ("m_apply, negative len %d", len));
1086	while (off > 0) {
1087		KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1088		if (off < m->m_len)
1089			break;
1090		off -= m->m_len;
1091		m = m->m_next;
1092	}
1093	while (len > 0) {
1094		KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1095		count = min(m->m_len - off, len);
1096		rval = (*f)(arg, mtod(m, caddr_t) + off, count);
1097		if (rval)
1098			return (rval);
1099		len -= count;
1100		off = 0;
1101		m = m->m_next;
1102	}
1103	return (0);
1104}
1105
1106/*
1107 * Return a pointer to mbuf/offset of location in mbuf chain.
1108 */
1109struct mbuf *
1110m_getptr(struct mbuf *m, int loc, int *off)
1111{
1112
1113	while (loc >= 0) {
1114		/* Normal end of search. */
1115		if (m->m_len > loc) {
1116			*off = loc;
1117			return (m);
1118		} else {
1119			loc -= m->m_len;
1120			if (m->m_next == NULL) {
1121				if (loc == 0) {
1122					/* Point at the end of valid data. */
1123					*off = m->m_len;
1124					return (m);
1125				}
1126				return (NULL);
1127			}
1128			m = m->m_next;
1129		}
1130	}
1131	return (NULL);
1132}
1133
1134void
1135m_print(const struct mbuf *m, int maxlen)
1136{
1137	int len;
1138	int pdata;
1139	const struct mbuf *m2;
1140
1141	if (m->m_flags & M_PKTHDR)
1142		len = m->m_pkthdr.len;
1143	else
1144		len = -1;
1145	m2 = m;
1146	while (m2 != NULL && (len == -1 || len)) {
1147		pdata = m2->m_len;
1148		if (maxlen != -1 && pdata > maxlen)
1149			pdata = maxlen;
1150		printf("mbuf: %p len: %d, next: %p, %b%s", m2, m2->m_len,
1151		    m2->m_next, m2->m_flags, "\20\20freelist\17skipfw"
1152		    "\11proto5\10proto4\7proto3\6proto2\5proto1\4rdonly"
1153		    "\3eor\2pkthdr\1ext", pdata ? "" : "\n");
1154		if (pdata)
1155			printf(", %*D\n", m2->m_len, (u_char *)m2->m_data, "-");
1156		if (len != -1)
1157			len -= m2->m_len;
1158		m2 = m2->m_next;
1159	}
1160	if (len > 0)
1161		printf("%d bytes unaccounted for.\n", len);
1162	return;
1163}
1164
1165u_int
1166m_fixhdr(struct mbuf *m0)
1167{
1168	u_int len;
1169
1170	len = m_length(m0, NULL);
1171	m0->m_pkthdr.len = len;
1172	return (len);
1173}
1174
1175u_int
1176m_length(struct mbuf *m0, struct mbuf **last)
1177{
1178	struct mbuf *m;
1179	u_int len;
1180
1181	len = 0;
1182	for (m = m0; m != NULL; m = m->m_next) {
1183		len += m->m_len;
1184		if (m->m_next == NULL)
1185			break;
1186	}
1187	if (last != NULL)
1188		*last = m;
1189	return (len);
1190}
1191
1192/*
1193 * Defragment a mbuf chain, returning the shortest possible
1194 * chain of mbufs and clusters.  If allocation fails and
1195 * this cannot be completed, NULL will be returned, but
1196 * the passed in chain will be unchanged.  Upon success,
1197 * the original chain will be freed, and the new chain
1198 * will be returned.
1199 *
1200 * If a non-packet header is passed in, the original
1201 * mbuf (chain?) will be returned unharmed.
1202 */
1203struct mbuf *
1204m_defrag(struct mbuf *m0, int how)
1205{
1206	struct mbuf *m_new = NULL, *m_final = NULL;
1207	int progress = 0, length;
1208
1209	MBUF_CHECKSLEEP(how);
1210	if (!(m0->m_flags & M_PKTHDR))
1211		return (m0);
1212
1213	m_fixhdr(m0); /* Needed sanity check */
1214
1215#ifdef MBUF_STRESS_TEST
1216	if (m_defragrandomfailures) {
1217		int temp = arc4random() & 0xff;
1218		if (temp == 0xba)
1219			goto nospace;
1220	}
1221#endif
1222
1223	if (m0->m_pkthdr.len > MHLEN)
1224		m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1225	else
1226		m_final = m_gethdr(how, MT_DATA);
1227
1228	if (m_final == NULL)
1229		goto nospace;
1230
1231	if (m_dup_pkthdr(m_final, m0, how) == 0)
1232		goto nospace;
1233
1234	m_new = m_final;
1235
1236	while (progress < m0->m_pkthdr.len) {
1237		length = m0->m_pkthdr.len - progress;
1238		if (length > MCLBYTES)
1239			length = MCLBYTES;
1240
1241		if (m_new == NULL) {
1242			if (length > MLEN)
1243				m_new = m_getcl(how, MT_DATA, 0);
1244			else
1245				m_new = m_get(how, MT_DATA);
1246			if (m_new == NULL)
1247				goto nospace;
1248		}
1249
1250		m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1251		progress += length;
1252		m_new->m_len = length;
1253		if (m_new != m_final)
1254			m_cat(m_final, m_new);
1255		m_new = NULL;
1256	}
1257#ifdef MBUF_STRESS_TEST
1258	if (m0->m_next == NULL)
1259		m_defraguseless++;
1260#endif
1261	m_freem(m0);
1262	m0 = m_final;
1263#ifdef MBUF_STRESS_TEST
1264	m_defragpackets++;
1265	m_defragbytes += m0->m_pkthdr.len;
1266#endif
1267	return (m0);
1268nospace:
1269#ifdef MBUF_STRESS_TEST
1270	m_defragfailure++;
1271#endif
1272	if (m_final)
1273		m_freem(m_final);
1274	return (NULL);
1275}
1276
1277#ifdef MBUF_STRESS_TEST
1278
1279/*
1280 * Fragment an mbuf chain.  There's no reason you'd ever want to do
1281 * this in normal usage, but it's great for stress testing various
1282 * mbuf consumers.
1283 *
1284 * If fragmentation is not possible, the original chain will be
1285 * returned.
1286 *
1287 * Possible length values:
1288 * 0	 no fragmentation will occur
1289 * > 0	each fragment will be of the specified length
1290 * -1	each fragment will be the same random value in length
1291 * -2	each fragment's length will be entirely random
1292 * (Random values range from 1 to 256)
1293 */
1294struct mbuf *
1295m_fragment(struct mbuf *m0, int how, int length)
1296{
1297	struct mbuf *m_new = NULL, *m_final = NULL;
1298	int progress = 0;
1299
1300	if (!(m0->m_flags & M_PKTHDR))
1301		return (m0);
1302
1303	if ((length == 0) || (length < -2))
1304		return (m0);
1305
1306	m_fixhdr(m0); /* Needed sanity check */
1307
1308	m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1309
1310	if (m_final == NULL)
1311		goto nospace;
1312
1313	if (m_dup_pkthdr(m_final, m0, how) == 0)
1314		goto nospace;
1315
1316	m_new = m_final;
1317
1318	if (length == -1)
1319		length = 1 + (arc4random() & 255);
1320
1321	while (progress < m0->m_pkthdr.len) {
1322		int fraglen;
1323
1324		if (length > 0)
1325			fraglen = length;
1326		else
1327			fraglen = 1 + (arc4random() & 255);
1328		if (fraglen > m0->m_pkthdr.len - progress)
1329			fraglen = m0->m_pkthdr.len - progress;
1330
1331		if (fraglen > MCLBYTES)
1332			fraglen = MCLBYTES;
1333
1334		if (m_new == NULL) {
1335			m_new = m_getcl(how, MT_DATA, 0);
1336			if (m_new == NULL)
1337				goto nospace;
1338		}
1339
1340		m_copydata(m0, progress, fraglen, mtod(m_new, caddr_t));
1341		progress += fraglen;
1342		m_new->m_len = fraglen;
1343		if (m_new != m_final)
1344			m_cat(m_final, m_new);
1345		m_new = NULL;
1346	}
1347	m_freem(m0);
1348	m0 = m_final;
1349	return (m0);
1350nospace:
1351	if (m_final)
1352		m_freem(m_final);
1353	/* Return the original chain on failure */
1354	return (m0);
1355}
1356
1357#endif
1358
1359struct mbuf *
1360m_uiotombuf(struct uio *uio, int how, int len, int align)
1361{
1362	struct mbuf *m_new = NULL, *m_final = NULL;
1363	int progress = 0, error = 0, length, total;
1364
1365	if (len > 0)
1366		total = min(uio->uio_resid, len);
1367	else
1368		total = uio->uio_resid;
1369	if (align >= MHLEN)
1370		goto nospace;
1371	if (total + align > MHLEN)
1372		m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1373	else
1374		m_final = m_gethdr(how, MT_DATA);
1375	if (m_final == NULL)
1376		goto nospace;
1377	m_final->m_data += align;
1378	m_new = m_final;
1379	while (progress < total) {
1380		length = total - progress;
1381		if (length > MCLBYTES)
1382			length = MCLBYTES;
1383		if (m_new == NULL) {
1384			if (length > MLEN)
1385				m_new = m_getcl(how, MT_DATA, 0);
1386			else
1387				m_new = m_get(how, MT_DATA);
1388			if (m_new == NULL)
1389				goto nospace;
1390		}
1391		error = uiomove(mtod(m_new, void *), length, uio);
1392		if (error)
1393			goto nospace;
1394		progress += length;
1395		m_new->m_len = length;
1396		if (m_new != m_final)
1397			m_cat(m_final, m_new);
1398		m_new = NULL;
1399	}
1400	m_fixhdr(m_final);
1401	return (m_final);
1402nospace:
1403	if (m_new)
1404		m_free(m_new);
1405	if (m_final)
1406		m_freem(m_final);
1407	return (NULL);
1408}
1409
1410/*
1411 * Set the m_data pointer of a newly-allocated mbuf
1412 * to place an object of the specified size at the
1413 * end of the mbuf, longword aligned.
1414 */
1415void
1416m_align(struct mbuf *m, int len)
1417{
1418	int adjust;
1419
1420	if (m->m_flags & M_EXT)
1421		adjust = m->m_ext.ext_size - len;
1422	else if (m->m_flags & M_PKTHDR)
1423		adjust = MHLEN - len;
1424	else
1425		adjust = MLEN - len;
1426	m->m_data += adjust &~ (sizeof(long)-1);
1427}
1428