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