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