Remove the priority part of the priority|flags argument to tsleep(). Only
[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.7 2003/07/19 21:14:39 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, 0, "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, 0, "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, 0, "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
472                 splx(ms);
473                 mbstat.m_drops++;
474                 if (ticks < last_report || (ticks - last_report) >= hz) {
475                         last_report = ticks;
476                         printf("All mbufs exhausted, please see tuning(7).\n");
477                 }
478         }
479
480         return (m);
481 }
482
483 /*
484  * As above; retry an MGETHDR.
485  */
486 struct mbuf *
487 m_retryhdr(i, t)
488         int i, t;
489 {
490         struct mbuf *m;
491         int ms;
492
493         /*
494          * Must only do the reclaim if not in an interrupt context.
495          */
496         if (i == M_WAIT) {
497 #ifdef __i386__
498                 KASSERT(mycpu->gd_intr_nesting_level == 0,
499                     ("MBALLOC: CANNOT WAIT IN INTERRUPT"));
500 #endif
501                 m_reclaim();
502         }
503
504         ms = splimp();
505         if (mmbfree == NULL)
506                 (void)m_mballoc(1, i);
507         m = mmbfree;
508         if (m != NULL) {
509                 mmbfree = m->m_next;
510                 mbtypes[MT_FREE]--;
511                 m->m_type = t;
512                 mbtypes[t]++;
513                 m->m_next = NULL;
514                 m->m_nextpkt = NULL;
515                 m->m_data = m->m_pktdat;
516                 m->m_flags = M_PKTHDR;
517                 m->m_pkthdr.rcvif = NULL;
518                 SLIST_INIT(&m->m_pkthdr.tags);
519                 m->m_pkthdr.csum_flags = 0;
520                 splx(ms);
521                 mbstat.m_wait++;
522         } else {
523                 static int last_report ; /* when we did that (in ticks) */
524
525                 splx(ms);
526                 mbstat.m_drops++;
527                 if (ticks < last_report || (ticks - last_report) >= hz) {
528                         last_report = ticks;
529                         printf("All mbufs exhausted, please see tuning(7).\n");
530                 }
531         }
532         
533         return (m);
534 }
535
536 static void
537 m_reclaim()
538 {
539         register struct domain *dp;
540         register struct protosw *pr;
541         int s = splimp();
542
543         for (dp = domains; dp; dp = dp->dom_next)
544                 for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++)
545                         if (pr->pr_drain)
546                                 (*pr->pr_drain)();
547         splx(s);
548         mbstat.m_drain++;
549 }
550
551 /*
552  * Space allocation routines.
553  * These are also available as macros
554  * for critical paths.
555  */
556 struct mbuf *
557 m_get(how, type)
558         int how, type;
559 {
560         struct mbuf *m;
561         int ms;
562
563         ms = splimp();
564         if (mmbfree == NULL)
565                 (void)m_mballoc(1, how);
566         m = mmbfree;
567         if (m != NULL) {
568                 mmbfree = m->m_next;
569                 mbtypes[MT_FREE]--;
570                 m->m_type = type;
571                 mbtypes[type]++;
572                 m->m_next = NULL;
573                 m->m_nextpkt = NULL;
574                 m->m_data = m->m_dat;
575                 m->m_flags = 0;
576                 splx(ms);
577         } else {
578                 splx(ms);
579                 m = m_retry(how, type);
580                 if (m == NULL && how == M_WAIT)
581                         m = m_mballoc_wait(MGET_C, type);
582         }
583         return (m);
584 }
585
586 struct mbuf *
587 m_gethdr(how, type)
588         int how, type;
589 {
590         struct mbuf *m;
591         int ms;
592
593         ms = splimp();
594         if (mmbfree == NULL)
595                 (void)m_mballoc(1, how);
596         m = mmbfree;
597         if (m != NULL) {
598                 mmbfree = m->m_next;
599                 mbtypes[MT_FREE]--;
600                 m->m_type = type;
601                 mbtypes[type]++;
602                 m->m_next = NULL;
603                 m->m_nextpkt = NULL;
604                 m->m_data = m->m_pktdat;
605                 m->m_flags = M_PKTHDR;
606                 m->m_pkthdr.rcvif = NULL;
607                 SLIST_INIT(&m->m_pkthdr.tags);
608                 m->m_pkthdr.csum_flags = 0;
609                 splx(ms);
610         } else {
611                 splx(ms);
612                 m = m_retryhdr(how, type);
613                 if (m == NULL && how == M_WAIT)
614                         m = m_mballoc_wait(MGETHDR_C, type);
615         }
616         return (m);
617 }
618
619 struct mbuf *
620 m_getclr(how, type)
621         int how, type;
622 {
623         register struct mbuf *m;
624
625         MGET(m, how, type);
626         if (m == 0)
627                 return (0);
628         bzero(mtod(m, caddr_t), MLEN);
629         return (m);
630 }
631
632 /*
633  * m_getcl() returns an mbuf with an attached cluster.
634  * Because many network drivers use this kind of buffers a lot, it is
635  * convenient to keep a small pool of free buffers of this kind.
636  * Even a small size such as 10 gives about 10% improvement in the
637  * forwarding rate in a bridge or router.
638  * The size of this free list is controlled by the sysctl variable
639  * mcl_pool_max. The list is populated on m_freem(), and used in
640  * m_getcl() if elements are available.
641  */
642 static struct mbuf *mcl_pool;
643 static int mcl_pool_now;
644 static int mcl_pool_max = 0;
645  
646 SYSCTL_INT(_kern_ipc, OID_AUTO, mcl_pool_max, CTLFLAG_RW, &mcl_pool_max, 0,
647            "Maximum number of mbufs+cluster in free list");
648 SYSCTL_INT(_kern_ipc, OID_AUTO, mcl_pool_now, CTLFLAG_RD, &mcl_pool_now, 0,
649            "Current number of mbufs+cluster in free list");
650
651 struct mbuf *
652 m_getcl(int how, short type, int flags)
653 {
654         int s = splimp();
655         struct mbuf *mp;
656
657         if (flags & M_PKTHDR) {
658                 if (type == MT_DATA && mcl_pool) {
659                         mp = mcl_pool;
660                         mcl_pool = mp->m_nextpkt;
661                         mcl_pool_now--;
662                         splx(s);
663                         mp->m_nextpkt = NULL;
664                         mp->m_data = mp->m_ext.ext_buf;
665                         mp->m_flags = M_PKTHDR|M_EXT;
666                         mp->m_pkthdr.rcvif = NULL;
667                         mp->m_pkthdr.csum_flags = 0;
668                         return mp;
669                 } else
670                         MGETHDR(mp, how, type);
671         } else
672                 MGET(mp, how, type);
673         if (mp) {
674                 MCLGET(mp, how);
675                 if ( (mp->m_flags & M_EXT) == 0) {
676                         m_free(mp);
677                         mp = NULL;
678                 }
679         }
680         splx(s);
681         return mp;
682 }
683
684 /*
685  * struct mbuf *
686  * m_getm(m, len, how, type)
687  *
688  * This will allocate len-worth of mbufs and/or mbuf clusters (whatever fits
689  * best) and return a pointer to the top of the allocated chain. If m is
690  * non-null, then we assume that it is a single mbuf or an mbuf chain to
691  * which we want len bytes worth of mbufs and/or clusters attached, and so
692  * if we succeed in allocating it, we will just return a pointer to m.
693  *
694  * If we happen to fail at any point during the allocation, we will free
695  * up everything we have already allocated and return NULL.
696  *
697  */
698 struct mbuf *
699 m_getm(struct mbuf *m, int len, int how, int type)
700 {
701         struct mbuf *top, *tail, *mp, *mtail = NULL;
702
703         KASSERT(len >= 0, ("len is < 0 in m_getm"));
704
705         MGET(mp, how, type);
706         if (mp == NULL)
707                 return (NULL);
708         else if (len > MINCLSIZE) {
709                 MCLGET(mp, how);
710                 if ((mp->m_flags & M_EXT) == 0) {
711                         m_free(mp);
712                         return (NULL);
713                 }
714         }
715         mp->m_len = 0;
716         len -= M_TRAILINGSPACE(mp);
717
718         if (m != NULL)
719                 for (mtail = m; mtail->m_next != NULL; mtail = mtail->m_next);
720         else
721                 m = mp;
722
723         top = tail = mp;
724         while (len > 0) {
725                 MGET(mp, how, type);
726                 if (mp == NULL)
727                         goto failed;
728
729                 tail->m_next = mp;
730                 tail = mp;
731                 if (len > MINCLSIZE) {
732                         MCLGET(mp, how);
733                         if ((mp->m_flags & M_EXT) == 0)
734                                 goto failed;
735                 }
736
737                 mp->m_len = 0;
738                 len -= M_TRAILINGSPACE(mp);
739         }
740
741         if (mtail != NULL)
742                 mtail->m_next = top;
743         return (m);
744
745 failed:
746         m_freem(top);
747         return (NULL);
748 }
749
750 /*
751  * MFREE(struct mbuf *m, struct mbuf *n)
752  * Free a single mbuf and associated external storage.
753  * Place the successor, if any, in n.
754  *
755  * we do need to check non-first mbuf for m_aux, since some of existing
756  * code does not call M_PREPEND properly.
757  * (example: call to bpf_mtap from drivers)
758  */
759 #define MFREE(m, n) MBUFLOCK(                                           \
760         struct mbuf *_mm = (m);                                         \
761                                                                         \
762         KASSERT(_mm->m_type != MT_FREE, ("freeing free mbuf"));         \
763         mbtypes[_mm->m_type]--;                                         \
764         if ((_mm->m_flags & M_PKTHDR) != 0)                             \
765                 m_tag_delete_chain(_mm, NULL);                          \
766         if (_mm->m_flags & M_EXT)                                       \
767                 MEXTFREE1(m);                                           \
768         (n) = _mm->m_next;                                              \
769         _mm->m_type = MT_FREE;                                          \
770         mbtypes[MT_FREE]++;                                             \
771         _mm->m_next = mmbfree;                                          \
772         mmbfree = _mm;                                                  \
773         MMBWAKEUP();                                                    \
774 )
775
776 struct mbuf *
777 m_free(m)
778         struct mbuf *m;
779 {
780         register struct mbuf *n;
781
782         MFREE(m, n);
783         return (n);
784 }
785
786 void
787 m_freem(m)
788         struct mbuf *m;
789 {
790         int s = splimp();
791
792         /*
793          * Try to keep a small pool of mbuf+cluster for quick use in
794          * device drivers. A good candidate is a M_PKTHDR buffer with
795          * only one cluster attached. Other mbufs, or those exceeding
796          * the pool size, are just m_free'd in the usual way.
797          * The following code makes sure that m_next, m_type,
798          * m_pkthdr.aux and m_ext.* are properly initialized.
799          * Other fields in the mbuf are initialized in m_getcl()
800          * upon allocation.
801          */
802         if (mcl_pool_now < mcl_pool_max && m && m->m_next == NULL &&
803             (m->m_flags & (M_PKTHDR|M_EXT)) == (M_PKTHDR|M_EXT) &&
804             m->m_type == MT_DATA && M_EXT_WRITABLE(m) ) {
805                 m_tag_delete_chain(m, NULL);
806                 m->m_nextpkt = mcl_pool;
807                 mcl_pool = m;
808                 mcl_pool_now++;
809         } else {
810                 while (m)
811                         m = m_free(m);
812         }
813         splx(s);
814 }
815
816 /*
817  * Mbuffer utility routines.
818  */
819
820 /*
821  * Lesser-used path for M_PREPEND:
822  * allocate new mbuf to prepend to chain,
823  * copy junk along.
824  */
825 struct mbuf *
826 m_prepend(m, len, how)
827         register struct mbuf *m;
828         int len, how;
829 {
830         struct mbuf *mn;
831
832         MGET(mn, how, m->m_type);
833         if (mn == (struct mbuf *)NULL) {
834                 m_freem(m);
835                 return ((struct mbuf *)NULL);
836         }
837         if (m->m_flags & M_PKTHDR)
838                 M_MOVE_PKTHDR(mn, m);
839         mn->m_next = m;
840         m = mn;
841         if (len < MHLEN)
842                 MH_ALIGN(m, len);
843         m->m_len = len;
844         return (m);
845 }
846
847 /*
848  * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
849  * continuing for "len" bytes.  If len is M_COPYALL, copy to end of mbuf.
850  * The wait parameter is a choice of M_WAIT/M_DONTWAIT from caller.
851  * Note that the copy is read-only, because clusters are not copied,
852  * only their reference counts are incremented.
853  */
854 #define MCFail (mbstat.m_mcfail)
855
856 struct mbuf *
857 m_copym(m, off0, len, wait)
858         register struct mbuf *m;
859         int off0, wait;
860         register int len;
861 {
862         register struct mbuf *n, **np;
863         register int off = off0;
864         struct mbuf *top;
865         int copyhdr = 0;
866
867         KASSERT(off >= 0, ("m_copym, negative off %d", off));
868         KASSERT(len >= 0, ("m_copym, negative len %d", len));
869         if (off == 0 && m->m_flags & M_PKTHDR)
870                 copyhdr = 1;
871         while (off > 0) {
872                 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
873                 if (off < m->m_len)
874                         break;
875                 off -= m->m_len;
876                 m = m->m_next;
877         }
878         np = &top;
879         top = 0;
880         while (len > 0) {
881                 if (m == 0) {
882                         KASSERT(len == M_COPYALL, 
883                             ("m_copym, length > size of mbuf chain"));
884                         break;
885                 }
886                 MGET(n, wait, m->m_type);
887                 *np = n;
888                 if (n == 0)
889                         goto nospace;
890                 if (copyhdr) {
891                         if (!m_dup_pkthdr(n, m, wait))
892                                 goto nospace;
893                         if (len == M_COPYALL)
894                                 n->m_pkthdr.len -= off0;
895                         else
896                                 n->m_pkthdr.len = len;
897                         copyhdr = 0;
898                 }
899                 n->m_len = min(len, m->m_len - off);
900                 if (m->m_flags & M_EXT) {
901                         n->m_data = m->m_data + off;
902                         if (m->m_ext.ext_ref == NULL) {
903                                 atomic_add_char(
904                                     &mclrefcnt[mtocl(m->m_ext.ext_buf)], 1);
905                         } else {
906                                 int s = splimp();
907
908                                 (*m->m_ext.ext_ref)(m->m_ext.ext_buf,
909                                     m->m_ext.ext_size);
910                                 splx(s);
911                         }
912                         n->m_ext = m->m_ext;
913                         n->m_flags |= M_EXT;
914                 } else
915                         bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
916                             (unsigned)n->m_len);
917                 if (len != M_COPYALL)
918                         len -= n->m_len;
919                 off = 0;
920                 m = m->m_next;
921                 np = &n->m_next;
922         }
923         if (top == 0)
924                 MCFail++;
925         return (top);
926 nospace:
927         m_freem(top);
928         MCFail++;
929         return (0);
930 }
931
932 /*
933  * Copy an entire packet, including header (which must be present).
934  * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
935  * Note that the copy is read-only, because clusters are not copied,
936  * only their reference counts are incremented.
937  * Preserve alignment of the first mbuf so if the creator has left
938  * some room at the beginning (e.g. for inserting protocol headers)
939  * the copies also have the room available.
940  */
941 struct mbuf *
942 m_copypacket(m, how)
943         struct mbuf *m;
944         int how;
945 {
946         struct mbuf *top, *n, *o;
947
948         MGET(n, how, m->m_type);
949         top = n;
950         if (!n)
951                 goto nospace;
952
953         if (!m_dup_pkthdr(n, m, how))
954                 goto nospace;
955         n->m_len = m->m_len;
956         if (m->m_flags & M_EXT) {
957                 n->m_data = m->m_data;
958                 if (m->m_ext.ext_ref == NULL)
959                         atomic_add_char(&mclrefcnt[mtocl(m->m_ext.ext_buf)], 1);
960                 else {
961                         int s = splimp();
962
963                         (*m->m_ext.ext_ref)(m->m_ext.ext_buf,
964                             m->m_ext.ext_size);
965                         splx(s);
966                 }
967                 n->m_ext = m->m_ext;
968                 n->m_flags |= M_EXT;
969         } else {
970                 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
971                 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
972         }
973
974         m = m->m_next;
975         while (m) {
976                 MGET(o, how, m->m_type);
977                 if (!o)
978                         goto nospace;
979
980                 n->m_next = o;
981                 n = n->m_next;
982
983                 n->m_len = m->m_len;
984                 if (m->m_flags & M_EXT) {
985                         n->m_data = m->m_data;
986                         if (m->m_ext.ext_ref == NULL) {
987                                 atomic_add_char(
988                                     &mclrefcnt[mtocl(m->m_ext.ext_buf)], 1);
989                         } else {
990                                 int s = splimp();
991
992                                 (*m->m_ext.ext_ref)(m->m_ext.ext_buf,
993                                     m->m_ext.ext_size);
994                                 splx(s);
995                         }
996                         n->m_ext = m->m_ext;
997                         n->m_flags |= M_EXT;
998                 } else {
999                         bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1000                 }
1001
1002                 m = m->m_next;
1003         }
1004         return top;
1005 nospace:
1006         m_freem(top);
1007         MCFail++;
1008         return 0;
1009 }
1010
1011 /*
1012  * Copy data from an mbuf chain starting "off" bytes from the beginning,
1013  * continuing for "len" bytes, into the indicated buffer.
1014  */
1015 void
1016 m_copydata(m, off, len, cp)
1017         register struct mbuf *m;
1018         register int off;
1019         register int len;
1020         caddr_t cp;
1021 {
1022         register unsigned count;
1023
1024         KASSERT(off >= 0, ("m_copydata, negative off %d", off));
1025         KASSERT(len >= 0, ("m_copydata, negative len %d", len));
1026         while (off > 0) {
1027                 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
1028                 if (off < m->m_len)
1029                         break;
1030                 off -= m->m_len;
1031                 m = m->m_next;
1032         }
1033         while (len > 0) {
1034                 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
1035                 count = min(m->m_len - off, len);
1036                 bcopy(mtod(m, caddr_t) + off, cp, count);
1037                 len -= count;
1038                 cp += count;
1039                 off = 0;
1040                 m = m->m_next;
1041         }
1042 }
1043
1044 /*
1045  * Copy a packet header mbuf chain into a completely new chain, including
1046  * copying any mbuf clusters.  Use this instead of m_copypacket() when
1047  * you need a writable copy of an mbuf chain.
1048  */
1049 struct mbuf *
1050 m_dup(m, how)
1051         struct mbuf *m;
1052         int how;
1053 {
1054         struct mbuf **p, *top = NULL;
1055         int remain, moff, nsize;
1056
1057         /* Sanity check */
1058         if (m == NULL)
1059                 return (0);
1060         KASSERT((m->m_flags & M_PKTHDR) != 0, ("%s: !PKTHDR", __FUNCTION__));
1061
1062         /* While there's more data, get a new mbuf, tack it on, and fill it */
1063         remain = m->m_pkthdr.len;
1064         moff = 0;
1065         p = &top;
1066         while (remain > 0 || top == NULL) {     /* allow m->m_pkthdr.len == 0 */
1067                 struct mbuf *n;
1068
1069                 /* Get the next new mbuf */
1070                 MGET(n, how, m->m_type);
1071                 if (n == NULL)
1072                         goto nospace;
1073                 if (top == NULL) {              /* first one, must be PKTHDR */
1074                         if (!m_dup_pkthdr(n, m, how))
1075                                 goto nospace;
1076                         nsize = MHLEN;
1077                 } else                          /* not the first one */
1078                         nsize = MLEN;
1079                 if (remain >= MINCLSIZE) {
1080                         MCLGET(n, how);
1081                         if ((n->m_flags & M_EXT) == 0) {
1082                                 (void)m_free(n);
1083                                 goto nospace;
1084                         }
1085                         nsize = MCLBYTES;
1086                 }
1087                 n->m_len = 0;
1088
1089                 /* Link it into the new chain */
1090                 *p = n;
1091                 p = &n->m_next;
1092
1093                 /* Copy data from original mbuf(s) into new mbuf */
1094                 while (n->m_len < nsize && m != NULL) {
1095                         int chunk = min(nsize - n->m_len, m->m_len - moff);
1096
1097                         bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1098                         moff += chunk;
1099                         n->m_len += chunk;
1100                         remain -= chunk;
1101                         if (moff == m->m_len) {
1102                                 m = m->m_next;
1103                                 moff = 0;
1104                         }
1105                 }
1106
1107                 /* Check correct total mbuf length */
1108                 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
1109                         ("%s: bogus m_pkthdr.len", __FUNCTION__));
1110         }
1111         return (top);
1112
1113 nospace:
1114         m_freem(top);
1115         MCFail++;
1116         return (0);
1117 }
1118
1119 /*
1120  * Concatenate mbuf chain n to m.
1121  * Both chains must be of the same type (e.g. MT_DATA).
1122  * Any m_pkthdr is not updated.
1123  */
1124 void
1125 m_cat(m, n)
1126         register struct mbuf *m, *n;
1127 {
1128         while (m->m_next)
1129                 m = m->m_next;
1130         while (n) {
1131                 if (m->m_flags & M_EXT ||
1132                     m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
1133                         /* just join the two chains */
1134                         m->m_next = n;
1135                         return;
1136                 }
1137                 /* splat the data from one into the other */
1138                 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1139                     (u_int)n->m_len);
1140                 m->m_len += n->m_len;
1141                 n = m_free(n);
1142         }
1143 }
1144
1145 void
1146 m_adj(mp, req_len)
1147         struct mbuf *mp;
1148         int req_len;
1149 {
1150         register int len = req_len;
1151         register struct mbuf *m;
1152         register int count;
1153
1154         if ((m = mp) == NULL)
1155                 return;
1156         if (len >= 0) {
1157                 /*
1158                  * Trim from head.
1159                  */
1160                 while (m != NULL && len > 0) {
1161                         if (m->m_len <= len) {
1162                                 len -= m->m_len;
1163                                 m->m_len = 0;
1164                                 m = m->m_next;
1165                         } else {
1166                                 m->m_len -= len;
1167                                 m->m_data += len;
1168                                 len = 0;
1169                         }
1170                 }
1171                 m = mp;
1172                 if (mp->m_flags & M_PKTHDR)
1173                         m->m_pkthdr.len -= (req_len - len);
1174         } else {
1175                 /*
1176                  * Trim from tail.  Scan the mbuf chain,
1177                  * calculating its length and finding the last mbuf.
1178                  * If the adjustment only affects this mbuf, then just
1179                  * adjust and return.  Otherwise, rescan and truncate
1180                  * after the remaining size.
1181                  */
1182                 len = -len;
1183                 count = 0;
1184                 for (;;) {
1185                         count += m->m_len;
1186                         if (m->m_next == (struct mbuf *)0)
1187                                 break;
1188                         m = m->m_next;
1189                 }
1190                 if (m->m_len >= len) {
1191                         m->m_len -= len;
1192                         if (mp->m_flags & M_PKTHDR)
1193                                 mp->m_pkthdr.len -= len;
1194                         return;
1195                 }
1196                 count -= len;
1197                 if (count < 0)
1198                         count = 0;
1199                 /*
1200                  * Correct length for chain is "count".
1201                  * Find the mbuf with last data, adjust its length,
1202                  * and toss data from remaining mbufs on chain.
1203                  */
1204                 m = mp;
1205                 if (m->m_flags & M_PKTHDR)
1206                         m->m_pkthdr.len = count;
1207                 for (; m; m = m->m_next) {
1208                         if (m->m_len >= count) {
1209                                 m->m_len = count;
1210                                 break;
1211                         }
1212                         count -= m->m_len;
1213                 }
1214                 while (m->m_next)
1215                         (m = m->m_next) ->m_len = 0;
1216         }
1217 }
1218
1219 /*
1220  * Rearange an mbuf chain so that len bytes are contiguous
1221  * and in the data area of an mbuf (so that mtod and dtom
1222  * will work for a structure of size len).  Returns the resulting
1223  * mbuf chain on success, frees it and returns null on failure.
1224  * If there is room, it will add up to max_protohdr-len extra bytes to the
1225  * contiguous region in an attempt to avoid being called next time.
1226  */
1227 #define MPFail (mbstat.m_mpfail)
1228
1229 struct mbuf *
1230 m_pullup(n, len)
1231         register struct mbuf *n;
1232         int len;
1233 {
1234         register struct mbuf *m;
1235         register int count;
1236         int space;
1237
1238         /*
1239          * If first mbuf has no cluster, and has room for len bytes
1240          * without shifting current data, pullup into it,
1241          * otherwise allocate a new mbuf to prepend to the chain.
1242          */
1243         if ((n->m_flags & M_EXT) == 0 &&
1244             n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
1245                 if (n->m_len >= len)
1246                         return (n);
1247                 m = n;
1248                 n = n->m_next;
1249                 len -= m->m_len;
1250         } else {
1251                 if (len > MHLEN)
1252                         goto bad;
1253                 MGET(m, M_DONTWAIT, n->m_type);
1254                 if (m == 0)
1255                         goto bad;
1256                 m->m_len = 0;
1257                 if (n->m_flags & M_PKTHDR)
1258                         M_MOVE_PKTHDR(m, n);
1259         }
1260         space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1261         do {
1262                 count = min(min(max(len, max_protohdr), space), n->m_len);
1263                 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1264                   (unsigned)count);
1265                 len -= count;
1266                 m->m_len += count;
1267                 n->m_len -= count;
1268                 space -= count;
1269                 if (n->m_len)
1270                         n->m_data += count;
1271                 else
1272                         n = m_free(n);
1273         } while (len > 0 && n);
1274         if (len > 0) {
1275                 (void) m_free(m);
1276                 goto bad;
1277         }
1278         m->m_next = n;
1279         return (m);
1280 bad:
1281         m_freem(n);
1282         MPFail++;
1283         return (0);
1284 }
1285
1286 /*
1287  * Partition an mbuf chain in two pieces, returning the tail --
1288  * all but the first len0 bytes.  In case of failure, it returns NULL and
1289  * attempts to restore the chain to its original state.
1290  *
1291  * Note that the resulting mbufs might be read-only, because the new
1292  * mbuf can end up sharing an mbuf cluster with the original mbuf if
1293  * the "breaking point" happens to lie within a cluster mbuf. Use the
1294  * M_WRITABLE() macro to check for this case.
1295  */
1296 struct mbuf *
1297 m_split(m0, len0, wait)
1298         register struct mbuf *m0;
1299         int len0, wait;
1300 {
1301         register struct mbuf *m, *n;
1302         unsigned len = len0, remain;
1303
1304         for (m = m0; m && len > m->m_len; m = m->m_next)
1305                 len -= m->m_len;
1306         if (m == 0)
1307                 return (0);
1308         remain = m->m_len - len;
1309         if (m0->m_flags & M_PKTHDR) {
1310                 MGETHDR(n, wait, m0->m_type);
1311                 if (n == 0)
1312                         return (0);
1313                 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1314                 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1315                 m0->m_pkthdr.len = len0;
1316                 if (m->m_flags & M_EXT)
1317                         goto extpacket;
1318                 if (remain > MHLEN) {
1319                         /* m can't be the lead packet */
1320                         MH_ALIGN(n, 0);
1321                         n->m_next = m_split(m, len, wait);
1322                         if (n->m_next == 0) {
1323                                 (void) m_free(n);
1324                                 return (0);
1325                         } else {
1326                                 n->m_len = 0;
1327                                 return (n);
1328                         }
1329                 } else
1330                         MH_ALIGN(n, remain);
1331         } else if (remain == 0) {
1332                 n = m->m_next;
1333                 m->m_next = 0;
1334                 return (n);
1335         } else {
1336                 MGET(n, wait, m->m_type);
1337                 if (n == 0)
1338                         return (0);
1339                 M_ALIGN(n, remain);
1340         }
1341 extpacket:
1342         if (m->m_flags & M_EXT) {
1343                 n->m_flags |= M_EXT;
1344                 n->m_ext = m->m_ext;
1345                 if (m->m_ext.ext_ref == NULL)
1346                         atomic_add_char(&mclrefcnt[mtocl(m->m_ext.ext_buf)], 1);
1347                 else {
1348                         int s = splimp();
1349
1350                         (*m->m_ext.ext_ref)(m->m_ext.ext_buf,
1351                             m->m_ext.ext_size);
1352                         splx(s);
1353                 }
1354                 n->m_data = m->m_data + len;
1355         } else {
1356                 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1357         }
1358         n->m_len = remain;
1359         m->m_len = len;
1360         n->m_next = m->m_next;
1361         m->m_next = 0;
1362         return (n);
1363 }
1364 /*
1365  * Routine to copy from device local memory into mbufs.
1366  */
1367 struct mbuf *
1368 m_devget(buf, totlen, off0, ifp, copy)
1369         char *buf;
1370         int totlen, off0;
1371         struct ifnet *ifp;
1372         void (*copy) __P((char *from, caddr_t to, u_int len));
1373 {
1374         register struct mbuf *m;
1375         struct mbuf *top = 0, **mp = &top;
1376         register int off = off0, len;
1377         register char *cp;
1378         char *epkt;
1379
1380         cp = buf;
1381         epkt = cp + totlen;
1382         if (off) {
1383                 cp += off + 2 * sizeof(u_short);
1384                 totlen -= 2 * sizeof(u_short);
1385         }
1386         MGETHDR(m, M_DONTWAIT, MT_DATA);
1387         if (m == 0)
1388                 return (0);
1389         m->m_pkthdr.rcvif = ifp;
1390         m->m_pkthdr.len = totlen;
1391         m->m_len = MHLEN;
1392
1393         while (totlen > 0) {
1394                 if (top) {
1395                         MGET(m, M_DONTWAIT, MT_DATA);
1396                         if (m == 0) {
1397                                 m_freem(top);
1398                                 return (0);
1399                         }
1400                         m->m_len = MLEN;
1401                 }
1402                 len = min(totlen, epkt - cp);
1403                 if (len >= MINCLSIZE) {
1404                         MCLGET(m, M_DONTWAIT);
1405                         if (m->m_flags & M_EXT)
1406                                 m->m_len = len = min(len, MCLBYTES);
1407                         else
1408                                 len = m->m_len;
1409                 } else {
1410                         /*
1411                          * Place initial small packet/header at end of mbuf.
1412                          */
1413                         if (len < m->m_len) {
1414                                 if (top == 0 && len + max_linkhdr <= m->m_len)
1415                                         m->m_data += max_linkhdr;
1416                                 m->m_len = len;
1417                         } else
1418                                 len = m->m_len;
1419                 }
1420                 if (copy)
1421                         copy(cp, mtod(m, caddr_t), (unsigned)len);
1422                 else
1423                         bcopy(cp, mtod(m, caddr_t), (unsigned)len);
1424                 cp += len;
1425                 *mp = m;
1426                 mp = &m->m_next;
1427                 totlen -= len;
1428                 if (cp == epkt)
1429                         cp = buf;
1430         }
1431         return (top);
1432 }
1433
1434 /*
1435  * Copy data from a buffer back into the indicated mbuf chain,
1436  * starting "off" bytes from the beginning, extending the mbuf
1437  * chain if necessary.
1438  */
1439 void
1440 m_copyback(m0, off, len, cp)
1441         struct  mbuf *m0;
1442         register int off;
1443         register int len;
1444         caddr_t cp;
1445 {
1446         register int mlen;
1447         register struct mbuf *m = m0, *n;
1448         int totlen = 0;
1449
1450         if (m0 == 0)
1451                 return;
1452         while (off > (mlen = m->m_len)) {
1453                 off -= mlen;
1454                 totlen += mlen;
1455                 if (m->m_next == 0) {
1456                         n = m_getclr(M_DONTWAIT, m->m_type);
1457                         if (n == 0)
1458                                 goto out;
1459                         n->m_len = min(MLEN, len + off);
1460                         m->m_next = n;
1461                 }
1462                 m = m->m_next;
1463         }
1464         while (len > 0) {
1465                 mlen = min (m->m_len - off, len);
1466                 bcopy(cp, off + mtod(m, caddr_t), (unsigned)mlen);
1467                 cp += mlen;
1468                 len -= mlen;
1469                 mlen += off;
1470                 off = 0;
1471                 totlen += mlen;
1472                 if (len == 0)
1473                         break;
1474                 if (m->m_next == 0) {
1475                         n = m_get(M_DONTWAIT, m->m_type);
1476                         if (n == 0)
1477                                 break;
1478                         n->m_len = min(MLEN, len);
1479                         m->m_next = n;
1480                 }
1481                 m = m->m_next;
1482         }
1483 out:    if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1484                 m->m_pkthdr.len = totlen;
1485 }
1486
1487 void
1488 m_print(const struct mbuf *m)
1489 {
1490         int len;
1491         const struct mbuf *m2;
1492
1493         len = m->m_pkthdr.len;
1494         m2 = m;
1495         while (len) {
1496                 printf("%p %*D\n", m2, m2->m_len, (u_char *)m2->m_data, "-");
1497                 len -= m2->m_len;
1498                 m2 = m2->m_next;
1499         }
1500         return;
1501 }
1502
1503 /*
1504  * "Move" mbuf pkthdr from "from" to "to".
1505  * "from" must have M_PKTHDR set, and "to" must be empty.
1506  */
1507 void
1508 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
1509 {
1510         KASSERT((to->m_flags & M_EXT) == 0, ("m_move_pkthdr: to has cluster"));
1511
1512         to->m_flags = from->m_flags & M_COPYFLAGS;
1513         to->m_data = to->m_pktdat;
1514         to->m_pkthdr = from->m_pkthdr;          /* especially tags */
1515         SLIST_INIT(&from->m_pkthdr.tags);       /* purge tags from src */
1516         from->m_flags &= ~M_PKTHDR;
1517 }
1518
1519 /*
1520  * Duplicate "from"'s mbuf pkthdr in "to".
1521  * "from" must have M_PKTHDR set, and "to" must be empty.
1522  * In particular, this does a deep copy of the packet tags.
1523  */
1524 int
1525 m_dup_pkthdr(struct mbuf *to, struct mbuf *from, int how)
1526 {
1527         to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
1528         if ((to->m_flags & M_EXT) == 0)
1529                 to->m_data = to->m_pktdat;
1530         to->m_pkthdr = from->m_pkthdr;
1531         SLIST_INIT(&to->m_pkthdr.tags);
1532         return (m_tag_copy_chain(to, from, how));
1533 }
1534
1535 /*
1536  * Defragment a mbuf chain, returning the shortest possible
1537  * chain of mbufs and clusters.  If allocation fails and
1538  * this cannot be completed, NULL will be returned, but
1539  * the passed in chain will be unchanged.  Upon success,
1540  * the original chain will be freed, and the new chain
1541  * will be returned.
1542  *
1543  * If a non-packet header is passed in, the original
1544  * mbuf (chain?) will be returned unharmed.
1545  */
1546 struct mbuf *
1547 m_defrag(struct mbuf *m0, int how)
1548 {
1549         struct mbuf     *m_new = NULL, *m_final = NULL;
1550         int             progress = 0, length;
1551
1552         if (!(m0->m_flags & M_PKTHDR))
1553                 return (m0);
1554
1555 #ifdef MBUF_STRESS_TEST
1556         if (m_defragrandomfailures) {
1557                 int temp = arc4random() & 0xff;
1558                 if (temp == 0xba)
1559                         goto nospace;
1560         }
1561 #endif
1562         
1563         if (m0->m_pkthdr.len > MHLEN)
1564                 m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1565         else
1566                 m_final = m_gethdr(how, MT_DATA);
1567
1568         if (m_final == NULL)
1569                 goto nospace;
1570
1571         if (m_dup_pkthdr(m_final, m0, how) == NULL)
1572                 goto nospace;
1573
1574         m_new = m_final;
1575
1576         while (progress < m0->m_pkthdr.len) {
1577                 length = m0->m_pkthdr.len - progress;
1578                 if (length > MCLBYTES)
1579                         length = MCLBYTES;
1580
1581                 if (m_new == NULL) {
1582                         if (length > MLEN)
1583                                 m_new = m_getcl(how, MT_DATA, 0);
1584                         else
1585                                 m_new = m_get(how, MT_DATA);
1586                         if (m_new == NULL)
1587                                 goto nospace;
1588                 }
1589
1590                 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1591                 progress += length;
1592                 m_new->m_len = length;
1593                 if (m_new != m_final)
1594                         m_cat(m_final, m_new);
1595                 m_new = NULL;
1596         }
1597         if (m0->m_next == NULL)
1598                 m_defraguseless++;
1599         m_freem(m0);
1600         m0 = m_final;
1601         m_defragpackets++;
1602         m_defragbytes += m0->m_pkthdr.len;
1603         return (m0);
1604 nospace:
1605         m_defragfailure++;
1606         if (m_new)
1607                 m_free(m_new);
1608         if (m_final)
1609                 m_freem(m_final);
1610         return (NULL);
1611 }