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