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