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