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