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