1a2a72c281cf54f3d8149f8fd2aca06fa87265fb
[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.42 2005/06/08 16:30:47 dillon Exp $
86  */
87
88 #include "opt_param.h"
89 #include "opt_ddb.h"
90 #include "opt_mbuf_stress_test.h"
91 #include <sys/param.h>
92 #include <sys/systm.h>
93 #include <sys/malloc.h>
94 #include <sys/mbuf.h>
95 #include <sys/kernel.h>
96 #include <sys/sysctl.h>
97 #include <sys/domain.h>
98 #include <sys/objcache.h>
99 #include <sys/protosw.h>
100 #include <sys/uio.h>
101 #include <sys/thread.h>
102 #include <sys/globaldata.h>
103 #include <sys/thread2.h>
104
105 #include <vm/vm.h>
106 #include <vm/vm_kern.h>
107 #include <vm/vm_extern.h>
108
109 #ifdef INVARIANTS
110 #include <machine/cpu.h>
111 #endif
112
113 /*
114  * mbuf cluster meta-data
115  */
116 struct mbcluster {
117         int32_t mcl_refs;
118         void    *mcl_data;
119 };
120
121 static void mbinit(void *);
122 SYSINIT(mbuf, SI_SUB_MBUF, SI_ORDER_FIRST, mbinit, NULL)
123
124 static u_long   mbtypes[MT_NTYPES];
125
126 struct mbstat mbstat;
127 int     max_linkhdr;
128 int     max_protohdr;
129 int     max_hdr;
130 int     max_datalen;
131 int     m_defragpackets;
132 int     m_defragbytes;
133 int     m_defraguseless;
134 int     m_defragfailure;
135 #ifdef MBUF_STRESS_TEST
136 int     m_defragrandomfailures;
137 #endif
138
139 struct objcache *mbuf_cache, *mbufphdr_cache;
140 struct objcache *mclmeta_cache;
141 struct objcache *mbufcluster_cache, *mbufphdrcluster_cache;
142
143 int     nmbclusters;
144 int     nmbufs;
145
146 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RW,
147            &max_linkhdr, 0, "");
148 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RW,
149            &max_protohdr, 0, "");
150 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RW, &max_hdr, 0, "");
151 SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RW,
152            &max_datalen, 0, "");
153 SYSCTL_INT(_kern_ipc, OID_AUTO, mbuf_wait, CTLFLAG_RW,
154            &mbuf_wait, 0, "");
155 SYSCTL_STRUCT(_kern_ipc, KIPC_MBSTAT, mbstat, CTLFLAG_RW, &mbstat, mbstat, "");
156 SYSCTL_OPAQUE(_kern_ipc, OID_AUTO, mbtypes, CTLFLAG_RD, mbtypes,
157            sizeof(mbtypes), "LU", "");
158 SYSCTL_INT(_kern_ipc, KIPC_NMBCLUSTERS, nmbclusters, CTLFLAG_RW, 
159            &nmbclusters, 0, "Maximum number of mbuf clusters available");
160 SYSCTL_INT(_kern_ipc, OID_AUTO, nmbufs, CTLFLAG_RW, &nmbufs, 0,
161            "Maximum number of mbufs available"); 
162
163 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
164            &m_defragpackets, 0, "");
165 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
166            &m_defragbytes, 0, "");
167 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
168            &m_defraguseless, 0, "");
169 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
170            &m_defragfailure, 0, "");
171 #ifdef MBUF_STRESS_TEST
172 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
173            &m_defragrandomfailures, 0, "");
174 #endif
175
176 static MALLOC_DEFINE(M_MBUF, "mbuf", "mbuf");
177 static MALLOC_DEFINE(M_MBUFCL, "mbufcl", "mbufcl");
178 static MALLOC_DEFINE(M_MCLMETA, "mclmeta", "mclmeta");
179
180 static void m_reclaim (void);
181 static void m_mclref(void *arg);
182 static void m_mclfree(void *arg);
183
184 #ifndef NMBCLUSTERS
185 #define NMBCLUSTERS     (512 + maxusers * 16)
186 #endif
187 #ifndef NMBUFS
188 #define NMBUFS          (nmbclusters * 2)
189 #endif
190
191 /*
192  * Perform sanity checks of tunables declared above.
193  */
194 static void
195 tunable_mbinit(void *dummy)
196 {
197
198         /*
199          * This has to be done before VM init.
200          */
201         nmbclusters = NMBCLUSTERS;
202         TUNABLE_INT_FETCH("kern.ipc.nmbclusters", &nmbclusters);
203         nmbufs = NMBUFS;
204         TUNABLE_INT_FETCH("kern.ipc.nmbufs", &nmbufs);
205         /* Sanity checks */
206         if (nmbufs < nmbclusters * 2)
207                 nmbufs = nmbclusters * 2;
208
209         return;
210 }
211 SYSINIT(tunable_mbinit, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_mbinit, NULL);
212
213 /* "number of clusters of pages" */
214 #define NCL_INIT        1
215
216 #define NMB_INIT        16
217
218 /*
219  * The mbuf object cache only guarantees that m_next and m_nextpkt are
220  * NULL and that m_data points to the beginning of the data area.  In
221  * particular, m_len and m_pkthdr.len are uninitialized.  It is the
222  * responsibility of the caller to initialize those fields before use.
223  */
224
225 static boolean_t __inline
226 mbuf_ctor(void *obj, void *private, int ocflags)
227 {
228         struct mbuf *m = obj;
229
230         m->m_next = NULL;
231         m->m_nextpkt = NULL;
232         m->m_data = m->m_dat;
233         m->m_flags = 0;
234
235         return (TRUE);
236 }
237
238 /*
239  * Initialize the mbuf and the packet header fields.
240  */
241 static boolean_t
242 mbufphdr_ctor(void *obj, void *private, int ocflags)
243 {
244         struct mbuf *m = obj;
245
246         m->m_next = NULL;
247         m->m_nextpkt = NULL;
248         m->m_data = m->m_pktdat;
249         m->m_flags = M_PKTHDR;
250
251         m->m_pkthdr.rcvif = NULL;       /* eliminate XXX JH */
252         SLIST_INIT(&m->m_pkthdr.tags);
253         m->m_pkthdr.csum_flags = 0;     /* eliminate XXX JH */
254         m->m_pkthdr.fw_flags = 0;       /* eliminate XXX JH */
255
256         return (TRUE);
257 }
258
259 /*
260  * A mbcluster object consists of 2K (MCLBYTES) cluster and a refcount.
261  */
262 static boolean_t
263 mclmeta_ctor(void *obj, void *private, int ocflags)
264 {
265         struct mbcluster *cl = obj;
266         void *buf;
267
268         if (ocflags & M_NOWAIT)
269                 buf = malloc(MCLBYTES, M_MBUFCL, M_NOWAIT | M_ZERO);
270         else
271                 buf = malloc(MCLBYTES, M_MBUFCL, M_INTWAIT | M_ZERO);
272         if (buf == NULL)
273                 return (FALSE);
274         cl->mcl_refs = 1;
275         cl->mcl_data = buf;
276         return (TRUE);
277 }
278
279 static void
280 linkcluster(struct mbuf *m, struct mbcluster *cl)
281 {
282         /*
283          * Add the cluster to the mbuf.  The caller will detect that the
284          * mbuf now has an attached cluster.
285          */
286         m->m_ext.ext_arg = cl;
287         m->m_ext.ext_buf = cl->mcl_data;
288         m->m_ext.ext_ref = m_mclref;
289         m->m_ext.ext_free = m_mclfree;
290         m->m_ext.ext_size = MCLBYTES;
291
292         m->m_data = m->m_ext.ext_buf;
293         m->m_flags |= M_EXT | M_EXT_CLUSTER;
294 }
295
296 static boolean_t
297 mbufphdrcluster_ctor(void *obj, void *private, int ocflags)
298 {
299         struct mbuf *m = obj;
300         struct mbcluster *cl;
301
302         mbufphdr_ctor(obj, private, ocflags);
303         cl = objcache_get(mclmeta_cache, ocflags);
304         if (cl == NULL)
305                 return (FALSE);
306         linkcluster(m, cl);
307         return (TRUE);
308 }
309
310 static boolean_t
311 mbufcluster_ctor(void *obj, void *private, int ocflags)
312 {
313         struct mbuf *m = obj;
314         struct mbcluster *cl;
315
316         mbuf_ctor(obj, private, ocflags);
317         cl = objcache_get(mclmeta_cache, ocflags);
318         if (cl == NULL)
319                 return (FALSE);
320         linkcluster(m, cl);
321         return (TRUE);
322 }
323
324 static void
325 mclmeta_dtor(void *obj, void *private)
326 {
327         struct mbcluster *mcl = obj;
328
329         KKASSERT(mcl->mcl_refs == 1);
330         free(mcl->mcl_data, M_MBUFCL);
331 }
332
333 static void
334 mbufcluster_dtor(void *obj, void *private)
335 {
336         struct mbuf *m = obj;
337
338         objcache_put(mclmeta_cache, m->m_ext.ext_arg);
339 }
340
341 static void
342 mbufphdrcluster_dtor(void *obj, void *private)
343 {
344         struct mbuf *m = obj;
345
346         objcache_put(mclmeta_cache, m->m_ext.ext_arg);
347 }
348
349 struct objcache_malloc_args mbuf_malloc_args = { MSIZE, M_MBUF };
350 struct objcache_malloc_args mclmeta_malloc_args =
351         { sizeof(struct mbcluster), M_MCLMETA };
352
353 /* ARGSUSED*/
354 static void
355 mbinit(void *dummy)
356 {
357         mbstat.m_msize = MSIZE;
358         mbstat.m_mclbytes = MCLBYTES;
359         mbstat.m_minclsize = MINCLSIZE;
360         mbstat.m_mlen = MLEN;
361         mbstat.m_mhlen = MHLEN;
362
363         mbuf_cache = objcache_create("mbuf", nmbufs, 0,
364             mbuf_ctor, null_dtor, NULL,
365             objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
366         mbufphdr_cache = objcache_create("mbuf pkt hdr", nmbufs, 64,
367             mbufphdr_ctor, null_dtor, NULL,
368             objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
369         mclmeta_cache = objcache_create("cluster mbuf", nmbclusters , 0,
370             mclmeta_ctor, mclmeta_dtor, NULL,
371             objcache_malloc_alloc, objcache_malloc_free, &mclmeta_malloc_args);
372         mbufcluster_cache = objcache_create("mbuf + cluster", nmbclusters, 0,
373             mbufcluster_ctor, mbufcluster_dtor, NULL,
374             objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
375         mbufphdrcluster_cache = objcache_create("mbuf pkt hdr + cluster",
376             nmbclusters, 64, mbufphdrcluster_ctor, mbufphdrcluster_dtor, NULL,
377             objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
378         return;
379 }
380
381 /*
382  * Return the number of references to this mbuf's data.  0 is returned
383  * if the mbuf is not M_EXT, a reference count is returned if it is
384  * M_EXT | M_EXT_CLUSTER, and 99 is returned if it is a special M_EXT.
385  */
386 int
387 m_sharecount(struct mbuf *m)
388 {
389         switch (m->m_flags & (M_EXT | M_EXT_CLUSTER)) {
390         case 0:
391                 return (0);
392         case M_EXT:
393                 return (99);
394         case M_EXT | M_EXT_CLUSTER:
395                 return (((struct mbcluster *)m->m_ext.ext_arg)->mcl_refs);
396         }
397         /* NOTREACHED */
398         return (0);             /* to shut up compiler */
399 }
400
401 /*
402  * change mbuf to new type
403  */
404 void
405 m_chtype(struct mbuf *m, int type)
406 {
407         crit_enter();
408         ++mbtypes[type];
409         --mbtypes[m->m_type];
410         m->m_type = type;
411         crit_exit();
412 }
413
414 static void
415 m_reclaim(void)
416 {
417         struct domain *dp;
418         struct protosw *pr;
419
420         crit_enter();
421         SLIST_FOREACH(dp, &domains, dom_next) {
422                 for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++) {
423                         if (pr->pr_drain)
424                                 (*pr->pr_drain)();
425                 }
426         }
427         crit_exit();
428         mbstat.m_drain++;
429 }
430
431 static void __inline
432 updatestats(struct mbuf *m, int type)
433 {
434         m->m_type = type;
435
436         crit_enter();
437         ++mbtypes[type];
438         ++mbstat.m_mbufs;
439         crit_exit();
440 }
441
442 /*
443  * Allocate an mbuf.
444  */
445 struct mbuf *
446 m_get(int how, int type)
447 {
448         struct mbuf *m;
449         int ntries = 0;
450         int ocf = MBTOM(how);
451
452 retryonce:
453
454         m = objcache_get(mbuf_cache, ocf);
455
456         if (m == NULL) {
457                 if ((how & MB_TRYWAIT) && ntries++ == 0) {
458                         struct objcache *reclaimlist[] = {
459                                 mbufphdr_cache,
460                                 mbufcluster_cache, mbufphdrcluster_cache
461                         };
462                         const int nreclaims = __arysize(reclaimlist);
463
464                         if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
465                                 m_reclaim();
466                         goto retryonce;
467                 }
468                 return (NULL);
469         }
470
471         updatestats(m, type);
472         return (m);
473 }
474
475 struct mbuf *
476 m_gethdr(int how, int type)
477 {
478         struct mbuf *m;
479         int ocf = MBTOM(how);
480         int ntries = 0;
481
482 retryonce:
483
484         m = objcache_get(mbufphdr_cache, ocf);
485
486         if (m == NULL) {
487                 if ((how & MB_TRYWAIT) && ntries++ == 0) {
488                         struct objcache *reclaimlist[] = {
489                                 mbuf_cache,
490                                 mbufcluster_cache, mbufphdrcluster_cache
491                         };
492                         const int nreclaims = __arysize(reclaimlist);
493
494                         if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
495                                 m_reclaim();
496                         goto retryonce;
497                 }
498                 return (NULL);
499         }
500
501         updatestats(m, type);
502         return (m);
503 }
504
505 /*
506  * Get a mbuf (not a mbuf cluster!) and zero it.
507  * Deprecated.
508  */
509 struct mbuf *
510 m_getclr(int how, int type)
511 {
512         struct mbuf *m;
513
514         m = m_get(how, type);
515         if (m != NULL)
516                 bzero(m->m_data, MLEN);
517         return (m);
518 }
519
520 /*
521  * Returns an mbuf with an attached cluster.
522  * Because many network drivers use this kind of buffers a lot, it is
523  * convenient to keep a small pool of free buffers of this kind.
524  * Even a small size such as 10 gives about 10% improvement in the
525  * forwarding rate in a bridge or router.
526  */
527 struct mbuf *
528 m_getcl(int how, short type, int flags)
529 {
530         struct mbuf *m;
531         int ocflags = MBTOM(how);
532         int ntries = 0;
533
534 retryonce:
535
536         if (flags & M_PKTHDR)
537                 m = objcache_get(mbufphdrcluster_cache, ocflags);
538         else
539                 m = objcache_get(mbufcluster_cache, ocflags);
540
541         if (m == NULL) {
542                 if ((how & MB_TRYWAIT) && ntries++ == 0) {
543                         struct objcache *reclaimlist[1];
544
545                         if (flags & M_PKTHDR)
546                                 reclaimlist[0] = mbufcluster_cache;
547                         else
548                                 reclaimlist[0] = mbufphdrcluster_cache;
549                         if (!objcache_reclaimlist(reclaimlist, 1, ocflags))
550                                 m_reclaim();
551                         goto retryonce;
552                 }
553                 return (NULL);
554         }
555
556         m->m_type = type;
557
558         crit_enter();
559         ++mbtypes[type];
560         ++mbstat.m_clusters;
561         crit_exit();
562         return (m);
563 }
564
565 /*
566  * Allocate chain of requested length.
567  */
568 struct mbuf *
569 m_getc(int len, int how, int type)
570 {
571         struct mbuf *n, *nfirst = NULL, **ntail = &nfirst;
572         int nsize;
573
574         while (len > 0) {
575                 n = m_getl(len, how, type, 0, &nsize);
576                 if (n == NULL)
577                         goto failed;
578                 n->m_len = 0;
579                 *ntail = n;
580                 ntail = &n->m_next;
581                 len -= nsize;
582         }
583         return (nfirst);
584
585 failed:
586         m_freem(nfirst);
587         return (NULL);
588 }
589
590 /*
591  * Allocate len-worth of mbufs and/or mbuf clusters (whatever fits best)
592  * and return a pointer to the head of the allocated chain. If m0 is
593  * non-null, then we assume that it is a single mbuf or an mbuf chain to
594  * which we want len bytes worth of mbufs and/or clusters attached, and so
595  * if we succeed in allocating it, we will just return a pointer to m0.
596  *
597  * If we happen to fail at any point during the allocation, we will free
598  * up everything we have already allocated and return NULL.
599  *
600  * Deprecated.  Use m_getc() and m_cat() instead.
601  */
602 struct mbuf *
603 m_getm(struct mbuf *m0, int len, int how, int type)
604 {
605         struct mbuf *nfirst;
606
607         nfirst = m_getc(len, how, type);
608
609         if (m0 != NULL) {
610                 m_last(m0)->m_next = nfirst;
611                 return (m0);
612         }
613
614         return (nfirst);
615 }
616
617 /*
618  * Adds a cluster to a normal mbuf, M_EXT is set on success.
619  * Deprecated.  Use m_getcl() instead.
620  */
621 void
622 m_mclget(struct mbuf *m, int how)
623 {
624         struct mbcluster *mcl;
625
626         mcl = objcache_get(mclmeta_cache, MBTOM(how));
627         if (mcl == NULL)
628                 return;
629         linkcluster(m, mcl);
630
631         crit_enter();
632         --mbstat.m_mbufs;
633         ++mbstat.m_clusters;
634         crit_exit();
635 }
636
637 static void
638 m_mclref(void *arg)
639 {
640         struct mbcluster *mcl = arg;
641
642         atomic_add_int(&mcl->mcl_refs, 1);
643 }
644
645 static void
646 m_mclfree(void *arg)
647 {
648         struct mbcluster *mcl = arg;
649
650         KKASSERT(mcl->mcl_refs > 1);
651         atomic_subtract_int(&mcl->mcl_refs, 1);
652 }
653
654 extern void db_print_backtrace(void);
655
656 /*
657  * Free a single mbuf and any associated external storage.  The successor,
658  * if any, is returned.
659  *
660  * We do need to check non-first mbuf for m_aux, since some of existing
661  * code does not call M_PREPEND properly.
662  * (example: call to bpf_mtap from drivers)
663  */
664 struct mbuf *
665 m_free(struct mbuf *m)
666 {
667         struct mbuf *n;
668
669         KASSERT(m->m_type != MT_FREE, ("freeing free mbuf %p", m));
670         --mbtypes[m->m_type];
671
672         n = m->m_next;
673
674         /*
675          * Make sure the mbuf is in constructed state before returning it
676          * to the objcache.
677          */
678         m->m_next = NULL;
679 #ifdef notyet
680         KKASSERT(m->m_nextpkt == NULL);
681 #else
682         if (m->m_nextpkt != NULL) {
683 #ifdef DDB
684                 static int afewtimes = 10;
685
686                 if (afewtimes-- > 0) {
687                         printf("mfree: m->m_nextpkt != NULL\n");
688                         db_print_backtrace();
689                 }
690 #endif
691                 m->m_nextpkt = NULL;
692         }
693 #endif
694         if (m->m_flags & M_PKTHDR) {
695                 m->m_pkthdr.rcvif = NULL;       /* eliminate XXX JH */
696                 m_tag_delete_chain(m);          /* eliminate XXX JH */
697                 m->m_pkthdr.csum_flags = 0;     /* eliminate XXX JH */
698                 m->m_pkthdr.fw_flags = 0;       /* eliminate XXX JH */
699         }
700         m->m_flags &= (M_PKTHDR | M_EXT | M_EXT_CLUSTER);
701
702         if (m->m_flags & M_EXT) {
703                 if (m_sharecount(m) > 1) {
704                         m->m_ext.ext_free(m->m_ext.ext_arg); 
705                         m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
706                         goto detachmbuf;
707                 }
708                 KKASSERT(((struct mbcluster *)m->m_ext.ext_arg)->mcl_refs == 1);
709                 m->m_data = m->m_ext.ext_buf;
710                 if (m->m_flags & M_PKTHDR)
711                         objcache_put(mbufphdrcluster_cache, m);
712                 else
713                         objcache_put(mbufcluster_cache, m);
714                 crit_enter();
715                 --mbstat.m_clusters;
716                 crit_exit();
717         } else {
718 detachmbuf:
719                 if (m->m_flags & M_PKTHDR) {
720                         m->m_data = m->m_pktdat;
721                         objcache_put(mbufphdr_cache, m);
722                 } else {
723                         m->m_data = m->m_dat;
724                         objcache_put(mbuf_cache, m);
725                 }
726                 crit_enter();
727                 --mbstat.m_mbufs;
728                 crit_exit();
729         }
730         return (n);
731 }
732
733 void
734 m_freem(struct mbuf *m)
735 {
736         crit_enter();
737         while (m)
738                 m = m_free(m);
739         crit_exit();
740 }
741
742 /*
743  * mbuf utility routines
744  */
745
746 /*
747  * Lesser-used path for M_PREPEND: allocate new mbuf to prepend to chain and
748  * copy junk along.
749  */
750 struct mbuf *
751 m_prepend(struct mbuf *m, int len, int how)
752 {
753         struct mbuf *mn;
754
755         mn = m_get(how, m->m_type);
756         if (mn == NULL) {
757                 m_freem(m);
758                 return (NULL);
759         }
760         if (m->m_flags & M_PKTHDR)
761                 M_MOVE_PKTHDR(mn, m);
762         mn->m_next = m;
763         m = mn;
764         if (len < MHLEN)
765                 MH_ALIGN(m, len);
766         m->m_len = len;
767         return (m);
768 }
769
770 /*
771  * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
772  * continuing for "len" bytes.  If len is M_COPYALL, copy to end of mbuf.
773  * The wait parameter is a choice of MB_WAIT/MB_DONTWAIT from caller.
774  * Note that the copy is read-only, because clusters are not copied,
775  * only their reference counts are incremented.
776  */
777 struct mbuf *
778 m_copym(const struct mbuf *m, int off0, int len, int wait)
779 {
780         struct mbuf *n, **np;
781         int off = off0;
782         struct mbuf *top;
783         int copyhdr = 0;
784
785         KASSERT(off >= 0, ("m_copym, negative off %d", off));
786         KASSERT(len >= 0, ("m_copym, negative len %d", len));
787         if (off == 0 && m->m_flags & M_PKTHDR)
788                 copyhdr = 1;
789         while (off > 0) {
790                 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
791                 if (off < m->m_len)
792                         break;
793                 off -= m->m_len;
794                 m = m->m_next;
795         }
796         np = &top;
797         top = 0;
798         while (len > 0) {
799                 if (m == NULL) {
800                         KASSERT(len == M_COPYALL, 
801                             ("m_copym, length > size of mbuf chain"));
802                         break;
803                 }
804                 n = m_get(wait, m->m_type);
805                 *np = n;
806                 if (n == NULL)
807                         goto nospace;
808                 if (copyhdr) {
809                         if (!m_dup_pkthdr(n, m, wait))
810                                 goto nospace;
811                         if (len == M_COPYALL)
812                                 n->m_pkthdr.len -= off0;
813                         else
814                                 n->m_pkthdr.len = len;
815                         copyhdr = 0;
816                 }
817                 n->m_len = min(len, m->m_len - off);
818                 if (m->m_flags & M_EXT) {
819                         n->m_data = m->m_data + off;
820                         m->m_ext.ext_ref(m->m_ext.ext_arg); 
821                         n->m_ext = m->m_ext;
822                         n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
823                 } else {
824                         bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
825                             (unsigned)n->m_len);
826                 }
827                 if (len != M_COPYALL)
828                         len -= n->m_len;
829                 off = 0;
830                 m = m->m_next;
831                 np = &n->m_next;
832         }
833         if (top == NULL)
834                 mbstat.m_mcfail++;
835         return (top);
836 nospace:
837         m_freem(top);
838         mbstat.m_mcfail++;
839         return (NULL);
840 }
841
842 /*
843  * Copy an entire packet, including header (which must be present).
844  * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
845  * Note that the copy is read-only, because clusters are not copied,
846  * only their reference counts are incremented.
847  * Preserve alignment of the first mbuf so if the creator has left
848  * some room at the beginning (e.g. for inserting protocol headers)
849  * the copies also have the room available.
850  */
851 struct mbuf *
852 m_copypacket(struct mbuf *m, int how)
853 {
854         struct mbuf *top, *n, *o;
855
856         n = m_get(how, m->m_type);
857         top = n;
858         if (!n)
859                 goto nospace;
860
861         if (!m_dup_pkthdr(n, m, how))
862                 goto nospace;
863         n->m_len = m->m_len;
864         if (m->m_flags & M_EXT) {
865                 n->m_data = m->m_data;
866                 m->m_ext.ext_ref(m->m_ext.ext_arg); 
867                 n->m_ext = m->m_ext;
868                 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
869         } else {
870                 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
871                 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
872         }
873
874         m = m->m_next;
875         while (m) {
876                 o = m_get(how, m->m_type);
877                 if (!o)
878                         goto nospace;
879
880                 n->m_next = o;
881                 n = n->m_next;
882
883                 n->m_len = m->m_len;
884                 if (m->m_flags & M_EXT) {
885                         n->m_data = m->m_data;
886                         m->m_ext.ext_ref(m->m_ext.ext_arg); 
887                         n->m_ext = m->m_ext;
888                         n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
889                 } else {
890                         bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
891                 }
892
893                 m = m->m_next;
894         }
895         return top;
896 nospace:
897         m_freem(top);
898         mbstat.m_mcfail++;
899         return (NULL);
900 }
901
902 /*
903  * Copy data from an mbuf chain starting "off" bytes from the beginning,
904  * continuing for "len" bytes, into the indicated buffer.
905  */
906 void
907 m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
908 {
909         unsigned count;
910
911         KASSERT(off >= 0, ("m_copydata, negative off %d", off));
912         KASSERT(len >= 0, ("m_copydata, negative len %d", len));
913         while (off > 0) {
914                 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
915                 if (off < m->m_len)
916                         break;
917                 off -= m->m_len;
918                 m = m->m_next;
919         }
920         while (len > 0) {
921                 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
922                 count = min(m->m_len - off, len);
923                 bcopy(mtod(m, caddr_t) + off, cp, count);
924                 len -= count;
925                 cp += count;
926                 off = 0;
927                 m = m->m_next;
928         }
929 }
930
931 /*
932  * Copy a packet header mbuf chain into a completely new chain, including
933  * copying any mbuf clusters.  Use this instead of m_copypacket() when
934  * you need a writable copy of an mbuf chain.
935  */
936 struct mbuf *
937 m_dup(struct mbuf *m, int how)
938 {
939         struct mbuf **p, *top = NULL;
940         int remain, moff, nsize;
941
942         /* Sanity check */
943         if (m == NULL)
944                 return (NULL);
945         KASSERT((m->m_flags & M_PKTHDR) != 0, ("%s: !PKTHDR", __func__));
946
947         /* While there's more data, get a new mbuf, tack it on, and fill it */
948         remain = m->m_pkthdr.len;
949         moff = 0;
950         p = &top;
951         while (remain > 0 || top == NULL) {     /* allow m->m_pkthdr.len == 0 */
952                 struct mbuf *n;
953
954                 /* Get the next new mbuf */
955                 n = m_getl(remain, how, m->m_type, top == NULL ? M_PKTHDR : 0,
956                            &nsize);
957                 if (n == NULL)
958                         goto nospace;
959                 if (top == NULL)
960                         if (!m_dup_pkthdr(n, m, how))
961                                 goto nospace0;
962
963                 /* Link it into the new chain */
964                 *p = n;
965                 p = &n->m_next;
966
967                 /* Copy data from original mbuf(s) into new mbuf */
968                 n->m_len = 0;
969                 while (n->m_len < nsize && m != NULL) {
970                         int chunk = min(nsize - n->m_len, m->m_len - moff);
971
972                         bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
973                         moff += chunk;
974                         n->m_len += chunk;
975                         remain -= chunk;
976                         if (moff == m->m_len) {
977                                 m = m->m_next;
978                                 moff = 0;
979                         }
980                 }
981
982                 /* Check correct total mbuf length */
983                 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
984                         ("%s: bogus m_pkthdr.len", __func__));
985         }
986         return (top);
987
988 nospace:
989         m_freem(top);
990 nospace0:
991         mbstat.m_mcfail++;
992         return (NULL);
993 }
994
995 /*
996  * Concatenate mbuf chain n to m.
997  * Both chains must be of the same type (e.g. MT_DATA).
998  * Any m_pkthdr is not updated.
999  */
1000 void
1001 m_cat(struct mbuf *m, struct mbuf *n)
1002 {
1003         m = m_last(m);
1004         while (n) {
1005                 if (m->m_flags & M_EXT ||
1006                     m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
1007                         /* just join the two chains */
1008                         m->m_next = n;
1009                         return;
1010                 }
1011                 /* splat the data from one into the other */
1012                 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1013                     (u_int)n->m_len);
1014                 m->m_len += n->m_len;
1015                 n = m_free(n);
1016         }
1017 }
1018
1019 void
1020 m_adj(struct mbuf *mp, int req_len)
1021 {
1022         int len = req_len;
1023         struct mbuf *m;
1024         int count;
1025
1026         if ((m = mp) == NULL)
1027                 return;
1028         if (len >= 0) {
1029                 /*
1030                  * Trim from head.
1031                  */
1032                 while (m != NULL && len > 0) {
1033                         if (m->m_len <= len) {
1034                                 len -= m->m_len;
1035                                 m->m_len = 0;
1036                                 m = m->m_next;
1037                         } else {
1038                                 m->m_len -= len;
1039                                 m->m_data += len;
1040                                 len = 0;
1041                         }
1042                 }
1043                 m = mp;
1044                 if (mp->m_flags & M_PKTHDR)
1045                         m->m_pkthdr.len -= (req_len - len);
1046         } else {
1047                 /*
1048                  * Trim from tail.  Scan the mbuf chain,
1049                  * calculating its length and finding the last mbuf.
1050                  * If the adjustment only affects this mbuf, then just
1051                  * adjust and return.  Otherwise, rescan and truncate
1052                  * after the remaining size.
1053                  */
1054                 len = -len;
1055                 count = 0;
1056                 for (;;) {
1057                         count += m->m_len;
1058                         if (m->m_next == (struct mbuf *)0)
1059                                 break;
1060                         m = m->m_next;
1061                 }
1062                 if (m->m_len >= len) {
1063                         m->m_len -= len;
1064                         if (mp->m_flags & M_PKTHDR)
1065                                 mp->m_pkthdr.len -= len;
1066                         return;
1067                 }
1068                 count -= len;
1069                 if (count < 0)
1070                         count = 0;
1071                 /*
1072                  * Correct length for chain is "count".
1073                  * Find the mbuf with last data, adjust its length,
1074                  * and toss data from remaining mbufs on chain.
1075                  */
1076                 m = mp;
1077                 if (m->m_flags & M_PKTHDR)
1078                         m->m_pkthdr.len = count;
1079                 for (; m; m = m->m_next) {
1080                         if (m->m_len >= count) {
1081                                 m->m_len = count;
1082                                 break;
1083                         }
1084                         count -= m->m_len;
1085                 }
1086                 while (m->m_next)
1087                         (m = m->m_next) ->m_len = 0;
1088         }
1089 }
1090
1091 /*
1092  * Rearrange an mbuf chain so that len bytes are contiguous
1093  * and in the data area of an mbuf (so that mtod will work for a structure
1094  * of size len).  Returns the resulting mbuf chain on success, frees it and
1095  * returns null on failure.  If there is room, it will add up to
1096  * max_protohdr-len extra bytes to the contiguous region in an attempt to
1097  * avoid being called next time.
1098  */
1099 struct mbuf *
1100 m_pullup(struct mbuf *n, int len)
1101 {
1102         struct mbuf *m;
1103         int count;
1104         int space;
1105
1106         /*
1107          * If first mbuf has no cluster, and has room for len bytes
1108          * without shifting current data, pullup into it,
1109          * otherwise allocate a new mbuf to prepend to the chain.
1110          */
1111         if (!(n->m_flags & M_EXT) &&
1112             n->m_data + len < &n->m_dat[MLEN] &&
1113             n->m_next) {
1114                 if (n->m_len >= len)
1115                         return (n);
1116                 m = n;
1117                 n = n->m_next;
1118                 len -= m->m_len;
1119         } else {
1120                 if (len > MHLEN)
1121                         goto bad;
1122                 m = m_get(MB_DONTWAIT, n->m_type);
1123                 if (m == NULL)
1124                         goto bad;
1125                 m->m_len = 0;
1126                 if (n->m_flags & M_PKTHDR)
1127                         M_MOVE_PKTHDR(m, n);
1128         }
1129         space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1130         do {
1131                 count = min(min(max(len, max_protohdr), space), n->m_len);
1132                 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1133                   (unsigned)count);
1134                 len -= count;
1135                 m->m_len += count;
1136                 n->m_len -= count;
1137                 space -= count;
1138                 if (n->m_len)
1139                         n->m_data += count;
1140                 else
1141                         n = m_free(n);
1142         } while (len > 0 && n);
1143         if (len > 0) {
1144                 m_free(m);
1145                 goto bad;
1146         }
1147         m->m_next = n;
1148         return (m);
1149 bad:
1150         m_freem(n);
1151         mbstat.m_mpfail++;
1152         return (NULL);
1153 }
1154
1155 /*
1156  * Partition an mbuf chain in two pieces, returning the tail --
1157  * all but the first len0 bytes.  In case of failure, it returns NULL and
1158  * attempts to restore the chain to its original state.
1159  *
1160  * Note that the resulting mbufs might be read-only, because the new
1161  * mbuf can end up sharing an mbuf cluster with the original mbuf if
1162  * the "breaking point" happens to lie within a cluster mbuf. Use the
1163  * M_WRITABLE() macro to check for this case.
1164  */
1165 struct mbuf *
1166 m_split(struct mbuf *m0, int len0, int wait)
1167 {
1168         struct mbuf *m, *n;
1169         unsigned len = len0, remain;
1170
1171         for (m = m0; m && len > m->m_len; m = m->m_next)
1172                 len -= m->m_len;
1173         if (m == NULL)
1174                 return (NULL);
1175         remain = m->m_len - len;
1176         if (m0->m_flags & M_PKTHDR) {
1177                 n = m_gethdr(wait, m0->m_type);
1178                 if (n == NULL)
1179                         return (NULL);
1180                 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1181                 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1182                 m0->m_pkthdr.len = len0;
1183                 if (m->m_flags & M_EXT)
1184                         goto extpacket;
1185                 if (remain > MHLEN) {
1186                         /* m can't be the lead packet */
1187                         MH_ALIGN(n, 0);
1188                         n->m_next = m_split(m, len, wait);
1189                         if (n->m_next == NULL) {
1190                                 m_free(n);
1191                                 return (NULL);
1192                         } else {
1193                                 n->m_len = 0;
1194                                 return (n);
1195                         }
1196                 } else
1197                         MH_ALIGN(n, remain);
1198         } else if (remain == 0) {
1199                 n = m->m_next;
1200                 m->m_next = 0;
1201                 return (n);
1202         } else {
1203                 n = m_get(wait, m->m_type);
1204                 if (n == NULL)
1205                         return (NULL);
1206                 M_ALIGN(n, remain);
1207         }
1208 extpacket:
1209         if (m->m_flags & M_EXT) {
1210                 n->m_data = m->m_data + len;
1211                 m->m_ext.ext_ref(m->m_ext.ext_arg); 
1212                 n->m_ext = m->m_ext;
1213                 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1214         } else {
1215                 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1216         }
1217         n->m_len = remain;
1218         m->m_len = len;
1219         n->m_next = m->m_next;
1220         m->m_next = 0;
1221         return (n);
1222 }
1223
1224 /*
1225  * Routine to copy from device local memory into mbufs.
1226  * Note: "offset" is ill-defined and always called as 0, so ignore it.
1227  */
1228 struct mbuf *
1229 m_devget(char *buf, int len, int offset, struct ifnet *ifp,
1230     void (*copy)(volatile const void *from, volatile void *to, size_t length))
1231 {
1232         struct mbuf *m, *mfirst = NULL, **mtail;
1233         int nsize, flags;
1234
1235         if (copy == NULL)
1236                 copy = bcopy;
1237         mtail = &mfirst;
1238         flags = M_PKTHDR;
1239
1240         while (len > 0) {
1241                 m = m_getl(len, MB_DONTWAIT, MT_DATA, flags, &nsize);
1242                 if (m == NULL) {
1243                         m_freem(mfirst);
1244                         return (NULL);
1245                 }
1246                 m->m_len = min(len, nsize);
1247
1248                 if (flags & M_PKTHDR) {
1249                         if (len + max_linkhdr <= nsize)
1250                                 m->m_data += max_linkhdr;
1251                         m->m_pkthdr.rcvif = ifp;
1252                         m->m_pkthdr.len = len;
1253                         flags = 0;
1254                 }
1255
1256                 copy(buf, m->m_data, (unsigned)m->m_len);
1257                 buf += m->m_len;
1258                 len -= m->m_len;
1259                 *mtail = m;
1260                 mtail = &m->m_next;
1261         }
1262
1263         return (mfirst);
1264 }
1265
1266 /*
1267  * Copy data from a buffer back into the indicated mbuf chain,
1268  * starting "off" bytes from the beginning, extending the mbuf
1269  * chain if necessary.
1270  */
1271 void
1272 m_copyback(struct mbuf *m0, int off, int len, caddr_t cp)
1273 {
1274         int mlen;
1275         struct mbuf *m = m0, *n;
1276         int totlen = 0;
1277
1278         if (m0 == NULL)
1279                 return;
1280         while (off > (mlen = m->m_len)) {
1281                 off -= mlen;
1282                 totlen += mlen;
1283                 if (m->m_next == NULL) {
1284                         n = m_getclr(MB_DONTWAIT, m->m_type);
1285                         if (n == NULL)
1286                                 goto out;
1287                         n->m_len = min(MLEN, len + off);
1288                         m->m_next = n;
1289                 }
1290                 m = m->m_next;
1291         }
1292         while (len > 0) {
1293                 mlen = min (m->m_len - off, len);
1294                 bcopy(cp, off + mtod(m, caddr_t), (unsigned)mlen);
1295                 cp += mlen;
1296                 len -= mlen;
1297                 mlen += off;
1298                 off = 0;
1299                 totlen += mlen;
1300                 if (len == 0)
1301                         break;
1302                 if (m->m_next == NULL) {
1303                         n = m_get(MB_DONTWAIT, m->m_type);
1304                         if (n == NULL)
1305                                 break;
1306                         n->m_len = min(MLEN, len);
1307                         m->m_next = n;
1308                 }
1309                 m = m->m_next;
1310         }
1311 out:    if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1312                 m->m_pkthdr.len = totlen;
1313 }
1314
1315 void
1316 m_print(const struct mbuf *m)
1317 {
1318         int len;
1319         const struct mbuf *m2;
1320
1321         len = m->m_pkthdr.len;
1322         m2 = m;
1323         while (len) {
1324                 printf("%p %*D\n", m2, m2->m_len, (u_char *)m2->m_data, "-");
1325                 len -= m2->m_len;
1326                 m2 = m2->m_next;
1327         }
1328         return;
1329 }
1330
1331 /*
1332  * "Move" mbuf pkthdr from "from" to "to".
1333  * "from" must have M_PKTHDR set, and "to" must be empty.
1334  */
1335 void
1336 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
1337 {
1338         KASSERT(!(to->m_flags & M_EXT), ("m_move_pkthdr: to has cluster"));
1339
1340         to->m_flags = from->m_flags & M_COPYFLAGS;
1341         to->m_data = to->m_pktdat;
1342         to->m_pkthdr = from->m_pkthdr;          /* especially tags */
1343         SLIST_INIT(&from->m_pkthdr.tags);       /* purge tags from src */
1344         from->m_flags &= ~M_PKTHDR;
1345 }
1346
1347 /*
1348  * Duplicate "from"'s mbuf pkthdr in "to".
1349  * "from" must have M_PKTHDR set, and "to" must be empty.
1350  * In particular, this does a deep copy of the packet tags.
1351  */
1352 int
1353 m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
1354 {
1355         to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
1356         if (!(to->m_flags & M_EXT))
1357                 to->m_data = to->m_pktdat;
1358         to->m_pkthdr = from->m_pkthdr;
1359         SLIST_INIT(&to->m_pkthdr.tags);
1360         return (m_tag_copy_chain(to, from, how));
1361 }
1362
1363 /*
1364  * Defragment a mbuf chain, returning the shortest possible
1365  * chain of mbufs and clusters.  If allocation fails and
1366  * this cannot be completed, NULL will be returned, but
1367  * the passed in chain will be unchanged.  Upon success,
1368  * the original chain will be freed, and the new chain
1369  * will be returned.
1370  *
1371  * If a non-packet header is passed in, the original
1372  * mbuf (chain?) will be returned unharmed.
1373  *
1374  * m_defrag_nofree doesn't free the passed in mbuf.
1375  */
1376 struct mbuf *
1377 m_defrag(struct mbuf *m0, int how)
1378 {
1379         struct mbuf *m_new;
1380
1381         if ((m_new = m_defrag_nofree(m0, how)) == NULL)
1382                 return (NULL);
1383         if (m_new != m0)
1384                 m_freem(m0);
1385         return (m_new);
1386 }
1387
1388 struct mbuf *
1389 m_defrag_nofree(struct mbuf *m0, int how)
1390 {
1391         struct mbuf     *m_new = NULL, *m_final = NULL;
1392         int             progress = 0, length, nsize;
1393
1394         if (!(m0->m_flags & M_PKTHDR))
1395                 return (m0);
1396
1397 #ifdef MBUF_STRESS_TEST
1398         if (m_defragrandomfailures) {
1399                 int temp = arc4random() & 0xff;
1400                 if (temp == 0xba)
1401                         goto nospace;
1402         }
1403 #endif
1404         
1405         m_final = m_getl(m0->m_pkthdr.len, how, MT_DATA, M_PKTHDR, &nsize);
1406         if (m_final == NULL)
1407                 goto nospace;
1408         m_final->m_len = 0;     /* in case m0->m_pkthdr.len is zero */
1409
1410         if (m_dup_pkthdr(m_final, m0, how) == NULL)
1411                 goto nospace;
1412
1413         m_new = m_final;
1414
1415         while (progress < m0->m_pkthdr.len) {
1416                 length = m0->m_pkthdr.len - progress;
1417                 if (length > MCLBYTES)
1418                         length = MCLBYTES;
1419
1420                 if (m_new == NULL) {
1421                         m_new = m_getl(length, how, MT_DATA, 0, &nsize);
1422                         if (m_new == NULL)
1423                                 goto nospace;
1424                 }
1425
1426                 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1427                 progress += length;
1428                 m_new->m_len = length;
1429                 if (m_new != m_final)
1430                         m_cat(m_final, m_new);
1431                 m_new = NULL;
1432         }
1433         if (m0->m_next == NULL)
1434                 m_defraguseless++;
1435         m_defragpackets++;
1436         m_defragbytes += m_final->m_pkthdr.len;
1437         return (m_final);
1438 nospace:
1439         m_defragfailure++;
1440         if (m_new)
1441                 m_free(m_new);
1442         m_freem(m_final);
1443         return (NULL);
1444 }
1445
1446 /*
1447  * Move data from uio into mbufs.
1448  */
1449 struct mbuf *
1450 m_uiomove(struct uio *uio)
1451 {
1452         struct mbuf *m;                 /* current working mbuf */
1453         struct mbuf *head = NULL;       /* result mbuf chain */
1454         struct mbuf **mp = &head;
1455         int resid = uio->uio_resid, nsize, flags = M_PKTHDR, error;
1456
1457         do {
1458                 m = m_getl(resid, MB_WAIT, MT_DATA, flags, &nsize);
1459                 if (flags) {
1460                         m->m_pkthdr.len = 0;
1461                         /* Leave room for protocol headers. */
1462                         if (resid < MHLEN)
1463                                 MH_ALIGN(m, resid);
1464                         flags = 0;
1465                 }
1466                 m->m_len = min(nsize, resid);
1467                 error = uiomove(mtod(m, caddr_t), m->m_len, uio);
1468                 if (error) {
1469                         m_free(m);
1470                         goto failed;
1471                 }
1472                 *mp = m;
1473                 mp = &m->m_next;
1474                 head->m_pkthdr.len += m->m_len;
1475                 resid -= m->m_len;
1476         } while (resid > 0);
1477
1478         return (head);
1479
1480 failed:
1481         m_freem(head);
1482         return (NULL);
1483 }
1484
1485 struct mbuf *
1486 m_last(struct mbuf *m)
1487 {
1488         while (m->m_next)
1489                 m = m->m_next;
1490         return (m);
1491 }
1492
1493 /*
1494  * Return the number of bytes in an mbuf chain.
1495  * If lastm is not NULL, also return the last mbuf.
1496  */
1497 u_int
1498 m_lengthm(struct mbuf *m, struct mbuf **lastm)
1499 {
1500         u_int len = 0;
1501         struct mbuf *prev = m;
1502
1503         while (m) {
1504                 len += m->m_len;
1505                 prev = m;
1506                 m = m->m_next;
1507         }
1508         if (lastm != NULL)
1509                 *lastm = prev;
1510         return (len);
1511 }
1512
1513 /*
1514  * Like m_lengthm(), except also keep track of mbuf usage.
1515  */
1516 u_int
1517 m_countm(struct mbuf *m, struct mbuf **lastm, u_int *pmbcnt)
1518 {
1519         u_int len = 0, mbcnt = 0;
1520         struct mbuf *prev = m;
1521
1522         while (m) {
1523                 len += m->m_len;
1524                 mbcnt += MSIZE;
1525                 if (m->m_flags & M_EXT)
1526                         mbcnt += m->m_ext.ext_size;
1527                 prev = m;
1528                 m = m->m_next;
1529         }
1530         if (lastm != NULL)
1531                 *lastm = prev;
1532         *pmbcnt = mbcnt;
1533         return (len);
1534 }