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