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