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