]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/net/netmap.h
bridge: Fix panic if the STP root is removed
[FreeBSD/FreeBSD.git] / sys / net / netmap.h
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (C) 2011-2014 Matteo Landi, Luigi Rizzo. 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  *
10  *   1. Redistributions of source code must retain the above copyright
11  *      notice, this list of conditions and the following disclaimer.
12  *   2. Redistributions in binary form must reproduce the above copyright
13  *      notice, this list of conditions and the following disclaimer in the
14  *      documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``S IS''AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28
29 /*
30  * $FreeBSD$
31  *
32  * Definitions of constants and the structures used by the netmap
33  * framework, for the part visible to both kernel and userspace.
34  * Detailed info on netmap is available with "man netmap" or at
35  *
36  *      http://info.iet.unipi.it/~luigi/netmap/
37  *
38  * This API is also used to communicate with the VALE software switch
39  */
40
41 #ifndef _NET_NETMAP_H_
42 #define _NET_NETMAP_H_
43
44 #define NETMAP_API      13              /* current API version */
45
46 #define NETMAP_MIN_API  13              /* min and max versions accepted */
47 #define NETMAP_MAX_API  15
48 /*
49  * Some fields should be cache-aligned to reduce contention.
50  * The alignment is architecture and OS dependent, but rather than
51  * digging into OS headers to find the exact value we use an estimate
52  * that should cover most architectures.
53  */
54 #define NM_CACHE_ALIGN  128
55
56 /*
57  * --- Netmap data structures ---
58  *
59  * The userspace data structures used by netmap are shown below.
60  * They are allocated by the kernel and mmap()ed by userspace threads.
61  * Pointers are implemented as memory offsets or indexes,
62  * so that they can be easily dereferenced in kernel and userspace.
63
64    KERNEL (opaque, obviously)
65
66   ====================================================================
67                                          |
68    USERSPACE                             |      struct netmap_ring
69                                          +---->+---------------+
70                                              / | head,cur,tail |
71    struct netmap_if (nifp, 1 per fd)        /  | buf_ofs       |
72     +---------------+                      /   | other fields  |
73     | ni_tx_rings   |                     /    +===============+
74     | ni_rx_rings   |                    /     | buf_idx, len  | slot[0]
75     |               |                   /      | flags, ptr    |
76     |               |                  /       +---------------+
77     +===============+                 /        | buf_idx, len  | slot[1]
78     | txring_ofs[0] | (rel.to nifp)--'         | flags, ptr    |
79     | txring_ofs[1] |                          +---------------+
80      (tx+1 entries)                           (num_slots entries)
81     | txring_ofs[t] |                          | buf_idx, len  | slot[n-1]
82     +---------------+                          | flags, ptr    |
83     | rxring_ofs[0] |                          +---------------+
84     | rxring_ofs[1] |
85      (rx+1 entries)
86     | rxring_ofs[r] |
87     +---------------+
88
89  * For each "interface" (NIC, host stack, PIPE, VALE switch port) bound to
90  * a file descriptor, the mmap()ed region contains a (logically readonly)
91  * struct netmap_if pointing to struct netmap_ring's.
92  *
93  * There is one netmap_ring per physical NIC ring, plus one tx/rx ring
94  * pair attached to the host stack (this pair is unused for non-NIC ports).
95  *
96  * All physical/host stack ports share the same memory region,
97  * so that zero-copy can be implemented between them.
98  * VALE switch ports instead have separate memory regions.
99  *
100  * The netmap_ring is the userspace-visible replica of the NIC ring.
101  * Each slot has the index of a buffer (MTU-sized and residing in the
102  * mmapped region), its length and some flags. An extra 64-bit pointer
103  * is provided for user-supplied buffers in the tx path.
104  *
105  * In user space, the buffer address is computed as
106  *      (char *)ring + buf_ofs + index * NETMAP_BUF_SIZE
107  *
108  * Added in NETMAP_API 11:
109  *
110  * + NIOCREGIF can request the allocation of extra spare buffers from
111  *   the same memory pool. The desired number of buffers must be in
112  *   nr_arg3. The ioctl may return fewer buffers, depending on memory
113  *   availability. nr_arg3 will return the actual value, and, once
114  *   mapped, nifp->ni_bufs_head will be the index of the first buffer.
115  *
116  *   The buffers are linked to each other using the first uint32_t
117  *   as the index. On close, ni_bufs_head must point to the list of
118  *   buffers to be released.
119  *
120  * + NIOCREGIF can request space for extra rings (and buffers)
121  *   allocated in the same memory space. The number of extra rings
122  *   is in nr_arg1, and is advisory. This is a no-op on NICs where
123  *   the size of the memory space is fixed.
124  *
125  * + NIOCREGIF can attach to PIPE rings sharing the same memory
126  *   space with a parent device. The ifname indicates the parent device,
127  *   which must already exist. Flags in nr_flags indicate if we want to
128  *   bind the master or slave side, the index (from nr_ringid)
129  *   is just a cookie and does not need to be sequential.
130  *
131  * + NIOCREGIF can also attach to 'monitor' rings that replicate
132  *   the content of specific rings, also from the same memory space.
133  *
134  *   Extra flags in nr_flags support the above functions.
135  *   Application libraries may use the following naming scheme:
136  *      netmap:foo                      all NIC ring pairs
137  *      netmap:foo^                     only host ring pair
138  *      netmap:foo+                     all NIC ring + host ring pairs
139  *      netmap:foo-k                    the k-th NIC ring pair
140  *      netmap:foo{k                    PIPE ring pair k, master side
141  *      netmap:foo}k                    PIPE ring pair k, slave side
142  *
143  * Some notes about host rings:
144  *
145  * + The RX host ring is used to store those packets that the host network
146  *   stack is trying to transmit through a NIC queue, but only if that queue
147  *   is currently in netmap mode. Netmap will not intercept host stack mbufs
148  *   designated to NIC queues that are not in netmap mode. As a consequence,
149  *   registering a netmap port with netmap:foo^ is not enough to intercept
150  *   mbufs in the RX host ring; the netmap port should be registered with
151  *   netmap:foo*, or another registration should be done to open at least a
152  *   NIC TX queue in netmap mode.
153  *
154  * + Netmap is not currently able to deal with intercepted trasmit mbufs which
155  *   require offloadings like TSO, UFO, checksumming offloadings, etc. It is
156  *   responsibility of the user to disable those offloadings (e.g. using
157  *   ifconfig on FreeBSD or ethtool -K on Linux) for an interface that is being
158  *   used in netmap mode. If the offloadings are not disabled, GSO and/or
159  *   unchecksummed packets may be dropped immediately or end up in the host RX
160  *   ring, and will be dropped as soon as the packet reaches another netmap
161  *   adapter.
162  */
163
164 /*
165  * struct netmap_slot is a buffer descriptor
166  */
167 struct netmap_slot {
168         uint32_t buf_idx;       /* buffer index */
169         uint16_t len;           /* length for this slot */
170         uint16_t flags;         /* buf changed, etc. */
171         uint64_t ptr;           /* pointer for indirect buffers */
172 };
173
174 /*
175  * The following flags control how the slot is used
176  */
177
178 #define NS_BUF_CHANGED  0x0001  /* buf_idx changed */
179         /*
180          * must be set whenever buf_idx is changed (as it might be
181          * necessary to recompute the physical address and mapping)
182          *
183          * It is also set by the kernel whenever the buf_idx is
184          * changed internally (e.g., by pipes). Applications may
185          * use this information to know when they can reuse the
186          * contents of previously prepared buffers.
187          */
188
189 #define NS_REPORT       0x0002  /* ask the hardware to report results */
190         /*
191          * Request notification when slot is used by the hardware.
192          * Normally transmit completions are handled lazily and
193          * may be unreported. This flag lets us know when a slot
194          * has been sent (e.g. to terminate the sender).
195          */
196
197 #define NS_FORWARD      0x0004  /* pass packet 'forward' */
198         /*
199          * (Only for physical ports, rx rings with NR_FORWARD set).
200          * Slot released to the kernel (i.e. before ring->head) with
201          * this flag set are passed to the peer ring (host/NIC),
202          * thus restoring the host-NIC connection for these slots.
203          * This supports efficient traffic monitoring or firewalling.
204          */
205
206 #define NS_NO_LEARN     0x0008  /* disable bridge learning */
207         /*
208          * On a VALE switch, do not 'learn' the source port for
209          * this buffer.
210          */
211
212 #define NS_INDIRECT     0x0010  /* userspace buffer */
213         /*
214          * (VALE tx rings only) data is in a userspace buffer,
215          * whose address is in the 'ptr' field in the slot.
216          */
217
218 #define NS_MOREFRAG     0x0020  /* packet has more fragments */
219         /*
220          * (VALE ports, ptnetmap ports and some NIC ports, e.g.
221          * ixgbe and i40e on Linux)
222          * Set on all but the last slot of a multi-segment packet.
223          * The 'len' field refers to the individual fragment.
224          */
225
226 #define NS_PORT_SHIFT   8
227 #define NS_PORT_MASK    (0xff << NS_PORT_SHIFT)
228         /*
229          * The high 8 bits of the flag, if not zero, indicate the
230          * destination port for the VALE switch, overriding
231          * the lookup table.
232          */
233
234 #define NS_RFRAGS(_slot)        ( ((_slot)->flags >> 8) & 0xff)
235         /*
236          * (VALE rx rings only) the high 8 bits
237          *  are the number of fragments.
238          */
239
240 #define NETMAP_MAX_FRAGS        64      /* max number of fragments */
241
242
243 /*
244  * struct netmap_ring
245  *
246  * Netmap representation of a TX or RX ring (also known as "queue").
247  * This is a queue implemented as a fixed-size circular array.
248  * At the software level the important fields are: head, cur, tail.
249  *
250  * In TX rings:
251  *
252  *      head    first slot available for transmission.
253  *      cur     wakeup point. select() and poll() will unblock
254  *              when 'tail' moves past 'cur'
255  *      tail    (readonly) first slot reserved to the kernel
256  *
257  *      [head .. tail-1] can be used for new packets to send;
258  *      'head' and 'cur' must be incremented as slots are filled
259  *          with new packets to be sent;
260  *      'cur' can be moved further ahead if we need more space
261  *      for new transmissions. XXX todo (2014-03-12)
262  *
263  * In RX rings:
264  *
265  *      head    first valid received packet
266  *      cur     wakeup point. select() and poll() will unblock
267  *              when 'tail' moves past 'cur'
268  *      tail    (readonly) first slot reserved to the kernel
269  *
270  *      [head .. tail-1] contain received packets;
271  *      'head' and 'cur' must be incremented as slots are consumed
272  *              and can be returned to the kernel;
273  *      'cur' can be moved further ahead if we want to wait for
274  *              new packets without returning the previous ones.
275  *
276  * DATA OWNERSHIP/LOCKING:
277  *      The netmap_ring, and all slots and buffers in the range
278  *      [head .. tail-1] are owned by the user program;
279  *      the kernel only accesses them during a netmap system call
280  *      and in the user thread context.
281  *
282  *      Other slots and buffers are reserved for use by the kernel
283  */
284 struct netmap_ring {
285         /*
286          * buf_ofs is meant to be used through macros.
287          * It contains the offset of the buffer region from this
288          * descriptor.
289          */
290         const int64_t   buf_ofs;
291         const uint32_t  num_slots;      /* number of slots in the ring. */
292         const uint32_t  nr_buf_size;
293         const uint16_t  ringid;
294         const uint16_t  dir;            /* 0: tx, 1: rx */
295
296         uint32_t        head;           /* (u) first user slot */
297         uint32_t        cur;            /* (u) wakeup point */
298         uint32_t        tail;           /* (k) first kernel slot */
299
300         uint32_t        flags;
301
302         struct timeval  ts;             /* (k) time of last *sync() */
303
304         /* opaque room for a mutex or similar object */
305 #if !defined(_WIN32) || defined(__CYGWIN__)
306         uint8_t __attribute__((__aligned__(NM_CACHE_ALIGN))) sem[128];
307 #else
308         uint8_t __declspec(align(NM_CACHE_ALIGN)) sem[128];
309 #endif
310
311         /* the slots follow. This struct has variable size */
312         struct netmap_slot slot[0];     /* array of slots. */
313 };
314
315
316 /*
317  * RING FLAGS
318  */
319 #define NR_TIMESTAMP    0x0002          /* set timestamp on *sync() */
320         /*
321          * updates the 'ts' field on each netmap syscall. This saves
322          * saves a separate gettimeofday(), and is not much worse than
323          * software timestamps generated in the interrupt handler.
324          */
325
326 #define NR_FORWARD      0x0004          /* enable NS_FORWARD for ring */
327         /*
328          * Enables the NS_FORWARD slot flag for the ring.
329          */
330
331 /*
332  * Helper functions for kernel and userspace
333  */
334
335 /*
336  * Check if space is available in the ring. We use ring->head, which
337  * points to the next netmap slot to be published to netmap. It is
338  * possible that the applications moves ring->cur ahead of ring->tail
339  * (e.g., by setting ring->cur <== ring->tail), if it wants more slots
340  * than the ones currently available, and it wants to be notified when
341  * more arrive. See netmap(4) for more details and examples.
342  */
343 static inline int
344 nm_ring_empty(struct netmap_ring *ring)
345 {
346         return (ring->head == ring->tail);
347 }
348
349 /*
350  * Netmap representation of an interface and its queue(s).
351  * This is initialized by the kernel when binding a file
352  * descriptor to a port, and should be considered as readonly
353  * by user programs. The kernel never uses it.
354  *
355  * There is one netmap_if for each file descriptor on which we want
356  * to select/poll.
357  * select/poll operates on one or all pairs depending on the value of
358  * nmr_queueid passed on the ioctl.
359  */
360 struct netmap_if {
361         char            ni_name[IFNAMSIZ]; /* name of the interface. */
362         const uint32_t  ni_version;     /* API version, currently unused */
363         const uint32_t  ni_flags;       /* properties */
364 #define NI_PRIV_MEM     0x1             /* private memory region */
365
366         /*
367          * The number of packet rings available in netmap mode.
368          * Physical NICs can have different numbers of tx and rx rings.
369          * Physical NICs also have a 'host' ring pair.
370          * Additionally, clients can request additional ring pairs to
371          * be used for internal communication.
372          */
373         const uint32_t  ni_tx_rings;    /* number of HW tx rings */
374         const uint32_t  ni_rx_rings;    /* number of HW rx rings */
375
376         uint32_t        ni_bufs_head;   /* head index for extra bufs */
377         uint32_t        ni_spare1[5];
378         /*
379          * The following array contains the offset of each netmap ring
380          * from this structure, in the following order:
381          * NIC tx rings (ni_tx_rings); host tx ring (1); extra tx rings;
382          * NIC rx rings (ni_rx_rings); host tx ring (1); extra rx rings.
383          *
384          * The area is filled up by the kernel on NIOCREGIF,
385          * and then only read by userspace code.
386          */
387         const ssize_t   ring_ofs[0];
388 };
389
390 /* Legacy interface to interact with a netmap control device.
391  * Included for backward compatibility. The user should not include this
392  * file directly. */
393 #include "netmap_legacy.h"
394
395 /*
396  * New API to control netmap control devices. New applications should only use
397  * nmreq_xyz structs with the NIOCCTRL ioctl() command.
398  *
399  * NIOCCTRL takes a nmreq_header struct, which contains the required
400  * API version, the name of a netmap port, a command type, and pointers
401  * to request body and options.
402  *
403  *      nr_name (in)
404  *              The name of the port (em0, valeXXX:YYY, eth0{pn1 etc.)
405  *
406  *      nr_version (in/out)
407  *              Must match NETMAP_API as used in the kernel, error otherwise.
408  *              Always returns the desired value on output.
409  *
410  *      nr_reqtype (in)
411  *              One of the NETMAP_REQ_* command types below
412  *
413  *      nr_body (in)
414  *              Pointer to a command-specific struct, described by one
415  *              of the struct nmreq_xyz below.
416  *
417  *      nr_options (in)
418  *              Command specific options, if any.
419  *
420  * A NETMAP_REQ_REGISTER command activates netmap mode on the netmap
421  * port (e.g. physical interface) specified by nmreq_header.nr_name.
422  * The request body (struct nmreq_register) has several arguments to
423  * specify how the port is to be registered.
424  *
425  *      nr_tx_slots, nr_tx_slots, nr_tx_rings, nr_rx_rings (in/out)
426  *              On input, non-zero values may be used to reconfigure the port
427  *              according to the requested values, but this is not guaranteed.
428  *              On output the actual values in use are reported.
429  *
430  *      nr_mode (in)
431  *              Indicate what set of rings must be bound to the netmap
432  *              device (e.g. all NIC rings, host rings only, NIC and
433  *              host rings, ...). Values are in NR_REG_*.
434  *
435  *      nr_ringid (in)
436  *              If nr_mode == NR_REG_ONE_NIC (only a single couple of TX/RX
437  *              rings), indicate which NIC TX and/or RX ring is to be bound
438  *              (0..nr_*x_rings-1).
439  *
440  *      nr_flags (in)
441  *              Indicate special options for how to open the port.
442  *
443  *              NR_NO_TX_POLL can be OR-ed to make select()/poll() push
444  *                      packets on tx rings only if POLLOUT is set.
445  *                      The default is to push any pending packet.
446  *
447  *              NR_DO_RX_POLL can be OR-ed to make select()/poll() release
448  *                      packets on rx rings also when POLLIN is NOT set.
449  *                      The default is to touch the rx ring only with POLLIN.
450  *                      Note that this is the opposite of TX because it
451  *                      reflects the common usage.
452  *
453  *              Other options are NR_MONITOR_TX, NR_MONITOR_RX, NR_ZCOPY_MON,
454  *              NR_EXCLUSIVE, NR_RX_RINGS_ONLY, NR_TX_RINGS_ONLY and
455  *              NR_ACCEPT_VNET_HDR.
456  *
457  *      nr_mem_id (in/out)
458  *              The identity of the memory region used.
459  *              On input, 0 means the system decides autonomously,
460  *              other values may try to select a specific region.
461  *              On return the actual value is reported.
462  *              Region '1' is the global allocator, normally shared
463  *              by all interfaces. Other values are private regions.
464  *              If two ports the same region zero-copy is possible.
465  *
466  *      nr_extra_bufs (in/out)
467  *              Number of extra buffers to be allocated.
468  *
469  * The other NETMAP_REQ_* commands are described below.
470  *
471  */
472
473 /* maximum size of a request, including all options */
474 #define NETMAP_REQ_MAXSIZE      4096
475
476 /* Header common to all request options. */
477 struct nmreq_option {
478         /* Pointer ot the next option. */
479         uint64_t                nro_next;
480         /* Option type. */
481         uint32_t                nro_reqtype;
482         /* (out) status of the option:
483          * 0: recognized and processed
484          * !=0: errno value
485          */
486         uint32_t                nro_status;
487         /* Option size, used only for options that can have variable size
488          * (e.g. because they contain arrays). For fixed-size options this
489          * field should be set to zero. */
490         uint64_t                nro_size;
491 };
492
493 /* Header common to all requests. Do not reorder these fields, as we need
494  * the second one (nr_reqtype) to know how much to copy from/to userspace. */
495 struct nmreq_header {
496         uint16_t                nr_version;     /* API version */
497         uint16_t                nr_reqtype;     /* nmreq type (NETMAP_REQ_*) */
498         uint32_t                nr_reserved;    /* must be zero */
499 #define NETMAP_REQ_IFNAMSIZ     64
500         char                    nr_name[NETMAP_REQ_IFNAMSIZ]; /* port name */
501         uint64_t                nr_options;     /* command-specific options */
502         uint64_t                nr_body;        /* ptr to nmreq_xyz struct */
503 };
504
505 enum {
506         /* Register a netmap port with the device. */
507         NETMAP_REQ_REGISTER = 1,
508         /* Get information from a netmap port. */
509         NETMAP_REQ_PORT_INFO_GET,
510         /* Attach a netmap port to a VALE switch. */
511         NETMAP_REQ_VALE_ATTACH,
512         /* Detach a netmap port from a VALE switch. */
513         NETMAP_REQ_VALE_DETACH,
514         /* List the ports attached to a VALE switch. */
515         NETMAP_REQ_VALE_LIST,
516         /* Set the port header length (was virtio-net header length). */
517         NETMAP_REQ_PORT_HDR_SET,
518         /* Get the port header length (was virtio-net header length). */
519         NETMAP_REQ_PORT_HDR_GET,
520         /* Create a new persistent VALE port. */
521         NETMAP_REQ_VALE_NEWIF,
522         /* Delete a persistent VALE port. */
523         NETMAP_REQ_VALE_DELIF,
524         /* Enable polling kernel thread(s) on an attached VALE port. */
525         NETMAP_REQ_VALE_POLLING_ENABLE,
526         /* Disable polling kernel thread(s) on an attached VALE port. */
527         NETMAP_REQ_VALE_POLLING_DISABLE,
528         /* Get info about the pools of a memory allocator. */
529         NETMAP_REQ_POOLS_INFO_GET,
530         /* Start an in-kernel loop that syncs the rings periodically or
531          * on notifications. The loop runs in the context of the ioctl
532          * syscall, and only stops on NETMAP_REQ_SYNC_KLOOP_STOP. */
533         NETMAP_REQ_SYNC_KLOOP_START,
534         /* Stops the thread executing the in-kernel loop. The thread
535          * returns from the ioctl syscall. */
536         NETMAP_REQ_SYNC_KLOOP_STOP,
537         /* Enable CSB mode on a registered netmap control device. */
538         NETMAP_REQ_CSB_ENABLE,
539 };
540
541 enum {
542         /* On NETMAP_REQ_REGISTER, ask netmap to use memory allocated
543          * from user-space allocated memory pools (e.g. hugepages).
544          */
545         NETMAP_REQ_OPT_EXTMEM = 1,
546
547         /* ON NETMAP_REQ_SYNC_KLOOP_START, ask netmap to use eventfd-based
548          * notifications to synchronize the kernel loop with the application.
549          */
550         NETMAP_REQ_OPT_SYNC_KLOOP_EVENTFDS,
551
552         /* On NETMAP_REQ_REGISTER, ask netmap to work in CSB mode, where
553          * head, cur and tail pointers are not exchanged through the
554          * struct netmap_ring header, but rather using an user-provided
555          * memory area (see struct nm_csb_atok and struct nm_csb_ktoa).
556          */
557         NETMAP_REQ_OPT_CSB,
558
559         /* An extension to NETMAP_REQ_OPT_SYNC_KLOOP_EVENTFDS, which specifies
560          * if the TX and/or RX rings are synced in the context of the VM exit.
561          * This requires the 'ioeventfd' fields to be valid (cannot be < 0).
562          */
563         NETMAP_REQ_OPT_SYNC_KLOOP_MODE,
564 };
565
566 /*
567  * nr_reqtype: NETMAP_REQ_REGISTER
568  * Bind (register) a netmap port to this control device.
569  */
570 struct nmreq_register {
571         uint64_t        nr_offset;      /* nifp offset in the shared region */
572         uint64_t        nr_memsize;     /* size of the shared region */
573         uint32_t        nr_tx_slots;    /* slots in tx rings */
574         uint32_t        nr_rx_slots;    /* slots in rx rings */
575         uint16_t        nr_tx_rings;    /* number of tx rings */
576         uint16_t        nr_rx_rings;    /* number of rx rings */
577
578         uint16_t        nr_mem_id;      /* id of the memory allocator */
579         uint16_t        nr_ringid;      /* ring(s) we care about */
580         uint32_t        nr_mode;        /* specify NR_REG_* modes */
581         uint32_t        nr_extra_bufs;  /* number of requested extra buffers */
582
583         uint64_t        nr_flags;       /* additional flags (see below) */
584 /* monitors use nr_ringid and nr_mode to select the rings to monitor */
585 #define NR_MONITOR_TX   0x100
586 #define NR_MONITOR_RX   0x200
587 #define NR_ZCOPY_MON    0x400
588 /* request exclusive access to the selected rings */
589 #define NR_EXCLUSIVE    0x800
590 /* 0x1000 unused */
591 #define NR_RX_RINGS_ONLY        0x2000
592 #define NR_TX_RINGS_ONLY        0x4000
593 /* Applications set this flag if they are able to deal with virtio-net headers,
594  * that is send/receive frames that start with a virtio-net header.
595  * If not set, NIOCREGIF will fail with netmap ports that require applications
596  * to use those headers. If the flag is set, the application can use the
597  * NETMAP_VNET_HDR_GET command to figure out the header length. */
598 #define NR_ACCEPT_VNET_HDR      0x8000
599 /* The following two have the same meaning of NETMAP_NO_TX_POLL and
600  * NETMAP_DO_RX_POLL. */
601 #define NR_DO_RX_POLL           0x10000
602 #define NR_NO_TX_POLL           0x20000
603 };
604
605 /* Valid values for nmreq_register.nr_mode (see above). */
606 enum {  NR_REG_DEFAULT  = 0,    /* backward compat, should not be used. */
607         NR_REG_ALL_NIC  = 1,
608         NR_REG_SW       = 2,
609         NR_REG_NIC_SW   = 3,
610         NR_REG_ONE_NIC  = 4,
611         NR_REG_PIPE_MASTER = 5, /* deprecated, use "x{y" port name syntax */
612         NR_REG_PIPE_SLAVE = 6,  /* deprecated, use "x}y" port name syntax */
613         NR_REG_NULL     = 7,
614 };
615
616 /* A single ioctl number is shared by all the new API command.
617  * Demultiplexing is done using the hdr.nr_reqtype field.
618  * FreeBSD uses the size value embedded in the _IOWR to determine
619  * how much to copy in/out, so we define the ioctl() command
620  * specifying only nmreq_header, and copyin/copyout the rest. */
621 #define NIOCCTRL        _IOWR('i', 151, struct nmreq_header)
622
623 /* The ioctl commands to sync TX/RX netmap rings.
624  * NIOCTXSYNC, NIOCRXSYNC synchronize tx or rx queues,
625  *      whose identity is set in NIOCREGIF through nr_ringid.
626  *      These are non blocking and take no argument. */
627 #define NIOCTXSYNC      _IO('i', 148) /* sync tx queues */
628 #define NIOCRXSYNC      _IO('i', 149) /* sync rx queues */
629
630 /*
631  * nr_reqtype: NETMAP_REQ_PORT_INFO_GET
632  * Get information about a netmap port, including number of rings.
633  * slots per ring, id of the memory allocator, etc. The netmap
634  * control device used for this operation does not need to be bound
635  * to a netmap port.
636  */
637 struct nmreq_port_info_get {
638         uint64_t        nr_memsize;     /* size of the shared region */
639         uint32_t        nr_tx_slots;    /* slots in tx rings */
640         uint32_t        nr_rx_slots;    /* slots in rx rings */
641         uint16_t        nr_tx_rings;    /* number of tx rings */
642         uint16_t        nr_rx_rings;    /* number of rx rings */
643         uint16_t        nr_mem_id;      /* memory allocator id (in/out) */
644         uint16_t        pad1;
645 };
646
647 #define NM_BDG_NAME             "vale"  /* prefix for bridge port name */
648
649 /*
650  * nr_reqtype: NETMAP_REQ_VALE_ATTACH
651  * Attach a netmap port to a VALE switch. Both the name of the netmap
652  * port and the VALE switch are specified through the nr_name argument.
653  * The attach operation could need to register a port, so at least
654  * the same arguments are available.
655  * port_index will contain the index where the port has been attached.
656  */
657 struct nmreq_vale_attach {
658         struct nmreq_register reg;
659         uint32_t port_index;
660         uint32_t pad1;
661 };
662
663 /*
664  * nr_reqtype: NETMAP_REQ_VALE_DETACH
665  * Detach a netmap port from a VALE switch. Both the name of the netmap
666  * port and the VALE switch are specified through the nr_name argument.
667  * port_index will contain the index where the port was attached.
668  */
669 struct nmreq_vale_detach {
670         uint32_t port_index;
671         uint32_t pad1;
672 };
673
674 /*
675  * nr_reqtype: NETMAP_REQ_VALE_LIST
676  * List the ports of a VALE switch.
677  */
678 struct nmreq_vale_list {
679         /* Name of the VALE port (valeXXX:YYY) or empty. */
680         uint16_t        nr_bridge_idx;
681         uint16_t        pad1;
682         uint32_t        nr_port_idx;
683 };
684
685 /*
686  * nr_reqtype: NETMAP_REQ_PORT_HDR_SET or NETMAP_REQ_PORT_HDR_GET
687  * Set or get the port header length of the port identified by hdr.nr_name.
688  * The control device does not need to be bound to a netmap port.
689  */
690 struct nmreq_port_hdr {
691         uint32_t        nr_hdr_len;
692         uint32_t        pad1;
693 };
694
695 /*
696  * nr_reqtype: NETMAP_REQ_VALE_NEWIF
697  * Create a new persistent VALE port.
698  */
699 struct nmreq_vale_newif {
700         uint32_t        nr_tx_slots;    /* slots in tx rings */
701         uint32_t        nr_rx_slots;    /* slots in rx rings */
702         uint16_t        nr_tx_rings;    /* number of tx rings */
703         uint16_t        nr_rx_rings;    /* number of rx rings */
704         uint16_t        nr_mem_id;      /* id of the memory allocator */
705         uint16_t        pad1;
706 };
707
708 /*
709  * nr_reqtype: NETMAP_REQ_VALE_POLLING_ENABLE or NETMAP_REQ_VALE_POLLING_DISABLE
710  * Enable or disable polling kthreads on a VALE port.
711  */
712 struct nmreq_vale_polling {
713         uint32_t        nr_mode;
714 #define NETMAP_POLLING_MODE_SINGLE_CPU 1
715 #define NETMAP_POLLING_MODE_MULTI_CPU 2
716         uint32_t        nr_first_cpu_id;
717         uint32_t        nr_num_polling_cpus;
718         uint32_t        pad1;
719 };
720
721 /*
722  * nr_reqtype: NETMAP_REQ_POOLS_INFO_GET
723  * Get info about the pools of the memory allocator of the netmap
724  * port specified by hdr.nr_name and nr_mem_id. The netmap control
725  * device used for this operation does not need to be bound to a netmap
726  * port.
727  */
728 struct nmreq_pools_info {
729         uint64_t        nr_memsize;
730         uint16_t        nr_mem_id; /* in/out argument */
731         uint16_t        pad1[3];
732         uint64_t        nr_if_pool_offset;
733         uint32_t        nr_if_pool_objtotal;
734         uint32_t        nr_if_pool_objsize;
735         uint64_t        nr_ring_pool_offset;
736         uint32_t        nr_ring_pool_objtotal;
737         uint32_t        nr_ring_pool_objsize;
738         uint64_t        nr_buf_pool_offset;
739         uint32_t        nr_buf_pool_objtotal;
740         uint32_t        nr_buf_pool_objsize;
741 };
742
743 /*
744  * nr_reqtype: NETMAP_REQ_SYNC_KLOOP_START
745  * Start an in-kernel loop that syncs the rings periodically or on
746  * notifications. The loop runs in the context of the ioctl syscall,
747  * and only stops on NETMAP_REQ_SYNC_KLOOP_STOP.
748  * The registered netmap port must be open in CSB mode.
749  */
750 struct nmreq_sync_kloop_start {
751         /* Sleeping is the default synchronization method for the kloop.
752          * The 'sleep_us' field specifies how many microsconds to sleep for
753          * when there is no work to do, before doing another kloop iteration.
754          */
755         uint32_t        sleep_us;
756         uint32_t        pad1;
757 };
758
759 /* A CSB entry for the application --> kernel direction. */
760 struct nm_csb_atok {
761         uint32_t head;            /* AW+ KR+ the head of the appl netmap_ring */
762         uint32_t cur;             /* AW+ KR+ the cur of the appl netmap_ring */
763         uint32_t appl_need_kick;  /* AW+ KR+ kern --> appl notification enable */
764         uint32_t sync_flags;      /* AW+ KR+ the flags of the appl [tx|rx]sync() */
765         uint32_t pad[12];         /* pad to a 64 bytes cacheline */
766 };
767
768 /* A CSB entry for the application <-- kernel direction. */
769 struct nm_csb_ktoa {
770         uint32_t hwcur;           /* AR+ KW+ the hwcur of the kern netmap_kring */
771         uint32_t hwtail;          /* AR+ KW+ the hwtail of the kern netmap_kring */
772         uint32_t kern_need_kick;  /* AR+ KW+ appl-->kern notification enable */
773         uint32_t pad[13];
774 };
775
776 #ifdef __linux__
777
778 #ifdef __KERNEL__
779 #define nm_stst_barrier smp_wmb
780 #define nm_ldld_barrier smp_rmb
781 #define nm_stld_barrier smp_mb
782 #else  /* !__KERNEL__ */
783 static inline void nm_stst_barrier(void)
784 {
785         /* A memory barrier with release semantic has the combined
786          * effect of a store-store barrier and a load-store barrier,
787          * which is fine for us. */
788         __atomic_thread_fence(__ATOMIC_RELEASE);
789 }
790 static inline void nm_ldld_barrier(void)
791 {
792         /* A memory barrier with acquire semantic has the combined
793          * effect of a load-load barrier and a store-load barrier,
794          * which is fine for us. */
795         __atomic_thread_fence(__ATOMIC_ACQUIRE);
796 }
797 #endif /* !__KERNEL__ */
798
799 #elif defined(__FreeBSD__)
800
801 #ifdef _KERNEL
802 #define nm_stst_barrier atomic_thread_fence_rel
803 #define nm_ldld_barrier atomic_thread_fence_acq
804 #define nm_stld_barrier atomic_thread_fence_seq_cst
805 #else  /* !_KERNEL */
806 #include <stdatomic.h>
807 static inline void nm_stst_barrier(void)
808 {
809         atomic_thread_fence(memory_order_release);
810 }
811 static inline void nm_ldld_barrier(void)
812 {
813         atomic_thread_fence(memory_order_acquire);
814 }
815 #endif /* !_KERNEL */
816
817 #else  /* !__linux__ && !__FreeBSD__ */
818 #error "OS not supported"
819 #endif /* !__linux__ && !__FreeBSD__ */
820
821 /* Application side of sync-kloop: Write ring pointers (cur, head) to the CSB.
822  * This routine is coupled with sync_kloop_kernel_read(). */
823 static inline void
824 nm_sync_kloop_appl_write(struct nm_csb_atok *atok, uint32_t cur,
825                          uint32_t head)
826 {
827         /* Issue a first store-store barrier to make sure writes to the
828          * netmap ring do not overcome updates on atok->cur and atok->head. */
829         nm_stst_barrier();
830
831         /*
832          * We need to write cur and head to the CSB but we cannot do it atomically.
833          * There is no way we can prevent the host from reading the updated value
834          * of one of the two and the old value of the other. However, if we make
835          * sure that the host never reads a value of head more recent than the
836          * value of cur we are safe. We can allow the host to read a value of cur
837          * more recent than the value of head, since in the netmap ring cur can be
838          * ahead of head and cur cannot wrap around head because it must be behind
839          * tail. Inverting the order of writes below could instead result into the
840          * host to think head went ahead of cur, which would cause the sync
841          * prologue to fail.
842          *
843          * The following memory barrier scheme is used to make this happen:
844          *
845          *          Guest                Host
846          *
847          *          STORE(cur)           LOAD(head)
848          *          wmb() <----------->  rmb()
849          *          STORE(head)          LOAD(cur)
850          *
851          */
852         atok->cur = cur;
853         nm_stst_barrier();
854         atok->head = head;
855 }
856
857 /* Application side of sync-kloop: Read kring pointers (hwcur, hwtail) from
858  * the CSB. This routine is coupled with sync_kloop_kernel_write(). */
859 static inline void
860 nm_sync_kloop_appl_read(struct nm_csb_ktoa *ktoa, uint32_t *hwtail,
861                         uint32_t *hwcur)
862 {
863         /*
864          * We place a memory barrier to make sure that the update of hwtail never
865          * overtakes the update of hwcur.
866          * (see explanation in sync_kloop_kernel_write).
867          */
868         *hwtail = ktoa->hwtail;
869         nm_ldld_barrier();
870         *hwcur = ktoa->hwcur;
871
872         /* Make sure that loads from ktoa->hwtail and ktoa->hwcur are not delayed
873          * after the loads from the netmap ring. */
874         nm_ldld_barrier();
875 }
876
877 /*
878  * data for NETMAP_REQ_OPT_* options
879  */
880
881 struct nmreq_opt_sync_kloop_eventfds {
882         struct nmreq_option     nro_opt;        /* common header */
883         /* An array of N entries for bidirectional notifications between
884          * the kernel loop and the application. The number of entries and
885          * their order must agree with the CSB arrays passed in the
886          * NETMAP_REQ_OPT_CSB option. Each entry contains a file descriptor
887          * backed by an eventfd.
888          *
889          * If any of the 'ioeventfd' entries is < 0, the event loop uses
890          * the sleeping synchronization strategy (according to sleep_us),
891          * and keeps kern_need_kick always disabled.
892          * Each 'irqfd' can be < 0, and in that case the corresponding queue
893          * is never notified.
894          */
895         struct {
896                 /* Notifier for the application --> kernel loop direction. */
897                 int32_t ioeventfd;
898                 /* Notifier for the kernel loop --> application direction. */
899                 int32_t irqfd;
900         } eventfds[0];
901 };
902
903 struct nmreq_opt_sync_kloop_mode {
904         struct nmreq_option     nro_opt;        /* common header */
905 #define NM_OPT_SYNC_KLOOP_DIRECT_TX (1 << 0)
906 #define NM_OPT_SYNC_KLOOP_DIRECT_RX (1 << 1)
907         uint32_t mode;
908 };
909
910 struct nmreq_opt_extmem {
911         struct nmreq_option     nro_opt;        /* common header */
912         uint64_t                nro_usrptr;     /* (in) ptr to usr memory */
913         struct nmreq_pools_info nro_info;       /* (in/out) */
914 };
915
916 struct nmreq_opt_csb {
917         struct nmreq_option     nro_opt;
918
919         /* Array of CSB entries for application --> kernel communication
920          * (N entries). */
921         uint64_t                csb_atok;
922
923         /* Array of CSB entries for kernel --> application communication
924          * (N entries). */
925         uint64_t                csb_ktoa;
926 };
927
928 #endif /* _NET_NETMAP_H_ */