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