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