xref: /freebsd/sys/dev/netmap/netmap.c (revision 28f4385e45a2681c14bd04b83fe1796eaefe8265)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (C) 2011-2014 Matteo Landi
5  * Copyright (C) 2011-2016 Luigi Rizzo
6  * Copyright (C) 2011-2016 Giuseppe Lettieri
7  * Copyright (C) 2011-2016 Vincenzo Maffione
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  *   1. Redistributions of source code must retain the above copyright
14  *      notice, this list of conditions and the following disclaimer.
15  *   2. Redistributions in binary form must reproduce the above copyright
16  *      notice, this list of conditions and the following disclaimer in the
17  *      documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 
33 /*
34  * $FreeBSD$
35  *
36  * This module supports memory mapped access to network devices,
37  * see netmap(4).
38  *
39  * The module uses a large, memory pool allocated by the kernel
40  * and accessible as mmapped memory by multiple userspace threads/processes.
41  * The memory pool contains packet buffers and "netmap rings",
42  * i.e. user-accessible copies of the interface's queues.
43  *
44  * Access to the network card works like this:
45  * 1. a process/thread issues one or more open() on /dev/netmap, to create
46  *    select()able file descriptor on which events are reported.
47  * 2. on each descriptor, the process issues an ioctl() to identify
48  *    the interface that should report events to the file descriptor.
49  * 3. on each descriptor, the process issues an mmap() request to
50  *    map the shared memory region within the process' address space.
51  *    The list of interesting queues is indicated by a location in
52  *    the shared memory region.
53  * 4. using the functions in the netmap(4) userspace API, a process
54  *    can look up the occupation state of a queue, access memory buffers,
55  *    and retrieve received packets or enqueue packets to transmit.
56  * 5. using some ioctl()s the process can synchronize the userspace view
57  *    of the queue with the actual status in the kernel. This includes both
58  *    receiving the notification of new packets, and transmitting new
59  *    packets on the output interface.
60  * 6. select() or poll() can be used to wait for events on individual
61  *    transmit or receive queues (or all queues for a given interface).
62  *
63 
64 		SYNCHRONIZATION (USER)
65 
66 The netmap rings and data structures may be shared among multiple
67 user threads or even independent processes.
68 Any synchronization among those threads/processes is delegated
69 to the threads themselves. Only one thread at a time can be in
70 a system call on the same netmap ring. The OS does not enforce
71 this and only guarantees against system crashes in case of
72 invalid usage.
73 
74 		LOCKING (INTERNAL)
75 
76 Within the kernel, access to the netmap rings is protected as follows:
77 
78 - a spinlock on each ring, to handle producer/consumer races on
79   RX rings attached to the host stack (against multiple host
80   threads writing from the host stack to the same ring),
81   and on 'destination' rings attached to a VALE switch
82   (i.e. RX rings in VALE ports, and TX rings in NIC/host ports)
83   protecting multiple active senders for the same destination)
84 
85 - an atomic variable to guarantee that there is at most one
86   instance of *_*xsync() on the ring at any time.
87   For rings connected to user file
88   descriptors, an atomic_test_and_set() protects this, and the
89   lock on the ring is not actually used.
90   For NIC RX rings connected to a VALE switch, an atomic_test_and_set()
91   is also used to prevent multiple executions (the driver might indeed
92   already guarantee this).
93   For NIC TX rings connected to a VALE switch, the lock arbitrates
94   access to the queue (both when allocating buffers and when pushing
95   them out).
96 
97 - *xsync() should be protected against initializations of the card.
98   On FreeBSD most devices have the reset routine protected by
99   a RING lock (ixgbe, igb, em) or core lock (re). lem is missing
100   the RING protection on rx_reset(), this should be added.
101 
102   On linux there is an external lock on the tx path, which probably
103   also arbitrates access to the reset routine. XXX to be revised
104 
105 - a per-interface core_lock protecting access from the host stack
106   while interfaces may be detached from netmap mode.
107   XXX there should be no need for this lock if we detach the interfaces
108   only while they are down.
109 
110 
111 --- VALE SWITCH ---
112 
113 NMG_LOCK() serializes all modifications to switches and ports.
114 A switch cannot be deleted until all ports are gone.
115 
116 For each switch, an SX lock (RWlock on linux) protects
117 deletion of ports. When configuring or deleting a new port, the
118 lock is acquired in exclusive mode (after holding NMG_LOCK).
119 When forwarding, the lock is acquired in shared mode (without NMG_LOCK).
120 The lock is held throughout the entire forwarding cycle,
121 during which the thread may incur in a page fault.
122 Hence it is important that sleepable shared locks are used.
123 
124 On the rx ring, the per-port lock is grabbed initially to reserve
125 a number of slot in the ring, then the lock is released,
126 packets are copied from source to destination, and then
127 the lock is acquired again and the receive ring is updated.
128 (A similar thing is done on the tx ring for NIC and host stack
129 ports attached to the switch)
130 
131  */
132 
133 
134 /* --- internals ----
135  *
136  * Roadmap to the code that implements the above.
137  *
138  * > 1. a process/thread issues one or more open() on /dev/netmap, to create
139  * >    select()able file descriptor on which events are reported.
140  *
141  *  	Internally, we allocate a netmap_priv_d structure, that will be
142  *  	initialized on ioctl(NIOCREGIF). There is one netmap_priv_d
143  *  	structure for each open().
144  *
145  *      os-specific:
146  *  	    FreeBSD: see netmap_open() (netmap_freebsd.c)
147  *  	    linux:   see linux_netmap_open() (netmap_linux.c)
148  *
149  * > 2. on each descriptor, the process issues an ioctl() to identify
150  * >    the interface that should report events to the file descriptor.
151  *
152  * 	Implemented by netmap_ioctl(), NIOCREGIF case, with nmr->nr_cmd==0.
153  * 	Most important things happen in netmap_get_na() and
154  * 	netmap_do_regif(), called from there. Additional details can be
155  * 	found in the comments above those functions.
156  *
157  * 	In all cases, this action creates/takes-a-reference-to a
158  * 	netmap_*_adapter describing the port, and allocates a netmap_if
159  * 	and all necessary netmap rings, filling them with netmap buffers.
160  *
161  *      In this phase, the sync callbacks for each ring are set (these are used
162  *      in steps 5 and 6 below).  The callbacks depend on the type of adapter.
163  *      The adapter creation/initialization code puts them in the
164  * 	netmap_adapter (fields na->nm_txsync and na->nm_rxsync).  Then, they
165  * 	are copied from there to the netmap_kring's during netmap_do_regif(), by
166  * 	the nm_krings_create() callback.  All the nm_krings_create callbacks
167  * 	actually call netmap_krings_create() to perform this and the other
168  * 	common stuff. netmap_krings_create() also takes care of the host rings,
169  * 	if needed, by setting their sync callbacks appropriately.
170  *
171  * 	Additional actions depend on the kind of netmap_adapter that has been
172  * 	registered:
173  *
174  * 	- netmap_hw_adapter:  	     [netmap.c]
175  * 	     This is a system netdev/ifp with native netmap support.
176  * 	     The ifp is detached from the host stack by redirecting:
177  * 	       - transmissions (from the network stack) to netmap_transmit()
178  * 	       - receive notifications to the nm_notify() callback for
179  * 	         this adapter. The callback is normally netmap_notify(), unless
180  * 	         the ifp is attached to a bridge using bwrap, in which case it
181  * 	         is netmap_bwrap_intr_notify().
182  *
183  * 	- netmap_generic_adapter:      [netmap_generic.c]
184  * 	      A system netdev/ifp without native netmap support.
185  *
186  * 	(the decision about native/non native support is taken in
187  * 	 netmap_get_hw_na(), called by netmap_get_na())
188  *
189  * 	- netmap_vp_adapter 		[netmap_vale.c]
190  * 	      Returned by netmap_get_bdg_na().
191  * 	      This is a persistent or ephemeral VALE port. Ephemeral ports
192  * 	      are created on the fly if they don't already exist, and are
193  * 	      always attached to a bridge.
194  * 	      Persistent VALE ports must must be created separately, and i
195  * 	      then attached like normal NICs. The NIOCREGIF we are examining
196  * 	      will find them only if they had previosly been created and
197  * 	      attached (see VALE_CTL below).
198  *
199  * 	- netmap_pipe_adapter 	      [netmap_pipe.c]
200  * 	      Returned by netmap_get_pipe_na().
201  * 	      Both pipe ends are created, if they didn't already exist.
202  *
203  * 	- netmap_monitor_adapter      [netmap_monitor.c]
204  * 	      Returned by netmap_get_monitor_na().
205  * 	      If successful, the nm_sync callbacks of the monitored adapter
206  * 	      will be intercepted by the returned monitor.
207  *
208  * 	- netmap_bwrap_adapter	      [netmap_vale.c]
209  * 	      Cannot be obtained in this way, see VALE_CTL below
210  *
211  *
212  * 	os-specific:
213  * 	    linux: we first go through linux_netmap_ioctl() to
214  * 	           adapt the FreeBSD interface to the linux one.
215  *
216  *
217  * > 3. on each descriptor, the process issues an mmap() request to
218  * >    map the shared memory region within the process' address space.
219  * >    The list of interesting queues is indicated by a location in
220  * >    the shared memory region.
221  *
222  *      os-specific:
223  *  	    FreeBSD: netmap_mmap_single (netmap_freebsd.c).
224  *  	    linux:   linux_netmap_mmap (netmap_linux.c).
225  *
226  * > 4. using the functions in the netmap(4) userspace API, a process
227  * >    can look up the occupation state of a queue, access memory buffers,
228  * >    and retrieve received packets or enqueue packets to transmit.
229  *
230  * 	these actions do not involve the kernel.
231  *
232  * > 5. using some ioctl()s the process can synchronize the userspace view
233  * >    of the queue with the actual status in the kernel. This includes both
234  * >    receiving the notification of new packets, and transmitting new
235  * >    packets on the output interface.
236  *
237  * 	These are implemented in netmap_ioctl(), NIOCTXSYNC and NIOCRXSYNC
238  * 	cases. They invoke the nm_sync callbacks on the netmap_kring
239  * 	structures, as initialized in step 2 and maybe later modified
240  * 	by a monitor. Monitors, however, will always call the original
241  * 	callback before doing anything else.
242  *
243  *
244  * > 6. select() or poll() can be used to wait for events on individual
245  * >    transmit or receive queues (or all queues for a given interface).
246  *
247  * 	Implemented in netmap_poll(). This will call the same nm_sync()
248  * 	callbacks as in step 5 above.
249  *
250  * 	os-specific:
251  * 		linux: we first go through linux_netmap_poll() to adapt
252  * 		       the FreeBSD interface to the linux one.
253  *
254  *
255  *  ----  VALE_CTL -----
256  *
257  *  VALE switches are controlled by issuing a NIOCREGIF with a non-null
258  *  nr_cmd in the nmreq structure. These subcommands are handled by
259  *  netmap_bdg_ctl() in netmap_vale.c. Persistent VALE ports are created
260  *  and destroyed by issuing the NETMAP_BDG_NEWIF and NETMAP_BDG_DELIF
261  *  subcommands, respectively.
262  *
263  *  Any network interface known to the system (including a persistent VALE
264  *  port) can be attached to a VALE switch by issuing the
265  *  NETMAP_REQ_VALE_ATTACH command. After the attachment, persistent VALE ports
266  *  look exactly like ephemeral VALE ports (as created in step 2 above).  The
267  *  attachment of other interfaces, instead, requires the creation of a
268  *  netmap_bwrap_adapter.  Moreover, the attached interface must be put in
269  *  netmap mode. This may require the creation of a netmap_generic_adapter if
270  *  we have no native support for the interface, or if generic adapters have
271  *  been forced by sysctl.
272  *
273  *  Both persistent VALE ports and bwraps are handled by netmap_get_bdg_na(),
274  *  called by nm_bdg_ctl_attach(), and discriminated by the nm_bdg_attach()
275  *  callback.  In the case of the bwrap, the callback creates the
276  *  netmap_bwrap_adapter.  The initialization of the bwrap is then
277  *  completed by calling netmap_do_regif() on it, in the nm_bdg_ctl()
278  *  callback (netmap_bwrap_bdg_ctl in netmap_vale.c).
279  *  A generic adapter for the wrapped ifp will be created if needed, when
280  *  netmap_get_bdg_na() calls netmap_get_hw_na().
281  *
282  *
283  *  ---- DATAPATHS -----
284  *
285  *              -= SYSTEM DEVICE WITH NATIVE SUPPORT =-
286  *
287  *    na == NA(ifp) == netmap_hw_adapter created in DEVICE_netmap_attach()
288  *
289  *    - tx from netmap userspace:
290  *	 concurrently:
291  *           1) ioctl(NIOCTXSYNC)/netmap_poll() in process context
292  *                kring->nm_sync() == DEVICE_netmap_txsync()
293  *           2) device interrupt handler
294  *                na->nm_notify()  == netmap_notify()
295  *    - rx from netmap userspace:
296  *       concurrently:
297  *           1) ioctl(NIOCRXSYNC)/netmap_poll() in process context
298  *                kring->nm_sync() == DEVICE_netmap_rxsync()
299  *           2) device interrupt handler
300  *                na->nm_notify()  == netmap_notify()
301  *    - rx from host stack
302  *       concurrently:
303  *           1) host stack
304  *                netmap_transmit()
305  *                  na->nm_notify  == netmap_notify()
306  *           2) ioctl(NIOCRXSYNC)/netmap_poll() in process context
307  *                kring->nm_sync() == netmap_rxsync_from_host
308  *                  netmap_rxsync_from_host(na, NULL, NULL)
309  *    - tx to host stack
310  *           ioctl(NIOCTXSYNC)/netmap_poll() in process context
311  *             kring->nm_sync() == netmap_txsync_to_host
312  *               netmap_txsync_to_host(na)
313  *                 nm_os_send_up()
314  *                   FreeBSD: na->if_input() == ether_input()
315  *                   linux: netif_rx() with NM_MAGIC_PRIORITY_RX
316  *
317  *
318  *               -= SYSTEM DEVICE WITH GENERIC SUPPORT =-
319  *
320  *    na == NA(ifp) == generic_netmap_adapter created in generic_netmap_attach()
321  *
322  *    - tx from netmap userspace:
323  *       concurrently:
324  *           1) ioctl(NIOCTXSYNC)/netmap_poll() in process context
325  *               kring->nm_sync() == generic_netmap_txsync()
326  *                   nm_os_generic_xmit_frame()
327  *                       linux:   dev_queue_xmit() with NM_MAGIC_PRIORITY_TX
328  *                           ifp->ndo_start_xmit == generic_ndo_start_xmit()
329  *                               gna->save_start_xmit == orig. dev. start_xmit
330  *                       FreeBSD: na->if_transmit() == orig. dev if_transmit
331  *           2) generic_mbuf_destructor()
332  *                   na->nm_notify() == netmap_notify()
333  *    - rx from netmap userspace:
334  *           1) ioctl(NIOCRXSYNC)/netmap_poll() in process context
335  *               kring->nm_sync() == generic_netmap_rxsync()
336  *                   mbq_safe_dequeue()
337  *           2) device driver
338  *               generic_rx_handler()
339  *                   mbq_safe_enqueue()
340  *                   na->nm_notify() == netmap_notify()
341  *    - rx from host stack
342  *        FreeBSD: same as native
343  *        Linux: same as native except:
344  *           1) host stack
345  *               dev_queue_xmit() without NM_MAGIC_PRIORITY_TX
346  *                   ifp->ndo_start_xmit == generic_ndo_start_xmit()
347  *                       netmap_transmit()
348  *                           na->nm_notify() == netmap_notify()
349  *    - tx to host stack (same as native):
350  *
351  *
352  *                           -= VALE =-
353  *
354  *   INCOMING:
355  *
356  *      - VALE ports:
357  *          ioctl(NIOCTXSYNC)/netmap_poll() in process context
358  *              kring->nm_sync() == netmap_vp_txsync()
359  *
360  *      - system device with native support:
361  *         from cable:
362  *             interrupt
363  *                na->nm_notify() == netmap_bwrap_intr_notify(ring_nr != host ring)
364  *                     kring->nm_sync() == DEVICE_netmap_rxsync()
365  *                     netmap_vp_txsync()
366  *                     kring->nm_sync() == DEVICE_netmap_rxsync()
367  *         from host stack:
368  *             netmap_transmit()
369  *                na->nm_notify() == netmap_bwrap_intr_notify(ring_nr == host ring)
370  *                     kring->nm_sync() == netmap_rxsync_from_host()
371  *                     netmap_vp_txsync()
372  *
373  *      - system device with generic support:
374  *         from device driver:
375  *            generic_rx_handler()
376  *                na->nm_notify() == netmap_bwrap_intr_notify(ring_nr != host ring)
377  *                     kring->nm_sync() == generic_netmap_rxsync()
378  *                     netmap_vp_txsync()
379  *                     kring->nm_sync() == generic_netmap_rxsync()
380  *         from host stack:
381  *            netmap_transmit()
382  *                na->nm_notify() == netmap_bwrap_intr_notify(ring_nr == host ring)
383  *                     kring->nm_sync() == netmap_rxsync_from_host()
384  *                     netmap_vp_txsync()
385  *
386  *   (all cases) --> nm_bdg_flush()
387  *                      dest_na->nm_notify() == (see below)
388  *
389  *   OUTGOING:
390  *
391  *      - VALE ports:
392  *         concurrently:
393  *             1) ioctl(NIOCRXSYNC)/netmap_poll() in process context
394  *                    kring->nm_sync() == netmap_vp_rxsync()
395  *             2) from nm_bdg_flush()
396  *                    na->nm_notify() == netmap_notify()
397  *
398  *      - system device with native support:
399  *          to cable:
400  *             na->nm_notify() == netmap_bwrap_notify()
401  *                 netmap_vp_rxsync()
402  *                 kring->nm_sync() == DEVICE_netmap_txsync()
403  *                 netmap_vp_rxsync()
404  *          to host stack:
405  *                 netmap_vp_rxsync()
406  *                 kring->nm_sync() == netmap_txsync_to_host
407  *                 netmap_vp_rxsync_locked()
408  *
409  *      - system device with generic adapter:
410  *          to device driver:
411  *             na->nm_notify() == netmap_bwrap_notify()
412  *                 netmap_vp_rxsync()
413  *                 kring->nm_sync() == generic_netmap_txsync()
414  *                 netmap_vp_rxsync()
415  *          to host stack:
416  *                 netmap_vp_rxsync()
417  *                 kring->nm_sync() == netmap_txsync_to_host
418  *                 netmap_vp_rxsync()
419  *
420  */
421 
422 /*
423  * OS-specific code that is used only within this file.
424  * Other OS-specific code that must be accessed by drivers
425  * is present in netmap_kern.h
426  */
427 
428 #if defined(__FreeBSD__)
429 #include <sys/cdefs.h> /* prerequisite */
430 #include <sys/types.h>
431 #include <sys/errno.h>
432 #include <sys/param.h>	/* defines used in kernel.h */
433 #include <sys/kernel.h>	/* types used in module initialization */
434 #include <sys/conf.h>	/* cdevsw struct, UID, GID */
435 #include <sys/filio.h>	/* FIONBIO */
436 #include <sys/sockio.h>
437 #include <sys/socketvar.h>	/* struct socket */
438 #include <sys/malloc.h>
439 #include <sys/poll.h>
440 #include <sys/rwlock.h>
441 #include <sys/socket.h> /* sockaddrs */
442 #include <sys/selinfo.h>
443 #include <sys/sysctl.h>
444 #include <sys/jail.h>
445 #include <net/vnet.h>
446 #include <net/if.h>
447 #include <net/if_var.h>
448 #include <net/bpf.h>		/* BIOCIMMEDIATE */
449 #include <machine/bus.h>	/* bus_dmamap_* */
450 #include <sys/endian.h>
451 #include <sys/refcount.h>
452 #include <net/ethernet.h>	/* ETHER_BPF_MTAP */
453 
454 
455 #elif defined(linux)
456 
457 #include "bsd_glue.h"
458 
459 #elif defined(__APPLE__)
460 
461 #warning OSX support is only partial
462 #include "osx_glue.h"
463 
464 #elif defined (_WIN32)
465 
466 #include "win_glue.h"
467 
468 #else
469 
470 #error	Unsupported platform
471 
472 #endif /* unsupported */
473 
474 /*
475  * common headers
476  */
477 #include <net/netmap.h>
478 #include <dev/netmap/netmap_kern.h>
479 #include <dev/netmap/netmap_mem2.h>
480 
481 
482 /* user-controlled variables */
483 int netmap_verbose;
484 #ifdef CONFIG_NETMAP_DEBUG
485 int netmap_debug;
486 #endif /* CONFIG_NETMAP_DEBUG */
487 
488 static int netmap_no_timestamp; /* don't timestamp on rxsync */
489 int netmap_no_pendintr = 1;
490 int netmap_txsync_retry = 2;
491 static int netmap_fwd = 0;	/* force transparent forwarding */
492 
493 /*
494  * netmap_admode selects the netmap mode to use.
495  * Invalid values are reset to NETMAP_ADMODE_BEST
496  */
497 enum {	NETMAP_ADMODE_BEST = 0,	/* use native, fallback to generic */
498 	NETMAP_ADMODE_NATIVE,	/* either native or none */
499 	NETMAP_ADMODE_GENERIC,	/* force generic */
500 	NETMAP_ADMODE_LAST };
501 static int netmap_admode = NETMAP_ADMODE_BEST;
502 
503 /* netmap_generic_mit controls mitigation of RX notifications for
504  * the generic netmap adapter. The value is a time interval in
505  * nanoseconds. */
506 int netmap_generic_mit = 100*1000;
507 
508 /* We use by default netmap-aware qdiscs with generic netmap adapters,
509  * even if there can be a little performance hit with hardware NICs.
510  * However, using the qdisc is the safer approach, for two reasons:
511  * 1) it prevents non-fifo qdiscs to break the TX notification
512  *    scheme, which is based on mbuf destructors when txqdisc is
513  *    not used.
514  * 2) it makes it possible to transmit over software devices that
515  *    change skb->dev, like bridge, veth, ...
516  *
517  * Anyway users looking for the best performance should
518  * use native adapters.
519  */
520 #ifdef linux
521 int netmap_generic_txqdisc = 1;
522 #endif
523 
524 /* Default number of slots and queues for generic adapters. */
525 int netmap_generic_ringsize = 1024;
526 int netmap_generic_rings = 1;
527 
528 /* Non-zero to enable checksum offloading in NIC drivers */
529 int netmap_generic_hwcsum = 0;
530 
531 /* Non-zero if ptnet devices are allowed to use virtio-net headers. */
532 int ptnet_vnet_hdr = 1;
533 
534 /*
535  * SYSCTL calls are grouped between SYSBEGIN and SYSEND to be emulated
536  * in some other operating systems
537  */
538 SYSBEGIN(main_init);
539 
540 SYSCTL_DECL(_dev_netmap);
541 SYSCTL_NODE(_dev, OID_AUTO, netmap, CTLFLAG_RW, 0, "Netmap args");
542 SYSCTL_INT(_dev_netmap, OID_AUTO, verbose,
543 		CTLFLAG_RW, &netmap_verbose, 0, "Verbose mode");
544 #ifdef CONFIG_NETMAP_DEBUG
545 SYSCTL_INT(_dev_netmap, OID_AUTO, debug,
546 		CTLFLAG_RW, &netmap_debug, 0, "Debug messages");
547 #endif /* CONFIG_NETMAP_DEBUG */
548 SYSCTL_INT(_dev_netmap, OID_AUTO, no_timestamp,
549 		CTLFLAG_RW, &netmap_no_timestamp, 0, "no_timestamp");
550 SYSCTL_INT(_dev_netmap, OID_AUTO, no_pendintr, CTLFLAG_RW, &netmap_no_pendintr,
551 		0, "Always look for new received packets.");
552 SYSCTL_INT(_dev_netmap, OID_AUTO, txsync_retry, CTLFLAG_RW,
553 		&netmap_txsync_retry, 0, "Number of txsync loops in bridge's flush.");
554 
555 SYSCTL_INT(_dev_netmap, OID_AUTO, fwd, CTLFLAG_RW, &netmap_fwd, 0,
556 		"Force NR_FORWARD mode");
557 SYSCTL_INT(_dev_netmap, OID_AUTO, admode, CTLFLAG_RW, &netmap_admode, 0,
558 		"Adapter mode. 0 selects the best option available,"
559 		"1 forces native adapter, 2 forces emulated adapter");
560 SYSCTL_INT(_dev_netmap, OID_AUTO, generic_hwcsum, CTLFLAG_RW, &netmap_generic_hwcsum,
561 		0, "Hardware checksums. 0 to disable checksum generation by the NIC (default),"
562 		"1 to enable checksum generation by the NIC");
563 SYSCTL_INT(_dev_netmap, OID_AUTO, generic_mit, CTLFLAG_RW, &netmap_generic_mit,
564 		0, "RX notification interval in nanoseconds");
565 SYSCTL_INT(_dev_netmap, OID_AUTO, generic_ringsize, CTLFLAG_RW,
566 		&netmap_generic_ringsize, 0,
567 		"Number of per-ring slots for emulated netmap mode");
568 SYSCTL_INT(_dev_netmap, OID_AUTO, generic_rings, CTLFLAG_RW,
569 		&netmap_generic_rings, 0,
570 		"Number of TX/RX queues for emulated netmap adapters");
571 #ifdef linux
572 SYSCTL_INT(_dev_netmap, OID_AUTO, generic_txqdisc, CTLFLAG_RW,
573 		&netmap_generic_txqdisc, 0, "Use qdisc for generic adapters");
574 #endif
575 SYSCTL_INT(_dev_netmap, OID_AUTO, ptnet_vnet_hdr, CTLFLAG_RW, &ptnet_vnet_hdr,
576 		0, "Allow ptnet devices to use virtio-net headers");
577 
578 SYSEND;
579 
580 NMG_LOCK_T	netmap_global_lock;
581 
582 /*
583  * mark the ring as stopped, and run through the locks
584  * to make sure other users get to see it.
585  * stopped must be either NR_KR_STOPPED (for unbounded stop)
586  * of NR_KR_LOCKED (brief stop for mutual exclusion purposes)
587  */
588 static void
589 netmap_disable_ring(struct netmap_kring *kr, int stopped)
590 {
591 	nm_kr_stop(kr, stopped);
592 	// XXX check if nm_kr_stop is sufficient
593 	mtx_lock(&kr->q_lock);
594 	mtx_unlock(&kr->q_lock);
595 	nm_kr_put(kr);
596 }
597 
598 /* stop or enable a single ring */
599 void
600 netmap_set_ring(struct netmap_adapter *na, u_int ring_id, enum txrx t, int stopped)
601 {
602 	if (stopped)
603 		netmap_disable_ring(NMR(na, t)[ring_id], stopped);
604 	else
605 		NMR(na, t)[ring_id]->nkr_stopped = 0;
606 }
607 
608 
609 /* stop or enable all the rings of na */
610 void
611 netmap_set_all_rings(struct netmap_adapter *na, int stopped)
612 {
613 	int i;
614 	enum txrx t;
615 
616 	if (!nm_netmap_on(na))
617 		return;
618 
619 	for_rx_tx(t) {
620 		for (i = 0; i < netmap_real_rings(na, t); i++) {
621 			netmap_set_ring(na, i, t, stopped);
622 		}
623 	}
624 }
625 
626 /*
627  * Convenience function used in drivers.  Waits for current txsync()s/rxsync()s
628  * to finish and prevents any new one from starting.  Call this before turning
629  * netmap mode off, or before removing the hardware rings (e.g., on module
630  * onload).
631  */
632 void
633 netmap_disable_all_rings(struct ifnet *ifp)
634 {
635 	if (NM_NA_VALID(ifp)) {
636 		netmap_set_all_rings(NA(ifp), NM_KR_STOPPED);
637 	}
638 }
639 
640 /*
641  * Convenience function used in drivers.  Re-enables rxsync and txsync on the
642  * adapter's rings In linux drivers, this should be placed near each
643  * napi_enable().
644  */
645 void
646 netmap_enable_all_rings(struct ifnet *ifp)
647 {
648 	if (NM_NA_VALID(ifp)) {
649 		netmap_set_all_rings(NA(ifp), 0 /* enabled */);
650 	}
651 }
652 
653 void
654 netmap_make_zombie(struct ifnet *ifp)
655 {
656 	if (NM_NA_VALID(ifp)) {
657 		struct netmap_adapter *na = NA(ifp);
658 		netmap_set_all_rings(na, NM_KR_LOCKED);
659 		na->na_flags |= NAF_ZOMBIE;
660 		netmap_set_all_rings(na, 0);
661 	}
662 }
663 
664 void
665 netmap_undo_zombie(struct ifnet *ifp)
666 {
667 	if (NM_NA_VALID(ifp)) {
668 		struct netmap_adapter *na = NA(ifp);
669 		if (na->na_flags & NAF_ZOMBIE) {
670 			netmap_set_all_rings(na, NM_KR_LOCKED);
671 			na->na_flags &= ~NAF_ZOMBIE;
672 			netmap_set_all_rings(na, 0);
673 		}
674 	}
675 }
676 
677 /*
678  * generic bound_checking function
679  */
680 u_int
681 nm_bound_var(u_int *v, u_int dflt, u_int lo, u_int hi, const char *msg)
682 {
683 	u_int oldv = *v;
684 	const char *op = NULL;
685 
686 	if (dflt < lo)
687 		dflt = lo;
688 	if (dflt > hi)
689 		dflt = hi;
690 	if (oldv < lo) {
691 		*v = dflt;
692 		op = "Bump";
693 	} else if (oldv > hi) {
694 		*v = hi;
695 		op = "Clamp";
696 	}
697 	if (op && msg)
698 		nm_prinf("%s %s to %d (was %d)", op, msg, *v, oldv);
699 	return *v;
700 }
701 
702 
703 /*
704  * packet-dump function, user-supplied or static buffer.
705  * The destination buffer must be at least 30+4*len
706  */
707 const char *
708 nm_dump_buf(char *p, int len, int lim, char *dst)
709 {
710 	static char _dst[8192];
711 	int i, j, i0;
712 	static char hex[] ="0123456789abcdef";
713 	char *o;	/* output position */
714 
715 #define P_HI(x)	hex[((x) & 0xf0)>>4]
716 #define P_LO(x)	hex[((x) & 0xf)]
717 #define P_C(x)	((x) >= 0x20 && (x) <= 0x7e ? (x) : '.')
718 	if (!dst)
719 		dst = _dst;
720 	if (lim <= 0 || lim > len)
721 		lim = len;
722 	o = dst;
723 	sprintf(o, "buf 0x%p len %d lim %d\n", p, len, lim);
724 	o += strlen(o);
725 	/* hexdump routine */
726 	for (i = 0; i < lim; ) {
727 		sprintf(o, "%5d: ", i);
728 		o += strlen(o);
729 		memset(o, ' ', 48);
730 		i0 = i;
731 		for (j=0; j < 16 && i < lim; i++, j++) {
732 			o[j*3] = P_HI(p[i]);
733 			o[j*3+1] = P_LO(p[i]);
734 		}
735 		i = i0;
736 		for (j=0; j < 16 && i < lim; i++, j++)
737 			o[j + 48] = P_C(p[i]);
738 		o[j+48] = '\n';
739 		o += j+49;
740 	}
741 	*o = '\0';
742 #undef P_HI
743 #undef P_LO
744 #undef P_C
745 	return dst;
746 }
747 
748 
749 /*
750  * Fetch configuration from the device, to cope with dynamic
751  * reconfigurations after loading the module.
752  */
753 /* call with NMG_LOCK held */
754 int
755 netmap_update_config(struct netmap_adapter *na)
756 {
757 	struct nm_config_info info;
758 
759 	bzero(&info, sizeof(info));
760 	if (na->nm_config == NULL ||
761 	    na->nm_config(na, &info)) {
762 		/* take whatever we had at init time */
763 		info.num_tx_rings = na->num_tx_rings;
764 		info.num_tx_descs = na->num_tx_desc;
765 		info.num_rx_rings = na->num_rx_rings;
766 		info.num_rx_descs = na->num_rx_desc;
767 		info.rx_buf_maxsize = na->rx_buf_maxsize;
768 	}
769 
770 	if (na->num_tx_rings == info.num_tx_rings &&
771 	    na->num_tx_desc == info.num_tx_descs &&
772 	    na->num_rx_rings == info.num_rx_rings &&
773 	    na->num_rx_desc == info.num_rx_descs &&
774 	    na->rx_buf_maxsize == info.rx_buf_maxsize)
775 		return 0; /* nothing changed */
776 	if (na->active_fds == 0) {
777 		na->num_tx_rings = info.num_tx_rings;
778 		na->num_tx_desc = info.num_tx_descs;
779 		na->num_rx_rings = info.num_rx_rings;
780 		na->num_rx_desc = info.num_rx_descs;
781 		na->rx_buf_maxsize = info.rx_buf_maxsize;
782 		if (netmap_verbose)
783 			nm_prinf("configuration changed for %s: txring %d x %d, "
784 				"rxring %d x %d, rxbufsz %d",
785 				na->name, na->num_tx_rings, na->num_tx_desc,
786 				na->num_rx_rings, na->num_rx_desc, na->rx_buf_maxsize);
787 		return 0;
788 	}
789 	nm_prerr("WARNING: configuration changed for %s while active: "
790 		"txring %d x %d, rxring %d x %d, rxbufsz %d",
791 		na->name, info.num_tx_rings, info.num_tx_descs,
792 		info.num_rx_rings, info.num_rx_descs,
793 		info.rx_buf_maxsize);
794 	return 1;
795 }
796 
797 /* nm_sync callbacks for the host rings */
798 static int netmap_txsync_to_host(struct netmap_kring *kring, int flags);
799 static int netmap_rxsync_from_host(struct netmap_kring *kring, int flags);
800 
801 /* create the krings array and initialize the fields common to all adapters.
802  * The array layout is this:
803  *
804  *                    +----------+
805  * na->tx_rings ----->|          | \
806  *                    |          |  } na->num_tx_ring
807  *                    |          | /
808  *                    +----------+
809  *                    |          |    host tx kring
810  * na->rx_rings ----> +----------+
811  *                    |          | \
812  *                    |          |  } na->num_rx_rings
813  *                    |          | /
814  *                    +----------+
815  *                    |          |    host rx kring
816  *                    +----------+
817  * na->tailroom ----->|          | \
818  *                    |          |  } tailroom bytes
819  *                    |          | /
820  *                    +----------+
821  *
822  * Note: for compatibility, host krings are created even when not needed.
823  * The tailroom space is currently used by vale ports for allocating leases.
824  */
825 /* call with NMG_LOCK held */
826 int
827 netmap_krings_create(struct netmap_adapter *na, u_int tailroom)
828 {
829 	u_int i, len, ndesc;
830 	struct netmap_kring *kring;
831 	u_int n[NR_TXRX];
832 	enum txrx t;
833 
834 	if (na->tx_rings != NULL) {
835 		if (netmap_debug & NM_DEBUG_ON)
836 			nm_prerr("warning: krings were already created");
837 		return 0;
838 	}
839 
840 	/* account for the (possibly fake) host rings */
841 	n[NR_TX] = netmap_all_rings(na, NR_TX);
842 	n[NR_RX] = netmap_all_rings(na, NR_RX);
843 
844 	len = (n[NR_TX] + n[NR_RX]) *
845 		(sizeof(struct netmap_kring) + sizeof(struct netmap_kring *))
846 		+ tailroom;
847 
848 	na->tx_rings = nm_os_malloc((size_t)len);
849 	if (na->tx_rings == NULL) {
850 		nm_prerr("Cannot allocate krings");
851 		return ENOMEM;
852 	}
853 	na->rx_rings = na->tx_rings + n[NR_TX];
854 	na->tailroom = na->rx_rings + n[NR_RX];
855 
856 	/* link the krings in the krings array */
857 	kring = (struct netmap_kring *)((char *)na->tailroom + tailroom);
858 	for (i = 0; i < n[NR_TX] + n[NR_RX]; i++) {
859 		na->tx_rings[i] = kring;
860 		kring++;
861 	}
862 
863 	/*
864 	 * All fields in krings are 0 except the one initialized below.
865 	 * but better be explicit on important kring fields.
866 	 */
867 	for_rx_tx(t) {
868 		ndesc = nma_get_ndesc(na, t);
869 		for (i = 0; i < n[t]; i++) {
870 			kring = NMR(na, t)[i];
871 			bzero(kring, sizeof(*kring));
872 			kring->na = na;
873 			kring->notify_na = na;
874 			kring->ring_id = i;
875 			kring->tx = t;
876 			kring->nkr_num_slots = ndesc;
877 			kring->nr_mode = NKR_NETMAP_OFF;
878 			kring->nr_pending_mode = NKR_NETMAP_OFF;
879 			if (i < nma_get_nrings(na, t)) {
880 				kring->nm_sync = (t == NR_TX ? na->nm_txsync : na->nm_rxsync);
881 			} else {
882 				if (!(na->na_flags & NAF_HOST_RINGS))
883 					kring->nr_kflags |= NKR_FAKERING;
884 				kring->nm_sync = (t == NR_TX ?
885 						netmap_txsync_to_host:
886 						netmap_rxsync_from_host);
887 			}
888 			kring->nm_notify = na->nm_notify;
889 			kring->rhead = kring->rcur = kring->nr_hwcur = 0;
890 			/*
891 			 * IMPORTANT: Always keep one slot empty.
892 			 */
893 			kring->rtail = kring->nr_hwtail = (t == NR_TX ? ndesc - 1 : 0);
894 			snprintf(kring->name, sizeof(kring->name) - 1, "%s %s%d", na->name,
895 					nm_txrx2str(t), i);
896 			ND("ktx %s h %d c %d t %d",
897 				kring->name, kring->rhead, kring->rcur, kring->rtail);
898 			mtx_init(&kring->q_lock, (t == NR_TX ? "nm_txq_lock" : "nm_rxq_lock"), NULL, MTX_DEF);
899 			nm_os_selinfo_init(&kring->si);
900 		}
901 		nm_os_selinfo_init(&na->si[t]);
902 	}
903 
904 
905 	return 0;
906 }
907 
908 
909 /* undo the actions performed by netmap_krings_create */
910 /* call with NMG_LOCK held */
911 void
912 netmap_krings_delete(struct netmap_adapter *na)
913 {
914 	struct netmap_kring **kring = na->tx_rings;
915 	enum txrx t;
916 
917 	if (na->tx_rings == NULL) {
918 		if (netmap_debug & NM_DEBUG_ON)
919 			nm_prerr("warning: krings were already deleted");
920 		return;
921 	}
922 
923 	for_rx_tx(t)
924 		nm_os_selinfo_uninit(&na->si[t]);
925 
926 	/* we rely on the krings layout described above */
927 	for ( ; kring != na->tailroom; kring++) {
928 		mtx_destroy(&(*kring)->q_lock);
929 		nm_os_selinfo_uninit(&(*kring)->si);
930 	}
931 	nm_os_free(na->tx_rings);
932 	na->tx_rings = na->rx_rings = na->tailroom = NULL;
933 }
934 
935 
936 /*
937  * Destructor for NIC ports. They also have an mbuf queue
938  * on the rings connected to the host so we need to purge
939  * them first.
940  */
941 /* call with NMG_LOCK held */
942 void
943 netmap_hw_krings_delete(struct netmap_adapter *na)
944 {
945 	u_int lim = netmap_real_rings(na, NR_RX), i;
946 
947 	for (i = nma_get_nrings(na, NR_RX); i < lim; i++) {
948 		struct mbq *q = &NMR(na, NR_RX)[i]->rx_queue;
949 		ND("destroy sw mbq with len %d", mbq_len(q));
950 		mbq_purge(q);
951 		mbq_safe_fini(q);
952 	}
953 	netmap_krings_delete(na);
954 }
955 
956 static void
957 netmap_mem_drop(struct netmap_adapter *na)
958 {
959 	int last = netmap_mem_deref(na->nm_mem, na);
960 	/* if the native allocator had been overrided on regif,
961 	 * restore it now and drop the temporary one
962 	 */
963 	if (last && na->nm_mem_prev) {
964 		netmap_mem_put(na->nm_mem);
965 		na->nm_mem = na->nm_mem_prev;
966 		na->nm_mem_prev = NULL;
967 	}
968 }
969 
970 /*
971  * Undo everything that was done in netmap_do_regif(). In particular,
972  * call nm_register(ifp,0) to stop netmap mode on the interface and
973  * revert to normal operation.
974  */
975 /* call with NMG_LOCK held */
976 static void netmap_unset_ringid(struct netmap_priv_d *);
977 static void netmap_krings_put(struct netmap_priv_d *);
978 void
979 netmap_do_unregif(struct netmap_priv_d *priv)
980 {
981 	struct netmap_adapter *na = priv->np_na;
982 
983 	NMG_LOCK_ASSERT();
984 	na->active_fds--;
985 	/* unset nr_pending_mode and possibly release exclusive mode */
986 	netmap_krings_put(priv);
987 
988 #ifdef	WITH_MONITOR
989 	/* XXX check whether we have to do something with monitor
990 	 * when rings change nr_mode. */
991 	if (na->active_fds <= 0) {
992 		/* walk through all the rings and tell any monitor
993 		 * that the port is going to exit netmap mode
994 		 */
995 		netmap_monitor_stop(na);
996 	}
997 #endif
998 
999 	if (na->active_fds <= 0 || nm_kring_pending(priv)) {
1000 		na->nm_register(na, 0);
1001 	}
1002 
1003 	/* delete rings and buffers that are no longer needed */
1004 	netmap_mem_rings_delete(na);
1005 
1006 	if (na->active_fds <= 0) {	/* last instance */
1007 		/*
1008 		 * (TO CHECK) We enter here
1009 		 * when the last reference to this file descriptor goes
1010 		 * away. This means we cannot have any pending poll()
1011 		 * or interrupt routine operating on the structure.
1012 		 * XXX The file may be closed in a thread while
1013 		 * another thread is using it.
1014 		 * Linux keeps the file opened until the last reference
1015 		 * by any outstanding ioctl/poll or mmap is gone.
1016 		 * FreeBSD does not track mmap()s (but we do) and
1017 		 * wakes up any sleeping poll(). Need to check what
1018 		 * happens if the close() occurs while a concurrent
1019 		 * syscall is running.
1020 		 */
1021 		if (netmap_debug & NM_DEBUG_ON)
1022 			nm_prinf("deleting last instance for %s", na->name);
1023 
1024 		if (nm_netmap_on(na)) {
1025 			nm_prerr("BUG: netmap on while going to delete the krings");
1026 		}
1027 
1028 		na->nm_krings_delete(na);
1029 	}
1030 
1031 	/* possibily decrement counter of tx_si/rx_si users */
1032 	netmap_unset_ringid(priv);
1033 	/* delete the nifp */
1034 	netmap_mem_if_delete(na, priv->np_nifp);
1035 	/* drop the allocator */
1036 	netmap_mem_drop(na);
1037 	/* mark the priv as unregistered */
1038 	priv->np_na = NULL;
1039 	priv->np_nifp = NULL;
1040 }
1041 
1042 struct netmap_priv_d*
1043 netmap_priv_new(void)
1044 {
1045 	struct netmap_priv_d *priv;
1046 
1047 	priv = nm_os_malloc(sizeof(struct netmap_priv_d));
1048 	if (priv == NULL)
1049 		return NULL;
1050 	priv->np_refs = 1;
1051 	nm_os_get_module();
1052 	return priv;
1053 }
1054 
1055 /*
1056  * Destructor of the netmap_priv_d, called when the fd is closed
1057  * Action: undo all the things done by NIOCREGIF,
1058  * On FreeBSD we need to track whether there are active mmap()s,
1059  * and we use np_active_mmaps for that. On linux, the field is always 0.
1060  * Return: 1 if we can free priv, 0 otherwise.
1061  *
1062  */
1063 /* call with NMG_LOCK held */
1064 void
1065 netmap_priv_delete(struct netmap_priv_d *priv)
1066 {
1067 	struct netmap_adapter *na = priv->np_na;
1068 
1069 	/* number of active references to this fd */
1070 	if (--priv->np_refs > 0) {
1071 		return;
1072 	}
1073 	nm_os_put_module();
1074 	if (na) {
1075 		netmap_do_unregif(priv);
1076 	}
1077 	netmap_unget_na(na, priv->np_ifp);
1078 	bzero(priv, sizeof(*priv));	/* for safety */
1079 	nm_os_free(priv);
1080 }
1081 
1082 
1083 /* call with NMG_LOCK *not* held */
1084 void
1085 netmap_dtor(void *data)
1086 {
1087 	struct netmap_priv_d *priv = data;
1088 
1089 	NMG_LOCK();
1090 	netmap_priv_delete(priv);
1091 	NMG_UNLOCK();
1092 }
1093 
1094 
1095 /*
1096  * Handlers for synchronization of the rings from/to the host stack.
1097  * These are associated to a network interface and are just another
1098  * ring pair managed by userspace.
1099  *
1100  * Netmap also supports transparent forwarding (NS_FORWARD and NR_FORWARD
1101  * flags):
1102  *
1103  * - Before releasing buffers on hw RX rings, the application can mark
1104  *   them with the NS_FORWARD flag. During the next RXSYNC or poll(), they
1105  *   will be forwarded to the host stack, similarly to what happened if
1106  *   the application moved them to the host TX ring.
1107  *
1108  * - Before releasing buffers on the host RX ring, the application can
1109  *   mark them with the NS_FORWARD flag. During the next RXSYNC or poll(),
1110  *   they will be forwarded to the hw TX rings, saving the application
1111  *   from doing the same task in user-space.
1112  *
1113  * Transparent fowarding can be enabled per-ring, by setting the NR_FORWARD
1114  * flag, or globally with the netmap_fwd sysctl.
1115  *
1116  * The transfer NIC --> host is relatively easy, just encapsulate
1117  * into mbufs and we are done. The host --> NIC side is slightly
1118  * harder because there might not be room in the tx ring so it
1119  * might take a while before releasing the buffer.
1120  */
1121 
1122 
1123 /*
1124  * Pass a whole queue of mbufs to the host stack as coming from 'dst'
1125  * We do not need to lock because the queue is private.
1126  * After this call the queue is empty.
1127  */
1128 static void
1129 netmap_send_up(struct ifnet *dst, struct mbq *q)
1130 {
1131 	struct mbuf *m;
1132 	struct mbuf *head = NULL, *prev = NULL;
1133 
1134 	/* Send packets up, outside the lock; head/prev machinery
1135 	 * is only useful for Windows. */
1136 	while ((m = mbq_dequeue(q)) != NULL) {
1137 		if (netmap_debug & NM_DEBUG_HOST)
1138 			nm_prinf("sending up pkt %p size %d", m, MBUF_LEN(m));
1139 		prev = nm_os_send_up(dst, m, prev);
1140 		if (head == NULL)
1141 			head = prev;
1142 	}
1143 	if (head)
1144 		nm_os_send_up(dst, NULL, head);
1145 	mbq_fini(q);
1146 }
1147 
1148 
1149 /*
1150  * Scan the buffers from hwcur to ring->head, and put a copy of those
1151  * marked NS_FORWARD (or all of them if forced) into a queue of mbufs.
1152  * Drop remaining packets in the unlikely event
1153  * of an mbuf shortage.
1154  */
1155 static void
1156 netmap_grab_packets(struct netmap_kring *kring, struct mbq *q, int force)
1157 {
1158 	u_int const lim = kring->nkr_num_slots - 1;
1159 	u_int const head = kring->rhead;
1160 	u_int n;
1161 	struct netmap_adapter *na = kring->na;
1162 
1163 	for (n = kring->nr_hwcur; n != head; n = nm_next(n, lim)) {
1164 		struct mbuf *m;
1165 		struct netmap_slot *slot = &kring->ring->slot[n];
1166 
1167 		if ((slot->flags & NS_FORWARD) == 0 && !force)
1168 			continue;
1169 		if (slot->len < 14 || slot->len > NETMAP_BUF_SIZE(na)) {
1170 			RD(5, "bad pkt at %d len %d", n, slot->len);
1171 			continue;
1172 		}
1173 		slot->flags &= ~NS_FORWARD; // XXX needed ?
1174 		/* XXX TODO: adapt to the case of a multisegment packet */
1175 		m = m_devget(NMB(na, slot), slot->len, 0, na->ifp, NULL);
1176 
1177 		if (m == NULL)
1178 			break;
1179 		mbq_enqueue(q, m);
1180 	}
1181 }
1182 
1183 static inline int
1184 _nm_may_forward(struct netmap_kring *kring)
1185 {
1186 	return	((netmap_fwd || kring->ring->flags & NR_FORWARD) &&
1187 		 kring->na->na_flags & NAF_HOST_RINGS &&
1188 		 kring->tx == NR_RX);
1189 }
1190 
1191 static inline int
1192 nm_may_forward_up(struct netmap_kring *kring)
1193 {
1194 	return	_nm_may_forward(kring) &&
1195 		 kring->ring_id != kring->na->num_rx_rings;
1196 }
1197 
1198 static inline int
1199 nm_may_forward_down(struct netmap_kring *kring, int sync_flags)
1200 {
1201 	return	_nm_may_forward(kring) &&
1202 		 (sync_flags & NAF_CAN_FORWARD_DOWN) &&
1203 		 kring->ring_id == kring->na->num_rx_rings;
1204 }
1205 
1206 /*
1207  * Send to the NIC rings packets marked NS_FORWARD between
1208  * kring->nr_hwcur and kring->rhead.
1209  * Called under kring->rx_queue.lock on the sw rx ring.
1210  *
1211  * It can only be called if the user opened all the TX hw rings,
1212  * see NAF_CAN_FORWARD_DOWN flag.
1213  * We can touch the TX netmap rings (slots, head and cur) since
1214  * we are in poll/ioctl system call context, and the application
1215  * is not supposed to touch the ring (using a different thread)
1216  * during the execution of the system call.
1217  */
1218 static u_int
1219 netmap_sw_to_nic(struct netmap_adapter *na)
1220 {
1221 	struct netmap_kring *kring = na->rx_rings[na->num_rx_rings];
1222 	struct netmap_slot *rxslot = kring->ring->slot;
1223 	u_int i, rxcur = kring->nr_hwcur;
1224 	u_int const head = kring->rhead;
1225 	u_int const src_lim = kring->nkr_num_slots - 1;
1226 	u_int sent = 0;
1227 
1228 	/* scan rings to find space, then fill as much as possible */
1229 	for (i = 0; i < na->num_tx_rings; i++) {
1230 		struct netmap_kring *kdst = na->tx_rings[i];
1231 		struct netmap_ring *rdst = kdst->ring;
1232 		u_int const dst_lim = kdst->nkr_num_slots - 1;
1233 
1234 		/* XXX do we trust ring or kring->rcur,rtail ? */
1235 		for (; rxcur != head && !nm_ring_empty(rdst);
1236 		     rxcur = nm_next(rxcur, src_lim) ) {
1237 			struct netmap_slot *src, *dst, tmp;
1238 			u_int dst_head = rdst->head;
1239 
1240 			src = &rxslot[rxcur];
1241 			if ((src->flags & NS_FORWARD) == 0 && !netmap_fwd)
1242 				continue;
1243 
1244 			sent++;
1245 
1246 			dst = &rdst->slot[dst_head];
1247 
1248 			tmp = *src;
1249 
1250 			src->buf_idx = dst->buf_idx;
1251 			src->flags = NS_BUF_CHANGED;
1252 
1253 			dst->buf_idx = tmp.buf_idx;
1254 			dst->len = tmp.len;
1255 			dst->flags = NS_BUF_CHANGED;
1256 
1257 			rdst->head = rdst->cur = nm_next(dst_head, dst_lim);
1258 		}
1259 		/* if (sent) XXX txsync ? it would be just an optimization */
1260 	}
1261 	return sent;
1262 }
1263 
1264 
1265 /*
1266  * netmap_txsync_to_host() passes packets up. We are called from a
1267  * system call in user process context, and the only contention
1268  * can be among multiple user threads erroneously calling
1269  * this routine concurrently.
1270  */
1271 static int
1272 netmap_txsync_to_host(struct netmap_kring *kring, int flags)
1273 {
1274 	struct netmap_adapter *na = kring->na;
1275 	u_int const lim = kring->nkr_num_slots - 1;
1276 	u_int const head = kring->rhead;
1277 	struct mbq q;
1278 
1279 	/* Take packets from hwcur to head and pass them up.
1280 	 * Force hwcur = head since netmap_grab_packets() stops at head
1281 	 */
1282 	mbq_init(&q);
1283 	netmap_grab_packets(kring, &q, 1 /* force */);
1284 	ND("have %d pkts in queue", mbq_len(&q));
1285 	kring->nr_hwcur = head;
1286 	kring->nr_hwtail = head + lim;
1287 	if (kring->nr_hwtail > lim)
1288 		kring->nr_hwtail -= lim + 1;
1289 
1290 	netmap_send_up(na->ifp, &q);
1291 	return 0;
1292 }
1293 
1294 
1295 /*
1296  * rxsync backend for packets coming from the host stack.
1297  * They have been put in kring->rx_queue by netmap_transmit().
1298  * We protect access to the kring using kring->rx_queue.lock
1299  *
1300  * also moves to the nic hw rings any packet the user has marked
1301  * for transparent-mode forwarding, then sets the NR_FORWARD
1302  * flag in the kring to let the caller push them out
1303  */
1304 static int
1305 netmap_rxsync_from_host(struct netmap_kring *kring, int flags)
1306 {
1307 	struct netmap_adapter *na = kring->na;
1308 	struct netmap_ring *ring = kring->ring;
1309 	u_int nm_i, n;
1310 	u_int const lim = kring->nkr_num_slots - 1;
1311 	u_int const head = kring->rhead;
1312 	int ret = 0;
1313 	struct mbq *q = &kring->rx_queue, fq;
1314 
1315 	mbq_init(&fq); /* fq holds packets to be freed */
1316 
1317 	mbq_lock(q);
1318 
1319 	/* First part: import newly received packets */
1320 	n = mbq_len(q);
1321 	if (n) { /* grab packets from the queue */
1322 		struct mbuf *m;
1323 		uint32_t stop_i;
1324 
1325 		nm_i = kring->nr_hwtail;
1326 		stop_i = nm_prev(kring->nr_hwcur, lim);
1327 		while ( nm_i != stop_i && (m = mbq_dequeue(q)) != NULL ) {
1328 			int len = MBUF_LEN(m);
1329 			struct netmap_slot *slot = &ring->slot[nm_i];
1330 
1331 			m_copydata(m, 0, len, NMB(na, slot));
1332 			ND("nm %d len %d", nm_i, len);
1333 			if (netmap_debug & NM_DEBUG_HOST)
1334 				nm_prinf("%s", nm_dump_buf(NMB(na, slot),len, 128, NULL));
1335 
1336 			slot->len = len;
1337 			slot->flags = 0;
1338 			nm_i = nm_next(nm_i, lim);
1339 			mbq_enqueue(&fq, m);
1340 		}
1341 		kring->nr_hwtail = nm_i;
1342 	}
1343 
1344 	/*
1345 	 * Second part: skip past packets that userspace has released.
1346 	 */
1347 	nm_i = kring->nr_hwcur;
1348 	if (nm_i != head) { /* something was released */
1349 		if (nm_may_forward_down(kring, flags)) {
1350 			ret = netmap_sw_to_nic(na);
1351 			if (ret > 0) {
1352 				kring->nr_kflags |= NR_FORWARD;
1353 				ret = 0;
1354 			}
1355 		}
1356 		kring->nr_hwcur = head;
1357 	}
1358 
1359 	mbq_unlock(q);
1360 
1361 	mbq_purge(&fq);
1362 	mbq_fini(&fq);
1363 
1364 	return ret;
1365 }
1366 
1367 
1368 /* Get a netmap adapter for the port.
1369  *
1370  * If it is possible to satisfy the request, return 0
1371  * with *na containing the netmap adapter found.
1372  * Otherwise return an error code, with *na containing NULL.
1373  *
1374  * When the port is attached to a bridge, we always return
1375  * EBUSY.
1376  * Otherwise, if the port is already bound to a file descriptor,
1377  * then we unconditionally return the existing adapter into *na.
1378  * In all the other cases, we return (into *na) either native,
1379  * generic or NULL, according to the following table:
1380  *
1381  *					native_support
1382  * active_fds   dev.netmap.admode         YES     NO
1383  * -------------------------------------------------------
1384  *    >0              *                 NA(ifp) NA(ifp)
1385  *
1386  *     0        NETMAP_ADMODE_BEST      NATIVE  GENERIC
1387  *     0        NETMAP_ADMODE_NATIVE    NATIVE   NULL
1388  *     0        NETMAP_ADMODE_GENERIC   GENERIC GENERIC
1389  *
1390  */
1391 static void netmap_hw_dtor(struct netmap_adapter *); /* needed by NM_IS_NATIVE() */
1392 int
1393 netmap_get_hw_na(struct ifnet *ifp, struct netmap_mem_d *nmd, struct netmap_adapter **na)
1394 {
1395 	/* generic support */
1396 	int i = netmap_admode;	/* Take a snapshot. */
1397 	struct netmap_adapter *prev_na;
1398 	int error = 0;
1399 
1400 	*na = NULL; /* default */
1401 
1402 	/* reset in case of invalid value */
1403 	if (i < NETMAP_ADMODE_BEST || i >= NETMAP_ADMODE_LAST)
1404 		i = netmap_admode = NETMAP_ADMODE_BEST;
1405 
1406 	if (NM_NA_VALID(ifp)) {
1407 		prev_na = NA(ifp);
1408 		/* If an adapter already exists, return it if
1409 		 * there are active file descriptors or if
1410 		 * netmap is not forced to use generic
1411 		 * adapters.
1412 		 */
1413 		if (NETMAP_OWNED_BY_ANY(prev_na)
1414 			|| i != NETMAP_ADMODE_GENERIC
1415 			|| prev_na->na_flags & NAF_FORCE_NATIVE
1416 #ifdef WITH_PIPES
1417 			/* ugly, but we cannot allow an adapter switch
1418 			 * if some pipe is referring to this one
1419 			 */
1420 			|| prev_na->na_next_pipe > 0
1421 #endif
1422 		) {
1423 			*na = prev_na;
1424 			goto assign_mem;
1425 		}
1426 	}
1427 
1428 	/* If there isn't native support and netmap is not allowed
1429 	 * to use generic adapters, we cannot satisfy the request.
1430 	 */
1431 	if (!NM_IS_NATIVE(ifp) && i == NETMAP_ADMODE_NATIVE)
1432 		return EOPNOTSUPP;
1433 
1434 	/* Otherwise, create a generic adapter and return it,
1435 	 * saving the previously used netmap adapter, if any.
1436 	 *
1437 	 * Note that here 'prev_na', if not NULL, MUST be a
1438 	 * native adapter, and CANNOT be a generic one. This is
1439 	 * true because generic adapters are created on demand, and
1440 	 * destroyed when not used anymore. Therefore, if the adapter
1441 	 * currently attached to an interface 'ifp' is generic, it
1442 	 * must be that
1443 	 * (NA(ifp)->active_fds > 0 || NETMAP_OWNED_BY_KERN(NA(ifp))).
1444 	 * Consequently, if NA(ifp) is generic, we will enter one of
1445 	 * the branches above. This ensures that we never override
1446 	 * a generic adapter with another generic adapter.
1447 	 */
1448 	error = generic_netmap_attach(ifp);
1449 	if (error)
1450 		return error;
1451 
1452 	*na = NA(ifp);
1453 
1454 assign_mem:
1455 	if (nmd != NULL && !((*na)->na_flags & NAF_MEM_OWNER) &&
1456 	    (*na)->active_fds == 0 && ((*na)->nm_mem != nmd)) {
1457 		(*na)->nm_mem_prev = (*na)->nm_mem;
1458 		(*na)->nm_mem = netmap_mem_get(nmd);
1459 	}
1460 
1461 	return 0;
1462 }
1463 
1464 /*
1465  * MUST BE CALLED UNDER NMG_LOCK()
1466  *
1467  * Get a refcounted reference to a netmap adapter attached
1468  * to the interface specified by req.
1469  * This is always called in the execution of an ioctl().
1470  *
1471  * Return ENXIO if the interface specified by the request does
1472  * not exist, ENOTSUP if netmap is not supported by the interface,
1473  * EBUSY if the interface is already attached to a bridge,
1474  * EINVAL if parameters are invalid, ENOMEM if needed resources
1475  * could not be allocated.
1476  * If successful, hold a reference to the netmap adapter.
1477  *
1478  * If the interface specified by req is a system one, also keep
1479  * a reference to it and return a valid *ifp.
1480  */
1481 int
1482 netmap_get_na(struct nmreq_header *hdr,
1483 	      struct netmap_adapter **na, struct ifnet **ifp,
1484 	      struct netmap_mem_d *nmd, int create)
1485 {
1486 	struct nmreq_register *req = (struct nmreq_register *)(uintptr_t)hdr->nr_body;
1487 	int error = 0;
1488 	struct netmap_adapter *ret = NULL;
1489 	int nmd_ref = 0;
1490 
1491 	*na = NULL;     /* default return value */
1492 	*ifp = NULL;
1493 
1494 	if (hdr->nr_reqtype != NETMAP_REQ_REGISTER) {
1495 		return EINVAL;
1496 	}
1497 
1498 	if (req->nr_mode == NR_REG_PIPE_MASTER ||
1499 			req->nr_mode == NR_REG_PIPE_SLAVE) {
1500 		/* Do not accept deprecated pipe modes. */
1501 		nm_prerr("Deprecated pipe nr_mode, use xx{yy or xx}yy syntax");
1502 		return EINVAL;
1503 	}
1504 
1505 	NMG_LOCK_ASSERT();
1506 
1507 	/* if the request contain a memid, try to find the
1508 	 * corresponding memory region
1509 	 */
1510 	if (nmd == NULL && req->nr_mem_id) {
1511 		nmd = netmap_mem_find(req->nr_mem_id);
1512 		if (nmd == NULL)
1513 			return EINVAL;
1514 		/* keep the rereference */
1515 		nmd_ref = 1;
1516 	}
1517 
1518 	/* We cascade through all possible types of netmap adapter.
1519 	 * All netmap_get_*_na() functions return an error and an na,
1520 	 * with the following combinations:
1521 	 *
1522 	 * error    na
1523 	 *   0	   NULL		type doesn't match
1524 	 *  !0	   NULL		type matches, but na creation/lookup failed
1525 	 *   0	  !NULL		type matches and na created/found
1526 	 *  !0    !NULL		impossible
1527 	 */
1528 	error = netmap_get_null_na(hdr, na, nmd, create);
1529 	if (error || *na != NULL)
1530 		goto out;
1531 
1532 	/* try to see if this is a monitor port */
1533 	error = netmap_get_monitor_na(hdr, na, nmd, create);
1534 	if (error || *na != NULL)
1535 		goto out;
1536 
1537 	/* try to see if this is a pipe port */
1538 	error = netmap_get_pipe_na(hdr, na, nmd, create);
1539 	if (error || *na != NULL)
1540 		goto out;
1541 
1542 	/* try to see if this is a bridge port */
1543 	error = netmap_get_vale_na(hdr, na, nmd, create);
1544 	if (error)
1545 		goto out;
1546 
1547 	if (*na != NULL) /* valid match in netmap_get_bdg_na() */
1548 		goto out;
1549 
1550 	/*
1551 	 * This must be a hardware na, lookup the name in the system.
1552 	 * Note that by hardware we actually mean "it shows up in ifconfig".
1553 	 * This may still be a tap, a veth/epair, or even a
1554 	 * persistent VALE port.
1555 	 */
1556 	*ifp = ifunit_ref(hdr->nr_name);
1557 	if (*ifp == NULL) {
1558 		error = ENXIO;
1559 		goto out;
1560 	}
1561 
1562 	error = netmap_get_hw_na(*ifp, nmd, &ret);
1563 	if (error)
1564 		goto out;
1565 
1566 	*na = ret;
1567 	netmap_adapter_get(ret);
1568 
1569 out:
1570 	if (error) {
1571 		if (ret)
1572 			netmap_adapter_put(ret);
1573 		if (*ifp) {
1574 			if_rele(*ifp);
1575 			*ifp = NULL;
1576 		}
1577 	}
1578 	if (nmd_ref)
1579 		netmap_mem_put(nmd);
1580 
1581 	return error;
1582 }
1583 
1584 /* undo netmap_get_na() */
1585 void
1586 netmap_unget_na(struct netmap_adapter *na, struct ifnet *ifp)
1587 {
1588 	if (ifp)
1589 		if_rele(ifp);
1590 	if (na)
1591 		netmap_adapter_put(na);
1592 }
1593 
1594 
1595 #define NM_FAIL_ON(t) do {						\
1596 	if (unlikely(t)) {						\
1597 		RD(5, "%s: fail '" #t "' "				\
1598 			"h %d c %d t %d "				\
1599 			"rh %d rc %d rt %d "				\
1600 			"hc %d ht %d",					\
1601 			kring->name,					\
1602 			head, cur, ring->tail,				\
1603 			kring->rhead, kring->rcur, kring->rtail,	\
1604 			kring->nr_hwcur, kring->nr_hwtail);		\
1605 		return kring->nkr_num_slots;				\
1606 	}								\
1607 } while (0)
1608 
1609 /*
1610  * validate parameters on entry for *_txsync()
1611  * Returns ring->cur if ok, or something >= kring->nkr_num_slots
1612  * in case of error.
1613  *
1614  * rhead, rcur and rtail=hwtail are stored from previous round.
1615  * hwcur is the next packet to send to the ring.
1616  *
1617  * We want
1618  *    hwcur <= *rhead <= head <= cur <= tail = *rtail <= hwtail
1619  *
1620  * hwcur, rhead, rtail and hwtail are reliable
1621  */
1622 u_int
1623 nm_txsync_prologue(struct netmap_kring *kring, struct netmap_ring *ring)
1624 {
1625 	u_int head = ring->head; /* read only once */
1626 	u_int cur = ring->cur; /* read only once */
1627 	u_int n = kring->nkr_num_slots;
1628 
1629 	ND(5, "%s kcur %d ktail %d head %d cur %d tail %d",
1630 		kring->name,
1631 		kring->nr_hwcur, kring->nr_hwtail,
1632 		ring->head, ring->cur, ring->tail);
1633 #if 1 /* kernel sanity checks; but we can trust the kring. */
1634 	NM_FAIL_ON(kring->nr_hwcur >= n || kring->rhead >= n ||
1635 	    kring->rtail >= n ||  kring->nr_hwtail >= n);
1636 #endif /* kernel sanity checks */
1637 	/*
1638 	 * user sanity checks. We only use head,
1639 	 * A, B, ... are possible positions for head:
1640 	 *
1641 	 *  0    A  rhead   B  rtail   C  n-1
1642 	 *  0    D  rtail   E  rhead   F  n-1
1643 	 *
1644 	 * B, F, D are valid. A, C, E are wrong
1645 	 */
1646 	if (kring->rtail >= kring->rhead) {
1647 		/* want rhead <= head <= rtail */
1648 		NM_FAIL_ON(head < kring->rhead || head > kring->rtail);
1649 		/* and also head <= cur <= rtail */
1650 		NM_FAIL_ON(cur < head || cur > kring->rtail);
1651 	} else { /* here rtail < rhead */
1652 		/* we need head outside rtail .. rhead */
1653 		NM_FAIL_ON(head > kring->rtail && head < kring->rhead);
1654 
1655 		/* two cases now: head <= rtail or head >= rhead  */
1656 		if (head <= kring->rtail) {
1657 			/* want head <= cur <= rtail */
1658 			NM_FAIL_ON(cur < head || cur > kring->rtail);
1659 		} else { /* head >= rhead */
1660 			/* cur must be outside rtail..head */
1661 			NM_FAIL_ON(cur > kring->rtail && cur < head);
1662 		}
1663 	}
1664 	if (ring->tail != kring->rtail) {
1665 		RD(5, "%s tail overwritten was %d need %d", kring->name,
1666 			ring->tail, kring->rtail);
1667 		ring->tail = kring->rtail;
1668 	}
1669 	kring->rhead = head;
1670 	kring->rcur = cur;
1671 	return head;
1672 }
1673 
1674 
1675 /*
1676  * validate parameters on entry for *_rxsync()
1677  * Returns ring->head if ok, kring->nkr_num_slots on error.
1678  *
1679  * For a valid configuration,
1680  * hwcur <= head <= cur <= tail <= hwtail
1681  *
1682  * We only consider head and cur.
1683  * hwcur and hwtail are reliable.
1684  *
1685  */
1686 u_int
1687 nm_rxsync_prologue(struct netmap_kring *kring, struct netmap_ring *ring)
1688 {
1689 	uint32_t const n = kring->nkr_num_slots;
1690 	uint32_t head, cur;
1691 
1692 	ND(5,"%s kc %d kt %d h %d c %d t %d",
1693 		kring->name,
1694 		kring->nr_hwcur, kring->nr_hwtail,
1695 		ring->head, ring->cur, ring->tail);
1696 	/*
1697 	 * Before storing the new values, we should check they do not
1698 	 * move backwards. However:
1699 	 * - head is not an issue because the previous value is hwcur;
1700 	 * - cur could in principle go back, however it does not matter
1701 	 *   because we are processing a brand new rxsync()
1702 	 */
1703 	cur = kring->rcur = ring->cur;	/* read only once */
1704 	head = kring->rhead = ring->head;	/* read only once */
1705 #if 1 /* kernel sanity checks */
1706 	NM_FAIL_ON(kring->nr_hwcur >= n || kring->nr_hwtail >= n);
1707 #endif /* kernel sanity checks */
1708 	/* user sanity checks */
1709 	if (kring->nr_hwtail >= kring->nr_hwcur) {
1710 		/* want hwcur <= rhead <= hwtail */
1711 		NM_FAIL_ON(head < kring->nr_hwcur || head > kring->nr_hwtail);
1712 		/* and also rhead <= rcur <= hwtail */
1713 		NM_FAIL_ON(cur < head || cur > kring->nr_hwtail);
1714 	} else {
1715 		/* we need rhead outside hwtail..hwcur */
1716 		NM_FAIL_ON(head < kring->nr_hwcur && head > kring->nr_hwtail);
1717 		/* two cases now: head <= hwtail or head >= hwcur  */
1718 		if (head <= kring->nr_hwtail) {
1719 			/* want head <= cur <= hwtail */
1720 			NM_FAIL_ON(cur < head || cur > kring->nr_hwtail);
1721 		} else {
1722 			/* cur must be outside hwtail..head */
1723 			NM_FAIL_ON(cur < head && cur > kring->nr_hwtail);
1724 		}
1725 	}
1726 	if (ring->tail != kring->rtail) {
1727 		RD(5, "%s tail overwritten was %d need %d",
1728 			kring->name,
1729 			ring->tail, kring->rtail);
1730 		ring->tail = kring->rtail;
1731 	}
1732 	return head;
1733 }
1734 
1735 
1736 /*
1737  * Error routine called when txsync/rxsync detects an error.
1738  * Can't do much more than resetting head = cur = hwcur, tail = hwtail
1739  * Return 1 on reinit.
1740  *
1741  * This routine is only called by the upper half of the kernel.
1742  * It only reads hwcur (which is changed only by the upper half, too)
1743  * and hwtail (which may be changed by the lower half, but only on
1744  * a tx ring and only to increase it, so any error will be recovered
1745  * on the next call). For the above, we don't strictly need to call
1746  * it under lock.
1747  */
1748 int
1749 netmap_ring_reinit(struct netmap_kring *kring)
1750 {
1751 	struct netmap_ring *ring = kring->ring;
1752 	u_int i, lim = kring->nkr_num_slots - 1;
1753 	int errors = 0;
1754 
1755 	// XXX KASSERT nm_kr_tryget
1756 	RD(10, "called for %s", kring->name);
1757 	// XXX probably wrong to trust userspace
1758 	kring->rhead = ring->head;
1759 	kring->rcur  = ring->cur;
1760 	kring->rtail = ring->tail;
1761 
1762 	if (ring->cur > lim)
1763 		errors++;
1764 	if (ring->head > lim)
1765 		errors++;
1766 	if (ring->tail > lim)
1767 		errors++;
1768 	for (i = 0; i <= lim; i++) {
1769 		u_int idx = ring->slot[i].buf_idx;
1770 		u_int len = ring->slot[i].len;
1771 		if (idx < 2 || idx >= kring->na->na_lut.objtotal) {
1772 			RD(5, "bad index at slot %d idx %d len %d ", i, idx, len);
1773 			ring->slot[i].buf_idx = 0;
1774 			ring->slot[i].len = 0;
1775 		} else if (len > NETMAP_BUF_SIZE(kring->na)) {
1776 			ring->slot[i].len = 0;
1777 			RD(5, "bad len at slot %d idx %d len %d", i, idx, len);
1778 		}
1779 	}
1780 	if (errors) {
1781 		RD(10, "total %d errors", errors);
1782 		RD(10, "%s reinit, cur %d -> %d tail %d -> %d",
1783 			kring->name,
1784 			ring->cur, kring->nr_hwcur,
1785 			ring->tail, kring->nr_hwtail);
1786 		ring->head = kring->rhead = kring->nr_hwcur;
1787 		ring->cur  = kring->rcur  = kring->nr_hwcur;
1788 		ring->tail = kring->rtail = kring->nr_hwtail;
1789 	}
1790 	return (errors ? 1 : 0);
1791 }
1792 
1793 /* interpret the ringid and flags fields of an nmreq, by translating them
1794  * into a pair of intervals of ring indices:
1795  *
1796  * [priv->np_txqfirst, priv->np_txqlast) and
1797  * [priv->np_rxqfirst, priv->np_rxqlast)
1798  *
1799  */
1800 int
1801 netmap_interp_ringid(struct netmap_priv_d *priv, uint32_t nr_mode,
1802 			uint16_t nr_ringid, uint64_t nr_flags)
1803 {
1804 	struct netmap_adapter *na = priv->np_na;
1805 	int excluded_direction[] = { NR_TX_RINGS_ONLY, NR_RX_RINGS_ONLY };
1806 	enum txrx t;
1807 	u_int j;
1808 
1809 	for_rx_tx(t) {
1810 		if (nr_flags & excluded_direction[t]) {
1811 			priv->np_qfirst[t] = priv->np_qlast[t] = 0;
1812 			continue;
1813 		}
1814 		switch (nr_mode) {
1815 		case NR_REG_ALL_NIC:
1816 		case NR_REG_NULL:
1817 			priv->np_qfirst[t] = 0;
1818 			priv->np_qlast[t] = nma_get_nrings(na, t);
1819 			ND("ALL/PIPE: %s %d %d", nm_txrx2str(t),
1820 				priv->np_qfirst[t], priv->np_qlast[t]);
1821 			break;
1822 		case NR_REG_SW:
1823 		case NR_REG_NIC_SW:
1824 			if (!(na->na_flags & NAF_HOST_RINGS)) {
1825 				nm_prerr("host rings not supported");
1826 				return EINVAL;
1827 			}
1828 			priv->np_qfirst[t] = (nr_mode == NR_REG_SW ?
1829 				nma_get_nrings(na, t) : 0);
1830 			priv->np_qlast[t] = netmap_all_rings(na, t);
1831 			ND("%s: %s %d %d", nr_mode == NR_REG_SW ? "SW" : "NIC+SW",
1832 				nm_txrx2str(t),
1833 				priv->np_qfirst[t], priv->np_qlast[t]);
1834 			break;
1835 		case NR_REG_ONE_NIC:
1836 			if (nr_ringid >= na->num_tx_rings &&
1837 					nr_ringid >= na->num_rx_rings) {
1838 				nm_prerr("invalid ring id %d", nr_ringid);
1839 				return EINVAL;
1840 			}
1841 			/* if not enough rings, use the first one */
1842 			j = nr_ringid;
1843 			if (j >= nma_get_nrings(na, t))
1844 				j = 0;
1845 			priv->np_qfirst[t] = j;
1846 			priv->np_qlast[t] = j + 1;
1847 			ND("ONE_NIC: %s %d %d", nm_txrx2str(t),
1848 				priv->np_qfirst[t], priv->np_qlast[t]);
1849 			break;
1850 		default:
1851 			nm_prerr("invalid regif type %d", nr_mode);
1852 			return EINVAL;
1853 		}
1854 	}
1855 	priv->np_flags = nr_flags;
1856 
1857 	/* Allow transparent forwarding mode in the host --> nic
1858 	 * direction only if all the TX hw rings have been opened. */
1859 	if (priv->np_qfirst[NR_TX] == 0 &&
1860 			priv->np_qlast[NR_TX] >= na->num_tx_rings) {
1861 		priv->np_sync_flags |= NAF_CAN_FORWARD_DOWN;
1862 	}
1863 
1864 	if (netmap_verbose) {
1865 		nm_prinf("%s: tx [%d,%d) rx [%d,%d) id %d",
1866 			na->name,
1867 			priv->np_qfirst[NR_TX],
1868 			priv->np_qlast[NR_TX],
1869 			priv->np_qfirst[NR_RX],
1870 			priv->np_qlast[NR_RX],
1871 			nr_ringid);
1872 	}
1873 	return 0;
1874 }
1875 
1876 
1877 /*
1878  * Set the ring ID. For devices with a single queue, a request
1879  * for all rings is the same as a single ring.
1880  */
1881 static int
1882 netmap_set_ringid(struct netmap_priv_d *priv, uint32_t nr_mode,
1883 		uint16_t nr_ringid, uint64_t nr_flags)
1884 {
1885 	struct netmap_adapter *na = priv->np_na;
1886 	int error;
1887 	enum txrx t;
1888 
1889 	error = netmap_interp_ringid(priv, nr_mode, nr_ringid, nr_flags);
1890 	if (error) {
1891 		return error;
1892 	}
1893 
1894 	priv->np_txpoll = (nr_flags & NR_NO_TX_POLL) ? 0 : 1;
1895 
1896 	/* optimization: count the users registered for more than
1897 	 * one ring, which are the ones sleeping on the global queue.
1898 	 * The default netmap_notify() callback will then
1899 	 * avoid signaling the global queue if nobody is using it
1900 	 */
1901 	for_rx_tx(t) {
1902 		if (nm_si_user(priv, t))
1903 			na->si_users[t]++;
1904 	}
1905 	return 0;
1906 }
1907 
1908 static void
1909 netmap_unset_ringid(struct netmap_priv_d *priv)
1910 {
1911 	struct netmap_adapter *na = priv->np_na;
1912 	enum txrx t;
1913 
1914 	for_rx_tx(t) {
1915 		if (nm_si_user(priv, t))
1916 			na->si_users[t]--;
1917 		priv->np_qfirst[t] = priv->np_qlast[t] = 0;
1918 	}
1919 	priv->np_flags = 0;
1920 	priv->np_txpoll = 0;
1921 	priv->np_kloop_state = 0;
1922 }
1923 
1924 
1925 /* Set the nr_pending_mode for the requested rings.
1926  * If requested, also try to get exclusive access to the rings, provided
1927  * the rings we want to bind are not exclusively owned by a previous bind.
1928  */
1929 static int
1930 netmap_krings_get(struct netmap_priv_d *priv)
1931 {
1932 	struct netmap_adapter *na = priv->np_na;
1933 	u_int i;
1934 	struct netmap_kring *kring;
1935 	int excl = (priv->np_flags & NR_EXCLUSIVE);
1936 	enum txrx t;
1937 
1938 	if (netmap_debug & NM_DEBUG_ON)
1939 		nm_prinf("%s: grabbing tx [%d, %d) rx [%d, %d)",
1940 			na->name,
1941 			priv->np_qfirst[NR_TX],
1942 			priv->np_qlast[NR_TX],
1943 			priv->np_qfirst[NR_RX],
1944 			priv->np_qlast[NR_RX]);
1945 
1946 	/* first round: check that all the requested rings
1947 	 * are neither alread exclusively owned, nor we
1948 	 * want exclusive ownership when they are already in use
1949 	 */
1950 	for_rx_tx(t) {
1951 		for (i = priv->np_qfirst[t]; i < priv->np_qlast[t]; i++) {
1952 			kring = NMR(na, t)[i];
1953 			if ((kring->nr_kflags & NKR_EXCLUSIVE) ||
1954 			    (kring->users && excl))
1955 			{
1956 				ND("ring %s busy", kring->name);
1957 				return EBUSY;
1958 			}
1959 		}
1960 	}
1961 
1962 	/* second round: increment usage count (possibly marking them
1963 	 * as exclusive) and set the nr_pending_mode
1964 	 */
1965 	for_rx_tx(t) {
1966 		for (i = priv->np_qfirst[t]; i < priv->np_qlast[t]; i++) {
1967 			kring = NMR(na, t)[i];
1968 			kring->users++;
1969 			if (excl)
1970 				kring->nr_kflags |= NKR_EXCLUSIVE;
1971 	                kring->nr_pending_mode = NKR_NETMAP_ON;
1972 		}
1973 	}
1974 
1975 	return 0;
1976 
1977 }
1978 
1979 /* Undo netmap_krings_get(). This is done by clearing the exclusive mode
1980  * if was asked on regif, and unset the nr_pending_mode if we are the
1981  * last users of the involved rings. */
1982 static void
1983 netmap_krings_put(struct netmap_priv_d *priv)
1984 {
1985 	struct netmap_adapter *na = priv->np_na;
1986 	u_int i;
1987 	struct netmap_kring *kring;
1988 	int excl = (priv->np_flags & NR_EXCLUSIVE);
1989 	enum txrx t;
1990 
1991 	ND("%s: releasing tx [%d, %d) rx [%d, %d)",
1992 			na->name,
1993 			priv->np_qfirst[NR_TX],
1994 			priv->np_qlast[NR_TX],
1995 			priv->np_qfirst[NR_RX],
1996 			priv->np_qlast[MR_RX]);
1997 
1998 	for_rx_tx(t) {
1999 		for (i = priv->np_qfirst[t]; i < priv->np_qlast[t]; i++) {
2000 			kring = NMR(na, t)[i];
2001 			if (excl)
2002 				kring->nr_kflags &= ~NKR_EXCLUSIVE;
2003 			kring->users--;
2004 			if (kring->users == 0)
2005 				kring->nr_pending_mode = NKR_NETMAP_OFF;
2006 		}
2007 	}
2008 }
2009 
2010 static int
2011 nm_priv_rx_enabled(struct netmap_priv_d *priv)
2012 {
2013 	return (priv->np_qfirst[NR_RX] != priv->np_qlast[NR_RX]);
2014 }
2015 
2016 /* Validate the CSB entries for both directions (atok and ktoa).
2017  * To be called under NMG_LOCK(). */
2018 static int
2019 netmap_csb_validate(struct netmap_priv_d *priv, struct nmreq_opt_csb *csbo)
2020 {
2021 	struct nm_csb_atok *csb_atok_base =
2022 		(struct nm_csb_atok *)(uintptr_t)csbo->csb_atok;
2023 	struct nm_csb_ktoa *csb_ktoa_base =
2024 		(struct nm_csb_ktoa *)(uintptr_t)csbo->csb_ktoa;
2025 	enum txrx t;
2026 	int num_rings[NR_TXRX], tot_rings;
2027 	size_t entry_size[2];
2028 	void *csb_start[2];
2029 	int i;
2030 
2031 	if (priv->np_kloop_state & NM_SYNC_KLOOP_RUNNING) {
2032 		nm_prerr("Cannot update CSB while kloop is running");
2033 		return EBUSY;
2034 	}
2035 
2036 	tot_rings = 0;
2037 	for_rx_tx(t) {
2038 		num_rings[t] = priv->np_qlast[t] - priv->np_qfirst[t];
2039 		tot_rings += num_rings[t];
2040 	}
2041 	if (tot_rings <= 0)
2042 		return 0;
2043 
2044 	if (!(priv->np_flags & NR_EXCLUSIVE)) {
2045 		nm_prerr("CSB mode requires NR_EXCLUSIVE");
2046 		return EINVAL;
2047 	}
2048 
2049 	entry_size[0] = sizeof(*csb_atok_base);
2050 	entry_size[1] = sizeof(*csb_ktoa_base);
2051 	csb_start[0] = (void *)csb_atok_base;
2052 	csb_start[1] = (void *)csb_ktoa_base;
2053 
2054 	for (i = 0; i < 2; i++) {
2055 		/* On Linux we could use access_ok() to simplify
2056 		 * the validation. However, the advantage of
2057 		 * this approach is that it works also on
2058 		 * FreeBSD. */
2059 		size_t csb_size = tot_rings * entry_size[i];
2060 		void *tmp;
2061 		int err;
2062 
2063 		if ((uintptr_t)csb_start[i] & (entry_size[i]-1)) {
2064 			nm_prerr("Unaligned CSB address");
2065 			return EINVAL;
2066 		}
2067 
2068 		tmp = nm_os_malloc(csb_size);
2069 		if (!tmp)
2070 			return ENOMEM;
2071 		if (i == 0) {
2072 			/* Application --> kernel direction. */
2073 			err = copyin(csb_start[i], tmp, csb_size);
2074 		} else {
2075 			/* Kernel --> application direction. */
2076 			memset(tmp, 0, csb_size);
2077 			err = copyout(tmp, csb_start[i], csb_size);
2078 		}
2079 		nm_os_free(tmp);
2080 		if (err) {
2081 			nm_prerr("Invalid CSB address");
2082 			return err;
2083 		}
2084 	}
2085 
2086 	priv->np_csb_atok_base = csb_atok_base;
2087 	priv->np_csb_ktoa_base = csb_ktoa_base;
2088 
2089 	/* Initialize the CSB. */
2090 	for_rx_tx(t) {
2091 		for (i = 0; i < num_rings[t]; i++) {
2092 			struct netmap_kring *kring =
2093 				NMR(priv->np_na, t)[i + priv->np_qfirst[t]];
2094 			struct nm_csb_atok *csb_atok = csb_atok_base + i;
2095 			struct nm_csb_ktoa *csb_ktoa = csb_ktoa_base + i;
2096 
2097 			if (t == NR_RX) {
2098 				csb_atok += num_rings[NR_TX];
2099 				csb_ktoa += num_rings[NR_TX];
2100 			}
2101 
2102 			CSB_WRITE(csb_atok, head, kring->rhead);
2103 			CSB_WRITE(csb_atok, cur, kring->rcur);
2104 			CSB_WRITE(csb_atok, appl_need_kick, 1);
2105 			CSB_WRITE(csb_atok, sync_flags, 1);
2106 			CSB_WRITE(csb_ktoa, hwcur, kring->nr_hwcur);
2107 			CSB_WRITE(csb_ktoa, hwtail, kring->nr_hwtail);
2108 			CSB_WRITE(csb_ktoa, kern_need_kick, 1);
2109 
2110 			nm_prinf("csb_init for kring %s: head %u, cur %u, "
2111 				"hwcur %u, hwtail %u", kring->name,
2112 				kring->rhead, kring->rcur, kring->nr_hwcur,
2113 				kring->nr_hwtail);
2114 		}
2115 	}
2116 
2117 	return 0;
2118 }
2119 
2120 /* Ensure that the netmap adapter can support the given MTU.
2121  * @return EINVAL if the na cannot be set to mtu, 0 otherwise.
2122  */
2123 int
2124 netmap_buf_size_validate(const struct netmap_adapter *na, unsigned mtu) {
2125 	unsigned nbs = NETMAP_BUF_SIZE(na);
2126 
2127 	if (mtu <= na->rx_buf_maxsize) {
2128 		/* The MTU fits a single NIC slot. We only
2129 		 * Need to check that netmap buffers are
2130 		 * large enough to hold an MTU. NS_MOREFRAG
2131 		 * cannot be used in this case. */
2132 		if (nbs < mtu) {
2133 			nm_prerr("error: netmap buf size (%u) "
2134 				 "< device MTU (%u)", nbs, mtu);
2135 			return EINVAL;
2136 		}
2137 	} else {
2138 		/* More NIC slots may be needed to receive
2139 		 * or transmit a single packet. Check that
2140 		 * the adapter supports NS_MOREFRAG and that
2141 		 * netmap buffers are large enough to hold
2142 		 * the maximum per-slot size. */
2143 		if (!(na->na_flags & NAF_MOREFRAG)) {
2144 			nm_prerr("error: large MTU (%d) needed "
2145 				 "but %s does not support "
2146 				 "NS_MOREFRAG", mtu,
2147 				 na->ifp->if_xname);
2148 			return EINVAL;
2149 		} else if (nbs < na->rx_buf_maxsize) {
2150 			nm_prerr("error: using NS_MOREFRAG on "
2151 				 "%s requires netmap buf size "
2152 				 ">= %u", na->ifp->if_xname,
2153 				 na->rx_buf_maxsize);
2154 			return EINVAL;
2155 		} else {
2156 			nm_prinf("info: netmap application on "
2157 				 "%s needs to support "
2158 				 "NS_MOREFRAG "
2159 				 "(MTU=%u,netmap_buf_size=%u)",
2160 				 na->ifp->if_xname, mtu, nbs);
2161 		}
2162 	}
2163 	return 0;
2164 }
2165 
2166 
2167 /*
2168  * possibly move the interface to netmap-mode.
2169  * If success it returns a pointer to netmap_if, otherwise NULL.
2170  * This must be called with NMG_LOCK held.
2171  *
2172  * The following na callbacks are called in the process:
2173  *
2174  * na->nm_config()			[by netmap_update_config]
2175  * (get current number and size of rings)
2176  *
2177  *  	We have a generic one for linux (netmap_linux_config).
2178  *  	The bwrap has to override this, since it has to forward
2179  *  	the request to the wrapped adapter (netmap_bwrap_config).
2180  *
2181  *
2182  * na->nm_krings_create()
2183  * (create and init the krings array)
2184  *
2185  * 	One of the following:
2186  *
2187  *	* netmap_hw_krings_create, 			(hw ports)
2188  *		creates the standard layout for the krings
2189  * 		and adds the mbq (used for the host rings).
2190  *
2191  * 	* netmap_vp_krings_create			(VALE ports)
2192  * 		add leases and scratchpads
2193  *
2194  * 	* netmap_pipe_krings_create			(pipes)
2195  * 		create the krings and rings of both ends and
2196  * 		cross-link them
2197  *
2198  *      * netmap_monitor_krings_create 			(monitors)
2199  *      	avoid allocating the mbq
2200  *
2201  *      * netmap_bwrap_krings_create			(bwraps)
2202  *      	create both the brap krings array,
2203  *      	the krings array of the wrapped adapter, and
2204  *      	(if needed) the fake array for the host adapter
2205  *
2206  * na->nm_register(, 1)
2207  * (put the adapter in netmap mode)
2208  *
2209  * 	This may be one of the following:
2210  *
2211  * 	* netmap_hw_reg				        (hw ports)
2212  * 		checks that the ifp is still there, then calls
2213  * 		the hardware specific callback;
2214  *
2215  * 	* netmap_vp_reg					(VALE ports)
2216  *		If the port is connected to a bridge,
2217  *		set the NAF_NETMAP_ON flag under the
2218  *		bridge write lock.
2219  *
2220  *	* netmap_pipe_reg				(pipes)
2221  *		inform the other pipe end that it is no
2222  *		longer responsible for the lifetime of this
2223  *		pipe end
2224  *
2225  *	* netmap_monitor_reg				(monitors)
2226  *		intercept the sync callbacks of the monitored
2227  *		rings
2228  *
2229  *	* netmap_bwrap_reg				(bwraps)
2230  *		cross-link the bwrap and hwna rings,
2231  *		forward the request to the hwna, override
2232  *		the hwna notify callback (to get the frames
2233  *		coming from outside go through the bridge).
2234  *
2235  *
2236  */
2237 int
2238 netmap_do_regif(struct netmap_priv_d *priv, struct netmap_adapter *na,
2239 	uint32_t nr_mode, uint16_t nr_ringid, uint64_t nr_flags)
2240 {
2241 	struct netmap_if *nifp = NULL;
2242 	int error;
2243 
2244 	NMG_LOCK_ASSERT();
2245 	priv->np_na = na;     /* store the reference */
2246 	error = netmap_mem_finalize(na->nm_mem, na);
2247 	if (error)
2248 		goto err;
2249 
2250 	if (na->active_fds == 0) {
2251 
2252 		/* cache the allocator info in the na */
2253 		error = netmap_mem_get_lut(na->nm_mem, &na->na_lut);
2254 		if (error)
2255 			goto err_drop_mem;
2256 		ND("lut %p bufs %u size %u", na->na_lut.lut, na->na_lut.objtotal,
2257 					    na->na_lut.objsize);
2258 
2259 		/* ring configuration may have changed, fetch from the card */
2260 		netmap_update_config(na);
2261 	}
2262 
2263 	/* compute the range of tx and rx rings to monitor */
2264 	error = netmap_set_ringid(priv, nr_mode, nr_ringid, nr_flags);
2265 	if (error)
2266 		goto err_put_lut;
2267 
2268 	if (na->active_fds == 0) {
2269 		/*
2270 		 * If this is the first registration of the adapter,
2271 		 * perform sanity checks and create the in-kernel view
2272 		 * of the netmap rings (the netmap krings).
2273 		 */
2274 		if (na->ifp && nm_priv_rx_enabled(priv)) {
2275 			/* This netmap adapter is attached to an ifnet. */
2276 			unsigned mtu = nm_os_ifnet_mtu(na->ifp);
2277 
2278 			ND("%s: mtu %d rx_buf_maxsize %d netmap_buf_size %d",
2279 				na->name, mtu, na->rx_buf_maxsize, NETMAP_BUF_SIZE(na));
2280 
2281 			if (na->rx_buf_maxsize == 0) {
2282 				nm_prerr("%s: error: rx_buf_maxsize == 0", na->name);
2283 				error = EIO;
2284 				goto err_drop_mem;
2285 			}
2286 
2287 			error = netmap_buf_size_validate(na, mtu);
2288 			if (error)
2289 				goto err_drop_mem;
2290 		}
2291 
2292 		/*
2293 		 * Depending on the adapter, this may also create
2294 		 * the netmap rings themselves
2295 		 */
2296 		error = na->nm_krings_create(na);
2297 		if (error)
2298 			goto err_put_lut;
2299 
2300 	}
2301 
2302 	/* now the krings must exist and we can check whether some
2303 	 * previous bind has exclusive ownership on them, and set
2304 	 * nr_pending_mode
2305 	 */
2306 	error = netmap_krings_get(priv);
2307 	if (error)
2308 		goto err_del_krings;
2309 
2310 	/* create all needed missing netmap rings */
2311 	error = netmap_mem_rings_create(na);
2312 	if (error)
2313 		goto err_rel_excl;
2314 
2315 	/* in all cases, create a new netmap if */
2316 	nifp = netmap_mem_if_new(na, priv);
2317 	if (nifp == NULL) {
2318 		error = ENOMEM;
2319 		goto err_rel_excl;
2320 	}
2321 
2322 	if (nm_kring_pending(priv)) {
2323 		/* Some kring is switching mode, tell the adapter to
2324 		 * react on this. */
2325 		error = na->nm_register(na, 1);
2326 		if (error)
2327 			goto err_del_if;
2328 	}
2329 
2330 	/* Commit the reference. */
2331 	na->active_fds++;
2332 
2333 	/*
2334 	 * advertise that the interface is ready by setting np_nifp.
2335 	 * The barrier is needed because readers (poll, *SYNC and mmap)
2336 	 * check for priv->np_nifp != NULL without locking
2337 	 */
2338 	mb(); /* make sure previous writes are visible to all CPUs */
2339 	priv->np_nifp = nifp;
2340 
2341 	return 0;
2342 
2343 err_del_if:
2344 	netmap_mem_if_delete(na, nifp);
2345 err_rel_excl:
2346 	netmap_krings_put(priv);
2347 	netmap_mem_rings_delete(na);
2348 err_del_krings:
2349 	if (na->active_fds == 0)
2350 		na->nm_krings_delete(na);
2351 err_put_lut:
2352 	if (na->active_fds == 0)
2353 		memset(&na->na_lut, 0, sizeof(na->na_lut));
2354 err_drop_mem:
2355 	netmap_mem_drop(na);
2356 err:
2357 	priv->np_na = NULL;
2358 	return error;
2359 }
2360 
2361 
2362 /*
2363  * update kring and ring at the end of rxsync/txsync.
2364  */
2365 static inline void
2366 nm_sync_finalize(struct netmap_kring *kring)
2367 {
2368 	/*
2369 	 * Update ring tail to what the kernel knows
2370 	 * After txsync: head/rhead/hwcur might be behind cur/rcur
2371 	 * if no carrier.
2372 	 */
2373 	kring->ring->tail = kring->rtail = kring->nr_hwtail;
2374 
2375 	ND(5, "%s now hwcur %d hwtail %d head %d cur %d tail %d",
2376 		kring->name, kring->nr_hwcur, kring->nr_hwtail,
2377 		kring->rhead, kring->rcur, kring->rtail);
2378 }
2379 
2380 /* set ring timestamp */
2381 static inline void
2382 ring_timestamp_set(struct netmap_ring *ring)
2383 {
2384 	if (netmap_no_timestamp == 0 || ring->flags & NR_TIMESTAMP) {
2385 		microtime(&ring->ts);
2386 	}
2387 }
2388 
2389 static int nmreq_copyin(struct nmreq_header *, int);
2390 static int nmreq_copyout(struct nmreq_header *, int);
2391 static int nmreq_checkoptions(struct nmreq_header *);
2392 
2393 /*
2394  * ioctl(2) support for the "netmap" device.
2395  *
2396  * Following a list of accepted commands:
2397  * - NIOCCTRL		device control API
2398  * - NIOCTXSYNC		sync TX rings
2399  * - NIOCRXSYNC		sync RX rings
2400  * - SIOCGIFADDR	just for convenience
2401  * - NIOCGINFO		deprecated (legacy API)
2402  * - NIOCREGIF		deprecated (legacy API)
2403  *
2404  * Return 0 on success, errno otherwise.
2405  */
2406 int
2407 netmap_ioctl(struct netmap_priv_d *priv, u_long cmd, caddr_t data,
2408 		struct thread *td, int nr_body_is_user)
2409 {
2410 	struct mbq q;	/* packets from RX hw queues to host stack */
2411 	struct netmap_adapter *na = NULL;
2412 	struct netmap_mem_d *nmd = NULL;
2413 	struct ifnet *ifp = NULL;
2414 	int error = 0;
2415 	u_int i, qfirst, qlast;
2416 	struct netmap_kring **krings;
2417 	int sync_flags;
2418 	enum txrx t;
2419 
2420 	switch (cmd) {
2421 	case NIOCCTRL: {
2422 		struct nmreq_header *hdr = (struct nmreq_header *)data;
2423 
2424 		if (hdr->nr_version < NETMAP_MIN_API ||
2425 		    hdr->nr_version > NETMAP_MAX_API) {
2426 			nm_prerr("API mismatch: got %d need %d",
2427 				hdr->nr_version, NETMAP_API);
2428 			return EINVAL;
2429 		}
2430 
2431 		/* Make a kernel-space copy of the user-space nr_body.
2432 		 * For convenince, the nr_body pointer and the pointers
2433 		 * in the options list will be replaced with their
2434 		 * kernel-space counterparts. The original pointers are
2435 		 * saved internally and later restored by nmreq_copyout
2436 		 */
2437 		error = nmreq_copyin(hdr, nr_body_is_user);
2438 		if (error) {
2439 			return error;
2440 		}
2441 
2442 		/* Sanitize hdr->nr_name. */
2443 		hdr->nr_name[sizeof(hdr->nr_name) - 1] = '\0';
2444 
2445 		switch (hdr->nr_reqtype) {
2446 		case NETMAP_REQ_REGISTER: {
2447 			struct nmreq_register *req =
2448 				(struct nmreq_register *)(uintptr_t)hdr->nr_body;
2449 			struct netmap_if *nifp;
2450 
2451 			/* Protect access to priv from concurrent requests. */
2452 			NMG_LOCK();
2453 			do {
2454 				struct nmreq_option *opt;
2455 				u_int memflags;
2456 
2457 				if (priv->np_nifp != NULL) {	/* thread already registered */
2458 					error = EBUSY;
2459 					break;
2460 				}
2461 
2462 #ifdef WITH_EXTMEM
2463 				opt = nmreq_findoption((struct nmreq_option *)(uintptr_t)hdr->nr_options,
2464 						NETMAP_REQ_OPT_EXTMEM);
2465 				if (opt != NULL) {
2466 					struct nmreq_opt_extmem *e =
2467 						(struct nmreq_opt_extmem *)opt;
2468 
2469 					error = nmreq_checkduplicate(opt);
2470 					if (error) {
2471 						opt->nro_status = error;
2472 						break;
2473 					}
2474 					nmd = netmap_mem_ext_create(e->nro_usrptr,
2475 							&e->nro_info, &error);
2476 					opt->nro_status = error;
2477 					if (nmd == NULL)
2478 						break;
2479 				}
2480 #endif /* WITH_EXTMEM */
2481 
2482 				if (nmd == NULL && req->nr_mem_id) {
2483 					/* find the allocator and get a reference */
2484 					nmd = netmap_mem_find(req->nr_mem_id);
2485 					if (nmd == NULL) {
2486 						if (netmap_verbose) {
2487 							nm_prerr("%s: failed to find mem_id %u",
2488 									hdr->nr_name, req->nr_mem_id);
2489 						}
2490 						error = EINVAL;
2491 						break;
2492 					}
2493 				}
2494 				/* find the interface and a reference */
2495 				error = netmap_get_na(hdr, &na, &ifp, nmd,
2496 						      1 /* create */); /* keep reference */
2497 				if (error)
2498 					break;
2499 				if (NETMAP_OWNED_BY_KERN(na)) {
2500 					error = EBUSY;
2501 					break;
2502 				}
2503 
2504 				if (na->virt_hdr_len && !(req->nr_flags & NR_ACCEPT_VNET_HDR)) {
2505 					nm_prerr("virt_hdr_len=%d, but application does "
2506 						"not accept it", na->virt_hdr_len);
2507 					error = EIO;
2508 					break;
2509 				}
2510 
2511 				error = netmap_do_regif(priv, na, req->nr_mode,
2512 							req->nr_ringid, req->nr_flags);
2513 				if (error) {    /* reg. failed, release priv and ref */
2514 					break;
2515 				}
2516 
2517 				opt = nmreq_findoption((struct nmreq_option *)(uintptr_t)hdr->nr_options,
2518 							NETMAP_REQ_OPT_CSB);
2519 				if (opt != NULL) {
2520 					struct nmreq_opt_csb *csbo =
2521 						(struct nmreq_opt_csb *)opt;
2522 					error = nmreq_checkduplicate(opt);
2523 					if (!error) {
2524 						error = netmap_csb_validate(priv, csbo);
2525 					}
2526 					opt->nro_status = error;
2527 					if (error) {
2528 						netmap_do_unregif(priv);
2529 						break;
2530 					}
2531 				}
2532 
2533 				nifp = priv->np_nifp;
2534 
2535 				/* return the offset of the netmap_if object */
2536 				req->nr_rx_rings = na->num_rx_rings;
2537 				req->nr_tx_rings = na->num_tx_rings;
2538 				req->nr_rx_slots = na->num_rx_desc;
2539 				req->nr_tx_slots = na->num_tx_desc;
2540 				error = netmap_mem_get_info(na->nm_mem, &req->nr_memsize, &memflags,
2541 					&req->nr_mem_id);
2542 				if (error) {
2543 					netmap_do_unregif(priv);
2544 					break;
2545 				}
2546 				if (memflags & NETMAP_MEM_PRIVATE) {
2547 					*(uint32_t *)(uintptr_t)&nifp->ni_flags |= NI_PRIV_MEM;
2548 				}
2549 				for_rx_tx(t) {
2550 					priv->np_si[t] = nm_si_user(priv, t) ?
2551 						&na->si[t] : &NMR(na, t)[priv->np_qfirst[t]]->si;
2552 				}
2553 
2554 				if (req->nr_extra_bufs) {
2555 					if (netmap_verbose)
2556 						nm_prinf("requested %d extra buffers",
2557 							req->nr_extra_bufs);
2558 					req->nr_extra_bufs = netmap_extra_alloc(na,
2559 						&nifp->ni_bufs_head, req->nr_extra_bufs);
2560 					if (netmap_verbose)
2561 						nm_prinf("got %d extra buffers", req->nr_extra_bufs);
2562 				}
2563 				req->nr_offset = netmap_mem_if_offset(na->nm_mem, nifp);
2564 
2565 				error = nmreq_checkoptions(hdr);
2566 				if (error) {
2567 					netmap_do_unregif(priv);
2568 					break;
2569 				}
2570 
2571 				/* store ifp reference so that priv destructor may release it */
2572 				priv->np_ifp = ifp;
2573 			} while (0);
2574 			if (error) {
2575 				netmap_unget_na(na, ifp);
2576 			}
2577 			/* release the reference from netmap_mem_find() or
2578 			 * netmap_mem_ext_create()
2579 			 */
2580 			if (nmd)
2581 				netmap_mem_put(nmd);
2582 			NMG_UNLOCK();
2583 			break;
2584 		}
2585 
2586 		case NETMAP_REQ_PORT_INFO_GET: {
2587 			struct nmreq_port_info_get *req =
2588 				(struct nmreq_port_info_get *)(uintptr_t)hdr->nr_body;
2589 
2590 			NMG_LOCK();
2591 			do {
2592 				u_int memflags;
2593 
2594 				if (hdr->nr_name[0] != '\0') {
2595 					/* Build a nmreq_register out of the nmreq_port_info_get,
2596 					 * so that we can call netmap_get_na(). */
2597 					struct nmreq_register regreq;
2598 					bzero(&regreq, sizeof(regreq));
2599 					regreq.nr_mode = NR_REG_ALL_NIC;
2600 					regreq.nr_tx_slots = req->nr_tx_slots;
2601 					regreq.nr_rx_slots = req->nr_rx_slots;
2602 					regreq.nr_tx_rings = req->nr_tx_rings;
2603 					regreq.nr_rx_rings = req->nr_rx_rings;
2604 					regreq.nr_mem_id = req->nr_mem_id;
2605 
2606 					/* get a refcount */
2607 					hdr->nr_reqtype = NETMAP_REQ_REGISTER;
2608 					hdr->nr_body = (uintptr_t)&regreq;
2609 					error = netmap_get_na(hdr, &na, &ifp, NULL, 1 /* create */);
2610 					hdr->nr_reqtype = NETMAP_REQ_PORT_INFO_GET; /* reset type */
2611 					hdr->nr_body = (uintptr_t)req; /* reset nr_body */
2612 					if (error) {
2613 						na = NULL;
2614 						ifp = NULL;
2615 						break;
2616 					}
2617 					nmd = na->nm_mem; /* get memory allocator */
2618 				} else {
2619 					nmd = netmap_mem_find(req->nr_mem_id ? req->nr_mem_id : 1);
2620 					if (nmd == NULL) {
2621 						if (netmap_verbose)
2622 							nm_prerr("%s: failed to find mem_id %u",
2623 									hdr->nr_name,
2624 									req->nr_mem_id ? req->nr_mem_id : 1);
2625 						error = EINVAL;
2626 						break;
2627 					}
2628 				}
2629 
2630 				error = netmap_mem_get_info(nmd, &req->nr_memsize, &memflags,
2631 					&req->nr_mem_id);
2632 				if (error)
2633 					break;
2634 				if (na == NULL) /* only memory info */
2635 					break;
2636 				netmap_update_config(na);
2637 				req->nr_rx_rings = na->num_rx_rings;
2638 				req->nr_tx_rings = na->num_tx_rings;
2639 				req->nr_rx_slots = na->num_rx_desc;
2640 				req->nr_tx_slots = na->num_tx_desc;
2641 			} while (0);
2642 			netmap_unget_na(na, ifp);
2643 			NMG_UNLOCK();
2644 			break;
2645 		}
2646 #ifdef WITH_VALE
2647 		case NETMAP_REQ_VALE_ATTACH: {
2648 			error = netmap_vale_attach(hdr, NULL /* userspace request */);
2649 			break;
2650 		}
2651 
2652 		case NETMAP_REQ_VALE_DETACH: {
2653 			error = netmap_vale_detach(hdr, NULL /* userspace request */);
2654 			break;
2655 		}
2656 
2657 		case NETMAP_REQ_VALE_LIST: {
2658 			error = netmap_vale_list(hdr);
2659 			break;
2660 		}
2661 
2662 		case NETMAP_REQ_PORT_HDR_SET: {
2663 			struct nmreq_port_hdr *req =
2664 				(struct nmreq_port_hdr *)(uintptr_t)hdr->nr_body;
2665 			/* Build a nmreq_register out of the nmreq_port_hdr,
2666 			 * so that we can call netmap_get_bdg_na(). */
2667 			struct nmreq_register regreq;
2668 			bzero(&regreq, sizeof(regreq));
2669 			regreq.nr_mode = NR_REG_ALL_NIC;
2670 
2671 			/* For now we only support virtio-net headers, and only for
2672 			 * VALE ports, but this may change in future. Valid lengths
2673 			 * for the virtio-net header are 0 (no header), 10 and 12. */
2674 			if (req->nr_hdr_len != 0 &&
2675 				req->nr_hdr_len != sizeof(struct nm_vnet_hdr) &&
2676 					req->nr_hdr_len != 12) {
2677 				if (netmap_verbose)
2678 					nm_prerr("invalid hdr_len %u", req->nr_hdr_len);
2679 				error = EINVAL;
2680 				break;
2681 			}
2682 			NMG_LOCK();
2683 			hdr->nr_reqtype = NETMAP_REQ_REGISTER;
2684 			hdr->nr_body = (uintptr_t)&regreq;
2685 			error = netmap_get_vale_na(hdr, &na, NULL, 0);
2686 			hdr->nr_reqtype = NETMAP_REQ_PORT_HDR_SET;
2687 			hdr->nr_body = (uintptr_t)req;
2688 			if (na && !error) {
2689 				struct netmap_vp_adapter *vpna =
2690 					(struct netmap_vp_adapter *)na;
2691 				na->virt_hdr_len = req->nr_hdr_len;
2692 				if (na->virt_hdr_len) {
2693 					vpna->mfs = NETMAP_BUF_SIZE(na);
2694 				}
2695 				if (netmap_verbose)
2696 					nm_prinf("Using vnet_hdr_len %d for %p", na->virt_hdr_len, na);
2697 				netmap_adapter_put(na);
2698 			} else if (!na) {
2699 				error = ENXIO;
2700 			}
2701 			NMG_UNLOCK();
2702 			break;
2703 		}
2704 
2705 		case NETMAP_REQ_PORT_HDR_GET: {
2706 			/* Get vnet-header length for this netmap port */
2707 			struct nmreq_port_hdr *req =
2708 				(struct nmreq_port_hdr *)(uintptr_t)hdr->nr_body;
2709 			/* Build a nmreq_register out of the nmreq_port_hdr,
2710 			 * so that we can call netmap_get_bdg_na(). */
2711 			struct nmreq_register regreq;
2712 			struct ifnet *ifp;
2713 
2714 			bzero(&regreq, sizeof(regreq));
2715 			regreq.nr_mode = NR_REG_ALL_NIC;
2716 			NMG_LOCK();
2717 			hdr->nr_reqtype = NETMAP_REQ_REGISTER;
2718 			hdr->nr_body = (uintptr_t)&regreq;
2719 			error = netmap_get_na(hdr, &na, &ifp, NULL, 0);
2720 			hdr->nr_reqtype = NETMAP_REQ_PORT_HDR_GET;
2721 			hdr->nr_body = (uintptr_t)req;
2722 			if (na && !error) {
2723 				req->nr_hdr_len = na->virt_hdr_len;
2724 			}
2725 			netmap_unget_na(na, ifp);
2726 			NMG_UNLOCK();
2727 			break;
2728 		}
2729 
2730 		case NETMAP_REQ_VALE_NEWIF: {
2731 			error = nm_vi_create(hdr);
2732 			break;
2733 		}
2734 
2735 		case NETMAP_REQ_VALE_DELIF: {
2736 			error = nm_vi_destroy(hdr->nr_name);
2737 			break;
2738 		}
2739 
2740 		case NETMAP_REQ_VALE_POLLING_ENABLE:
2741 		case NETMAP_REQ_VALE_POLLING_DISABLE: {
2742 			error = nm_bdg_polling(hdr);
2743 			break;
2744 		}
2745 #endif  /* WITH_VALE */
2746 		case NETMAP_REQ_POOLS_INFO_GET: {
2747 			/* Get information from the memory allocator used for
2748 			 * hdr->nr_name. */
2749 			struct nmreq_pools_info *req =
2750 				(struct nmreq_pools_info *)(uintptr_t)hdr->nr_body;
2751 			NMG_LOCK();
2752 			do {
2753 				/* Build a nmreq_register out of the nmreq_pools_info,
2754 				 * so that we can call netmap_get_na(). */
2755 				struct nmreq_register regreq;
2756 				bzero(&regreq, sizeof(regreq));
2757 				regreq.nr_mem_id = req->nr_mem_id;
2758 				regreq.nr_mode = NR_REG_ALL_NIC;
2759 
2760 				hdr->nr_reqtype = NETMAP_REQ_REGISTER;
2761 				hdr->nr_body = (uintptr_t)&regreq;
2762 				error = netmap_get_na(hdr, &na, &ifp, NULL, 1 /* create */);
2763 				hdr->nr_reqtype = NETMAP_REQ_POOLS_INFO_GET; /* reset type */
2764 				hdr->nr_body = (uintptr_t)req; /* reset nr_body */
2765 				if (error) {
2766 					na = NULL;
2767 					ifp = NULL;
2768 					break;
2769 				}
2770 				nmd = na->nm_mem; /* grab the memory allocator */
2771 				if (nmd == NULL) {
2772 					error = EINVAL;
2773 					break;
2774 				}
2775 
2776 				/* Finalize the memory allocator, get the pools
2777 				 * information and release the allocator. */
2778 				error = netmap_mem_finalize(nmd, na);
2779 				if (error) {
2780 					break;
2781 				}
2782 				error = netmap_mem_pools_info_get(req, nmd);
2783 				netmap_mem_drop(na);
2784 			} while (0);
2785 			netmap_unget_na(na, ifp);
2786 			NMG_UNLOCK();
2787 			break;
2788 		}
2789 
2790 		case NETMAP_REQ_CSB_ENABLE: {
2791 			struct nmreq_option *opt;
2792 
2793 			opt = nmreq_findoption((struct nmreq_option *)(uintptr_t)hdr->nr_options,
2794 						NETMAP_REQ_OPT_CSB);
2795 			if (opt == NULL) {
2796 				error = EINVAL;
2797 			} else {
2798 				struct nmreq_opt_csb *csbo =
2799 					(struct nmreq_opt_csb *)opt;
2800 				error = nmreq_checkduplicate(opt);
2801 				if (!error) {
2802 					NMG_LOCK();
2803 					error = netmap_csb_validate(priv, csbo);
2804 					NMG_UNLOCK();
2805 				}
2806 				opt->nro_status = error;
2807 			}
2808 			break;
2809 		}
2810 
2811 		case NETMAP_REQ_SYNC_KLOOP_START: {
2812 			error = netmap_sync_kloop(priv, hdr);
2813 			break;
2814 		}
2815 
2816 		case NETMAP_REQ_SYNC_KLOOP_STOP: {
2817 			error = netmap_sync_kloop_stop(priv);
2818 			break;
2819 		}
2820 
2821 		default: {
2822 			error = EINVAL;
2823 			break;
2824 		}
2825 		}
2826 		/* Write back request body to userspace and reset the
2827 		 * user-space pointer. */
2828 		error = nmreq_copyout(hdr, error);
2829 		break;
2830 	}
2831 
2832 	case NIOCTXSYNC:
2833 	case NIOCRXSYNC: {
2834 		if (unlikely(priv->np_nifp == NULL)) {
2835 			error = ENXIO;
2836 			break;
2837 		}
2838 		mb(); /* make sure following reads are not from cache */
2839 
2840 		if (unlikely(priv->np_csb_atok_base)) {
2841 			nm_prerr("Invalid sync in CSB mode");
2842 			error = EBUSY;
2843 			break;
2844 		}
2845 
2846 		na = priv->np_na;      /* we have a reference */
2847 
2848 		mbq_init(&q);
2849 		t = (cmd == NIOCTXSYNC ? NR_TX : NR_RX);
2850 		krings = NMR(na, t);
2851 		qfirst = priv->np_qfirst[t];
2852 		qlast = priv->np_qlast[t];
2853 		sync_flags = priv->np_sync_flags;
2854 
2855 		for (i = qfirst; i < qlast; i++) {
2856 			struct netmap_kring *kring = krings[i];
2857 			struct netmap_ring *ring = kring->ring;
2858 
2859 			if (unlikely(nm_kr_tryget(kring, 1, &error))) {
2860 				error = (error ? EIO : 0);
2861 				continue;
2862 			}
2863 
2864 			if (cmd == NIOCTXSYNC) {
2865 				if (netmap_debug & NM_DEBUG_TXSYNC)
2866 					nm_prinf("pre txsync ring %d cur %d hwcur %d",
2867 					    i, ring->cur,
2868 					    kring->nr_hwcur);
2869 				if (nm_txsync_prologue(kring, ring) >= kring->nkr_num_slots) {
2870 					netmap_ring_reinit(kring);
2871 				} else if (kring->nm_sync(kring, sync_flags | NAF_FORCE_RECLAIM) == 0) {
2872 					nm_sync_finalize(kring);
2873 				}
2874 				if (netmap_debug & NM_DEBUG_TXSYNC)
2875 					nm_prinf("post txsync ring %d cur %d hwcur %d",
2876 					    i, ring->cur,
2877 					    kring->nr_hwcur);
2878 			} else {
2879 				if (nm_rxsync_prologue(kring, ring) >= kring->nkr_num_slots) {
2880 					netmap_ring_reinit(kring);
2881 				}
2882 				if (nm_may_forward_up(kring)) {
2883 					/* transparent forwarding, see netmap_poll() */
2884 					netmap_grab_packets(kring, &q, netmap_fwd);
2885 				}
2886 				if (kring->nm_sync(kring, sync_flags | NAF_FORCE_READ) == 0) {
2887 					nm_sync_finalize(kring);
2888 				}
2889 				ring_timestamp_set(ring);
2890 			}
2891 			nm_kr_put(kring);
2892 		}
2893 
2894 		if (mbq_peek(&q)) {
2895 			netmap_send_up(na->ifp, &q);
2896 		}
2897 
2898 		break;
2899 	}
2900 
2901 	default: {
2902 		return netmap_ioctl_legacy(priv, cmd, data, td);
2903 		break;
2904 	}
2905 	}
2906 
2907 	return (error);
2908 }
2909 
2910 size_t
2911 nmreq_size_by_type(uint16_t nr_reqtype)
2912 {
2913 	switch (nr_reqtype) {
2914 	case NETMAP_REQ_REGISTER:
2915 		return sizeof(struct nmreq_register);
2916 	case NETMAP_REQ_PORT_INFO_GET:
2917 		return sizeof(struct nmreq_port_info_get);
2918 	case NETMAP_REQ_VALE_ATTACH:
2919 		return sizeof(struct nmreq_vale_attach);
2920 	case NETMAP_REQ_VALE_DETACH:
2921 		return sizeof(struct nmreq_vale_detach);
2922 	case NETMAP_REQ_VALE_LIST:
2923 		return sizeof(struct nmreq_vale_list);
2924 	case NETMAP_REQ_PORT_HDR_SET:
2925 	case NETMAP_REQ_PORT_HDR_GET:
2926 		return sizeof(struct nmreq_port_hdr);
2927 	case NETMAP_REQ_VALE_NEWIF:
2928 		return sizeof(struct nmreq_vale_newif);
2929 	case NETMAP_REQ_VALE_DELIF:
2930 	case NETMAP_REQ_SYNC_KLOOP_STOP:
2931 	case NETMAP_REQ_CSB_ENABLE:
2932 		return 0;
2933 	case NETMAP_REQ_VALE_POLLING_ENABLE:
2934 	case NETMAP_REQ_VALE_POLLING_DISABLE:
2935 		return sizeof(struct nmreq_vale_polling);
2936 	case NETMAP_REQ_POOLS_INFO_GET:
2937 		return sizeof(struct nmreq_pools_info);
2938 	case NETMAP_REQ_SYNC_KLOOP_START:
2939 		return sizeof(struct nmreq_sync_kloop_start);
2940 	}
2941 	return 0;
2942 }
2943 
2944 static size_t
2945 nmreq_opt_size_by_type(uint32_t nro_reqtype, uint64_t nro_size)
2946 {
2947 	size_t rv = sizeof(struct nmreq_option);
2948 #ifdef NETMAP_REQ_OPT_DEBUG
2949 	if (nro_reqtype & NETMAP_REQ_OPT_DEBUG)
2950 		return (nro_reqtype & ~NETMAP_REQ_OPT_DEBUG);
2951 #endif /* NETMAP_REQ_OPT_DEBUG */
2952 	switch (nro_reqtype) {
2953 #ifdef WITH_EXTMEM
2954 	case NETMAP_REQ_OPT_EXTMEM:
2955 		rv = sizeof(struct nmreq_opt_extmem);
2956 		break;
2957 #endif /* WITH_EXTMEM */
2958 	case NETMAP_REQ_OPT_SYNC_KLOOP_EVENTFDS:
2959 		if (nro_size >= rv)
2960 			rv = nro_size;
2961 		break;
2962 	case NETMAP_REQ_OPT_CSB:
2963 		rv = sizeof(struct nmreq_opt_csb);
2964 		break;
2965 	}
2966 	/* subtract the common header */
2967 	return rv - sizeof(struct nmreq_option);
2968 }
2969 
2970 int
2971 nmreq_copyin(struct nmreq_header *hdr, int nr_body_is_user)
2972 {
2973 	size_t rqsz, optsz, bufsz;
2974 	int error;
2975 	char *ker = NULL, *p;
2976 	struct nmreq_option **next, *src;
2977 	struct nmreq_option buf;
2978 	uint64_t *ptrs;
2979 
2980 	if (hdr->nr_reserved) {
2981 		if (netmap_verbose)
2982 			nm_prerr("nr_reserved must be zero");
2983 		return EINVAL;
2984 	}
2985 
2986 	if (!nr_body_is_user)
2987 		return 0;
2988 
2989 	hdr->nr_reserved = nr_body_is_user;
2990 
2991 	/* compute the total size of the buffer */
2992 	rqsz = nmreq_size_by_type(hdr->nr_reqtype);
2993 	if (rqsz > NETMAP_REQ_MAXSIZE) {
2994 		error = EMSGSIZE;
2995 		goto out_err;
2996 	}
2997 	if ((rqsz && hdr->nr_body == (uintptr_t)NULL) ||
2998 		(!rqsz && hdr->nr_body != (uintptr_t)NULL)) {
2999 		/* Request body expected, but not found; or
3000 		 * request body found but unexpected. */
3001 		if (netmap_verbose)
3002 			nm_prerr("nr_body expected but not found, or vice versa");
3003 		error = EINVAL;
3004 		goto out_err;
3005 	}
3006 
3007 	bufsz = 2 * sizeof(void *) + rqsz;
3008 	optsz = 0;
3009 	for (src = (struct nmreq_option *)(uintptr_t)hdr->nr_options; src;
3010 	     src = (struct nmreq_option *)(uintptr_t)buf.nro_next)
3011 	{
3012 		error = copyin(src, &buf, sizeof(*src));
3013 		if (error)
3014 			goto out_err;
3015 		optsz += sizeof(*src);
3016 		optsz += nmreq_opt_size_by_type(buf.nro_reqtype, buf.nro_size);
3017 		if (rqsz + optsz > NETMAP_REQ_MAXSIZE) {
3018 			error = EMSGSIZE;
3019 			goto out_err;
3020 		}
3021 		bufsz += optsz + sizeof(void *);
3022 	}
3023 
3024 	ker = nm_os_malloc(bufsz);
3025 	if (ker == NULL) {
3026 		error = ENOMEM;
3027 		goto out_err;
3028 	}
3029 	p = ker;
3030 
3031 	/* make a copy of the user pointers */
3032 	ptrs = (uint64_t*)p;
3033 	*ptrs++ = hdr->nr_body;
3034 	*ptrs++ = hdr->nr_options;
3035 	p = (char *)ptrs;
3036 
3037 	/* copy the body */
3038 	error = copyin((void *)(uintptr_t)hdr->nr_body, p, rqsz);
3039 	if (error)
3040 		goto out_restore;
3041 	/* overwrite the user pointer with the in-kernel one */
3042 	hdr->nr_body = (uintptr_t)p;
3043 	p += rqsz;
3044 
3045 	/* copy the options */
3046 	next = (struct nmreq_option **)&hdr->nr_options;
3047 	src = *next;
3048 	while (src) {
3049 		struct nmreq_option *opt;
3050 
3051 		/* copy the option header */
3052 		ptrs = (uint64_t *)p;
3053 		opt = (struct nmreq_option *)(ptrs + 1);
3054 		error = copyin(src, opt, sizeof(*src));
3055 		if (error)
3056 			goto out_restore;
3057 		/* make a copy of the user next pointer */
3058 		*ptrs = opt->nro_next;
3059 		/* overwrite the user pointer with the in-kernel one */
3060 		*next = opt;
3061 
3062 		/* initialize the option as not supported.
3063 		 * Recognized options will update this field.
3064 		 */
3065 		opt->nro_status = EOPNOTSUPP;
3066 
3067 		p = (char *)(opt + 1);
3068 
3069 		/* copy the option body */
3070 		optsz = nmreq_opt_size_by_type(opt->nro_reqtype,
3071 						opt->nro_size);
3072 		if (optsz) {
3073 			/* the option body follows the option header */
3074 			error = copyin(src + 1, p, optsz);
3075 			if (error)
3076 				goto out_restore;
3077 			p += optsz;
3078 		}
3079 
3080 		/* move to next option */
3081 		next = (struct nmreq_option **)&opt->nro_next;
3082 		src = *next;
3083 	}
3084 	return 0;
3085 
3086 out_restore:
3087 	ptrs = (uint64_t *)ker;
3088 	hdr->nr_body = *ptrs++;
3089 	hdr->nr_options = *ptrs++;
3090 	hdr->nr_reserved = 0;
3091 	nm_os_free(ker);
3092 out_err:
3093 	return error;
3094 }
3095 
3096 static int
3097 nmreq_copyout(struct nmreq_header *hdr, int rerror)
3098 {
3099 	struct nmreq_option *src, *dst;
3100 	void *ker = (void *)(uintptr_t)hdr->nr_body, *bufstart;
3101 	uint64_t *ptrs;
3102 	size_t bodysz;
3103 	int error;
3104 
3105 	if (!hdr->nr_reserved)
3106 		return rerror;
3107 
3108 	/* restore the user pointers in the header */
3109 	ptrs = (uint64_t *)ker - 2;
3110 	bufstart = ptrs;
3111 	hdr->nr_body = *ptrs++;
3112 	src = (struct nmreq_option *)(uintptr_t)hdr->nr_options;
3113 	hdr->nr_options = *ptrs;
3114 
3115 	if (!rerror) {
3116 		/* copy the body */
3117 		bodysz = nmreq_size_by_type(hdr->nr_reqtype);
3118 		error = copyout(ker, (void *)(uintptr_t)hdr->nr_body, bodysz);
3119 		if (error) {
3120 			rerror = error;
3121 			goto out;
3122 		}
3123 	}
3124 
3125 	/* copy the options */
3126 	dst = (struct nmreq_option *)(uintptr_t)hdr->nr_options;
3127 	while (src) {
3128 		size_t optsz;
3129 		uint64_t next;
3130 
3131 		/* restore the user pointer */
3132 		next = src->nro_next;
3133 		ptrs = (uint64_t *)src - 1;
3134 		src->nro_next = *ptrs;
3135 
3136 		/* always copy the option header */
3137 		error = copyout(src, dst, sizeof(*src));
3138 		if (error) {
3139 			rerror = error;
3140 			goto out;
3141 		}
3142 
3143 		/* copy the option body only if there was no error */
3144 		if (!rerror && !src->nro_status) {
3145 			optsz = nmreq_opt_size_by_type(src->nro_reqtype,
3146 							src->nro_size);
3147 			if (optsz) {
3148 				error = copyout(src + 1, dst + 1, optsz);
3149 				if (error) {
3150 					rerror = error;
3151 					goto out;
3152 				}
3153 			}
3154 		}
3155 		src = (struct nmreq_option *)(uintptr_t)next;
3156 		dst = (struct nmreq_option *)(uintptr_t)*ptrs;
3157 	}
3158 
3159 
3160 out:
3161 	hdr->nr_reserved = 0;
3162 	nm_os_free(bufstart);
3163 	return rerror;
3164 }
3165 
3166 struct nmreq_option *
3167 nmreq_findoption(struct nmreq_option *opt, uint16_t reqtype)
3168 {
3169 	for ( ; opt; opt = (struct nmreq_option *)(uintptr_t)opt->nro_next)
3170 		if (opt->nro_reqtype == reqtype)
3171 			return opt;
3172 	return NULL;
3173 }
3174 
3175 int
3176 nmreq_checkduplicate(struct nmreq_option *opt) {
3177 	uint16_t type = opt->nro_reqtype;
3178 	int dup = 0;
3179 
3180 	while ((opt = nmreq_findoption((struct nmreq_option *)(uintptr_t)opt->nro_next,
3181 			type))) {
3182 		dup++;
3183 		opt->nro_status = EINVAL;
3184 	}
3185 	return (dup ? EINVAL : 0);
3186 }
3187 
3188 static int
3189 nmreq_checkoptions(struct nmreq_header *hdr)
3190 {
3191 	struct nmreq_option *opt;
3192 	/* return error if there is still any option
3193 	 * marked as not supported
3194 	 */
3195 
3196 	for (opt = (struct nmreq_option *)(uintptr_t)hdr->nr_options; opt;
3197 	     opt = (struct nmreq_option *)(uintptr_t)opt->nro_next)
3198 		if (opt->nro_status == EOPNOTSUPP)
3199 			return EOPNOTSUPP;
3200 
3201 	return 0;
3202 }
3203 
3204 /*
3205  * select(2) and poll(2) handlers for the "netmap" device.
3206  *
3207  * Can be called for one or more queues.
3208  * Return true the event mask corresponding to ready events.
3209  * If there are no ready events (and 'sr' is not NULL), do a
3210  * selrecord on either individual selinfo or on the global one.
3211  * Device-dependent parts (locking and sync of tx/rx rings)
3212  * are done through callbacks.
3213  *
3214  * On linux, arguments are really pwait, the poll table, and 'td' is struct file *
3215  * The first one is remapped to pwait as selrecord() uses the name as an
3216  * hidden argument.
3217  */
3218 int
3219 netmap_poll(struct netmap_priv_d *priv, int events, NM_SELRECORD_T *sr)
3220 {
3221 	struct netmap_adapter *na;
3222 	struct netmap_kring *kring;
3223 	struct netmap_ring *ring;
3224 	u_int i, want[NR_TXRX], revents = 0;
3225 	NM_SELINFO_T *si[NR_TXRX];
3226 #define want_tx want[NR_TX]
3227 #define want_rx want[NR_RX]
3228 	struct mbq q;	/* packets from RX hw queues to host stack */
3229 
3230 	/*
3231 	 * In order to avoid nested locks, we need to "double check"
3232 	 * txsync and rxsync if we decide to do a selrecord().
3233 	 * retry_tx (and retry_rx, later) prevent looping forever.
3234 	 */
3235 	int retry_tx = 1, retry_rx = 1;
3236 
3237 	/* Transparent mode: send_down is 1 if we have found some
3238 	 * packets to forward (host RX ring --> NIC) during the rx
3239 	 * scan and we have not sent them down to the NIC yet.
3240 	 * Transparent mode requires to bind all rings to a single
3241 	 * file descriptor.
3242 	 */
3243 	int send_down = 0;
3244 	int sync_flags = priv->np_sync_flags;
3245 
3246 	mbq_init(&q);
3247 
3248 	if (unlikely(priv->np_nifp == NULL)) {
3249 		return POLLERR;
3250 	}
3251 	mb(); /* make sure following reads are not from cache */
3252 
3253 	na = priv->np_na;
3254 
3255 	if (unlikely(!nm_netmap_on(na)))
3256 		return POLLERR;
3257 
3258 	if (unlikely(priv->np_csb_atok_base)) {
3259 		nm_prerr("Invalid poll in CSB mode");
3260 		return POLLERR;
3261 	}
3262 
3263 	if (netmap_debug & NM_DEBUG_ON)
3264 		nm_prinf("device %s events 0x%x", na->name, events);
3265 	want_tx = events & (POLLOUT | POLLWRNORM);
3266 	want_rx = events & (POLLIN | POLLRDNORM);
3267 
3268 	/*
3269 	 * If the card has more than one queue AND the file descriptor is
3270 	 * bound to all of them, we sleep on the "global" selinfo, otherwise
3271 	 * we sleep on individual selinfo (FreeBSD only allows two selinfo's
3272 	 * per file descriptor).
3273 	 * The interrupt routine in the driver wake one or the other
3274 	 * (or both) depending on which clients are active.
3275 	 *
3276 	 * rxsync() is only called if we run out of buffers on a POLLIN.
3277 	 * txsync() is called if we run out of buffers on POLLOUT, or
3278 	 * there are pending packets to send. The latter can be disabled
3279 	 * passing NETMAP_NO_TX_POLL in the NIOCREG call.
3280 	 */
3281 	si[NR_RX] = nm_si_user(priv, NR_RX) ? &na->si[NR_RX] :
3282 				&na->rx_rings[priv->np_qfirst[NR_RX]]->si;
3283 	si[NR_TX] = nm_si_user(priv, NR_TX) ? &na->si[NR_TX] :
3284 				&na->tx_rings[priv->np_qfirst[NR_TX]]->si;
3285 
3286 #ifdef __FreeBSD__
3287 	/*
3288 	 * We start with a lock free round which is cheap if we have
3289 	 * slots available. If this fails, then lock and call the sync
3290 	 * routines. We can't do this on Linux, as the contract says
3291 	 * that we must call nm_os_selrecord() unconditionally.
3292 	 */
3293 	if (want_tx) {
3294 		const enum txrx t = NR_TX;
3295 		for (i = priv->np_qfirst[t]; i < priv->np_qlast[t]; i++) {
3296 			kring = NMR(na, t)[i];
3297 			if (kring->ring->cur != kring->ring->tail) {
3298 				/* Some unseen TX space is available, so what
3299 				 * we don't need to run txsync. */
3300 				revents |= want[t];
3301 				want[t] = 0;
3302 				break;
3303 			}
3304 		}
3305 	}
3306 	if (want_rx) {
3307 		const enum txrx t = NR_RX;
3308 		int rxsync_needed = 0;
3309 
3310 		for (i = priv->np_qfirst[t]; i < priv->np_qlast[t]; i++) {
3311 			kring = NMR(na, t)[i];
3312 			if (kring->ring->cur == kring->ring->tail
3313 				|| kring->rhead != kring->ring->head) {
3314 				/* There are no unseen packets on this ring,
3315 				 * or there are some buffers to be returned
3316 				 * to the netmap port. We therefore go ahead
3317 				 * and run rxsync. */
3318 				rxsync_needed = 1;
3319 				break;
3320 			}
3321 		}
3322 		if (!rxsync_needed) {
3323 			revents |= want_rx;
3324 			want_rx = 0;
3325 		}
3326 	}
3327 #endif
3328 
3329 #ifdef linux
3330 	/* The selrecord must be unconditional on linux. */
3331 	nm_os_selrecord(sr, si[NR_RX]);
3332 	nm_os_selrecord(sr, si[NR_TX]);
3333 #endif /* linux */
3334 
3335 	/*
3336 	 * If we want to push packets out (priv->np_txpoll) or
3337 	 * want_tx is still set, we must issue txsync calls
3338 	 * (on all rings, to avoid that the tx rings stall).
3339 	 * Fortunately, normal tx mode has np_txpoll set.
3340 	 */
3341 	if (priv->np_txpoll || want_tx) {
3342 		/*
3343 		 * The first round checks if anyone is ready, if not
3344 		 * do a selrecord and another round to handle races.
3345 		 * want_tx goes to 0 if any space is found, and is
3346 		 * used to skip rings with no pending transmissions.
3347 		 */
3348 flush_tx:
3349 		for (i = priv->np_qfirst[NR_TX]; i < priv->np_qlast[NR_TX]; i++) {
3350 			int found = 0;
3351 
3352 			kring = na->tx_rings[i];
3353 			ring = kring->ring;
3354 
3355 			/*
3356 			 * Don't try to txsync this TX ring if we already found some
3357 			 * space in some of the TX rings (want_tx == 0) and there are no
3358 			 * TX slots in this ring that need to be flushed to the NIC
3359 			 * (head == hwcur).
3360 			 */
3361 			if (!send_down && !want_tx && ring->head == kring->nr_hwcur)
3362 				continue;
3363 
3364 			if (nm_kr_tryget(kring, 1, &revents))
3365 				continue;
3366 
3367 			if (nm_txsync_prologue(kring, ring) >= kring->nkr_num_slots) {
3368 				netmap_ring_reinit(kring);
3369 				revents |= POLLERR;
3370 			} else {
3371 				if (kring->nm_sync(kring, sync_flags))
3372 					revents |= POLLERR;
3373 				else
3374 					nm_sync_finalize(kring);
3375 			}
3376 
3377 			/*
3378 			 * If we found new slots, notify potential
3379 			 * listeners on the same ring.
3380 			 * Since we just did a txsync, look at the copies
3381 			 * of cur,tail in the kring.
3382 			 */
3383 			found = kring->rcur != kring->rtail;
3384 			nm_kr_put(kring);
3385 			if (found) { /* notify other listeners */
3386 				revents |= want_tx;
3387 				want_tx = 0;
3388 #ifndef linux
3389 				kring->nm_notify(kring, 0);
3390 #endif /* linux */
3391 			}
3392 		}
3393 		/* if there were any packet to forward we must have handled them by now */
3394 		send_down = 0;
3395 		if (want_tx && retry_tx && sr) {
3396 #ifndef linux
3397 			nm_os_selrecord(sr, si[NR_TX]);
3398 #endif /* !linux */
3399 			retry_tx = 0;
3400 			goto flush_tx;
3401 		}
3402 	}
3403 
3404 	/*
3405 	 * If want_rx is still set scan receive rings.
3406 	 * Do it on all rings because otherwise we starve.
3407 	 */
3408 	if (want_rx) {
3409 		/* two rounds here for race avoidance */
3410 do_retry_rx:
3411 		for (i = priv->np_qfirst[NR_RX]; i < priv->np_qlast[NR_RX]; i++) {
3412 			int found = 0;
3413 
3414 			kring = na->rx_rings[i];
3415 			ring = kring->ring;
3416 
3417 			if (unlikely(nm_kr_tryget(kring, 1, &revents)))
3418 				continue;
3419 
3420 			if (nm_rxsync_prologue(kring, ring) >= kring->nkr_num_slots) {
3421 				netmap_ring_reinit(kring);
3422 				revents |= POLLERR;
3423 			}
3424 			/* now we can use kring->rcur, rtail */
3425 
3426 			/*
3427 			 * transparent mode support: collect packets from
3428 			 * hw rxring(s) that have been released by the user
3429 			 */
3430 			if (nm_may_forward_up(kring)) {
3431 				netmap_grab_packets(kring, &q, netmap_fwd);
3432 			}
3433 
3434 			/* Clear the NR_FORWARD flag anyway, it may be set by
3435 			 * the nm_sync() below only on for the host RX ring (see
3436 			 * netmap_rxsync_from_host()). */
3437 			kring->nr_kflags &= ~NR_FORWARD;
3438 			if (kring->nm_sync(kring, sync_flags))
3439 				revents |= POLLERR;
3440 			else
3441 				nm_sync_finalize(kring);
3442 			send_down |= (kring->nr_kflags & NR_FORWARD);
3443 			ring_timestamp_set(ring);
3444 			found = kring->rcur != kring->rtail;
3445 			nm_kr_put(kring);
3446 			if (found) {
3447 				revents |= want_rx;
3448 				retry_rx = 0;
3449 #ifndef linux
3450 				kring->nm_notify(kring, 0);
3451 #endif /* linux */
3452 			}
3453 		}
3454 
3455 #ifndef linux
3456 		if (retry_rx && sr) {
3457 			nm_os_selrecord(sr, si[NR_RX]);
3458 		}
3459 #endif /* !linux */
3460 		if (send_down || retry_rx) {
3461 			retry_rx = 0;
3462 			if (send_down)
3463 				goto flush_tx; /* and retry_rx */
3464 			else
3465 				goto do_retry_rx;
3466 		}
3467 	}
3468 
3469 	/*
3470 	 * Transparent mode: released bufs (i.e. between kring->nr_hwcur and
3471 	 * ring->head) marked with NS_FORWARD on hw rx rings are passed up
3472 	 * to the host stack.
3473 	 */
3474 
3475 	if (mbq_peek(&q)) {
3476 		netmap_send_up(na->ifp, &q);
3477 	}
3478 
3479 	return (revents);
3480 #undef want_tx
3481 #undef want_rx
3482 }
3483 
3484 int
3485 nma_intr_enable(struct netmap_adapter *na, int onoff)
3486 {
3487 	bool changed = false;
3488 	enum txrx t;
3489 	int i;
3490 
3491 	for_rx_tx(t) {
3492 		for (i = 0; i < nma_get_nrings(na, t); i++) {
3493 			struct netmap_kring *kring = NMR(na, t)[i];
3494 			int on = !(kring->nr_kflags & NKR_NOINTR);
3495 
3496 			if (!!onoff != !!on) {
3497 				changed = true;
3498 			}
3499 			if (onoff) {
3500 				kring->nr_kflags &= ~NKR_NOINTR;
3501 			} else {
3502 				kring->nr_kflags |= NKR_NOINTR;
3503 			}
3504 		}
3505 	}
3506 
3507 	if (!changed) {
3508 		return 0; /* nothing to do */
3509 	}
3510 
3511 	if (!na->nm_intr) {
3512 		nm_prerr("Cannot %s interrupts for %s", onoff ? "enable" : "disable",
3513 		  na->name);
3514 		return -1;
3515 	}
3516 
3517 	na->nm_intr(na, onoff);
3518 
3519 	return 0;
3520 }
3521 
3522 
3523 /*-------------------- driver support routines -------------------*/
3524 
3525 /* default notify callback */
3526 static int
3527 netmap_notify(struct netmap_kring *kring, int flags)
3528 {
3529 	struct netmap_adapter *na = kring->notify_na;
3530 	enum txrx t = kring->tx;
3531 
3532 	nm_os_selwakeup(&kring->si);
3533 	/* optimization: avoid a wake up on the global
3534 	 * queue if nobody has registered for more
3535 	 * than one ring
3536 	 */
3537 	if (na->si_users[t] > 0)
3538 		nm_os_selwakeup(&na->si[t]);
3539 
3540 	return NM_IRQ_COMPLETED;
3541 }
3542 
3543 /* called by all routines that create netmap_adapters.
3544  * provide some defaults and get a reference to the
3545  * memory allocator
3546  */
3547 int
3548 netmap_attach_common(struct netmap_adapter *na)
3549 {
3550 	if (!na->rx_buf_maxsize) {
3551 		/* Set a conservative default (larger is safer). */
3552 		na->rx_buf_maxsize = PAGE_SIZE;
3553 	}
3554 
3555 #ifdef __FreeBSD__
3556 	if (na->na_flags & NAF_HOST_RINGS && na->ifp) {
3557 		na->if_input = na->ifp->if_input; /* for netmap_send_up */
3558 	}
3559 	na->pdev = na; /* make sure netmap_mem_map() is called */
3560 #endif /* __FreeBSD__ */
3561 	if (na->na_flags & NAF_HOST_RINGS) {
3562 		if (na->num_host_rx_rings == 0)
3563 			na->num_host_rx_rings = 1;
3564 		if (na->num_host_tx_rings == 0)
3565 			na->num_host_tx_rings = 1;
3566 	}
3567 	if (na->nm_krings_create == NULL) {
3568 		/* we assume that we have been called by a driver,
3569 		 * since other port types all provide their own
3570 		 * nm_krings_create
3571 		 */
3572 		na->nm_krings_create = netmap_hw_krings_create;
3573 		na->nm_krings_delete = netmap_hw_krings_delete;
3574 	}
3575 	if (na->nm_notify == NULL)
3576 		na->nm_notify = netmap_notify;
3577 	na->active_fds = 0;
3578 
3579 	if (na->nm_mem == NULL) {
3580 		/* use the global allocator */
3581 		na->nm_mem = netmap_mem_get(&nm_mem);
3582 	}
3583 #ifdef WITH_VALE
3584 	if (na->nm_bdg_attach == NULL)
3585 		/* no special nm_bdg_attach callback. On VALE
3586 		 * attach, we need to interpose a bwrap
3587 		 */
3588 		na->nm_bdg_attach = netmap_default_bdg_attach;
3589 #endif
3590 
3591 	return 0;
3592 }
3593 
3594 /* Wrapper for the register callback provided netmap-enabled
3595  * hardware drivers.
3596  * nm_iszombie(na) means that the driver module has been
3597  * unloaded, so we cannot call into it.
3598  * nm_os_ifnet_lock() must guarantee mutual exclusion with
3599  * module unloading.
3600  */
3601 static int
3602 netmap_hw_reg(struct netmap_adapter *na, int onoff)
3603 {
3604 	struct netmap_hw_adapter *hwna =
3605 		(struct netmap_hw_adapter*)na;
3606 	int error = 0;
3607 
3608 	nm_os_ifnet_lock();
3609 
3610 	if (nm_iszombie(na)) {
3611 		if (onoff) {
3612 			error = ENXIO;
3613 		} else if (na != NULL) {
3614 			na->na_flags &= ~NAF_NETMAP_ON;
3615 		}
3616 		goto out;
3617 	}
3618 
3619 	error = hwna->nm_hw_register(na, onoff);
3620 
3621 out:
3622 	nm_os_ifnet_unlock();
3623 
3624 	return error;
3625 }
3626 
3627 static void
3628 netmap_hw_dtor(struct netmap_adapter *na)
3629 {
3630 	if (na->ifp == NULL)
3631 		return;
3632 
3633 	NM_DETACH_NA(na->ifp);
3634 }
3635 
3636 
3637 /*
3638  * Allocate a netmap_adapter object, and initialize it from the
3639  * 'arg' passed by the driver on attach.
3640  * We allocate a block of memory of 'size' bytes, which has room
3641  * for struct netmap_adapter plus additional room private to
3642  * the caller.
3643  * Return 0 on success, ENOMEM otherwise.
3644  */
3645 int
3646 netmap_attach_ext(struct netmap_adapter *arg, size_t size, int override_reg)
3647 {
3648 	struct netmap_hw_adapter *hwna = NULL;
3649 	struct ifnet *ifp = NULL;
3650 
3651 	if (size < sizeof(struct netmap_hw_adapter)) {
3652 		if (netmap_debug & NM_DEBUG_ON)
3653 			nm_prerr("Invalid netmap adapter size %d", (int)size);
3654 		return EINVAL;
3655 	}
3656 
3657 	if (arg == NULL || arg->ifp == NULL) {
3658 		if (netmap_debug & NM_DEBUG_ON)
3659 			nm_prerr("either arg or arg->ifp is NULL");
3660 		return EINVAL;
3661 	}
3662 
3663 	if (arg->num_tx_rings == 0 || arg->num_rx_rings == 0) {
3664 		if (netmap_debug & NM_DEBUG_ON)
3665 			nm_prerr("%s: invalid rings tx %d rx %d",
3666 				arg->name, arg->num_tx_rings, arg->num_rx_rings);
3667 		return EINVAL;
3668 	}
3669 
3670 	ifp = arg->ifp;
3671 	if (NM_NA_CLASH(ifp)) {
3672 		/* If NA(ifp) is not null but there is no valid netmap
3673 		 * adapter it means that someone else is using the same
3674 		 * pointer (e.g. ax25_ptr on linux). This happens for
3675 		 * instance when also PF_RING is in use. */
3676 		nm_prerr("Error: netmap adapter hook is busy");
3677 		return EBUSY;
3678 	}
3679 
3680 	hwna = nm_os_malloc(size);
3681 	if (hwna == NULL)
3682 		goto fail;
3683 	hwna->up = *arg;
3684 	hwna->up.na_flags |= NAF_HOST_RINGS | NAF_NATIVE;
3685 	strlcpy(hwna->up.name, ifp->if_xname, sizeof(hwna->up.name));
3686 	if (override_reg) {
3687 		hwna->nm_hw_register = hwna->up.nm_register;
3688 		hwna->up.nm_register = netmap_hw_reg;
3689 	}
3690 	if (netmap_attach_common(&hwna->up)) {
3691 		nm_os_free(hwna);
3692 		goto fail;
3693 	}
3694 	netmap_adapter_get(&hwna->up);
3695 
3696 	NM_ATTACH_NA(ifp, &hwna->up);
3697 
3698 	nm_os_onattach(ifp);
3699 
3700 	if (arg->nm_dtor == NULL) {
3701 		hwna->up.nm_dtor = netmap_hw_dtor;
3702 	}
3703 
3704 	if_printf(ifp, "netmap queues/slots: TX %d/%d, RX %d/%d\n",
3705 	    hwna->up.num_tx_rings, hwna->up.num_tx_desc,
3706 	    hwna->up.num_rx_rings, hwna->up.num_rx_desc);
3707 	return 0;
3708 
3709 fail:
3710 	nm_prerr("fail, arg %p ifp %p na %p", arg, ifp, hwna);
3711 	return (hwna ? EINVAL : ENOMEM);
3712 }
3713 
3714 
3715 int
3716 netmap_attach(struct netmap_adapter *arg)
3717 {
3718 	return netmap_attach_ext(arg, sizeof(struct netmap_hw_adapter),
3719 			1 /* override nm_reg */);
3720 }
3721 
3722 
3723 void
3724 NM_DBG(netmap_adapter_get)(struct netmap_adapter *na)
3725 {
3726 	if (!na) {
3727 		return;
3728 	}
3729 
3730 	refcount_acquire(&na->na_refcount);
3731 }
3732 
3733 
3734 /* returns 1 iff the netmap_adapter is destroyed */
3735 int
3736 NM_DBG(netmap_adapter_put)(struct netmap_adapter *na)
3737 {
3738 	if (!na)
3739 		return 1;
3740 
3741 	if (!refcount_release(&na->na_refcount))
3742 		return 0;
3743 
3744 	if (na->nm_dtor)
3745 		na->nm_dtor(na);
3746 
3747 	if (na->tx_rings) { /* XXX should not happen */
3748 		if (netmap_debug & NM_DEBUG_ON)
3749 			nm_prerr("freeing leftover tx_rings");
3750 		na->nm_krings_delete(na);
3751 	}
3752 	netmap_pipe_dealloc(na);
3753 	if (na->nm_mem)
3754 		netmap_mem_put(na->nm_mem);
3755 	bzero(na, sizeof(*na));
3756 	nm_os_free(na);
3757 
3758 	return 1;
3759 }
3760 
3761 /* nm_krings_create callback for all hardware native adapters */
3762 int
3763 netmap_hw_krings_create(struct netmap_adapter *na)
3764 {
3765 	int ret = netmap_krings_create(na, 0);
3766 	if (ret == 0) {
3767 		/* initialize the mbq for the sw rx ring */
3768 		u_int lim = netmap_real_rings(na, NR_RX), i;
3769 		for (i = na->num_rx_rings; i < lim; i++) {
3770 			mbq_safe_init(&NMR(na, NR_RX)[i]->rx_queue);
3771 		}
3772 		ND("initialized sw rx queue %d", na->num_rx_rings);
3773 	}
3774 	return ret;
3775 }
3776 
3777 
3778 
3779 /*
3780  * Called on module unload by the netmap-enabled drivers
3781  */
3782 void
3783 netmap_detach(struct ifnet *ifp)
3784 {
3785 	struct netmap_adapter *na = NA(ifp);
3786 
3787 	if (!na)
3788 		return;
3789 
3790 	NMG_LOCK();
3791 	netmap_set_all_rings(na, NM_KR_LOCKED);
3792 	/*
3793 	 * if the netmap adapter is not native, somebody
3794 	 * changed it, so we can not release it here.
3795 	 * The NAF_ZOMBIE flag will notify the new owner that
3796 	 * the driver is gone.
3797 	 */
3798 	if (!(na->na_flags & NAF_NATIVE) || !netmap_adapter_put(na)) {
3799 		na->na_flags |= NAF_ZOMBIE;
3800 	}
3801 	/* give active users a chance to notice that NAF_ZOMBIE has been
3802 	 * turned on, so that they can stop and return an error to userspace.
3803 	 * Note that this becomes a NOP if there are no active users and,
3804 	 * therefore, the put() above has deleted the na, since now NA(ifp) is
3805 	 * NULL.
3806 	 */
3807 	netmap_enable_all_rings(ifp);
3808 	NMG_UNLOCK();
3809 }
3810 
3811 
3812 /*
3813  * Intercept packets from the network stack and pass them
3814  * to netmap as incoming packets on the 'software' ring.
3815  *
3816  * We only store packets in a bounded mbq and then copy them
3817  * in the relevant rxsync routine.
3818  *
3819  * We rely on the OS to make sure that the ifp and na do not go
3820  * away (typically the caller checks for IFF_DRV_RUNNING or the like).
3821  * In nm_register() or whenever there is a reinitialization,
3822  * we make sure to make the mode change visible here.
3823  */
3824 int
3825 netmap_transmit(struct ifnet *ifp, struct mbuf *m)
3826 {
3827 	struct netmap_adapter *na = NA(ifp);
3828 	struct netmap_kring *kring, *tx_kring;
3829 	u_int len = MBUF_LEN(m);
3830 	u_int error = ENOBUFS;
3831 	unsigned int txr;
3832 	struct mbq *q;
3833 	int busy;
3834 	u_int i;
3835 
3836 	i = MBUF_TXQ(m);
3837 	if (i >= na->num_host_rx_rings) {
3838 		i = i % na->num_host_rx_rings;
3839 	}
3840 	kring = NMR(na, NR_RX)[nma_get_nrings(na, NR_RX) + i];
3841 
3842 	// XXX [Linux] we do not need this lock
3843 	// if we follow the down/configure/up protocol -gl
3844 	// mtx_lock(&na->core_lock);
3845 
3846 	if (!nm_netmap_on(na)) {
3847 		nm_prerr("%s not in netmap mode anymore", na->name);
3848 		error = ENXIO;
3849 		goto done;
3850 	}
3851 
3852 	txr = MBUF_TXQ(m);
3853 	if (txr >= na->num_tx_rings) {
3854 		txr %= na->num_tx_rings;
3855 	}
3856 	tx_kring = NMR(na, NR_TX)[txr];
3857 
3858 	if (tx_kring->nr_mode == NKR_NETMAP_OFF) {
3859 		return MBUF_TRANSMIT(na, ifp, m);
3860 	}
3861 
3862 	q = &kring->rx_queue;
3863 
3864 	// XXX reconsider long packets if we handle fragments
3865 	if (len > NETMAP_BUF_SIZE(na)) { /* too long for us */
3866 		nm_prerr("%s from_host, drop packet size %d > %d", na->name,
3867 			len, NETMAP_BUF_SIZE(na));
3868 		goto done;
3869 	}
3870 
3871 	if (!netmap_generic_hwcsum) {
3872 		if (nm_os_mbuf_has_csum_offld(m)) {
3873 			RD(1, "%s drop mbuf that needs checksum offload", na->name);
3874 			goto done;
3875 		}
3876 	}
3877 
3878 	if (nm_os_mbuf_has_seg_offld(m)) {
3879 		RD(1, "%s drop mbuf that needs generic segmentation offload", na->name);
3880 		goto done;
3881 	}
3882 
3883 #ifdef __FreeBSD__
3884 	ETHER_BPF_MTAP(ifp, m);
3885 #endif /* __FreeBSD__ */
3886 
3887 	/* protect against netmap_rxsync_from_host(), netmap_sw_to_nic()
3888 	 * and maybe other instances of netmap_transmit (the latter
3889 	 * not possible on Linux).
3890 	 * We enqueue the mbuf only if we are sure there is going to be
3891 	 * enough room in the host RX ring, otherwise we drop it.
3892 	 */
3893 	mbq_lock(q);
3894 
3895 	busy = kring->nr_hwtail - kring->nr_hwcur;
3896 	if (busy < 0)
3897 		busy += kring->nkr_num_slots;
3898 	if (busy + mbq_len(q) >= kring->nkr_num_slots - 1) {
3899 		RD(2, "%s full hwcur %d hwtail %d qlen %d", na->name,
3900 			kring->nr_hwcur, kring->nr_hwtail, mbq_len(q));
3901 	} else {
3902 		mbq_enqueue(q, m);
3903 		ND(2, "%s %d bufs in queue", na->name, mbq_len(q));
3904 		/* notify outside the lock */
3905 		m = NULL;
3906 		error = 0;
3907 	}
3908 	mbq_unlock(q);
3909 
3910 done:
3911 	if (m)
3912 		m_freem(m);
3913 	/* unconditionally wake up listeners */
3914 	kring->nm_notify(kring, 0);
3915 	/* this is normally netmap_notify(), but for nics
3916 	 * connected to a bridge it is netmap_bwrap_intr_notify(),
3917 	 * that possibly forwards the frames through the switch
3918 	 */
3919 
3920 	return (error);
3921 }
3922 
3923 
3924 /*
3925  * netmap_reset() is called by the driver routines when reinitializing
3926  * a ring. The driver is in charge of locking to protect the kring.
3927  * If native netmap mode is not set just return NULL.
3928  * If native netmap mode is set, in particular, we have to set nr_mode to
3929  * NKR_NETMAP_ON.
3930  */
3931 struct netmap_slot *
3932 netmap_reset(struct netmap_adapter *na, enum txrx tx, u_int n,
3933 	u_int new_cur)
3934 {
3935 	struct netmap_kring *kring;
3936 	int new_hwofs, lim;
3937 
3938 	if (!nm_native_on(na)) {
3939 		ND("interface not in native netmap mode");
3940 		return NULL;	/* nothing to reinitialize */
3941 	}
3942 
3943 	/* XXX note- in the new scheme, we are not guaranteed to be
3944 	 * under lock (e.g. when called on a device reset).
3945 	 * In this case, we should set a flag and do not trust too
3946 	 * much the values. In practice: TODO
3947 	 * - set a RESET flag somewhere in the kring
3948 	 * - do the processing in a conservative way
3949 	 * - let the *sync() fixup at the end.
3950 	 */
3951 	if (tx == NR_TX) {
3952 		if (n >= na->num_tx_rings)
3953 			return NULL;
3954 
3955 		kring = na->tx_rings[n];
3956 
3957 		if (kring->nr_pending_mode == NKR_NETMAP_OFF) {
3958 			kring->nr_mode = NKR_NETMAP_OFF;
3959 			return NULL;
3960 		}
3961 
3962 		// XXX check whether we should use hwcur or rcur
3963 		new_hwofs = kring->nr_hwcur - new_cur;
3964 	} else {
3965 		if (n >= na->num_rx_rings)
3966 			return NULL;
3967 		kring = na->rx_rings[n];
3968 
3969 		if (kring->nr_pending_mode == NKR_NETMAP_OFF) {
3970 			kring->nr_mode = NKR_NETMAP_OFF;
3971 			return NULL;
3972 		}
3973 
3974 		new_hwofs = kring->nr_hwtail - new_cur;
3975 	}
3976 	lim = kring->nkr_num_slots - 1;
3977 	if (new_hwofs > lim)
3978 		new_hwofs -= lim + 1;
3979 
3980 	/* Always set the new offset value and realign the ring. */
3981 	if (netmap_debug & NM_DEBUG_ON)
3982 	    nm_prinf("%s %s%d hwofs %d -> %d, hwtail %d -> %d",
3983 		na->name,
3984 		tx == NR_TX ? "TX" : "RX", n,
3985 		kring->nkr_hwofs, new_hwofs,
3986 		kring->nr_hwtail,
3987 		tx == NR_TX ? lim : kring->nr_hwtail);
3988 	kring->nkr_hwofs = new_hwofs;
3989 	if (tx == NR_TX) {
3990 		kring->nr_hwtail = kring->nr_hwcur + lim;
3991 		if (kring->nr_hwtail > lim)
3992 			kring->nr_hwtail -= lim + 1;
3993 	}
3994 
3995 	/*
3996 	 * Wakeup on the individual and global selwait
3997 	 * We do the wakeup here, but the ring is not yet reconfigured.
3998 	 * However, we are under lock so there are no races.
3999 	 */
4000 	kring->nr_mode = NKR_NETMAP_ON;
4001 	kring->nm_notify(kring, 0);
4002 	return kring->ring->slot;
4003 }
4004 
4005 
4006 /*
4007  * Dispatch rx/tx interrupts to the netmap rings.
4008  *
4009  * "work_done" is non-null on the RX path, NULL for the TX path.
4010  * We rely on the OS to make sure that there is only one active
4011  * instance per queue, and that there is appropriate locking.
4012  *
4013  * The 'notify' routine depends on what the ring is attached to.
4014  * - for a netmap file descriptor, do a selwakeup on the individual
4015  *   waitqueue, plus one on the global one if needed
4016  *   (see netmap_notify)
4017  * - for a nic connected to a switch, call the proper forwarding routine
4018  *   (see netmap_bwrap_intr_notify)
4019  */
4020 int
4021 netmap_common_irq(struct netmap_adapter *na, u_int q, u_int *work_done)
4022 {
4023 	struct netmap_kring *kring;
4024 	enum txrx t = (work_done ? NR_RX : NR_TX);
4025 
4026 	q &= NETMAP_RING_MASK;
4027 
4028 	if (netmap_debug & (NM_DEBUG_RXINTR|NM_DEBUG_TXINTR)) {
4029 	        nm_prlim(5, "received %s queue %d", work_done ? "RX" : "TX" , q);
4030 	}
4031 
4032 	if (q >= nma_get_nrings(na, t))
4033 		return NM_IRQ_PASS; // not a physical queue
4034 
4035 	kring = NMR(na, t)[q];
4036 
4037 	if (kring->nr_mode == NKR_NETMAP_OFF) {
4038 		return NM_IRQ_PASS;
4039 	}
4040 
4041 	if (t == NR_RX) {
4042 		kring->nr_kflags |= NKR_PENDINTR;	// XXX atomic ?
4043 		*work_done = 1; /* do not fire napi again */
4044 	}
4045 
4046 	return kring->nm_notify(kring, 0);
4047 }
4048 
4049 
4050 /*
4051  * Default functions to handle rx/tx interrupts from a physical device.
4052  * "work_done" is non-null on the RX path, NULL for the TX path.
4053  *
4054  * If the card is not in netmap mode, simply return NM_IRQ_PASS,
4055  * so that the caller proceeds with regular processing.
4056  * Otherwise call netmap_common_irq().
4057  *
4058  * If the card is connected to a netmap file descriptor,
4059  * do a selwakeup on the individual queue, plus one on the global one
4060  * if needed (multiqueue card _and_ there are multiqueue listeners),
4061  * and return NR_IRQ_COMPLETED.
4062  *
4063  * Finally, if called on rx from an interface connected to a switch,
4064  * calls the proper forwarding routine.
4065  */
4066 int
4067 netmap_rx_irq(struct ifnet *ifp, u_int q, u_int *work_done)
4068 {
4069 	struct netmap_adapter *na = NA(ifp);
4070 
4071 	/*
4072 	 * XXX emulated netmap mode sets NAF_SKIP_INTR so
4073 	 * we still use the regular driver even though the previous
4074 	 * check fails. It is unclear whether we should use
4075 	 * nm_native_on() here.
4076 	 */
4077 	if (!nm_netmap_on(na))
4078 		return NM_IRQ_PASS;
4079 
4080 	if (na->na_flags & NAF_SKIP_INTR) {
4081 		ND("use regular interrupt");
4082 		return NM_IRQ_PASS;
4083 	}
4084 
4085 	return netmap_common_irq(na, q, work_done);
4086 }
4087 
4088 /* set/clear native flags and if_transmit/netdev_ops */
4089 void
4090 nm_set_native_flags(struct netmap_adapter *na)
4091 {
4092 	struct ifnet *ifp = na->ifp;
4093 
4094 	/* We do the setup for intercepting packets only if we are the
4095 	 * first user of this adapapter. */
4096 	if (na->active_fds > 0) {
4097 		return;
4098 	}
4099 
4100 	na->na_flags |= NAF_NETMAP_ON;
4101 	nm_os_onenter(ifp);
4102 	nm_update_hostrings_mode(na);
4103 }
4104 
4105 void
4106 nm_clear_native_flags(struct netmap_adapter *na)
4107 {
4108 	struct ifnet *ifp = na->ifp;
4109 
4110 	/* We undo the setup for intercepting packets only if we are the
4111 	 * last user of this adapter. */
4112 	if (na->active_fds > 0) {
4113 		return;
4114 	}
4115 
4116 	nm_update_hostrings_mode(na);
4117 	nm_os_onexit(ifp);
4118 
4119 	na->na_flags &= ~NAF_NETMAP_ON;
4120 }
4121 
4122 /*
4123  * Module loader and unloader
4124  *
4125  * netmap_init() creates the /dev/netmap device and initializes
4126  * all global variables. Returns 0 on success, errno on failure
4127  * (but there is no chance)
4128  *
4129  * netmap_fini() destroys everything.
4130  */
4131 
4132 static struct cdev *netmap_dev; /* /dev/netmap character device. */
4133 extern struct cdevsw netmap_cdevsw;
4134 
4135 
4136 void
4137 netmap_fini(void)
4138 {
4139 	if (netmap_dev)
4140 		destroy_dev(netmap_dev);
4141 	/* we assume that there are no longer netmap users */
4142 	nm_os_ifnet_fini();
4143 	netmap_uninit_bridges();
4144 	netmap_mem_fini();
4145 	NMG_LOCK_DESTROY();
4146 	nm_prinf("netmap: unloaded module.");
4147 }
4148 
4149 
4150 int
4151 netmap_init(void)
4152 {
4153 	int error;
4154 
4155 	NMG_LOCK_INIT();
4156 
4157 	error = netmap_mem_init();
4158 	if (error != 0)
4159 		goto fail;
4160 	/*
4161 	 * MAKEDEV_ETERNAL_KLD avoids an expensive check on syscalls
4162 	 * when the module is compiled in.
4163 	 * XXX could use make_dev_credv() to get error number
4164 	 */
4165 	netmap_dev = make_dev_credf(MAKEDEV_ETERNAL_KLD,
4166 		&netmap_cdevsw, 0, NULL, UID_ROOT, GID_WHEEL, 0600,
4167 			      "netmap");
4168 	if (!netmap_dev)
4169 		goto fail;
4170 
4171 	error = netmap_init_bridges();
4172 	if (error)
4173 		goto fail;
4174 
4175 #ifdef __FreeBSD__
4176 	nm_os_vi_init_index();
4177 #endif
4178 
4179 	error = nm_os_ifnet_init();
4180 	if (error)
4181 		goto fail;
4182 
4183 	nm_prinf("netmap: loaded module");
4184 	return (0);
4185 fail:
4186 	netmap_fini();
4187 	return (EINVAL); /* may be incorrect */
4188 }
4189