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