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