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