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