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