1 /* 2 * Copyright (C) 2013-2016 Vincenzo Maffione 3 * Copyright (C) 2013-2016 Luigi Rizzo 4 * All rights reserved. 5 * 6 * Redistribution and use in source and binary forms, with or without 7 * modification, are permitted provided that the following conditions 8 * are met: 9 * 1. Redistributions of source code must retain the above copyright 10 * notice, this list of conditions and the following disclaimer. 11 * 2. Redistributions in binary form must reproduce the above copyright 12 * notice, this list of conditions and the following disclaimer in the 13 * documentation and/or other materials provided with the distribution. 14 * 15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 25 * SUCH DAMAGE. 26 */ 27 28 /* 29 * This module implements netmap support on top of standard, 30 * unmodified device drivers. 31 * 32 * A NIOCREGIF request is handled here if the device does not 33 * have native support. TX and RX rings are emulated as follows: 34 * 35 * NIOCREGIF 36 * We preallocate a block of TX mbufs (roughly as many as 37 * tx descriptors; the number is not critical) to speed up 38 * operation during transmissions. The refcount on most of 39 * these buffers is artificially bumped up so we can recycle 40 * them more easily. Also, the destructor is intercepted 41 * so we use it as an interrupt notification to wake up 42 * processes blocked on a poll(). 43 * 44 * For each receive ring we allocate one "struct mbq" 45 * (an mbuf tailq plus a spinlock). We intercept packets 46 * (through if_input) 47 * on the receive path and put them in the mbq from which 48 * netmap receive routines can grab them. 49 * 50 * TX: 51 * in the generic_txsync() routine, netmap buffers are copied 52 * (or linked, in a future) to the preallocated mbufs 53 * and pushed to the transmit queue. Some of these mbufs 54 * (those with NS_REPORT, or otherwise every half ring) 55 * have the refcount=1, others have refcount=2. 56 * When the destructor is invoked, we take that as 57 * a notification that all mbufs up to that one in 58 * the specific ring have been completed, and generate 59 * the equivalent of a transmit interrupt. 60 * 61 * RX: 62 * 63 */ 64 65 #ifdef __FreeBSD__ 66 67 #include <sys/cdefs.h> /* prerequisite */ 68 __FBSDID("$FreeBSD$"); 69 70 #include <sys/types.h> 71 #include <sys/errno.h> 72 #include <sys/malloc.h> 73 #include <sys/lock.h> /* PROT_EXEC */ 74 #include <sys/rwlock.h> 75 #include <sys/socket.h> /* sockaddrs */ 76 #include <sys/selinfo.h> 77 #include <net/if.h> 78 #include <net/if_types.h> 79 #include <net/if_var.h> 80 #include <machine/bus.h> /* bus_dmamap_* in netmap_kern.h */ 81 82 // XXX temporary - D() defined here 83 #include <net/netmap.h> 84 #include <dev/netmap/netmap_kern.h> 85 #include <dev/netmap/netmap_mem2.h> 86 87 #define rtnl_lock() ND("rtnl_lock called") 88 #define rtnl_unlock() ND("rtnl_unlock called") 89 #define MBUF_RXQ(m) ((m)->m_pkthdr.flowid) 90 #define smp_mb() 91 92 /* 93 * FreeBSD mbuf allocator/deallocator in emulation mode: 94 */ 95 #if __FreeBSD_version < 1100000 96 97 /* 98 * For older versions of FreeBSD: 99 * 100 * We allocate EXT_PACKET mbuf+clusters, but need to set M_NOFREE 101 * so that the destructor, if invoked, will not free the packet. 102 * In principle we should set the destructor only on demand, 103 * but since there might be a race we better do it on allocation. 104 * As a consequence, we also need to set the destructor or we 105 * would leak buffers. 106 */ 107 108 /* mbuf destructor, also need to change the type to EXT_EXTREF, 109 * add an M_NOFREE flag, and then clear the flag and 110 * chain into uma_zfree(zone_pack, mf) 111 * (or reinstall the buffer ?) 112 */ 113 #define SET_MBUF_DESTRUCTOR(m, fn) do { \ 114 (m)->m_ext.ext_free = (void *)fn; \ 115 (m)->m_ext.ext_type = EXT_EXTREF; \ 116 } while (0) 117 118 static int 119 void_mbuf_dtor(struct mbuf *m, void *arg1, void *arg2) 120 { 121 /* restore original mbuf */ 122 m->m_ext.ext_buf = m->m_data = m->m_ext.ext_arg1; 123 m->m_ext.ext_arg1 = NULL; 124 m->m_ext.ext_type = EXT_PACKET; 125 m->m_ext.ext_free = NULL; 126 if (MBUF_REFCNT(m) == 0) 127 SET_MBUF_REFCNT(m, 1); 128 uma_zfree(zone_pack, m); 129 130 return 0; 131 } 132 133 static inline struct mbuf * 134 nm_os_get_mbuf(struct ifnet *ifp, int len) 135 { 136 struct mbuf *m; 137 138 (void)ifp; 139 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR); 140 if (m) { 141 /* m_getcl() (mb_ctor_mbuf) has an assert that checks that 142 * M_NOFREE flag is not specified as third argument, 143 * so we have to set M_NOFREE after m_getcl(). */ 144 m->m_flags |= M_NOFREE; 145 m->m_ext.ext_arg1 = m->m_ext.ext_buf; // XXX save 146 m->m_ext.ext_free = (void *)void_mbuf_dtor; 147 m->m_ext.ext_type = EXT_EXTREF; 148 ND(5, "create m %p refcnt %d", m, MBUF_REFCNT(m)); 149 } 150 return m; 151 } 152 153 #else /* __FreeBSD_version >= 1100000 */ 154 155 /* 156 * Newer versions of FreeBSD, using a straightforward scheme. 157 * 158 * We allocate mbufs with m_gethdr(), since the mbuf header is needed 159 * by the driver. We also attach a customly-provided external storage, 160 * which in this case is a netmap buffer. When calling m_extadd(), however 161 * we pass a NULL address, since the real address (and length) will be 162 * filled in by nm_os_generic_xmit_frame() right before calling 163 * if_transmit(). 164 * 165 * The dtor function does nothing, however we need it since mb_free_ext() 166 * has a KASSERT(), checking that the mbuf dtor function is not NULL. 167 */ 168 169 static void void_mbuf_dtor(struct mbuf *m, void *arg1, void *arg2) { } 170 171 #define SET_MBUF_DESTRUCTOR(m, fn) do { \ 172 (m)->m_ext.ext_free = (fn != NULL) ? \ 173 (void *)fn : (void *)void_mbuf_dtor; \ 174 } while (0) 175 176 static inline struct mbuf * 177 nm_os_get_mbuf(struct ifnet *ifp, int len) 178 { 179 struct mbuf *m; 180 181 (void)ifp; 182 (void)len; 183 184 m = m_gethdr(M_NOWAIT, MT_DATA); 185 if (m == NULL) { 186 return m; 187 } 188 189 m_extadd(m, NULL /* buf */, 0 /* size */, void_mbuf_dtor, 190 NULL, NULL, 0, EXT_NET_DRV); 191 192 return m; 193 } 194 195 #endif /* __FreeBSD_version >= 1100000 */ 196 197 #elif defined _WIN32 198 199 #include "win_glue.h" 200 201 #define rtnl_lock() ND("rtnl_lock called") 202 #define rtnl_unlock() ND("rtnl_unlock called") 203 #define MBUF_TXQ(m) 0//((m)->m_pkthdr.flowid) 204 #define MBUF_RXQ(m) 0//((m)->m_pkthdr.flowid) 205 #define smp_mb() //XXX: to be correctly defined 206 207 #else /* linux */ 208 209 #include "bsd_glue.h" 210 211 #include <linux/rtnetlink.h> /* rtnl_[un]lock() */ 212 #include <linux/ethtool.h> /* struct ethtool_ops, get_ringparam */ 213 #include <linux/hrtimer.h> 214 215 static inline struct mbuf * 216 nm_os_get_mbuf(struct ifnet *ifp, int len) 217 { 218 return alloc_skb(ifp->needed_headroom + len + 219 ifp->needed_tailroom, GFP_ATOMIC); 220 } 221 222 #endif /* linux */ 223 224 225 /* Common headers. */ 226 #include <net/netmap.h> 227 #include <dev/netmap/netmap_kern.h> 228 #include <dev/netmap/netmap_mem2.h> 229 230 231 #define for_each_kring_n(_i, _k, _karr, _n) \ 232 for (_k=_karr, _i = 0; _i < _n; (_k)++, (_i)++) 233 234 #define for_each_tx_kring(_i, _k, _na) \ 235 for_each_kring_n(_i, _k, (_na)->tx_rings, (_na)->num_tx_rings) 236 #define for_each_tx_kring_h(_i, _k, _na) \ 237 for_each_kring_n(_i, _k, (_na)->tx_rings, (_na)->num_tx_rings + 1) 238 239 #define for_each_rx_kring(_i, _k, _na) \ 240 for_each_kring_n(_i, _k, (_na)->rx_rings, (_na)->num_rx_rings) 241 #define for_each_rx_kring_h(_i, _k, _na) \ 242 for_each_kring_n(_i, _k, (_na)->rx_rings, (_na)->num_rx_rings + 1) 243 244 245 /* ======================== PERFORMANCE STATISTICS =========================== */ 246 247 #ifdef RATE_GENERIC 248 #define IFRATE(x) x 249 struct rate_stats { 250 unsigned long txpkt; 251 unsigned long txsync; 252 unsigned long txirq; 253 unsigned long txrepl; 254 unsigned long txdrop; 255 unsigned long rxpkt; 256 unsigned long rxirq; 257 unsigned long rxsync; 258 }; 259 260 struct rate_context { 261 unsigned refcount; 262 struct timer_list timer; 263 struct rate_stats new; 264 struct rate_stats old; 265 }; 266 267 #define RATE_PRINTK(_NAME_) \ 268 printk( #_NAME_ " = %lu Hz\n", (cur._NAME_ - ctx->old._NAME_)/RATE_PERIOD); 269 #define RATE_PERIOD 2 270 static void rate_callback(unsigned long arg) 271 { 272 struct rate_context * ctx = (struct rate_context *)arg; 273 struct rate_stats cur = ctx->new; 274 int r; 275 276 RATE_PRINTK(txpkt); 277 RATE_PRINTK(txsync); 278 RATE_PRINTK(txirq); 279 RATE_PRINTK(txrepl); 280 RATE_PRINTK(txdrop); 281 RATE_PRINTK(rxpkt); 282 RATE_PRINTK(rxsync); 283 RATE_PRINTK(rxirq); 284 printk("\n"); 285 286 ctx->old = cur; 287 r = mod_timer(&ctx->timer, jiffies + 288 msecs_to_jiffies(RATE_PERIOD * 1000)); 289 if (unlikely(r)) 290 D("[v1000] Error: mod_timer()"); 291 } 292 293 static struct rate_context rate_ctx; 294 295 void generic_rate(int txp, int txs, int txi, int rxp, int rxs, int rxi) 296 { 297 if (txp) rate_ctx.new.txpkt++; 298 if (txs) rate_ctx.new.txsync++; 299 if (txi) rate_ctx.new.txirq++; 300 if (rxp) rate_ctx.new.rxpkt++; 301 if (rxs) rate_ctx.new.rxsync++; 302 if (rxi) rate_ctx.new.rxirq++; 303 } 304 305 #else /* !RATE */ 306 #define IFRATE(x) 307 #endif /* !RATE */ 308 309 310 /* ========== GENERIC (EMULATED) NETMAP ADAPTER SUPPORT ============= */ 311 312 /* 313 * Wrapper used by the generic adapter layer to notify 314 * the poller threads. Differently from netmap_rx_irq(), we check 315 * only NAF_NETMAP_ON instead of NAF_NATIVE_ON to enable the irq. 316 */ 317 void 318 netmap_generic_irq(struct netmap_adapter *na, u_int q, u_int *work_done) 319 { 320 if (unlikely(!nm_netmap_on(na))) 321 return; 322 323 netmap_common_irq(na, q, work_done); 324 #ifdef RATE_GENERIC 325 if (work_done) 326 rate_ctx.new.rxirq++; 327 else 328 rate_ctx.new.txirq++; 329 #endif /* RATE_GENERIC */ 330 } 331 332 static int 333 generic_netmap_unregister(struct netmap_adapter *na) 334 { 335 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na; 336 struct netmap_kring *kring = NULL; 337 int i, r; 338 339 if (na->active_fds == 0) { 340 rtnl_lock(); 341 342 na->na_flags &= ~NAF_NETMAP_ON; 343 344 /* Release packet steering control. */ 345 nm_os_catch_tx(gna, 0); 346 347 /* Stop intercepting packets on the RX path. */ 348 nm_os_catch_rx(gna, 0); 349 350 rtnl_unlock(); 351 } 352 353 for_each_rx_kring_h(r, kring, na) { 354 if (nm_kring_pending_off(kring)) { 355 D("Emulated adapter: ring '%s' deactivated", kring->name); 356 kring->nr_mode = NKR_NETMAP_OFF; 357 } 358 } 359 for_each_tx_kring_h(r, kring, na) { 360 if (nm_kring_pending_off(kring)) { 361 kring->nr_mode = NKR_NETMAP_OFF; 362 D("Emulated adapter: ring '%s' deactivated", kring->name); 363 } 364 } 365 366 for_each_rx_kring(r, kring, na) { 367 /* Free the mbufs still pending in the RX queues, 368 * that did not end up into the corresponding netmap 369 * RX rings. */ 370 mbq_safe_purge(&kring->rx_queue); 371 nm_os_mitigation_cleanup(&gna->mit[r]); 372 } 373 374 /* Decrement reference counter for the mbufs in the 375 * TX pools. These mbufs can be still pending in drivers, 376 * (e.g. this happens with virtio-net driver, which 377 * does lazy reclaiming of transmitted mbufs). */ 378 for_each_tx_kring(r, kring, na) { 379 /* We must remove the destructor on the TX event, 380 * because the destructor invokes netmap code, and 381 * the netmap module may disappear before the 382 * TX event is consumed. */ 383 mtx_lock_spin(&kring->tx_event_lock); 384 if (kring->tx_event) { 385 SET_MBUF_DESTRUCTOR(kring->tx_event, NULL); 386 } 387 kring->tx_event = NULL; 388 mtx_unlock_spin(&kring->tx_event_lock); 389 } 390 391 if (na->active_fds == 0) { 392 nm_os_free(gna->mit); 393 394 for_each_rx_kring(r, kring, na) { 395 mbq_safe_fini(&kring->rx_queue); 396 } 397 398 for_each_tx_kring(r, kring, na) { 399 mtx_destroy(&kring->tx_event_lock); 400 if (kring->tx_pool == NULL) { 401 continue; 402 } 403 404 for (i=0; i<na->num_tx_desc; i++) { 405 if (kring->tx_pool[i]) { 406 m_freem(kring->tx_pool[i]); 407 } 408 } 409 nm_os_free(kring->tx_pool); 410 kring->tx_pool = NULL; 411 } 412 413 #ifdef RATE_GENERIC 414 if (--rate_ctx.refcount == 0) { 415 D("del_timer()"); 416 del_timer(&rate_ctx.timer); 417 } 418 #endif 419 D("Emulated adapter for %s deactivated", na->name); 420 } 421 422 return 0; 423 } 424 425 /* Enable/disable netmap mode for a generic network interface. */ 426 static int 427 generic_netmap_register(struct netmap_adapter *na, int enable) 428 { 429 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na; 430 struct netmap_kring *kring = NULL; 431 int error; 432 int i, r; 433 434 if (!na) { 435 return EINVAL; 436 } 437 438 if (!enable) { 439 /* This is actually an unregif. */ 440 return generic_netmap_unregister(na); 441 } 442 443 if (na->active_fds == 0) { 444 D("Emulated adapter for %s activated", na->name); 445 /* Do all memory allocations when (na->active_fds == 0), to 446 * simplify error management. */ 447 448 /* Allocate memory for mitigation support on all the rx queues. */ 449 gna->mit = nm_os_malloc(na->num_rx_rings * sizeof(struct nm_generic_mit)); 450 if (!gna->mit) { 451 D("mitigation allocation failed"); 452 error = ENOMEM; 453 goto out; 454 } 455 456 for_each_rx_kring(r, kring, na) { 457 /* Init mitigation support. */ 458 nm_os_mitigation_init(&gna->mit[r], r, na); 459 460 /* Initialize the rx queue, as generic_rx_handler() can 461 * be called as soon as nm_os_catch_rx() returns. 462 */ 463 mbq_safe_init(&kring->rx_queue); 464 } 465 466 /* 467 * Prepare mbuf pools (parallel to the tx rings), for packet 468 * transmission. Don't preallocate the mbufs here, it's simpler 469 * to leave this task to txsync. 470 */ 471 for_each_tx_kring(r, kring, na) { 472 kring->tx_pool = NULL; 473 } 474 for_each_tx_kring(r, kring, na) { 475 kring->tx_pool = 476 nm_os_malloc(na->num_tx_desc * sizeof(struct mbuf *)); 477 if (!kring->tx_pool) { 478 D("tx_pool allocation failed"); 479 error = ENOMEM; 480 goto free_tx_pools; 481 } 482 mtx_init(&kring->tx_event_lock, "tx_event_lock", 483 NULL, MTX_SPIN); 484 } 485 } 486 487 for_each_rx_kring_h(r, kring, na) { 488 if (nm_kring_pending_on(kring)) { 489 D("Emulated adapter: ring '%s' activated", kring->name); 490 kring->nr_mode = NKR_NETMAP_ON; 491 } 492 493 } 494 for_each_tx_kring_h(r, kring, na) { 495 if (nm_kring_pending_on(kring)) { 496 D("Emulated adapter: ring '%s' activated", kring->name); 497 kring->nr_mode = NKR_NETMAP_ON; 498 } 499 } 500 501 for_each_tx_kring(r, kring, na) { 502 /* Initialize tx_pool and tx_event. */ 503 for (i=0; i<na->num_tx_desc; i++) { 504 kring->tx_pool[i] = NULL; 505 } 506 507 kring->tx_event = NULL; 508 } 509 510 if (na->active_fds == 0) { 511 rtnl_lock(); 512 513 /* Prepare to intercept incoming traffic. */ 514 error = nm_os_catch_rx(gna, 1); 515 if (error) { 516 D("nm_os_catch_rx(1) failed (%d)", error); 517 goto register_handler; 518 } 519 520 /* Make netmap control the packet steering. */ 521 error = nm_os_catch_tx(gna, 1); 522 if (error) { 523 D("nm_os_catch_tx(1) failed (%d)", error); 524 goto catch_rx; 525 } 526 527 rtnl_unlock(); 528 529 na->na_flags |= NAF_NETMAP_ON; 530 531 #ifdef RATE_GENERIC 532 if (rate_ctx.refcount == 0) { 533 D("setup_timer()"); 534 memset(&rate_ctx, 0, sizeof(rate_ctx)); 535 setup_timer(&rate_ctx.timer, &rate_callback, (unsigned long)&rate_ctx); 536 if (mod_timer(&rate_ctx.timer, jiffies + msecs_to_jiffies(1500))) { 537 D("Error: mod_timer()"); 538 } 539 } 540 rate_ctx.refcount++; 541 #endif /* RATE */ 542 } 543 544 return 0; 545 546 /* Here (na->active_fds == 0) holds. */ 547 catch_rx: 548 nm_os_catch_rx(gna, 0); 549 register_handler: 550 rtnl_unlock(); 551 free_tx_pools: 552 for_each_tx_kring(r, kring, na) { 553 mtx_destroy(&kring->tx_event_lock); 554 if (kring->tx_pool == NULL) { 555 continue; 556 } 557 nm_os_free(kring->tx_pool); 558 kring->tx_pool = NULL; 559 } 560 for_each_rx_kring(r, kring, na) { 561 mbq_safe_fini(&kring->rx_queue); 562 } 563 nm_os_free(gna->mit); 564 out: 565 566 return error; 567 } 568 569 /* 570 * Callback invoked when the device driver frees an mbuf used 571 * by netmap to transmit a packet. This usually happens when 572 * the NIC notifies the driver that transmission is completed. 573 */ 574 static void 575 generic_mbuf_destructor(struct mbuf *m) 576 { 577 struct netmap_adapter *na = NA(GEN_TX_MBUF_IFP(m)); 578 struct netmap_kring *kring; 579 unsigned int r = MBUF_TXQ(m); 580 unsigned int r_orig = r; 581 582 if (unlikely(!nm_netmap_on(na) || r >= na->num_tx_rings)) { 583 D("Error: no netmap adapter on device %p", 584 GEN_TX_MBUF_IFP(m)); 585 return; 586 } 587 588 /* 589 * First, clear the event mbuf. 590 * In principle, the event 'm' should match the one stored 591 * on ring 'r'. However we check it explicitely to stay 592 * safe against lower layers (qdisc, driver, etc.) changing 593 * MBUF_TXQ(m) under our feet. If the match is not found 594 * on 'r', we try to see if it belongs to some other ring. 595 */ 596 for (;;) { 597 bool match = false; 598 599 kring = &na->tx_rings[r]; 600 mtx_lock_spin(&kring->tx_event_lock); 601 if (kring->tx_event == m) { 602 kring->tx_event = NULL; 603 match = true; 604 } 605 mtx_unlock_spin(&kring->tx_event_lock); 606 607 if (match) { 608 if (r != r_orig) { 609 RD(1, "event %p migrated: ring %u --> %u", 610 m, r_orig, r); 611 } 612 break; 613 } 614 615 if (++r == na->num_tx_rings) r = 0; 616 617 if (r == r_orig) { 618 RD(1, "Cannot match event %p", m); 619 return; 620 } 621 } 622 623 /* Second, wake up clients. They will reclaim the event through 624 * txsync. */ 625 netmap_generic_irq(na, r, NULL); 626 #ifdef __FreeBSD__ 627 void_mbuf_dtor(m, NULL, NULL); 628 #endif 629 } 630 631 /* Record completed transmissions and update hwtail. 632 * 633 * The oldest tx buffer not yet completed is at nr_hwtail + 1, 634 * nr_hwcur is the first unsent buffer. 635 */ 636 static u_int 637 generic_netmap_tx_clean(struct netmap_kring *kring, int txqdisc) 638 { 639 u_int const lim = kring->nkr_num_slots - 1; 640 u_int nm_i = nm_next(kring->nr_hwtail, lim); 641 u_int hwcur = kring->nr_hwcur; 642 u_int n = 0; 643 struct mbuf **tx_pool = kring->tx_pool; 644 645 ND("hwcur = %d, hwtail = %d", kring->nr_hwcur, kring->nr_hwtail); 646 647 while (nm_i != hwcur) { /* buffers not completed */ 648 struct mbuf *m = tx_pool[nm_i]; 649 650 if (txqdisc) { 651 if (m == NULL) { 652 /* Nothing to do, this is going 653 * to be replenished. */ 654 RD(3, "Is this happening?"); 655 656 } else if (MBUF_QUEUED(m)) { 657 break; /* Not dequeued yet. */ 658 659 } else if (MBUF_REFCNT(m) != 1) { 660 /* This mbuf has been dequeued but is still busy 661 * (refcount is 2). 662 * Leave it to the driver and replenish. */ 663 m_freem(m); 664 tx_pool[nm_i] = NULL; 665 } 666 667 } else { 668 if (unlikely(m == NULL)) { 669 int event_consumed; 670 671 /* This slot was used to place an event. */ 672 mtx_lock_spin(&kring->tx_event_lock); 673 event_consumed = (kring->tx_event == NULL); 674 mtx_unlock_spin(&kring->tx_event_lock); 675 if (!event_consumed) { 676 /* The event has not been consumed yet, 677 * still busy in the driver. */ 678 break; 679 } 680 /* The event has been consumed, we can go 681 * ahead. */ 682 683 } else if (MBUF_REFCNT(m) != 1) { 684 /* This mbuf is still busy: its refcnt is 2. */ 685 break; 686 } 687 } 688 689 n++; 690 nm_i = nm_next(nm_i, lim); 691 } 692 kring->nr_hwtail = nm_prev(nm_i, lim); 693 ND("tx completed [%d] -> hwtail %d", n, kring->nr_hwtail); 694 695 return n; 696 } 697 698 /* Compute a slot index in the middle between inf and sup. */ 699 static inline u_int 700 ring_middle(u_int inf, u_int sup, u_int lim) 701 { 702 u_int n = lim + 1; 703 u_int e; 704 705 if (sup >= inf) { 706 e = (sup + inf) / 2; 707 } else { /* wrap around */ 708 e = (sup + n + inf) / 2; 709 if (e >= n) { 710 e -= n; 711 } 712 } 713 714 if (unlikely(e >= n)) { 715 D("This cannot happen"); 716 e = 0; 717 } 718 719 return e; 720 } 721 722 static void 723 generic_set_tx_event(struct netmap_kring *kring, u_int hwcur) 724 { 725 u_int lim = kring->nkr_num_slots - 1; 726 struct mbuf *m; 727 u_int e; 728 u_int ntc = nm_next(kring->nr_hwtail, lim); /* next to clean */ 729 730 if (ntc == hwcur) { 731 return; /* all buffers are free */ 732 } 733 734 /* 735 * We have pending packets in the driver between hwtail+1 736 * and hwcur, and we have to chose one of these slot to 737 * generate a notification. 738 * There is a race but this is only called within txsync which 739 * does a double check. 740 */ 741 #if 0 742 /* Choose a slot in the middle, so that we don't risk ending 743 * up in a situation where the client continuously wake up, 744 * fills one or a few TX slots and go to sleep again. */ 745 e = ring_middle(ntc, hwcur, lim); 746 #else 747 /* Choose the first pending slot, to be safe against driver 748 * reordering mbuf transmissions. */ 749 e = ntc; 750 #endif 751 752 m = kring->tx_pool[e]; 753 if (m == NULL) { 754 /* An event is already in place. */ 755 return; 756 } 757 758 mtx_lock_spin(&kring->tx_event_lock); 759 if (kring->tx_event) { 760 /* An event is already in place. */ 761 mtx_unlock_spin(&kring->tx_event_lock); 762 return; 763 } 764 765 SET_MBUF_DESTRUCTOR(m, generic_mbuf_destructor); 766 kring->tx_event = m; 767 mtx_unlock_spin(&kring->tx_event_lock); 768 769 kring->tx_pool[e] = NULL; 770 771 ND(5, "Request Event at %d mbuf %p refcnt %d", e, m, m ? MBUF_REFCNT(m) : -2 ); 772 773 /* Decrement the refcount. This will free it if we lose the race 774 * with the driver. */ 775 m_freem(m); 776 smp_mb(); 777 } 778 779 780 /* 781 * generic_netmap_txsync() transforms netmap buffers into mbufs 782 * and passes them to the standard device driver 783 * (ndo_start_xmit() or ifp->if_transmit() ). 784 * On linux this is not done directly, but using dev_queue_xmit(), 785 * since it implements the TX flow control (and takes some locks). 786 */ 787 static int 788 generic_netmap_txsync(struct netmap_kring *kring, int flags) 789 { 790 struct netmap_adapter *na = kring->na; 791 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na; 792 struct ifnet *ifp = na->ifp; 793 struct netmap_ring *ring = kring->ring; 794 u_int nm_i; /* index into the netmap ring */ // j 795 u_int const lim = kring->nkr_num_slots - 1; 796 u_int const head = kring->rhead; 797 u_int ring_nr = kring->ring_id; 798 799 IFRATE(rate_ctx.new.txsync++); 800 801 rmb(); 802 803 /* 804 * First part: process new packets to send. 805 */ 806 nm_i = kring->nr_hwcur; 807 if (nm_i != head) { /* we have new packets to send */ 808 struct nm_os_gen_arg a; 809 u_int event = -1; 810 811 if (gna->txqdisc && nm_kr_txempty(kring)) { 812 /* In txqdisc mode, we ask for a delayed notification, 813 * but only when cur == hwtail, which means that the 814 * client is going to block. */ 815 event = ring_middle(nm_i, head, lim); 816 ND(3, "Place txqdisc event (hwcur=%u,event=%u," 817 "head=%u,hwtail=%u)", nm_i, event, head, 818 kring->nr_hwtail); 819 } 820 821 a.ifp = ifp; 822 a.ring_nr = ring_nr; 823 a.head = a.tail = NULL; 824 825 while (nm_i != head) { 826 struct netmap_slot *slot = &ring->slot[nm_i]; 827 u_int len = slot->len; 828 void *addr = NMB(na, slot); 829 /* device-specific */ 830 struct mbuf *m; 831 int tx_ret; 832 833 NM_CHECK_ADDR_LEN(na, addr, len); 834 835 /* Tale a mbuf from the tx pool (replenishing the pool 836 * entry if necessary) and copy in the user packet. */ 837 m = kring->tx_pool[nm_i]; 838 if (unlikely(m == NULL)) { 839 kring->tx_pool[nm_i] = m = 840 nm_os_get_mbuf(ifp, NETMAP_BUF_SIZE(na)); 841 if (m == NULL) { 842 RD(2, "Failed to replenish mbuf"); 843 /* Here we could schedule a timer which 844 * retries to replenish after a while, 845 * and notifies the client when it 846 * manages to replenish some slots. In 847 * any case we break early to avoid 848 * crashes. */ 849 break; 850 } 851 IFRATE(rate_ctx.new.txrepl++); 852 } 853 854 a.m = m; 855 a.addr = addr; 856 a.len = len; 857 a.qevent = (nm_i == event); 858 /* When not in txqdisc mode, we should ask 859 * notifications when NS_REPORT is set, or roughly 860 * every half ring. To optimize this, we set a 861 * notification event when the client runs out of 862 * TX ring space, or when transmission fails. In 863 * the latter case we also break early. 864 */ 865 tx_ret = nm_os_generic_xmit_frame(&a); 866 if (unlikely(tx_ret)) { 867 if (!gna->txqdisc) { 868 /* 869 * No room for this mbuf in the device driver. 870 * Request a notification FOR A PREVIOUS MBUF, 871 * then call generic_netmap_tx_clean(kring) to do the 872 * double check and see if we can free more buffers. 873 * If there is space continue, else break; 874 * NOTE: the double check is necessary if the problem 875 * occurs in the txsync call after selrecord(). 876 * Also, we need some way to tell the caller that not 877 * all buffers were queued onto the device (this was 878 * not a problem with native netmap driver where space 879 * is preallocated). The bridge has a similar problem 880 * and we solve it there by dropping the excess packets. 881 */ 882 generic_set_tx_event(kring, nm_i); 883 if (generic_netmap_tx_clean(kring, gna->txqdisc)) { 884 /* space now available */ 885 continue; 886 } else { 887 break; 888 } 889 } 890 891 /* In txqdisc mode, the netmap-aware qdisc 892 * queue has the same length as the number of 893 * netmap slots (N). Since tail is advanced 894 * only when packets are dequeued, qdisc 895 * queue overrun cannot happen, so 896 * nm_os_generic_xmit_frame() did not fail 897 * because of that. 898 * However, packets can be dropped because 899 * carrier is off, or because our qdisc is 900 * being deactivated, or possibly for other 901 * reasons. In these cases, we just let the 902 * packet to be dropped. */ 903 IFRATE(rate_ctx.new.txdrop++); 904 } 905 906 slot->flags &= ~(NS_REPORT | NS_BUF_CHANGED); 907 nm_i = nm_next(nm_i, lim); 908 IFRATE(rate_ctx.new.txpkt++); 909 } 910 if (a.head != NULL) { 911 a.addr = NULL; 912 nm_os_generic_xmit_frame(&a); 913 } 914 /* Update hwcur to the next slot to transmit. Here nm_i 915 * is not necessarily head, we could break early. */ 916 kring->nr_hwcur = nm_i; 917 } 918 919 /* 920 * Second, reclaim completed buffers 921 */ 922 if (!gna->txqdisc && (flags & NAF_FORCE_RECLAIM || nm_kr_txempty(kring))) { 923 /* No more available slots? Set a notification event 924 * on a netmap slot that will be cleaned in the future. 925 * No doublecheck is performed, since txsync() will be 926 * called twice by netmap_poll(). 927 */ 928 generic_set_tx_event(kring, nm_i); 929 } 930 931 generic_netmap_tx_clean(kring, gna->txqdisc); 932 933 return 0; 934 } 935 936 937 /* 938 * This handler is registered (through nm_os_catch_rx()) 939 * within the attached network interface 940 * in the RX subsystem, so that every mbuf passed up by 941 * the driver can be stolen to the network stack. 942 * Stolen packets are put in a queue where the 943 * generic_netmap_rxsync() callback can extract them. 944 * Returns 1 if the packet was stolen, 0 otherwise. 945 */ 946 int 947 generic_rx_handler(struct ifnet *ifp, struct mbuf *m) 948 { 949 struct netmap_adapter *na = NA(ifp); 950 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na; 951 struct netmap_kring *kring; 952 u_int work_done; 953 u_int r = MBUF_RXQ(m); /* receive ring number */ 954 955 if (r >= na->num_rx_rings) { 956 r = r % na->num_rx_rings; 957 } 958 959 kring = &na->rx_rings[r]; 960 961 if (kring->nr_mode == NKR_NETMAP_OFF) { 962 /* We must not intercept this mbuf. */ 963 return 0; 964 } 965 966 /* limit the size of the queue */ 967 if (unlikely(!gna->rxsg && MBUF_LEN(m) > NETMAP_BUF_SIZE(na))) { 968 /* This may happen when GRO/LRO features are enabled for 969 * the NIC driver when the generic adapter does not 970 * support RX scatter-gather. */ 971 RD(2, "Warning: driver pushed up big packet " 972 "(size=%d)", (int)MBUF_LEN(m)); 973 m_freem(m); 974 } else if (unlikely(mbq_len(&kring->rx_queue) > 1024)) { 975 m_freem(m); 976 } else { 977 mbq_safe_enqueue(&kring->rx_queue, m); 978 } 979 980 if (netmap_generic_mit < 32768) { 981 /* no rx mitigation, pass notification up */ 982 netmap_generic_irq(na, r, &work_done); 983 } else { 984 /* same as send combining, filter notification if there is a 985 * pending timer, otherwise pass it up and start a timer. 986 */ 987 if (likely(nm_os_mitigation_active(&gna->mit[r]))) { 988 /* Record that there is some pending work. */ 989 gna->mit[r].mit_pending = 1; 990 } else { 991 netmap_generic_irq(na, r, &work_done); 992 nm_os_mitigation_start(&gna->mit[r]); 993 } 994 } 995 996 /* We have intercepted the mbuf. */ 997 return 1; 998 } 999 1000 /* 1001 * generic_netmap_rxsync() extracts mbufs from the queue filled by 1002 * generic_netmap_rx_handler() and puts their content in the netmap 1003 * receive ring. 1004 * Access must be protected because the rx handler is asynchronous, 1005 */ 1006 static int 1007 generic_netmap_rxsync(struct netmap_kring *kring, int flags) 1008 { 1009 struct netmap_ring *ring = kring->ring; 1010 struct netmap_adapter *na = kring->na; 1011 u_int nm_i; /* index into the netmap ring */ //j, 1012 u_int n; 1013 u_int const lim = kring->nkr_num_slots - 1; 1014 u_int const head = kring->rhead; 1015 int force_update = (flags & NAF_FORCE_READ) || kring->nr_kflags & NKR_PENDINTR; 1016 1017 /* Adapter-specific variables. */ 1018 uint16_t slot_flags = kring->nkr_slot_flags; 1019 u_int nm_buf_len = NETMAP_BUF_SIZE(na); 1020 struct mbq tmpq; 1021 struct mbuf *m; 1022 int avail; /* in bytes */ 1023 int mlen; 1024 int copy; 1025 1026 if (head > lim) 1027 return netmap_ring_reinit(kring); 1028 1029 IFRATE(rate_ctx.new.rxsync++); 1030 1031 /* 1032 * First part: skip past packets that userspace has released. 1033 * This can possibly make room for the second part. 1034 */ 1035 nm_i = kring->nr_hwcur; 1036 if (nm_i != head) { 1037 /* Userspace has released some packets. */ 1038 for (n = 0; nm_i != head; n++) { 1039 struct netmap_slot *slot = &ring->slot[nm_i]; 1040 1041 slot->flags &= ~NS_BUF_CHANGED; 1042 nm_i = nm_next(nm_i, lim); 1043 } 1044 kring->nr_hwcur = head; 1045 } 1046 1047 /* 1048 * Second part: import newly received packets. 1049 */ 1050 if (!netmap_no_pendintr && !force_update) { 1051 return 0; 1052 } 1053 1054 nm_i = kring->nr_hwtail; /* First empty slot in the receive ring. */ 1055 1056 /* Compute the available space (in bytes) in this netmap ring. 1057 * The first slot that is not considered in is the one before 1058 * nr_hwcur. */ 1059 1060 avail = nm_prev(kring->nr_hwcur, lim) - nm_i; 1061 if (avail < 0) 1062 avail += lim + 1; 1063 avail *= nm_buf_len; 1064 1065 /* First pass: While holding the lock on the RX mbuf queue, 1066 * extract as many mbufs as they fit the available space, 1067 * and put them in a temporary queue. 1068 * To avoid performing a per-mbuf division (mlen / nm_buf_len) to 1069 * to update avail, we do the update in a while loop that we 1070 * also use to set the RX slots, but without performing the copy. */ 1071 mbq_init(&tmpq); 1072 mbq_lock(&kring->rx_queue); 1073 for (n = 0;; n++) { 1074 m = mbq_peek(&kring->rx_queue); 1075 if (!m) { 1076 /* No more packets from the driver. */ 1077 break; 1078 } 1079 1080 mlen = MBUF_LEN(m); 1081 if (mlen > avail) { 1082 /* No more space in the ring. */ 1083 break; 1084 } 1085 1086 mbq_dequeue(&kring->rx_queue); 1087 1088 while (mlen) { 1089 copy = nm_buf_len; 1090 if (mlen < copy) { 1091 copy = mlen; 1092 } 1093 mlen -= copy; 1094 avail -= nm_buf_len; 1095 1096 ring->slot[nm_i].len = copy; 1097 ring->slot[nm_i].flags = slot_flags | (mlen ? NS_MOREFRAG : 0); 1098 nm_i = nm_next(nm_i, lim); 1099 } 1100 1101 mbq_enqueue(&tmpq, m); 1102 } 1103 mbq_unlock(&kring->rx_queue); 1104 1105 /* Second pass: Drain the temporary queue, going over the used RX slots, 1106 * and perform the copy out of the RX queue lock. */ 1107 nm_i = kring->nr_hwtail; 1108 1109 for (;;) { 1110 void *nmaddr; 1111 int ofs = 0; 1112 int morefrag; 1113 1114 m = mbq_dequeue(&tmpq); 1115 if (!m) { 1116 break; 1117 } 1118 1119 do { 1120 nmaddr = NMB(na, &ring->slot[nm_i]); 1121 /* We only check the address here on generic rx rings. */ 1122 if (nmaddr == NETMAP_BUF_BASE(na)) { /* Bad buffer */ 1123 m_freem(m); 1124 mbq_purge(&tmpq); 1125 mbq_fini(&tmpq); 1126 return netmap_ring_reinit(kring); 1127 } 1128 1129 copy = ring->slot[nm_i].len; 1130 m_copydata(m, ofs, copy, nmaddr); 1131 ofs += copy; 1132 morefrag = ring->slot[nm_i].flags & NS_MOREFRAG; 1133 nm_i = nm_next(nm_i, lim); 1134 } while (morefrag); 1135 1136 m_freem(m); 1137 } 1138 1139 mbq_fini(&tmpq); 1140 1141 if (n) { 1142 kring->nr_hwtail = nm_i; 1143 IFRATE(rate_ctx.new.rxpkt += n); 1144 } 1145 kring->nr_kflags &= ~NKR_PENDINTR; 1146 1147 return 0; 1148 } 1149 1150 static void 1151 generic_netmap_dtor(struct netmap_adapter *na) 1152 { 1153 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter*)na; 1154 struct ifnet *ifp = netmap_generic_getifp(gna); 1155 struct netmap_adapter *prev_na = gna->prev; 1156 1157 if (prev_na != NULL) { 1158 netmap_adapter_put(prev_na); 1159 if (nm_iszombie(na)) { 1160 /* 1161 * The driver has been removed without releasing 1162 * the reference so we need to do it here. 1163 */ 1164 netmap_adapter_put(prev_na); 1165 } 1166 D("Native netmap adapter %p restored", prev_na); 1167 } 1168 NM_ATTACH_NA(ifp, prev_na); 1169 /* 1170 * netmap_detach_common(), that it's called after this function, 1171 * overrides WNA(ifp) if na->ifp is not NULL. 1172 */ 1173 na->ifp = NULL; 1174 D("Emulated netmap adapter for %s destroyed", na->name); 1175 } 1176 1177 int 1178 na_is_generic(struct netmap_adapter *na) 1179 { 1180 return na->nm_register == generic_netmap_register; 1181 } 1182 1183 /* 1184 * generic_netmap_attach() makes it possible to use netmap on 1185 * a device without native netmap support. 1186 * This is less performant than native support but potentially 1187 * faster than raw sockets or similar schemes. 1188 * 1189 * In this "emulated" mode, netmap rings do not necessarily 1190 * have the same size as those in the NIC. We use a default 1191 * value and possibly override it if the OS has ways to fetch the 1192 * actual configuration. 1193 */ 1194 int 1195 generic_netmap_attach(struct ifnet *ifp) 1196 { 1197 struct netmap_adapter *na; 1198 struct netmap_generic_adapter *gna; 1199 int retval; 1200 u_int num_tx_desc, num_rx_desc; 1201 1202 #ifdef __FreeBSD__ 1203 if (ifp->if_type == IFT_LOOP) { 1204 D("if_loop is not supported by %s", __func__); 1205 return EINVAL; 1206 } 1207 #endif 1208 1209 num_tx_desc = num_rx_desc = netmap_generic_ringsize; /* starting point */ 1210 1211 nm_os_generic_find_num_desc(ifp, &num_tx_desc, &num_rx_desc); /* ignore errors */ 1212 ND("Netmap ring size: TX = %d, RX = %d", num_tx_desc, num_rx_desc); 1213 if (num_tx_desc == 0 || num_rx_desc == 0) { 1214 D("Device has no hw slots (tx %u, rx %u)", num_tx_desc, num_rx_desc); 1215 return EINVAL; 1216 } 1217 1218 gna = nm_os_malloc(sizeof(*gna)); 1219 if (gna == NULL) { 1220 D("no memory on attach, give up"); 1221 return ENOMEM; 1222 } 1223 na = (struct netmap_adapter *)gna; 1224 strncpy(na->name, ifp->if_xname, sizeof(na->name)); 1225 na->ifp = ifp; 1226 na->num_tx_desc = num_tx_desc; 1227 na->num_rx_desc = num_rx_desc; 1228 na->nm_register = &generic_netmap_register; 1229 na->nm_txsync = &generic_netmap_txsync; 1230 na->nm_rxsync = &generic_netmap_rxsync; 1231 na->nm_dtor = &generic_netmap_dtor; 1232 /* when using generic, NAF_NETMAP_ON is set so we force 1233 * NAF_SKIP_INTR to use the regular interrupt handler 1234 */ 1235 na->na_flags = NAF_SKIP_INTR | NAF_HOST_RINGS; 1236 1237 ND("[GNA] num_tx_queues(%d), real_num_tx_queues(%d), len(%lu)", 1238 ifp->num_tx_queues, ifp->real_num_tx_queues, 1239 ifp->tx_queue_len); 1240 ND("[GNA] num_rx_queues(%d), real_num_rx_queues(%d)", 1241 ifp->num_rx_queues, ifp->real_num_rx_queues); 1242 1243 nm_os_generic_find_num_queues(ifp, &na->num_tx_rings, &na->num_rx_rings); 1244 1245 retval = netmap_attach_common(na); 1246 if (retval) { 1247 nm_os_free(gna); 1248 return retval; 1249 } 1250 1251 gna->prev = NA(ifp); /* save old na */ 1252 if (gna->prev != NULL) { 1253 netmap_adapter_get(gna->prev); 1254 } 1255 NM_ATTACH_NA(ifp, na); 1256 1257 nm_os_generic_set_features(gna); 1258 1259 D("Emulated adapter for %s created (prev was %p)", na->name, gna->prev); 1260 1261 return retval; 1262 } 1263