1 /* 2 * Copyright (C) 2011 Matteo Landi, Luigi Rizzo. All rights reserved. 3 * 4 * Redistribution and use in source and binary forms, with or without 5 * modification, are permitted provided that the following conditions 6 * are met: 7 * 1. Redistributions of source code must retain the above copyright 8 * notice, this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright 10 * notice, this list of conditions and the following disclaimer in the 11 * documentation and/or other materials provided with the distribution. 12 * 13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 16 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 23 * SUCH DAMAGE. 24 */ 25 26 /* 27 * $FreeBSD$ 28 * $Id: netmap.c 9795 2011-12-02 11:39:08Z luigi $ 29 * 30 * This module supports memory mapped access to network devices, 31 * see netmap(4). 32 * 33 * The module uses a large, memory pool allocated by the kernel 34 * and accessible as mmapped memory by multiple userspace threads/processes. 35 * The memory pool contains packet buffers and "netmap rings", 36 * i.e. user-accessible copies of the interface's queues. 37 * 38 * Access to the network card works like this: 39 * 1. a process/thread issues one or more open() on /dev/netmap, to create 40 * select()able file descriptor on which events are reported. 41 * 2. on each descriptor, the process issues an ioctl() to identify 42 * the interface that should report events to the file descriptor. 43 * 3. on each descriptor, the process issues an mmap() request to 44 * map the shared memory region within the process' address space. 45 * The list of interesting queues is indicated by a location in 46 * the shared memory region. 47 * 4. using the functions in the netmap(4) userspace API, a process 48 * can look up the occupation state of a queue, access memory buffers, 49 * and retrieve received packets or enqueue packets to transmit. 50 * 5. using some ioctl()s the process can synchronize the userspace view 51 * of the queue with the actual status in the kernel. This includes both 52 * receiving the notification of new packets, and transmitting new 53 * packets on the output interface. 54 * 6. select() or poll() can be used to wait for events on individual 55 * transmit or receive queues (or all queues for a given interface). 56 */ 57 58 #include <sys/cdefs.h> /* prerequisite */ 59 __FBSDID("$FreeBSD$"); 60 61 #include <sys/types.h> 62 #include <sys/module.h> 63 #include <sys/errno.h> 64 #include <sys/param.h> /* defines used in kernel.h */ 65 #include <sys/jail.h> 66 #include <sys/kernel.h> /* types used in module initialization */ 67 #include <sys/conf.h> /* cdevsw struct */ 68 #include <sys/uio.h> /* uio struct */ 69 #include <sys/sockio.h> 70 #include <sys/socketvar.h> /* struct socket */ 71 #include <sys/malloc.h> 72 #include <sys/mman.h> /* PROT_EXEC */ 73 #include <sys/poll.h> 74 #include <sys/proc.h> 75 #include <vm/vm.h> /* vtophys */ 76 #include <vm/pmap.h> /* vtophys */ 77 #include <sys/socket.h> /* sockaddrs */ 78 #include <machine/bus.h> 79 #include <sys/selinfo.h> 80 #include <sys/sysctl.h> 81 #include <net/if.h> 82 #include <net/bpf.h> /* BIOCIMMEDIATE */ 83 #include <net/vnet.h> 84 #include <net/netmap.h> 85 #include <dev/netmap/netmap_kern.h> 86 #include <machine/bus.h> /* bus_dmamap_* */ 87 88 MALLOC_DEFINE(M_NETMAP, "netmap", "Network memory map"); 89 90 /* 91 * lock and unlock for the netmap memory allocator 92 */ 93 #define NMA_LOCK() mtx_lock(&netmap_mem_d->nm_mtx); 94 #define NMA_UNLOCK() mtx_unlock(&netmap_mem_d->nm_mtx); 95 96 /* 97 * Default amount of memory pre-allocated by the module. 98 * We start with a large size and then shrink our demand 99 * according to what is avalable when the module is loaded. 100 * At the moment the block is contiguous, but we can easily 101 * restrict our demand to smaller units (16..64k) 102 */ 103 #define NETMAP_MEMORY_SIZE (64 * 1024 * PAGE_SIZE) 104 static void * netmap_malloc(size_t size, const char *msg); 105 static void netmap_free(void *addr, const char *msg); 106 107 /* 108 * Allocator for a pool of packet buffers. For each buffer we have 109 * one entry in the bitmap to signal the state. Allocation scans 110 * the bitmap, but since this is done only on attach, we are not 111 * too worried about performance 112 * XXX if we need to allocate small blocks, a translation 113 * table is used both for kernel virtual address and physical 114 * addresses. 115 */ 116 struct netmap_buf_pool { 117 u_int total_buffers; /* total buffers. */ 118 u_int free; 119 u_int bufsize; 120 char *base; /* buffer base address */ 121 uint32_t *bitmap; /* one bit per buffer, 1 means free */ 122 }; 123 struct netmap_buf_pool nm_buf_pool; 124 /* XXX move these two vars back into netmap_buf_pool */ 125 u_int netmap_total_buffers; 126 char *netmap_buffer_base; 127 128 /* user-controlled variables */ 129 int netmap_verbose; 130 131 static int no_timestamp; /* don't timestamp on rxsync */ 132 133 SYSCTL_NODE(_dev, OID_AUTO, netmap, CTLFLAG_RW, 0, "Netmap args"); 134 SYSCTL_INT(_dev_netmap, OID_AUTO, verbose, 135 CTLFLAG_RW, &netmap_verbose, 0, "Verbose mode"); 136 SYSCTL_INT(_dev_netmap, OID_AUTO, no_timestamp, 137 CTLFLAG_RW, &no_timestamp, 0, "no_timestamp"); 138 SYSCTL_INT(_dev_netmap, OID_AUTO, total_buffers, 139 CTLFLAG_RD, &nm_buf_pool.total_buffers, 0, "total_buffers"); 140 SYSCTL_INT(_dev_netmap, OID_AUTO, free_buffers, 141 CTLFLAG_RD, &nm_buf_pool.free, 0, "free_buffers"); 142 143 /* 144 * Allocate n buffers from the ring, and fill the slot. 145 * Buffer 0 is the 'junk' buffer. 146 */ 147 static void 148 netmap_new_bufs(struct netmap_buf_pool *p, struct netmap_slot *slot, u_int n) 149 { 150 uint32_t bi = 0; /* index in the bitmap */ 151 uint32_t mask, j, i = 0; /* slot counter */ 152 153 if (n > p->free) { 154 D("only %d out of %d buffers available", i, n); 155 return; 156 } 157 /* termination is guaranteed by p->free */ 158 while (i < n && p->free > 0) { 159 uint32_t cur = p->bitmap[bi]; 160 if (cur == 0) { /* bitmask is fully used */ 161 bi++; 162 continue; 163 } 164 /* locate a slot */ 165 for (j = 0, mask = 1; (cur & mask) == 0; j++, mask <<= 1) ; 166 p->bitmap[bi] &= ~mask; /* slot in use */ 167 p->free--; 168 slot[i].buf_idx = bi*32+j; 169 slot[i].len = p->bufsize; 170 slot[i].flags = NS_BUF_CHANGED; 171 i++; 172 } 173 ND("allocated %d buffers, %d available", n, p->free); 174 } 175 176 177 static void 178 netmap_free_buf(struct netmap_buf_pool *p, uint32_t i) 179 { 180 uint32_t pos, mask; 181 if (i >= p->total_buffers) { 182 D("invalid free index %d", i); 183 return; 184 } 185 pos = i / 32; 186 mask = 1 << (i % 32); 187 if (p->bitmap[pos] & mask) { 188 D("slot %d already free", i); 189 return; 190 } 191 p->bitmap[pos] |= mask; 192 p->free++; 193 } 194 195 196 /* Descriptor of the memory objects handled by our memory allocator. */ 197 struct netmap_mem_obj { 198 TAILQ_ENTRY(netmap_mem_obj) nmo_next; /* next object in the 199 chain. */ 200 int nmo_used; /* flag set on used memory objects. */ 201 size_t nmo_size; /* size of the memory area reserved for the 202 object. */ 203 void *nmo_data; /* pointer to the memory area. */ 204 }; 205 206 /* Wrap our memory objects to make them ``chainable``. */ 207 TAILQ_HEAD(netmap_mem_obj_h, netmap_mem_obj); 208 209 210 /* Descriptor of our custom memory allocator. */ 211 struct netmap_mem_d { 212 struct mtx nm_mtx; /* lock used to handle the chain of memory 213 objects. */ 214 struct netmap_mem_obj_h nm_molist; /* list of memory objects */ 215 size_t nm_size; /* total amount of memory used for rings etc. */ 216 size_t nm_totalsize; /* total amount of allocated memory 217 (the difference is used for buffers) */ 218 size_t nm_buf_start; /* offset of packet buffers. 219 This is page-aligned. */ 220 size_t nm_buf_len; /* total memory for buffers */ 221 void *nm_buffer; /* pointer to the whole pre-allocated memory 222 area. */ 223 }; 224 225 226 /* Structure associated to each thread which registered an interface. */ 227 struct netmap_priv_d { 228 struct netmap_if *np_nifp; /* netmap interface descriptor. */ 229 230 struct ifnet *np_ifp; /* device for which we hold a reference */ 231 int np_ringid; /* from the ioctl */ 232 u_int np_qfirst, np_qlast; /* range of rings to scan */ 233 uint16_t np_txpoll; 234 }; 235 236 237 static struct cdev *netmap_dev; /* /dev/netmap character device. */ 238 static struct netmap_mem_d *netmap_mem_d; /* Our memory allocator. */ 239 240 241 static d_mmap_t netmap_mmap; 242 static d_ioctl_t netmap_ioctl; 243 static d_poll_t netmap_poll; 244 245 #ifdef NETMAP_KEVENT 246 static d_kqfilter_t netmap_kqfilter; 247 #endif 248 249 static struct cdevsw netmap_cdevsw = { 250 .d_version = D_VERSION, 251 .d_name = "netmap", 252 .d_mmap = netmap_mmap, 253 .d_ioctl = netmap_ioctl, 254 .d_poll = netmap_poll, 255 #ifdef NETMAP_KEVENT 256 .d_kqfilter = netmap_kqfilter, 257 #endif 258 }; 259 260 #ifdef NETMAP_KEVENT 261 static int netmap_kqread(struct knote *, long); 262 static int netmap_kqwrite(struct knote *, long); 263 static void netmap_kqdetach(struct knote *); 264 265 static struct filterops netmap_read_filterops = { 266 .f_isfd = 1, 267 .f_attach = NULL, 268 .f_detach = netmap_kqdetach, 269 .f_event = netmap_kqread, 270 }; 271 272 static struct filterops netmap_write_filterops = { 273 .f_isfd = 1, 274 .f_attach = NULL, 275 .f_detach = netmap_kqdetach, 276 .f_event = netmap_kqwrite, 277 }; 278 279 /* 280 * support for the kevent() system call. 281 * 282 * This is the kevent filter, and is executed each time a new event 283 * is triggered on the device. This function execute some operation 284 * depending on the received filter. 285 * 286 * The implementation should test the filters and should implement 287 * filter operations we are interested on (a full list in /sys/event.h). 288 * 289 * On a match we should: 290 * - set kn->kn_fop 291 * - set kn->kn_hook 292 * - call knlist_add() to deliver the event to the application. 293 * 294 * Return 0 if the event should be delivered to the application. 295 */ 296 static int 297 netmap_kqfilter(struct cdev *dev, struct knote *kn) 298 { 299 /* declare variables needed to read/write */ 300 301 switch(kn->kn_filter) { 302 case EVFILT_READ: 303 if (netmap_verbose) 304 D("%s kqfilter: EVFILT_READ" ifp->if_xname); 305 306 /* read operations */ 307 kn->kn_fop = &netmap_read_filterops; 308 break; 309 310 case EVFILT_WRITE: 311 if (netmap_verbose) 312 D("%s kqfilter: EVFILT_WRITE" ifp->if_xname); 313 314 /* write operations */ 315 kn->kn_fop = &netmap_write_filterops; 316 break; 317 318 default: 319 if (netmap_verbose) 320 D("%s kqfilter: invalid filter" ifp->if_xname); 321 return(EINVAL); 322 } 323 324 kn->kn_hook = 0;// 325 knlist_add(&netmap_sc->tun_rsel.si_note, kn, 0); 326 327 return (0); 328 } 329 #endif /* NETMAP_KEVENT */ 330 331 /* 332 * File descriptor's private data destructor. 333 * 334 * Call nm_register(ifp,0) to stop netmap mode on the interface and 335 * revert to normal operation. We expect that np_ifp has not gone. 336 */ 337 static void 338 netmap_dtor(void *data) 339 { 340 struct netmap_priv_d *priv = data; 341 struct ifnet *ifp = priv->np_ifp; 342 struct netmap_adapter *na = NA(ifp); 343 struct netmap_if *nifp = priv->np_nifp; 344 345 if (0) 346 printf("%s starting for %p ifp %p\n", __FUNCTION__, priv, 347 priv ? priv->np_ifp : NULL); 348 349 na->nm_lock(ifp->if_softc, NETMAP_CORE_LOCK, 0); 350 351 na->refcount--; 352 if (na->refcount <= 0) { /* last instance */ 353 u_int i; 354 355 D("deleting last netmap instance for %s", ifp->if_xname); 356 /* 357 * there is a race here with *_netmap_task() and 358 * netmap_poll(), which don't run under NETMAP_CORE_LOCK. 359 * na->refcount == 0 && na->ifp->if_capenable & IFCAP_NETMAP 360 * (aka NETMAP_DELETING(na)) are a unique marker that the 361 * device is dying. 362 * Before destroying stuff we sleep a bit, and then complete 363 * the job. NIOCREG should realize the condition and 364 * loop until they can continue; the other routines 365 * should check the condition at entry and quit if 366 * they cannot run. 367 */ 368 na->nm_lock(ifp->if_softc, NETMAP_CORE_UNLOCK, 0); 369 tsleep(na, 0, "NIOCUNREG", 4); 370 na->nm_lock(ifp->if_softc, NETMAP_CORE_LOCK, 0); 371 na->nm_register(ifp, 0); /* off, clear IFCAP_NETMAP */ 372 /* Wake up any sleeping threads. netmap_poll will 373 * then return POLLERR 374 */ 375 for (i = 0; i < na->num_queues + 2; i++) { 376 selwakeuppri(&na->tx_rings[i].si, PI_NET); 377 selwakeuppri(&na->rx_rings[i].si, PI_NET); 378 } 379 /* release all buffers */ 380 NMA_LOCK(); 381 for (i = 0; i < na->num_queues + 1; i++) { 382 int j, lim; 383 struct netmap_ring *ring; 384 385 ND("tx queue %d", i); 386 ring = na->tx_rings[i].ring; 387 lim = na->tx_rings[i].nkr_num_slots; 388 for (j = 0; j < lim; j++) 389 netmap_free_buf(&nm_buf_pool, 390 ring->slot[j].buf_idx); 391 392 ND("rx queue %d", i); 393 ring = na->rx_rings[i].ring; 394 lim = na->rx_rings[i].nkr_num_slots; 395 for (j = 0; j < lim; j++) 396 netmap_free_buf(&nm_buf_pool, 397 ring->slot[j].buf_idx); 398 } 399 NMA_UNLOCK(); 400 netmap_free(na->tx_rings[0].ring, "shadow rings"); 401 wakeup(na); 402 } 403 netmap_free(nifp, "nifp"); 404 405 na->nm_lock(ifp->if_softc, NETMAP_CORE_UNLOCK, 0); 406 407 if_rele(ifp); 408 409 bzero(priv, sizeof(*priv)); /* XXX for safety */ 410 free(priv, M_DEVBUF); 411 } 412 413 414 415 /* 416 * Create and return a new ``netmap_if`` object, and possibly also 417 * rings and packet buffors. 418 * 419 * Return NULL on failure. 420 */ 421 static void * 422 netmap_if_new(const char *ifname, struct netmap_adapter *na) 423 { 424 struct netmap_if *nifp; 425 struct netmap_ring *ring; 426 char *buff; 427 u_int i, len, ofs; 428 u_int n = na->num_queues + 1; /* shorthand, include stack queue */ 429 430 /* 431 * the descriptor is followed inline by an array of offsets 432 * to the tx and rx rings in the shared memory region. 433 */ 434 len = sizeof(struct netmap_if) + 2 * n * sizeof(ssize_t); 435 nifp = netmap_malloc(len, "nifp"); 436 if (nifp == NULL) 437 return (NULL); 438 439 /* initialize base fields */ 440 *(int *)(uintptr_t)&nifp->ni_num_queues = na->num_queues; 441 strncpy(nifp->ni_name, ifname, IFNAMSIZ); 442 443 (na->refcount)++; /* XXX atomic ? we are under lock */ 444 if (na->refcount > 1) 445 goto final; 446 447 /* 448 * If this is the first instance, allocate the shadow rings and 449 * buffers for this card (one for each hw queue, one for the host). 450 * The rings are contiguous, but have variable size. 451 * The entire block is reachable at 452 * na->tx_rings[0].ring 453 */ 454 455 len = n * (2 * sizeof(struct netmap_ring) + 456 (na->num_tx_desc + na->num_rx_desc) * 457 sizeof(struct netmap_slot) ); 458 buff = netmap_malloc(len, "shadow rings"); 459 if (buff == NULL) { 460 D("failed to allocate %d bytes for %s shadow ring", 461 len, ifname); 462 error: 463 (na->refcount)--; 464 netmap_free(nifp, "nifp, rings failed"); 465 return (NULL); 466 } 467 /* do we have the bufers ? we are in need of num_tx_desc buffers for 468 * each tx ring and num_tx_desc buffers for each rx ring. */ 469 len = n * (na->num_tx_desc + na->num_rx_desc); 470 NMA_LOCK(); 471 if (nm_buf_pool.free < len) { 472 NMA_UNLOCK(); 473 netmap_free(buff, "not enough bufs"); 474 goto error; 475 } 476 /* 477 * in the kring, store the pointers to the shared rings 478 * and initialize the rings. We are under NMA_LOCK(). 479 */ 480 ofs = 0; 481 for (i = 0; i < n; i++) { 482 struct netmap_kring *kring; 483 int numdesc; 484 485 /* Transmit rings */ 486 kring = &na->tx_rings[i]; 487 numdesc = na->num_tx_desc; 488 bzero(kring, sizeof(*kring)); 489 kring->na = na; 490 491 ring = kring->ring = (struct netmap_ring *)(buff + ofs); 492 *(ssize_t *)(uintptr_t)&ring->buf_ofs = 493 nm_buf_pool.base - (char *)ring; 494 ND("txring[%d] at %p ofs %d", i, ring, ring->buf_ofs); 495 *(int *)(int *)(uintptr_t)&ring->num_slots = 496 kring->nkr_num_slots = numdesc; 497 498 /* 499 * IMPORTANT: 500 * Always keep one slot empty, so we can detect new 501 * transmissions comparing cur and nr_hwcur (they are 502 * the same only if there are no new transmissions). 503 */ 504 ring->avail = kring->nr_hwavail = numdesc - 1; 505 ring->cur = kring->nr_hwcur = 0; 506 netmap_new_bufs(&nm_buf_pool, ring->slot, numdesc); 507 508 ofs += sizeof(struct netmap_ring) + 509 numdesc * sizeof(struct netmap_slot); 510 511 /* Receive rings */ 512 kring = &na->rx_rings[i]; 513 numdesc = na->num_rx_desc; 514 bzero(kring, sizeof(*kring)); 515 kring->na = na; 516 517 ring = kring->ring = (struct netmap_ring *)(buff + ofs); 518 *(ssize_t *)(uintptr_t)&ring->buf_ofs = 519 nm_buf_pool.base - (char *)ring; 520 ND("rxring[%d] at %p offset %d", i, ring, ring->buf_ofs); 521 *(int *)(int *)(uintptr_t)&ring->num_slots = 522 kring->nkr_num_slots = numdesc; 523 ring->cur = kring->nr_hwcur = 0; 524 ring->avail = kring->nr_hwavail = 0; /* empty */ 525 netmap_new_bufs(&nm_buf_pool, ring->slot, numdesc); 526 ofs += sizeof(struct netmap_ring) + 527 numdesc * sizeof(struct netmap_slot); 528 } 529 NMA_UNLOCK(); 530 for (i = 0; i < n+1; i++) { 531 // XXX initialize the selrecord structs. 532 } 533 final: 534 /* 535 * fill the slots for the rx and tx queues. They contain the offset 536 * between the ring and nifp, so the information is usable in 537 * userspace to reach the ring from the nifp. 538 */ 539 for (i = 0; i < n; i++) { 540 char *base = (char *)nifp; 541 *(ssize_t *)(uintptr_t)&nifp->ring_ofs[i] = 542 (char *)na->tx_rings[i].ring - base; 543 *(ssize_t *)(uintptr_t)&nifp->ring_ofs[i+n] = 544 (char *)na->rx_rings[i].ring - base; 545 } 546 return (nifp); 547 } 548 549 550 /* 551 * mmap(2) support for the "netmap" device. 552 * 553 * Expose all the memory previously allocated by our custom memory 554 * allocator: this way the user has only to issue a single mmap(2), and 555 * can work on all the data structures flawlessly. 556 * 557 * Return 0 on success, -1 otherwise. 558 */ 559 static int 560 #if __FreeBSD_version < 900000 561 netmap_mmap(__unused struct cdev *dev, vm_offset_t offset, vm_paddr_t *paddr, 562 int nprot) 563 #else 564 netmap_mmap(__unused struct cdev *dev, vm_ooffset_t offset, vm_paddr_t *paddr, 565 int nprot, __unused vm_memattr_t *memattr) 566 #endif 567 { 568 if (nprot & PROT_EXEC) 569 return (-1); // XXX -1 or EINVAL ? 570 ND("request for offset 0x%x", (uint32_t)offset); 571 *paddr = vtophys(netmap_mem_d->nm_buffer) + offset; 572 573 return (0); 574 } 575 576 577 /* 578 * handler for synchronization of the queues from/to the host 579 */ 580 static void 581 netmap_sync_to_host(struct netmap_adapter *na) 582 { 583 struct netmap_kring *kring = &na->tx_rings[na->num_queues]; 584 struct netmap_ring *ring = kring->ring; 585 struct mbuf *head = NULL, *tail = NULL, *m; 586 u_int n, lim = kring->nkr_num_slots - 1; 587 588 na->nm_lock(na->ifp->if_softc, NETMAP_CORE_LOCK, 0); 589 590 /* Take packets from hwcur to cur and pass them up. 591 * In case of no buffers we give up. At the end of the loop, 592 * the queue is drained in all cases. 593 */ 594 for (n = kring->nr_hwcur; n != ring->cur;) { 595 struct netmap_slot *slot = &ring->slot[n]; 596 597 n = (n == lim) ? 0 : n + 1; 598 if (slot->len < 14 || slot->len > NETMAP_BUF_SIZE) { 599 D("bad pkt at %d len %d", n, slot->len); 600 continue; 601 } 602 m = m_devget(NMB(slot), slot->len, 0, na->ifp, NULL); 603 604 if (m == NULL) 605 break; 606 if (tail) 607 tail->m_nextpkt = m; 608 else 609 head = m; 610 tail = m; 611 m->m_nextpkt = NULL; 612 } 613 kring->nr_hwcur = ring->cur; 614 kring->nr_hwavail = ring->avail = lim; 615 na->nm_lock(na->ifp->if_softc, NETMAP_CORE_UNLOCK, 0); 616 617 /* send packets up, outside the lock */ 618 while ((m = head) != NULL) { 619 head = head->m_nextpkt; 620 m->m_nextpkt = NULL; 621 m->m_pkthdr.rcvif = na->ifp; 622 if (netmap_verbose & NM_VERB_HOST) 623 D("sending up pkt %p size %d", m, m->m_pkthdr.len); 624 (na->ifp->if_input)(na->ifp, m); 625 } 626 } 627 628 /* 629 * This routine also does the selrecord if called from the poll handler 630 * (we know because td != NULL). 631 */ 632 static void 633 netmap_sync_from_host(struct netmap_adapter *na, struct thread *td) 634 { 635 struct netmap_kring *kring = &na->rx_rings[na->num_queues]; 636 struct netmap_ring *ring = kring->ring; 637 int delta; 638 639 na->nm_lock(na->ifp->if_softc, NETMAP_CORE_LOCK, 0); 640 641 /* skip past packets processed by userspace, 642 * and then sync cur/avail with hwcur/hwavail 643 */ 644 delta = ring->cur - kring->nr_hwcur; 645 if (delta < 0) 646 delta += kring->nkr_num_slots; 647 kring->nr_hwavail -= delta; 648 kring->nr_hwcur = ring->cur; 649 ring->avail = kring->nr_hwavail; 650 if (ring->avail == 0 && td) 651 selrecord(td, &kring->si); 652 if (ring->avail && (netmap_verbose & NM_VERB_HOST)) 653 D("%d pkts from stack", ring->avail); 654 na->nm_lock(na->ifp->if_softc, NETMAP_CORE_UNLOCK, 0); 655 } 656 657 658 /* 659 * get a refcounted reference to an interface. 660 * Return ENXIO if the interface does not exist, EINVAL if netmap 661 * is not supported by the interface. 662 * If successful, hold a reference. 663 */ 664 static int 665 get_ifp(const char *name, struct ifnet **ifp) 666 { 667 *ifp = ifunit_ref(name); 668 if (*ifp == NULL) 669 return (ENXIO); 670 /* can do this if the capability exists and if_pspare[0] 671 * points to the netmap descriptor. 672 */ 673 if ((*ifp)->if_capabilities & IFCAP_NETMAP && NA(*ifp)) 674 return 0; /* valid pointer, we hold the refcount */ 675 if_rele(*ifp); 676 return EINVAL; // not NETMAP capable 677 } 678 679 680 /* 681 * Error routine called when txsync/rxsync detects an error. 682 * Can't do much more than resetting cur = hwcur, avail = hwavail. 683 * Return 1 on reinit. 684 * 685 * This routine is only called by the upper half of the kernel. 686 * It only reads hwcur (which is changed only by the upper half, too) 687 * and hwavail (which may be changed by the lower half, but only on 688 * a tx ring and only to increase it, so any error will be recovered 689 * on the next call). For the above, we don't strictly need to call 690 * it under lock. 691 */ 692 int 693 netmap_ring_reinit(struct netmap_kring *kring) 694 { 695 struct netmap_ring *ring = kring->ring; 696 u_int i, lim = kring->nkr_num_slots - 1; 697 int errors = 0; 698 699 D("called for %s", kring->na->ifp->if_xname); 700 if (ring->cur > lim) 701 errors++; 702 for (i = 0; i <= lim; i++) { 703 u_int idx = ring->slot[i].buf_idx; 704 u_int len = ring->slot[i].len; 705 if (idx < 2 || idx >= netmap_total_buffers) { 706 if (!errors++) 707 D("bad buffer at slot %d idx %d len %d ", i, idx, len); 708 ring->slot[i].buf_idx = 0; 709 ring->slot[i].len = 0; 710 } else if (len > NETMAP_BUF_SIZE) { 711 ring->slot[i].len = 0; 712 if (!errors++) 713 D("bad len %d at slot %d idx %d", 714 len, i, idx); 715 } 716 } 717 if (errors) { 718 int pos = kring - kring->na->tx_rings; 719 int n = kring->na->num_queues + 2; 720 721 D("total %d errors", errors); 722 errors++; 723 D("%s %s[%d] reinit, cur %d -> %d avail %d -> %d", 724 kring->na->ifp->if_xname, 725 pos < n ? "TX" : "RX", pos < n ? pos : pos - n, 726 ring->cur, kring->nr_hwcur, 727 ring->avail, kring->nr_hwavail); 728 ring->cur = kring->nr_hwcur; 729 ring->avail = kring->nr_hwavail; 730 } 731 return (errors ? 1 : 0); 732 } 733 734 735 /* 736 * Set the ring ID. For devices with a single queue, a request 737 * for all rings is the same as a single ring. 738 */ 739 static int 740 netmap_set_ringid(struct netmap_priv_d *priv, u_int ringid) 741 { 742 struct ifnet *ifp = priv->np_ifp; 743 struct netmap_adapter *na = NA(ifp); 744 void *adapter = na->ifp->if_softc; /* shorthand */ 745 u_int i = ringid & NETMAP_RING_MASK; 746 /* first time we don't lock */ 747 int need_lock = (priv->np_qfirst != priv->np_qlast); 748 749 if ( (ringid & NETMAP_HW_RING) && i >= na->num_queues) { 750 D("invalid ring id %d", i); 751 return (EINVAL); 752 } 753 if (need_lock) 754 na->nm_lock(adapter, NETMAP_CORE_LOCK, 0); 755 priv->np_ringid = ringid; 756 if (ringid & NETMAP_SW_RING) { 757 priv->np_qfirst = na->num_queues; 758 priv->np_qlast = na->num_queues + 1; 759 } else if (ringid & NETMAP_HW_RING) { 760 priv->np_qfirst = i; 761 priv->np_qlast = i + 1; 762 } else { 763 priv->np_qfirst = 0; 764 priv->np_qlast = na->num_queues; 765 } 766 priv->np_txpoll = (ringid & NETMAP_NO_TX_POLL) ? 0 : 1; 767 if (need_lock) 768 na->nm_lock(adapter, NETMAP_CORE_UNLOCK, 0); 769 if (ringid & NETMAP_SW_RING) 770 D("ringid %s set to SW RING", ifp->if_xname); 771 else if (ringid & NETMAP_HW_RING) 772 D("ringid %s set to HW RING %d", ifp->if_xname, 773 priv->np_qfirst); 774 else 775 D("ringid %s set to all %d HW RINGS", ifp->if_xname, 776 priv->np_qlast); 777 return 0; 778 } 779 780 /* 781 * ioctl(2) support for the "netmap" device. 782 * 783 * Following a list of accepted commands: 784 * - NIOCGINFO 785 * - SIOCGIFADDR just for convenience 786 * - NIOCREGIF 787 * - NIOCUNREGIF 788 * - NIOCTXSYNC 789 * - NIOCRXSYNC 790 * 791 * Return 0 on success, errno otherwise. 792 */ 793 static int 794 netmap_ioctl(__unused struct cdev *dev, u_long cmd, caddr_t data, 795 __unused int fflag, struct thread *td) 796 { 797 struct netmap_priv_d *priv = NULL; 798 struct ifnet *ifp; 799 struct nmreq *nmr = (struct nmreq *) data; 800 struct netmap_adapter *na; 801 void *adapter; 802 int error; 803 u_int i; 804 struct netmap_if *nifp; 805 806 CURVNET_SET(TD_TO_VNET(td)); 807 808 error = devfs_get_cdevpriv((void **)&priv); 809 if (error != ENOENT && error != 0) { 810 CURVNET_RESTORE(); 811 return (error); 812 } 813 814 error = 0; /* Could be ENOENT */ 815 switch (cmd) { 816 case NIOCGINFO: /* return capabilities etc */ 817 /* memsize is always valid */ 818 nmr->nr_memsize = netmap_mem_d->nm_totalsize; 819 nmr->nr_offset = 0; 820 nmr->nr_numrings = 0; 821 nmr->nr_numslots = 0; 822 if (nmr->nr_name[0] == '\0') /* just get memory info */ 823 break; 824 error = get_ifp(nmr->nr_name, &ifp); /* get a refcount */ 825 if (error) 826 break; 827 na = NA(ifp); /* retrieve netmap_adapter */ 828 nmr->nr_numrings = na->num_queues; 829 nmr->nr_numslots = na->num_tx_desc; 830 if_rele(ifp); /* return the refcount */ 831 break; 832 833 case NIOCREGIF: 834 if (priv != NULL) { /* thread already registered */ 835 error = netmap_set_ringid(priv, nmr->nr_ringid); 836 break; 837 } 838 /* find the interface and a reference */ 839 error = get_ifp(nmr->nr_name, &ifp); /* keep reference */ 840 if (error) 841 break; 842 na = NA(ifp); /* retrieve netmap adapter */ 843 adapter = na->ifp->if_softc; /* shorthand */ 844 /* 845 * Allocate the private per-thread structure. 846 * XXX perhaps we can use a blocking malloc ? 847 */ 848 priv = malloc(sizeof(struct netmap_priv_d), M_DEVBUF, 849 M_NOWAIT | M_ZERO); 850 if (priv == NULL) { 851 error = ENOMEM; 852 if_rele(ifp); /* return the refcount */ 853 break; 854 } 855 856 857 for (i = 10; i > 0; i--) { 858 na->nm_lock(adapter, NETMAP_CORE_LOCK, 0); 859 if (!NETMAP_DELETING(na)) 860 break; 861 na->nm_lock(adapter, NETMAP_CORE_UNLOCK, 0); 862 tsleep(na, 0, "NIOCREGIF", hz/10); 863 } 864 if (i == 0) { 865 D("too many NIOCREGIF attempts, give up"); 866 error = EINVAL; 867 free(priv, M_DEVBUF); 868 if_rele(ifp); /* return the refcount */ 869 break; 870 } 871 872 priv->np_ifp = ifp; /* store the reference */ 873 error = netmap_set_ringid(priv, nmr->nr_ringid); 874 if (error) 875 goto error; 876 priv->np_nifp = nifp = netmap_if_new(nmr->nr_name, na); 877 if (nifp == NULL) { /* allocation failed */ 878 error = ENOMEM; 879 } else if (ifp->if_capenable & IFCAP_NETMAP) { 880 /* was already set */ 881 } else { 882 /* Otherwise set the card in netmap mode 883 * and make it use the shared buffers. 884 */ 885 error = na->nm_register(ifp, 1); /* mode on */ 886 if (error) { 887 /* 888 * do something similar to netmap_dtor(). 889 */ 890 netmap_free(na->tx_rings[0].ring, "rings, reg.failed"); 891 free(na->tx_rings, M_DEVBUF); 892 na->tx_rings = na->rx_rings = NULL; 893 na->refcount--; 894 netmap_free(nifp, "nifp, rings failed"); 895 nifp = NULL; 896 } 897 } 898 899 if (error) { /* reg. failed, release priv and ref */ 900 error: 901 na->nm_lock(adapter, NETMAP_CORE_UNLOCK, 0); 902 free(priv, M_DEVBUF); 903 if_rele(ifp); /* return the refcount */ 904 break; 905 } 906 907 na->nm_lock(adapter, NETMAP_CORE_UNLOCK, 0); 908 error = devfs_set_cdevpriv(priv, netmap_dtor); 909 910 if (error != 0) { 911 /* could not assign the private storage for the 912 * thread, call the destructor explicitly. 913 */ 914 netmap_dtor(priv); 915 break; 916 } 917 918 /* return the offset of the netmap_if object */ 919 nmr->nr_numrings = na->num_queues; 920 nmr->nr_numslots = na->num_tx_desc; 921 nmr->nr_memsize = netmap_mem_d->nm_totalsize; 922 nmr->nr_offset = 923 ((char *) nifp - (char *) netmap_mem_d->nm_buffer); 924 break; 925 926 case NIOCUNREGIF: 927 if (priv == NULL) { 928 error = ENXIO; 929 break; 930 } 931 932 /* the interface is unregistered inside the 933 destructor of the private data. */ 934 devfs_clear_cdevpriv(); 935 break; 936 937 case NIOCTXSYNC: 938 case NIOCRXSYNC: 939 if (priv == NULL) { 940 error = ENXIO; 941 break; 942 } 943 ifp = priv->np_ifp; /* we have a reference */ 944 na = NA(ifp); /* retrieve netmap adapter */ 945 adapter = ifp->if_softc; /* shorthand */ 946 947 if (priv->np_qfirst == na->num_queues) { 948 /* queues to/from host */ 949 if (cmd == NIOCTXSYNC) 950 netmap_sync_to_host(na); 951 else 952 netmap_sync_from_host(na, NULL); 953 break; 954 } 955 956 for (i = priv->np_qfirst; i < priv->np_qlast; i++) { 957 if (cmd == NIOCTXSYNC) { 958 struct netmap_kring *kring = &na->tx_rings[i]; 959 if (netmap_verbose & NM_VERB_TXSYNC) 960 D("sync tx ring %d cur %d hwcur %d", 961 i, kring->ring->cur, 962 kring->nr_hwcur); 963 na->nm_txsync(adapter, i, 1 /* do lock */); 964 if (netmap_verbose & NM_VERB_TXSYNC) 965 D("after sync tx ring %d cur %d hwcur %d", 966 i, kring->ring->cur, 967 kring->nr_hwcur); 968 } else { 969 na->nm_rxsync(adapter, i, 1 /* do lock */); 970 microtime(&na->rx_rings[i].ring->ts); 971 } 972 } 973 974 break; 975 976 case BIOCIMMEDIATE: 977 case BIOCGHDRCMPLT: 978 case BIOCSHDRCMPLT: 979 case BIOCSSEESENT: 980 D("ignore BIOCIMMEDIATE/BIOCSHDRCMPLT/BIOCSHDRCMPLT/BIOCSSEESENT"); 981 break; 982 983 default: 984 { 985 /* 986 * allow device calls 987 */ 988 struct socket so; 989 bzero(&so, sizeof(so)); 990 error = get_ifp(nmr->nr_name, &ifp); /* keep reference */ 991 if (error) 992 break; 993 so.so_vnet = ifp->if_vnet; 994 // so->so_proto not null. 995 error = ifioctl(&so, cmd, data, td); 996 if_rele(ifp); 997 } 998 } 999 1000 CURVNET_RESTORE(); 1001 return (error); 1002 } 1003 1004 1005 /* 1006 * select(2) and poll(2) handlers for the "netmap" device. 1007 * 1008 * Can be called for one or more queues. 1009 * Return true the event mask corresponding to ready events. 1010 * If there are no ready events, do a selrecord on either individual 1011 * selfd or on the global one. 1012 * Device-dependent parts (locking and sync of tx/rx rings) 1013 * are done through callbacks. 1014 */ 1015 static int 1016 netmap_poll(__unused struct cdev *dev, int events, struct thread *td) 1017 { 1018 struct netmap_priv_d *priv = NULL; 1019 struct netmap_adapter *na; 1020 struct ifnet *ifp; 1021 struct netmap_kring *kring; 1022 u_int i, check_all, want_tx, want_rx, revents = 0; 1023 void *adapter; 1024 1025 if (devfs_get_cdevpriv((void **)&priv) != 0 || priv == NULL) 1026 return POLLERR; 1027 1028 ifp = priv->np_ifp; 1029 // XXX check for deleting() ? 1030 if ( (ifp->if_capenable & IFCAP_NETMAP) == 0) 1031 return POLLERR; 1032 1033 if (netmap_verbose & 0x8000) 1034 D("device %s events 0x%x", ifp->if_xname, events); 1035 want_tx = events & (POLLOUT | POLLWRNORM); 1036 want_rx = events & (POLLIN | POLLRDNORM); 1037 1038 adapter = ifp->if_softc; 1039 na = NA(ifp); /* retrieve netmap adapter */ 1040 1041 /* how many queues we are scanning */ 1042 i = priv->np_qfirst; 1043 if (i == na->num_queues) { /* from/to host */ 1044 if (priv->np_txpoll || want_tx) { 1045 /* push any packets up, then we are always ready */ 1046 kring = &na->tx_rings[i]; 1047 netmap_sync_to_host(na); 1048 revents |= want_tx; 1049 } 1050 if (want_rx) { 1051 kring = &na->rx_rings[i]; 1052 if (kring->ring->avail == 0) 1053 netmap_sync_from_host(na, td); 1054 if (kring->ring->avail > 0) { 1055 revents |= want_rx; 1056 } 1057 } 1058 return (revents); 1059 } 1060 1061 /* 1062 * check_all is set if the card has more than one queue and 1063 * the client is polling all of them. If true, we sleep on 1064 * the "global" selfd, otherwise we sleep on individual selfd 1065 * (we can only sleep on one of them per direction). 1066 * The interrupt routine in the driver should always wake on 1067 * the individual selfd, and also on the global one if the card 1068 * has more than one ring. 1069 * 1070 * If the card has only one lock, we just use that. 1071 * If the card has separate ring locks, we just use those 1072 * unless we are doing check_all, in which case the whole 1073 * loop is wrapped by the global lock. 1074 * We acquire locks only when necessary: if poll is called 1075 * when buffers are available, we can just return without locks. 1076 * 1077 * rxsync() is only called if we run out of buffers on a POLLIN. 1078 * txsync() is called if we run out of buffers on POLLOUT, or 1079 * there are pending packets to send. The latter can be disabled 1080 * passing NETMAP_NO_TX_POLL in the NIOCREG call. 1081 */ 1082 check_all = (i + 1 != priv->np_qlast); 1083 1084 /* 1085 * core_lock indicates what to do with the core lock. 1086 * The core lock is used when either the card has no individual 1087 * locks, or it has individual locks but we are cheking all 1088 * rings so we need the core lock to avoid missing wakeup events. 1089 * 1090 * It has three possible states: 1091 * NO_CL we don't need to use the core lock, e.g. 1092 * because we are protected by individual locks. 1093 * NEED_CL we need the core lock. In this case, when we 1094 * call the lock routine, move to LOCKED_CL 1095 * to remember to release the lock once done. 1096 * LOCKED_CL core lock is set, so we need to release it. 1097 */ 1098 enum {NO_CL, NEED_CL, LOCKED_CL }; 1099 int core_lock = (check_all || !na->separate_locks) ? 1100 NEED_CL:NO_CL; 1101 /* 1102 * We start with a lock free round which is good if we have 1103 * data available. If this fails, then lock and call the sync 1104 * routines. 1105 */ 1106 for (i = priv->np_qfirst; want_rx && i < priv->np_qlast; i++) { 1107 kring = &na->rx_rings[i]; 1108 if (kring->ring->avail > 0) { 1109 revents |= want_rx; 1110 want_rx = 0; /* also breaks the loop */ 1111 } 1112 } 1113 for (i = priv->np_qfirst; want_tx && i < priv->np_qlast; i++) { 1114 kring = &na->tx_rings[i]; 1115 if (kring->ring->avail > 0) { 1116 revents |= want_tx; 1117 want_tx = 0; /* also breaks the loop */ 1118 } 1119 } 1120 1121 /* 1122 * If we to push packets out (priv->np_txpoll) or want_tx is 1123 * still set, we do need to run the txsync calls (on all rings, 1124 * to avoid that the tx rings stall). 1125 */ 1126 if (priv->np_txpoll || want_tx) { 1127 for (i = priv->np_qfirst; i < priv->np_qlast; i++) { 1128 kring = &na->tx_rings[i]; 1129 if (!want_tx && kring->ring->cur == kring->nr_hwcur) 1130 continue; 1131 if (core_lock == NEED_CL) { 1132 na->nm_lock(adapter, NETMAP_CORE_LOCK, 0); 1133 core_lock = LOCKED_CL; 1134 } 1135 if (na->separate_locks) 1136 na->nm_lock(adapter, NETMAP_TX_LOCK, i); 1137 if (netmap_verbose & NM_VERB_TXSYNC) 1138 D("send %d on %s %d", 1139 kring->ring->cur, 1140 ifp->if_xname, i); 1141 if (na->nm_txsync(adapter, i, 0 /* no lock */)) 1142 revents |= POLLERR; 1143 1144 if (want_tx) { 1145 if (kring->ring->avail > 0) { 1146 /* stop at the first ring. We don't risk 1147 * starvation. 1148 */ 1149 revents |= want_tx; 1150 want_tx = 0; 1151 } else if (!check_all) 1152 selrecord(td, &kring->si); 1153 } 1154 if (na->separate_locks) 1155 na->nm_lock(adapter, NETMAP_TX_UNLOCK, i); 1156 } 1157 } 1158 1159 /* 1160 * now if want_rx is still set we need to lock and rxsync. 1161 * Do it on all rings because otherwise we starve. 1162 */ 1163 if (want_rx) { 1164 for (i = priv->np_qfirst; i < priv->np_qlast; i++) { 1165 kring = &na->rx_rings[i]; 1166 if (core_lock == NEED_CL) { 1167 na->nm_lock(adapter, NETMAP_CORE_LOCK, 0); 1168 core_lock = LOCKED_CL; 1169 } 1170 if (na->separate_locks) 1171 na->nm_lock(adapter, NETMAP_RX_LOCK, i); 1172 1173 if (na->nm_rxsync(adapter, i, 0 /* no lock */)) 1174 revents |= POLLERR; 1175 if (no_timestamp == 0 || 1176 kring->ring->flags & NR_TIMESTAMP) 1177 microtime(&kring->ring->ts); 1178 1179 if (kring->ring->avail > 0) 1180 revents |= want_rx; 1181 else if (!check_all) 1182 selrecord(td, &kring->si); 1183 if (na->separate_locks) 1184 na->nm_lock(adapter, NETMAP_RX_UNLOCK, i); 1185 } 1186 } 1187 if (check_all && revents == 0) { 1188 i = na->num_queues + 1; /* the global queue */ 1189 if (want_tx) 1190 selrecord(td, &na->tx_rings[i].si); 1191 if (want_rx) 1192 selrecord(td, &na->rx_rings[i].si); 1193 } 1194 if (core_lock == LOCKED_CL) 1195 na->nm_lock(adapter, NETMAP_CORE_UNLOCK, 0); 1196 1197 return (revents); 1198 } 1199 1200 /*------- driver support routines ------*/ 1201 1202 /* 1203 * Initialize a ``netmap_adapter`` object created by driver on attach. 1204 * We allocate a block of memory with room for a struct netmap_adapter 1205 * plus two sets of N+2 struct netmap_kring (where N is the number 1206 * of hardware rings): 1207 * krings 0..N-1 are for the hardware queues. 1208 * kring N is for the host stack queue 1209 * kring N+1 is only used for the selinfo for all queues. 1210 * Return 0 on success, ENOMEM otherwise. 1211 */ 1212 int 1213 netmap_attach(struct netmap_adapter *na, int num_queues) 1214 { 1215 int n = num_queues + 2; 1216 int size = sizeof(*na) + 2 * n * sizeof(struct netmap_kring); 1217 void *buf; 1218 struct ifnet *ifp = na->ifp; 1219 1220 if (ifp == NULL) { 1221 D("ifp not set, giving up"); 1222 return EINVAL; 1223 } 1224 na->refcount = 0; 1225 na->num_queues = num_queues; 1226 1227 buf = malloc(size, M_DEVBUF, M_NOWAIT | M_ZERO); 1228 if (buf) { 1229 ifp->if_pspare[0] = buf; 1230 na->tx_rings = (void *)((char *)buf + sizeof(*na)); 1231 na->rx_rings = na->tx_rings + n; 1232 bcopy(na, buf, sizeof(*na)); 1233 ifp->if_capabilities |= IFCAP_NETMAP; 1234 } 1235 D("%s for %s", buf ? "ok" : "failed", ifp->if_xname); 1236 1237 return (buf ? 0 : ENOMEM); 1238 } 1239 1240 1241 /* 1242 * Free the allocated memory linked to the given ``netmap_adapter`` 1243 * object. 1244 */ 1245 void 1246 netmap_detach(struct ifnet *ifp) 1247 { 1248 u_int i; 1249 struct netmap_adapter *na = NA(ifp); 1250 1251 if (!na) 1252 return; 1253 1254 for (i = 0; i < na->num_queues + 2; i++) { 1255 knlist_destroy(&na->tx_rings[i].si.si_note); 1256 knlist_destroy(&na->rx_rings[i].si.si_note); 1257 } 1258 bzero(na, sizeof(*na)); 1259 ifp->if_pspare[0] = NULL; 1260 free(na, M_DEVBUF); 1261 } 1262 1263 1264 /* 1265 * intercept packets coming from the network stack and present 1266 * them to netmap as incoming packets on a separate ring. 1267 * We are not locked when called. 1268 */ 1269 int 1270 netmap_start(struct ifnet *ifp, struct mbuf *m) 1271 { 1272 struct netmap_adapter *na = NA(ifp); 1273 u_int i, len, n = na->num_queues; 1274 int error = EBUSY; 1275 struct netmap_kring *kring = &na->rx_rings[n]; 1276 struct netmap_slot *slot; 1277 1278 len = m->m_pkthdr.len; 1279 if (netmap_verbose & NM_VERB_HOST) 1280 D("%s packet %d len %d from the stack", ifp->if_xname, 1281 kring->nr_hwcur + kring->nr_hwavail, len); 1282 na->nm_lock(ifp->if_softc, NETMAP_CORE_LOCK, 0); 1283 if (kring->nr_hwavail >= (int)kring->nkr_num_slots - 1) { 1284 D("stack ring %s full\n", ifp->if_xname); 1285 goto done; /* no space */ 1286 } 1287 if (len > na->buff_size) { 1288 D("drop packet size %d > %d", len, na->buff_size); 1289 goto done; /* too long for us */ 1290 } 1291 1292 /* compute the insert position */ 1293 i = kring->nr_hwcur + kring->nr_hwavail; 1294 if (i >= kring->nkr_num_slots) 1295 i -= kring->nkr_num_slots; 1296 slot = &kring->ring->slot[i]; 1297 m_copydata(m, 0, len, NMB(slot)); 1298 slot->len = len; 1299 kring->nr_hwavail++; 1300 if (netmap_verbose & NM_VERB_HOST) 1301 D("wake up host ring %s %d", na->ifp->if_xname, na->num_queues); 1302 selwakeuppri(&kring->si, PI_NET); 1303 error = 0; 1304 done: 1305 na->nm_lock(ifp->if_softc, NETMAP_CORE_UNLOCK, 0); 1306 1307 /* release the mbuf in either cases of success or failure. As an 1308 * alternative, put the mbuf in a free list and free the list 1309 * only when really necessary. 1310 */ 1311 m_freem(m); 1312 1313 return (error); 1314 } 1315 1316 1317 /* 1318 * netmap_reset() is called by the driver routines when reinitializing 1319 * a ring. The driver is in charge of locking to protect the kring. 1320 * If netmap mode is not set just return NULL. 1321 */ 1322 struct netmap_slot * 1323 netmap_reset(struct netmap_adapter *na, enum txrx tx, int n, 1324 u_int new_cur) 1325 { 1326 struct netmap_kring *kring; 1327 struct netmap_ring *ring; 1328 int new_hwofs, lim; 1329 1330 if (na == NULL) 1331 return NULL; /* no netmap support here */ 1332 if (!(na->ifp->if_capenable & IFCAP_NETMAP)) 1333 return NULL; /* nothing to reinitialize */ 1334 kring = tx == NR_TX ? na->tx_rings + n : na->rx_rings + n; 1335 ring = kring->ring; 1336 lim = kring->nkr_num_slots - 1; 1337 1338 if (tx == NR_TX) 1339 new_hwofs = kring->nr_hwcur - new_cur; 1340 else 1341 new_hwofs = kring->nr_hwcur + kring->nr_hwavail - new_cur; 1342 if (new_hwofs > lim) 1343 new_hwofs -= lim + 1; 1344 1345 /* Alwayws set the new offset value and realign the ring. */ 1346 kring->nkr_hwofs = new_hwofs; 1347 if (tx == NR_TX) 1348 kring->nr_hwavail = kring->nkr_num_slots - 1; 1349 D("new hwofs %d on %s %s[%d]", 1350 kring->nkr_hwofs, na->ifp->if_xname, 1351 tx == NR_TX ? "TX" : "RX", n); 1352 1353 /* 1354 * We do the wakeup here, but the ring is not yet reconfigured. 1355 * However, we are under lock so there are no races. 1356 */ 1357 selwakeuppri(&kring->si, PI_NET); 1358 selwakeuppri(&kring[na->num_queues + 1 - n].si, PI_NET); 1359 return kring->ring->slot; 1360 } 1361 1362 static void 1363 ns_dmamap_cb(__unused void *arg, __unused bus_dma_segment_t * segs, 1364 __unused int nseg, __unused int error) 1365 { 1366 } 1367 1368 /* unload a bus_dmamap and create a new one. Used when the 1369 * buffer in the slot is changed. 1370 * XXX buflen is probably not needed, buffers have constant size. 1371 */ 1372 void 1373 netmap_reload_map(bus_dma_tag_t tag, bus_dmamap_t map, 1374 void *buf, bus_size_t buflen) 1375 { 1376 bus_addr_t paddr; 1377 bus_dmamap_unload(tag, map); 1378 bus_dmamap_load(tag, map, buf, buflen, ns_dmamap_cb, &paddr, 1379 BUS_DMA_NOWAIT); 1380 } 1381 1382 void 1383 netmap_load_map(bus_dma_tag_t tag, bus_dmamap_t map, 1384 void *buf, bus_size_t buflen) 1385 { 1386 bus_addr_t paddr; 1387 bus_dmamap_load(tag, map, buf, buflen, ns_dmamap_cb, &paddr, 1388 BUS_DMA_NOWAIT); 1389 } 1390 1391 /*------ netmap memory allocator -------*/ 1392 /* 1393 * Request for a chunk of memory. 1394 * 1395 * Memory objects are arranged into a list, hence we need to walk this 1396 * list until we find an object with the needed amount of data free. 1397 * This sounds like a completely inefficient implementation, but given 1398 * the fact that data allocation is done once, we can handle it 1399 * flawlessly. 1400 * 1401 * Return NULL on failure. 1402 */ 1403 static void * 1404 netmap_malloc(size_t size, __unused const char *msg) 1405 { 1406 struct netmap_mem_obj *mem_obj, *new_mem_obj; 1407 void *ret = NULL; 1408 1409 NMA_LOCK(); 1410 TAILQ_FOREACH(mem_obj, &netmap_mem_d->nm_molist, nmo_next) { 1411 if (mem_obj->nmo_used != 0 || mem_obj->nmo_size < size) 1412 continue; 1413 1414 new_mem_obj = malloc(sizeof(struct netmap_mem_obj), M_NETMAP, 1415 M_WAITOK | M_ZERO); 1416 TAILQ_INSERT_BEFORE(mem_obj, new_mem_obj, nmo_next); 1417 1418 new_mem_obj->nmo_used = 1; 1419 new_mem_obj->nmo_size = size; 1420 new_mem_obj->nmo_data = mem_obj->nmo_data; 1421 memset(new_mem_obj->nmo_data, 0, new_mem_obj->nmo_size); 1422 1423 mem_obj->nmo_size -= size; 1424 mem_obj->nmo_data = (char *) mem_obj->nmo_data + size; 1425 if (mem_obj->nmo_size == 0) { 1426 TAILQ_REMOVE(&netmap_mem_d->nm_molist, mem_obj, 1427 nmo_next); 1428 free(mem_obj, M_NETMAP); 1429 } 1430 1431 ret = new_mem_obj->nmo_data; 1432 1433 break; 1434 } 1435 NMA_UNLOCK(); 1436 ND("%s: %d bytes at %p", msg, size, ret); 1437 1438 return (ret); 1439 } 1440 1441 /* 1442 * Return the memory to the allocator. 1443 * 1444 * While freeing a memory object, we try to merge adjacent chunks in 1445 * order to reduce memory fragmentation. 1446 */ 1447 static void 1448 netmap_free(void *addr, const char *msg) 1449 { 1450 size_t size; 1451 struct netmap_mem_obj *cur, *prev, *next; 1452 1453 if (addr == NULL) { 1454 D("NULL addr for %s", msg); 1455 return; 1456 } 1457 1458 NMA_LOCK(); 1459 TAILQ_FOREACH(cur, &netmap_mem_d->nm_molist, nmo_next) { 1460 if (cur->nmo_data == addr && cur->nmo_used) 1461 break; 1462 } 1463 if (cur == NULL) { 1464 NMA_UNLOCK(); 1465 D("invalid addr %s %p", msg, addr); 1466 return; 1467 } 1468 1469 size = cur->nmo_size; 1470 cur->nmo_used = 0; 1471 1472 /* merge current chunk of memory with the previous one, 1473 if present. */ 1474 prev = TAILQ_PREV(cur, netmap_mem_obj_h, nmo_next); 1475 if (prev && prev->nmo_used == 0) { 1476 TAILQ_REMOVE(&netmap_mem_d->nm_molist, cur, nmo_next); 1477 prev->nmo_size += cur->nmo_size; 1478 free(cur, M_NETMAP); 1479 cur = prev; 1480 } 1481 1482 /* merge with the next one */ 1483 next = TAILQ_NEXT(cur, nmo_next); 1484 if (next && next->nmo_used == 0) { 1485 TAILQ_REMOVE(&netmap_mem_d->nm_molist, next, nmo_next); 1486 cur->nmo_size += next->nmo_size; 1487 free(next, M_NETMAP); 1488 } 1489 NMA_UNLOCK(); 1490 ND("freed %s %d bytes at %p", msg, size, addr); 1491 } 1492 1493 1494 /* 1495 * Initialize the memory allocator. 1496 * 1497 * Create the descriptor for the memory , allocate the pool of memory 1498 * and initialize the list of memory objects with a single chunk 1499 * containing the whole pre-allocated memory marked as free. 1500 * 1501 * Start with a large size, then halve as needed if we fail to 1502 * allocate the block. While halving, always add one extra page 1503 * because buffers 0 and 1 are used for special purposes. 1504 * Return 0 on success, errno otherwise. 1505 */ 1506 static int 1507 netmap_memory_init(void) 1508 { 1509 struct netmap_mem_obj *mem_obj; 1510 void *buf = NULL; 1511 int i, n, sz = NETMAP_MEMORY_SIZE; 1512 int extra_sz = 0; // space for rings and two spare buffers 1513 1514 for (; !buf && sz >= 1<<20; sz >>=1) { 1515 extra_sz = sz/200; 1516 extra_sz = (extra_sz + 2*PAGE_SIZE - 1) & ~(PAGE_SIZE-1); 1517 buf = contigmalloc(sz + extra_sz, 1518 M_NETMAP, 1519 M_WAITOK | M_ZERO, 1520 0, /* low address */ 1521 -1UL, /* high address */ 1522 PAGE_SIZE, /* alignment */ 1523 0 /* boundary */ 1524 ); 1525 } 1526 if (buf == NULL) 1527 return (ENOMEM); 1528 sz += extra_sz; 1529 netmap_mem_d = malloc(sizeof(struct netmap_mem_d), M_NETMAP, 1530 M_WAITOK | M_ZERO); 1531 mtx_init(&netmap_mem_d->nm_mtx, "netmap memory allocator lock", NULL, 1532 MTX_DEF); 1533 TAILQ_INIT(&netmap_mem_d->nm_molist); 1534 netmap_mem_d->nm_buffer = buf; 1535 netmap_mem_d->nm_totalsize = sz; 1536 1537 /* 1538 * A buffer takes 2k, a slot takes 8 bytes + ring overhead, 1539 * so the ratio is 200:1. In other words, we can use 1/200 of 1540 * the memory for the rings, and the rest for the buffers, 1541 * and be sure we never run out. 1542 */ 1543 netmap_mem_d->nm_size = sz/200; 1544 netmap_mem_d->nm_buf_start = 1545 (netmap_mem_d->nm_size + PAGE_SIZE - 1) & ~(PAGE_SIZE-1); 1546 netmap_mem_d->nm_buf_len = sz - netmap_mem_d->nm_buf_start; 1547 1548 nm_buf_pool.base = netmap_mem_d->nm_buffer; 1549 nm_buf_pool.base += netmap_mem_d->nm_buf_start; 1550 netmap_buffer_base = nm_buf_pool.base; 1551 D("netmap_buffer_base %p (offset %d)", 1552 netmap_buffer_base, (int)netmap_mem_d->nm_buf_start); 1553 /* number of buffers, they all start as free */ 1554 1555 netmap_total_buffers = nm_buf_pool.total_buffers = 1556 netmap_mem_d->nm_buf_len / NETMAP_BUF_SIZE; 1557 nm_buf_pool.bufsize = NETMAP_BUF_SIZE; 1558 1559 D("Have %d MB, use %dKB for rings, %d buffers at %p", 1560 (sz >> 20), (int)(netmap_mem_d->nm_size >> 10), 1561 nm_buf_pool.total_buffers, nm_buf_pool.base); 1562 1563 /* allocate and initialize the bitmap. Entry 0 is considered 1564 * always busy (used as default when there are no buffers left). 1565 */ 1566 n = (nm_buf_pool.total_buffers + 31) / 32; 1567 nm_buf_pool.bitmap = malloc(sizeof(uint32_t) * n, M_NETMAP, 1568 M_WAITOK | M_ZERO); 1569 nm_buf_pool.bitmap[0] = ~3; /* slot 0 and 1 always busy */ 1570 for (i = 1; i < n; i++) 1571 nm_buf_pool.bitmap[i] = ~0; 1572 nm_buf_pool.free = nm_buf_pool.total_buffers - 2; 1573 1574 mem_obj = malloc(sizeof(struct netmap_mem_obj), M_NETMAP, 1575 M_WAITOK | M_ZERO); 1576 TAILQ_INSERT_HEAD(&netmap_mem_d->nm_molist, mem_obj, nmo_next); 1577 mem_obj->nmo_used = 0; 1578 mem_obj->nmo_size = netmap_mem_d->nm_size; 1579 mem_obj->nmo_data = netmap_mem_d->nm_buffer; 1580 1581 return (0); 1582 } 1583 1584 1585 /* 1586 * Finalize the memory allocator. 1587 * 1588 * Free all the memory objects contained inside the list, and deallocate 1589 * the pool of memory; finally free the memory allocator descriptor. 1590 */ 1591 static void 1592 netmap_memory_fini(void) 1593 { 1594 struct netmap_mem_obj *mem_obj; 1595 1596 while (!TAILQ_EMPTY(&netmap_mem_d->nm_molist)) { 1597 mem_obj = TAILQ_FIRST(&netmap_mem_d->nm_molist); 1598 TAILQ_REMOVE(&netmap_mem_d->nm_molist, mem_obj, nmo_next); 1599 if (mem_obj->nmo_used == 1) { 1600 printf("netmap: leaked %d bytes at %p\n", 1601 (int)mem_obj->nmo_size, 1602 mem_obj->nmo_data); 1603 } 1604 free(mem_obj, M_NETMAP); 1605 } 1606 contigfree(netmap_mem_d->nm_buffer, netmap_mem_d->nm_totalsize, M_NETMAP); 1607 // XXX mutex_destroy(nm_mtx); 1608 free(netmap_mem_d, M_NETMAP); 1609 } 1610 1611 1612 /* 1613 * Module loader. 1614 * 1615 * Create the /dev/netmap device and initialize all global 1616 * variables. 1617 * 1618 * Return 0 on success, errno on failure. 1619 */ 1620 static int 1621 netmap_init(void) 1622 { 1623 int error; 1624 1625 1626 error = netmap_memory_init(); 1627 if (error != 0) { 1628 printf("netmap: unable to initialize the memory allocator."); 1629 return (error); 1630 } 1631 printf("netmap: loaded module with %d Mbytes\n", 1632 (int)(netmap_mem_d->nm_totalsize >> 20)); 1633 1634 netmap_dev = make_dev(&netmap_cdevsw, 0, UID_ROOT, GID_WHEEL, 0660, 1635 "netmap"); 1636 1637 return (0); 1638 } 1639 1640 1641 /* 1642 * Module unloader. 1643 * 1644 * Free all the memory, and destroy the ``/dev/netmap`` device. 1645 */ 1646 static void 1647 netmap_fini(void) 1648 { 1649 destroy_dev(netmap_dev); 1650 1651 netmap_memory_fini(); 1652 1653 printf("netmap: unloaded module.\n"); 1654 } 1655 1656 1657 /* 1658 * Kernel entry point. 1659 * 1660 * Initialize/finalize the module and return. 1661 * 1662 * Return 0 on success, errno on failure. 1663 */ 1664 static int 1665 netmap_loader(__unused struct module *module, int event, __unused void *arg) 1666 { 1667 int error = 0; 1668 1669 switch (event) { 1670 case MOD_LOAD: 1671 error = netmap_init(); 1672 break; 1673 1674 case MOD_UNLOAD: 1675 netmap_fini(); 1676 break; 1677 1678 default: 1679 error = EOPNOTSUPP; 1680 break; 1681 } 1682 1683 return (error); 1684 } 1685 1686 1687 DEV_MODULE(netmap, netmap_loader, NULL); 1688