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