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