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