Nuke huge mbuf macros stage 1/2: Remove massive inline mbuf macros to reduce
[dragonfly.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  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *      @(#)uipc_mbuf.c 8.2 (Berkeley) 1/4/94
34  * $FreeBSD: src/sys/kern/uipc_mbuf.c,v 1.51.2.24 2003/04/15 06:59:29 silby Exp $
35  * $DragonFly: src/sys/kern/uipc_mbuf.c,v 1.6 2003/07/19 21:09:24 dillon Exp $
36  */
37
38 #include "opt_param.h"
39 #include "opt_mbuf_stress_test.h"
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/malloc.h>
43 #include <sys/mbuf.h>
44 #include <sys/kernel.h>
45 #include <sys/sysctl.h>
46 #include <sys/domain.h>
47 #include <sys/protosw.h>
48 #include <sys/thread.h>
49 #include <sys/globaldata.h>
50
51 #include <vm/vm.h>
52 #include <vm/vm_kern.h>
53 #include <vm/vm_extern.h>
54
55 #ifdef INVARIANTS
56 #include <machine/cpu.h>
57 #endif
58
59 static void mbinit __P((void *));
60 SYSINIT(mbuf, SI_SUB_MBUF, SI_ORDER_FIRST, mbinit, NULL)
61
62 struct mbuf *mbutl;
63 char    *mclrefcnt;
64 struct mbstat mbstat;
65 u_long  mbtypes[MT_NTYPES];
66 struct mbuf *mmbfree;
67 union mcluster *mclfree;
68 int     max_linkhdr;
69 int     max_protohdr;
70 int     max_hdr;
71 int     max_datalen;
72 int     m_defragpackets;
73 int     m_defragbytes;
74 int     m_defraguseless;
75 int     m_defragfailure;
76 #ifdef MBUF_STRESS_TEST
77 int     m_defragrandomfailures;
78 #endif
79
80 int     nmbclusters;
81 int     nmbufs;
82 u_int   m_mballoc_wid = 0;
83 u_int   m_clalloc_wid = 0;
84
85 SYSCTL_DECL(_kern_ipc);
86 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RW,
87            &max_linkhdr, 0, "");
88 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RW,
89            &max_protohdr, 0, "");
90 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RW, &max_hdr, 0, "");
91 SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RW,
92            &max_datalen, 0, "");
93 SYSCTL_INT(_kern_ipc, OID_AUTO, mbuf_wait, CTLFLAG_RW,
94            &mbuf_wait, 0, "");
95 SYSCTL_STRUCT(_kern_ipc, KIPC_MBSTAT, mbstat, CTLFLAG_RW, &mbstat, mbstat, "");
96 SYSCTL_OPAQUE(_kern_ipc, OID_AUTO, mbtypes, CTLFLAG_RD, mbtypes,
97            sizeof(mbtypes), "LU", "");
98 SYSCTL_INT(_kern_ipc, KIPC_NMBCLUSTERS, nmbclusters, CTLFLAG_RD, 
99            &nmbclusters, 0, "Maximum number of mbuf clusters available");
100 SYSCTL_INT(_kern_ipc, OID_AUTO, nmbufs, CTLFLAG_RD, &nmbufs, 0,
101            "Maximum number of mbufs available"); 
102 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
103            &m_defragpackets, 0, "");
104 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
105            &m_defragbytes, 0, "");
106 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
107            &m_defraguseless, 0, "");
108 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
109            &m_defragfailure, 0, "");
110 #ifdef MBUF_STRESS_TEST
111 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
112            &m_defragrandomfailures, 0, "");
113 #endif
114
115 static void     m_reclaim __P((void));
116
117 #ifndef NMBCLUSTERS
118 #define NMBCLUSTERS     (512 + maxusers * 16)
119 #endif
120 #ifndef NMBUFS
121 #define NMBUFS          (nmbclusters * 4)
122 #endif
123
124 /*
125  * Perform sanity checks of tunables declared above.
126  */
127 static void
128 tunable_mbinit(void *dummy)
129 {
130
131         /*
132          * This has to be done before VM init.
133          */
134         nmbclusters = NMBCLUSTERS;
135         TUNABLE_INT_FETCH("kern.ipc.nmbclusters", &nmbclusters);
136         nmbufs = NMBUFS;
137         TUNABLE_INT_FETCH("kern.ipc.nmbufs", &nmbufs);
138         /* Sanity checks */
139         if (nmbufs < nmbclusters * 2)
140                 nmbufs = nmbclusters * 2;
141
142         return;
143 }
144 SYSINIT(tunable_mbinit, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_mbinit, NULL);
145
146 /* "number of clusters of pages" */
147 #define NCL_INIT        1
148
149 #define NMB_INIT        16
150
151 /* ARGSUSED*/
152 static void
153 mbinit(dummy)
154         void *dummy;
155 {
156         int s;
157
158         mmbfree = NULL; mclfree = NULL;
159         mbstat.m_msize = MSIZE;
160         mbstat.m_mclbytes = MCLBYTES;
161         mbstat.m_minclsize = MINCLSIZE;
162         mbstat.m_mlen = MLEN;
163         mbstat.m_mhlen = MHLEN;
164
165         s = splimp();
166         if (m_mballoc(NMB_INIT, M_DONTWAIT) == 0)
167                 goto bad;
168 #if MCLBYTES <= PAGE_SIZE
169         if (m_clalloc(NCL_INIT, M_DONTWAIT) == 0)
170                 goto bad;
171 #else
172         /* It's OK to call contigmalloc in this context. */
173         if (m_clalloc(16, M_WAIT) == 0)
174                 goto bad;
175 #endif
176         splx(s);
177         return;
178 bad:
179         panic("mbinit");
180 }
181
182 /*
183  * Allocate at least nmb mbufs and place on mbuf free list.
184  * Must be called at splimp.
185  */
186 /* ARGSUSED */
187 int
188 m_mballoc(nmb, how)
189         register int nmb;
190         int how;
191 {
192         register caddr_t p;
193         register int i;
194         int nbytes;
195
196         /*
197          * If we've hit the mbuf limit, stop allocating from mb_map,
198          * (or trying to) in order to avoid dipping into the section of
199          * mb_map which we've "reserved" for clusters.
200          */
201         if ((nmb + mbstat.m_mbufs) > nmbufs)
202                 return (0);
203
204         /*
205          * Once we run out of map space, it will be impossible to get
206          * any more (nothing is ever freed back to the map)
207          * -- however you are not dead as m_reclaim might
208          * still be able to free a substantial amount of space.
209          *
210          * XXX Furthermore, we can also work with "recycled" mbufs (when
211          * we're calling with M_WAIT the sleep procedure will be woken
212          * up when an mbuf is freed. See m_mballoc_wait()).
213          */
214         if (mb_map_full)
215                 return (0);
216
217         nbytes = round_page(nmb * MSIZE);
218         p = (caddr_t)kmem_malloc(mb_map, nbytes, M_NOWAIT);
219         if (p == 0 && how == M_WAIT) {
220                 mbstat.m_wait++;
221                 p = (caddr_t)kmem_malloc(mb_map, nbytes, M_WAITOK);
222         }
223
224         /*
225          * Either the map is now full, or `how' is M_NOWAIT and there
226          * are no pages left.
227          */
228         if (p == NULL)
229                 return (0);
230
231         nmb = nbytes / MSIZE;
232         for (i = 0; i < nmb; i++) {
233                 ((struct mbuf *)p)->m_next = mmbfree;
234                 mmbfree = (struct mbuf *)p;
235                 p += MSIZE;
236         }
237         mbstat.m_mbufs += nmb;
238         mbtypes[MT_FREE] += nmb;
239         return (1);
240 }
241
242 /*
243  * Once the mb_map has been exhausted and if the call to the allocation macros
244  * (or, in some cases, functions) is with M_WAIT, then it is necessary to rely
245  * solely on reclaimed mbufs. Here we wait for an mbuf to be freed for a 
246  * designated (mbuf_wait) time. 
247  */
248 struct mbuf *
249 m_mballoc_wait(int caller, int type)
250 {
251         struct mbuf *p;
252         int s;
253
254         s = splimp();
255         m_mballoc_wid++;
256         if ((tsleep(&m_mballoc_wid, PVM, "mballc", mbuf_wait)) == EWOULDBLOCK)
257                 m_mballoc_wid--;
258         splx(s);
259
260         /*
261          * Now that we (think) that we've got something, we will redo an
262          * MGET, but avoid getting into another instance of m_mballoc_wait()
263          * XXX: We retry to fetch _even_ if the sleep timed out. This is left
264          *      this way, purposely, in the [unlikely] case that an mbuf was
265          *      freed but the sleep was not awakened in time. 
266          */
267         p = NULL;
268         switch (caller) {
269         case MGET_C:
270                 MGET(p, M_DONTWAIT, type);
271                 break;
272         case MGETHDR_C:
273                 MGETHDR(p, M_DONTWAIT, type);
274                 break;
275         default:
276                 panic("m_mballoc_wait: invalid caller (%d)", caller);
277         }
278
279         s = splimp();
280         if (p != NULL) {                /* We waited and got something... */
281                 mbstat.m_wait++;
282                 /* Wake up another if we have more free. */
283                 if (mmbfree != NULL)
284                         MMBWAKEUP();
285         }
286         splx(s);
287         return (p);
288 }
289
290 #if MCLBYTES > PAGE_SIZE
291 static int i_want_my_mcl;
292
293 static void
294 kproc_mclalloc(void)
295 {
296         int status;
297
298         while (1) {
299                 tsleep(&i_want_my_mcl, PVM, "mclalloc", 0);
300
301                 for (; i_want_my_mcl; i_want_my_mcl--) {
302                         if (m_clalloc(1, M_WAIT) == 0)
303                                 printf("m_clalloc failed even in process context!\n");
304                 }
305         }
306 }
307
308 static struct thread *mclallocthread;
309 static struct kproc_desc mclalloc_kp = {
310         "mclalloc",
311         kproc_mclalloc,
312         &mclallocthread
313 };
314 SYSINIT(mclallocthread, SI_SUB_KTHREAD_UPDATE, SI_ORDER_ANY, kproc_start,
315            &mclalloc_kp);
316 #endif
317
318 /*
319  * Allocate some number of mbuf clusters
320  * and place on cluster free list.
321  * Must be called at splimp.
322  */
323 /* ARGSUSED */
324 int
325 m_clalloc(ncl, how)
326         register int ncl;
327         int how;
328 {
329         register caddr_t p;
330         register int i;
331         int npg;
332
333         /*
334          * If we've hit the mcluster number limit, stop allocating from
335          * mb_map, (or trying to) in order to avoid dipping into the section
336          * of mb_map which we've "reserved" for mbufs.
337          */
338         if ((ncl + mbstat.m_clusters) > nmbclusters)
339                 goto m_clalloc_fail;
340
341         /*
342          * Once we run out of map space, it will be impossible
343          * to get any more (nothing is ever freed back to the
344          * map). From this point on, we solely rely on freed 
345          * mclusters.
346          */
347         if (mb_map_full)
348                 goto m_clalloc_fail;
349
350 #if MCLBYTES > PAGE_SIZE
351         if (how != M_WAIT) {
352                 i_want_my_mcl += ncl;
353                 wakeup(&i_want_my_mcl);
354                 mbstat.m_wait++;
355                 p = 0;
356         } else {
357                 p = contigmalloc1(MCLBYTES * ncl, M_DEVBUF, M_WAITOK, 0ul,
358                                   ~0ul, PAGE_SIZE, 0, mb_map);
359         }
360 #else
361         npg = ncl;
362         p = (caddr_t)kmem_malloc(mb_map, ctob(npg),
363                                  how != M_WAIT ? M_NOWAIT : M_WAITOK);
364         ncl = ncl * PAGE_SIZE / MCLBYTES;
365 #endif
366         /*
367          * Either the map is now full, or `how' is M_NOWAIT and there
368          * are no pages left.
369          */
370         if (p == NULL) {
371                 static int last_report ; /* when we did that (in ticks) */
372 m_clalloc_fail:
373                 mbstat.m_drops++;
374                 if (ticks < last_report || (ticks - last_report) >= hz) {
375                         last_report = ticks;
376                         printf("All mbuf clusters exhausted, please see tuning(7).\n");
377                 }
378                 return (0);
379         }
380
381         for (i = 0; i < ncl; i++) {
382                 ((union mcluster *)p)->mcl_next = mclfree;
383                 mclfree = (union mcluster *)p;
384                 p += MCLBYTES;
385                 mbstat.m_clfree++;
386         }
387         mbstat.m_clusters += ncl;
388         return (1);
389 }
390
391 /*
392  * Once the mb_map submap has been exhausted and the allocation is called with
393  * M_WAIT, we rely on the mclfree union pointers. If nothing is free, we will
394  * sleep for a designated amount of time (mbuf_wait) or until we're woken up
395  * due to sudden mcluster availability.
396  */
397 caddr_t
398 m_clalloc_wait(void)
399 {
400         caddr_t p;
401         int s;
402
403 #ifdef __i386__
404         /* If in interrupt context, and INVARIANTS, maintain sanity and die. */
405         KASSERT(mycpu->gd_intr_nesting_level == 0, ("CLALLOC: CANNOT WAIT IN INTERRUPT"));
406 #endif
407
408         /* Sleep until something's available or until we expire. */
409         m_clalloc_wid++;
410         if ((tsleep(&m_clalloc_wid, PVM, "mclalc", mbuf_wait)) == EWOULDBLOCK)
411                 m_clalloc_wid--;
412
413         /*
414          * Now that we (think) that we've got something, we will redo and
415          * MGET, but avoid getting into another instance of m_clalloc_wait()
416          */
417         p = NULL;
418         MCLALLOC(p, M_DONTWAIT);
419
420         s = splimp();
421         if (p != NULL) {        /* We waited and got something... */
422                 mbstat.m_wait++;
423                 /* Wake up another if we have more free. */
424                 if (mclfree != NULL)
425                         MCLWAKEUP();
426         }
427
428         splx(s);
429         return (p);
430 }
431
432 /*
433  * When MGET fails, ask protocols to free space when short of memory,
434  * then re-attempt to allocate an mbuf.
435  */
436 struct mbuf *
437 m_retry(i, t)
438         int i, t;
439 {
440         struct mbuf *m;
441         int ms;
442
443         /*
444          * Must only do the reclaim if not in an interrupt context.
445          */
446         if (i == M_WAIT) {
447 #ifdef __i386__
448                 KASSERT(mycpu->gd_intr_nesting_level == 0,
449                     ("MBALLOC: CANNOT WAIT IN INTERRUPT"));
450 #endif
451                 m_reclaim();
452         }
453
454         ms = splimp();
455         if (mmbfree == NULL)
456                 (void)m_mballoc(1, i);
457         m = mmbfree;
458         if (m != NULL) {
459                 mmbfree = m->m_next;
460                 mbtypes[MT_FREE]--;
461                 m->m_type = t;
462                 mbtypes[t]++;
463                 m->m_next = NULL;
464                 m->m_nextpkt = NULL;
465                 m->m_data = m->m_dat;
466                 m->m_flags = 0;
467                 splx(ms);
468                 mbstat.m_wait++;
469         } else {
470                 static int last_report ; /* when we did that (in ticks) */
471                 splx(ms);
472                 mbstat.m_drops++;
473                 if (ticks < last_report || (ticks - last_report) >= hz) {
474                         last_report = ticks;
475                         printf("All mbufs exhausted, please see tuning(7).\n");
476                 }
477         }
478
479         return (m);
480 }
481
482 /*
483  * As above; retry an MGETHDR.
484  */
485 struct mbuf *
486 m_retryhdr(i, t)
487         int i, t;
488 {
489         struct mbuf *m;
490         int ms;
491
492         /*
493          * Must only do the reclaim if not in an interrupt context.
494          */
495         if (i == M_WAIT) {
496 #ifdef __i386__
497                 KASSERT(mycpu->gd_intr_nesting_level == 0,
498                     ("MBALLOC: CANNOT WAIT IN INTERRUPT"));
499 #endif
500                 m_reclaim();
501         }
502
503         ms = splimp();
504         if (mmbfree == NULL)
505                 (void)m_mballoc(1, i);
506         m = mmbfree;
507         if (m != NULL) {
508                 mmbfree = m->m_next;
509                 mbtypes[MT_FREE]--;
510                 m->m_type = t;
511                 mbtypes[t]++;
512                 m->m_next = NULL;
513                 m->m_nextpkt = NULL;
514                 m->m_data = m->m_pktdat;
515                 m->m_flags = M_PKTHDR;
516                 m->m_pkthdr.rcvif = NULL;
517                 SLIST_INIT(&m->m_pkthdr.tags);
518                 m->m_pkthdr.csum_flags = 0;
519                 splx(ms);
520                 mbstat.m_wait++;
521         } else {
522                 static int last_report ; /* when we did that (in ticks) */
523
524                 splx(ms);
525                 mbstat.m_drops++;
526                 if (ticks < last_report || (ticks - last_report) >= hz) {
527                         last_report = ticks;
528                         printf("All mbufs exhausted, please see tuning(7).\n");
529                 }
530         }
531         
532         return (m);
533 }
534
535 static void
536 m_reclaim()
537 {
538         register struct domain *dp;
539         register struct protosw *pr;
540         int s = splimp();
541
542         for (dp = domains; dp; dp = dp->dom_next)
543                 for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++)
544                         if (pr->pr_drain)
545                                 (*pr->pr_drain)();
546         splx(s);
547         mbstat.m_drain++;
548 }
549
550 /*
551  * Space allocation routines.
552  * These are also available as macros
553  * for critical paths.
554  */
555 struct mbuf *
556 m_get(how, type)
557         int how, type;
558 {
559         struct mbuf *m;
560         int ms;
561
562         ms = splimp();
563         if (mmbfree == NULL)
564                 (void)m_mballoc(1, how);
565         m = mmbfree;
566         if (m != NULL) {
567                 mmbfree = m->m_next;
568                 mbtypes[MT_FREE]--;
569                 m->m_type = type;
570                 mbtypes[type]++;
571                 m->m_next = NULL;
572                 m->m_nextpkt = NULL;
573                 m->m_data = m->m_dat;
574                 m->m_flags = 0;
575                 splx(ms);
576         } else {
577                 splx(ms);
578                 m = m_retry(how, type);
579                 if (m == NULL && how == M_WAIT)
580                         m = m_mballoc_wait(MGET_C, type);
581         }
582         return (m);
583 }
584
585 struct mbuf *
586 m_gethdr(how, type)
587         int how, type;
588 {
589         struct mbuf *m;
590         int ms;
591
592         ms = splimp();
593         if (mmbfree == NULL)
594                 (void)m_mballoc(1, how);
595         m = mmbfree;
596         if (m != NULL) {
597                 mmbfree = m->m_next;
598                 mbtypes[MT_FREE]--;
599                 m->m_type = type;
600                 mbtypes[type]++;
601                 m->m_next = NULL;
602                 m->m_nextpkt = NULL;
603                 m->m_data = m->m_pktdat;
604                 m->m_flags = M_PKTHDR;
605                 m->m_pkthdr.rcvif = NULL;
606                 SLIST_INIT(&m->m_pkthdr.tags);
607                 m->m_pkthdr.csum_flags = 0;
608                 splx(ms);
609         } else {
610                 splx(ms);
611                 m = m_retryhdr(how, type);
612                 if (m == NULL && how == M_WAIT)
613                         m = m_mballoc_wait(MGETHDR_C, type);
614         }
615         return (m);
616 }
617
618 struct mbuf *
619 m_getclr(how, type)
620         int how, type;
621 {
622         register struct mbuf *m;
623
624         MGET(m, how, type);
625         if (m == 0)
626                 return (0);
627         bzero(mtod(m, caddr_t), MLEN);
628         return (m);
629 }
630
631 /*
632  * m_getcl() returns an mbuf with an attached cluster.
633  * Because many network drivers use this kind of buffers a lot, it is
634  * convenient to keep a small pool of free buffers of this kind.
635  * Even a small size such as 10 gives about 10% improvement in the
636  * forwarding rate in a bridge or router.
637  * The size of this free list is controlled by the sysctl variable
638  * mcl_pool_max. The list is populated on m_freem(), and used in
639  * m_getcl() if elements are available.
640  */
641 static struct mbuf *mcl_pool;
642 static int mcl_pool_now;
643 static int mcl_pool_max = 0;
644  
645 SYSCTL_INT(_kern_ipc, OID_AUTO, mcl_pool_max, CTLFLAG_RW, &mcl_pool_max, 0,
646            "Maximum number of mbufs+cluster in free list");
647 SYSCTL_INT(_kern_ipc, OID_AUTO, mcl_pool_now, CTLFLAG_RD, &mcl_pool_now, 0,
648            "Current number of mbufs+cluster in free list");
649
650 struct mbuf *
651 m_getcl(int how, short type, int flags)
652 {
653         int s = splimp();
654         struct mbuf *mp;
655
656         if (flags & M_PKTHDR) {
657                 if (type == MT_DATA && mcl_pool) {
658                         mp = mcl_pool;
659                         mcl_pool = mp->m_nextpkt;
660                         mcl_pool_now--;
661                         splx(s);
662                         mp->m_nextpkt = NULL;
663                         mp->m_data = mp->m_ext.ext_buf;
664                         mp->m_flags = M_PKTHDR|M_EXT;
665                         mp->m_pkthdr.rcvif = NULL;
666                         mp->m_pkthdr.csum_flags = 0;
667                         return mp;
668                 } else
669                         MGETHDR(mp, how, type);
670         } else
671                 MGET(mp, how, type);
672         if (mp) {
673                 MCLGET(mp, how);
674                 if ( (mp->m_flags & M_EXT) == 0) {
675                         m_free(mp);
676                         mp = NULL;
677                 }
678         }
679         splx(s);
680         return mp;
681 }
682
683 /*
684  * struct mbuf *
685  * m_getm(m, len, how, type)
686  *
687  * This will allocate len-worth of mbufs and/or mbuf clusters (whatever fits
688  * best) and return a pointer to the top of the allocated chain. If m is
689  * non-null, then we assume that it is a single mbuf or an mbuf chain to
690  * which we want len bytes worth of mbufs and/or clusters attached, and so
691  * if we succeed in allocating it, we will just return a pointer to m.
692  *
693  * If we happen to fail at any point during the allocation, we will free
694  * up everything we have already allocated and return NULL.
695  *
696  */
697 struct mbuf *
698 m_getm(struct mbuf *m, int len, int how, int type)
699 {
700         struct mbuf *top, *tail, *mp, *mtail = NULL;
701
702         KASSERT(len >= 0, ("len is < 0 in m_getm"));
703
704         MGET(mp, how, type);
705         if (mp == NULL)
706                 return (NULL);
707         else if (len > MINCLSIZE) {
708                 MCLGET(mp, how);
709                 if ((mp->m_flags & M_EXT) == 0) {
710                         m_free(mp);
711                         return (NULL);
712                 }
713         }
714         mp->m_len = 0;
715         len -= M_TRAILINGSPACE(mp);
716
717         if (m != NULL)
718                 for (mtail = m; mtail->m_next != NULL; mtail = mtail->m_next);
719         else
720                 m = mp;
721
722         top = tail = mp;
723         while (len > 0) {
724                 MGET(mp, how, type);
725                 if (mp == NULL)
726                         goto failed;
727
728                 tail->m_next = mp;
729                 tail = mp;
730                 if (len > MINCLSIZE) {
731                         MCLGET(mp, how);
732                         if ((mp->m_flags & M_EXT) == 0)
733                                 goto failed;
734                 }
735
736                 mp->m_len = 0;
737                 len -= M_TRAILINGSPACE(mp);
738         }
739
740         if (mtail != NULL)
741                 mtail->m_next = top;
742         return (m);
743
744 failed:
745         m_freem(top);
746         return (NULL);
747 }
748
749 /*
750  * MFREE(struct mbuf *m, struct mbuf *n)
751  * Free a single mbuf and associated external storage.
752  * Place the successor, if any, in n.
753  *
754  * we do need to check non-first mbuf for m_aux, since some of existing
755  * code does not call M_PREPEND properly.
756  * (example: call to bpf_mtap from drivers)
757  */
758 #define MFREE(m, n) MBUFLOCK(                                           \
759         struct mbuf *_mm = (m);                                         \
760                                                                         \
761         KASSERT(_mm->m_type != MT_FREE, ("freeing free mbuf"));         \
762         mbtypes[_mm->m_type]--;                                         \
763         if ((_mm->m_flags & M_PKTHDR) != 0)                             \
764                 m_tag_delete_chain(_mm, NULL);                          \
765         if (_mm->m_flags & M_EXT)                                       \
766                 MEXTFREE1(m);                                           \
767         (n) = _mm->m_next;                                              \
768         _mm->m_type = MT_FREE;                                          \
769         mbtypes[MT_FREE]++;                                             \
770         _mm->m_next = mmbfree;                                          \
771         mmbfree = _mm;                                                  \
772         MMBWAKEUP();                                                    \
773 )
774
775 struct mbuf *
776 m_free(m)
777         struct mbuf *m;
778 {
779         register struct mbuf *n;
780
781         MFREE(m, n);
782         return (n);
783 }
784
785 void
786 m_freem(m)
787         struct mbuf *m;
788 {
789         int s = splimp();
790
791         /*
792          * Try to keep a small pool of mbuf+cluster for quick use in
793          * device drivers. A good candidate is a M_PKTHDR buffer with
794          * only one cluster attached. Other mbufs, or those exceeding
795          * the pool size, are just m_free'd in the usual way.
796          * The following code makes sure that m_next, m_type,
797          * m_pkthdr.aux and m_ext.* are properly initialized.
798          * Other fields in the mbuf are initialized in m_getcl()
799          * upon allocation.
800          */
801         if (mcl_pool_now < mcl_pool_max && m && m->m_next == NULL &&
802             (m->m_flags & (M_PKTHDR|M_EXT)) == (M_PKTHDR|M_EXT) &&
803             m->m_type == MT_DATA && M_EXT_WRITABLE(m) ) {
804                 m_tag_delete_chain(m, NULL);
805                 m->m_nextpkt = mcl_pool;
806                 mcl_pool = m;
807                 mcl_pool_now++;
808         } else {
809                 while (m)
810                         m = m_free(m);
811         }
812         splx(s);
813 }
814
815 /*
816  * Mbuffer utility routines.
817  */
818
819 /*
820  * Lesser-used path for M_PREPEND:
821  * allocate new mbuf to prepend to chain,
822  * copy junk along.
823  */
824 struct mbuf *
825 m_prepend(m, len, how)
826         register struct mbuf *m;
827         int len, how;
828 {
829         struct mbuf *mn;
830
831         MGET(mn, how, m->m_type);
832         if (mn == (struct mbuf *)NULL) {
833                 m_freem(m);
834                 return ((struct mbuf *)NULL);
835         }
836         if (m->m_flags & M_PKTHDR)
837                 M_MOVE_PKTHDR(mn, m);
838         mn->m_next = m;
839         m = mn;
840         if (len < MHLEN)
841                 MH_ALIGN(m, len);
842         m->m_len = len;
843         return (m);
844 }
845
846 /*
847  * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
848  * continuing for "len" bytes.  If len is M_COPYALL, copy to end of mbuf.
849  * The wait parameter is a choice of M_WAIT/M_DONTWAIT from caller.
850  * Note that the copy is read-only, because clusters are not copied,
851  * only their reference counts are incremented.
852  */
853 #define MCFail (mbstat.m_mcfail)
854
855 struct mbuf *
856 m_copym(m, off0, len, wait)
857         register struct mbuf *m;
858         int off0, wait;
859         register int len;
860 {
861         register struct mbuf *n, **np;
862         register int off = off0;
863         struct mbuf *top;
864         int copyhdr = 0;
865
866         KASSERT(off >= 0, ("m_copym, negative off %d", off));
867         KASSERT(len >= 0, ("m_copym, negative len %d", len));
868         if (off == 0 && m->m_flags & M_PKTHDR)
869                 copyhdr = 1;
870         while (off > 0) {
871                 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
872                 if (off < m->m_len)
873                         break;
874                 off -= m->m_len;
875                 m = m->m_next;
876         }
877         np = &top;
878         top = 0;
879         while (len > 0) {
880                 if (m == 0) {
881                         KASSERT(len == M_COPYALL, 
882                             ("m_copym, length > size of mbuf chain"));
883                         break;
884                 }
885                 MGET(n, wait, m->m_type);
886                 *np = n;
887                 if (n == 0)
888                         goto nospace;
889                 if (copyhdr) {
890                         if (!m_dup_pkthdr(n, m, wait))
891                                 goto nospace;
892                         if (len == M_COPYALL)
893                                 n->m_pkthdr.len -= off0;
894                         else
895                                 n->m_pkthdr.len = len;
896                         copyhdr = 0;
897                 }
898                 n->m_len = min(len, m->m_len - off);
899                 if (m->m_flags & M_EXT) {
900                         n->m_data = m->m_data + off;
901                         if (m->m_ext.ext_ref == NULL) {
902                                 atomic_add_char(
903                                     &mclrefcnt[mtocl(m->m_ext.ext_buf)], 1);
904                         } else {
905                                 int s = splimp();
906
907                                 (*m->m_ext.ext_ref)(m->m_ext.ext_buf,
908                                     m->m_ext.ext_size);
909                                 splx(s);
910                         }
911                         n->m_ext = m->m_ext;
912                         n->m_flags |= M_EXT;
913                 } else
914                         bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
915                             (unsigned)n->m_len);
916                 if (len != M_COPYALL)
917                         len -= n->m_len;
918                 off = 0;
919                 m = m->m_next;
920                 np = &n->m_next;
921         }
922         if (top == 0)
923                 MCFail++;
924         return (top);
925 nospace:
926         m_freem(top);
927         MCFail++;
928         return (0);
929 }
930
931 /*
932  * Copy an entire packet, including header (which must be present).
933  * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
934  * Note that the copy is read-only, because clusters are not copied,
935  * only their reference counts are incremented.
936  * Preserve alignment of the first mbuf so if the creator has left
937  * some room at the beginning (e.g. for inserting protocol headers)
938  * the copies also have the room available.
939  */
940 struct mbuf *
941 m_copypacket(m, how)
942         struct mbuf *m;
943         int how;
944 {
945         struct mbuf *top, *n, *o;
946
947         MGET(n, how, m->m_type);
948         top = n;
949         if (!n)
950                 goto nospace;
951
952         if (!m_dup_pkthdr(n, m, how))
953                 goto nospace;
954         n->m_len = m->m_len;
955         if (m->m_flags & M_EXT) {
956                 n->m_data = m->m_data;
957                 if (m->m_ext.ext_ref == NULL)
958                         atomic_add_char(&mclrefcnt[mtocl(m->m_ext.ext_buf)], 1);
959                 else {
960                         int s = splimp();
961
962                         (*m->m_ext.ext_ref)(m->m_ext.ext_buf,
963                             m->m_ext.ext_size);
964                         splx(s);
965                 }
966                 n->m_ext = m->m_ext;
967                 n->m_flags |= M_EXT;
968         } else {
969                 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
970                 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
971         }
972
973         m = m->m_next;
974         while (m) {
975                 MGET(o, how, m->m_type);
976                 if (!o)
977                         goto nospace;
978
979                 n->m_next = o;
980                 n = n->m_next;
981
982                 n->m_len = m->m_len;
983                 if (m->m_flags & M_EXT) {
984                         n->m_data = m->m_data;
985                         if (m->m_ext.ext_ref == NULL) {
986                                 atomic_add_char(
987                                     &mclrefcnt[mtocl(m->m_ext.ext_buf)], 1);
988                         } else {
989                                 int s = splimp();
990
991                                 (*m->m_ext.ext_ref)(m->m_ext.ext_buf,
992                                     m->m_ext.ext_size);
993                                 splx(s);
994                         }
995                         n->m_ext = m->m_ext;
996                         n->m_flags |= M_EXT;
997                 } else {
998                         bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
999                 }
1000
1001                 m = m->m_next;
1002         }
1003         return top;
1004 nospace:
1005         m_freem(top);
1006         MCFail++;
1007         return 0;
1008 }
1009
1010 /*
1011  * Copy data from an mbuf chain starting "off" bytes from the beginning,
1012  * continuing for "len" bytes, into the indicated buffer.
1013  */
1014 void
1015 m_copydata(m, off, len, cp)
1016         register struct mbuf *m;
1017         register int off;
1018         register int len;
1019         caddr_t cp;
1020 {
1021         register unsigned count;
1022
1023         KASSERT(off >= 0, ("m_copydata, negative off %d", off));
1024         KASSERT(len >= 0, ("m_copydata, negative len %d", len));
1025         while (off > 0) {
1026                 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
1027                 if (off < m->m_len)
1028                         break;
1029                 off -= m->m_len;
1030                 m = m->m_next;
1031         }
1032         while (len > 0) {
1033                 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
1034                 count = min(m->m_len - off, len);
1035                 bcopy(mtod(m, caddr_t) + off, cp, count);
1036                 len -= count;
1037                 cp += count;
1038                 off = 0;
1039                 m = m->m_next;
1040         }
1041 }
1042
1043 /*
1044  * Copy a packet header mbuf chain into a completely new chain, including
1045  * copying any mbuf clusters.  Use this instead of m_copypacket() when
1046  * you need a writable copy of an mbuf chain.
1047  */
1048 struct mbuf *
1049 m_dup(m, how)
1050         struct mbuf *m;
1051         int how;
1052 {
1053         struct mbuf **p, *top = NULL;
1054         int remain, moff, nsize;
1055
1056         /* Sanity check */
1057         if (m == NULL)
1058                 return (0);
1059         KASSERT((m->m_flags & M_PKTHDR) != 0, ("%s: !PKTHDR", __FUNCTION__));
1060
1061         /* While there's more data, get a new mbuf, tack it on, and fill it */
1062         remain = m->m_pkthdr.len;
1063         moff = 0;
1064         p = &top;
1065         while (remain > 0 || top == NULL) {     /* allow m->m_pkthdr.len == 0 */
1066                 struct mbuf *n;
1067
1068                 /* Get the next new mbuf */
1069                 MGET(n, how, m->m_type);
1070                 if (n == NULL)
1071                         goto nospace;
1072                 if (top == NULL) {              /* first one, must be PKTHDR */
1073                         if (!m_dup_pkthdr(n, m, how))
1074                                 goto nospace;
1075                         nsize = MHLEN;
1076                 } else                          /* not the first one */
1077                         nsize = MLEN;
1078                 if (remain >= MINCLSIZE) {
1079                         MCLGET(n, how);
1080                         if ((n->m_flags & M_EXT) == 0) {
1081                                 (void)m_free(n);
1082                                 goto nospace;
1083                         }
1084                         nsize = MCLBYTES;
1085                 }
1086                 n->m_len = 0;
1087
1088                 /* Link it into the new chain */
1089                 *p = n;
1090                 p = &n->m_next;
1091
1092                 /* Copy data from original mbuf(s) into new mbuf */
1093                 while (n->m_len < nsize && m != NULL) {
1094                         int chunk = min(nsize - n->m_len, m->m_len - moff);
1095
1096                         bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1097                         moff += chunk;
1098                         n->m_len += chunk;
1099                         remain -= chunk;
1100                         if (moff == m->m_len) {
1101                                 m = m->m_next;
1102                                 moff = 0;
1103                         }
1104                 }
1105
1106                 /* Check correct total mbuf length */
1107                 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
1108                         ("%s: bogus m_pkthdr.len", __FUNCTION__));
1109         }
1110         return (top);
1111
1112 nospace:
1113         m_freem(top);
1114         MCFail++;
1115         return (0);
1116 }
1117
1118 /*
1119  * Concatenate mbuf chain n to m.
1120  * Both chains must be of the same type (e.g. MT_DATA).
1121  * Any m_pkthdr is not updated.
1122  */
1123 void
1124 m_cat(m, n)
1125         register struct mbuf *m, *n;
1126 {
1127         while (m->m_next)
1128                 m = m->m_next;
1129         while (n) {
1130                 if (m->m_flags & M_EXT ||
1131                     m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
1132                         /* just join the two chains */
1133                         m->m_next = n;
1134                         return;
1135                 }
1136                 /* splat the data from one into the other */
1137                 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1138                     (u_int)n->m_len);
1139                 m->m_len += n->m_len;
1140                 n = m_free(n);
1141         }
1142 }
1143
1144 void
1145 m_adj(mp, req_len)
1146         struct mbuf *mp;
1147         int req_len;
1148 {
1149         register int len = req_len;
1150         register struct mbuf *m;
1151         register int count;
1152
1153         if ((m = mp) == NULL)
1154                 return;
1155         if (len >= 0) {
1156                 /*
1157                  * Trim from head.
1158                  */
1159                 while (m != NULL && len > 0) {
1160                         if (m->m_len <= len) {
1161                                 len -= m->m_len;
1162                                 m->m_len = 0;
1163                                 m = m->m_next;
1164                         } else {
1165                                 m->m_len -= len;
1166                                 m->m_data += len;
1167                                 len = 0;
1168                         }
1169                 }
1170                 m = mp;
1171                 if (mp->m_flags & M_PKTHDR)
1172                         m->m_pkthdr.len -= (req_len - len);
1173         } else {
1174                 /*
1175                  * Trim from tail.  Scan the mbuf chain,
1176                  * calculating its length and finding the last mbuf.
1177                  * If the adjustment only affects this mbuf, then just
1178                  * adjust and return.  Otherwise, rescan and truncate
1179                  * after the remaining size.
1180                  */
1181                 len = -len;
1182                 count = 0;
1183                 for (;;) {
1184                         count += m->m_len;
1185                         if (m->m_next == (struct mbuf *)0)
1186                                 break;
1187                         m = m->m_next;
1188                 }
1189                 if (m->m_len >= len) {
1190                         m->m_len -= len;
1191                         if (mp->m_flags & M_PKTHDR)
1192                                 mp->m_pkthdr.len -= len;
1193                         return;
1194                 }
1195                 count -= len;
1196                 if (count < 0)
1197                         count = 0;
1198                 /*
1199                  * Correct length for chain is "count".
1200                  * Find the mbuf with last data, adjust its length,
1201                  * and toss data from remaining mbufs on chain.
1202                  */
1203                 m = mp;
1204                 if (m->m_flags & M_PKTHDR)
1205                         m->m_pkthdr.len = count;
1206                 for (; m; m = m->m_next) {
1207                         if (m->m_len >= count) {
1208                                 m->m_len = count;
1209                                 break;
1210                         }
1211                         count -= m->m_len;
1212                 }
1213                 while (m->m_next)
1214                         (m = m->m_next) ->m_len = 0;
1215         }
1216 }
1217
1218 /*
1219  * Rearange an mbuf chain so that len bytes are contiguous
1220  * and in the data area of an mbuf (so that mtod and dtom
1221  * will work for a structure of size len).  Returns the resulting
1222  * mbuf chain on success, frees it and returns null on failure.
1223  * If there is room, it will add up to max_protohdr-len extra bytes to the
1224  * contiguous region in an attempt to avoid being called next time.
1225  */
1226 #define MPFail (mbstat.m_mpfail)
1227
1228 struct mbuf *
1229 m_pullup(n, len)
1230         register struct mbuf *n;
1231         int len;
1232 {
1233         register struct mbuf *m;
1234         register int count;
1235         int space;
1236
1237         /*
1238          * If first mbuf has no cluster, and has room for len bytes
1239          * without shifting current data, pullup into it,
1240          * otherwise allocate a new mbuf to prepend to the chain.
1241          */
1242         if ((n->m_flags & M_EXT) == 0 &&
1243             n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
1244                 if (n->m_len >= len)
1245                         return (n);
1246                 m = n;
1247                 n = n->m_next;
1248                 len -= m->m_len;
1249         } else {
1250                 if (len > MHLEN)
1251                         goto bad;
1252                 MGET(m, M_DONTWAIT, n->m_type);
1253                 if (m == 0)
1254                         goto bad;
1255                 m->m_len = 0;
1256                 if (n->m_flags & M_PKTHDR)
1257                         M_MOVE_PKTHDR(m, n);
1258         }
1259         space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1260         do {
1261                 count = min(min(max(len, max_protohdr), space), n->m_len);
1262                 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1263                   (unsigned)count);
1264                 len -= count;
1265                 m->m_len += count;
1266                 n->m_len -= count;
1267                 space -= count;
1268                 if (n->m_len)
1269                         n->m_data += count;
1270                 else
1271                         n = m_free(n);
1272         } while (len > 0 && n);
1273         if (len > 0) {
1274                 (void) m_free(m);
1275                 goto bad;
1276         }
1277         m->m_next = n;
1278         return (m);
1279 bad:
1280         m_freem(n);
1281         MPFail++;
1282         return (0);
1283 }
1284
1285 /*
1286  * Partition an mbuf chain in two pieces, returning the tail --
1287  * all but the first len0 bytes.  In case of failure, it returns NULL and
1288  * attempts to restore the chain to its original state.
1289  *
1290  * Note that the resulting mbufs might be read-only, because the new
1291  * mbuf can end up sharing an mbuf cluster with the original mbuf if
1292  * the "breaking point" happens to lie within a cluster mbuf. Use the
1293  * M_WRITABLE() macro to check for this case.
1294  */
1295 struct mbuf *
1296 m_split(m0, len0, wait)
1297         register struct mbuf *m0;
1298         int len0, wait;
1299 {
1300         register struct mbuf *m, *n;
1301         unsigned len = len0, remain;
1302
1303         for (m = m0; m && len > m->m_len; m = m->m_next)
1304                 len -= m->m_len;
1305         if (m == 0)
1306                 return (0);
1307         remain = m->m_len - len;
1308         if (m0->m_flags & M_PKTHDR) {
1309                 MGETHDR(n, wait, m0->m_type);
1310                 if (n == 0)
1311                         return (0);
1312                 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1313                 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1314                 m0->m_pkthdr.len = len0;
1315                 if (m->m_flags & M_EXT)
1316                         goto extpacket;
1317                 if (remain > MHLEN) {
1318                         /* m can't be the lead packet */
1319                         MH_ALIGN(n, 0);
1320                         n->m_next = m_split(m, len, wait);
1321                         if (n->m_next == 0) {
1322                                 (void) m_free(n);
1323                                 return (0);
1324                         } else {
1325                                 n->m_len = 0;
1326                                 return (n);
1327                         }
1328                 } else
1329                         MH_ALIGN(n, remain);
1330         } else if (remain == 0) {
1331                 n = m->m_next;
1332                 m->m_next = 0;
1333                 return (n);
1334         } else {
1335                 MGET(n, wait, m->m_type);
1336                 if (n == 0)
1337                         return (0);
1338                 M_ALIGN(n, remain);
1339         }
1340 extpacket:
1341         if (m->m_flags & M_EXT) {
1342                 n->m_flags |= M_EXT;
1343                 n->m_ext = m->m_ext;
1344                 if (m->m_ext.ext_ref == NULL)
1345                         atomic_add_char(&mclrefcnt[mtocl(m->m_ext.ext_buf)], 1);
1346                 else {
1347                         int s = splimp();
1348
1349                         (*m->m_ext.ext_ref)(m->m_ext.ext_buf,
1350                             m->m_ext.ext_size);
1351                         splx(s);
1352                 }
1353                 n->m_data = m->m_data + len;
1354         } else {
1355                 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1356         }
1357         n->m_len = remain;
1358         m->m_len = len;
1359         n->m_next = m->m_next;
1360         m->m_next = 0;
1361         return (n);
1362 }
1363 /*
1364  * Routine to copy from device local memory into mbufs.
1365  */
1366 struct mbuf *
1367 m_devget(buf, totlen, off0, ifp, copy)
1368         char *buf;
1369         int totlen, off0;
1370         struct ifnet *ifp;
1371         void (*copy) __P((char *from, caddr_t to, u_int len));
1372 {
1373         register struct mbuf *m;
1374         struct mbuf *top = 0, **mp = &top;
1375         register int off = off0, len;
1376         register char *cp;
1377         char *epkt;
1378
1379         cp = buf;
1380         epkt = cp + totlen;
1381         if (off) {
1382                 cp += off + 2 * sizeof(u_short);
1383                 totlen -= 2 * sizeof(u_short);
1384         }
1385         MGETHDR(m, M_DONTWAIT, MT_DATA);
1386         if (m == 0)
1387                 return (0);
1388         m->m_pkthdr.rcvif = ifp;
1389         m->m_pkthdr.len = totlen;
1390         m->m_len = MHLEN;
1391
1392         while (totlen > 0) {
1393                 if (top) {
1394                         MGET(m, M_DONTWAIT, MT_DATA);
1395                         if (m == 0) {
1396                                 m_freem(top);
1397                                 return (0);
1398                         }
1399                         m->m_len = MLEN;
1400                 }
1401                 len = min(totlen, epkt - cp);
1402                 if (len >= MINCLSIZE) {
1403                         MCLGET(m, M_DONTWAIT);
1404                         if (m->m_flags & M_EXT)
1405                                 m->m_len = len = min(len, MCLBYTES);
1406                         else
1407                                 len = m->m_len;
1408                 } else {
1409                         /*
1410                          * Place initial small packet/header at end of mbuf.
1411                          */
1412                         if (len < m->m_len) {
1413                                 if (top == 0 && len + max_linkhdr <= m->m_len)
1414                                         m->m_data += max_linkhdr;
1415                                 m->m_len = len;
1416                         } else
1417                                 len = m->m_len;
1418                 }
1419                 if (copy)
1420                         copy(cp, mtod(m, caddr_t), (unsigned)len);
1421                 else
1422                         bcopy(cp, mtod(m, caddr_t), (unsigned)len);
1423                 cp += len;
1424                 *mp = m;
1425                 mp = &m->m_next;
1426                 totlen -= len;
1427                 if (cp == epkt)
1428                         cp = buf;
1429         }
1430         return (top);
1431 }
1432
1433 /*
1434  * Copy data from a buffer back into the indicated mbuf chain,
1435  * starting "off" bytes from the beginning, extending the mbuf
1436  * chain if necessary.
1437  */
1438 void
1439 m_copyback(m0, off, len, cp)
1440         struct  mbuf *m0;
1441         register int off;
1442         register int len;
1443         caddr_t cp;
1444 {
1445         register int mlen;
1446         register struct mbuf *m = m0, *n;
1447         int totlen = 0;
1448
1449         if (m0 == 0)
1450                 return;
1451         while (off > (mlen = m->m_len)) {
1452                 off -= mlen;
1453                 totlen += mlen;
1454                 if (m->m_next == 0) {
1455                         n = m_getclr(M_DONTWAIT, m->m_type);
1456                         if (n == 0)
1457                                 goto out;
1458                         n->m_len = min(MLEN, len + off);
1459                         m->m_next = n;
1460                 }
1461                 m = m->m_next;
1462         }
1463         while (len > 0) {
1464                 mlen = min (m->m_len - off, len);
1465                 bcopy(cp, off + mtod(m, caddr_t), (unsigned)mlen);
1466                 cp += mlen;
1467                 len -= mlen;
1468                 mlen += off;
1469                 off = 0;
1470                 totlen += mlen;
1471                 if (len == 0)
1472                         break;
1473                 if (m->m_next == 0) {
1474                         n = m_get(M_DONTWAIT, m->m_type);
1475                         if (n == 0)
1476                                 break;
1477                         n->m_len = min(MLEN, len);
1478                         m->m_next = n;
1479                 }
1480                 m = m->m_next;
1481         }
1482 out:    if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1483                 m->m_pkthdr.len = totlen;
1484 }
1485
1486 void
1487 m_print(const struct mbuf *m)
1488 {
1489         int len;
1490         const struct mbuf *m2;
1491
1492         len = m->m_pkthdr.len;
1493         m2 = m;
1494         while (len) {
1495                 printf("%p %*D\n", m2, m2->m_len, (u_char *)m2->m_data, "-");
1496                 len -= m2->m_len;
1497                 m2 = m2->m_next;
1498         }
1499         return;
1500 }
1501
1502 /*
1503  * "Move" mbuf pkthdr from "from" to "to".
1504  * "from" must have M_PKTHDR set, and "to" must be empty.
1505  */
1506 void
1507 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
1508 {
1509         KASSERT((to->m_flags & M_EXT) == 0, ("m_move_pkthdr: to has cluster"));
1510
1511         to->m_flags = from->m_flags & M_COPYFLAGS;
1512         to->m_data = to->m_pktdat;
1513         to->m_pkthdr = from->m_pkthdr;          /* especially tags */
1514         SLIST_INIT(&from->m_pkthdr.tags);       /* purge tags from src */
1515         from->m_flags &= ~M_PKTHDR;
1516 }
1517
1518 /*
1519  * Duplicate "from"'s mbuf pkthdr in "to".
1520  * "from" must have M_PKTHDR set, and "to" must be empty.
1521  * In particular, this does a deep copy of the packet tags.
1522  */
1523 int
1524 m_dup_pkthdr(struct mbuf *to, struct mbuf *from, int how)
1525 {
1526         to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
1527         if ((to->m_flags & M_EXT) == 0)
1528                 to->m_data = to->m_pktdat;
1529         to->m_pkthdr = from->m_pkthdr;
1530         SLIST_INIT(&to->m_pkthdr.tags);
1531         return (m_tag_copy_chain(to, from, how));
1532 }
1533
1534 /*
1535  * Defragment a mbuf chain, returning the shortest possible
1536  * chain of mbufs and clusters.  If allocation fails and
1537  * this cannot be completed, NULL will be returned, but
1538  * the passed in chain will be unchanged.  Upon success,
1539  * the original chain will be freed, and the new chain
1540  * will be returned.
1541  *
1542  * If a non-packet header is passed in, the original
1543  * mbuf (chain?) will be returned unharmed.
1544  */
1545 struct mbuf *
1546 m_defrag(struct mbuf *m0, int how)
1547 {
1548         struct mbuf     *m_new = NULL, *m_final = NULL;
1549         int             progress = 0, length;
1550
1551         if (!(m0->m_flags & M_PKTHDR))
1552                 return (m0);
1553
1554 #ifdef MBUF_STRESS_TEST
1555         if (m_defragrandomfailures) {
1556                 int temp = arc4random() & 0xff;
1557                 if (temp == 0xba)
1558                         goto nospace;
1559         }
1560 #endif
1561         
1562         if (m0->m_pkthdr.len > MHLEN)
1563                 m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1564         else
1565                 m_final = m_gethdr(how, MT_DATA);
1566
1567         if (m_final == NULL)
1568                 goto nospace;
1569
1570         if (m_dup_pkthdr(m_final, m0, how) == NULL)
1571                 goto nospace;
1572
1573         m_new = m_final;
1574
1575         while (progress < m0->m_pkthdr.len) {
1576                 length = m0->m_pkthdr.len - progress;
1577                 if (length > MCLBYTES)
1578                         length = MCLBYTES;
1579
1580                 if (m_new == NULL) {
1581                         if (length > MLEN)
1582                                 m_new = m_getcl(how, MT_DATA, 0);
1583                         else
1584                                 m_new = m_get(how, MT_DATA);
1585                         if (m_new == NULL)
1586                                 goto nospace;
1587                 }
1588
1589                 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1590                 progress += length;
1591                 m_new->m_len = length;
1592                 if (m_new != m_final)
1593                         m_cat(m_final, m_new);
1594                 m_new = NULL;
1595         }
1596         if (m0->m_next == NULL)
1597                 m_defraguseless++;
1598         m_freem(m0);
1599         m0 = m_final;
1600         m_defragpackets++;
1601         m_defragbytes += m0->m_pkthdr.len;
1602         return (m0);
1603 nospace:
1604         m_defragfailure++;
1605         if (m_new)
1606                 m_free(m_new);
1607         if (m_final)
1608                 m_freem(m_final);
1609         return (NULL);
1610 }