uipc_mbuf.c revision 149643
1139804Simp/*-
21541Srgrimes * Copyright (c) 1982, 1986, 1988, 1991, 1993
31541Srgrimes *	The Regents of the University of California.  All rights reserved.
41541Srgrimes *
51541Srgrimes * Redistribution and use in source and binary forms, with or without
61541Srgrimes * modification, are permitted provided that the following conditions
71541Srgrimes * are met:
81541Srgrimes * 1. Redistributions of source code must retain the above copyright
91541Srgrimes *    notice, this list of conditions and the following disclaimer.
101541Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
111541Srgrimes *    notice, this list of conditions and the following disclaimer in the
121541Srgrimes *    documentation and/or other materials provided with the distribution.
131541Srgrimes * 4. Neither the name of the University nor the names of its contributors
141541Srgrimes *    may be used to endorse or promote products derived from this software
151541Srgrimes *    without specific prior written permission.
161541Srgrimes *
171541Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
181541Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
191541Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
201541Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
211541Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
221541Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
231541Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
241541Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
251541Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
261541Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
271541Srgrimes * SUCH DAMAGE.
281541Srgrimes *
291541Srgrimes *	@(#)uipc_mbuf.c	8.2 (Berkeley) 1/4/94
301541Srgrimes */
311541Srgrimes
32116182Sobrien#include <sys/cdefs.h>
33116182Sobrien__FBSDID("$FreeBSD: head/sys/kern/uipc_mbuf.c 149643 2005-08-30 20:07:49Z andre $");
34116182Sobrien
35101007Srwatson#include "opt_mac.h"
3677572Sobrien#include "opt_param.h"
37113490Ssilby#include "opt_mbuf_stress_test.h"
38101007Srwatson
391541Srgrimes#include <sys/param.h>
401541Srgrimes#include <sys/systm.h>
4176166Smarkm#include <sys/kernel.h>
42125296Ssilby#include <sys/limits.h>
4376166Smarkm#include <sys/lock.h>
44101173Srwatson#include <sys/mac.h>
4532036Sbde#include <sys/malloc.h>
461541Srgrimes#include <sys/mbuf.h>
4723081Swollman#include <sys/sysctl.h>
481541Srgrimes#include <sys/domain.h>
491541Srgrimes#include <sys/protosw.h>
50125296Ssilby#include <sys/uio.h>
5176166Smarkm
529759Sbdeint	max_linkhdr;
539759Sbdeint	max_protohdr;
549759Sbdeint	max_hdr;
559759Sbdeint	max_datalen;
56116455Ssilby#ifdef MBUF_STRESS_TEST
57112777Ssilbyint	m_defragpackets;
58112777Ssilbyint	m_defragbytes;
59112777Ssilbyint	m_defraguseless;
60112777Ssilbyint	m_defragfailure;
61113490Ssilbyint	m_defragrandomfailures;
62113490Ssilby#endif
631541Srgrimes
6466475Sbmilekic/*
6566475Sbmilekic * sysctl(8) exported objects
6666475Sbmilekic */
6744078SdfrSYSCTL_DECL(_kern_ipc);
6823081SwollmanSYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RW,
6923081Swollman	   &max_linkhdr, 0, "");
7023081SwollmanSYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RW,
7123081Swollman	   &max_protohdr, 0, "");
7223081SwollmanSYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RW, &max_hdr, 0, "");
7323081SwollmanSYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RW,
7423081Swollman	   &max_datalen, 0, "");
75116455Ssilby#ifdef MBUF_STRESS_TEST
76112777SsilbySYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
77112777Ssilby	   &m_defragpackets, 0, "");
78112777SsilbySYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
79112777Ssilby	   &m_defragbytes, 0, "");
80112777SsilbySYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
81112777Ssilby	   &m_defraguseless, 0, "");
82112777SsilbySYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
83112777Ssilby	   &m_defragfailure, 0, "");
84113490SsilbySYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
85113490Ssilby	   &m_defragrandomfailures, 0, "");
86113490Ssilby#endif
8775112Sbmilekic
881541Srgrimes/*
89129906Sbmilekic * Malloc-type for external ext_buf ref counts.
90129906Sbmilekic */
91141616Sphkstatic MALLOC_DEFINE(M_MBUF, "mbextcnt", "mbuf external ref counts");
92129906Sbmilekic
93129906Sbmilekic/*
94129906Sbmilekic * Allocate a given length worth of mbufs and/or clusters (whatever fits
95129906Sbmilekic * best) and return a pointer to the top of the allocated chain.  If an
96129906Sbmilekic * existing mbuf chain is provided, then we will append the new chain
97129906Sbmilekic * to the existing one but still return the top of the newly allocated
98129906Sbmilekic * chain.
99129906Sbmilekic */
100129906Sbmilekicstruct mbuf *
101129906Sbmilekicm_getm(struct mbuf *m, int len, int how, short type)
102129906Sbmilekic{
103129906Sbmilekic	struct mbuf *mb, *top, *cur, *mtail;
104129906Sbmilekic	int num, rem;
105129906Sbmilekic	int i;
106129906Sbmilekic
107129906Sbmilekic	KASSERT(len >= 0, ("m_getm(): len is < 0"));
108129906Sbmilekic
109129906Sbmilekic	/* If m != NULL, we will append to the end of that chain. */
110129906Sbmilekic	if (m != NULL)
111129906Sbmilekic		for (mtail = m; mtail->m_next != NULL; mtail = mtail->m_next);
112129906Sbmilekic	else
113129906Sbmilekic		mtail = NULL;
114129906Sbmilekic
115129906Sbmilekic	/*
116129906Sbmilekic	 * Calculate how many mbufs+clusters ("packets") we need and how much
117129906Sbmilekic	 * leftover there is after that and allocate the first mbuf+cluster
118129906Sbmilekic	 * if required.
119129906Sbmilekic	 */
120129906Sbmilekic	num = len / MCLBYTES;
121129906Sbmilekic	rem = len % MCLBYTES;
122129906Sbmilekic	top = cur = NULL;
123129906Sbmilekic	if (num > 0) {
124129906Sbmilekic		if ((top = cur = m_getcl(how, type, 0)) == NULL)
125129906Sbmilekic			goto failed;
126130271Smux		top->m_len = 0;
127129906Sbmilekic	}
128129906Sbmilekic	num--;
129129906Sbmilekic
130129906Sbmilekic	for (i = 0; i < num; i++) {
131129906Sbmilekic		mb = m_getcl(how, type, 0);
132129906Sbmilekic		if (mb == NULL)
133129906Sbmilekic			goto failed;
134129906Sbmilekic		mb->m_len = 0;
135129906Sbmilekic		cur = (cur->m_next = mb);
136129906Sbmilekic	}
137129906Sbmilekic	if (rem > 0) {
138129906Sbmilekic		mb = (rem > MINCLSIZE) ?
139129906Sbmilekic		    m_getcl(how, type, 0) : m_get(how, type);
140129906Sbmilekic		if (mb == NULL)
141129906Sbmilekic			goto failed;
142129906Sbmilekic		mb->m_len = 0;
143129906Sbmilekic		if (cur == NULL)
144129906Sbmilekic			top = mb;
145129906Sbmilekic		else
146129906Sbmilekic			cur->m_next = mb;
147129906Sbmilekic	}
148129906Sbmilekic
149129906Sbmilekic	if (mtail != NULL)
150129906Sbmilekic		mtail->m_next = top;
151129906Sbmilekic	return top;
152129906Sbmilekicfailed:
153129906Sbmilekic	if (top != NULL)
154129906Sbmilekic		m_freem(top);
155129906Sbmilekic	return NULL;
156129906Sbmilekic}
157129906Sbmilekic
158129906Sbmilekic/*
159129906Sbmilekic * Free an entire chain of mbufs and associated external buffers, if
160129906Sbmilekic * applicable.
161129906Sbmilekic */
162129906Sbmilekicvoid
163129906Sbmilekicm_freem(struct mbuf *mb)
164129906Sbmilekic{
165129906Sbmilekic
166129906Sbmilekic	while (mb != NULL)
167129906Sbmilekic		mb = m_free(mb);
168129906Sbmilekic}
169129906Sbmilekic
170129906Sbmilekic/*-
171129906Sbmilekic * Configure a provided mbuf to refer to the provided external storage
172129906Sbmilekic * buffer and setup a reference count for said buffer.  If the setting
173129906Sbmilekic * up of the reference count fails, the M_EXT bit will not be set.  If
174129906Sbmilekic * successfull, the M_EXT bit is set in the mbuf's flags.
175129906Sbmilekic *
176129906Sbmilekic * Arguments:
177129906Sbmilekic *    mb     The existing mbuf to which to attach the provided buffer.
178129906Sbmilekic *    buf    The address of the provided external storage buffer.
179129906Sbmilekic *    size   The size of the provided buffer.
180129906Sbmilekic *    freef  A pointer to a routine that is responsible for freeing the
181129906Sbmilekic *           provided external storage buffer.
182129906Sbmilekic *    args   A pointer to an argument structure (of any type) to be passed
183129906Sbmilekic *           to the provided freef routine (may be NULL).
184129906Sbmilekic *    flags  Any other flags to be passed to the provided mbuf.
185129906Sbmilekic *    type   The type that the external storage buffer should be
186129906Sbmilekic *           labeled with.
187129906Sbmilekic *
188129906Sbmilekic * Returns:
189129906Sbmilekic *    Nothing.
190129906Sbmilekic */
191129906Sbmilekicvoid
192129906Sbmilekicm_extadd(struct mbuf *mb, caddr_t buf, u_int size,
193129906Sbmilekic    void (*freef)(void *, void *), void *args, int flags, int type)
194129906Sbmilekic{
195129906Sbmilekic	u_int *ref_cnt = NULL;
196129906Sbmilekic
197129906Sbmilekic	/* XXX Shouldn't be adding EXT_CLUSTER with this API */
198129906Sbmilekic	if (type == EXT_CLUSTER)
199129906Sbmilekic		ref_cnt = (u_int *)uma_find_refcnt(zone_clust,
200129906Sbmilekic		    mb->m_ext.ext_buf);
201129906Sbmilekic	else if (type == EXT_EXTREF)
202143188Salc		ref_cnt = __DEVOLATILE(u_int *, mb->m_ext.ref_cnt);
203129906Sbmilekic	mb->m_ext.ref_cnt = (ref_cnt == NULL) ?
204129906Sbmilekic	    malloc(sizeof(u_int), M_MBUF, M_NOWAIT) : (u_int *)ref_cnt;
205129906Sbmilekic	if (mb->m_ext.ref_cnt != NULL) {
206129906Sbmilekic		*(mb->m_ext.ref_cnt) = 1;
207129906Sbmilekic		mb->m_flags |= (M_EXT | flags);
208129906Sbmilekic		mb->m_ext.ext_buf = buf;
209129906Sbmilekic		mb->m_data = mb->m_ext.ext_buf;
210129906Sbmilekic		mb->m_ext.ext_size = size;
211129906Sbmilekic		mb->m_ext.ext_free = freef;
212129906Sbmilekic		mb->m_ext.ext_args = args;
213129906Sbmilekic		mb->m_ext.ext_type = type;
214129906Sbmilekic        }
215129906Sbmilekic}
216129906Sbmilekic
217129906Sbmilekic/*
218129906Sbmilekic * Non-directly-exported function to clean up after mbufs with M_EXT
219129906Sbmilekic * storage attached to them if the reference count hits 0.
220129906Sbmilekic */
221129906Sbmilekicvoid
222129906Sbmilekicmb_free_ext(struct mbuf *m)
223129906Sbmilekic{
224130289Sbmilekic	u_int cnt;
225141668Sbmilekic	int dofree;
226129906Sbmilekic
227141668Sbmilekic	/* Account for lazy ref count assign. */
228141668Sbmilekic	if (m->m_ext.ref_cnt == NULL)
229141668Sbmilekic		dofree = 1;
230141668Sbmilekic	else
231141668Sbmilekic		dofree = 0;
232141668Sbmilekic
233130289Sbmilekic	/*
234130289Sbmilekic	 * This is tricky.  We need to make sure to decrement the
235130289Sbmilekic	 * refcount in a safe way but to also clean up if we're the
236130289Sbmilekic	 * last reference.  This method seems to do it without race.
237130289Sbmilekic	 */
238141668Sbmilekic	while (dofree == 0) {
239143188Salc		cnt = *(m->m_ext.ref_cnt);
240130289Sbmilekic		if (atomic_cmpset_int(m->m_ext.ref_cnt, cnt, cnt - 1)) {
241141668Sbmilekic			if (cnt == 1)
242141668Sbmilekic				dofree = 1;
243130289Sbmilekic			break;
244129906Sbmilekic		}
245141668Sbmilekic	}
246141668Sbmilekic
247141668Sbmilekic	if (dofree) {
248141668Sbmilekic		/*
249141668Sbmilekic		 * Do the free, should be safe.
250141668Sbmilekic		 */
251141668Sbmilekic		if (m->m_ext.ext_type == EXT_PACKET) {
252141668Sbmilekic			uma_zfree(zone_pack, m);
253141668Sbmilekic			return;
254141668Sbmilekic		} else if (m->m_ext.ext_type == EXT_CLUSTER) {
255141668Sbmilekic			uma_zfree(zone_clust, m->m_ext.ext_buf);
256141668Sbmilekic			m->m_ext.ext_buf = NULL;
257141668Sbmilekic		} else {
258141668Sbmilekic			(*(m->m_ext.ext_free))(m->m_ext.ext_buf,
259141668Sbmilekic			    m->m_ext.ext_args);
260141668Sbmilekic			if (m->m_ext.ext_type != EXT_EXTREF) {
261141668Sbmilekic				if (m->m_ext.ref_cnt != NULL)
262143188Salc					free(__DEVOLATILE(u_int *,
263143188Salc					    m->m_ext.ref_cnt), M_MBUF);
264141668Sbmilekic				m->m_ext.ref_cnt = NULL;
265141668Sbmilekic			}
266141668Sbmilekic			m->m_ext.ext_buf = NULL;
267141668Sbmilekic		}
268141668Sbmilekic	}
269130357Sbmilekic	uma_zfree(zone_mbuf, m);
270129906Sbmilekic}
271129906Sbmilekic
272129906Sbmilekic/*
273149598Sandre * Clean up mbuf (chain) from any tags and packet headers.
274149598Sandre */
275149598Sandrevoid
276149643Sandrem_demote(struct mbuf *m0)
277149598Sandre{
278149598Sandre	struct mbuf *m;
279149598Sandre
280149598Sandre	for (m = all ? m0 : m0->m_next; m != NULL; m = m->m_next) {
281149598Sandre		if (m->m_flags & M_PKTHDR) {
282149598Sandre			m_tag_delete_chain(m, NULL);
283149598Sandre			m->m_flags &= ~M_PKTHDR;
284149598Sandre			bzero(&m->m_pkthdr, sizeof(struct pkthdr));
285149598Sandre		}
286149643Sandre		if (m->m_type == MT_HEADER)
287149598Sandre			m->m_type = MT_DATA;
288149643Sandre		if (m != m0 && m->m_nextpkt != NULL)
289149598Sandre			m->m_nextpkt = NULL;
290149598Sandre		m->m_flags = m->m_flags & (M_EXT|M_EOR|M_RDONLY|M_FREELIST);
291149598Sandre	}
292149598Sandre}
293149598Sandre
294149598Sandre/*
295149599Sandre * Sanity checks on mbuf (chain).
296149599Sandre * Returns 0 bad, 1 good, panic worse.
297149599Sandre * sanitize, 0 run M_SANITY_ACTION, 1 garble things so they blow up later.
298149599Sandre */
299149599Sandreint
300149599Sandrem_sanity(struct mbuf *m0, int sanitize)
301149599Sandre{
302149599Sandre	struct mbuf *m;
303149599Sandre	caddr_t a, b;
304149599Sandre	int pktlen = 0;
305149599Sandre
306149599Sandre#define	M_SANITY_ACTION(s)	return (0)
307149599Sandre/* #define	M_SANITY_ACTION(s)	panic("mbuf %p: " s, m) */
308149599Sandre
309149599Sandre	m = m0;
310149599Sandre	while (m) {
311149599Sandre		/*
312149599Sandre		 * Basic pointer checks.  If any of these fails then some
313149599Sandre		 * unrelated kernel memory before or after us is trashed.
314149599Sandre		 * No way to recover from that.
315149599Sandre		 */
316149599Sandre		a = (m->m_flags & M_EXT ? m->m_ext.ext_buf :
317149599Sandre			(m->m_flags & M_PKTHDR ? (caddr_t)(&m->m_pktdat) :
318149599Sandre			 (caddr_t)(&m->m_dat)) );
319149599Sandre		b = (caddr_t)(a + (m->m_flags & M_EXT ? m->m_ext.ext_size :
320149599Sandre			(m->m_flags & M_PKTHDR ? MHLEN : MLEN)));
321149599Sandre		if ((caddr_t)m->m_data < a)
322149599Sandre			M_SANITY_ACTION("m_data outside mbuf data range left");
323149599Sandre		if ((caddr_t)m->m_data > b)
324149599Sandre			M_SANITY_ACTION("m_data outside mbuf data range right");
325149599Sandre		if ((caddr_t)m->m_data + m->m_len > b)
326149599Sandre			M_SANITY_ACTION("m_data + m_len exeeds mbuf space");
327149599Sandre		if (m->m_flags & M_PKTHDR && m->m_pkthdr.header) {
328149599Sandre			if ((caddr_t)m->m_pkthdr.header < a ||
329149599Sandre			    (caddr_t)m->m_pkthdr.header > b)
330149599Sandre				M_SANITY_ACTION("m_pkthdr.header outside mbuf data range");
331149599Sandre		}
332149599Sandre
333149599Sandre		/* m->m_nextpkt may only be set on first mbuf in chain. */
334149599Sandre		if (m != m0 && m->m_nextpkt) {
335149599Sandre			if (sanitize) {
336149599Sandre				m_freem(m->m_nextpkt);
337149599Sandre				m->m_nextpkt = (struct mbuf *)0xDEADC0DE;
338149599Sandre			} else
339149599Sandre				M_SANITY_ACTION("m->m_nextpkt on in-chain mbuf");
340149599Sandre		}
341149599Sandre
342149599Sandre		/* correct type correlations. */
343149599Sandre		if (m->m_type == MT_HEADER && !(m->m_flags & M_PKTHDR)) {
344149599Sandre			if (sanitize)
345149599Sandre				m->m_type = MT_DATA;
346149599Sandre			else
347149599Sandre				M_SANITY_ACTION("MT_HEADER set but not M_PKTHDR");
348149599Sandre		}
349149599Sandre
350149599Sandre		/* packet length (not mbuf length!) calculation */
351149599Sandre		if (m0->m_flags & M_PKTHDR)
352149599Sandre			pktlen += m->m_len;
353149599Sandre
354149599Sandre		/* m_tags may only be attached to first mbuf in chain. */
355149599Sandre		if (m != m0 && m->m_flags & M_PKTHDR &&
356149599Sandre		    !SLIST_EMPTY(&m->m_pkthdr.tags)) {
357149599Sandre			if (sanitize) {
358149599Sandre				m_tag_delete_chain(m, NULL);
359149599Sandre				/* put in 0xDEADC0DE perhaps? */
360149599Sandre			}
361149599Sandre			else
362149599Sandre				M_SANITY_ACTION("m_tags on in-chain mbuf");
363149599Sandre		}
364149599Sandre
365149599Sandre		/* M_PKTHDR may only be set on first mbuf in chain */
366149599Sandre		if (m != m0 && m->m_flags & M_PKTHDR) {
367149599Sandre			if (sanitize) {
368149599Sandre				bzero(&m->m_pkthdr, sizeof(m->m_pkthdr));
369149599Sandre				m->m_flags &= ~M_PKTHDR;
370149599Sandre				/* put in 0xDEADCODE and leave hdr flag in */
371149599Sandre			} else
372149599Sandre				M_SANITY_ACTION("M_PKTHDR on in-chain mbuf");
373149599Sandre		}
374149599Sandre
375149599Sandre		m = m->m_next;
376149599Sandre	}
377149599Sandre	if (pktlen && pktlen != m0->m_pkthdr.len) {
378149599Sandre		if (sanitize)
379149599Sandre			m0->m_pkthdr.len = 0;
380149599Sandre		else
381149599Sandre			M_SANITY_ACTION("m_pkthdr.len != mbuf chain length");
382149599Sandre	}
383149599Sandre#undef	M_SANITY_ACTION
384149599Sandre
385149599Sandre	return 1;
386149599Sandre}
387149599Sandre
388149599Sandre
389149599Sandre/*
390108466Ssam * "Move" mbuf pkthdr from "from" to "to".
391100960Srwatson * "from" must have M_PKTHDR set, and "to" must be empty.
392100960Srwatson */
393100960Srwatsonvoid
394108466Ssamm_move_pkthdr(struct mbuf *to, struct mbuf *from)
395100960Srwatson{
396100960Srwatson
397100960Srwatson#if 0
398108466Ssam	/* see below for why these are not enabled */
399113255Sdes	M_ASSERTPKTHDR(to);
400113487Srwatson	/* Note: with MAC, this may not be a good assertion. */
401108466Ssam	KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags),
402108466Ssam	    ("m_move_pkthdr: to has tags"));
403100960Srwatson#endif
404101007Srwatson#ifdef MAC
405113487Srwatson	/*
406113487Srwatson	 * XXXMAC: It could be this should also occur for non-MAC?
407113487Srwatson	 */
408101007Srwatson	if (to->m_flags & M_PKTHDR)
409113487Srwatson		m_tag_delete_chain(to, NULL);
410101007Srwatson#endif
411143302Ssam	to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
412143302Ssam	if ((to->m_flags & M_EXT) == 0)
413143302Ssam		to->m_data = to->m_pktdat;
414108466Ssam	to->m_pkthdr = from->m_pkthdr;		/* especially tags */
415108466Ssam	SLIST_INIT(&from->m_pkthdr.tags);	/* purge tags from src */
416108466Ssam	from->m_flags &= ~M_PKTHDR;
417108466Ssam}
418108466Ssam
419108466Ssam/*
420108466Ssam * Duplicate "from"'s mbuf pkthdr in "to".
421108466Ssam * "from" must have M_PKTHDR set, and "to" must be empty.
422108466Ssam * In particular, this does a deep copy of the packet tags.
423108466Ssam */
424108466Ssamint
425108466Ssamm_dup_pkthdr(struct mbuf *to, struct mbuf *from, int how)
426108466Ssam{
427108466Ssam
428108466Ssam#if 0
429108466Ssam	/*
430108466Ssam	 * The mbuf allocator only initializes the pkthdr
431108466Ssam	 * when the mbuf is allocated with MGETHDR. Many users
432108466Ssam	 * (e.g. m_copy*, m_prepend) use MGET and then
433108466Ssam	 * smash the pkthdr as needed causing these
434108466Ssam	 * assertions to trip.  For now just disable them.
435108466Ssam	 */
436113255Sdes	M_ASSERTPKTHDR(to);
437113487Srwatson	/* Note: with MAC, this may not be a good assertion. */
438108466Ssam	KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags), ("m_dup_pkthdr: to has tags"));
439108466Ssam#endif
440132488Salfred	MBUF_CHECKSLEEP(how);
441108466Ssam#ifdef MAC
442108466Ssam	if (to->m_flags & M_PKTHDR)
443113487Srwatson		m_tag_delete_chain(to, NULL);
444108466Ssam#endif
445112733Ssilby	to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
446112733Ssilby	if ((to->m_flags & M_EXT) == 0)
447112733Ssilby		to->m_data = to->m_pktdat;
448100960Srwatson	to->m_pkthdr = from->m_pkthdr;
449108466Ssam	SLIST_INIT(&to->m_pkthdr.tags);
450113480Srwatson	return (m_tag_copy_chain(to, from, MBTOM(how)));
451100960Srwatson}
452100960Srwatson
453100960Srwatson/*
4541541Srgrimes * Lesser-used path for M_PREPEND:
4551541Srgrimes * allocate new mbuf to prepend to chain,
4561541Srgrimes * copy junk along.
4571541Srgrimes */
4581541Srgrimesstruct mbuf *
45972356Sbmilekicm_prepend(struct mbuf *m, int len, int how)
4601541Srgrimes{
4611541Srgrimes	struct mbuf *mn;
4621541Srgrimes
463117770Ssilby	if (m->m_flags & M_PKTHDR)
464117770Ssilby		MGETHDR(mn, how, m->m_type);
465117770Ssilby	else
466117770Ssilby		MGET(mn, how, m->m_type);
46772356Sbmilekic	if (mn == NULL) {
4681541Srgrimes		m_freem(m);
46972356Sbmilekic		return (NULL);
4701541Srgrimes	}
471113487Srwatson	if (m->m_flags & M_PKTHDR)
472108466Ssam		M_MOVE_PKTHDR(mn, m);
4731541Srgrimes	mn->m_next = m;
4741541Srgrimes	m = mn;
4751541Srgrimes	if (len < MHLEN)
4761541Srgrimes		MH_ALIGN(m, len);
4771541Srgrimes	m->m_len = len;
4781541Srgrimes	return (m);
4791541Srgrimes}
4801541Srgrimes
4811541Srgrimes/*
4821541Srgrimes * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
4831541Srgrimes * continuing for "len" bytes.  If len is M_COPYALL, copy to end of mbuf.
484111119Simp * The wait parameter is a choice of M_TRYWAIT/M_DONTWAIT from caller.
48554002Sarchie * Note that the copy is read-only, because clusters are not copied,
48654002Sarchie * only their reference counts are incremented.
4871541Srgrimes */
4881541Srgrimesstruct mbuf *
48972356Sbmilekicm_copym(struct mbuf *m, int off0, int len, int wait)
4901541Srgrimes{
49172356Sbmilekic	struct mbuf *n, **np;
49272356Sbmilekic	int off = off0;
4931541Srgrimes	struct mbuf *top;
4941541Srgrimes	int copyhdr = 0;
4951541Srgrimes
49652201Salfred	KASSERT(off >= 0, ("m_copym, negative off %d", off));
49752201Salfred	KASSERT(len >= 0, ("m_copym, negative len %d", len));
498132488Salfred	MBUF_CHECKSLEEP(wait);
4991541Srgrimes	if (off == 0 && m->m_flags & M_PKTHDR)
5001541Srgrimes		copyhdr = 1;
5011541Srgrimes	while (off > 0) {
50252201Salfred		KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
5031541Srgrimes		if (off < m->m_len)
5041541Srgrimes			break;
5051541Srgrimes		off -= m->m_len;
5061541Srgrimes		m = m->m_next;
5071541Srgrimes	}
5081541Srgrimes	np = &top;
5091541Srgrimes	top = 0;
5101541Srgrimes	while (len > 0) {
51172356Sbmilekic		if (m == NULL) {
51252201Salfred			KASSERT(len == M_COPYALL,
51352201Salfred			    ("m_copym, length > size of mbuf chain"));
5141541Srgrimes			break;
5151541Srgrimes		}
516117770Ssilby		if (copyhdr)
517117770Ssilby			MGETHDR(n, wait, m->m_type);
518117770Ssilby		else
519117770Ssilby			MGET(n, wait, m->m_type);
5201541Srgrimes		*np = n;
52172356Sbmilekic		if (n == NULL)
5221541Srgrimes			goto nospace;
5231541Srgrimes		if (copyhdr) {
524108466Ssam			if (!m_dup_pkthdr(n, m, wait))
525108466Ssam				goto nospace;
5261541Srgrimes			if (len == M_COPYALL)
5271541Srgrimes				n->m_pkthdr.len -= off0;
5281541Srgrimes			else
5291541Srgrimes				n->m_pkthdr.len = len;
5301541Srgrimes			copyhdr = 0;
5311541Srgrimes		}
5321541Srgrimes		n->m_len = min(len, m->m_len - off);
5331541Srgrimes		if (m->m_flags & M_EXT) {
5341541Srgrimes			n->m_data = m->m_data + off;
5351541Srgrimes			n->m_ext = m->m_ext;
5361541Srgrimes			n->m_flags |= M_EXT;
53764837Sdwmalone			MEXT_ADD_REF(m);
538141668Sbmilekic			n->m_ext.ref_cnt = m->m_ext.ref_cnt;
5391541Srgrimes		} else
5401541Srgrimes			bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
541103569Sbmilekic			    (u_int)n->m_len);
5421541Srgrimes		if (len != M_COPYALL)
5431541Srgrimes			len -= n->m_len;
5441541Srgrimes		off = 0;
5451541Srgrimes		m = m->m_next;
5461541Srgrimes		np = &n->m_next;
5471541Srgrimes	}
54878592Sbmilekic	if (top == NULL)
54978592Sbmilekic		mbstat.m_mcfail++;	/* XXX: No consistency. */
55078592Sbmilekic
5511541Srgrimes	return (top);
5521541Srgrimesnospace:
5531541Srgrimes	m_freem(top);
55478592Sbmilekic	mbstat.m_mcfail++;	/* XXX: No consistency. */
55572356Sbmilekic	return (NULL);
5561541Srgrimes}
5571541Srgrimes
5581541Srgrimes/*
559149602Sandre * Returns mbuf chain with new head for the prepending case.
560149602Sandre * Copies from mbuf (chain) n from off for len to mbuf (chain) m
561149602Sandre * either prepending or appending the data.
562149602Sandre * The resulting mbuf (chain) m is fully writeable.
563149602Sandre * m is destination (is made writeable)
564149602Sandre * n is source, off is offset in source, len is len from offset
565149602Sandre * dir, 0 append, 1 prepend
566149602Sandre * how, wait or nowait
567149602Sandre */
568149602Sandre
569149602Sandrestatic int
570149602Sandrem_bcopyxxx(void *s, void *t, u_int len)
571149602Sandre{
572149602Sandre	bcopy(s, t, (size_t)len);
573149602Sandre	return 0;
574149602Sandre}
575149602Sandre
576149602Sandrestruct mbuf *
577149602Sandrem_copymdata(struct mbuf *m, struct mbuf *n, int off, int len,
578149602Sandre    int prep, int how)
579149602Sandre{
580149602Sandre	struct mbuf *mm, *x, *z;
581149602Sandre	caddr_t p;
582149602Sandre	int i, mlen, nlen = 0;
583149602Sandre	caddr_t buf[MLEN];
584149602Sandre
585149602Sandre	KASSERT(m != NULL && n != NULL, ("m_copymdata, no target or source"));
586149602Sandre	KASSERT(off >= 0, ("m_copymdata, negative off %d", off));
587149602Sandre	KASSERT(len >= 0, ("m_copymdata, negative len %d", len));
588149602Sandre	KASSERT(prep == 0 || prep == 1, ("m_copymdata, unknown direction %d", prep));
589149602Sandre
590149602Sandre	/* Make sure environment is sane. */
591149602Sandre	for (z = m; z != NULL; z = z->m_next) {
592149602Sandre		mlen += z->m_len;
593149602Sandre		if (!M_WRITABLE(z)) {
594149602Sandre			/* Make clusters writeable. */
595149602Sandre			if (z->m_flags & M_RDONLY)
596149602Sandre				return NULL;	/* Can't handle ext ref. */
597149602Sandre			x = m_getcl(how, MT_DATA, 0);
598149602Sandre			if (!x)
599149602Sandre				return NULL;
600149602Sandre			bcopy(z->m_ext.ext_buf, x->m_ext.ext_buf, x->m_ext.ext_size);
601149602Sandre			p = x->m_ext.ext_buf + (z->m_data - z->m_ext.ext_buf);
602149602Sandre			MEXT_REM_REF(z);	/* XXX */
603149602Sandre			z->m_data = p;
604149602Sandre			x->m_flags &= ~M_EXT;
605149602Sandre			(void)m_free(x);
606149602Sandre		}
607149602Sandre	}
608149602Sandre	mm = prep ? m : z;
609149602Sandre	for (z = n; z != NULL; z = z->m_next)
610149602Sandre		nlen += z->m_len;
611149602Sandre	if (len == M_COPYALL)
612149602Sandre		len = nlen - off;
613149602Sandre	if (off + len > nlen || len < 1)
614149602Sandre		return NULL;
615149602Sandre
616149602Sandre	/*
617149602Sandre	 * Append/prepend the data.  Allocating mbufs as necessary.
618149602Sandre	 */
619149602Sandre	/* Shortcut if enough free space in first/last mbuf. */
620149602Sandre	if (!prep && M_TRAILINGSPACE(mm) >= len) {
621149602Sandre		m_apply(n, off, len, m_bcopyxxx, mtod(mm, caddr_t) +
622149602Sandre			 mm->m_len);
623149602Sandre		mm->m_len += len;
624149602Sandre		mm->m_pkthdr.len += len;
625149602Sandre		return m;
626149602Sandre	}
627149602Sandre	if (prep && M_LEADINGSPACE(mm) >= len) {
628149602Sandre		mm->m_data = mtod(mm, caddr_t) - len;
629149602Sandre		m_apply(n, off, len, m_bcopyxxx, mtod(mm, caddr_t));
630149602Sandre		mm->m_len += len;
631149602Sandre		mm->m_pkthdr.len += len;
632149602Sandre		return mm;
633149602Sandre	}
634149602Sandre
635149602Sandre	/* Expand first/last mbuf to cluster if possible. */
636149602Sandre	if (!prep && !(mm->m_flags & M_EXT) && len > M_TRAILINGSPACE(mm)) {
637149602Sandre		bcopy(mm->m_data, &buf, mm->m_len);
638149602Sandre		m_clget(mm, how);
639149602Sandre		if (!(mm->m_flags & M_EXT))
640149602Sandre			return NULL;
641149602Sandre		bcopy(&buf, mm->m_ext.ext_buf, mm->m_len);
642149602Sandre		mm->m_data = mm->m_ext.ext_buf;
643149602Sandre		mm->m_pkthdr.header = NULL;
644149602Sandre	}
645149602Sandre	if (prep && !(mm->m_flags & M_EXT) && len > M_LEADINGSPACE(mm)) {
646149602Sandre		bcopy(mm->m_data, &buf, mm->m_len);
647149602Sandre		m_clget(mm, how);
648149602Sandre		if (!(mm->m_flags & M_EXT))
649149602Sandre			return NULL;
650149602Sandre		bcopy(&buf, (caddr_t *)mm->m_ext.ext_buf +
651149602Sandre		       mm->m_ext.ext_size - mm->m_len, mm->m_len);
652149602Sandre		mm->m_data = (caddr_t)mm->m_ext.ext_buf +
653149602Sandre			      mm->m_ext.ext_size - mm->m_len;
654149602Sandre		mm->m_pkthdr.header = NULL;
655149602Sandre	}
656149602Sandre
657149602Sandre	/* Append/prepend as many mbuf (clusters) as necessary to fit len. */
658149602Sandre	if (!prep && len > M_TRAILINGSPACE(mm)) {
659149602Sandre		if (!m_getm(mm, len - M_TRAILINGSPACE(mm), how, MT_DATA))
660149602Sandre			return NULL;
661149602Sandre	}
662149602Sandre	if (prep && len > M_LEADINGSPACE(mm)) {
663149602Sandre		if (!(z = m_getm(NULL, len - M_LEADINGSPACE(mm), how, MT_DATA)))
664149602Sandre			return NULL;
665149602Sandre		i = 0;
666149602Sandre		for (x = z; x != NULL; x = x->m_next) {
667149602Sandre			i += x->m_flags & M_EXT ? x->m_ext.ext_size :
668149602Sandre			      (x->m_flags & M_PKTHDR ? MHLEN : MLEN);
669149602Sandre			if (!x->m_next)
670149602Sandre				break;
671149602Sandre		}
672149602Sandre		z->m_data += i - len;
673149602Sandre		m_move_pkthdr(mm, z);
674149602Sandre		x->m_next = mm;
675149602Sandre		mm = z;
676149602Sandre	}
677149602Sandre
678149602Sandre	/* Seek to start position in source mbuf. Optimization for long chains. */
679149602Sandre	while (off > 0) {
680149602Sandre		if (off < n->m_len)
681149602Sandre			break;
682149602Sandre		off -= n->m_len;
683149602Sandre		n = n->m_next;
684149602Sandre	}
685149602Sandre
686149602Sandre	/* Copy data into target mbuf. */
687149602Sandre	z = mm;
688149602Sandre	while (len > 0) {
689149602Sandre		KASSERT(z != NULL, ("m_copymdata, falling off target edge"));
690149602Sandre		i = M_TRAILINGSPACE(z);
691149602Sandre		m_apply(n, off, i, m_bcopyxxx, mtod(z, caddr_t) + z->m_len);
692149602Sandre		z->m_len += i;
693149602Sandre		/* fixup pkthdr.len if necessary */
694149602Sandre		if ((prep ? mm : m)->m_flags & M_PKTHDR)
695149602Sandre			(prep ? mm : m)->m_pkthdr.len += i;
696149602Sandre		off += i;
697149602Sandre		len -= i;
698149602Sandre		z = z->m_next;
699149602Sandre	}
700149602Sandre	return (prep ? mm : m);
701149602Sandre}
702149602Sandre
703149602Sandre/*
70415689Swollman * Copy an entire packet, including header (which must be present).
70515689Swollman * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
70654002Sarchie * Note that the copy is read-only, because clusters are not copied,
70754002Sarchie * only their reference counts are incremented.
70872750Sluigi * Preserve alignment of the first mbuf so if the creator has left
70972750Sluigi * some room at the beginning (e.g. for inserting protocol headers)
71072750Sluigi * the copies still have the room available.
71115689Swollman */
71215689Swollmanstruct mbuf *
71372356Sbmilekicm_copypacket(struct mbuf *m, int how)
71415689Swollman{
71515689Swollman	struct mbuf *top, *n, *o;
71615689Swollman
717132488Salfred	MBUF_CHECKSLEEP(how);
71815689Swollman	MGET(n, how, m->m_type);
71915689Swollman	top = n;
72072356Sbmilekic	if (n == NULL)
72115689Swollman		goto nospace;
72215689Swollman
723108466Ssam	if (!m_dup_pkthdr(n, m, how))
724108466Ssam		goto nospace;
72515689Swollman	n->m_len = m->m_len;
72615689Swollman	if (m->m_flags & M_EXT) {
72715689Swollman		n->m_data = m->m_data;
72815689Swollman		n->m_ext = m->m_ext;
72915689Swollman		n->m_flags |= M_EXT;
73064837Sdwmalone		MEXT_ADD_REF(m);
731141668Sbmilekic		n->m_ext.ref_cnt = m->m_ext.ref_cnt;
73215689Swollman	} else {
73372750Sluigi		n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
73415689Swollman		bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
73515689Swollman	}
73615689Swollman
73715689Swollman	m = m->m_next;
73815689Swollman	while (m) {
73915689Swollman		MGET(o, how, m->m_type);
74072356Sbmilekic		if (o == NULL)
74115689Swollman			goto nospace;
74215689Swollman
74315689Swollman		n->m_next = o;
74415689Swollman		n = n->m_next;
74515689Swollman
74615689Swollman		n->m_len = m->m_len;
74715689Swollman		if (m->m_flags & M_EXT) {
74815689Swollman			n->m_data = m->m_data;
74915689Swollman			n->m_ext = m->m_ext;
75015689Swollman			n->m_flags |= M_EXT;
75164837Sdwmalone			MEXT_ADD_REF(m);
752141668Sbmilekic			n->m_ext.ref_cnt = m->m_ext.ref_cnt;
75315689Swollman		} else {
75415689Swollman			bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
75515689Swollman		}
75615689Swollman
75715689Swollman		m = m->m_next;
75815689Swollman	}
75915689Swollman	return top;
76015689Swollmannospace:
76115689Swollman	m_freem(top);
76278592Sbmilekic	mbstat.m_mcfail++;	/* XXX: No consistency. */
76372356Sbmilekic	return (NULL);
76415689Swollman}
76515689Swollman
76615689Swollman/*
7671541Srgrimes * Copy data from an mbuf chain starting "off" bytes from the beginning,
7681541Srgrimes * continuing for "len" bytes, into the indicated buffer.
7691541Srgrimes */
7701549Srgrimesvoid
77181907Sjulianm_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
7721541Srgrimes{
773103569Sbmilekic	u_int count;
7741541Srgrimes
77552201Salfred	KASSERT(off >= 0, ("m_copydata, negative off %d", off));
77652201Salfred	KASSERT(len >= 0, ("m_copydata, negative len %d", len));
7771541Srgrimes	while (off > 0) {
77852201Salfred		KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
7791541Srgrimes		if (off < m->m_len)
7801541Srgrimes			break;
7811541Srgrimes		off -= m->m_len;
7821541Srgrimes		m = m->m_next;
7831541Srgrimes	}
7841541Srgrimes	while (len > 0) {
78552201Salfred		KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
7861541Srgrimes		count = min(m->m_len - off, len);
7871541Srgrimes		bcopy(mtod(m, caddr_t) + off, cp, count);
7881541Srgrimes		len -= count;
7891541Srgrimes		cp += count;
7901541Srgrimes		off = 0;
7911541Srgrimes		m = m->m_next;
7921541Srgrimes	}
7931541Srgrimes}
7941541Srgrimes
7951541Srgrimes/*
79654002Sarchie * Copy a packet header mbuf chain into a completely new chain, including
79754002Sarchie * copying any mbuf clusters.  Use this instead of m_copypacket() when
79854002Sarchie * you need a writable copy of an mbuf chain.
79954002Sarchie */
80054002Sarchiestruct mbuf *
80172356Sbmilekicm_dup(struct mbuf *m, int how)
80254002Sarchie{
80354002Sarchie	struct mbuf **p, *top = NULL;
80454002Sarchie	int remain, moff, nsize;
80554002Sarchie
806132488Salfred	MBUF_CHECKSLEEP(how);
80754002Sarchie	/* Sanity check */
80854002Sarchie	if (m == NULL)
80972356Sbmilekic		return (NULL);
810113255Sdes	M_ASSERTPKTHDR(m);
81154002Sarchie
81254002Sarchie	/* While there's more data, get a new mbuf, tack it on, and fill it */
81354002Sarchie	remain = m->m_pkthdr.len;
81454002Sarchie	moff = 0;
81554002Sarchie	p = &top;
81654002Sarchie	while (remain > 0 || top == NULL) {	/* allow m->m_pkthdr.len == 0 */
81754002Sarchie		struct mbuf *n;
81854002Sarchie
81954002Sarchie		/* Get the next new mbuf */
820129906Sbmilekic		if (remain >= MINCLSIZE) {
821129906Sbmilekic			n = m_getcl(how, m->m_type, 0);
822129906Sbmilekic			nsize = MCLBYTES;
823129906Sbmilekic		} else {
824129906Sbmilekic			n = m_get(how, m->m_type);
825129906Sbmilekic			nsize = MLEN;
826129906Sbmilekic		}
82754002Sarchie		if (n == NULL)
82854002Sarchie			goto nospace;
829129906Sbmilekic
830129906Sbmilekic		if (top == NULL) {		/* First one, must be PKTHDR */
831129906Sbmilekic			if (!m_dup_pkthdr(n, m, how)) {
832129906Sbmilekic				m_free(n);
833108466Ssam				goto nospace;
834129906Sbmilekic			}
83554002Sarchie			nsize = MHLEN;
83654002Sarchie		}
83754002Sarchie		n->m_len = 0;
83854002Sarchie
83954002Sarchie		/* Link it into the new chain */
84054002Sarchie		*p = n;
84154002Sarchie		p = &n->m_next;
84254002Sarchie
84354002Sarchie		/* Copy data from original mbuf(s) into new mbuf */
84454002Sarchie		while (n->m_len < nsize && m != NULL) {
84554002Sarchie			int chunk = min(nsize - n->m_len, m->m_len - moff);
84654002Sarchie
84754002Sarchie			bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
84854002Sarchie			moff += chunk;
84954002Sarchie			n->m_len += chunk;
85054002Sarchie			remain -= chunk;
85154002Sarchie			if (moff == m->m_len) {
85254002Sarchie				m = m->m_next;
85354002Sarchie				moff = 0;
85454002Sarchie			}
85554002Sarchie		}
85654002Sarchie
85754002Sarchie		/* Check correct total mbuf length */
85854002Sarchie		KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
85987594Sobrien		    	("%s: bogus m_pkthdr.len", __func__));
86054002Sarchie	}
86154002Sarchie	return (top);
86254002Sarchie
86354002Sarchienospace:
86454002Sarchie	m_freem(top);
86578592Sbmilekic	mbstat.m_mcfail++;	/* XXX: No consistency. */
86672356Sbmilekic	return (NULL);
86754002Sarchie}
86854002Sarchie
86954002Sarchie/*
8701541Srgrimes * Concatenate mbuf chain n to m.
8711541Srgrimes * Both chains must be of the same type (e.g. MT_DATA).
8721541Srgrimes * Any m_pkthdr is not updated.
8731541Srgrimes */
8741549Srgrimesvoid
87572356Sbmilekicm_cat(struct mbuf *m, struct mbuf *n)
8761541Srgrimes{
8771541Srgrimes	while (m->m_next)
8781541Srgrimes		m = m->m_next;
8791541Srgrimes	while (n) {
8801541Srgrimes		if (m->m_flags & M_EXT ||
8811541Srgrimes		    m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
8821541Srgrimes			/* just join the two chains */
8831541Srgrimes			m->m_next = n;
8841541Srgrimes			return;
8851541Srgrimes		}
8861541Srgrimes		/* splat the data from one into the other */
8871541Srgrimes		bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
8881541Srgrimes		    (u_int)n->m_len);
8891541Srgrimes		m->m_len += n->m_len;
8901541Srgrimes		n = m_free(n);
8911541Srgrimes	}
8921541Srgrimes}
8931541Srgrimes
8941549Srgrimesvoid
89572356Sbmilekicm_adj(struct mbuf *mp, int req_len)
8961541Srgrimes{
89772356Sbmilekic	int len = req_len;
89872356Sbmilekic	struct mbuf *m;
89972356Sbmilekic	int count;
9001541Srgrimes
9011541Srgrimes	if ((m = mp) == NULL)
9021541Srgrimes		return;
9031541Srgrimes	if (len >= 0) {
9041541Srgrimes		/*
9051541Srgrimes		 * Trim from head.
9061541Srgrimes		 */
9071541Srgrimes		while (m != NULL && len > 0) {
9081541Srgrimes			if (m->m_len <= len) {
9091541Srgrimes				len -= m->m_len;
9101541Srgrimes				m->m_len = 0;
9111541Srgrimes				m = m->m_next;
9121541Srgrimes			} else {
9131541Srgrimes				m->m_len -= len;
9141541Srgrimes				m->m_data += len;
9151541Srgrimes				len = 0;
9161541Srgrimes			}
9171541Srgrimes		}
9181541Srgrimes		m = mp;
9191541Srgrimes		if (mp->m_flags & M_PKTHDR)
9201541Srgrimes			m->m_pkthdr.len -= (req_len - len);
9211541Srgrimes	} else {
9221541Srgrimes		/*
9231541Srgrimes		 * Trim from tail.  Scan the mbuf chain,
9241541Srgrimes		 * calculating its length and finding the last mbuf.
9251541Srgrimes		 * If the adjustment only affects this mbuf, then just
9261541Srgrimes		 * adjust and return.  Otherwise, rescan and truncate
9271541Srgrimes		 * after the remaining size.
9281541Srgrimes		 */
9291541Srgrimes		len = -len;
9301541Srgrimes		count = 0;
9311541Srgrimes		for (;;) {
9321541Srgrimes			count += m->m_len;
9331541Srgrimes			if (m->m_next == (struct mbuf *)0)
9341541Srgrimes				break;
9351541Srgrimes			m = m->m_next;
9361541Srgrimes		}
9371541Srgrimes		if (m->m_len >= len) {
9381541Srgrimes			m->m_len -= len;
9391541Srgrimes			if (mp->m_flags & M_PKTHDR)
9401541Srgrimes				mp->m_pkthdr.len -= len;
9411541Srgrimes			return;
9421541Srgrimes		}
9431541Srgrimes		count -= len;
9441541Srgrimes		if (count < 0)
9451541Srgrimes			count = 0;
9461541Srgrimes		/*
9471541Srgrimes		 * Correct length for chain is "count".
9481541Srgrimes		 * Find the mbuf with last data, adjust its length,
9491541Srgrimes		 * and toss data from remaining mbufs on chain.
9501541Srgrimes		 */
9511541Srgrimes		m = mp;
9521541Srgrimes		if (m->m_flags & M_PKTHDR)
9531541Srgrimes			m->m_pkthdr.len = count;
9541541Srgrimes		for (; m; m = m->m_next) {
9551541Srgrimes			if (m->m_len >= count) {
9561541Srgrimes				m->m_len = count;
957142350Ssam				if (m->m_next != NULL) {
958142350Ssam					m_freem(m->m_next);
959142350Ssam					m->m_next = NULL;
960142350Ssam				}
9611541Srgrimes				break;
9621541Srgrimes			}
9631541Srgrimes			count -= m->m_len;
9641541Srgrimes		}
9651541Srgrimes	}
9661541Srgrimes}
9671541Srgrimes
9681541Srgrimes/*
9691541Srgrimes * Rearange an mbuf chain so that len bytes are contiguous
9701541Srgrimes * and in the data area of an mbuf (so that mtod and dtom
9711541Srgrimes * will work for a structure of size len).  Returns the resulting
9721541Srgrimes * mbuf chain on success, frees it and returns null on failure.
9731541Srgrimes * If there is room, it will add up to max_protohdr-len extra bytes to the
9741541Srgrimes * contiguous region in an attempt to avoid being called next time.
9751541Srgrimes */
9761541Srgrimesstruct mbuf *
97772356Sbmilekicm_pullup(struct mbuf *n, int len)
9781541Srgrimes{
97972356Sbmilekic	struct mbuf *m;
98072356Sbmilekic	int count;
9811541Srgrimes	int space;
9821541Srgrimes
9831541Srgrimes	/*
9841541Srgrimes	 * If first mbuf has no cluster, and has room for len bytes
9851541Srgrimes	 * without shifting current data, pullup into it,
9861541Srgrimes	 * otherwise allocate a new mbuf to prepend to the chain.
9871541Srgrimes	 */
9881541Srgrimes	if ((n->m_flags & M_EXT) == 0 &&
9891541Srgrimes	    n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
9901541Srgrimes		if (n->m_len >= len)
9911541Srgrimes			return (n);
9921541Srgrimes		m = n;
9931541Srgrimes		n = n->m_next;
9941541Srgrimes		len -= m->m_len;
9951541Srgrimes	} else {
9961541Srgrimes		if (len > MHLEN)
9971541Srgrimes			goto bad;
998111119Simp		MGET(m, M_DONTWAIT, n->m_type);
99972356Sbmilekic		if (m == NULL)
10001541Srgrimes			goto bad;
10011541Srgrimes		m->m_len = 0;
1002108466Ssam		if (n->m_flags & M_PKTHDR)
1003108466Ssam			M_MOVE_PKTHDR(m, n);
10041541Srgrimes	}
10051541Srgrimes	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
10061541Srgrimes	do {
10071541Srgrimes		count = min(min(max(len, max_protohdr), space), n->m_len);
10081541Srgrimes		bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1009103569Sbmilekic		  (u_int)count);
10101541Srgrimes		len -= count;
10111541Srgrimes		m->m_len += count;
10121541Srgrimes		n->m_len -= count;
10131541Srgrimes		space -= count;
10141541Srgrimes		if (n->m_len)
10151541Srgrimes			n->m_data += count;
10161541Srgrimes		else
10171541Srgrimes			n = m_free(n);
10181541Srgrimes	} while (len > 0 && n);
10191541Srgrimes	if (len > 0) {
10201541Srgrimes		(void) m_free(m);
10211541Srgrimes		goto bad;
10221541Srgrimes	}
10231541Srgrimes	m->m_next = n;
10241541Srgrimes	return (m);
10251541Srgrimesbad:
10261541Srgrimes	m_freem(n);
102778592Sbmilekic	mbstat.m_mpfail++;	/* XXX: No consistency. */
102872356Sbmilekic	return (NULL);
10291541Srgrimes}
10301541Srgrimes
10311541Srgrimes/*
1032143761Sjmg * Like m_pullup(), except a new mbuf is always allocated, and we allow
1033143761Sjmg * the amount of empty space before the data in the new mbuf to be specified
1034143761Sjmg * (in the event that the caller expects to prepend later).
1035143761Sjmg */
1036143761Sjmgint MSFail;
1037143761Sjmg
1038143761Sjmgstruct mbuf *
1039143761Sjmgm_copyup(struct mbuf *n, int len, int dstoff)
1040143761Sjmg{
1041143761Sjmg	struct mbuf *m;
1042143761Sjmg	int count, space;
1043143761Sjmg
1044143761Sjmg	if (len > (MHLEN - dstoff))
1045143761Sjmg		goto bad;
1046143761Sjmg	MGET(m, M_DONTWAIT, n->m_type);
1047143761Sjmg	if (m == NULL)
1048143761Sjmg		goto bad;
1049143761Sjmg	m->m_len = 0;
1050143761Sjmg	if (n->m_flags & M_PKTHDR)
1051143761Sjmg		M_MOVE_PKTHDR(m, n);
1052143761Sjmg	m->m_data += dstoff;
1053143761Sjmg	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1054143761Sjmg	do {
1055143761Sjmg		count = min(min(max(len, max_protohdr), space), n->m_len);
1056143761Sjmg		memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
1057143761Sjmg		    (unsigned)count);
1058143761Sjmg		len -= count;
1059143761Sjmg		m->m_len += count;
1060143761Sjmg		n->m_len -= count;
1061143761Sjmg		space -= count;
1062143761Sjmg		if (n->m_len)
1063143761Sjmg			n->m_data += count;
1064143761Sjmg		else
1065143761Sjmg			n = m_free(n);
1066143761Sjmg	} while (len > 0 && n);
1067143761Sjmg	if (len > 0) {
1068143761Sjmg		(void) m_free(m);
1069143761Sjmg		goto bad;
1070143761Sjmg	}
1071143761Sjmg	m->m_next = n;
1072143761Sjmg	return (m);
1073143761Sjmg bad:
1074143761Sjmg	m_freem(n);
1075143761Sjmg	MSFail++;
1076143761Sjmg	return (NULL);
1077143761Sjmg}
1078143761Sjmg
1079143761Sjmg/*
10801541Srgrimes * Partition an mbuf chain in two pieces, returning the tail --
10811541Srgrimes * all but the first len0 bytes.  In case of failure, it returns NULL and
10821541Srgrimes * attempts to restore the chain to its original state.
108397681Sarchie *
108497681Sarchie * Note that the resulting mbufs might be read-only, because the new
108597681Sarchie * mbuf can end up sharing an mbuf cluster with the original mbuf if
108697681Sarchie * the "breaking point" happens to lie within a cluster mbuf. Use the
108797681Sarchie * M_WRITABLE() macro to check for this case.
10881541Srgrimes */
10891541Srgrimesstruct mbuf *
109072356Sbmilekicm_split(struct mbuf *m0, int len0, int wait)
10911541Srgrimes{
109272356Sbmilekic	struct mbuf *m, *n;
1093103569Sbmilekic	u_int len = len0, remain;
10941541Srgrimes
1095132488Salfred	MBUF_CHECKSLEEP(wait);
10961541Srgrimes	for (m = m0; m && len > m->m_len; m = m->m_next)
10971541Srgrimes		len -= m->m_len;
109872356Sbmilekic	if (m == NULL)
109972356Sbmilekic		return (NULL);
11001541Srgrimes	remain = m->m_len - len;
11011541Srgrimes	if (m0->m_flags & M_PKTHDR) {
11021541Srgrimes		MGETHDR(n, wait, m0->m_type);
110372356Sbmilekic		if (n == NULL)
110472356Sbmilekic			return (NULL);
11051541Srgrimes		n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
11061541Srgrimes		n->m_pkthdr.len = m0->m_pkthdr.len - len0;
11071541Srgrimes		m0->m_pkthdr.len = len0;
11081541Srgrimes		if (m->m_flags & M_EXT)
11091541Srgrimes			goto extpacket;
11101541Srgrimes		if (remain > MHLEN) {
11111541Srgrimes			/* m can't be the lead packet */
11121541Srgrimes			MH_ALIGN(n, 0);
11131541Srgrimes			n->m_next = m_split(m, len, wait);
111472356Sbmilekic			if (n->m_next == NULL) {
11151541Srgrimes				(void) m_free(n);
111672356Sbmilekic				return (NULL);
111794471Shsu			} else {
111894471Shsu				n->m_len = 0;
11191541Srgrimes				return (n);
112094471Shsu			}
11211541Srgrimes		} else
11221541Srgrimes			MH_ALIGN(n, remain);
11231541Srgrimes	} else if (remain == 0) {
11241541Srgrimes		n = m->m_next;
112572356Sbmilekic		m->m_next = NULL;
11261541Srgrimes		return (n);
11271541Srgrimes	} else {
11281541Srgrimes		MGET(n, wait, m->m_type);
112972356Sbmilekic		if (n == NULL)
113072356Sbmilekic			return (NULL);
11311541Srgrimes		M_ALIGN(n, remain);
11321541Srgrimes	}
11331541Srgrimesextpacket:
11341541Srgrimes	if (m->m_flags & M_EXT) {
11351541Srgrimes		n->m_flags |= M_EXT;
11361541Srgrimes		n->m_ext = m->m_ext;
113764837Sdwmalone		MEXT_ADD_REF(m);
1138141668Sbmilekic		n->m_ext.ref_cnt = m->m_ext.ref_cnt;
11391541Srgrimes		n->m_data = m->m_data + len;
11401541Srgrimes	} else {
11411541Srgrimes		bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
11421541Srgrimes	}
11431541Srgrimes	n->m_len = remain;
11441541Srgrimes	m->m_len = len;
11451541Srgrimes	n->m_next = m->m_next;
114672356Sbmilekic	m->m_next = NULL;
11471541Srgrimes	return (n);
11481541Srgrimes}
11491541Srgrimes/*
11501541Srgrimes * Routine to copy from device local memory into mbufs.
115178508Sbmilekic * Note that `off' argument is offset into first mbuf of target chain from
115278508Sbmilekic * which to begin copying the data to.
11531541Srgrimes */
11541541Srgrimesstruct mbuf *
115578508Sbmilekicm_devget(char *buf, int totlen, int off, struct ifnet *ifp,
115672356Sbmilekic	 void (*copy)(char *from, caddr_t to, u_int len))
11571541Srgrimes{
115872356Sbmilekic	struct mbuf *m;
1159129906Sbmilekic	struct mbuf *top = NULL, **mp = &top;
116078508Sbmilekic	int len;
11611541Srgrimes
116278508Sbmilekic	if (off < 0 || off > MHLEN)
116378508Sbmilekic		return (NULL);
116478508Sbmilekic
1165129906Sbmilekic	while (totlen > 0) {
1166129906Sbmilekic		if (top == NULL) {	/* First one, must be PKTHDR */
1167129906Sbmilekic			if (totlen + off >= MINCLSIZE) {
1168129906Sbmilekic				m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
1169129906Sbmilekic				len = MCLBYTES;
1170129906Sbmilekic			} else {
1171129906Sbmilekic				m = m_gethdr(M_DONTWAIT, MT_DATA);
1172129906Sbmilekic				len = MHLEN;
11731541Srgrimes
1174129906Sbmilekic				/* Place initial small packet/header at end of mbuf */
1175129906Sbmilekic				if (m && totlen + off + max_linkhdr <= MLEN) {
1176129906Sbmilekic					m->m_data += max_linkhdr;
1177129906Sbmilekic					len -= max_linkhdr;
1178129906Sbmilekic				}
1179129906Sbmilekic			}
1180129906Sbmilekic			if (m == NULL)
1181129906Sbmilekic				return NULL;
1182129906Sbmilekic			m->m_pkthdr.rcvif = ifp;
1183129906Sbmilekic			m->m_pkthdr.len = totlen;
1184129906Sbmilekic		} else {
1185129906Sbmilekic			if (totlen + off >= MINCLSIZE) {
1186129906Sbmilekic				m = m_getcl(M_DONTWAIT, MT_DATA, 0);
1187129906Sbmilekic				len = MCLBYTES;
1188129906Sbmilekic			} else {
1189129906Sbmilekic				m = m_get(M_DONTWAIT, MT_DATA);
1190129906Sbmilekic				len = MLEN;
1191129906Sbmilekic			}
119272356Sbmilekic			if (m == NULL) {
11931541Srgrimes				m_freem(top);
1194129906Sbmilekic				return NULL;
11951541Srgrimes			}
11961541Srgrimes		}
119778508Sbmilekic		if (off) {
119878508Sbmilekic			m->m_data += off;
119978508Sbmilekic			len -= off;
120078508Sbmilekic			off = 0;
120178508Sbmilekic		}
120278508Sbmilekic		m->m_len = len = min(totlen, len);
12031541Srgrimes		if (copy)
1204103569Sbmilekic			copy(buf, mtod(m, caddr_t), (u_int)len);
12051541Srgrimes		else
1206103569Sbmilekic			bcopy(buf, mtod(m, caddr_t), (u_int)len);
120778508Sbmilekic		buf += len;
12081541Srgrimes		*mp = m;
12091541Srgrimes		mp = &m->m_next;
12101541Srgrimes		totlen -= len;
12111541Srgrimes	}
12121541Srgrimes	return (top);
12131541Srgrimes}
12143352Sphk
12153352Sphk/*
12163352Sphk * Copy data from a buffer back into the indicated mbuf chain,
12173352Sphk * starting "off" bytes from the beginning, extending the mbuf
12183352Sphk * chain if necessary.
12193352Sphk */
12203352Sphkvoid
1221128402Sluigim_copyback(struct mbuf *m0, int off, int len, c_caddr_t cp)
12223352Sphk{
122372356Sbmilekic	int mlen;
122472356Sbmilekic	struct mbuf *m = m0, *n;
12253352Sphk	int totlen = 0;
12263352Sphk
122772356Sbmilekic	if (m0 == NULL)
12283352Sphk		return;
12293352Sphk	while (off > (mlen = m->m_len)) {
12303352Sphk		off -= mlen;
12313352Sphk		totlen += mlen;
123272356Sbmilekic		if (m->m_next == NULL) {
1233129906Sbmilekic			n = m_get(M_DONTWAIT, m->m_type);
123472356Sbmilekic			if (n == NULL)
12353352Sphk				goto out;
1236129906Sbmilekic			bzero(mtod(n, caddr_t), MLEN);
12373352Sphk			n->m_len = min(MLEN, len + off);
12383352Sphk			m->m_next = n;
12393352Sphk		}
12403352Sphk		m = m->m_next;
12413352Sphk	}
12423352Sphk	while (len > 0) {
12433352Sphk		mlen = min (m->m_len - off, len);
1244103569Sbmilekic		bcopy(cp, off + mtod(m, caddr_t), (u_int)mlen);
12453352Sphk		cp += mlen;
12463352Sphk		len -= mlen;
12473352Sphk		mlen += off;
12483352Sphk		off = 0;
12493352Sphk		totlen += mlen;
12503352Sphk		if (len == 0)
12513352Sphk			break;
125272356Sbmilekic		if (m->m_next == NULL) {
1253111119Simp			n = m_get(M_DONTWAIT, m->m_type);
125472356Sbmilekic			if (n == NULL)
12553352Sphk				break;
12563352Sphk			n->m_len = min(MLEN, len);
12573352Sphk			m->m_next = n;
12583352Sphk		}
12593352Sphk		m = m->m_next;
12603352Sphk	}
12613352Sphkout:	if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
12623352Sphk		m->m_pkthdr.len = totlen;
12633352Sphk}
126452756Sphk
1265123557Sbms/*
1266138541Ssam * Append the specified data to the indicated mbuf chain,
1267138541Ssam * Extend the mbuf chain if the new data does not fit in
1268138541Ssam * existing space.
1269138541Ssam *
1270138541Ssam * Return 1 if able to complete the job; otherwise 0.
1271138541Ssam */
1272138541Ssamint
1273138541Ssamm_append(struct mbuf *m0, int len, c_caddr_t cp)
1274138541Ssam{
1275138541Ssam	struct mbuf *m, *n;
1276138541Ssam	int remainder, space;
1277138541Ssam
1278138541Ssam	for (m = m0; m->m_next != NULL; m = m->m_next)
1279138541Ssam		;
1280138541Ssam	remainder = len;
1281138541Ssam	space = M_TRAILINGSPACE(m);
1282138541Ssam	if (space > 0) {
1283138541Ssam		/*
1284138541Ssam		 * Copy into available space.
1285138541Ssam		 */
1286138541Ssam		if (space > remainder)
1287138541Ssam			space = remainder;
1288138541Ssam		bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
1289138541Ssam		m->m_len += space;
1290138541Ssam		cp += space, remainder -= space;
1291138541Ssam	}
1292138541Ssam	while (remainder > 0) {
1293138541Ssam		/*
1294138541Ssam		 * Allocate a new mbuf; could check space
1295138541Ssam		 * and allocate a cluster instead.
1296138541Ssam		 */
1297138541Ssam		n = m_get(M_DONTWAIT, m->m_type);
1298138541Ssam		if (n == NULL)
1299138541Ssam			break;
1300138541Ssam		n->m_len = min(MLEN, remainder);
1301138894Ssam		bcopy(cp, mtod(n, caddr_t), n->m_len);
1302138894Ssam		cp += n->m_len, remainder -= n->m_len;
1303138541Ssam		m->m_next = n;
1304138541Ssam		m = n;
1305138541Ssam	}
1306138541Ssam	if (m0->m_flags & M_PKTHDR)
1307138541Ssam		m0->m_pkthdr.len += len - remainder;
1308138541Ssam	return (remainder == 0);
1309138541Ssam}
1310138541Ssam
1311138541Ssam/*
1312123557Sbms * Apply function f to the data in an mbuf chain starting "off" bytes from
1313123557Sbms * the beginning, continuing for "len" bytes.
1314123557Sbms */
1315123557Sbmsint
1316123557Sbmsm_apply(struct mbuf *m, int off, int len,
1317123564Sbms    int (*f)(void *, void *, u_int), void *arg)
1318123557Sbms{
1319123564Sbms	u_int count;
1320123557Sbms	int rval;
1321123557Sbms
1322123557Sbms	KASSERT(off >= 0, ("m_apply, negative off %d", off));
1323123557Sbms	KASSERT(len >= 0, ("m_apply, negative len %d", len));
1324123557Sbms	while (off > 0) {
1325123557Sbms		KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1326123557Sbms		if (off < m->m_len)
1327123557Sbms			break;
1328123557Sbms		off -= m->m_len;
1329123557Sbms		m = m->m_next;
1330123557Sbms	}
1331123557Sbms	while (len > 0) {
1332123557Sbms		KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1333123557Sbms		count = min(m->m_len - off, len);
1334123557Sbms		rval = (*f)(arg, mtod(m, caddr_t) + off, count);
1335123557Sbms		if (rval)
1336123557Sbms			return (rval);
1337123557Sbms		len -= count;
1338123557Sbms		off = 0;
1339123557Sbms		m = m->m_next;
1340123557Sbms	}
1341123557Sbms	return (0);
1342123557Sbms}
1343123557Sbms
1344123557Sbms/*
1345123557Sbms * Return a pointer to mbuf/offset of location in mbuf chain.
1346123557Sbms */
1347123557Sbmsstruct mbuf *
1348123557Sbmsm_getptr(struct mbuf *m, int loc, int *off)
1349123557Sbms{
1350123557Sbms
1351123557Sbms	while (loc >= 0) {
1352123564Sbms		/* Normal end of search. */
1353123557Sbms		if (m->m_len > loc) {
1354123557Sbms			*off = loc;
1355123557Sbms			return (m);
1356123557Sbms		} else {
1357123557Sbms			loc -= m->m_len;
1358123557Sbms			if (m->m_next == NULL) {
1359123557Sbms				if (loc == 0) {
1360123564Sbms					/* Point at the end of valid data. */
1361123557Sbms					*off = m->m_len;
1362123557Sbms					return (m);
1363123564Sbms				}
1364123564Sbms				return (NULL);
1365123564Sbms			}
1366123564Sbms			m = m->m_next;
1367123557Sbms		}
1368123557Sbms	}
1369123557Sbms	return (NULL);
1370123557Sbms}
1371123557Sbms
137252756Sphkvoid
1373135904Sjmgm_print(const struct mbuf *m, int maxlen)
137452756Sphk{
137552756Sphk	int len;
1376135904Sjmg	int pdata;
137754906Seivind	const struct mbuf *m2;
137852756Sphk
1379135904Sjmg	if (m->m_flags & M_PKTHDR)
1380135904Sjmg		len = m->m_pkthdr.len;
1381135904Sjmg	else
1382135904Sjmg		len = -1;
138352756Sphk	m2 = m;
1384135904Sjmg	while (m2 != NULL && (len == -1 || len)) {
1385135904Sjmg		pdata = m2->m_len;
1386135904Sjmg		if (maxlen != -1 && pdata > maxlen)
1387135904Sjmg			pdata = maxlen;
1388135904Sjmg		printf("mbuf: %p len: %d, next: %p, %b%s", m2, m2->m_len,
1389135904Sjmg		    m2->m_next, m2->m_flags, "\20\20freelist\17skipfw"
1390135904Sjmg		    "\11proto5\10proto4\7proto3\6proto2\5proto1\4rdonly"
1391135904Sjmg		    "\3eor\2pkthdr\1ext", pdata ? "" : "\n");
1392135904Sjmg		if (pdata)
1393135904Sjmg			printf(", %*D\n", m2->m_len, (u_char *)m2->m_data, "-");
1394135904Sjmg		if (len != -1)
1395135904Sjmg			len -= m2->m_len;
139652756Sphk		m2 = m2->m_next;
139752756Sphk	}
1398135904Sjmg	if (len > 0)
1399135904Sjmg		printf("%d bytes unaccounted for.\n", len);
140052756Sphk	return;
140152756Sphk}
1402103540Sphk
1403103569Sbmilekicu_int
1404103540Sphkm_fixhdr(struct mbuf *m0)
1405103540Sphk{
1406103569Sbmilekic	u_int len;
1407103540Sphk
1408103544Sphk	len = m_length(m0, NULL);
1409103544Sphk	m0->m_pkthdr.len = len;
1410103544Sphk	return (len);
1411103544Sphk}
1412103544Sphk
1413103569Sbmilekicu_int
1414103544Sphkm_length(struct mbuf *m0, struct mbuf **last)
1415103544Sphk{
1416103544Sphk	struct mbuf *m;
1417103569Sbmilekic	u_int len;
1418103544Sphk
1419103544Sphk	len = 0;
1420103544Sphk	for (m = m0; m != NULL; m = m->m_next) {
1421103540Sphk		len += m->m_len;
1422103544Sphk		if (m->m_next == NULL)
1423103544Sphk			break;
1424103540Sphk	}
1425103544Sphk	if (last != NULL)
1426103544Sphk		*last = m;
1427103544Sphk	return (len);
1428103540Sphk}
1429112777Ssilby
1430112777Ssilby/*
1431112777Ssilby * Defragment a mbuf chain, returning the shortest possible
1432112777Ssilby * chain of mbufs and clusters.  If allocation fails and
1433112777Ssilby * this cannot be completed, NULL will be returned, but
1434112777Ssilby * the passed in chain will be unchanged.  Upon success,
1435112777Ssilby * the original chain will be freed, and the new chain
1436112777Ssilby * will be returned.
1437112777Ssilby *
1438112777Ssilby * If a non-packet header is passed in, the original
1439112777Ssilby * mbuf (chain?) will be returned unharmed.
1440112777Ssilby */
1441112777Ssilbystruct mbuf *
1442112777Ssilbym_defrag(struct mbuf *m0, int how)
1443112777Ssilby{
1444125472Ssilby	struct mbuf *m_new = NULL, *m_final = NULL;
1445125472Ssilby	int progress = 0, length;
1446112777Ssilby
1447132488Salfred	MBUF_CHECKSLEEP(how);
1448112777Ssilby	if (!(m0->m_flags & M_PKTHDR))
1449112777Ssilby		return (m0);
1450112777Ssilby
1451117770Ssilby	m_fixhdr(m0); /* Needed sanity check */
1452117770Ssilby
1453113490Ssilby#ifdef MBUF_STRESS_TEST
1454113490Ssilby	if (m_defragrandomfailures) {
1455113490Ssilby		int temp = arc4random() & 0xff;
1456113490Ssilby		if (temp == 0xba)
1457113490Ssilby			goto nospace;
1458113490Ssilby	}
1459113490Ssilby#endif
1460112777Ssilby
1461112777Ssilby	if (m0->m_pkthdr.len > MHLEN)
1462112777Ssilby		m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1463112777Ssilby	else
1464112777Ssilby		m_final = m_gethdr(how, MT_DATA);
1465112777Ssilby
1466112777Ssilby	if (m_final == NULL)
1467112777Ssilby		goto nospace;
1468112777Ssilby
1469123740Speter	if (m_dup_pkthdr(m_final, m0, how) == 0)
1470112777Ssilby		goto nospace;
1471112777Ssilby
1472112777Ssilby	m_new = m_final;
1473112777Ssilby
1474112777Ssilby	while (progress < m0->m_pkthdr.len) {
1475112777Ssilby		length = m0->m_pkthdr.len - progress;
1476112777Ssilby		if (length > MCLBYTES)
1477112777Ssilby			length = MCLBYTES;
1478112777Ssilby
1479112777Ssilby		if (m_new == NULL) {
1480112777Ssilby			if (length > MLEN)
1481112777Ssilby				m_new = m_getcl(how, MT_DATA, 0);
1482112777Ssilby			else
1483112777Ssilby				m_new = m_get(how, MT_DATA);
1484112777Ssilby			if (m_new == NULL)
1485112777Ssilby				goto nospace;
1486112777Ssilby		}
1487112777Ssilby
1488112777Ssilby		m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1489112777Ssilby		progress += length;
1490112777Ssilby		m_new->m_len = length;
1491112777Ssilby		if (m_new != m_final)
1492112777Ssilby			m_cat(m_final, m_new);
1493112777Ssilby		m_new = NULL;
1494112777Ssilby	}
1495116455Ssilby#ifdef MBUF_STRESS_TEST
1496112777Ssilby	if (m0->m_next == NULL)
1497112777Ssilby		m_defraguseless++;
1498116455Ssilby#endif
1499112777Ssilby	m_freem(m0);
1500112777Ssilby	m0 = m_final;
1501116455Ssilby#ifdef MBUF_STRESS_TEST
1502112777Ssilby	m_defragpackets++;
1503112777Ssilby	m_defragbytes += m0->m_pkthdr.len;
1504116455Ssilby#endif
1505112777Ssilby	return (m0);
1506112777Ssilbynospace:
1507116455Ssilby#ifdef MBUF_STRESS_TEST
1508112777Ssilby	m_defragfailure++;
1509116455Ssilby#endif
1510112777Ssilby	if (m_final)
1511112777Ssilby		m_freem(m_final);
1512112777Ssilby	return (NULL);
1513112777Ssilby}
1514119644Ssilby
1515119644Ssilby#ifdef MBUF_STRESS_TEST
1516119644Ssilby
1517119644Ssilby/*
1518119644Ssilby * Fragment an mbuf chain.  There's no reason you'd ever want to do
1519119644Ssilby * this in normal usage, but it's great for stress testing various
1520119644Ssilby * mbuf consumers.
1521119644Ssilby *
1522119644Ssilby * If fragmentation is not possible, the original chain will be
1523119644Ssilby * returned.
1524119644Ssilby *
1525119644Ssilby * Possible length values:
1526119644Ssilby * 0	 no fragmentation will occur
1527119644Ssilby * > 0	each fragment will be of the specified length
1528119644Ssilby * -1	each fragment will be the same random value in length
1529119644Ssilby * -2	each fragment's length will be entirely random
1530119644Ssilby * (Random values range from 1 to 256)
1531119644Ssilby */
1532119644Ssilbystruct mbuf *
1533119644Ssilbym_fragment(struct mbuf *m0, int how, int length)
1534119644Ssilby{
1535125472Ssilby	struct mbuf *m_new = NULL, *m_final = NULL;
1536125472Ssilby	int progress = 0;
1537119644Ssilby
1538119644Ssilby	if (!(m0->m_flags & M_PKTHDR))
1539119644Ssilby		return (m0);
1540119644Ssilby
1541119644Ssilby	if ((length == 0) || (length < -2))
1542119644Ssilby		return (m0);
1543119644Ssilby
1544119644Ssilby	m_fixhdr(m0); /* Needed sanity check */
1545119644Ssilby
1546119644Ssilby	m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1547119644Ssilby
1548119644Ssilby	if (m_final == NULL)
1549119644Ssilby		goto nospace;
1550119644Ssilby
1551123823Ssilby	if (m_dup_pkthdr(m_final, m0, how) == 0)
1552119644Ssilby		goto nospace;
1553119644Ssilby
1554119644Ssilby	m_new = m_final;
1555119644Ssilby
1556119644Ssilby	if (length == -1)
1557119644Ssilby		length = 1 + (arc4random() & 255);
1558119644Ssilby
1559119644Ssilby	while (progress < m0->m_pkthdr.len) {
1560119644Ssilby		int fraglen;
1561119644Ssilby
1562119644Ssilby		if (length > 0)
1563119644Ssilby			fraglen = length;
1564119644Ssilby		else
1565119644Ssilby			fraglen = 1 + (arc4random() & 255);
1566119644Ssilby		if (fraglen > m0->m_pkthdr.len - progress)
1567119644Ssilby			fraglen = m0->m_pkthdr.len - progress;
1568119644Ssilby
1569119644Ssilby		if (fraglen > MCLBYTES)
1570119644Ssilby			fraglen = MCLBYTES;
1571119644Ssilby
1572119644Ssilby		if (m_new == NULL) {
1573119644Ssilby			m_new = m_getcl(how, MT_DATA, 0);
1574119644Ssilby			if (m_new == NULL)
1575119644Ssilby				goto nospace;
1576119644Ssilby		}
1577119644Ssilby
1578119644Ssilby		m_copydata(m0, progress, fraglen, mtod(m_new, caddr_t));
1579119644Ssilby		progress += fraglen;
1580119644Ssilby		m_new->m_len = fraglen;
1581119644Ssilby		if (m_new != m_final)
1582119644Ssilby			m_cat(m_final, m_new);
1583119644Ssilby		m_new = NULL;
1584119644Ssilby	}
1585119644Ssilby	m_freem(m0);
1586119644Ssilby	m0 = m_final;
1587119644Ssilby	return (m0);
1588119644Ssilbynospace:
1589119644Ssilby	if (m_final)
1590119644Ssilby		m_freem(m_final);
1591119644Ssilby	/* Return the original chain on failure */
1592119644Ssilby	return (m0);
1593119644Ssilby}
1594119644Ssilby
1595119644Ssilby#endif
1596125296Ssilby
1597125296Ssilbystruct mbuf *
1598145883Semaxm_uiotombuf(struct uio *uio, int how, int len, int align)
1599125296Ssilby{
1600125472Ssilby	struct mbuf *m_new = NULL, *m_final = NULL;
1601125472Ssilby	int progress = 0, error = 0, length, total;
1602125296Ssilby
1603125296Ssilby	if (len > 0)
1604125296Ssilby		total = min(uio->uio_resid, len);
1605125296Ssilby	else
1606125296Ssilby		total = uio->uio_resid;
1607145883Semax	if (align >= MHLEN)
1608145883Semax		goto nospace;
1609145883Semax	if (total + align > MHLEN)
1610125296Ssilby		m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1611125296Ssilby	else
1612125296Ssilby		m_final = m_gethdr(how, MT_DATA);
1613125296Ssilby	if (m_final == NULL)
1614125296Ssilby		goto nospace;
1615145883Semax	m_final->m_data += align;
1616125296Ssilby	m_new = m_final;
1617125296Ssilby	while (progress < total) {
1618125296Ssilby		length = total - progress;
1619125296Ssilby		if (length > MCLBYTES)
1620125296Ssilby			length = MCLBYTES;
1621125296Ssilby		if (m_new == NULL) {
1622125296Ssilby			if (length > MLEN)
1623125296Ssilby				m_new = m_getcl(how, MT_DATA, 0);
1624125296Ssilby			else
1625125296Ssilby				m_new = m_get(how, MT_DATA);
1626125296Ssilby			if (m_new == NULL)
1627125296Ssilby				goto nospace;
1628125296Ssilby		}
1629125296Ssilby		error = uiomove(mtod(m_new, void *), length, uio);
1630125296Ssilby		if (error)
1631125296Ssilby			goto nospace;
1632125296Ssilby		progress += length;
1633125296Ssilby		m_new->m_len = length;
1634125296Ssilby		if (m_new != m_final)
1635125296Ssilby			m_cat(m_final, m_new);
1636125296Ssilby		m_new = NULL;
1637125296Ssilby	}
1638125296Ssilby	m_fixhdr(m_final);
1639125296Ssilby	return (m_final);
1640125296Ssilbynospace:
1641125296Ssilby	if (m_new)
1642125296Ssilby		m_free(m_new);
1643125296Ssilby	if (m_final)
1644125296Ssilby		m_freem(m_final);
1645125296Ssilby	return (NULL);
1646125296Ssilby}
1647148552Ssam
1648148552Ssam/*
1649148552Ssam * Set the m_data pointer of a newly-allocated mbuf
1650148552Ssam * to place an object of the specified size at the
1651148552Ssam * end of the mbuf, longword aligned.
1652148552Ssam */
1653148552Ssamvoid
1654148552Ssamm_align(struct mbuf *m, int len)
1655148552Ssam{
1656148552Ssam	int adjust;
1657148552Ssam
1658148552Ssam	if (m->m_flags & M_EXT)
1659148552Ssam		adjust = m->m_ext.ext_size - len;
1660148552Ssam	else if (m->m_flags & M_PKTHDR)
1661148552Ssam		adjust = MHLEN - len;
1662148552Ssam	else
1663148552Ssam		adjust = MLEN - len;
1664148552Ssam	m->m_data += adjust &~ (sizeof(long)-1);
1665148552Ssam}
1666