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