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