uipc_mbuf.c revision 254799
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 254799 2013-08-24 16:57:44Z andre $");
34
35#include "opt_param.h"
36#include "opt_mbuf_stress_test.h"
37#include "opt_mbuf_profiling.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/malloc.h>
45#include <sys/mbuf.h>
46#include <sys/sysctl.h>
47#include <sys/domain.h>
48#include <sys/protosw.h>
49#include <sys/uio.h>
50
51int	max_linkhdr;
52int	max_protohdr;
53int	max_hdr;
54int	max_datalen;
55#ifdef MBUF_STRESS_TEST
56int	m_defragpackets;
57int	m_defragbytes;
58int	m_defraguseless;
59int	m_defragfailure;
60int	m_defragrandomfailures;
61#endif
62
63/*
64 * sysctl(8) exported objects
65 */
66SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RD,
67	   &max_linkhdr, 0, "Size of largest link layer header");
68SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RD,
69	   &max_protohdr, 0, "Size of largest protocol layer header");
70SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RD,
71	   &max_hdr, 0, "Size of largest link plus protocol header");
72SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RD,
73	   &max_datalen, 0, "Minimum space left in mbuf after max_hdr");
74#ifdef MBUF_STRESS_TEST
75SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
76	   &m_defragpackets, 0, "");
77SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
78	   &m_defragbytes, 0, "");
79SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
80	   &m_defraguseless, 0, "");
81SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
82	   &m_defragfailure, 0, "");
83SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
84	   &m_defragrandomfailures, 0, "");
85#endif
86
87/*
88 * m_get2() allocates minimum mbuf that would fit "size" argument.
89 */
90struct mbuf *
91m_get2(int size, int how, short type, int flags)
92{
93	struct mb_args args;
94	struct mbuf *m, *n;
95
96	args.flags = flags;
97	args.type = type;
98
99	if (size <= MHLEN || (size <= MLEN && (flags & M_PKTHDR) == 0))
100		return (uma_zalloc_arg(zone_mbuf, &args, how));
101	if (size <= MCLBYTES)
102		return (uma_zalloc_arg(zone_pack, &args, how));
103
104	if (size > MJUMPAGESIZE)
105		return (NULL);
106
107	m = uma_zalloc_arg(zone_mbuf, &args, how);
108	if (m == NULL)
109		return (NULL);
110
111	n = uma_zalloc_arg(zone_jumbop, m, how);
112	if (n == NULL) {
113		uma_zfree(zone_mbuf, m);
114		return (NULL);
115	}
116
117	return (m);
118}
119
120/*
121 * m_getjcl() returns an mbuf with a cluster of the specified size attached.
122 * For size it takes MCLBYTES, MJUMPAGESIZE, MJUM9BYTES, MJUM16BYTES.
123 */
124struct mbuf *
125m_getjcl(int how, short type, int flags, int size)
126{
127	struct mb_args args;
128	struct mbuf *m, *n;
129	uma_zone_t zone;
130
131	if (size == MCLBYTES)
132		return m_getcl(how, type, flags);
133
134	args.flags = flags;
135	args.type = type;
136
137	m = uma_zalloc_arg(zone_mbuf, &args, how);
138	if (m == NULL)
139		return (NULL);
140
141	zone = m_getzone(size);
142	n = uma_zalloc_arg(zone, m, how);
143	if (n == NULL) {
144		uma_zfree(zone_mbuf, m);
145		return (NULL);
146	}
147	return (m);
148}
149
150/*
151 * Allocate a given length worth of mbufs and/or clusters (whatever fits
152 * best) and return a pointer to the top of the allocated chain.  If an
153 * existing mbuf chain is provided, then we will append the new chain
154 * to the existing one but still return the top of the newly allocated
155 * chain.
156 */
157struct mbuf *
158m_getm2(struct mbuf *m, int len, int how, short type, int flags)
159{
160	struct mbuf *mb, *nm = NULL, *mtail = NULL;
161
162	KASSERT(len >= 0, ("%s: len is < 0", __func__));
163
164	/* Validate flags. */
165	flags &= (M_PKTHDR | M_EOR);
166
167	/* Packet header mbuf must be first in chain. */
168	if ((flags & M_PKTHDR) && m != NULL)
169		flags &= ~M_PKTHDR;
170
171	/* Loop and append maximum sized mbufs to the chain tail. */
172	while (len > 0) {
173		if (len > MCLBYTES)
174			mb = m_getjcl(how, type, (flags & M_PKTHDR),
175			    MJUMPAGESIZE);
176		else if (len >= MINCLSIZE)
177			mb = m_getcl(how, type, (flags & M_PKTHDR));
178		else if (flags & M_PKTHDR)
179			mb = m_gethdr(how, type);
180		else
181			mb = m_get(how, type);
182
183		/* Fail the whole operation if one mbuf can't be allocated. */
184		if (mb == NULL) {
185			if (nm != NULL)
186				m_freem(nm);
187			return (NULL);
188		}
189
190		/* Book keeping. */
191		len -= (mb->m_flags & M_EXT) ? mb->m_ext.ext_size :
192			((mb->m_flags & M_PKTHDR) ? MHLEN : MLEN);
193		if (mtail != NULL)
194			mtail->m_next = mb;
195		else
196			nm = mb;
197		mtail = mb;
198		flags &= ~M_PKTHDR;	/* Only valid on the first mbuf. */
199	}
200	if (flags & M_EOR)
201		mtail->m_flags |= M_EOR;  /* Only valid on the last mbuf. */
202
203	/* If mbuf was supplied, append new chain to the end of it. */
204	if (m != NULL) {
205		for (mtail = m; mtail->m_next != NULL; mtail = mtail->m_next)
206			;
207		mtail->m_next = nm;
208		mtail->m_flags &= ~M_EOR;
209	} else
210		m = nm;
211
212	return (m);
213}
214
215/*
216 * Free an entire chain of mbufs and associated external buffers, if
217 * applicable.
218 */
219void
220m_freem(struct mbuf *mb)
221{
222
223	while (mb != NULL)
224		mb = m_free(mb);
225}
226
227/*-
228 * Configure a provided mbuf to refer to the provided external storage
229 * buffer and setup a reference count for said buffer.  If the setting
230 * up of the reference count fails, the M_EXT bit will not be set.  If
231 * successfull, the M_EXT bit is set in the mbuf's flags.
232 *
233 * Arguments:
234 *    mb     The existing mbuf to which to attach the provided buffer.
235 *    buf    The address of the provided external storage buffer.
236 *    size   The size of the provided buffer.
237 *    freef  A pointer to a routine that is responsible for freeing the
238 *           provided external storage buffer.
239 *    args   A pointer to an argument structure (of any type) to be passed
240 *           to the provided freef routine (may be NULL).
241 *    flags  Any other flags to be passed to the provided mbuf.
242 *    type   The type that the external storage buffer should be
243 *           labeled with.
244 *
245 * Returns:
246 *    Nothing.
247 */
248int
249m_extadd(struct mbuf *mb, caddr_t buf, u_int size,
250    void (*freef)(struct mbuf *, void *, void *), void *arg1, void *arg2,
251    int flags, int type, int wait)
252{
253	KASSERT(type != EXT_CLUSTER, ("%s: EXT_CLUSTER not allowed", __func__));
254
255	if (type != EXT_EXTREF)
256		mb->m_ext.ref_cnt = uma_zalloc(zone_ext_refcnt, wait);
257
258	if (mb->m_ext.ref_cnt == NULL)
259		return (ENOMEM);
260
261	*(mb->m_ext.ref_cnt) = 1;
262	mb->m_flags |= (M_EXT | flags);
263	mb->m_ext.ext_buf = buf;
264	mb->m_data = mb->m_ext.ext_buf;
265	mb->m_ext.ext_size = size;
266	mb->m_ext.ext_free = freef;
267	mb->m_ext.ext_arg1 = arg1;
268	mb->m_ext.ext_arg2 = arg2;
269	mb->m_ext.ext_type = type;
270	mb->m_ext.ext_flags = 0;
271
272	return (0);
273}
274
275/*
276 * Non-directly-exported function to clean up after mbufs with M_EXT
277 * storage attached to them if the reference count hits 1.
278 */
279void
280mb_free_ext(struct mbuf *m)
281{
282	int skipmbuf;
283
284	KASSERT((m->m_flags & M_EXT) == M_EXT, ("%s: M_EXT not set", __func__));
285	KASSERT(m->m_ext.ref_cnt != NULL, ("%s: ref_cnt not set", __func__));
286
287	/*
288	 * check if the header is embedded in the cluster
289	 */
290	skipmbuf = (m->m_flags & M_NOFREE);
291
292	/* Free attached storage if this mbuf is the only reference to it. */
293	if (*(m->m_ext.ref_cnt) == 1 ||
294	    atomic_fetchadd_int(m->m_ext.ref_cnt, -1) == 1) {
295		switch (m->m_ext.ext_type) {
296		case EXT_PACKET:	/* The packet zone is special. */
297			if (*(m->m_ext.ref_cnt) == 0)
298				*(m->m_ext.ref_cnt) = 1;
299			uma_zfree(zone_pack, m);
300			return;		/* Job done. */
301		case EXT_CLUSTER:
302			uma_zfree(zone_clust, m->m_ext.ext_buf);
303			break;
304		case EXT_JUMBOP:
305			uma_zfree(zone_jumbop, m->m_ext.ext_buf);
306			break;
307		case EXT_JUMBO9:
308			uma_zfree(zone_jumbo9, m->m_ext.ext_buf);
309			break;
310		case EXT_JUMBO16:
311			uma_zfree(zone_jumbo16, m->m_ext.ext_buf);
312			break;
313		case EXT_SFBUF:
314		case EXT_NET_DRV:
315		case EXT_MOD_TYPE:
316		case EXT_DISPOSABLE:
317			*(m->m_ext.ref_cnt) = 0;
318			uma_zfree(zone_ext_refcnt, __DEVOLATILE(u_int *,
319				m->m_ext.ref_cnt));
320			/* FALLTHROUGH */
321		case EXT_EXTREF:
322			KASSERT(m->m_ext.ext_free != NULL,
323				("%s: ext_free not set", __func__));
324			(*(m->m_ext.ext_free))(m, m->m_ext.ext_arg1,
325			    m->m_ext.ext_arg2);
326			break;
327		default:
328			KASSERT(m->m_ext.ext_type == 0,
329				("%s: unknown ext_type", __func__));
330		}
331	}
332	if (skipmbuf)
333		return;
334
335	/*
336	 * Free this mbuf back to the mbuf zone with all m_ext
337	 * information purged.
338	 */
339	m->m_ext.ext_buf = NULL;
340	m->m_ext.ext_free = NULL;
341	m->m_ext.ext_arg1 = NULL;
342	m->m_ext.ext_arg2 = NULL;
343	m->m_ext.ref_cnt = NULL;
344	m->m_ext.ext_size = 0;
345	m->m_ext.ext_type = 0;
346	m->m_ext.ext_flags = 0;
347	m->m_flags &= ~M_EXT;
348	uma_zfree(zone_mbuf, m);
349}
350
351/*
352 * Attach the cluster from *m to *n, set up m_ext in *n
353 * and bump the refcount of the cluster.
354 */
355static void
356mb_dupcl(struct mbuf *n, struct mbuf *m)
357{
358	KASSERT((m->m_flags & M_EXT) == M_EXT, ("%s: M_EXT not set", __func__));
359	KASSERT(m->m_ext.ref_cnt != NULL, ("%s: ref_cnt not set", __func__));
360	KASSERT((n->m_flags & M_EXT) == 0, ("%s: M_EXT set", __func__));
361
362	if (*(m->m_ext.ref_cnt) == 1)
363		*(m->m_ext.ref_cnt) += 1;
364	else
365		atomic_add_int(m->m_ext.ref_cnt, 1);
366	n->m_ext.ext_buf = m->m_ext.ext_buf;
367	n->m_ext.ext_free = m->m_ext.ext_free;
368	n->m_ext.ext_arg1 = m->m_ext.ext_arg1;
369	n->m_ext.ext_arg2 = m->m_ext.ext_arg2;
370	n->m_ext.ext_size = m->m_ext.ext_size;
371	n->m_ext.ref_cnt = m->m_ext.ref_cnt;
372	n->m_ext.ext_type = m->m_ext.ext_type;
373	n->m_ext.ext_flags = m->m_ext.ext_flags;
374	n->m_flags |= M_EXT;
375	n->m_flags |= m->m_flags & M_RDONLY;
376}
377
378/*
379 * Clean up mbuf (chain) from any tags and packet headers.
380 * If "all" is set then the first mbuf in the chain will be
381 * cleaned too.
382 */
383void
384m_demote(struct mbuf *m0, int all)
385{
386	struct mbuf *m;
387
388	for (m = all ? m0 : m0->m_next; m != NULL; m = m->m_next) {
389		if (m->m_flags & M_PKTHDR) {
390			m_tag_delete_chain(m, NULL);
391			m->m_flags &= ~M_PKTHDR;
392			bzero(&m->m_pkthdr, sizeof(struct pkthdr));
393		}
394		if (m != m0 && m->m_nextpkt != NULL) {
395			KASSERT(m->m_nextpkt == NULL,
396			    ("%s: m_nextpkt not NULL", __func__));
397			m_freem(m->m_nextpkt);
398			m->m_nextpkt = NULL;
399		}
400		m->m_flags = m->m_flags & (M_EXT|M_RDONLY|M_NOFREE);
401	}
402}
403
404/*
405 * Sanity checks on mbuf (chain) for use in KASSERT() and general
406 * debugging.
407 * Returns 0 or panics when bad and 1 on all tests passed.
408 * Sanitize, 0 to run M_SANITY_ACTION, 1 to garble things so they
409 * blow up later.
410 */
411int
412m_sanity(struct mbuf *m0, int sanitize)
413{
414	struct mbuf *m;
415	caddr_t a, b;
416	int pktlen = 0;
417
418#ifdef INVARIANTS
419#define	M_SANITY_ACTION(s)	panic("mbuf %p: " s, m)
420#else
421#define	M_SANITY_ACTION(s)	printf("mbuf %p: " s, m)
422#endif
423
424	for (m = m0; m != NULL; m = m->m_next) {
425		/*
426		 * Basic pointer checks.  If any of these fails then some
427		 * unrelated kernel memory before or after us is trashed.
428		 * No way to recover from that.
429		 */
430		a = ((m->m_flags & M_EXT) ? m->m_ext.ext_buf :
431			((m->m_flags & M_PKTHDR) ? (caddr_t)(&m->m_pktdat) :
432			 (caddr_t)(&m->m_dat)) );
433		b = (caddr_t)(a + (m->m_flags & M_EXT ? m->m_ext.ext_size :
434			((m->m_flags & M_PKTHDR) ? MHLEN : MLEN)));
435		if ((caddr_t)m->m_data < a)
436			M_SANITY_ACTION("m_data outside mbuf data range left");
437		if ((caddr_t)m->m_data > b)
438			M_SANITY_ACTION("m_data outside mbuf data range right");
439		if ((caddr_t)m->m_data + m->m_len > b)
440			M_SANITY_ACTION("m_data + m_len exeeds mbuf space");
441		if ((m->m_flags & M_PKTHDR) && m->m_pkthdr.header) {
442			if ((caddr_t)m->m_pkthdr.header < a ||
443			    (caddr_t)m->m_pkthdr.header > b)
444				M_SANITY_ACTION("m_pkthdr.header outside mbuf data range");
445		}
446
447		/* m->m_nextpkt may only be set on first mbuf in chain. */
448		if (m != m0 && m->m_nextpkt != NULL) {
449			if (sanitize) {
450				m_freem(m->m_nextpkt);
451				m->m_nextpkt = (struct mbuf *)0xDEADC0DE;
452			} else
453				M_SANITY_ACTION("m->m_nextpkt on in-chain mbuf");
454		}
455
456		/* packet length (not mbuf length!) calculation */
457		if (m0->m_flags & M_PKTHDR)
458			pktlen += m->m_len;
459
460		/* m_tags may only be attached to first mbuf in chain. */
461		if (m != m0 && m->m_flags & M_PKTHDR &&
462		    !SLIST_EMPTY(&m->m_pkthdr.tags)) {
463			if (sanitize) {
464				m_tag_delete_chain(m, NULL);
465				/* put in 0xDEADC0DE perhaps? */
466			} else
467				M_SANITY_ACTION("m_tags on in-chain mbuf");
468		}
469
470		/* M_PKTHDR may only be set on first mbuf in chain */
471		if (m != m0 && m->m_flags & M_PKTHDR) {
472			if (sanitize) {
473				bzero(&m->m_pkthdr, sizeof(m->m_pkthdr));
474				m->m_flags &= ~M_PKTHDR;
475				/* put in 0xDEADCODE and leave hdr flag in */
476			} else
477				M_SANITY_ACTION("M_PKTHDR on in-chain mbuf");
478		}
479	}
480	m = m0;
481	if (pktlen && pktlen != m->m_pkthdr.len) {
482		if (sanitize)
483			m->m_pkthdr.len = 0;
484		else
485			M_SANITY_ACTION("m_pkthdr.len != mbuf chain length");
486	}
487	return 1;
488
489#undef	M_SANITY_ACTION
490}
491
492
493/*
494 * "Move" mbuf pkthdr from "from" to "to".
495 * "from" must have M_PKTHDR set, and "to" must be empty.
496 */
497void
498m_move_pkthdr(struct mbuf *to, struct mbuf *from)
499{
500
501#if 0
502	/* see below for why these are not enabled */
503	M_ASSERTPKTHDR(to);
504	/* Note: with MAC, this may not be a good assertion. */
505	KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags),
506	    ("m_move_pkthdr: to has tags"));
507#endif
508#ifdef MAC
509	/*
510	 * XXXMAC: It could be this should also occur for non-MAC?
511	 */
512	if (to->m_flags & M_PKTHDR)
513		m_tag_delete_chain(to, NULL);
514#endif
515	to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
516	if ((to->m_flags & M_EXT) == 0)
517		to->m_data = to->m_pktdat;
518	to->m_pkthdr = from->m_pkthdr;		/* especially tags */
519	SLIST_INIT(&from->m_pkthdr.tags);	/* purge tags from src */
520	from->m_flags &= ~M_PKTHDR;
521}
522
523/*
524 * Duplicate "from"'s mbuf pkthdr in "to".
525 * "from" must have M_PKTHDR set, and "to" must be empty.
526 * In particular, this does a deep copy of the packet tags.
527 */
528int
529m_dup_pkthdr(struct mbuf *to, struct mbuf *from, int how)
530{
531
532#if 0
533	/*
534	 * The mbuf allocator only initializes the pkthdr
535	 * when the mbuf is allocated with m_gethdr(). Many users
536	 * (e.g. m_copy*, m_prepend) use m_get() and then
537	 * smash the pkthdr as needed causing these
538	 * assertions to trip.  For now just disable them.
539	 */
540	M_ASSERTPKTHDR(to);
541	/* Note: with MAC, this may not be a good assertion. */
542	KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags), ("m_dup_pkthdr: to has tags"));
543#endif
544	MBUF_CHECKSLEEP(how);
545#ifdef MAC
546	if (to->m_flags & M_PKTHDR)
547		m_tag_delete_chain(to, NULL);
548#endif
549	to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
550	if ((to->m_flags & M_EXT) == 0)
551		to->m_data = to->m_pktdat;
552	to->m_pkthdr = from->m_pkthdr;
553	SLIST_INIT(&to->m_pkthdr.tags);
554	return (m_tag_copy_chain(to, from, MBTOM(how)));
555}
556
557/*
558 * Lesser-used path for M_PREPEND:
559 * allocate new mbuf to prepend to chain,
560 * copy junk along.
561 */
562struct mbuf *
563m_prepend(struct mbuf *m, int len, int how)
564{
565	struct mbuf *mn;
566
567	if (m->m_flags & M_PKTHDR)
568		mn = m_gethdr(how, m->m_type);
569	else
570		mn = m_get(how, m->m_type);
571	if (mn == NULL) {
572		m_freem(m);
573		return (NULL);
574	}
575	if (m->m_flags & M_PKTHDR)
576		m_move_pkthdr(mn, m);
577	mn->m_next = m;
578	m = mn;
579	if(m->m_flags & M_PKTHDR) {
580		if (len < MHLEN)
581			MH_ALIGN(m, len);
582	} else {
583		if (len < MLEN)
584			M_ALIGN(m, len);
585	}
586	m->m_len = len;
587	return (m);
588}
589
590/*
591 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
592 * continuing for "len" bytes.  If len is M_COPYALL, copy to end of mbuf.
593 * The wait parameter is a choice of M_WAITOK/M_NOWAIT from caller.
594 * Note that the copy is read-only, because clusters are not copied,
595 * only their reference counts are incremented.
596 */
597struct mbuf *
598m_copym(struct mbuf *m, int off0, int len, int wait)
599{
600	struct mbuf *n, **np;
601	int off = off0;
602	struct mbuf *top;
603	int copyhdr = 0;
604
605	KASSERT(off >= 0, ("m_copym, negative off %d", off));
606	KASSERT(len >= 0, ("m_copym, negative len %d", len));
607	MBUF_CHECKSLEEP(wait);
608	if (off == 0 && m->m_flags & M_PKTHDR)
609		copyhdr = 1;
610	while (off > 0) {
611		KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
612		if (off < m->m_len)
613			break;
614		off -= m->m_len;
615		m = m->m_next;
616	}
617	np = &top;
618	top = 0;
619	while (len > 0) {
620		if (m == NULL) {
621			KASSERT(len == M_COPYALL,
622			    ("m_copym, length > size of mbuf chain"));
623			break;
624		}
625		if (copyhdr)
626			n = m_gethdr(wait, m->m_type);
627		else
628			n = m_get(wait, m->m_type);
629		*np = n;
630		if (n == NULL)
631			goto nospace;
632		if (copyhdr) {
633			if (!m_dup_pkthdr(n, m, wait))
634				goto nospace;
635			if (len == M_COPYALL)
636				n->m_pkthdr.len -= off0;
637			else
638				n->m_pkthdr.len = len;
639			copyhdr = 0;
640		}
641		n->m_len = min(len, m->m_len - off);
642		if (m->m_flags & M_EXT) {
643			n->m_data = m->m_data + off;
644			mb_dupcl(n, m);
645		} else
646			bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
647			    (u_int)n->m_len);
648		if (len != M_COPYALL)
649			len -= n->m_len;
650		off = 0;
651		m = m->m_next;
652		np = &n->m_next;
653	}
654
655	return (top);
656nospace:
657	m_freem(top);
658	return (NULL);
659}
660
661/*
662 * Returns mbuf chain with new head for the prepending case.
663 * Copies from mbuf (chain) n from off for len to mbuf (chain) m
664 * either prepending or appending the data.
665 * The resulting mbuf (chain) m is fully writeable.
666 * m is destination (is made writeable)
667 * n is source, off is offset in source, len is len from offset
668 * dir, 0 append, 1 prepend
669 * how, wait or nowait
670 */
671
672static int
673m_bcopyxxx(void *s, void *t, u_int len)
674{
675	bcopy(s, t, (size_t)len);
676	return 0;
677}
678
679struct mbuf *
680m_copymdata(struct mbuf *m, struct mbuf *n, int off, int len,
681    int prep, int how)
682{
683	struct mbuf *mm, *x, *z, *prev = NULL;
684	caddr_t p;
685	int i, nlen = 0;
686	caddr_t buf[MLEN];
687
688	KASSERT(m != NULL && n != NULL, ("m_copymdata, no target or source"));
689	KASSERT(off >= 0, ("m_copymdata, negative off %d", off));
690	KASSERT(len >= 0, ("m_copymdata, negative len %d", len));
691	KASSERT(prep == 0 || prep == 1, ("m_copymdata, unknown direction %d", prep));
692
693	mm = m;
694	if (!prep) {
695		while(mm->m_next) {
696			prev = mm;
697			mm = mm->m_next;
698		}
699	}
700	for (z = n; z != NULL; z = z->m_next)
701		nlen += z->m_len;
702	if (len == M_COPYALL)
703		len = nlen - off;
704	if (off + len > nlen || len < 1)
705		return NULL;
706
707	if (!M_WRITABLE(mm)) {
708		/* XXX: Use proper m_xxx function instead. */
709		x = m_getcl(how, MT_DATA, mm->m_flags);
710		if (x == NULL)
711			return NULL;
712		bcopy(mm->m_ext.ext_buf, x->m_ext.ext_buf, x->m_ext.ext_size);
713		p = x->m_ext.ext_buf + (mm->m_data - mm->m_ext.ext_buf);
714		x->m_data = p;
715		mm->m_next = NULL;
716		if (mm != m)
717			prev->m_next = x;
718		m_free(mm);
719		mm = x;
720	}
721
722	/*
723	 * Append/prepend the data.  Allocating mbufs as necessary.
724	 */
725	/* Shortcut if enough free space in first/last mbuf. */
726	if (!prep && M_TRAILINGSPACE(mm) >= len) {
727		m_apply(n, off, len, m_bcopyxxx, mtod(mm, caddr_t) +
728			 mm->m_len);
729		mm->m_len += len;
730		mm->m_pkthdr.len += len;
731		return m;
732	}
733	if (prep && M_LEADINGSPACE(mm) >= len) {
734		mm->m_data = mtod(mm, caddr_t) - len;
735		m_apply(n, off, len, m_bcopyxxx, mtod(mm, caddr_t));
736		mm->m_len += len;
737		mm->m_pkthdr.len += len;
738		return mm;
739	}
740
741	/* Expand first/last mbuf to cluster if possible. */
742	if (!prep && !(mm->m_flags & M_EXT) && len > M_TRAILINGSPACE(mm)) {
743		bcopy(mm->m_data, &buf, mm->m_len);
744		m_clget(mm, how);
745		if (!(mm->m_flags & M_EXT))
746			return NULL;
747		bcopy(&buf, mm->m_ext.ext_buf, mm->m_len);
748		mm->m_data = mm->m_ext.ext_buf;
749		mm->m_pkthdr.header = NULL;
750	}
751	if (prep && !(mm->m_flags & M_EXT) && len > M_LEADINGSPACE(mm)) {
752		bcopy(mm->m_data, &buf, mm->m_len);
753		m_clget(mm, how);
754		if (!(mm->m_flags & M_EXT))
755			return NULL;
756		bcopy(&buf, (caddr_t *)mm->m_ext.ext_buf +
757		       mm->m_ext.ext_size - mm->m_len, mm->m_len);
758		mm->m_data = (caddr_t)mm->m_ext.ext_buf +
759			      mm->m_ext.ext_size - mm->m_len;
760		mm->m_pkthdr.header = NULL;
761	}
762
763	/* Append/prepend as many mbuf (clusters) as necessary to fit len. */
764	if (!prep && len > M_TRAILINGSPACE(mm)) {
765		if (!m_getm(mm, len - M_TRAILINGSPACE(mm), how, MT_DATA))
766			return NULL;
767	}
768	if (prep && len > M_LEADINGSPACE(mm)) {
769		if (!(z = m_getm(NULL, len - M_LEADINGSPACE(mm), how, MT_DATA)))
770			return NULL;
771		i = 0;
772		for (x = z; x != NULL; x = x->m_next) {
773			i += x->m_flags & M_EXT ? x->m_ext.ext_size :
774			      (x->m_flags & M_PKTHDR ? MHLEN : MLEN);
775			if (!x->m_next)
776				break;
777		}
778		z->m_data += i - len;
779		m_move_pkthdr(mm, z);
780		x->m_next = mm;
781		mm = z;
782	}
783
784	/* Seek to start position in source mbuf. Optimization for long chains. */
785	while (off > 0) {
786		if (off < n->m_len)
787			break;
788		off -= n->m_len;
789		n = n->m_next;
790	}
791
792	/* Copy data into target mbuf. */
793	z = mm;
794	while (len > 0) {
795		KASSERT(z != NULL, ("m_copymdata, falling off target edge"));
796		i = M_TRAILINGSPACE(z);
797		m_apply(n, off, i, m_bcopyxxx, mtod(z, caddr_t) + z->m_len);
798		z->m_len += i;
799		/* fixup pkthdr.len if necessary */
800		if ((prep ? mm : m)->m_flags & M_PKTHDR)
801			(prep ? mm : m)->m_pkthdr.len += i;
802		off += i;
803		len -= i;
804		z = z->m_next;
805	}
806	return (prep ? mm : m);
807}
808
809/*
810 * Copy an entire packet, including header (which must be present).
811 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
812 * Note that the copy is read-only, because clusters are not copied,
813 * only their reference counts are incremented.
814 * Preserve alignment of the first mbuf so if the creator has left
815 * some room at the beginning (e.g. for inserting protocol headers)
816 * the copies still have the room available.
817 */
818struct mbuf *
819m_copypacket(struct mbuf *m, int how)
820{
821	struct mbuf *top, *n, *o;
822
823	MBUF_CHECKSLEEP(how);
824	n = m_get(how, m->m_type);
825	top = n;
826	if (n == NULL)
827		goto nospace;
828
829	if (!m_dup_pkthdr(n, m, how))
830		goto nospace;
831	n->m_len = m->m_len;
832	if (m->m_flags & M_EXT) {
833		n->m_data = m->m_data;
834		mb_dupcl(n, m);
835	} else {
836		n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
837		bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
838	}
839
840	m = m->m_next;
841	while (m) {
842		o = m_get(how, m->m_type);
843		if (o == NULL)
844			goto nospace;
845
846		n->m_next = o;
847		n = n->m_next;
848
849		n->m_len = m->m_len;
850		if (m->m_flags & M_EXT) {
851			n->m_data = m->m_data;
852			mb_dupcl(n, m);
853		} else {
854			bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
855		}
856
857		m = m->m_next;
858	}
859	return top;
860nospace:
861	m_freem(top);
862	return (NULL);
863}
864
865/*
866 * Copy data from an mbuf chain starting "off" bytes from the beginning,
867 * continuing for "len" bytes, into the indicated buffer.
868 */
869void
870m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
871{
872	u_int count;
873
874	KASSERT(off >= 0, ("m_copydata, negative off %d", off));
875	KASSERT(len >= 0, ("m_copydata, negative len %d", len));
876	while (off > 0) {
877		KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
878		if (off < m->m_len)
879			break;
880		off -= m->m_len;
881		m = m->m_next;
882	}
883	while (len > 0) {
884		KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
885		count = min(m->m_len - off, len);
886		bcopy(mtod(m, caddr_t) + off, cp, count);
887		len -= count;
888		cp += count;
889		off = 0;
890		m = m->m_next;
891	}
892}
893
894/*
895 * Copy a packet header mbuf chain into a completely new chain, including
896 * copying any mbuf clusters.  Use this instead of m_copypacket() when
897 * you need a writable copy of an mbuf chain.
898 */
899struct mbuf *
900m_dup(struct mbuf *m, int how)
901{
902	struct mbuf **p, *top = NULL;
903	int remain, moff, nsize;
904
905	MBUF_CHECKSLEEP(how);
906	/* Sanity check */
907	if (m == NULL)
908		return (NULL);
909	M_ASSERTPKTHDR(m);
910
911	/* While there's more data, get a new mbuf, tack it on, and fill it */
912	remain = m->m_pkthdr.len;
913	moff = 0;
914	p = &top;
915	while (remain > 0 || top == NULL) {	/* allow m->m_pkthdr.len == 0 */
916		struct mbuf *n;
917
918		/* Get the next new mbuf */
919		if (remain >= MINCLSIZE) {
920			n = m_getcl(how, m->m_type, 0);
921			nsize = MCLBYTES;
922		} else {
923			n = m_get(how, m->m_type);
924			nsize = MLEN;
925		}
926		if (n == NULL)
927			goto nospace;
928
929		if (top == NULL) {		/* First one, must be PKTHDR */
930			if (!m_dup_pkthdr(n, m, how)) {
931				m_free(n);
932				goto nospace;
933			}
934			if ((n->m_flags & M_EXT) == 0)
935				nsize = MHLEN;
936		}
937		n->m_len = 0;
938
939		/* Link it into the new chain */
940		*p = n;
941		p = &n->m_next;
942
943		/* Copy data from original mbuf(s) into new mbuf */
944		while (n->m_len < nsize && m != NULL) {
945			int chunk = min(nsize - n->m_len, m->m_len - moff);
946
947			bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
948			moff += chunk;
949			n->m_len += chunk;
950			remain -= chunk;
951			if (moff == m->m_len) {
952				m = m->m_next;
953				moff = 0;
954			}
955		}
956
957		/* Check correct total mbuf length */
958		KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
959		    	("%s: bogus m_pkthdr.len", __func__));
960	}
961	return (top);
962
963nospace:
964	m_freem(top);
965	return (NULL);
966}
967
968/*
969 * Concatenate mbuf chain n to m.
970 * Both chains must be of the same type (e.g. MT_DATA).
971 * Any m_pkthdr is not updated.
972 */
973void
974m_cat(struct mbuf *m, struct mbuf *n)
975{
976	while (m->m_next)
977		m = m->m_next;
978	while (n) {
979		if (!M_WRITABLE(m) ||
980		    M_TRAILINGSPACE(m) < n->m_len) {
981			/* just join the two chains */
982			m->m_next = n;
983			return;
984		}
985		/* splat the data from one into the other */
986		bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
987		    (u_int)n->m_len);
988		m->m_len += n->m_len;
989		n = m_free(n);
990	}
991}
992
993void
994m_adj(struct mbuf *mp, int req_len)
995{
996	int len = req_len;
997	struct mbuf *m;
998	int count;
999
1000	if ((m = mp) == NULL)
1001		return;
1002	if (len >= 0) {
1003		/*
1004		 * Trim from head.
1005		 */
1006		while (m != NULL && len > 0) {
1007			if (m->m_len <= len) {
1008				len -= m->m_len;
1009				m->m_len = 0;
1010				m = m->m_next;
1011			} else {
1012				m->m_len -= len;
1013				m->m_data += len;
1014				len = 0;
1015			}
1016		}
1017		if (mp->m_flags & M_PKTHDR)
1018			mp->m_pkthdr.len -= (req_len - len);
1019	} else {
1020		/*
1021		 * Trim from tail.  Scan the mbuf chain,
1022		 * calculating its length and finding the last mbuf.
1023		 * If the adjustment only affects this mbuf, then just
1024		 * adjust and return.  Otherwise, rescan and truncate
1025		 * after the remaining size.
1026		 */
1027		len = -len;
1028		count = 0;
1029		for (;;) {
1030			count += m->m_len;
1031			if (m->m_next == (struct mbuf *)0)
1032				break;
1033			m = m->m_next;
1034		}
1035		if (m->m_len >= len) {
1036			m->m_len -= len;
1037			if (mp->m_flags & M_PKTHDR)
1038				mp->m_pkthdr.len -= len;
1039			return;
1040		}
1041		count -= len;
1042		if (count < 0)
1043			count = 0;
1044		/*
1045		 * Correct length for chain is "count".
1046		 * Find the mbuf with last data, adjust its length,
1047		 * and toss data from remaining mbufs on chain.
1048		 */
1049		m = mp;
1050		if (m->m_flags & M_PKTHDR)
1051			m->m_pkthdr.len = count;
1052		for (; m; m = m->m_next) {
1053			if (m->m_len >= count) {
1054				m->m_len = count;
1055				if (m->m_next != NULL) {
1056					m_freem(m->m_next);
1057					m->m_next = NULL;
1058				}
1059				break;
1060			}
1061			count -= m->m_len;
1062		}
1063	}
1064}
1065
1066/*
1067 * Rearange an mbuf chain so that len bytes are contiguous
1068 * and in the data area of an mbuf (so that mtod will work
1069 * for a structure of size len).  Returns the resulting
1070 * mbuf chain on success, frees it and returns null on failure.
1071 * If there is room, it will add up to max_protohdr-len extra bytes to the
1072 * contiguous region in an attempt to avoid being called next time.
1073 */
1074struct mbuf *
1075m_pullup(struct mbuf *n, int len)
1076{
1077	struct mbuf *m;
1078	int count;
1079	int space;
1080
1081	/*
1082	 * If first mbuf has no cluster, and has room for len bytes
1083	 * without shifting current data, pullup into it,
1084	 * otherwise allocate a new mbuf to prepend to the chain.
1085	 */
1086	if ((n->m_flags & M_EXT) == 0 &&
1087	    n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
1088		if (n->m_len >= len)
1089			return (n);
1090		m = n;
1091		n = n->m_next;
1092		len -= m->m_len;
1093	} else {
1094		if (len > MHLEN)
1095			goto bad;
1096		m = m_get(M_NOWAIT, n->m_type);
1097		if (m == NULL)
1098			goto bad;
1099		if (n->m_flags & M_PKTHDR)
1100			m_move_pkthdr(m, n);
1101	}
1102	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1103	do {
1104		count = min(min(max(len, max_protohdr), space), n->m_len);
1105		bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1106		  (u_int)count);
1107		len -= count;
1108		m->m_len += count;
1109		n->m_len -= count;
1110		space -= count;
1111		if (n->m_len)
1112			n->m_data += count;
1113		else
1114			n = m_free(n);
1115	} while (len > 0 && n);
1116	if (len > 0) {
1117		(void) m_free(m);
1118		goto bad;
1119	}
1120	m->m_next = n;
1121	return (m);
1122bad:
1123	m_freem(n);
1124	return (NULL);
1125}
1126
1127/*
1128 * Like m_pullup(), except a new mbuf is always allocated, and we allow
1129 * the amount of empty space before the data in the new mbuf to be specified
1130 * (in the event that the caller expects to prepend later).
1131 */
1132int MSFail;
1133
1134struct mbuf *
1135m_copyup(struct mbuf *n, int len, int dstoff)
1136{
1137	struct mbuf *m;
1138	int count, space;
1139
1140	if (len > (MHLEN - dstoff))
1141		goto bad;
1142	m = m_get(M_NOWAIT, n->m_type);
1143	if (m == NULL)
1144		goto bad;
1145	if (n->m_flags & M_PKTHDR)
1146		m_move_pkthdr(m, n);
1147	m->m_data += dstoff;
1148	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1149	do {
1150		count = min(min(max(len, max_protohdr), space), n->m_len);
1151		memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
1152		    (unsigned)count);
1153		len -= count;
1154		m->m_len += count;
1155		n->m_len -= count;
1156		space -= count;
1157		if (n->m_len)
1158			n->m_data += count;
1159		else
1160			n = m_free(n);
1161	} while (len > 0 && n);
1162	if (len > 0) {
1163		(void) m_free(m);
1164		goto bad;
1165	}
1166	m->m_next = n;
1167	return (m);
1168 bad:
1169	m_freem(n);
1170	MSFail++;
1171	return (NULL);
1172}
1173
1174/*
1175 * Partition an mbuf chain in two pieces, returning the tail --
1176 * all but the first len0 bytes.  In case of failure, it returns NULL and
1177 * attempts to restore the chain to its original state.
1178 *
1179 * Note that the resulting mbufs might be read-only, because the new
1180 * mbuf can end up sharing an mbuf cluster with the original mbuf if
1181 * the "breaking point" happens to lie within a cluster mbuf. Use the
1182 * M_WRITABLE() macro to check for this case.
1183 */
1184struct mbuf *
1185m_split(struct mbuf *m0, int len0, int wait)
1186{
1187	struct mbuf *m, *n;
1188	u_int len = len0, remain;
1189
1190	MBUF_CHECKSLEEP(wait);
1191	for (m = m0; m && len > m->m_len; m = m->m_next)
1192		len -= m->m_len;
1193	if (m == NULL)
1194		return (NULL);
1195	remain = m->m_len - len;
1196	if (m0->m_flags & M_PKTHDR && remain == 0) {
1197		n = m_gethdr(wait, m0->m_type);
1198			return (NULL);
1199		n->m_next = m->m_next;
1200		m->m_next = NULL;
1201		n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1202		n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1203		m0->m_pkthdr.len = len0;
1204		return (n);
1205	} else if (m0->m_flags & M_PKTHDR) {
1206		n = m_gethdr(wait, m0->m_type);
1207		if (n == NULL)
1208			return (NULL);
1209		n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1210		n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1211		m0->m_pkthdr.len = len0;
1212		if (m->m_flags & M_EXT)
1213			goto extpacket;
1214		if (remain > MHLEN) {
1215			/* m can't be the lead packet */
1216			MH_ALIGN(n, 0);
1217			n->m_next = m_split(m, len, wait);
1218			if (n->m_next == NULL) {
1219				(void) m_free(n);
1220				return (NULL);
1221			} else {
1222				n->m_len = 0;
1223				return (n);
1224			}
1225		} else
1226			MH_ALIGN(n, remain);
1227	} else if (remain == 0) {
1228		n = m->m_next;
1229		m->m_next = NULL;
1230		return (n);
1231	} else {
1232		n = m_get(wait, m->m_type);
1233		if (n == NULL)
1234			return (NULL);
1235		M_ALIGN(n, remain);
1236	}
1237extpacket:
1238	if (m->m_flags & M_EXT) {
1239		n->m_data = m->m_data + len;
1240		mb_dupcl(n, m);
1241	} else {
1242		bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1243	}
1244	n->m_len = remain;
1245	m->m_len = len;
1246	n->m_next = m->m_next;
1247	m->m_next = NULL;
1248	return (n);
1249}
1250/*
1251 * Routine to copy from device local memory into mbufs.
1252 * Note that `off' argument is offset into first mbuf of target chain from
1253 * which to begin copying the data to.
1254 */
1255struct mbuf *
1256m_devget(char *buf, int totlen, int off, struct ifnet *ifp,
1257    void (*copy)(char *from, caddr_t to, u_int len))
1258{
1259	struct mbuf *m;
1260	struct mbuf *top = NULL, **mp = &top;
1261	int len;
1262
1263	if (off < 0 || off > MHLEN)
1264		return (NULL);
1265
1266	while (totlen > 0) {
1267		if (top == NULL) {	/* First one, must be PKTHDR */
1268			if (totlen + off >= MINCLSIZE) {
1269				m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1270				len = MCLBYTES;
1271			} else {
1272				m = m_gethdr(M_NOWAIT, MT_DATA);
1273				len = MHLEN;
1274
1275				/* Place initial small packet/header at end of mbuf */
1276				if (m && totlen + off + max_linkhdr <= MLEN) {
1277					m->m_data += max_linkhdr;
1278					len -= max_linkhdr;
1279				}
1280			}
1281			if (m == NULL)
1282				return NULL;
1283			m->m_pkthdr.rcvif = ifp;
1284			m->m_pkthdr.len = totlen;
1285		} else {
1286			if (totlen + off >= MINCLSIZE) {
1287				m = m_getcl(M_NOWAIT, MT_DATA, 0);
1288				len = MCLBYTES;
1289			} else {
1290				m = m_get(M_NOWAIT, MT_DATA);
1291				len = MLEN;
1292			}
1293			if (m == NULL) {
1294				m_freem(top);
1295				return NULL;
1296			}
1297		}
1298		if (off) {
1299			m->m_data += off;
1300			len -= off;
1301			off = 0;
1302		}
1303		m->m_len = len = min(totlen, len);
1304		if (copy)
1305			copy(buf, mtod(m, caddr_t), (u_int)len);
1306		else
1307			bcopy(buf, mtod(m, caddr_t), (u_int)len);
1308		buf += len;
1309		*mp = m;
1310		mp = &m->m_next;
1311		totlen -= len;
1312	}
1313	return (top);
1314}
1315
1316/*
1317 * Copy data from a buffer back into the indicated mbuf chain,
1318 * starting "off" bytes from the beginning, extending the mbuf
1319 * chain if necessary.
1320 */
1321void
1322m_copyback(struct mbuf *m0, int off, int len, c_caddr_t cp)
1323{
1324	int mlen;
1325	struct mbuf *m = m0, *n;
1326	int totlen = 0;
1327
1328	if (m0 == NULL)
1329		return;
1330	while (off > (mlen = m->m_len)) {
1331		off -= mlen;
1332		totlen += mlen;
1333		if (m->m_next == NULL) {
1334			n = m_get(M_NOWAIT, m->m_type);
1335			if (n == NULL)
1336				goto out;
1337			bzero(mtod(n, caddr_t), MLEN);
1338			n->m_len = min(MLEN, len + off);
1339			m->m_next = n;
1340		}
1341		m = m->m_next;
1342	}
1343	while (len > 0) {
1344		if (m->m_next == NULL && (len > m->m_len - off)) {
1345			m->m_len += min(len - (m->m_len - off),
1346			    M_TRAILINGSPACE(m));
1347		}
1348		mlen = min (m->m_len - off, len);
1349		bcopy(cp, off + mtod(m, caddr_t), (u_int)mlen);
1350		cp += mlen;
1351		len -= mlen;
1352		mlen += off;
1353		off = 0;
1354		totlen += mlen;
1355		if (len == 0)
1356			break;
1357		if (m->m_next == NULL) {
1358			n = m_get(M_NOWAIT, m->m_type);
1359			if (n == NULL)
1360				break;
1361			n->m_len = min(MLEN, len);
1362			m->m_next = n;
1363		}
1364		m = m->m_next;
1365	}
1366out:	if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1367		m->m_pkthdr.len = totlen;
1368}
1369
1370/*
1371 * Append the specified data to the indicated mbuf chain,
1372 * Extend the mbuf chain if the new data does not fit in
1373 * existing space.
1374 *
1375 * Return 1 if able to complete the job; otherwise 0.
1376 */
1377int
1378m_append(struct mbuf *m0, int len, c_caddr_t cp)
1379{
1380	struct mbuf *m, *n;
1381	int remainder, space;
1382
1383	for (m = m0; m->m_next != NULL; m = m->m_next)
1384		;
1385	remainder = len;
1386	space = M_TRAILINGSPACE(m);
1387	if (space > 0) {
1388		/*
1389		 * Copy into available space.
1390		 */
1391		if (space > remainder)
1392			space = remainder;
1393		bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
1394		m->m_len += space;
1395		cp += space, remainder -= space;
1396	}
1397	while (remainder > 0) {
1398		/*
1399		 * Allocate a new mbuf; could check space
1400		 * and allocate a cluster instead.
1401		 */
1402		n = m_get(M_NOWAIT, m->m_type);
1403		if (n == NULL)
1404			break;
1405		n->m_len = min(MLEN, remainder);
1406		bcopy(cp, mtod(n, caddr_t), n->m_len);
1407		cp += n->m_len, remainder -= n->m_len;
1408		m->m_next = n;
1409		m = n;
1410	}
1411	if (m0->m_flags & M_PKTHDR)
1412		m0->m_pkthdr.len += len - remainder;
1413	return (remainder == 0);
1414}
1415
1416/*
1417 * Apply function f to the data in an mbuf chain starting "off" bytes from
1418 * the beginning, continuing for "len" bytes.
1419 */
1420int
1421m_apply(struct mbuf *m, int off, int len,
1422    int (*f)(void *, void *, u_int), void *arg)
1423{
1424	u_int count;
1425	int rval;
1426
1427	KASSERT(off >= 0, ("m_apply, negative off %d", off));
1428	KASSERT(len >= 0, ("m_apply, negative len %d", len));
1429	while (off > 0) {
1430		KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1431		if (off < m->m_len)
1432			break;
1433		off -= m->m_len;
1434		m = m->m_next;
1435	}
1436	while (len > 0) {
1437		KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1438		count = min(m->m_len - off, len);
1439		rval = (*f)(arg, mtod(m, caddr_t) + off, count);
1440		if (rval)
1441			return (rval);
1442		len -= count;
1443		off = 0;
1444		m = m->m_next;
1445	}
1446	return (0);
1447}
1448
1449/*
1450 * Return a pointer to mbuf/offset of location in mbuf chain.
1451 */
1452struct mbuf *
1453m_getptr(struct mbuf *m, int loc, int *off)
1454{
1455
1456	while (loc >= 0) {
1457		/* Normal end of search. */
1458		if (m->m_len > loc) {
1459			*off = loc;
1460			return (m);
1461		} else {
1462			loc -= m->m_len;
1463			if (m->m_next == NULL) {
1464				if (loc == 0) {
1465					/* Point at the end of valid data. */
1466					*off = m->m_len;
1467					return (m);
1468				}
1469				return (NULL);
1470			}
1471			m = m->m_next;
1472		}
1473	}
1474	return (NULL);
1475}
1476
1477void
1478m_print(const struct mbuf *m, int maxlen)
1479{
1480	int len;
1481	int pdata;
1482	const struct mbuf *m2;
1483
1484	if (m == NULL) {
1485		printf("mbuf: %p\n", m);
1486		return;
1487	}
1488
1489	if (m->m_flags & M_PKTHDR)
1490		len = m->m_pkthdr.len;
1491	else
1492		len = -1;
1493	m2 = m;
1494	while (m2 != NULL && (len == -1 || len)) {
1495		pdata = m2->m_len;
1496		if (maxlen != -1 && pdata > maxlen)
1497			pdata = maxlen;
1498		printf("mbuf: %p len: %d, next: %p, %b%s", m2, m2->m_len,
1499		    m2->m_next, m2->m_flags, "\20\20freelist\17skipfw"
1500		    "\11proto5\10proto4\7proto3\6proto2\5proto1\4rdonly"
1501		    "\3eor\2pkthdr\1ext", pdata ? "" : "\n");
1502		if (pdata)
1503			printf(", %*D\n", pdata, (u_char *)m2->m_data, "-");
1504		if (len != -1)
1505			len -= m2->m_len;
1506		m2 = m2->m_next;
1507	}
1508	if (len > 0)
1509		printf("%d bytes unaccounted for.\n", len);
1510	return;
1511}
1512
1513u_int
1514m_fixhdr(struct mbuf *m0)
1515{
1516	u_int len;
1517
1518	len = m_length(m0, NULL);
1519	m0->m_pkthdr.len = len;
1520	return (len);
1521}
1522
1523u_int
1524m_length(struct mbuf *m0, struct mbuf **last)
1525{
1526	struct mbuf *m;
1527	u_int len;
1528
1529	len = 0;
1530	for (m = m0; m != NULL; m = m->m_next) {
1531		len += m->m_len;
1532		if (m->m_next == NULL)
1533			break;
1534	}
1535	if (last != NULL)
1536		*last = m;
1537	return (len);
1538}
1539
1540/*
1541 * Defragment a mbuf chain, returning the shortest possible
1542 * chain of mbufs and clusters.  If allocation fails and
1543 * this cannot be completed, NULL will be returned, but
1544 * the passed in chain will be unchanged.  Upon success,
1545 * the original chain will be freed, and the new chain
1546 * will be returned.
1547 *
1548 * If a non-packet header is passed in, the original
1549 * mbuf (chain?) will be returned unharmed.
1550 */
1551struct mbuf *
1552m_defrag(struct mbuf *m0, int how)
1553{
1554	struct mbuf *m_new = NULL, *m_final = NULL;
1555	int progress = 0, length;
1556
1557	MBUF_CHECKSLEEP(how);
1558	if (!(m0->m_flags & M_PKTHDR))
1559		return (m0);
1560
1561	m_fixhdr(m0); /* Needed sanity check */
1562
1563#ifdef MBUF_STRESS_TEST
1564	if (m_defragrandomfailures) {
1565		int temp = arc4random() & 0xff;
1566		if (temp == 0xba)
1567			goto nospace;
1568	}
1569#endif
1570
1571	if (m0->m_pkthdr.len > MHLEN)
1572		m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1573	else
1574		m_final = m_gethdr(how, MT_DATA);
1575
1576	if (m_final == NULL)
1577		goto nospace;
1578
1579	if (m_dup_pkthdr(m_final, m0, how) == 0)
1580		goto nospace;
1581
1582	m_new = m_final;
1583
1584	while (progress < m0->m_pkthdr.len) {
1585		length = m0->m_pkthdr.len - progress;
1586		if (length > MCLBYTES)
1587			length = MCLBYTES;
1588
1589		if (m_new == NULL) {
1590			if (length > MLEN)
1591				m_new = m_getcl(how, MT_DATA, 0);
1592			else
1593				m_new = m_get(how, MT_DATA);
1594			if (m_new == NULL)
1595				goto nospace;
1596		}
1597
1598		m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1599		progress += length;
1600		m_new->m_len = length;
1601		if (m_new != m_final)
1602			m_cat(m_final, m_new);
1603		m_new = NULL;
1604	}
1605#ifdef MBUF_STRESS_TEST
1606	if (m0->m_next == NULL)
1607		m_defraguseless++;
1608#endif
1609	m_freem(m0);
1610	m0 = m_final;
1611#ifdef MBUF_STRESS_TEST
1612	m_defragpackets++;
1613	m_defragbytes += m0->m_pkthdr.len;
1614#endif
1615	return (m0);
1616nospace:
1617#ifdef MBUF_STRESS_TEST
1618	m_defragfailure++;
1619#endif
1620	if (m_final)
1621		m_freem(m_final);
1622	return (NULL);
1623}
1624
1625/*
1626 * Defragment an mbuf chain, returning at most maxfrags separate
1627 * mbufs+clusters.  If this is not possible NULL is returned and
1628 * the original mbuf chain is left in it's present (potentially
1629 * modified) state.  We use two techniques: collapsing consecutive
1630 * mbufs and replacing consecutive mbufs by a cluster.
1631 *
1632 * NB: this should really be named m_defrag but that name is taken
1633 */
1634struct mbuf *
1635m_collapse(struct mbuf *m0, int how, int maxfrags)
1636{
1637	struct mbuf *m, *n, *n2, **prev;
1638	u_int curfrags;
1639
1640	/*
1641	 * Calculate the current number of frags.
1642	 */
1643	curfrags = 0;
1644	for (m = m0; m != NULL; m = m->m_next)
1645		curfrags++;
1646	/*
1647	 * First, try to collapse mbufs.  Note that we always collapse
1648	 * towards the front so we don't need to deal with moving the
1649	 * pkthdr.  This may be suboptimal if the first mbuf has much
1650	 * less data than the following.
1651	 */
1652	m = m0;
1653again:
1654	for (;;) {
1655		n = m->m_next;
1656		if (n == NULL)
1657			break;
1658		if (M_WRITABLE(m) &&
1659		    n->m_len < M_TRAILINGSPACE(m)) {
1660			bcopy(mtod(n, void *), mtod(m, char *) + m->m_len,
1661				n->m_len);
1662			m->m_len += n->m_len;
1663			m->m_next = n->m_next;
1664			m_free(n);
1665			if (--curfrags <= maxfrags)
1666				return m0;
1667		} else
1668			m = n;
1669	}
1670	KASSERT(maxfrags > 1,
1671		("maxfrags %u, but normal collapse failed", maxfrags));
1672	/*
1673	 * Collapse consecutive mbufs to a cluster.
1674	 */
1675	prev = &m0->m_next;		/* NB: not the first mbuf */
1676	while ((n = *prev) != NULL) {
1677		if ((n2 = n->m_next) != NULL &&
1678		    n->m_len + n2->m_len < MCLBYTES) {
1679			m = m_getcl(how, MT_DATA, 0);
1680			if (m == NULL)
1681				goto bad;
1682			bcopy(mtod(n, void *), mtod(m, void *), n->m_len);
1683			bcopy(mtod(n2, void *), mtod(m, char *) + n->m_len,
1684				n2->m_len);
1685			m->m_len = n->m_len + n2->m_len;
1686			m->m_next = n2->m_next;
1687			*prev = m;
1688			m_free(n);
1689			m_free(n2);
1690			if (--curfrags <= maxfrags)	/* +1 cl -2 mbufs */
1691				return m0;
1692			/*
1693			 * Still not there, try the normal collapse
1694			 * again before we allocate another cluster.
1695			 */
1696			goto again;
1697		}
1698		prev = &n->m_next;
1699	}
1700	/*
1701	 * No place where we can collapse to a cluster; punt.
1702	 * This can occur if, for example, you request 2 frags
1703	 * but the packet requires that both be clusters (we
1704	 * never reallocate the first mbuf to avoid moving the
1705	 * packet header).
1706	 */
1707bad:
1708	return NULL;
1709}
1710
1711#ifdef MBUF_STRESS_TEST
1712
1713/*
1714 * Fragment an mbuf chain.  There's no reason you'd ever want to do
1715 * this in normal usage, but it's great for stress testing various
1716 * mbuf consumers.
1717 *
1718 * If fragmentation is not possible, the original chain will be
1719 * returned.
1720 *
1721 * Possible length values:
1722 * 0	 no fragmentation will occur
1723 * > 0	each fragment will be of the specified length
1724 * -1	each fragment will be the same random value in length
1725 * -2	each fragment's length will be entirely random
1726 * (Random values range from 1 to 256)
1727 */
1728struct mbuf *
1729m_fragment(struct mbuf *m0, int how, int length)
1730{
1731	struct mbuf *m_new = NULL, *m_final = NULL;
1732	int progress = 0;
1733
1734	if (!(m0->m_flags & M_PKTHDR))
1735		return (m0);
1736
1737	if ((length == 0) || (length < -2))
1738		return (m0);
1739
1740	m_fixhdr(m0); /* Needed sanity check */
1741
1742	m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1743
1744	if (m_final == NULL)
1745		goto nospace;
1746
1747	if (m_dup_pkthdr(m_final, m0, how) == 0)
1748		goto nospace;
1749
1750	m_new = m_final;
1751
1752	if (length == -1)
1753		length = 1 + (arc4random() & 255);
1754
1755	while (progress < m0->m_pkthdr.len) {
1756		int fraglen;
1757
1758		if (length > 0)
1759			fraglen = length;
1760		else
1761			fraglen = 1 + (arc4random() & 255);
1762		if (fraglen > m0->m_pkthdr.len - progress)
1763			fraglen = m0->m_pkthdr.len - progress;
1764
1765		if (fraglen > MCLBYTES)
1766			fraglen = MCLBYTES;
1767
1768		if (m_new == NULL) {
1769			m_new = m_getcl(how, MT_DATA, 0);
1770			if (m_new == NULL)
1771				goto nospace;
1772		}
1773
1774		m_copydata(m0, progress, fraglen, mtod(m_new, caddr_t));
1775		progress += fraglen;
1776		m_new->m_len = fraglen;
1777		if (m_new != m_final)
1778			m_cat(m_final, m_new);
1779		m_new = NULL;
1780	}
1781	m_freem(m0);
1782	m0 = m_final;
1783	return (m0);
1784nospace:
1785	if (m_final)
1786		m_freem(m_final);
1787	/* Return the original chain on failure */
1788	return (m0);
1789}
1790
1791#endif
1792
1793/*
1794 * Copy the contents of uio into a properly sized mbuf chain.
1795 */
1796struct mbuf *
1797m_uiotombuf(struct uio *uio, int how, int len, int align, int flags)
1798{
1799	struct mbuf *m, *mb;
1800	int error, length;
1801	ssize_t total;
1802	int progress = 0;
1803
1804	/*
1805	 * len can be zero or an arbitrary large value bound by
1806	 * the total data supplied by the uio.
1807	 */
1808	if (len > 0)
1809		total = min(uio->uio_resid, len);
1810	else
1811		total = uio->uio_resid;
1812
1813	/*
1814	 * The smallest unit returned by m_getm2() is a single mbuf
1815	 * with pkthdr.  We can't align past it.
1816	 */
1817	if (align >= MHLEN)
1818		return (NULL);
1819
1820	/*
1821	 * Give us the full allocation or nothing.
1822	 * If len is zero return the smallest empty mbuf.
1823	 */
1824	m = m_getm2(NULL, max(total + align, 1), how, MT_DATA, flags);
1825	if (m == NULL)
1826		return (NULL);
1827	m->m_data += align;
1828
1829	/* Fill all mbufs with uio data and update header information. */
1830	for (mb = m; mb != NULL; mb = mb->m_next) {
1831		length = min(M_TRAILINGSPACE(mb), total - progress);
1832
1833		error = uiomove(mtod(mb, void *), length, uio);
1834		if (error) {
1835			m_freem(m);
1836			return (NULL);
1837		}
1838
1839		mb->m_len = length;
1840		progress += length;
1841		if (flags & M_PKTHDR)
1842			m->m_pkthdr.len += length;
1843	}
1844	KASSERT(progress == total, ("%s: progress != total", __func__));
1845
1846	return (m);
1847}
1848
1849/*
1850 * Copy an mbuf chain into a uio limited by len if set.
1851 */
1852int
1853m_mbuftouio(struct uio *uio, struct mbuf *m, int len)
1854{
1855	int error, length, total;
1856	int progress = 0;
1857
1858	if (len > 0)
1859		total = min(uio->uio_resid, len);
1860	else
1861		total = uio->uio_resid;
1862
1863	/* Fill the uio with data from the mbufs. */
1864	for (; m != NULL; m = m->m_next) {
1865		length = min(m->m_len, total - progress);
1866
1867		error = uiomove(mtod(m, void *), length, uio);
1868		if (error)
1869			return (error);
1870
1871		progress += length;
1872	}
1873
1874	return (0);
1875}
1876
1877/*
1878 * Set the m_data pointer of a newly-allocated mbuf
1879 * to place an object of the specified size at the
1880 * end of the mbuf, longword aligned.
1881 */
1882void
1883m_align(struct mbuf *m, int len)
1884{
1885#ifdef INVARIANTS
1886	const char *msg = "%s: not a virgin mbuf";
1887#endif
1888	int adjust;
1889
1890	if (m->m_flags & M_EXT) {
1891		KASSERT(m->m_data == m->m_ext.ext_buf, (msg, __func__));
1892		adjust = m->m_ext.ext_size - len;
1893	} else if (m->m_flags & M_PKTHDR) {
1894		KASSERT(m->m_data == m->m_pktdat, (msg, __func__));
1895		adjust = MHLEN - len;
1896	} else {
1897		KASSERT(m->m_data == m->m_dat, (msg, __func__));
1898		adjust = MLEN - len;
1899	}
1900
1901	m->m_data += adjust &~ (sizeof(long)-1);
1902}
1903
1904/*
1905 * Create a writable copy of the mbuf chain.  While doing this
1906 * we compact the chain with a goal of producing a chain with
1907 * at most two mbufs.  The second mbuf in this chain is likely
1908 * to be a cluster.  The primary purpose of this work is to create
1909 * a writable packet for encryption, compression, etc.  The
1910 * secondary goal is to linearize the data so the data can be
1911 * passed to crypto hardware in the most efficient manner possible.
1912 */
1913struct mbuf *
1914m_unshare(struct mbuf *m0, int how)
1915{
1916	struct mbuf *m, *mprev;
1917	struct mbuf *n, *mfirst, *mlast;
1918	int len, off;
1919
1920	mprev = NULL;
1921	for (m = m0; m != NULL; m = mprev->m_next) {
1922		/*
1923		 * Regular mbufs are ignored unless there's a cluster
1924		 * in front of it that we can use to coalesce.  We do
1925		 * the latter mainly so later clusters can be coalesced
1926		 * also w/o having to handle them specially (i.e. convert
1927		 * mbuf+cluster -> cluster).  This optimization is heavily
1928		 * influenced by the assumption that we're running over
1929		 * Ethernet where MCLBYTES is large enough that the max
1930		 * packet size will permit lots of coalescing into a
1931		 * single cluster.  This in turn permits efficient
1932		 * crypto operations, especially when using hardware.
1933		 */
1934		if ((m->m_flags & M_EXT) == 0) {
1935			if (mprev && (mprev->m_flags & M_EXT) &&
1936			    m->m_len <= M_TRAILINGSPACE(mprev)) {
1937				/* XXX: this ignores mbuf types */
1938				memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1939				       mtod(m, caddr_t), m->m_len);
1940				mprev->m_len += m->m_len;
1941				mprev->m_next = m->m_next;	/* unlink from chain */
1942				m_free(m);			/* reclaim mbuf */
1943#if 0
1944				newipsecstat.ips_mbcoalesced++;
1945#endif
1946			} else {
1947				mprev = m;
1948			}
1949			continue;
1950		}
1951		/*
1952		 * Writable mbufs are left alone (for now).
1953		 */
1954		if (M_WRITABLE(m)) {
1955			mprev = m;
1956			continue;
1957		}
1958
1959		/*
1960		 * Not writable, replace with a copy or coalesce with
1961		 * the previous mbuf if possible (since we have to copy
1962		 * it anyway, we try to reduce the number of mbufs and
1963		 * clusters so that future work is easier).
1964		 */
1965		KASSERT(m->m_flags & M_EXT, ("m_flags 0x%x", m->m_flags));
1966		/* NB: we only coalesce into a cluster or larger */
1967		if (mprev != NULL && (mprev->m_flags & M_EXT) &&
1968		    m->m_len <= M_TRAILINGSPACE(mprev)) {
1969			/* XXX: this ignores mbuf types */
1970			memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1971			       mtod(m, caddr_t), m->m_len);
1972			mprev->m_len += m->m_len;
1973			mprev->m_next = m->m_next;	/* unlink from chain */
1974			m_free(m);			/* reclaim mbuf */
1975#if 0
1976			newipsecstat.ips_clcoalesced++;
1977#endif
1978			continue;
1979		}
1980
1981		/*
1982		 * Allocate new space to hold the copy and copy the data.
1983		 * We deal with jumbo mbufs (i.e. m_len > MCLBYTES) by
1984		 * splitting them into clusters.  We could just malloc a
1985		 * buffer and make it external but too many device drivers
1986		 * don't know how to break up the non-contiguous memory when
1987		 * doing DMA.
1988		 */
1989		n = m_getcl(how, m->m_type, m->m_flags);
1990		if (n == NULL) {
1991			m_freem(m0);
1992			return (NULL);
1993		}
1994		len = m->m_len;
1995		off = 0;
1996		mfirst = n;
1997		mlast = NULL;
1998		for (;;) {
1999			int cc = min(len, MCLBYTES);
2000			memcpy(mtod(n, caddr_t), mtod(m, caddr_t) + off, cc);
2001			n->m_len = cc;
2002			if (mlast != NULL)
2003				mlast->m_next = n;
2004			mlast = n;
2005#if 0
2006			newipsecstat.ips_clcopied++;
2007#endif
2008
2009			len -= cc;
2010			if (len <= 0)
2011				break;
2012			off += cc;
2013
2014			n = m_getcl(how, m->m_type, m->m_flags);
2015			if (n == NULL) {
2016				m_freem(mfirst);
2017				m_freem(m0);
2018				return (NULL);
2019			}
2020		}
2021		n->m_next = m->m_next;
2022		if (mprev == NULL)
2023			m0 = mfirst;		/* new head of chain */
2024		else
2025			mprev->m_next = mfirst;	/* replace old mbuf */
2026		m_free(m);			/* release old mbuf */
2027		mprev = mfirst;
2028	}
2029	return (m0);
2030}
2031
2032#ifdef MBUF_PROFILING
2033
2034#define MP_BUCKETS 32 /* don't just change this as things may overflow.*/
2035struct mbufprofile {
2036	uintmax_t wasted[MP_BUCKETS];
2037	uintmax_t used[MP_BUCKETS];
2038	uintmax_t segments[MP_BUCKETS];
2039} mbprof;
2040
2041#define MP_MAXDIGITS 21	/* strlen("16,000,000,000,000,000,000") == 21 */
2042#define MP_NUMLINES 6
2043#define MP_NUMSPERLINE 16
2044#define MP_EXTRABYTES 64	/* > strlen("used:\nwasted:\nsegments:\n") */
2045/* work out max space needed and add a bit of spare space too */
2046#define MP_MAXLINE ((MP_MAXDIGITS+1) * MP_NUMSPERLINE)
2047#define MP_BUFSIZE ((MP_MAXLINE * MP_NUMLINES) + 1 + MP_EXTRABYTES)
2048
2049char mbprofbuf[MP_BUFSIZE];
2050
2051void
2052m_profile(struct mbuf *m)
2053{
2054	int segments = 0;
2055	int used = 0;
2056	int wasted = 0;
2057
2058	while (m) {
2059		segments++;
2060		used += m->m_len;
2061		if (m->m_flags & M_EXT) {
2062			wasted += MHLEN - sizeof(m->m_ext) +
2063			    m->m_ext.ext_size - m->m_len;
2064		} else {
2065			if (m->m_flags & M_PKTHDR)
2066				wasted += MHLEN - m->m_len;
2067			else
2068				wasted += MLEN - m->m_len;
2069		}
2070		m = m->m_next;
2071	}
2072	/* be paranoid.. it helps */
2073	if (segments > MP_BUCKETS - 1)
2074		segments = MP_BUCKETS - 1;
2075	if (used > 100000)
2076		used = 100000;
2077	if (wasted > 100000)
2078		wasted = 100000;
2079	/* store in the appropriate bucket */
2080	/* don't bother locking. if it's slightly off, so what? */
2081	mbprof.segments[segments]++;
2082	mbprof.used[fls(used)]++;
2083	mbprof.wasted[fls(wasted)]++;
2084}
2085
2086static void
2087mbprof_textify(void)
2088{
2089	int offset;
2090	char *c;
2091	uint64_t *p;
2092
2093
2094	p = &mbprof.wasted[0];
2095	c = mbprofbuf;
2096	offset = snprintf(c, MP_MAXLINE + 10,
2097	    "wasted:\n"
2098	    "%ju %ju %ju %ju %ju %ju %ju %ju "
2099	    "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2100	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2101	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2102#ifdef BIG_ARRAY
2103	p = &mbprof.wasted[16];
2104	c += offset;
2105	offset = snprintf(c, MP_MAXLINE,
2106	    "%ju %ju %ju %ju %ju %ju %ju %ju "
2107	    "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2108	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2109	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2110#endif
2111	p = &mbprof.used[0];
2112	c += offset;
2113	offset = snprintf(c, MP_MAXLINE + 10,
2114	    "used:\n"
2115	    "%ju %ju %ju %ju %ju %ju %ju %ju "
2116	    "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2117	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2118	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2119#ifdef BIG_ARRAY
2120	p = &mbprof.used[16];
2121	c += offset;
2122	offset = snprintf(c, MP_MAXLINE,
2123	    "%ju %ju %ju %ju %ju %ju %ju %ju "
2124	    "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2125	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2126	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2127#endif
2128	p = &mbprof.segments[0];
2129	c += offset;
2130	offset = snprintf(c, MP_MAXLINE + 10,
2131	    "segments:\n"
2132	    "%ju %ju %ju %ju %ju %ju %ju %ju "
2133	    "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2134	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2135	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2136#ifdef BIG_ARRAY
2137	p = &mbprof.segments[16];
2138	c += offset;
2139	offset = snprintf(c, MP_MAXLINE,
2140	    "%ju %ju %ju %ju %ju %ju %ju %ju "
2141	    "%ju %ju %ju %ju %ju %ju %ju %jju",
2142	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2143	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2144#endif
2145}
2146
2147static int
2148mbprof_handler(SYSCTL_HANDLER_ARGS)
2149{
2150	int error;
2151
2152	mbprof_textify();
2153	error = SYSCTL_OUT(req, mbprofbuf, strlen(mbprofbuf) + 1);
2154	return (error);
2155}
2156
2157static int
2158mbprof_clr_handler(SYSCTL_HANDLER_ARGS)
2159{
2160	int clear, error;
2161
2162	clear = 0;
2163	error = sysctl_handle_int(oidp, &clear, 0, req);
2164	if (error || !req->newptr)
2165		return (error);
2166
2167	if (clear) {
2168		bzero(&mbprof, sizeof(mbprof));
2169	}
2170
2171	return (error);
2172}
2173
2174
2175SYSCTL_PROC(_kern_ipc, OID_AUTO, mbufprofile, CTLTYPE_STRING|CTLFLAG_RD,
2176	    NULL, 0, mbprof_handler, "A", "mbuf profiling statistics");
2177
2178SYSCTL_PROC(_kern_ipc, OID_AUTO, mbufprofileclr, CTLTYPE_INT|CTLFLAG_RW,
2179	    NULL, 0, mbprof_clr_handler, "I", "clear mbuf profiling statistics");
2180#endif
2181
2182