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