]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/sys/mbuf.h
Import driver source from hyperv-20130627 vendor branch.
[FreeBSD/FreeBSD.git] / sys / sys / mbuf.h
1 /*-
2  * Copyright (c) 1982, 1986, 1988, 1993
3  *      The Regents of the University of California.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. Neither the name of the University nor the names of its contributors
15  *    may be used to endorse or promote products derived from this software
16  *    without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  *      @(#)mbuf.h      8.5 (Berkeley) 2/19/95
31  * $FreeBSD$
32  */
33
34 #ifndef _SYS_MBUF_H_
35 #define _SYS_MBUF_H_
36
37 /* XXX: These includes suck. Sorry! */
38 #include <sys/queue.h>
39 #ifdef _KERNEL
40 #include <sys/systm.h>
41 #include <vm/uma.h>
42 #ifdef WITNESS
43 #include <sys/lock.h>
44 #endif
45 #endif
46
47 /*
48  * Mbufs are of a single size, MSIZE (sys/param.h), which includes overhead.
49  * An mbuf may add a single "mbuf cluster" of size MCLBYTES (also in
50  * sys/param.h), which has no additional overhead and is used instead of the
51  * internal data area; this is done when at least MINCLSIZE of data must be
52  * stored.  Additionally, it is possible to allocate a separate buffer
53  * externally and attach it to the mbuf in a way similar to that of mbuf
54  * clusters.
55  *
56  * MLEN is data length in a normal mbuf.
57  * MHLEN is data length in an mbuf with pktheader.
58  * MINCLSIZE is a smallest amount of data that should be put into cluster.
59  */
60 #define MLEN            ((int)(MSIZE - sizeof(struct m_hdr)))
61 #define MHLEN           ((int)(MLEN - sizeof(struct pkthdr)))
62 #define MINCLSIZE       (MHLEN + 1)
63
64 #ifdef _KERNEL
65 /*-
66  * Macro for type conversion: convert mbuf pointer to data pointer of correct
67  * type:
68  *
69  * mtod(m, t)   -- Convert mbuf pointer to data pointer of correct type.
70  */
71 #define mtod(m, t)      ((t)((m)->m_data))
72
73 /*
74  * Argument structure passed to UMA routines during mbuf and packet
75  * allocations.
76  */
77 struct mb_args {
78         int     flags;  /* Flags for mbuf being allocated */
79         short   type;   /* Type of mbuf being allocated */
80 };
81 #endif /* _KERNEL */
82
83 #if defined(__LP64__)
84 #define M_HDR_PAD    6
85 #else
86 #define M_HDR_PAD    2
87 #endif
88
89 /*
90  * Header present at the beginning of every mbuf.
91  */
92 struct m_hdr {
93         struct mbuf     *mh_next;       /* next buffer in chain */
94         struct mbuf     *mh_nextpkt;    /* next chain in queue/record */
95         caddr_t          mh_data;       /* location of data */
96         int              mh_len;        /* amount of data in this mbuf */
97         int              mh_flags;      /* flags; see below */
98         short            mh_type;       /* type of data in this mbuf */
99         uint8_t          pad[M_HDR_PAD];/* word align                  */
100 };
101
102 /*
103  * Packet tag structure (see below for details).
104  */
105 struct m_tag {
106         SLIST_ENTRY(m_tag)      m_tag_link;     /* List of packet tags */
107         u_int16_t               m_tag_id;       /* Tag ID */
108         u_int16_t               m_tag_len;      /* Length of data */
109         u_int32_t               m_tag_cookie;   /* ABI/Module ID */
110         void                    (*m_tag_free)(struct m_tag *);
111 };
112
113 /*
114  * Record/packet header in first mbuf of chain; valid only if M_PKTHDR is set.
115  */
116 struct pkthdr {
117         struct ifnet    *rcvif;         /* rcv interface */
118         /* variables for ip and tcp reassembly */
119         void            *header;        /* pointer to packet header */
120         int              len;           /* total packet length */
121         uint32_t         flowid;        /* packet's 4-tuple system
122                                          * flow identifier
123                                          */
124         /* variables for hardware checksum */
125         int              csum_flags;    /* flags regarding checksum */
126         int              csum_data;     /* data field used by csum routines */
127         u_int16_t        tso_segsz;     /* TSO segment size */
128         union {
129                 u_int16_t vt_vtag;      /* Ethernet 802.1p+q vlan tag */
130                 u_int16_t vt_nrecs;     /* # of IGMPv3 records in this chain */
131         } PH_vt;
132         u_int16_t        fibnum;        /* this packet should use this fib */
133         u_int16_t        pad2;          /* align to 32 bits */
134         SLIST_HEAD(packet_tags, m_tag) tags; /* list of packet tags */
135 };
136 #define ether_vtag      PH_vt.vt_vtag
137
138 /*
139  * Description of external storage mapped into mbuf; valid only if M_EXT is
140  * set.
141  */
142 struct m_ext {
143         caddr_t          ext_buf;       /* start of buffer */
144         void            (*ext_free)     /* free routine if not the usual */
145                             (void *, void *);
146         void            *ext_arg1;      /* optional argument pointer */
147         void            *ext_arg2;      /* optional argument pointer */
148         u_int            ext_size;      /* size of buffer, for ext_free */
149         volatile u_int  *ref_cnt;       /* pointer to ref count info */
150         int              ext_type;      /* type of external storage */
151 };
152
153 /*
154  * The core of the mbuf object along with some shortcut defines for practical
155  * purposes.
156  */
157 struct mbuf {
158         struct m_hdr    m_hdr;
159         union {
160                 struct {
161                         struct pkthdr   MH_pkthdr;      /* M_PKTHDR set */
162                         union {
163                                 struct m_ext    MH_ext; /* M_EXT set */
164                                 char            MH_databuf[MHLEN];
165                         } MH_dat;
166                 } MH;
167                 char    M_databuf[MLEN];                /* !M_PKTHDR, !M_EXT */
168         } M_dat;
169 };
170 #define m_next          m_hdr.mh_next
171 #define m_len           m_hdr.mh_len
172 #define m_data          m_hdr.mh_data
173 #define m_type          m_hdr.mh_type
174 #define m_flags         m_hdr.mh_flags
175 #define m_nextpkt       m_hdr.mh_nextpkt
176 #define m_act           m_nextpkt
177 #define m_pkthdr        M_dat.MH.MH_pkthdr
178 #define m_ext           M_dat.MH.MH_dat.MH_ext
179 #define m_pktdat        M_dat.MH.MH_dat.MH_databuf
180 #define m_dat           M_dat.M_databuf
181
182 /*
183  * mbuf flags.
184  */
185 #define M_EXT           0x00000001 /* has associated external storage */
186 #define M_PKTHDR        0x00000002 /* start of record */
187 #define M_EOR           0x00000004 /* end of record */
188 #define M_RDONLY        0x00000008 /* associated data is marked read-only */
189 #define M_PROTO1        0x00000010 /* protocol-specific */
190 #define M_PROTO2        0x00000020 /* protocol-specific */
191 #define M_PROTO3        0x00000040 /* protocol-specific */
192 #define M_PROTO4        0x00000080 /* protocol-specific */
193 #define M_PROTO5        0x00000100 /* protocol-specific */
194 #define M_BCAST         0x00000200 /* send/received as link-level broadcast */
195 #define M_MCAST         0x00000400 /* send/received as link-level multicast */
196 #define M_FRAG          0x00000800 /* packet is a fragment of a larger packet */
197 #define M_FIRSTFRAG     0x00001000 /* packet is first fragment */
198 #define M_LASTFRAG      0x00002000 /* packet is last fragment */
199 #define M_SKIP_FIREWALL 0x00004000 /* skip firewall processing */
200                      /* 0x00008000    free */
201 #define M_VLANTAG       0x00010000 /* ether_vtag is valid */
202 #define M_PROMISC       0x00020000 /* packet was not for us */
203 #define M_NOFREE        0x00040000 /* do not free mbuf, embedded in cluster */
204 #define M_PROTO6        0x00080000 /* protocol-specific */
205 #define M_PROTO7        0x00100000 /* protocol-specific */
206 #define M_PROTO8        0x00200000 /* protocol-specific */
207 #define M_FLOWID        0x00400000 /* deprecated: flowid is valid */
208 #define M_HASHTYPEBITS  0x0F000000 /* mask of bits holding flowid hash type */
209
210 #define M_NOTIFICATION  M_PROTO5    /* SCTP notification */
211
212 /*
213  * Flags to purge when crossing layers.
214  */
215 #define M_PROTOFLAGS \
216     (M_PROTO1|M_PROTO2|M_PROTO3|M_PROTO4|M_PROTO5|M_PROTO6|M_PROTO7|M_PROTO8)
217
218 /*
219  * Network interface cards are able to hash protocol fields (such as IPv4
220  * addresses and TCP port numbers) classify packets into flows.  These flows
221  * can then be used to maintain ordering while delivering packets to the OS
222  * via parallel input queues, as well as to provide a stateless affinity
223  * model.  NIC drivers can pass up the hash via m->m_pkthdr.flowid, and set
224  * m_flag fields to indicate how the hash should be interpreted by the
225  * network stack.
226  *
227  * Most NICs support RSS, which provides ordering and explicit affinity, and
228  * use the hash m_flag bits to indicate what header fields were covered by
229  * the hash.  M_HASHTYPE_OPAQUE can be set by non-RSS cards or configurations
230  * that provide an opaque flow identifier, allowing for ordering and
231  * distribution without explicit affinity.
232  */
233 #define M_HASHTYPE_SHIFT                24
234 #define M_HASHTYPE_NONE                 0x0
235 #define M_HASHTYPE_RSS_IPV4             0x1     /* IPv4 2-tuple */
236 #define M_HASHTYPE_RSS_TCP_IPV4         0x2     /* TCPv4 4-tuple */
237 #define M_HASHTYPE_RSS_IPV6             0x3     /* IPv6 2-tuple */
238 #define M_HASHTYPE_RSS_TCP_IPV6         0x4     /* TCPv6 4-tuple */
239 #define M_HASHTYPE_RSS_IPV6_EX          0x5     /* IPv6 2-tuple + ext hdrs */
240 #define M_HASHTYPE_RSS_TCP_IPV6_EX      0x6     /* TCPv6 4-tiple + ext hdrs */
241 #define M_HASHTYPE_OPAQUE               0xf     /* ordering, not affinity */
242
243 #define M_HASHTYPE_CLEAR(m)     (m)->m_flags &= ~(M_HASHTYPEBITS)
244 #define M_HASHTYPE_GET(m)       (((m)->m_flags & M_HASHTYPEBITS) >> \
245                                     M_HASHTYPE_SHIFT)
246 #define M_HASHTYPE_SET(m, v)    do {                                    \
247         (m)->m_flags &= ~M_HASHTYPEBITS;                                \
248         (m)->m_flags |= ((v) << M_HASHTYPE_SHIFT);                      \
249 } while (0)
250 #define M_HASHTYPE_TEST(m, v)   (M_HASHTYPE_GET(m) == (v))
251
252 /*
253  * Flags preserved when copying m_pkthdr.
254  */
255 #define M_COPYFLAGS \
256     (M_PKTHDR|M_EOR|M_RDONLY|M_PROTOFLAGS|M_SKIP_FIREWALL|M_BCAST|M_MCAST|\
257      M_FRAG|M_FIRSTFRAG|M_LASTFRAG|M_VLANTAG|M_PROMISC|M_HASHTYPEBITS)
258
259 /*
260  * External buffer types: identify ext_buf type.
261  */
262 #define EXT_CLUSTER     1       /* mbuf cluster */
263 #define EXT_SFBUF       2       /* sendfile(2)'s sf_bufs */
264 #define EXT_JUMBOP      3       /* jumbo cluster 4096 bytes */
265 #define EXT_JUMBO9      4       /* jumbo cluster 9216 bytes */
266 #define EXT_JUMBO16     5       /* jumbo cluster 16184 bytes */
267 #define EXT_PACKET      6       /* mbuf+cluster from packet zone */
268 #define EXT_MBUF        7       /* external mbuf reference (M_IOVEC) */
269 #define EXT_NET_DRV     100     /* custom ext_buf provided by net driver(s) */
270 #define EXT_MOD_TYPE    200     /* custom module's ext_buf type */
271 #define EXT_DISPOSABLE  300     /* can throw this buffer away w/page flipping */
272 #define EXT_EXTREF      400     /* has externally maintained ref_cnt ptr */
273
274 /*
275  * Flags indicating hw checksum support and sw checksum requirements.  This
276  * field can be directly tested against if_data.ifi_hwassist.
277  */
278 #define CSUM_IP                 0x0001          /* will csum IP */
279 #define CSUM_TCP                0x0002          /* will csum TCP */
280 #define CSUM_UDP                0x0004          /* will csum UDP */
281 #define CSUM_FRAGMENT           0x0010          /* will do IP fragmentation */
282 #define CSUM_TSO                0x0020          /* will do TSO */
283 #define CSUM_SCTP               0x0040          /* will csum SCTP */
284 #define CSUM_SCTP_IPV6          0x0080          /* will csum IPv6/SCTP */
285
286 #define CSUM_IP_CHECKED         0x0100          /* did csum IP */
287 #define CSUM_IP_VALID           0x0200          /*   ... the csum is valid */
288 #define CSUM_DATA_VALID         0x0400          /* csum_data field is valid */
289 #define CSUM_PSEUDO_HDR         0x0800          /* csum_data has pseudo hdr */
290 #define CSUM_SCTP_VALID         0x1000          /* SCTP checksum is valid */
291 #define CSUM_UDP_IPV6           0x2000          /* will csum IPv6/UDP */
292 #define CSUM_TCP_IPV6           0x4000          /* will csum IPv6/TCP */
293 /*      CSUM_TSO_IPV6           0x8000          will do IPv6/TSO */
294
295 /*      CSUM_FRAGMENT_IPV6      0x10000         will do IPv6 fragementation */
296
297 #define CSUM_DELAY_DATA_IPV6    (CSUM_TCP_IPV6 | CSUM_UDP_IPV6)
298 #define CSUM_DATA_VALID_IPV6    CSUM_DATA_VALID
299
300 #define CSUM_DELAY_DATA         (CSUM_TCP | CSUM_UDP)
301 #define CSUM_DELAY_IP           (CSUM_IP)       /* Only v4, no v6 IP hdr csum */
302
303 /*
304  * mbuf types.
305  */
306 #define MT_NOTMBUF      0       /* USED INTERNALLY ONLY! Object is not mbuf */
307 #define MT_DATA         1       /* dynamic (data) allocation */
308 #define MT_HEADER       MT_DATA /* packet header, use M_PKTHDR instead */
309 #define MT_SONAME       8       /* socket name */
310 #define MT_CONTROL      14      /* extra-data protocol message */
311 #define MT_OOBDATA      15      /* expedited data  */
312 #define MT_NTYPES       16      /* number of mbuf types for mbtypes[] */
313
314 #define MT_NOINIT       255     /* Not a type but a flag to allocate
315                                    a non-initialized mbuf */
316
317 #define MB_NOTAGS       0x1UL   /* no tags attached to mbuf */
318
319 /*
320  * General mbuf allocator statistics structure.
321  *
322  * Many of these statistics are no longer used; we instead track many
323  * allocator statistics through UMA's built in statistics mechanism.
324  */
325 struct mbstat {
326         u_long  m_mbufs;        /* XXX */
327         u_long  m_mclusts;      /* XXX */
328
329         u_long  m_drain;        /* times drained protocols for space */
330         u_long  m_mcfail;       /* XXX: times m_copym failed */
331         u_long  m_mpfail;       /* XXX: times m_pullup failed */
332         u_long  m_msize;        /* length of an mbuf */
333         u_long  m_mclbytes;     /* length of an mbuf cluster */
334         u_long  m_minclsize;    /* min length of data to allocate a cluster */
335         u_long  m_mlen;         /* length of data in an mbuf */
336         u_long  m_mhlen;        /* length of data in a header mbuf */
337
338         /* Number of mbtypes (gives # elems in mbtypes[] array) */
339         short   m_numtypes;
340
341         /* XXX: Sendfile stats should eventually move to their own struct */
342         u_long  sf_iocnt;       /* times sendfile had to do disk I/O */
343         u_long  sf_allocfail;   /* times sfbuf allocation failed */
344         u_long  sf_allocwait;   /* times sfbuf allocation had to wait */
345 };
346
347 /*
348  * Compatibility with historic mbuf allocator.
349  */
350 #define MBTOM(how)      (how)
351 #define M_DONTWAIT      M_NOWAIT
352 #define M_TRYWAIT       M_WAITOK
353 #define M_WAIT          M_WAITOK
354
355 /*
356  * String names of mbuf-related UMA(9) and malloc(9) types.  Exposed to
357  * !_KERNEL so that monitoring tools can look up the zones with
358  * libmemstat(3).
359  */
360 #define MBUF_MEM_NAME           "mbuf"
361 #define MBUF_CLUSTER_MEM_NAME   "mbuf_cluster"
362 #define MBUF_PACKET_MEM_NAME    "mbuf_packet"
363 #define MBUF_JUMBOP_MEM_NAME    "mbuf_jumbo_page"
364 #define MBUF_JUMBO9_MEM_NAME    "mbuf_jumbo_9k"
365 #define MBUF_JUMBO16_MEM_NAME   "mbuf_jumbo_16k"
366 #define MBUF_TAG_MEM_NAME       "mbuf_tag"
367 #define MBUF_EXTREFCNT_MEM_NAME "mbuf_ext_refcnt"
368
369 #ifdef _KERNEL
370
371 #ifdef WITNESS
372 #define MBUF_CHECKSLEEP(how) do {                                       \
373         if (how == M_WAITOK)                                            \
374                 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,         \
375                     "Sleeping in \"%s\"", __func__);                    \
376 } while (0)
377 #else
378 #define MBUF_CHECKSLEEP(how)
379 #endif
380
381 /*
382  * Network buffer allocation API
383  *
384  * The rest of it is defined in kern/kern_mbuf.c
385  */
386 extern uma_zone_t       zone_mbuf;
387 extern uma_zone_t       zone_clust;
388 extern uma_zone_t       zone_pack;
389 extern uma_zone_t       zone_jumbop;
390 extern uma_zone_t       zone_jumbo9;
391 extern uma_zone_t       zone_jumbo16;
392 extern uma_zone_t       zone_ext_refcnt;
393
394 void             mb_free_ext(struct mbuf *);
395 int              m_pkthdr_init(struct mbuf *, int);
396
397 static __inline int
398 m_gettype(int size)
399 {
400         int type;
401
402         switch (size) {
403         case MSIZE:
404                 type = EXT_MBUF;
405                 break;
406         case MCLBYTES:
407                 type = EXT_CLUSTER;
408                 break;
409 #if MJUMPAGESIZE != MCLBYTES
410         case MJUMPAGESIZE:
411                 type = EXT_JUMBOP;
412                 break;
413 #endif
414         case MJUM9BYTES:
415                 type = EXT_JUMBO9;
416                 break;
417         case MJUM16BYTES:
418                 type = EXT_JUMBO16;
419                 break;
420         default:
421                 panic("%s: invalid cluster size", __func__);
422         }
423
424         return (type);
425 }
426
427 static __inline uma_zone_t
428 m_getzone(int size)
429 {
430         uma_zone_t zone;
431
432         switch (size) {
433         case MCLBYTES:
434                 zone = zone_clust;
435                 break;
436 #if MJUMPAGESIZE != MCLBYTES
437         case MJUMPAGESIZE:
438                 zone = zone_jumbop;
439                 break;
440 #endif
441         case MJUM9BYTES:
442                 zone = zone_jumbo9;
443                 break;
444         case MJUM16BYTES:
445                 zone = zone_jumbo16;
446                 break;
447         default:
448                 panic("%s: invalid cluster size", __func__);
449         }
450
451         return (zone);
452 }
453
454 /*
455  * Initialize an mbuf with linear storage.
456  *
457  * Inline because the consumer text overhead will be roughly the same to
458  * initialize or call a function with this many parameters and M_PKTHDR
459  * should go away with constant propagation for !MGETHDR.
460  */
461 static __inline int
462 m_init(struct mbuf *m, uma_zone_t zone, int size, int how, short type,
463     int flags)
464 {
465         int error;
466
467         m->m_next = NULL;
468         m->m_nextpkt = NULL;
469         m->m_data = m->m_dat;
470         m->m_len = 0;
471         m->m_flags = flags;
472         m->m_type = type;
473         if (flags & M_PKTHDR) {
474                 if ((error = m_pkthdr_init(m, how)) != 0)
475                         return (error);
476         }
477
478         return (0);
479 }
480
481 static __inline struct mbuf *
482 m_get(int how, short type)
483 {
484         struct mb_args args;
485
486         args.flags = 0;
487         args.type = type;
488         return (uma_zalloc_arg(zone_mbuf, &args, how));
489 }
490
491 /*
492  * XXX This should be deprecated, very little use.
493  */
494 static __inline struct mbuf *
495 m_getclr(int how, short type)
496 {
497         struct mbuf *m;
498         struct mb_args args;
499
500         args.flags = 0;
501         args.type = type;
502         m = uma_zalloc_arg(zone_mbuf, &args, how);
503         if (m != NULL)
504                 bzero(m->m_data, MLEN);
505         return (m);
506 }
507
508 static __inline struct mbuf *
509 m_gethdr(int how, short type)
510 {
511         struct mb_args args;
512
513         args.flags = M_PKTHDR;
514         args.type = type;
515         return (uma_zalloc_arg(zone_mbuf, &args, how));
516 }
517
518 static __inline struct mbuf *
519 m_getcl(int how, short type, int flags)
520 {
521         struct mb_args args;
522
523         args.flags = flags;
524         args.type = type;
525         return (uma_zalloc_arg(zone_pack, &args, how));
526 }
527
528 static __inline void
529 m_free_fast(struct mbuf *m)
530 {
531 #ifdef INVARIANTS
532         if (m->m_flags & M_PKTHDR)
533                 KASSERT(SLIST_EMPTY(&m->m_pkthdr.tags), ("doing fast free of mbuf with tags"));
534 #endif
535
536         uma_zfree_arg(zone_mbuf, m, (void *)MB_NOTAGS);
537 }
538
539 static __inline struct mbuf *
540 m_free(struct mbuf *m)
541 {
542         struct mbuf *n = m->m_next;
543
544         if (m->m_flags & M_EXT)
545                 mb_free_ext(m);
546         else if ((m->m_flags & M_NOFREE) == 0)
547                 uma_zfree(zone_mbuf, m);
548         return (n);
549 }
550
551 static __inline void
552 m_clget(struct mbuf *m, int how)
553 {
554
555         if (m->m_flags & M_EXT)
556                 printf("%s: %p mbuf already has cluster\n", __func__, m);
557         m->m_ext.ext_buf = (char *)NULL;
558         uma_zalloc_arg(zone_clust, m, how);
559         /*
560          * On a cluster allocation failure, drain the packet zone and retry,
561          * we might be able to loosen a few clusters up on the drain.
562          */
563         if ((how & M_NOWAIT) && (m->m_ext.ext_buf == NULL)) {
564                 zone_drain(zone_pack);
565                 uma_zalloc_arg(zone_clust, m, how);
566         }
567 }
568
569 /*
570  * m_cljget() is different from m_clget() as it can allocate clusters without
571  * attaching them to an mbuf.  In that case the return value is the pointer
572  * to the cluster of the requested size.  If an mbuf was specified, it gets
573  * the cluster attached to it and the return value can be safely ignored.
574  * For size it takes MCLBYTES, MJUMPAGESIZE, MJUM9BYTES, MJUM16BYTES.
575  */
576 static __inline void *
577 m_cljget(struct mbuf *m, int how, int size)
578 {
579         uma_zone_t zone;
580
581         if (m && m->m_flags & M_EXT)
582                 printf("%s: %p mbuf already has cluster\n", __func__, m);
583         if (m != NULL)
584                 m->m_ext.ext_buf = NULL;
585
586         zone = m_getzone(size);
587         return (uma_zalloc_arg(zone, m, how));
588 }
589
590 static __inline void
591 m_cljset(struct mbuf *m, void *cl, int type)
592 {
593         uma_zone_t zone;
594         int size;
595
596         switch (type) {
597         case EXT_CLUSTER:
598                 size = MCLBYTES;
599                 zone = zone_clust;
600                 break;
601 #if MJUMPAGESIZE != MCLBYTES
602         case EXT_JUMBOP:
603                 size = MJUMPAGESIZE;
604                 zone = zone_jumbop;
605                 break;
606 #endif
607         case EXT_JUMBO9:
608                 size = MJUM9BYTES;
609                 zone = zone_jumbo9;
610                 break;
611         case EXT_JUMBO16:
612                 size = MJUM16BYTES;
613                 zone = zone_jumbo16;
614                 break;
615         default:
616                 panic("%s: unknown cluster type", __func__);
617                 break;
618         }
619
620         m->m_data = m->m_ext.ext_buf = cl;
621         m->m_ext.ext_free = m->m_ext.ext_arg1 = m->m_ext.ext_arg2 = NULL;
622         m->m_ext.ext_size = size;
623         m->m_ext.ext_type = type;
624         m->m_ext.ref_cnt = uma_find_refcnt(zone, cl);
625         m->m_flags |= M_EXT;
626
627 }
628
629 static __inline void
630 m_chtype(struct mbuf *m, short new_type)
631 {
632
633         m->m_type = new_type;
634 }
635
636 static __inline struct mbuf *
637 m_last(struct mbuf *m)
638 {
639
640         while (m->m_next)
641                 m = m->m_next;
642         return (m);
643 }
644
645 /*
646  * mbuf, cluster, and external object allocation macros (for compatibility
647  * purposes).
648  */
649 #define M_MOVE_PKTHDR(to, from) m_move_pkthdr((to), (from))
650 #define MGET(m, how, type)      ((m) = m_get((how), (type)))
651 #define MGETHDR(m, how, type)   ((m) = m_gethdr((how), (type)))
652 #define MCLGET(m, how)          m_clget((m), (how))
653 #define MEXTADD(m, buf, size, free, arg1, arg2, flags, type)            \
654     (void )m_extadd((m), (caddr_t)(buf), (size), (free), (arg1), (arg2),\
655     (flags), (type), M_NOWAIT)
656 #define m_getm(m, len, how, type)                                       \
657     m_getm2((m), (len), (how), (type), M_PKTHDR)
658
659 /*
660  * Evaluate TRUE if it's safe to write to the mbuf m's data region (this can
661  * be both the local data payload, or an external buffer area, depending on
662  * whether M_EXT is set).
663  */
664 #define M_WRITABLE(m)   (!((m)->m_flags & M_RDONLY) &&                  \
665                          (!(((m)->m_flags & M_EXT)) ||                  \
666                          (*((m)->m_ext.ref_cnt) == 1)) )                \
667
668 /* Check if the supplied mbuf has a packet header, or else panic. */
669 #define M_ASSERTPKTHDR(m)                                               \
670         KASSERT((m) != NULL && (m)->m_flags & M_PKTHDR,                 \
671             ("%s: no mbuf packet header!", __func__))
672
673 /*
674  * Ensure that the supplied mbuf is a valid, non-free mbuf.
675  *
676  * XXX: Broken at the moment.  Need some UMA magic to make it work again.
677  */
678 #define M_ASSERTVALID(m)                                                \
679         KASSERT((((struct mbuf *)m)->m_flags & 0) == 0,                 \
680             ("%s: attempted use of a free mbuf!", __func__))
681
682 /*
683  * Set the m_data pointer of a newly-allocated mbuf (m_get/MGET) to place an
684  * object of the specified size at the end of the mbuf, longword aligned.
685  */
686 #define M_ALIGN(m, len) do {                                            \
687         KASSERT(!((m)->m_flags & (M_PKTHDR|M_EXT)),                     \
688                 ("%s: M_ALIGN not normal mbuf", __func__));             \
689         KASSERT((m)->m_data == (m)->m_dat,                              \
690                 ("%s: M_ALIGN not a virgin mbuf", __func__));           \
691         (m)->m_data += (MLEN - (len)) & ~(sizeof(long) - 1);            \
692 } while (0)
693
694 /*
695  * As above, for mbufs allocated with m_gethdr/MGETHDR or initialized by
696  * M_DUP/MOVE_PKTHDR.
697  */
698 #define MH_ALIGN(m, len) do {                                           \
699         KASSERT((m)->m_flags & M_PKTHDR && !((m)->m_flags & M_EXT),     \
700                 ("%s: MH_ALIGN not PKTHDR mbuf", __func__));            \
701         KASSERT((m)->m_data == (m)->m_pktdat,                           \
702                 ("%s: MH_ALIGN not a virgin mbuf", __func__));          \
703         (m)->m_data += (MHLEN - (len)) & ~(sizeof(long) - 1);           \
704 } while (0)
705
706 /*
707  * As above, for mbuf with external storage.
708  */
709 #define MEXT_ALIGN(m, len) do {                                         \
710         KASSERT((m)->m_flags & M_EXT,                                   \
711                 ("%s: MEXT_ALIGN not an M_EXT mbuf", __func__));        \
712         KASSERT((m)->m_data == (m)->m_ext.ext_buf,                      \
713                 ("%s: MEXT_ALIGN not a virgin mbuf", __func__));        \
714         (m)->m_data += ((m)->m_ext.ext_size - (len)) &                  \
715             ~(sizeof(long) - 1);                                        \
716 } while (0)
717
718 /*
719  * Compute the amount of space available before the current start of data in
720  * an mbuf.
721  *
722  * The M_WRITABLE() is a temporary, conservative safety measure: the burden
723  * of checking writability of the mbuf data area rests solely with the caller.
724  */
725 #define M_LEADINGSPACE(m)                                               \
726         ((m)->m_flags & M_EXT ?                                         \
727             (M_WRITABLE(m) ? (m)->m_data - (m)->m_ext.ext_buf : 0):     \
728             (m)->m_flags & M_PKTHDR ? (m)->m_data - (m)->m_pktdat :     \
729             (m)->m_data - (m)->m_dat)
730
731 /*
732  * Compute the amount of space available after the end of data in an mbuf.
733  *
734  * The M_WRITABLE() is a temporary, conservative safety measure: the burden
735  * of checking writability of the mbuf data area rests solely with the caller.
736  */
737 #define M_TRAILINGSPACE(m)                                              \
738         ((m)->m_flags & M_EXT ?                                         \
739             (M_WRITABLE(m) ? (m)->m_ext.ext_buf + (m)->m_ext.ext_size   \
740                 - ((m)->m_data + (m)->m_len) : 0) :                     \
741             &(m)->m_dat[MLEN] - ((m)->m_data + (m)->m_len))
742
743 /*
744  * Arrange to prepend space of size plen to mbuf m.  If a new mbuf must be
745  * allocated, how specifies whether to wait.  If the allocation fails, the
746  * original mbuf chain is freed and m is set to NULL.
747  */
748 #define M_PREPEND(m, plen, how) do {                                    \
749         struct mbuf **_mmp = &(m);                                      \
750         struct mbuf *_mm = *_mmp;                                       \
751         int _mplen = (plen);                                            \
752         int __mhow = (how);                                             \
753                                                                         \
754         MBUF_CHECKSLEEP(how);                                           \
755         if (M_LEADINGSPACE(_mm) >= _mplen) {                            \
756                 _mm->m_data -= _mplen;                                  \
757                 _mm->m_len += _mplen;                                   \
758         } else                                                          \
759                 _mm = m_prepend(_mm, _mplen, __mhow);                   \
760         if (_mm != NULL && _mm->m_flags & M_PKTHDR)                     \
761                 _mm->m_pkthdr.len += _mplen;                            \
762         *_mmp = _mm;                                                    \
763 } while (0)
764
765 /*
766  * Change mbuf to new type.  This is a relatively expensive operation and
767  * should be avoided.
768  */
769 #define MCHTYPE(m, t)   m_chtype((m), (t))
770
771 /* Length to m_copy to copy all. */
772 #define M_COPYALL       1000000000
773
774 /* Compatibility with 4.3. */
775 #define m_copy(m, o, l) m_copym((m), (o), (l), M_NOWAIT)
776
777 extern int              max_datalen;    /* MHLEN - max_hdr */
778 extern int              max_hdr;        /* Largest link + protocol header */
779 extern int              max_linkhdr;    /* Largest link-level header */
780 extern int              max_protohdr;   /* Largest protocol header */
781 extern struct mbstat    mbstat;         /* General mbuf stats/infos */
782 extern int              nmbclusters;    /* Maximum number of clusters */
783
784 struct uio;
785
786 void             m_adj(struct mbuf *, int);
787 void             m_align(struct mbuf *, int);
788 int              m_apply(struct mbuf *, int, int,
789                     int (*)(void *, void *, u_int), void *);
790 int              m_append(struct mbuf *, int, c_caddr_t);
791 void             m_cat(struct mbuf *, struct mbuf *);
792 int              m_extadd(struct mbuf *, caddr_t, u_int,
793                     void (*)(void *, void *), void *, void *, int, int, int);
794 struct mbuf     *m_collapse(struct mbuf *, int, int);
795 void             m_copyback(struct mbuf *, int, int, c_caddr_t);
796 void             m_copydata(const struct mbuf *, int, int, caddr_t);
797 struct mbuf     *m_copym(struct mbuf *, int, int, int);
798 struct mbuf     *m_copymdata(struct mbuf *, struct mbuf *,
799                     int, int, int, int);
800 struct mbuf     *m_copypacket(struct mbuf *, int);
801 void             m_copy_pkthdr(struct mbuf *, struct mbuf *);
802 struct mbuf     *m_copyup(struct mbuf *, int, int);
803 struct mbuf     *m_defrag(struct mbuf *, int);
804 void             m_demote(struct mbuf *, int);
805 struct mbuf     *m_devget(char *, int, int, struct ifnet *,
806                     void (*)(char *, caddr_t, u_int));
807 struct mbuf     *m_dup(struct mbuf *, int);
808 int              m_dup_pkthdr(struct mbuf *, struct mbuf *, int);
809 u_int            m_fixhdr(struct mbuf *);
810 struct mbuf     *m_fragment(struct mbuf *, int, int);
811 void             m_freem(struct mbuf *);
812 struct mbuf     *m_get2(int, int, short, int);
813 struct mbuf     *m_getjcl(int, short, int, int);
814 struct mbuf     *m_getm2(struct mbuf *, int, int, short, int);
815 struct mbuf     *m_getptr(struct mbuf *, int, int *);
816 u_int            m_length(struct mbuf *, struct mbuf **);
817 int              m_mbuftouio(struct uio *, struct mbuf *, int);
818 void             m_move_pkthdr(struct mbuf *, struct mbuf *);
819 struct mbuf     *m_prepend(struct mbuf *, int, int);
820 void             m_print(const struct mbuf *, int);
821 struct mbuf     *m_pulldown(struct mbuf *, int, int, int *);
822 struct mbuf     *m_pullup(struct mbuf *, int);
823 int              m_sanity(struct mbuf *, int);
824 struct mbuf     *m_split(struct mbuf *, int, int);
825 struct mbuf     *m_uiotombuf(struct uio *, int, int, int, int);
826 struct mbuf     *m_unshare(struct mbuf *, int);
827
828 /*-
829  * Network packets may have annotations attached by affixing a list of
830  * "packet tags" to the pkthdr structure.  Packet tags are dynamically
831  * allocated semi-opaque data structures that have a fixed header
832  * (struct m_tag) that specifies the size of the memory block and a
833  * <cookie,type> pair that identifies it.  The cookie is a 32-bit unique
834  * unsigned value used to identify a module or ABI.  By convention this value
835  * is chosen as the date+time that the module is created, expressed as the
836  * number of seconds since the epoch (e.g., using date -u +'%s').  The type
837  * value is an ABI/module-specific value that identifies a particular
838  * annotation and is private to the module.  For compatibility with systems
839  * like OpenBSD that define packet tags w/o an ABI/module cookie, the value
840  * PACKET_ABI_COMPAT is used to implement m_tag_get and m_tag_find
841  * compatibility shim functions and several tag types are defined below.
842  * Users that do not require compatibility should use a private cookie value
843  * so that packet tag-related definitions can be maintained privately.
844  *
845  * Note that the packet tag returned by m_tag_alloc has the default memory
846  * alignment implemented by malloc.  To reference private data one can use a
847  * construct like:
848  *
849  *      struct m_tag *mtag = m_tag_alloc(...);
850  *      struct foo *p = (struct foo *)(mtag+1);
851  *
852  * if the alignment of struct m_tag is sufficient for referencing members of
853  * struct foo.  Otherwise it is necessary to embed struct m_tag within the
854  * private data structure to insure proper alignment; e.g.,
855  *
856  *      struct foo {
857  *              struct m_tag    tag;
858  *              ...
859  *      };
860  *      struct foo *p = (struct foo *) m_tag_alloc(...);
861  *      struct m_tag *mtag = &p->tag;
862  */
863
864 /*
865  * Persistent tags stay with an mbuf until the mbuf is reclaimed.  Otherwise
866  * tags are expected to ``vanish'' when they pass through a network
867  * interface.  For most interfaces this happens normally as the tags are
868  * reclaimed when the mbuf is free'd.  However in some special cases
869  * reclaiming must be done manually.  An example is packets that pass through
870  * the loopback interface.  Also, one must be careful to do this when
871  * ``turning around'' packets (e.g., icmp_reflect).
872  *
873  * To mark a tag persistent bit-or this flag in when defining the tag id.
874  * The tag will then be treated as described above.
875  */
876 #define MTAG_PERSISTENT                         0x800
877
878 #define PACKET_TAG_NONE                         0  /* Nadda */
879
880 /* Packet tags for use with PACKET_ABI_COMPAT. */
881 #define PACKET_TAG_IPSEC_IN_DONE                1  /* IPsec applied, in */
882 #define PACKET_TAG_IPSEC_OUT_DONE               2  /* IPsec applied, out */
883 #define PACKET_TAG_IPSEC_IN_CRYPTO_DONE         3  /* NIC IPsec crypto done */
884 #define PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED      4  /* NIC IPsec crypto req'ed */
885 #define PACKET_TAG_IPSEC_IN_COULD_DO_CRYPTO     5  /* NIC notifies IPsec */
886 #define PACKET_TAG_IPSEC_PENDING_TDB            6  /* Reminder to do IPsec */
887 #define PACKET_TAG_BRIDGE                       7  /* Bridge processing done */
888 #define PACKET_TAG_GIF                          8  /* GIF processing done */
889 #define PACKET_TAG_GRE                          9  /* GRE processing done */
890 #define PACKET_TAG_IN_PACKET_CHECKSUM           10 /* NIC checksumming done */
891 #define PACKET_TAG_ENCAP                        11 /* Encap.  processing */
892 #define PACKET_TAG_IPSEC_SOCKET                 12 /* IPSEC socket ref */
893 #define PACKET_TAG_IPSEC_HISTORY                13 /* IPSEC history */
894 #define PACKET_TAG_IPV6_INPUT                   14 /* IPV6 input processing */
895 #define PACKET_TAG_DUMMYNET                     15 /* dummynet info */
896 #define PACKET_TAG_DIVERT                       17 /* divert info */
897 #define PACKET_TAG_IPFORWARD                    18 /* ipforward info */
898 #define PACKET_TAG_MACLABEL     (19 | MTAG_PERSISTENT) /* MAC label */
899 #define PACKET_TAG_PF           (21 | MTAG_PERSISTENT) /* PF/ALTQ information */
900 #define PACKET_TAG_RTSOCKFAM                    25 /* rtsock sa family */
901 #define PACKET_TAG_IPOPTIONS                    27 /* Saved IP options */
902 #define PACKET_TAG_CARP                         28 /* CARP info */
903 #define PACKET_TAG_IPSEC_NAT_T_PORTS            29 /* two uint16_t */
904 #define PACKET_TAG_ND_OUTGOING                  30 /* ND outgoing */
905
906 /* Specific cookies and tags. */
907
908 /* Packet tag routines. */
909 struct m_tag    *m_tag_alloc(u_int32_t, int, int, int);
910 void             m_tag_delete(struct mbuf *, struct m_tag *);
911 void             m_tag_delete_chain(struct mbuf *, struct m_tag *);
912 void             m_tag_free_default(struct m_tag *);
913 struct m_tag    *m_tag_locate(struct mbuf *, u_int32_t, int, struct m_tag *);
914 struct m_tag    *m_tag_copy(struct m_tag *, int);
915 int              m_tag_copy_chain(struct mbuf *, struct mbuf *, int);
916 void             m_tag_delete_nonpersistent(struct mbuf *);
917
918 /*
919  * Initialize the list of tags associated with an mbuf.
920  */
921 static __inline void
922 m_tag_init(struct mbuf *m)
923 {
924
925         SLIST_INIT(&m->m_pkthdr.tags);
926 }
927
928 /*
929  * Set up the contents of a tag.  Note that this does not fill in the free
930  * method; the caller is expected to do that.
931  *
932  * XXX probably should be called m_tag_init, but that was already taken.
933  */
934 static __inline void
935 m_tag_setup(struct m_tag *t, u_int32_t cookie, int type, int len)
936 {
937
938         t->m_tag_id = type;
939         t->m_tag_len = len;
940         t->m_tag_cookie = cookie;
941 }
942
943 /*
944  * Reclaim resources associated with a tag.
945  */
946 static __inline void
947 m_tag_free(struct m_tag *t)
948 {
949
950         (*t->m_tag_free)(t);
951 }
952
953 /*
954  * Return the first tag associated with an mbuf.
955  */
956 static __inline struct m_tag *
957 m_tag_first(struct mbuf *m)
958 {
959
960         return (SLIST_FIRST(&m->m_pkthdr.tags));
961 }
962
963 /*
964  * Return the next tag in the list of tags associated with an mbuf.
965  */
966 static __inline struct m_tag *
967 m_tag_next(struct mbuf *m, struct m_tag *t)
968 {
969
970         return (SLIST_NEXT(t, m_tag_link));
971 }
972
973 /*
974  * Prepend a tag to the list of tags associated with an mbuf.
975  */
976 static __inline void
977 m_tag_prepend(struct mbuf *m, struct m_tag *t)
978 {
979
980         SLIST_INSERT_HEAD(&m->m_pkthdr.tags, t, m_tag_link);
981 }
982
983 /*
984  * Unlink a tag from the list of tags associated with an mbuf.
985  */
986 static __inline void
987 m_tag_unlink(struct mbuf *m, struct m_tag *t)
988 {
989
990         SLIST_REMOVE(&m->m_pkthdr.tags, t, m_tag, m_tag_link);
991 }
992
993 /* These are for OpenBSD compatibility. */
994 #define MTAG_ABI_COMPAT         0               /* compatibility ABI */
995
996 static __inline struct m_tag *
997 m_tag_get(int type, int length, int wait)
998 {
999         return (m_tag_alloc(MTAG_ABI_COMPAT, type, length, wait));
1000 }
1001
1002 static __inline struct m_tag *
1003 m_tag_find(struct mbuf *m, int type, struct m_tag *start)
1004 {
1005         return (SLIST_EMPTY(&m->m_pkthdr.tags) ? (struct m_tag *)NULL :
1006             m_tag_locate(m, MTAG_ABI_COMPAT, type, start));
1007 }
1008
1009 static int inline
1010 rt_m_getfib(struct mbuf *m)
1011 {
1012         KASSERT(m->m_flags & M_PKTHDR , ("Attempt to get FIB from non header mbuf."));
1013         return (m->m_pkthdr.fibnum);
1014 }
1015
1016 #define M_GETFIB(_m)   rt_m_getfib(_m)
1017
1018 #define M_SETFIB(_m, _fib) do {                                         \
1019         KASSERT((_m)->m_flags & M_PKTHDR, ("Attempt to set FIB on non header mbuf."));  \
1020         ((_m)->m_pkthdr.fibnum) = (_fib);                               \
1021 } while (0)
1022
1023 #endif /* _KERNEL */
1024
1025 #ifdef MBUF_PROFILING
1026  void m_profile(struct mbuf *m);
1027  #define M_PROFILE(m) m_profile(m)
1028 #else
1029  #define M_PROFILE(m)
1030 #endif
1031
1032
1033 #endif /* !_SYS_MBUF_H_ */