uipc_mbuf.c revision 129906
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 129906 2004-05-31 21:46:06Z bmilekic $");
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 */
91MALLOC_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	}
127	num--;
128	top->m_len = 0;
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 = 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
225	MEXT_REM_REF(m);
226	if (atomic_cmpset_int(m->m_ext.ref_cnt, 0, 1)) {
227		if (m->m_ext.ext_type == EXT_PACKET) {
228			uma_zfree(zone_pack, m);
229			return;
230		} else if (m->m_ext.ext_type == EXT_CLUSTER) {
231			uma_zfree(zone_clust, m->m_ext.ext_buf);
232			m->m_ext.ext_buf = NULL;
233		} else {
234			(*(m->m_ext.ext_free))(m->m_ext.ext_buf,
235			    m->m_ext.ext_args);
236			if (m->m_ext.ext_type != EXT_EXTREF)
237				free(m->m_ext.ref_cnt, M_MBUF);
238		}
239	}
240	uma_zfree(zone_mbuf, m);
241}
242
243/*
244 * "Move" mbuf pkthdr from "from" to "to".
245 * "from" must have M_PKTHDR set, and "to" must be empty.
246 */
247void
248m_move_pkthdr(struct mbuf *to, struct mbuf *from)
249{
250
251#if 0
252	/* see below for why these are not enabled */
253	M_ASSERTPKTHDR(to);
254	/* Note: with MAC, this may not be a good assertion. */
255	KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags),
256	    ("m_move_pkthdr: to has tags"));
257#endif
258	KASSERT((to->m_flags & M_EXT) == 0, ("m_move_pkthdr: to has cluster"));
259#ifdef MAC
260	/*
261	 * XXXMAC: It could be this should also occur for non-MAC?
262	 */
263	if (to->m_flags & M_PKTHDR)
264		m_tag_delete_chain(to, NULL);
265#endif
266	to->m_flags = from->m_flags & M_COPYFLAGS;
267	to->m_data = to->m_pktdat;
268	to->m_pkthdr = from->m_pkthdr;		/* especially tags */
269	SLIST_INIT(&from->m_pkthdr.tags);	/* purge tags from src */
270	from->m_flags &= ~M_PKTHDR;
271}
272
273/*
274 * Duplicate "from"'s mbuf pkthdr in "to".
275 * "from" must have M_PKTHDR set, and "to" must be empty.
276 * In particular, this does a deep copy of the packet tags.
277 */
278int
279m_dup_pkthdr(struct mbuf *to, struct mbuf *from, int how)
280{
281
282#if 0
283	/*
284	 * The mbuf allocator only initializes the pkthdr
285	 * when the mbuf is allocated with MGETHDR. Many users
286	 * (e.g. m_copy*, m_prepend) use MGET and then
287	 * smash the pkthdr as needed causing these
288	 * assertions to trip.  For now just disable them.
289	 */
290	M_ASSERTPKTHDR(to);
291	/* Note: with MAC, this may not be a good assertion. */
292	KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags), ("m_dup_pkthdr: to has tags"));
293#endif
294#ifdef MAC
295	if (to->m_flags & M_PKTHDR)
296		m_tag_delete_chain(to, NULL);
297#endif
298	to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
299	if ((to->m_flags & M_EXT) == 0)
300		to->m_data = to->m_pktdat;
301	to->m_pkthdr = from->m_pkthdr;
302	SLIST_INIT(&to->m_pkthdr.tags);
303	return (m_tag_copy_chain(to, from, MBTOM(how)));
304}
305
306/*
307 * Lesser-used path for M_PREPEND:
308 * allocate new mbuf to prepend to chain,
309 * copy junk along.
310 */
311struct mbuf *
312m_prepend(struct mbuf *m, int len, int how)
313{
314	struct mbuf *mn;
315
316	if (m->m_flags & M_PKTHDR)
317		MGETHDR(mn, how, m->m_type);
318	else
319		MGET(mn, how, m->m_type);
320	if (mn == NULL) {
321		m_freem(m);
322		return (NULL);
323	}
324	if (m->m_flags & M_PKTHDR)
325		M_MOVE_PKTHDR(mn, m);
326	mn->m_next = m;
327	m = mn;
328	if (len < MHLEN)
329		MH_ALIGN(m, len);
330	m->m_len = len;
331	return (m);
332}
333
334/*
335 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
336 * continuing for "len" bytes.  If len is M_COPYALL, copy to end of mbuf.
337 * The wait parameter is a choice of M_TRYWAIT/M_DONTWAIT from caller.
338 * Note that the copy is read-only, because clusters are not copied,
339 * only their reference counts are incremented.
340 */
341struct mbuf *
342m_copym(struct mbuf *m, int off0, int len, int wait)
343{
344	struct mbuf *n, **np;
345	int off = off0;
346	struct mbuf *top;
347	int copyhdr = 0;
348
349	KASSERT(off >= 0, ("m_copym, negative off %d", off));
350	KASSERT(len >= 0, ("m_copym, negative len %d", len));
351	if (off == 0 && m->m_flags & M_PKTHDR)
352		copyhdr = 1;
353	while (off > 0) {
354		KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
355		if (off < m->m_len)
356			break;
357		off -= m->m_len;
358		m = m->m_next;
359	}
360	np = &top;
361	top = 0;
362	while (len > 0) {
363		if (m == NULL) {
364			KASSERT(len == M_COPYALL,
365			    ("m_copym, length > size of mbuf chain"));
366			break;
367		}
368		if (copyhdr)
369			MGETHDR(n, wait, m->m_type);
370		else
371			MGET(n, wait, m->m_type);
372		*np = n;
373		if (n == NULL)
374			goto nospace;
375		if (copyhdr) {
376			if (!m_dup_pkthdr(n, m, wait))
377				goto nospace;
378			if (len == M_COPYALL)
379				n->m_pkthdr.len -= off0;
380			else
381				n->m_pkthdr.len = len;
382			copyhdr = 0;
383		}
384		n->m_len = min(len, m->m_len - off);
385		if (m->m_flags & M_EXT) {
386			n->m_data = m->m_data + off;
387			n->m_ext = m->m_ext;
388			n->m_flags |= M_EXT;
389			MEXT_ADD_REF(m);
390		} else
391			bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
392			    (u_int)n->m_len);
393		if (len != M_COPYALL)
394			len -= n->m_len;
395		off = 0;
396		m = m->m_next;
397		np = &n->m_next;
398	}
399	if (top == NULL)
400		mbstat.m_mcfail++;	/* XXX: No consistency. */
401
402	return (top);
403nospace:
404	m_freem(top);
405	mbstat.m_mcfail++;	/* XXX: No consistency. */
406	return (NULL);
407}
408
409/*
410 * Copy an entire packet, including header (which must be present).
411 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
412 * Note that the copy is read-only, because clusters are not copied,
413 * only their reference counts are incremented.
414 * Preserve alignment of the first mbuf so if the creator has left
415 * some room at the beginning (e.g. for inserting protocol headers)
416 * the copies still have the room available.
417 */
418struct mbuf *
419m_copypacket(struct mbuf *m, int how)
420{
421	struct mbuf *top, *n, *o;
422
423	MGET(n, how, m->m_type);
424	top = n;
425	if (n == NULL)
426		goto nospace;
427
428	if (!m_dup_pkthdr(n, m, how))
429		goto nospace;
430	n->m_len = m->m_len;
431	if (m->m_flags & M_EXT) {
432		n->m_data = m->m_data;
433		n->m_ext = m->m_ext;
434		n->m_flags |= M_EXT;
435		MEXT_ADD_REF(m);
436	} else {
437		n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
438		bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
439	}
440
441	m = m->m_next;
442	while (m) {
443		MGET(o, how, m->m_type);
444		if (o == NULL)
445			goto nospace;
446
447		n->m_next = o;
448		n = n->m_next;
449
450		n->m_len = m->m_len;
451		if (m->m_flags & M_EXT) {
452			n->m_data = m->m_data;
453			n->m_ext = m->m_ext;
454			n->m_flags |= M_EXT;
455			MEXT_ADD_REF(m);
456		} else {
457			bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
458		}
459
460		m = m->m_next;
461	}
462	return top;
463nospace:
464	m_freem(top);
465	mbstat.m_mcfail++;	/* XXX: No consistency. */
466	return (NULL);
467}
468
469/*
470 * Copy data from an mbuf chain starting "off" bytes from the beginning,
471 * continuing for "len" bytes, into the indicated buffer.
472 */
473void
474m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
475{
476	u_int count;
477
478	KASSERT(off >= 0, ("m_copydata, negative off %d", off));
479	KASSERT(len >= 0, ("m_copydata, negative len %d", len));
480	while (off > 0) {
481		KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
482		if (off < m->m_len)
483			break;
484		off -= m->m_len;
485		m = m->m_next;
486	}
487	while (len > 0) {
488		KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
489		count = min(m->m_len - off, len);
490		bcopy(mtod(m, caddr_t) + off, cp, count);
491		len -= count;
492		cp += count;
493		off = 0;
494		m = m->m_next;
495	}
496}
497
498/*
499 * Copy a packet header mbuf chain into a completely new chain, including
500 * copying any mbuf clusters.  Use this instead of m_copypacket() when
501 * you need a writable copy of an mbuf chain.
502 */
503struct mbuf *
504m_dup(struct mbuf *m, int how)
505{
506	struct mbuf **p, *top = NULL;
507	int remain, moff, nsize;
508
509	/* Sanity check */
510	if (m == NULL)
511		return (NULL);
512	M_ASSERTPKTHDR(m);
513
514	/* While there's more data, get a new mbuf, tack it on, and fill it */
515	remain = m->m_pkthdr.len;
516	moff = 0;
517	p = &top;
518	while (remain > 0 || top == NULL) {	/* allow m->m_pkthdr.len == 0 */
519		struct mbuf *n;
520
521		/* Get the next new mbuf */
522		if (remain >= MINCLSIZE) {
523			n = m_getcl(how, m->m_type, 0);
524			nsize = MCLBYTES;
525		} else {
526			n = m_get(how, m->m_type);
527			nsize = MLEN;
528		}
529		if (n == NULL)
530			goto nospace;
531
532		if (top == NULL) {		/* First one, must be PKTHDR */
533			if (!m_dup_pkthdr(n, m, how)) {
534				m_free(n);
535				goto nospace;
536			}
537			nsize = MHLEN;
538		}
539		n->m_len = 0;
540
541		/* Link it into the new chain */
542		*p = n;
543		p = &n->m_next;
544
545		/* Copy data from original mbuf(s) into new mbuf */
546		while (n->m_len < nsize && m != NULL) {
547			int chunk = min(nsize - n->m_len, m->m_len - moff);
548
549			bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
550			moff += chunk;
551			n->m_len += chunk;
552			remain -= chunk;
553			if (moff == m->m_len) {
554				m = m->m_next;
555				moff = 0;
556			}
557		}
558
559		/* Check correct total mbuf length */
560		KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
561		    	("%s: bogus m_pkthdr.len", __func__));
562	}
563	return (top);
564
565nospace:
566	m_freem(top);
567	mbstat.m_mcfail++;	/* XXX: No consistency. */
568	return (NULL);
569}
570
571/*
572 * Concatenate mbuf chain n to m.
573 * Both chains must be of the same type (e.g. MT_DATA).
574 * Any m_pkthdr is not updated.
575 */
576void
577m_cat(struct mbuf *m, struct mbuf *n)
578{
579	while (m->m_next)
580		m = m->m_next;
581	while (n) {
582		if (m->m_flags & M_EXT ||
583		    m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
584			/* just join the two chains */
585			m->m_next = n;
586			return;
587		}
588		/* splat the data from one into the other */
589		bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
590		    (u_int)n->m_len);
591		m->m_len += n->m_len;
592		n = m_free(n);
593	}
594}
595
596void
597m_adj(struct mbuf *mp, int req_len)
598{
599	int len = req_len;
600	struct mbuf *m;
601	int count;
602
603	if ((m = mp) == NULL)
604		return;
605	if (len >= 0) {
606		/*
607		 * Trim from head.
608		 */
609		while (m != NULL && len > 0) {
610			if (m->m_len <= len) {
611				len -= m->m_len;
612				m->m_len = 0;
613				m = m->m_next;
614			} else {
615				m->m_len -= len;
616				m->m_data += len;
617				len = 0;
618			}
619		}
620		m = mp;
621		if (mp->m_flags & M_PKTHDR)
622			m->m_pkthdr.len -= (req_len - len);
623	} else {
624		/*
625		 * Trim from tail.  Scan the mbuf chain,
626		 * calculating its length and finding the last mbuf.
627		 * If the adjustment only affects this mbuf, then just
628		 * adjust and return.  Otherwise, rescan and truncate
629		 * after the remaining size.
630		 */
631		len = -len;
632		count = 0;
633		for (;;) {
634			count += m->m_len;
635			if (m->m_next == (struct mbuf *)0)
636				break;
637			m = m->m_next;
638		}
639		if (m->m_len >= len) {
640			m->m_len -= len;
641			if (mp->m_flags & M_PKTHDR)
642				mp->m_pkthdr.len -= len;
643			return;
644		}
645		count -= len;
646		if (count < 0)
647			count = 0;
648		/*
649		 * Correct length for chain is "count".
650		 * Find the mbuf with last data, adjust its length,
651		 * and toss data from remaining mbufs on chain.
652		 */
653		m = mp;
654		if (m->m_flags & M_PKTHDR)
655			m->m_pkthdr.len = count;
656		for (; m; m = m->m_next) {
657			if (m->m_len >= count) {
658				m->m_len = count;
659				break;
660			}
661			count -= m->m_len;
662		}
663		while (m->m_next)
664			(m = m->m_next) ->m_len = 0;
665	}
666}
667
668/*
669 * Rearange an mbuf chain so that len bytes are contiguous
670 * and in the data area of an mbuf (so that mtod and dtom
671 * will work for a structure of size len).  Returns the resulting
672 * mbuf chain on success, frees it and returns null on failure.
673 * If there is room, it will add up to max_protohdr-len extra bytes to the
674 * contiguous region in an attempt to avoid being called next time.
675 */
676struct mbuf *
677m_pullup(struct mbuf *n, int len)
678{
679	struct mbuf *m;
680	int count;
681	int space;
682
683	/*
684	 * If first mbuf has no cluster, and has room for len bytes
685	 * without shifting current data, pullup into it,
686	 * otherwise allocate a new mbuf to prepend to the chain.
687	 */
688	if ((n->m_flags & M_EXT) == 0 &&
689	    n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
690		if (n->m_len >= len)
691			return (n);
692		m = n;
693		n = n->m_next;
694		len -= m->m_len;
695	} else {
696		if (len > MHLEN)
697			goto bad;
698		MGET(m, M_DONTWAIT, n->m_type);
699		if (m == NULL)
700			goto bad;
701		m->m_len = 0;
702		if (n->m_flags & M_PKTHDR)
703			M_MOVE_PKTHDR(m, n);
704	}
705	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
706	do {
707		count = min(min(max(len, max_protohdr), space), n->m_len);
708		bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
709		  (u_int)count);
710		len -= count;
711		m->m_len += count;
712		n->m_len -= count;
713		space -= count;
714		if (n->m_len)
715			n->m_data += count;
716		else
717			n = m_free(n);
718	} while (len > 0 && n);
719	if (len > 0) {
720		(void) m_free(m);
721		goto bad;
722	}
723	m->m_next = n;
724	return (m);
725bad:
726	m_freem(n);
727	mbstat.m_mpfail++;	/* XXX: No consistency. */
728	return (NULL);
729}
730
731/*
732 * Partition an mbuf chain in two pieces, returning the tail --
733 * all but the first len0 bytes.  In case of failure, it returns NULL and
734 * attempts to restore the chain to its original state.
735 *
736 * Note that the resulting mbufs might be read-only, because the new
737 * mbuf can end up sharing an mbuf cluster with the original mbuf if
738 * the "breaking point" happens to lie within a cluster mbuf. Use the
739 * M_WRITABLE() macro to check for this case.
740 */
741struct mbuf *
742m_split(struct mbuf *m0, int len0, int wait)
743{
744	struct mbuf *m, *n;
745	u_int len = len0, remain;
746
747	for (m = m0; m && len > m->m_len; m = m->m_next)
748		len -= m->m_len;
749	if (m == NULL)
750		return (NULL);
751	remain = m->m_len - len;
752	if (m0->m_flags & M_PKTHDR) {
753		MGETHDR(n, wait, m0->m_type);
754		if (n == NULL)
755			return (NULL);
756		n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
757		n->m_pkthdr.len = m0->m_pkthdr.len - len0;
758		m0->m_pkthdr.len = len0;
759		if (m->m_flags & M_EXT)
760			goto extpacket;
761		if (remain > MHLEN) {
762			/* m can't be the lead packet */
763			MH_ALIGN(n, 0);
764			n->m_next = m_split(m, len, wait);
765			if (n->m_next == NULL) {
766				(void) m_free(n);
767				return (NULL);
768			} else {
769				n->m_len = 0;
770				return (n);
771			}
772		} else
773			MH_ALIGN(n, remain);
774	} else if (remain == 0) {
775		n = m->m_next;
776		m->m_next = NULL;
777		return (n);
778	} else {
779		MGET(n, wait, m->m_type);
780		if (n == NULL)
781			return (NULL);
782		M_ALIGN(n, remain);
783	}
784extpacket:
785	if (m->m_flags & M_EXT) {
786		n->m_flags |= M_EXT;
787		n->m_ext = m->m_ext;
788		MEXT_ADD_REF(m);
789		n->m_data = m->m_data + len;
790	} else {
791		bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
792	}
793	n->m_len = remain;
794	m->m_len = len;
795	n->m_next = m->m_next;
796	m->m_next = NULL;
797	return (n);
798}
799/*
800 * Routine to copy from device local memory into mbufs.
801 * Note that `off' argument is offset into first mbuf of target chain from
802 * which to begin copying the data to.
803 */
804struct mbuf *
805m_devget(char *buf, int totlen, int off, struct ifnet *ifp,
806	 void (*copy)(char *from, caddr_t to, u_int len))
807{
808	struct mbuf *m;
809	struct mbuf *top = NULL, **mp = &top;
810	int len;
811
812	if (off < 0 || off > MHLEN)
813		return (NULL);
814
815	while (totlen > 0) {
816		if (top == NULL) {	/* First one, must be PKTHDR */
817			if (totlen + off >= MINCLSIZE) {
818				m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
819				len = MCLBYTES;
820			} else {
821				m = m_gethdr(M_DONTWAIT, MT_DATA);
822				len = MHLEN;
823
824				/* Place initial small packet/header at end of mbuf */
825				if (m && totlen + off + max_linkhdr <= MLEN) {
826					m->m_data += max_linkhdr;
827					len -= max_linkhdr;
828				}
829			}
830			if (m == NULL)
831				return NULL;
832			m->m_pkthdr.rcvif = ifp;
833			m->m_pkthdr.len = totlen;
834		} else {
835			if (totlen + off >= MINCLSIZE) {
836				m = m_getcl(M_DONTWAIT, MT_DATA, 0);
837				len = MCLBYTES;
838			} else {
839				m = m_get(M_DONTWAIT, MT_DATA);
840				len = MLEN;
841			}
842			if (m == NULL) {
843				m_freem(top);
844				return NULL;
845			}
846		}
847		if (off) {
848			m->m_data += off;
849			len -= off;
850			off = 0;
851		}
852		m->m_len = len = min(totlen, len);
853		if (copy)
854			copy(buf, mtod(m, caddr_t), (u_int)len);
855		else
856			bcopy(buf, mtod(m, caddr_t), (u_int)len);
857		buf += len;
858		*mp = m;
859		mp = &m->m_next;
860		totlen -= len;
861	}
862	return (top);
863}
864
865/*
866 * Copy data from a buffer back into the indicated mbuf chain,
867 * starting "off" bytes from the beginning, extending the mbuf
868 * chain if necessary.
869 */
870void
871m_copyback(struct mbuf *m0, int off, int len, c_caddr_t cp)
872{
873	int mlen;
874	struct mbuf *m = m0, *n;
875	int totlen = 0;
876
877	if (m0 == NULL)
878		return;
879	while (off > (mlen = m->m_len)) {
880		off -= mlen;
881		totlen += mlen;
882		if (m->m_next == NULL) {
883			n = m_get(M_DONTWAIT, m->m_type);
884			if (n == NULL)
885				goto out;
886			bzero(mtod(n, caddr_t), MLEN);
887			n->m_len = min(MLEN, len + off);
888			m->m_next = n;
889		}
890		m = m->m_next;
891	}
892	while (len > 0) {
893		mlen = min (m->m_len - off, len);
894		bcopy(cp, off + mtod(m, caddr_t), (u_int)mlen);
895		cp += mlen;
896		len -= mlen;
897		mlen += off;
898		off = 0;
899		totlen += mlen;
900		if (len == 0)
901			break;
902		if (m->m_next == NULL) {
903			n = m_get(M_DONTWAIT, m->m_type);
904			if (n == NULL)
905				break;
906			n->m_len = min(MLEN, len);
907			m->m_next = n;
908		}
909		m = m->m_next;
910	}
911out:	if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
912		m->m_pkthdr.len = totlen;
913}
914
915/*
916 * Apply function f to the data in an mbuf chain starting "off" bytes from
917 * the beginning, continuing for "len" bytes.
918 */
919int
920m_apply(struct mbuf *m, int off, int len,
921    int (*f)(void *, void *, u_int), void *arg)
922{
923	u_int count;
924	int rval;
925
926	KASSERT(off >= 0, ("m_apply, negative off %d", off));
927	KASSERT(len >= 0, ("m_apply, negative len %d", len));
928	while (off > 0) {
929		KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
930		if (off < m->m_len)
931			break;
932		off -= m->m_len;
933		m = m->m_next;
934	}
935	while (len > 0) {
936		KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
937		count = min(m->m_len - off, len);
938		rval = (*f)(arg, mtod(m, caddr_t) + off, count);
939		if (rval)
940			return (rval);
941		len -= count;
942		off = 0;
943		m = m->m_next;
944	}
945	return (0);
946}
947
948/*
949 * Return a pointer to mbuf/offset of location in mbuf chain.
950 */
951struct mbuf *
952m_getptr(struct mbuf *m, int loc, int *off)
953{
954
955	while (loc >= 0) {
956		/* Normal end of search. */
957		if (m->m_len > loc) {
958			*off = loc;
959			return (m);
960		} else {
961			loc -= m->m_len;
962			if (m->m_next == NULL) {
963				if (loc == 0) {
964					/* Point at the end of valid data. */
965					*off = m->m_len;
966					return (m);
967				}
968				return (NULL);
969			}
970			m = m->m_next;
971		}
972	}
973	return (NULL);
974}
975
976void
977m_print(const struct mbuf *m)
978{
979	int len;
980	const struct mbuf *m2;
981
982	len = m->m_pkthdr.len;
983	m2 = m;
984	while (len) {
985		printf("%p %*D\n", m2, m2->m_len, (u_char *)m2->m_data, "-");
986		len -= m2->m_len;
987		m2 = m2->m_next;
988	}
989	return;
990}
991
992u_int
993m_fixhdr(struct mbuf *m0)
994{
995	u_int len;
996
997	len = m_length(m0, NULL);
998	m0->m_pkthdr.len = len;
999	return (len);
1000}
1001
1002u_int
1003m_length(struct mbuf *m0, struct mbuf **last)
1004{
1005	struct mbuf *m;
1006	u_int len;
1007
1008	len = 0;
1009	for (m = m0; m != NULL; m = m->m_next) {
1010		len += m->m_len;
1011		if (m->m_next == NULL)
1012			break;
1013	}
1014	if (last != NULL)
1015		*last = m;
1016	return (len);
1017}
1018
1019/*
1020 * Defragment a mbuf chain, returning the shortest possible
1021 * chain of mbufs and clusters.  If allocation fails and
1022 * this cannot be completed, NULL will be returned, but
1023 * the passed in chain will be unchanged.  Upon success,
1024 * the original chain will be freed, and the new chain
1025 * will be returned.
1026 *
1027 * If a non-packet header is passed in, the original
1028 * mbuf (chain?) will be returned unharmed.
1029 */
1030struct mbuf *
1031m_defrag(struct mbuf *m0, int how)
1032{
1033	struct mbuf *m_new = NULL, *m_final = NULL;
1034	int progress = 0, length;
1035
1036	if (!(m0->m_flags & M_PKTHDR))
1037		return (m0);
1038
1039	m_fixhdr(m0); /* Needed sanity check */
1040
1041#ifdef MBUF_STRESS_TEST
1042	if (m_defragrandomfailures) {
1043		int temp = arc4random() & 0xff;
1044		if (temp == 0xba)
1045			goto nospace;
1046	}
1047#endif
1048
1049	if (m0->m_pkthdr.len > MHLEN)
1050		m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1051	else
1052		m_final = m_gethdr(how, MT_DATA);
1053
1054	if (m_final == NULL)
1055		goto nospace;
1056
1057	if (m_dup_pkthdr(m_final, m0, how) == 0)
1058		goto nospace;
1059
1060	m_new = m_final;
1061
1062	while (progress < m0->m_pkthdr.len) {
1063		length = m0->m_pkthdr.len - progress;
1064		if (length > MCLBYTES)
1065			length = MCLBYTES;
1066
1067		if (m_new == NULL) {
1068			if (length > MLEN)
1069				m_new = m_getcl(how, MT_DATA, 0);
1070			else
1071				m_new = m_get(how, MT_DATA);
1072			if (m_new == NULL)
1073				goto nospace;
1074		}
1075
1076		m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1077		progress += length;
1078		m_new->m_len = length;
1079		if (m_new != m_final)
1080			m_cat(m_final, m_new);
1081		m_new = NULL;
1082	}
1083#ifdef MBUF_STRESS_TEST
1084	if (m0->m_next == NULL)
1085		m_defraguseless++;
1086#endif
1087	m_freem(m0);
1088	m0 = m_final;
1089#ifdef MBUF_STRESS_TEST
1090	m_defragpackets++;
1091	m_defragbytes += m0->m_pkthdr.len;
1092#endif
1093	return (m0);
1094nospace:
1095#ifdef MBUF_STRESS_TEST
1096	m_defragfailure++;
1097#endif
1098	if (m_new)
1099		m_free(m_new);
1100	if (m_final)
1101		m_freem(m_final);
1102	return (NULL);
1103}
1104
1105#ifdef MBUF_STRESS_TEST
1106
1107/*
1108 * Fragment an mbuf chain.  There's no reason you'd ever want to do
1109 * this in normal usage, but it's great for stress testing various
1110 * mbuf consumers.
1111 *
1112 * If fragmentation is not possible, the original chain will be
1113 * returned.
1114 *
1115 * Possible length values:
1116 * 0	 no fragmentation will occur
1117 * > 0	each fragment will be of the specified length
1118 * -1	each fragment will be the same random value in length
1119 * -2	each fragment's length will be entirely random
1120 * (Random values range from 1 to 256)
1121 */
1122struct mbuf *
1123m_fragment(struct mbuf *m0, int how, int length)
1124{
1125	struct mbuf *m_new = NULL, *m_final = NULL;
1126	int progress = 0;
1127
1128	if (!(m0->m_flags & M_PKTHDR))
1129		return (m0);
1130
1131	if ((length == 0) || (length < -2))
1132		return (m0);
1133
1134	m_fixhdr(m0); /* Needed sanity check */
1135
1136	m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1137
1138	if (m_final == NULL)
1139		goto nospace;
1140
1141	if (m_dup_pkthdr(m_final, m0, how) == 0)
1142		goto nospace;
1143
1144	m_new = m_final;
1145
1146	if (length == -1)
1147		length = 1 + (arc4random() & 255);
1148
1149	while (progress < m0->m_pkthdr.len) {
1150		int fraglen;
1151
1152		if (length > 0)
1153			fraglen = length;
1154		else
1155			fraglen = 1 + (arc4random() & 255);
1156		if (fraglen > m0->m_pkthdr.len - progress)
1157			fraglen = m0->m_pkthdr.len - progress;
1158
1159		if (fraglen > MCLBYTES)
1160			fraglen = MCLBYTES;
1161
1162		if (m_new == NULL) {
1163			m_new = m_getcl(how, MT_DATA, 0);
1164			if (m_new == NULL)
1165				goto nospace;
1166		}
1167
1168		m_copydata(m0, progress, fraglen, mtod(m_new, caddr_t));
1169		progress += fraglen;
1170		m_new->m_len = fraglen;
1171		if (m_new != m_final)
1172			m_cat(m_final, m_new);
1173		m_new = NULL;
1174	}
1175	m_freem(m0);
1176	m0 = m_final;
1177	return (m0);
1178nospace:
1179	if (m_new)
1180		m_free(m_new);
1181	if (m_final)
1182		m_freem(m_final);
1183	/* Return the original chain on failure */
1184	return (m0);
1185}
1186
1187#endif
1188
1189struct mbuf *
1190m_uiotombuf(struct uio *uio, int how, int len)
1191{
1192	struct mbuf *m_new = NULL, *m_final = NULL;
1193	int progress = 0, error = 0, length, total;
1194
1195	if (len > 0)
1196		total = min(uio->uio_resid, len);
1197	else
1198		total = uio->uio_resid;
1199	if (total > MHLEN)
1200		m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1201	else
1202		m_final = m_gethdr(how, MT_DATA);
1203	if (m_final == NULL)
1204		goto nospace;
1205	m_new = m_final;
1206	while (progress < total) {
1207		length = total - progress;
1208		if (length > MCLBYTES)
1209			length = MCLBYTES;
1210		if (m_new == NULL) {
1211			if (length > MLEN)
1212				m_new = m_getcl(how, MT_DATA, 0);
1213			else
1214				m_new = m_get(how, MT_DATA);
1215			if (m_new == NULL)
1216				goto nospace;
1217		}
1218		error = uiomove(mtod(m_new, void *), length, uio);
1219		if (error)
1220			goto nospace;
1221		progress += length;
1222		m_new->m_len = length;
1223		if (m_new != m_final)
1224			m_cat(m_final, m_new);
1225		m_new = NULL;
1226	}
1227	m_fixhdr(m_final);
1228	return (m_final);
1229nospace:
1230	if (m_new)
1231		m_free(m_new);
1232	if (m_final)
1233		m_freem(m_final);
1234	return (NULL);
1235}
1236