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