1 /*- 2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD 3 * 4 * Copyright (c) 2009-2011 Spectra Logic Corporation 5 * All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice, this list of conditions, and the following disclaimer, 12 * without modification. 13 * 2. Redistributions in binary form must reproduce at minimum a disclaimer 14 * substantially similar to the "NO WARRANTY" disclaimer below 15 * ("Disclaimer") and any redistribution must be conditioned upon 16 * including a substantially similar Disclaimer requirement for further 17 * binary redistribution. 18 * 19 * NO WARRANTY 20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR 23 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 28 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 29 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 30 * POSSIBILITY OF SUCH DAMAGES. 31 * 32 * Authors: Justin T. Gibbs (Spectra Logic Corporation) 33 * Alan Somers (Spectra Logic Corporation) 34 * John Suykerbuyk (Spectra Logic Corporation) 35 */ 36 37 #include <sys/cdefs.h> 38 __FBSDID("$FreeBSD$"); 39 40 /** 41 * \file netback.c 42 * 43 * \brief Device driver supporting the vending of network access 44 * from this FreeBSD domain to other domains. 45 */ 46 #include "opt_inet.h" 47 #include "opt_inet6.h" 48 49 #include <sys/param.h> 50 #include <sys/kernel.h> 51 52 #include <sys/bus.h> 53 #include <sys/module.h> 54 #include <sys/rman.h> 55 #include <sys/socket.h> 56 #include <sys/sockio.h> 57 #include <sys/sysctl.h> 58 59 #include <net/if.h> 60 #include <net/if_var.h> 61 #include <net/if_arp.h> 62 #include <net/ethernet.h> 63 #include <net/if_dl.h> 64 #include <net/if_media.h> 65 #include <net/if_types.h> 66 67 #include <netinet/in.h> 68 #include <netinet/ip.h> 69 #include <netinet/if_ether.h> 70 #include <netinet/tcp.h> 71 #include <netinet/ip_icmp.h> 72 #include <netinet/udp.h> 73 #include <machine/in_cksum.h> 74 75 #include <vm/vm.h> 76 #include <vm/pmap.h> 77 #include <vm/vm_extern.h> 78 #include <vm/vm_kern.h> 79 80 #include <machine/_inttypes.h> 81 82 #include <xen/xen-os.h> 83 #include <xen/hypervisor.h> 84 #include <xen/xen_intr.h> 85 #include <xen/interface/io/netif.h> 86 #include <xen/xenbus/xenbusvar.h> 87 88 /*--------------------------- Compile-time Tunables --------------------------*/ 89 90 /*---------------------------------- Macros ----------------------------------*/ 91 /** 92 * Custom malloc type for all driver allocations. 93 */ 94 static MALLOC_DEFINE(M_XENNETBACK, "xnb", "Xen Net Back Driver Data"); 95 96 #define XNB_SG 1 /* netback driver supports feature-sg */ 97 #define XNB_GSO_TCPV4 0 /* netback driver supports feature-gso-tcpv4 */ 98 #define XNB_RX_COPY 1 /* netback driver supports feature-rx-copy */ 99 #define XNB_RX_FLIP 0 /* netback driver does not support feature-rx-flip */ 100 101 #undef XNB_DEBUG 102 #define XNB_DEBUG /* hardcode on during development */ 103 104 #ifdef XNB_DEBUG 105 #define DPRINTF(fmt, args...) \ 106 printf("xnb(%s:%d): " fmt, __FUNCTION__, __LINE__, ##args) 107 #else 108 #define DPRINTF(fmt, args...) do {} while (0) 109 #endif 110 111 /* Default length for stack-allocated grant tables */ 112 #define GNTTAB_LEN (64) 113 114 /* Features supported by all backends. TSO and LRO can be negotiated */ 115 #define XNB_CSUM_FEATURES (CSUM_TCP | CSUM_UDP) 116 117 #define NET_TX_RING_SIZE __RING_SIZE((netif_tx_sring_t *)0, PAGE_SIZE) 118 #define NET_RX_RING_SIZE __RING_SIZE((netif_rx_sring_t *)0, PAGE_SIZE) 119 120 /** 121 * Two argument version of the standard macro. Second argument is a tentative 122 * value of req_cons 123 */ 124 #define RING_HAS_UNCONSUMED_REQUESTS_2(_r, cons) ({ \ 125 unsigned int req = (_r)->sring->req_prod - cons; \ 126 unsigned int rsp = RING_SIZE(_r) - \ 127 (cons - (_r)->rsp_prod_pvt); \ 128 req < rsp ? req : rsp; \ 129 }) 130 131 #define virt_to_mfn(x) (vtophys(x) >> PAGE_SHIFT) 132 #define virt_to_offset(x) ((x) & (PAGE_SIZE - 1)) 133 134 /** 135 * Predefined array type of grant table copy descriptors. Used to pass around 136 * statically allocated memory structures. 137 */ 138 typedef struct gnttab_copy gnttab_copy_table[GNTTAB_LEN]; 139 140 /*--------------------------- Forward Declarations ---------------------------*/ 141 struct xnb_softc; 142 struct xnb_pkt; 143 144 static void xnb_attach_failed(struct xnb_softc *xnb, 145 int err, const char *fmt, ...) 146 __printflike(3,4); 147 static int xnb_shutdown(struct xnb_softc *xnb); 148 static int create_netdev(device_t dev); 149 static int xnb_detach(device_t dev); 150 static int xnb_ifmedia_upd(struct ifnet *ifp); 151 static void xnb_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr); 152 static void xnb_intr(void *arg); 153 static int xnb_send(netif_rx_back_ring_t *rxb, domid_t otherend, 154 const struct mbuf *mbufc, gnttab_copy_table gnttab); 155 static int xnb_recv(netif_tx_back_ring_t *txb, domid_t otherend, 156 struct mbuf **mbufc, struct ifnet *ifnet, 157 gnttab_copy_table gnttab); 158 static int xnb_ring2pkt(struct xnb_pkt *pkt, 159 const netif_tx_back_ring_t *tx_ring, 160 RING_IDX start); 161 static void xnb_txpkt2rsp(const struct xnb_pkt *pkt, 162 netif_tx_back_ring_t *ring, int error); 163 static struct mbuf *xnb_pkt2mbufc(const struct xnb_pkt *pkt, struct ifnet *ifp); 164 static int xnb_txpkt2gnttab(const struct xnb_pkt *pkt, 165 struct mbuf *mbufc, 166 gnttab_copy_table gnttab, 167 const netif_tx_back_ring_t *txb, 168 domid_t otherend_id); 169 static void xnb_update_mbufc(struct mbuf *mbufc, 170 const gnttab_copy_table gnttab, int n_entries); 171 static int xnb_mbufc2pkt(const struct mbuf *mbufc, 172 struct xnb_pkt *pkt, 173 RING_IDX start, int space); 174 static int xnb_rxpkt2gnttab(const struct xnb_pkt *pkt, 175 const struct mbuf *mbufc, 176 gnttab_copy_table gnttab, 177 const netif_rx_back_ring_t *rxb, 178 domid_t otherend_id); 179 static int xnb_rxpkt2rsp(const struct xnb_pkt *pkt, 180 const gnttab_copy_table gnttab, int n_entries, 181 netif_rx_back_ring_t *ring); 182 static void xnb_stop(struct xnb_softc*); 183 static int xnb_ioctl(struct ifnet*, u_long, caddr_t); 184 static void xnb_start_locked(struct ifnet*); 185 static void xnb_start(struct ifnet*); 186 static void xnb_ifinit_locked(struct xnb_softc*); 187 static void xnb_ifinit(void*); 188 #ifdef XNB_DEBUG 189 static int xnb_unit_test_main(SYSCTL_HANDLER_ARGS); 190 static int xnb_dump_rings(SYSCTL_HANDLER_ARGS); 191 #endif 192 #if defined(INET) || defined(INET6) 193 static void xnb_add_mbuf_cksum(struct mbuf *mbufc); 194 #endif 195 /*------------------------------ Data Structures -----------------------------*/ 196 197 198 /** 199 * Representation of a xennet packet. Simplified version of a packet as 200 * stored in the Xen tx ring. Applicable to both RX and TX packets 201 */ 202 struct xnb_pkt{ 203 /** 204 * Array index of the first data-bearing (eg, not extra info) entry 205 * for this packet 206 */ 207 RING_IDX car; 208 209 /** 210 * Array index of the second data-bearing entry for this packet. 211 * Invalid if the packet has only one data-bearing entry. If the 212 * packet has more than two data-bearing entries, then the second 213 * through the last will be sequential modulo the ring size 214 */ 215 RING_IDX cdr; 216 217 /** 218 * Optional extra info. Only valid if flags contains 219 * NETTXF_extra_info. Note that extra.type will always be 220 * XEN_NETIF_EXTRA_TYPE_GSO. Currently, no known netfront or netback 221 * driver will ever set XEN_NETIF_EXTRA_TYPE_MCAST_* 222 */ 223 netif_extra_info_t extra; 224 225 /** Size of entire packet in bytes. */ 226 uint16_t size; 227 228 /** The size of the first entry's data in bytes */ 229 uint16_t car_size; 230 231 /** 232 * Either NETTXF_ or NETRXF_ flags. Note that the flag values are 233 * not the same for TX and RX packets 234 */ 235 uint16_t flags; 236 237 /** 238 * The number of valid data-bearing entries (either netif_tx_request's 239 * or netif_rx_response's) in the packet. If this is 0, it means the 240 * entire packet is invalid. 241 */ 242 uint16_t list_len; 243 244 /** There was an error processing the packet */ 245 uint8_t error; 246 }; 247 248 /** xnb_pkt method: initialize it */ 249 static inline void 250 xnb_pkt_initialize(struct xnb_pkt *pxnb) 251 { 252 bzero(pxnb, sizeof(*pxnb)); 253 } 254 255 /** xnb_pkt method: mark the packet as valid */ 256 static inline void 257 xnb_pkt_validate(struct xnb_pkt *pxnb) 258 { 259 pxnb->error = 0; 260 }; 261 262 /** xnb_pkt method: mark the packet as invalid */ 263 static inline void 264 xnb_pkt_invalidate(struct xnb_pkt *pxnb) 265 { 266 pxnb->error = 1; 267 }; 268 269 /** xnb_pkt method: Check whether the packet is valid */ 270 static inline int 271 xnb_pkt_is_valid(const struct xnb_pkt *pxnb) 272 { 273 return (! pxnb->error); 274 } 275 276 #ifdef XNB_DEBUG 277 /** xnb_pkt method: print the packet's contents in human-readable format*/ 278 static void __unused 279 xnb_dump_pkt(const struct xnb_pkt *pkt) { 280 if (pkt == NULL) { 281 DPRINTF("Was passed a null pointer.\n"); 282 return; 283 } 284 DPRINTF("pkt address= %p\n", pkt); 285 DPRINTF("pkt->size=%d\n", pkt->size); 286 DPRINTF("pkt->car_size=%d\n", pkt->car_size); 287 DPRINTF("pkt->flags=0x%04x\n", pkt->flags); 288 DPRINTF("pkt->list_len=%d\n", pkt->list_len); 289 /* DPRINTF("pkt->extra"); TODO */ 290 DPRINTF("pkt->car=%d\n", pkt->car); 291 DPRINTF("pkt->cdr=%d\n", pkt->cdr); 292 DPRINTF("pkt->error=%d\n", pkt->error); 293 } 294 #endif /* XNB_DEBUG */ 295 296 static void 297 xnb_dump_txreq(RING_IDX idx, const struct netif_tx_request *txreq) 298 { 299 if (txreq != NULL) { 300 DPRINTF("netif_tx_request index =%u\n", idx); 301 DPRINTF("netif_tx_request.gref =%u\n", txreq->gref); 302 DPRINTF("netif_tx_request.offset=%hu\n", txreq->offset); 303 DPRINTF("netif_tx_request.flags =%hu\n", txreq->flags); 304 DPRINTF("netif_tx_request.id =%hu\n", txreq->id); 305 DPRINTF("netif_tx_request.size =%hu\n", txreq->size); 306 } 307 } 308 309 310 /** 311 * \brief Configuration data for a shared memory request ring 312 * used to communicate with the front-end client of this 313 * this driver. 314 */ 315 struct xnb_ring_config { 316 /** 317 * Runtime structures for ring access. Unfortunately, TX and RX rings 318 * use different data structures, and that cannot be changed since it 319 * is part of the interdomain protocol. 320 */ 321 union{ 322 netif_rx_back_ring_t rx_ring; 323 netif_tx_back_ring_t tx_ring; 324 } back_ring; 325 326 /** 327 * The device bus address returned by the hypervisor when 328 * mapping the ring and required to unmap it when a connection 329 * is torn down. 330 */ 331 uint64_t bus_addr; 332 333 /** The pseudo-physical address where ring memory is mapped.*/ 334 uint64_t gnt_addr; 335 336 /** KVA address where ring memory is mapped. */ 337 vm_offset_t va; 338 339 /** 340 * Grant table handles, one per-ring page, returned by the 341 * hyperpervisor upon mapping of the ring and required to 342 * unmap it when a connection is torn down. 343 */ 344 grant_handle_t handle; 345 346 /** The number of ring pages mapped for the current connection. */ 347 unsigned ring_pages; 348 349 /** 350 * The grant references, one per-ring page, supplied by the 351 * front-end, allowing us to reference the ring pages in the 352 * front-end's domain and to map these pages into our own domain. 353 */ 354 grant_ref_t ring_ref; 355 }; 356 357 /** 358 * Per-instance connection state flags. 359 */ 360 typedef enum 361 { 362 /** Communication with the front-end has been established. */ 363 XNBF_RING_CONNECTED = 0x01, 364 365 /** 366 * Front-end requests exist in the ring and are waiting for 367 * xnb_xen_req objects to free up. 368 */ 369 XNBF_RESOURCE_SHORTAGE = 0x02, 370 371 /** Connection teardown has started. */ 372 XNBF_SHUTDOWN = 0x04, 373 374 /** A thread is already performing shutdown processing. */ 375 XNBF_IN_SHUTDOWN = 0x08 376 } xnb_flag_t; 377 378 /** 379 * Types of rings. Used for array indices and to identify a ring's control 380 * data structure type 381 */ 382 typedef enum{ 383 XNB_RING_TYPE_TX = 0, /* ID of TX rings, used for array indices */ 384 XNB_RING_TYPE_RX = 1, /* ID of RX rings, used for array indices */ 385 XNB_NUM_RING_TYPES 386 } xnb_ring_type_t; 387 388 /** 389 * Per-instance configuration data. 390 */ 391 struct xnb_softc { 392 /** NewBus device corresponding to this instance. */ 393 device_t dev; 394 395 /* Media related fields */ 396 397 /** Generic network media state */ 398 struct ifmedia sc_media; 399 400 /** Media carrier info */ 401 struct ifnet *xnb_ifp; 402 403 /** Our own private carrier state */ 404 unsigned carrier; 405 406 /** Device MAC Address */ 407 uint8_t mac[ETHER_ADDR_LEN]; 408 409 /* Xen related fields */ 410 411 /** 412 * \brief The netif protocol abi in effect. 413 * 414 * There are situations where the back and front ends can 415 * have a different, native abi (e.g. intel x86_64 and 416 * 32bit x86 domains on the same machine). The back-end 417 * always accommodates the front-end's native abi. That 418 * value is pulled from the XenStore and recorded here. 419 */ 420 int abi; 421 422 /** 423 * Name of the bridge to which this VIF is connected, if any 424 * This field is dynamically allocated by xenbus and must be free()ed 425 * when no longer needed 426 */ 427 char *bridge; 428 429 /** The interrupt driven even channel used to signal ring events. */ 430 evtchn_port_t evtchn; 431 432 /** Xen device handle.*/ 433 long handle; 434 435 /** Handle to the communication ring event channel. */ 436 xen_intr_handle_t xen_intr_handle; 437 438 /** 439 * \brief Cached value of the front-end's domain id. 440 * 441 * This value is used at once for each mapped page in 442 * a transaction. We cache it to avoid incuring the 443 * cost of an ivar access every time this is needed. 444 */ 445 domid_t otherend_id; 446 447 /** 448 * Undocumented frontend feature. Has something to do with 449 * scatter/gather IO 450 */ 451 uint8_t can_sg; 452 /** Undocumented frontend feature */ 453 uint8_t gso; 454 /** Undocumented frontend feature */ 455 uint8_t gso_prefix; 456 /** Can checksum TCP/UDP over IPv4 */ 457 uint8_t ip_csum; 458 459 /* Implementation related fields */ 460 /** 461 * Preallocated grant table copy descriptor for RX operations. 462 * Access must be protected by rx_lock 463 */ 464 gnttab_copy_table rx_gnttab; 465 466 /** 467 * Preallocated grant table copy descriptor for TX operations. 468 * Access must be protected by tx_lock 469 */ 470 gnttab_copy_table tx_gnttab; 471 472 /** 473 * Resource representing allocated physical address space 474 * associated with our per-instance kva region. 475 */ 476 struct resource *pseudo_phys_res; 477 478 /** Resource id for allocated physical address space. */ 479 int pseudo_phys_res_id; 480 481 /** Ring mapping and interrupt configuration data. */ 482 struct xnb_ring_config ring_configs[XNB_NUM_RING_TYPES]; 483 484 /** 485 * Global pool of kva used for mapping remote domain ring 486 * and I/O transaction data. 487 */ 488 vm_offset_t kva; 489 490 /** Pseudo-physical address corresponding to kva. */ 491 uint64_t gnt_base_addr; 492 493 /** Various configuration and state bit flags. */ 494 xnb_flag_t flags; 495 496 /** Mutex protecting per-instance data in the receive path. */ 497 struct mtx rx_lock; 498 499 /** Mutex protecting per-instance data in the softc structure. */ 500 struct mtx sc_lock; 501 502 /** Mutex protecting per-instance data in the transmit path. */ 503 struct mtx tx_lock; 504 505 /** The size of the global kva pool. */ 506 int kva_size; 507 508 /** Name of the interface */ 509 char if_name[IFNAMSIZ]; 510 }; 511 512 /*---------------------------- Debugging functions ---------------------------*/ 513 #ifdef XNB_DEBUG 514 static void __unused 515 xnb_dump_gnttab_copy(const struct gnttab_copy *entry) 516 { 517 if (entry == NULL) { 518 printf("NULL grant table pointer\n"); 519 return; 520 } 521 522 if (entry->flags & GNTCOPY_dest_gref) 523 printf("gnttab dest ref=\t%u\n", entry->dest.u.ref); 524 else 525 printf("gnttab dest gmfn=\t%"PRI_xen_pfn"\n", 526 entry->dest.u.gmfn); 527 printf("gnttab dest offset=\t%hu\n", entry->dest.offset); 528 printf("gnttab dest domid=\t%hu\n", entry->dest.domid); 529 if (entry->flags & GNTCOPY_source_gref) 530 printf("gnttab source ref=\t%u\n", entry->source.u.ref); 531 else 532 printf("gnttab source gmfn=\t%"PRI_xen_pfn"\n", 533 entry->source.u.gmfn); 534 printf("gnttab source offset=\t%hu\n", entry->source.offset); 535 printf("gnttab source domid=\t%hu\n", entry->source.domid); 536 printf("gnttab len=\t%hu\n", entry->len); 537 printf("gnttab flags=\t%hu\n", entry->flags); 538 printf("gnttab status=\t%hd\n", entry->status); 539 } 540 541 static int 542 xnb_dump_rings(SYSCTL_HANDLER_ARGS) 543 { 544 static char results[720]; 545 struct xnb_softc const* xnb = (struct xnb_softc*)arg1; 546 netif_rx_back_ring_t const* rxb = 547 &xnb->ring_configs[XNB_RING_TYPE_RX].back_ring.rx_ring; 548 netif_tx_back_ring_t const* txb = 549 &xnb->ring_configs[XNB_RING_TYPE_TX].back_ring.tx_ring; 550 551 /* empty the result strings */ 552 results[0] = 0; 553 554 if ( !txb || !txb->sring || !rxb || !rxb->sring ) 555 return (SYSCTL_OUT(req, results, strnlen(results, 720))); 556 557 snprintf(results, 720, 558 "\n\t%35s %18s\n" /* TX, RX */ 559 "\t%16s %18d %18d\n" /* req_cons */ 560 "\t%16s %18d %18d\n" /* nr_ents */ 561 "\t%16s %18d %18d\n" /* rsp_prod_pvt */ 562 "\t%16s %18p %18p\n" /* sring */ 563 "\t%16s %18d %18d\n" /* req_prod */ 564 "\t%16s %18d %18d\n" /* req_event */ 565 "\t%16s %18d %18d\n" /* rsp_prod */ 566 "\t%16s %18d %18d\n", /* rsp_event */ 567 "TX", "RX", 568 "req_cons", txb->req_cons, rxb->req_cons, 569 "nr_ents", txb->nr_ents, rxb->nr_ents, 570 "rsp_prod_pvt", txb->rsp_prod_pvt, rxb->rsp_prod_pvt, 571 "sring", txb->sring, rxb->sring, 572 "sring->req_prod", txb->sring->req_prod, rxb->sring->req_prod, 573 "sring->req_event", txb->sring->req_event, rxb->sring->req_event, 574 "sring->rsp_prod", txb->sring->rsp_prod, rxb->sring->rsp_prod, 575 "sring->rsp_event", txb->sring->rsp_event, rxb->sring->rsp_event); 576 577 return (SYSCTL_OUT(req, results, strnlen(results, 720))); 578 } 579 580 static void __unused 581 xnb_dump_mbuf(const struct mbuf *m) 582 { 583 int len; 584 uint8_t *d; 585 if (m == NULL) 586 return; 587 588 printf("xnb_dump_mbuf:\n"); 589 if (m->m_flags & M_PKTHDR) { 590 printf(" flowid=%10d, csum_flags=%#8x, csum_data=%#8x, " 591 "tso_segsz=%5hd\n", 592 m->m_pkthdr.flowid, (int)m->m_pkthdr.csum_flags, 593 m->m_pkthdr.csum_data, m->m_pkthdr.tso_segsz); 594 printf(" rcvif=%16p, len=%19d\n", 595 m->m_pkthdr.rcvif, m->m_pkthdr.len); 596 } 597 printf(" m_next=%16p, m_nextpk=%16p, m_data=%16p\n", 598 m->m_next, m->m_nextpkt, m->m_data); 599 printf(" m_len=%17d, m_flags=%#15x, m_type=%18u\n", 600 m->m_len, m->m_flags, m->m_type); 601 602 len = m->m_len; 603 d = mtod(m, uint8_t*); 604 while (len > 0) { 605 int i; 606 printf(" "); 607 for (i = 0; (i < 16) && (len > 0); i++, len--) { 608 printf("%02hhx ", *(d++)); 609 } 610 printf("\n"); 611 } 612 } 613 #endif /* XNB_DEBUG */ 614 615 /*------------------------ Inter-Domain Communication ------------------------*/ 616 /** 617 * Free dynamically allocated KVA or pseudo-physical address allocations. 618 * 619 * \param xnb Per-instance xnb configuration structure. 620 */ 621 static void 622 xnb_free_communication_mem(struct xnb_softc *xnb) 623 { 624 if (xnb->kva != 0) { 625 if (xnb->pseudo_phys_res != NULL) { 626 xenmem_free(xnb->dev, xnb->pseudo_phys_res_id, 627 xnb->pseudo_phys_res); 628 xnb->pseudo_phys_res = NULL; 629 } 630 } 631 xnb->kva = 0; 632 xnb->gnt_base_addr = 0; 633 } 634 635 /** 636 * Cleanup all inter-domain communication mechanisms. 637 * 638 * \param xnb Per-instance xnb configuration structure. 639 */ 640 static int 641 xnb_disconnect(struct xnb_softc *xnb) 642 { 643 struct gnttab_unmap_grant_ref gnts[XNB_NUM_RING_TYPES]; 644 int error; 645 int i; 646 647 if (xnb->xen_intr_handle != NULL) 648 xen_intr_unbind(&xnb->xen_intr_handle); 649 650 /* 651 * We may still have another thread currently processing requests. We 652 * must acquire the rx and tx locks to make sure those threads are done, 653 * but we can release those locks as soon as we acquire them, because no 654 * more interrupts will be arriving. 655 */ 656 mtx_lock(&xnb->tx_lock); 657 mtx_unlock(&xnb->tx_lock); 658 mtx_lock(&xnb->rx_lock); 659 mtx_unlock(&xnb->rx_lock); 660 661 mtx_lock(&xnb->sc_lock); 662 /* Free malloc'd softc member variables */ 663 if (xnb->bridge != NULL) { 664 free(xnb->bridge, M_XENSTORE); 665 xnb->bridge = NULL; 666 } 667 668 /* All request processing has stopped, so unmap the rings */ 669 for (i=0; i < XNB_NUM_RING_TYPES; i++) { 670 gnts[i].host_addr = xnb->ring_configs[i].gnt_addr; 671 gnts[i].dev_bus_addr = xnb->ring_configs[i].bus_addr; 672 gnts[i].handle = xnb->ring_configs[i].handle; 673 } 674 error = HYPERVISOR_grant_table_op(GNTTABOP_unmap_grant_ref, gnts, 675 XNB_NUM_RING_TYPES); 676 KASSERT(error == 0, ("Grant table unmap op failed (%d)", error)); 677 678 xnb_free_communication_mem(xnb); 679 /* 680 * Zero the ring config structs because the pointers, handles, and 681 * grant refs contained therein are no longer valid. 682 */ 683 bzero(&xnb->ring_configs[XNB_RING_TYPE_TX], 684 sizeof(struct xnb_ring_config)); 685 bzero(&xnb->ring_configs[XNB_RING_TYPE_RX], 686 sizeof(struct xnb_ring_config)); 687 688 xnb->flags &= ~XNBF_RING_CONNECTED; 689 mtx_unlock(&xnb->sc_lock); 690 691 return (0); 692 } 693 694 /** 695 * Map a single shared memory ring into domain local address space and 696 * initialize its control structure 697 * 698 * \param xnb Per-instance xnb configuration structure 699 * \param ring_type Array index of this ring in the xnb's array of rings 700 * \return An errno 701 */ 702 static int 703 xnb_connect_ring(struct xnb_softc *xnb, xnb_ring_type_t ring_type) 704 { 705 struct gnttab_map_grant_ref gnt; 706 struct xnb_ring_config *ring = &xnb->ring_configs[ring_type]; 707 int error; 708 709 /* TX ring type = 0, RX =1 */ 710 ring->va = xnb->kva + ring_type * PAGE_SIZE; 711 ring->gnt_addr = xnb->gnt_base_addr + ring_type * PAGE_SIZE; 712 713 gnt.host_addr = ring->gnt_addr; 714 gnt.flags = GNTMAP_host_map; 715 gnt.ref = ring->ring_ref; 716 gnt.dom = xnb->otherend_id; 717 718 error = HYPERVISOR_grant_table_op(GNTTABOP_map_grant_ref, &gnt, 1); 719 if (error != 0) 720 panic("netback: Ring page grant table op failed (%d)", error); 721 722 if (gnt.status != 0) { 723 ring->va = 0; 724 error = EACCES; 725 xenbus_dev_fatal(xnb->dev, error, 726 "Ring shared page mapping failed. " 727 "Status %d.", gnt.status); 728 } else { 729 ring->handle = gnt.handle; 730 ring->bus_addr = gnt.dev_bus_addr; 731 732 if (ring_type == XNB_RING_TYPE_TX) { 733 BACK_RING_INIT(&ring->back_ring.tx_ring, 734 (netif_tx_sring_t*)ring->va, 735 ring->ring_pages * PAGE_SIZE); 736 } else if (ring_type == XNB_RING_TYPE_RX) { 737 BACK_RING_INIT(&ring->back_ring.rx_ring, 738 (netif_rx_sring_t*)ring->va, 739 ring->ring_pages * PAGE_SIZE); 740 } else { 741 xenbus_dev_fatal(xnb->dev, error, 742 "Unknown ring type %d", ring_type); 743 } 744 } 745 746 return error; 747 } 748 749 /** 750 * Setup the shared memory rings and bind an interrupt to the event channel 751 * used to notify us of ring changes. 752 * 753 * \param xnb Per-instance xnb configuration structure. 754 */ 755 static int 756 xnb_connect_comms(struct xnb_softc *xnb) 757 { 758 int error; 759 xnb_ring_type_t i; 760 761 if ((xnb->flags & XNBF_RING_CONNECTED) != 0) 762 return (0); 763 764 /* 765 * Kva for our rings are at the tail of the region of kva allocated 766 * by xnb_alloc_communication_mem(). 767 */ 768 for (i=0; i < XNB_NUM_RING_TYPES; i++) { 769 error = xnb_connect_ring(xnb, i); 770 if (error != 0) 771 return error; 772 } 773 774 xnb->flags |= XNBF_RING_CONNECTED; 775 776 error = xen_intr_bind_remote_port(xnb->dev, 777 xnb->otherend_id, 778 xnb->evtchn, 779 /*filter*/NULL, 780 xnb_intr, /*arg*/xnb, 781 INTR_TYPE_NET | INTR_MPSAFE, 782 &xnb->xen_intr_handle); 783 if (error != 0) { 784 (void)xnb_disconnect(xnb); 785 xenbus_dev_fatal(xnb->dev, error, "binding event channel"); 786 return (error); 787 } 788 789 DPRINTF("rings connected!\n"); 790 791 return (0); 792 } 793 794 /** 795 * Size KVA and pseudo-physical address allocations based on negotiated 796 * values for the size and number of I/O requests, and the size of our 797 * communication ring. 798 * 799 * \param xnb Per-instance xnb configuration structure. 800 * 801 * These address spaces are used to dynamically map pages in the 802 * front-end's domain into our own. 803 */ 804 static int 805 xnb_alloc_communication_mem(struct xnb_softc *xnb) 806 { 807 xnb_ring_type_t i; 808 809 xnb->kva_size = 0; 810 for (i=0; i < XNB_NUM_RING_TYPES; i++) { 811 xnb->kva_size += xnb->ring_configs[i].ring_pages * PAGE_SIZE; 812 } 813 814 /* 815 * Reserve a range of pseudo physical memory that we can map 816 * into kva. These pages will only be backed by machine 817 * pages ("real memory") during the lifetime of front-end requests 818 * via grant table operations. We will map the netif tx and rx rings 819 * into this space. 820 */ 821 xnb->pseudo_phys_res_id = 0; 822 xnb->pseudo_phys_res = xenmem_alloc(xnb->dev, &xnb->pseudo_phys_res_id, 823 xnb->kva_size); 824 if (xnb->pseudo_phys_res == NULL) { 825 xnb->kva = 0; 826 return (ENOMEM); 827 } 828 xnb->kva = (vm_offset_t)rman_get_virtual(xnb->pseudo_phys_res); 829 xnb->gnt_base_addr = rman_get_start(xnb->pseudo_phys_res); 830 return (0); 831 } 832 833 /** 834 * Collect information from the XenStore related to our device and its frontend 835 * 836 * \param xnb Per-instance xnb configuration structure. 837 */ 838 static int 839 xnb_collect_xenstore_info(struct xnb_softc *xnb) 840 { 841 /** 842 * \todo Linux collects the following info. We should collect most 843 * of this, too: 844 * "feature-rx-notify" 845 */ 846 const char *otherend_path; 847 const char *our_path; 848 int err; 849 unsigned int rx_copy, bridge_len; 850 uint8_t no_csum_offload; 851 852 otherend_path = xenbus_get_otherend_path(xnb->dev); 853 our_path = xenbus_get_node(xnb->dev); 854 855 /* Collect the critical communication parameters */ 856 err = xs_gather(XST_NIL, otherend_path, 857 "tx-ring-ref", "%l" PRIu32, 858 &xnb->ring_configs[XNB_RING_TYPE_TX].ring_ref, 859 "rx-ring-ref", "%l" PRIu32, 860 &xnb->ring_configs[XNB_RING_TYPE_RX].ring_ref, 861 "event-channel", "%" PRIu32, &xnb->evtchn, 862 NULL); 863 if (err != 0) { 864 xenbus_dev_fatal(xnb->dev, err, 865 "Unable to retrieve ring information from " 866 "frontend %s. Unable to connect.", 867 otherend_path); 868 return (err); 869 } 870 871 /* Collect the handle from xenstore */ 872 err = xs_scanf(XST_NIL, our_path, "handle", NULL, "%li", &xnb->handle); 873 if (err != 0) { 874 xenbus_dev_fatal(xnb->dev, err, 875 "Error reading handle from frontend %s. " 876 "Unable to connect.", otherend_path); 877 } 878 879 /* 880 * Collect the bridgename, if any. We do not need bridge_len; we just 881 * throw it away 882 */ 883 err = xs_read(XST_NIL, our_path, "bridge", &bridge_len, 884 (void**)&xnb->bridge); 885 if (err != 0) 886 xnb->bridge = NULL; 887 888 /* 889 * Does the frontend request that we use rx copy? If not, return an 890 * error because this driver only supports rx copy. 891 */ 892 err = xs_scanf(XST_NIL, otherend_path, "request-rx-copy", NULL, 893 "%" PRIu32, &rx_copy); 894 if (err == ENOENT) { 895 err = 0; 896 rx_copy = 0; 897 } 898 if (err < 0) { 899 xenbus_dev_fatal(xnb->dev, err, "reading %s/request-rx-copy", 900 otherend_path); 901 return err; 902 } 903 /** 904 * \todo: figure out the exact meaning of this feature, and when 905 * the frontend will set it to true. It should be set to true 906 * at some point 907 */ 908 /* if (!rx_copy)*/ 909 /* return EOPNOTSUPP;*/ 910 911 /** \todo Collect the rx notify feature */ 912 913 /* Collect the feature-sg. */ 914 if (xs_scanf(XST_NIL, otherend_path, "feature-sg", NULL, 915 "%hhu", &xnb->can_sg) < 0) 916 xnb->can_sg = 0; 917 918 /* Collect remaining frontend features */ 919 if (xs_scanf(XST_NIL, otherend_path, "feature-gso-tcpv4", NULL, 920 "%hhu", &xnb->gso) < 0) 921 xnb->gso = 0; 922 923 if (xs_scanf(XST_NIL, otherend_path, "feature-gso-tcpv4-prefix", NULL, 924 "%hhu", &xnb->gso_prefix) < 0) 925 xnb->gso_prefix = 0; 926 927 if (xs_scanf(XST_NIL, otherend_path, "feature-no-csum-offload", NULL, 928 "%hhu", &no_csum_offload) < 0) 929 no_csum_offload = 0; 930 xnb->ip_csum = (no_csum_offload == 0); 931 932 return (0); 933 } 934 935 /** 936 * Supply information about the physical device to the frontend 937 * via XenBus. 938 * 939 * \param xnb Per-instance xnb configuration structure. 940 */ 941 static int 942 xnb_publish_backend_info(struct xnb_softc *xnb) 943 { 944 struct xs_transaction xst; 945 const char *our_path; 946 int error; 947 948 our_path = xenbus_get_node(xnb->dev); 949 950 do { 951 error = xs_transaction_start(&xst); 952 if (error != 0) { 953 xenbus_dev_fatal(xnb->dev, error, 954 "Error publishing backend info " 955 "(start transaction)"); 956 break; 957 } 958 959 error = xs_printf(xst, our_path, "feature-sg", 960 "%d", XNB_SG); 961 if (error != 0) 962 break; 963 964 error = xs_printf(xst, our_path, "feature-gso-tcpv4", 965 "%d", XNB_GSO_TCPV4); 966 if (error != 0) 967 break; 968 969 error = xs_printf(xst, our_path, "feature-rx-copy", 970 "%d", XNB_RX_COPY); 971 if (error != 0) 972 break; 973 974 error = xs_printf(xst, our_path, "feature-rx-flip", 975 "%d", XNB_RX_FLIP); 976 if (error != 0) 977 break; 978 979 error = xs_transaction_end(xst, 0); 980 if (error != 0 && error != EAGAIN) { 981 xenbus_dev_fatal(xnb->dev, error, "ending transaction"); 982 break; 983 } 984 985 } while (error == EAGAIN); 986 987 return (error); 988 } 989 990 /** 991 * Connect to our netfront peer now that it has completed publishing 992 * its configuration into the XenStore. 993 * 994 * \param xnb Per-instance xnb configuration structure. 995 */ 996 static void 997 xnb_connect(struct xnb_softc *xnb) 998 { 999 int error; 1000 1001 if (xenbus_get_state(xnb->dev) == XenbusStateConnected) 1002 return; 1003 1004 if (xnb_collect_xenstore_info(xnb) != 0) 1005 return; 1006 1007 xnb->flags &= ~XNBF_SHUTDOWN; 1008 1009 /* Read front end configuration. */ 1010 1011 /* Allocate resources whose size depends on front-end configuration. */ 1012 error = xnb_alloc_communication_mem(xnb); 1013 if (error != 0) { 1014 xenbus_dev_fatal(xnb->dev, error, 1015 "Unable to allocate communication memory"); 1016 return; 1017 } 1018 1019 /* 1020 * Connect communication channel. 1021 */ 1022 error = xnb_connect_comms(xnb); 1023 if (error != 0) { 1024 /* Specific errors are reported by xnb_connect_comms(). */ 1025 return; 1026 } 1027 xnb->carrier = 1; 1028 1029 /* Ready for I/O. */ 1030 xenbus_set_state(xnb->dev, XenbusStateConnected); 1031 } 1032 1033 /*-------------------------- Device Teardown Support -------------------------*/ 1034 /** 1035 * Perform device shutdown functions. 1036 * 1037 * \param xnb Per-instance xnb configuration structure. 1038 * 1039 * Mark this instance as shutting down, wait for any active requests 1040 * to drain, disconnect from the front-end, and notify any waiters (e.g. 1041 * a thread invoking our detach method) that detach can now proceed. 1042 */ 1043 static int 1044 xnb_shutdown(struct xnb_softc *xnb) 1045 { 1046 /* 1047 * Due to the need to drop our mutex during some 1048 * xenbus operations, it is possible for two threads 1049 * to attempt to close out shutdown processing at 1050 * the same time. Tell the caller that hits this 1051 * race to try back later. 1052 */ 1053 if ((xnb->flags & XNBF_IN_SHUTDOWN) != 0) 1054 return (EAGAIN); 1055 1056 xnb->flags |= XNBF_SHUTDOWN; 1057 1058 xnb->flags |= XNBF_IN_SHUTDOWN; 1059 1060 mtx_unlock(&xnb->sc_lock); 1061 /* Free the network interface */ 1062 xnb->carrier = 0; 1063 if (xnb->xnb_ifp != NULL) { 1064 ether_ifdetach(xnb->xnb_ifp); 1065 if_free(xnb->xnb_ifp); 1066 xnb->xnb_ifp = NULL; 1067 } 1068 1069 xnb_disconnect(xnb); 1070 1071 if (xenbus_get_state(xnb->dev) < XenbusStateClosing) 1072 xenbus_set_state(xnb->dev, XenbusStateClosing); 1073 mtx_lock(&xnb->sc_lock); 1074 1075 xnb->flags &= ~XNBF_IN_SHUTDOWN; 1076 1077 /* Indicate to xnb_detach() that is it safe to proceed. */ 1078 wakeup(xnb); 1079 1080 return (0); 1081 } 1082 1083 /** 1084 * Report an attach time error to the console and Xen, and cleanup 1085 * this instance by forcing immediate detach processing. 1086 * 1087 * \param xnb Per-instance xnb configuration structure. 1088 * \param err Errno describing the error. 1089 * \param fmt Printf style format and arguments 1090 */ 1091 static void 1092 xnb_attach_failed(struct xnb_softc *xnb, int err, const char *fmt, ...) 1093 { 1094 va_list ap; 1095 va_list ap_hotplug; 1096 1097 va_start(ap, fmt); 1098 va_copy(ap_hotplug, ap); 1099 xs_vprintf(XST_NIL, xenbus_get_node(xnb->dev), 1100 "hotplug-error", fmt, ap_hotplug); 1101 va_end(ap_hotplug); 1102 (void)xs_printf(XST_NIL, xenbus_get_node(xnb->dev), 1103 "hotplug-status", "error"); 1104 1105 xenbus_dev_vfatal(xnb->dev, err, fmt, ap); 1106 va_end(ap); 1107 1108 (void)xs_printf(XST_NIL, xenbus_get_node(xnb->dev), "online", "0"); 1109 xnb_detach(xnb->dev); 1110 } 1111 1112 /*---------------------------- NewBus Entrypoints ----------------------------*/ 1113 /** 1114 * Inspect a XenBus device and claim it if is of the appropriate type. 1115 * 1116 * \param dev NewBus device object representing a candidate XenBus device. 1117 * 1118 * \return 0 for success, errno codes for failure. 1119 */ 1120 static int 1121 xnb_probe(device_t dev) 1122 { 1123 if (!strcmp(xenbus_get_type(dev), "vif")) { 1124 DPRINTF("Claiming device %d, %s\n", device_get_unit(dev), 1125 devclass_get_name(device_get_devclass(dev))); 1126 device_set_desc(dev, "Backend Virtual Network Device"); 1127 device_quiet(dev); 1128 return (0); 1129 } 1130 return (ENXIO); 1131 } 1132 1133 /** 1134 * Setup sysctl variables to control various Network Back parameters. 1135 * 1136 * \param xnb Xen Net Back softc. 1137 * 1138 */ 1139 static void 1140 xnb_setup_sysctl(struct xnb_softc *xnb) 1141 { 1142 struct sysctl_ctx_list *sysctl_ctx = NULL; 1143 struct sysctl_oid *sysctl_tree = NULL; 1144 1145 sysctl_ctx = device_get_sysctl_ctx(xnb->dev); 1146 if (sysctl_ctx == NULL) 1147 return; 1148 1149 sysctl_tree = device_get_sysctl_tree(xnb->dev); 1150 if (sysctl_tree == NULL) 1151 return; 1152 1153 #ifdef XNB_DEBUG 1154 SYSCTL_ADD_PROC(sysctl_ctx, 1155 SYSCTL_CHILDREN(sysctl_tree), 1156 OID_AUTO, 1157 "unit_test_results", 1158 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT, 1159 xnb, 1160 0, 1161 xnb_unit_test_main, 1162 "A", 1163 "Results of builtin unit tests"); 1164 1165 SYSCTL_ADD_PROC(sysctl_ctx, 1166 SYSCTL_CHILDREN(sysctl_tree), 1167 OID_AUTO, 1168 "dump_rings", 1169 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT, 1170 xnb, 1171 0, 1172 xnb_dump_rings, 1173 "A", 1174 "Xennet Back Rings"); 1175 #endif /* XNB_DEBUG */ 1176 } 1177 1178 /** 1179 * Create a network device. 1180 * @param handle device handle 1181 */ 1182 int 1183 create_netdev(device_t dev) 1184 { 1185 struct ifnet *ifp; 1186 struct xnb_softc *xnb; 1187 int err = 0; 1188 uint32_t handle; 1189 1190 xnb = device_get_softc(dev); 1191 mtx_init(&xnb->sc_lock, "xnb_softc", "xen netback softc lock", MTX_DEF); 1192 mtx_init(&xnb->tx_lock, "xnb_tx", "xen netback tx lock", MTX_DEF); 1193 mtx_init(&xnb->rx_lock, "xnb_rx", "xen netback rx lock", MTX_DEF); 1194 1195 xnb->dev = dev; 1196 1197 ifmedia_init(&xnb->sc_media, 0, xnb_ifmedia_upd, xnb_ifmedia_sts); 1198 ifmedia_add(&xnb->sc_media, IFM_ETHER|IFM_MANUAL, 0, NULL); 1199 ifmedia_set(&xnb->sc_media, IFM_ETHER|IFM_MANUAL); 1200 1201 /* 1202 * Set the MAC address to a dummy value (00:00:00:00:00), 1203 * if the MAC address of the host-facing interface is set 1204 * to the same as the guest-facing one (the value found in 1205 * xenstore), the bridge would stop delivering packets to 1206 * us because it would see that the destination address of 1207 * the packet is the same as the interface, and so the bridge 1208 * would expect the packet has already been delivered locally 1209 * (and just drop it). 1210 */ 1211 bzero(&xnb->mac[0], sizeof(xnb->mac)); 1212 1213 /* The interface will be named using the following nomenclature: 1214 * 1215 * xnb<domid>.<handle> 1216 * 1217 * Where handle is the oder of the interface referred to the guest. 1218 */ 1219 err = xs_scanf(XST_NIL, xenbus_get_node(xnb->dev), "handle", NULL, 1220 "%" PRIu32, &handle); 1221 if (err != 0) 1222 return (err); 1223 snprintf(xnb->if_name, IFNAMSIZ, "xnb%" PRIu16 ".%" PRIu32, 1224 xenbus_get_otherend_id(dev), handle); 1225 1226 if (err == 0) { 1227 /* Set up ifnet structure */ 1228 ifp = xnb->xnb_ifp = if_alloc(IFT_ETHER); 1229 ifp->if_softc = xnb; 1230 if_initname(ifp, xnb->if_name, IF_DUNIT_NONE); 1231 ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST; 1232 ifp->if_ioctl = xnb_ioctl; 1233 ifp->if_start = xnb_start; 1234 ifp->if_init = xnb_ifinit; 1235 ifp->if_mtu = ETHERMTU; 1236 ifp->if_snd.ifq_maxlen = NET_RX_RING_SIZE - 1; 1237 1238 ifp->if_hwassist = XNB_CSUM_FEATURES; 1239 ifp->if_capabilities = IFCAP_HWCSUM; 1240 ifp->if_capenable = IFCAP_HWCSUM; 1241 1242 ether_ifattach(ifp, xnb->mac); 1243 xnb->carrier = 0; 1244 } 1245 1246 return err; 1247 } 1248 1249 /** 1250 * Attach to a XenBus device that has been claimed by our probe routine. 1251 * 1252 * \param dev NewBus device object representing this Xen Net Back instance. 1253 * 1254 * \return 0 for success, errno codes for failure. 1255 */ 1256 static int 1257 xnb_attach(device_t dev) 1258 { 1259 struct xnb_softc *xnb; 1260 int error; 1261 xnb_ring_type_t i; 1262 1263 error = create_netdev(dev); 1264 if (error != 0) { 1265 xenbus_dev_fatal(dev, error, "creating netdev"); 1266 return (error); 1267 } 1268 1269 DPRINTF("Attaching to %s\n", xenbus_get_node(dev)); 1270 1271 /* 1272 * Basic initialization. 1273 * After this block it is safe to call xnb_detach() 1274 * to clean up any allocated data for this instance. 1275 */ 1276 xnb = device_get_softc(dev); 1277 xnb->otherend_id = xenbus_get_otherend_id(dev); 1278 for (i=0; i < XNB_NUM_RING_TYPES; i++) { 1279 xnb->ring_configs[i].ring_pages = 1; 1280 } 1281 1282 /* 1283 * Setup sysctl variables. 1284 */ 1285 xnb_setup_sysctl(xnb); 1286 1287 /* Update hot-plug status to satisfy xend. */ 1288 error = xs_printf(XST_NIL, xenbus_get_node(xnb->dev), 1289 "hotplug-status", "connected"); 1290 if (error != 0) { 1291 xnb_attach_failed(xnb, error, "writing %s/hotplug-status", 1292 xenbus_get_node(xnb->dev)); 1293 return (error); 1294 } 1295 1296 if ((error = xnb_publish_backend_info(xnb)) != 0) { 1297 /* 1298 * If we can't publish our data, we cannot participate 1299 * in this connection, and waiting for a front-end state 1300 * change will not help the situation. 1301 */ 1302 xnb_attach_failed(xnb, error, 1303 "Publishing backend status for %s", 1304 xenbus_get_node(xnb->dev)); 1305 return error; 1306 } 1307 1308 /* Tell the front end that we are ready to connect. */ 1309 xenbus_set_state(dev, XenbusStateInitWait); 1310 1311 return (0); 1312 } 1313 1314 /** 1315 * Detach from a net back device instance. 1316 * 1317 * \param dev NewBus device object representing this Xen Net Back instance. 1318 * 1319 * \return 0 for success, errno codes for failure. 1320 * 1321 * \note A net back device may be detached at any time in its life-cycle, 1322 * including part way through the attach process. For this reason, 1323 * initialization order and the initialization state checks in this 1324 * routine must be carefully coupled so that attach time failures 1325 * are gracefully handled. 1326 */ 1327 static int 1328 xnb_detach(device_t dev) 1329 { 1330 struct xnb_softc *xnb; 1331 1332 DPRINTF("\n"); 1333 1334 xnb = device_get_softc(dev); 1335 mtx_lock(&xnb->sc_lock); 1336 while (xnb_shutdown(xnb) == EAGAIN) { 1337 msleep(xnb, &xnb->sc_lock, /*wakeup prio unchanged*/0, 1338 "xnb_shutdown", 0); 1339 } 1340 mtx_unlock(&xnb->sc_lock); 1341 DPRINTF("\n"); 1342 1343 mtx_destroy(&xnb->tx_lock); 1344 mtx_destroy(&xnb->rx_lock); 1345 mtx_destroy(&xnb->sc_lock); 1346 return (0); 1347 } 1348 1349 /** 1350 * Prepare this net back device for suspension of this VM. 1351 * 1352 * \param dev NewBus device object representing this Xen net Back instance. 1353 * 1354 * \return 0 for success, errno codes for failure. 1355 */ 1356 static int 1357 xnb_suspend(device_t dev) 1358 { 1359 return (0); 1360 } 1361 1362 /** 1363 * Perform any processing required to recover from a suspended state. 1364 * 1365 * \param dev NewBus device object representing this Xen Net Back instance. 1366 * 1367 * \return 0 for success, errno codes for failure. 1368 */ 1369 static int 1370 xnb_resume(device_t dev) 1371 { 1372 return (0); 1373 } 1374 1375 /** 1376 * Handle state changes expressed via the XenStore by our front-end peer. 1377 * 1378 * \param dev NewBus device object representing this Xen 1379 * Net Back instance. 1380 * \param frontend_state The new state of the front-end. 1381 * 1382 * \return 0 for success, errno codes for failure. 1383 */ 1384 static void 1385 xnb_frontend_changed(device_t dev, XenbusState frontend_state) 1386 { 1387 struct xnb_softc *xnb; 1388 1389 xnb = device_get_softc(dev); 1390 1391 DPRINTF("frontend_state=%s, xnb_state=%s\n", 1392 xenbus_strstate(frontend_state), 1393 xenbus_strstate(xenbus_get_state(xnb->dev))); 1394 1395 switch (frontend_state) { 1396 case XenbusStateInitialising: 1397 break; 1398 case XenbusStateInitialised: 1399 case XenbusStateConnected: 1400 xnb_connect(xnb); 1401 break; 1402 case XenbusStateClosing: 1403 case XenbusStateClosed: 1404 mtx_lock(&xnb->sc_lock); 1405 xnb_shutdown(xnb); 1406 mtx_unlock(&xnb->sc_lock); 1407 if (frontend_state == XenbusStateClosed) 1408 xenbus_set_state(xnb->dev, XenbusStateClosed); 1409 break; 1410 default: 1411 xenbus_dev_fatal(xnb->dev, EINVAL, "saw state %d at frontend", 1412 frontend_state); 1413 break; 1414 } 1415 } 1416 1417 1418 /*---------------------------- Request Processing ----------------------------*/ 1419 /** 1420 * Interrupt handler bound to the shared ring's event channel. 1421 * Entry point for the xennet transmit path in netback 1422 * Transfers packets from the Xen ring to the host's generic networking stack 1423 * 1424 * \param arg Callback argument registerd during event channel 1425 * binding - the xnb_softc for this instance. 1426 */ 1427 static void 1428 xnb_intr(void *arg) 1429 { 1430 struct xnb_softc *xnb; 1431 struct ifnet *ifp; 1432 netif_tx_back_ring_t *txb; 1433 RING_IDX req_prod_local; 1434 1435 xnb = (struct xnb_softc *)arg; 1436 ifp = xnb->xnb_ifp; 1437 txb = &xnb->ring_configs[XNB_RING_TYPE_TX].back_ring.tx_ring; 1438 1439 mtx_lock(&xnb->tx_lock); 1440 do { 1441 int notify; 1442 req_prod_local = txb->sring->req_prod; 1443 xen_rmb(); 1444 1445 for (;;) { 1446 struct mbuf *mbufc; 1447 int err; 1448 1449 err = xnb_recv(txb, xnb->otherend_id, &mbufc, ifp, 1450 xnb->tx_gnttab); 1451 if (err || (mbufc == NULL)) 1452 break; 1453 1454 /* Send the packet to the generic network stack */ 1455 (*xnb->xnb_ifp->if_input)(xnb->xnb_ifp, mbufc); 1456 } 1457 1458 RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(txb, notify); 1459 if (notify != 0) 1460 xen_intr_signal(xnb->xen_intr_handle); 1461 1462 txb->sring->req_event = txb->req_cons + 1; 1463 xen_mb(); 1464 } while (txb->sring->req_prod != req_prod_local) ; 1465 mtx_unlock(&xnb->tx_lock); 1466 1467 xnb_start(ifp); 1468 } 1469 1470 1471 /** 1472 * Build a struct xnb_pkt based on netif_tx_request's from a netif tx ring. 1473 * Will read exactly 0 or 1 packets from the ring; never a partial packet. 1474 * \param[out] pkt The returned packet. If there is an error building 1475 * the packet, pkt.list_len will be set to 0. 1476 * \param[in] tx_ring Pointer to the Ring that is the input to this function 1477 * \param[in] start The ring index of the first potential request 1478 * \return The number of requests consumed to build this packet 1479 */ 1480 static int 1481 xnb_ring2pkt(struct xnb_pkt *pkt, const netif_tx_back_ring_t *tx_ring, 1482 RING_IDX start) 1483 { 1484 /* 1485 * Outline: 1486 * 1) Initialize pkt 1487 * 2) Read the first request of the packet 1488 * 3) Read the extras 1489 * 4) Set cdr 1490 * 5) Loop on the remainder of the packet 1491 * 6) Finalize pkt (stuff like car_size and list_len) 1492 */ 1493 int idx = start; 1494 int discard = 0; /* whether to discard the packet */ 1495 int more_data = 0; /* there are more request past the last one */ 1496 uint16_t cdr_size = 0; /* accumulated size of requests 2 through n */ 1497 1498 xnb_pkt_initialize(pkt); 1499 1500 /* Read the first request */ 1501 if (RING_HAS_UNCONSUMED_REQUESTS_2(tx_ring, idx)) { 1502 netif_tx_request_t *tx = RING_GET_REQUEST(tx_ring, idx); 1503 pkt->size = tx->size; 1504 pkt->flags = tx->flags & ~NETTXF_more_data; 1505 more_data = tx->flags & NETTXF_more_data; 1506 pkt->list_len++; 1507 pkt->car = idx; 1508 idx++; 1509 } 1510 1511 /* Read the extra info */ 1512 if ((pkt->flags & NETTXF_extra_info) && 1513 RING_HAS_UNCONSUMED_REQUESTS_2(tx_ring, idx)) { 1514 netif_extra_info_t *ext = 1515 (netif_extra_info_t*) RING_GET_REQUEST(tx_ring, idx); 1516 pkt->extra.type = ext->type; 1517 switch (pkt->extra.type) { 1518 case XEN_NETIF_EXTRA_TYPE_GSO: 1519 pkt->extra.u.gso = ext->u.gso; 1520 break; 1521 default: 1522 /* 1523 * The reference Linux netfront driver will 1524 * never set any other extra.type. So we don't 1525 * know what to do with it. Let's print an 1526 * error, then consume and discard the packet 1527 */ 1528 printf("xnb(%s:%d): Unknown extra info type %d." 1529 " Discarding packet\n", 1530 __func__, __LINE__, pkt->extra.type); 1531 xnb_dump_txreq(start, RING_GET_REQUEST(tx_ring, 1532 start)); 1533 xnb_dump_txreq(idx, RING_GET_REQUEST(tx_ring, 1534 idx)); 1535 discard = 1; 1536 break; 1537 } 1538 1539 pkt->extra.flags = ext->flags; 1540 if (ext->flags & XEN_NETIF_EXTRA_FLAG_MORE) { 1541 /* 1542 * The reference linux netfront driver never sets this 1543 * flag (nor does any other known netfront). So we 1544 * will discard the packet. 1545 */ 1546 printf("xnb(%s:%d): Request sets " 1547 "XEN_NETIF_EXTRA_FLAG_MORE, but we can't handle " 1548 "that\n", __func__, __LINE__); 1549 xnb_dump_txreq(start, RING_GET_REQUEST(tx_ring, start)); 1550 xnb_dump_txreq(idx, RING_GET_REQUEST(tx_ring, idx)); 1551 discard = 1; 1552 } 1553 1554 idx++; 1555 } 1556 1557 /* Set cdr. If there is not more data, cdr is invalid */ 1558 pkt->cdr = idx; 1559 1560 /* Loop on remainder of packet */ 1561 while (more_data && RING_HAS_UNCONSUMED_REQUESTS_2(tx_ring, idx)) { 1562 netif_tx_request_t *tx = RING_GET_REQUEST(tx_ring, idx); 1563 pkt->list_len++; 1564 cdr_size += tx->size; 1565 if (tx->flags & ~NETTXF_more_data) { 1566 /* There should be no other flags set at this point */ 1567 printf("xnb(%s:%d): Request sets unknown flags %d " 1568 "after the 1st request in the packet.\n", 1569 __func__, __LINE__, tx->flags); 1570 xnb_dump_txreq(start, RING_GET_REQUEST(tx_ring, start)); 1571 xnb_dump_txreq(idx, RING_GET_REQUEST(tx_ring, idx)); 1572 } 1573 1574 more_data = tx->flags & NETTXF_more_data; 1575 idx++; 1576 } 1577 1578 /* Finalize packet */ 1579 if (more_data != 0) { 1580 /* The ring ran out of requests before finishing the packet */ 1581 xnb_pkt_invalidate(pkt); 1582 idx = start; /* tell caller that we consumed no requests */ 1583 } else { 1584 /* Calculate car_size */ 1585 pkt->car_size = pkt->size - cdr_size; 1586 } 1587 if (discard != 0) { 1588 xnb_pkt_invalidate(pkt); 1589 } 1590 1591 return idx - start; 1592 } 1593 1594 1595 /** 1596 * Respond to all the requests that constituted pkt. Builds the responses and 1597 * writes them to the ring, but doesn't push them to the shared ring. 1598 * \param[in] pkt the packet that needs a response 1599 * \param[in] error true if there was an error handling the packet, such 1600 * as in the hypervisor copy op or mbuf allocation 1601 * \param[out] ring Responses go here 1602 */ 1603 static void 1604 xnb_txpkt2rsp(const struct xnb_pkt *pkt, netif_tx_back_ring_t *ring, 1605 int error) 1606 { 1607 /* 1608 * Outline: 1609 * 1) Respond to the first request 1610 * 2) Respond to the extra info reques 1611 * Loop through every remaining request in the packet, generating 1612 * responses that copy those requests' ids and sets the status 1613 * appropriately. 1614 */ 1615 netif_tx_request_t *tx; 1616 netif_tx_response_t *rsp; 1617 int i; 1618 uint16_t status; 1619 1620 status = (xnb_pkt_is_valid(pkt) == 0) || error ? 1621 NETIF_RSP_ERROR : NETIF_RSP_OKAY; 1622 KASSERT((pkt->list_len == 0) || (ring->rsp_prod_pvt == pkt->car), 1623 ("Cannot respond to ring requests out of order")); 1624 1625 if (pkt->list_len >= 1) { 1626 uint16_t id; 1627 tx = RING_GET_REQUEST(ring, ring->rsp_prod_pvt); 1628 id = tx->id; 1629 rsp = RING_GET_RESPONSE(ring, ring->rsp_prod_pvt); 1630 rsp->id = id; 1631 rsp->status = status; 1632 ring->rsp_prod_pvt++; 1633 1634 if (pkt->flags & NETRXF_extra_info) { 1635 rsp = RING_GET_RESPONSE(ring, ring->rsp_prod_pvt); 1636 rsp->status = NETIF_RSP_NULL; 1637 ring->rsp_prod_pvt++; 1638 } 1639 } 1640 1641 for (i=0; i < pkt->list_len - 1; i++) { 1642 uint16_t id; 1643 tx = RING_GET_REQUEST(ring, ring->rsp_prod_pvt); 1644 id = tx->id; 1645 rsp = RING_GET_RESPONSE(ring, ring->rsp_prod_pvt); 1646 rsp->id = id; 1647 rsp->status = status; 1648 ring->rsp_prod_pvt++; 1649 } 1650 } 1651 1652 /** 1653 * Create an mbuf chain to represent a packet. Initializes all of the headers 1654 * in the mbuf chain, but does not copy the data. The returned chain must be 1655 * free()'d when no longer needed 1656 * \param[in] pkt A packet to model the mbuf chain after 1657 * \return A newly allocated mbuf chain, possibly with clusters attached. 1658 * NULL on failure 1659 */ 1660 static struct mbuf* 1661 xnb_pkt2mbufc(const struct xnb_pkt *pkt, struct ifnet *ifp) 1662 { 1663 /** 1664 * \todo consider using a memory pool for mbufs instead of 1665 * reallocating them for every packet 1666 */ 1667 /** \todo handle extra data */ 1668 struct mbuf *m; 1669 1670 m = m_getm(NULL, pkt->size, M_NOWAIT, MT_DATA); 1671 1672 if (m != NULL) { 1673 m->m_pkthdr.rcvif = ifp; 1674 if (pkt->flags & NETTXF_data_validated) { 1675 /* 1676 * We lie to the host OS and always tell it that the 1677 * checksums are ok, because the packet is unlikely to 1678 * get corrupted going across domains. 1679 */ 1680 m->m_pkthdr.csum_flags = ( 1681 CSUM_IP_CHECKED | 1682 CSUM_IP_VALID | 1683 CSUM_DATA_VALID | 1684 CSUM_PSEUDO_HDR 1685 ); 1686 m->m_pkthdr.csum_data = 0xffff; 1687 } 1688 } 1689 return m; 1690 } 1691 1692 /** 1693 * Build a gnttab_copy table that can be used to copy data from a pkt 1694 * to an mbufc. Does not actually perform the copy. Always uses gref's on 1695 * the packet side. 1696 * \param[in] pkt pkt's associated requests form the src for 1697 * the copy operation 1698 * \param[in] mbufc mbufc's storage forms the dest for the copy operation 1699 * \param[out] gnttab Storage for the returned grant table 1700 * \param[in] txb Pointer to the backend ring structure 1701 * \param[in] otherend_id The domain ID of the other end of the copy 1702 * \return The number of gnttab entries filled 1703 */ 1704 static int 1705 xnb_txpkt2gnttab(const struct xnb_pkt *pkt, struct mbuf *mbufc, 1706 gnttab_copy_table gnttab, const netif_tx_back_ring_t *txb, 1707 domid_t otherend_id) 1708 { 1709 1710 struct mbuf *mbuf = mbufc;/* current mbuf within the chain */ 1711 int gnt_idx = 0; /* index into grant table */ 1712 RING_IDX r_idx = pkt->car; /* index into tx ring buffer */ 1713 int r_ofs = 0; /* offset of next data within tx request's data area */ 1714 int m_ofs = 0; /* offset of next data within mbuf's data area */ 1715 /* size in bytes that still needs to be represented in the table */ 1716 uint16_t size_remaining = pkt->size; 1717 1718 while (size_remaining > 0) { 1719 const netif_tx_request_t *txq = RING_GET_REQUEST(txb, r_idx); 1720 const size_t mbuf_space = M_TRAILINGSPACE(mbuf) - m_ofs; 1721 const size_t req_size = 1722 r_idx == pkt->car ? pkt->car_size : txq->size; 1723 const size_t pkt_space = req_size - r_ofs; 1724 /* 1725 * space is the largest amount of data that can be copied in the 1726 * grant table's next entry 1727 */ 1728 const size_t space = MIN(pkt_space, mbuf_space); 1729 1730 /* TODO: handle this error condition without panicking */ 1731 KASSERT(gnt_idx < GNTTAB_LEN, ("Grant table is too short")); 1732 1733 gnttab[gnt_idx].source.u.ref = txq->gref; 1734 gnttab[gnt_idx].source.domid = otherend_id; 1735 gnttab[gnt_idx].source.offset = txq->offset + r_ofs; 1736 gnttab[gnt_idx].dest.u.gmfn = virt_to_mfn( 1737 mtod(mbuf, vm_offset_t) + m_ofs); 1738 gnttab[gnt_idx].dest.offset = virt_to_offset( 1739 mtod(mbuf, vm_offset_t) + m_ofs); 1740 gnttab[gnt_idx].dest.domid = DOMID_SELF; 1741 gnttab[gnt_idx].len = space; 1742 gnttab[gnt_idx].flags = GNTCOPY_source_gref; 1743 1744 gnt_idx++; 1745 r_ofs += space; 1746 m_ofs += space; 1747 size_remaining -= space; 1748 if (req_size - r_ofs <= 0) { 1749 /* Must move to the next tx request */ 1750 r_ofs = 0; 1751 r_idx = (r_idx == pkt->car) ? pkt->cdr : r_idx + 1; 1752 } 1753 if (M_TRAILINGSPACE(mbuf) - m_ofs <= 0) { 1754 /* Must move to the next mbuf */ 1755 m_ofs = 0; 1756 mbuf = mbuf->m_next; 1757 } 1758 } 1759 1760 return gnt_idx; 1761 } 1762 1763 /** 1764 * Check the status of the grant copy operations, and update mbufs various 1765 * non-data fields to reflect the data present. 1766 * \param[in,out] mbufc mbuf chain to update. The chain must be valid and of 1767 * the correct length, and data should already be present 1768 * \param[in] gnttab A grant table for a just completed copy op 1769 * \param[in] n_entries The number of valid entries in the grant table 1770 */ 1771 static void 1772 xnb_update_mbufc(struct mbuf *mbufc, const gnttab_copy_table gnttab, 1773 int n_entries) 1774 { 1775 struct mbuf *mbuf = mbufc; 1776 int i; 1777 size_t total_size = 0; 1778 1779 for (i = 0; i < n_entries; i++) { 1780 KASSERT(gnttab[i].status == GNTST_okay, 1781 ("Some gnttab_copy entry had error status %hd\n", 1782 gnttab[i].status)); 1783 1784 mbuf->m_len += gnttab[i].len; 1785 total_size += gnttab[i].len; 1786 if (M_TRAILINGSPACE(mbuf) <= 0) { 1787 mbuf = mbuf->m_next; 1788 } 1789 } 1790 mbufc->m_pkthdr.len = total_size; 1791 1792 #if defined(INET) || defined(INET6) 1793 xnb_add_mbuf_cksum(mbufc); 1794 #endif 1795 } 1796 1797 /** 1798 * Dequeue at most one packet from the shared ring 1799 * \param[in,out] txb Netif tx ring. A packet will be removed from it, and 1800 * its private indices will be updated. But the indices 1801 * will not be pushed to the shared ring. 1802 * \param[in] ifnet Interface to which the packet will be sent 1803 * \param[in] otherend Domain ID of the other end of the ring 1804 * \param[out] mbufc The assembled mbuf chain, ready to send to the generic 1805 * networking stack 1806 * \param[in,out] gnttab Pointer to enough memory for a grant table. We make 1807 * this a function parameter so that we will take less 1808 * stack space. 1809 * \return An error code 1810 */ 1811 static int 1812 xnb_recv(netif_tx_back_ring_t *txb, domid_t otherend, struct mbuf **mbufc, 1813 struct ifnet *ifnet, gnttab_copy_table gnttab) 1814 { 1815 struct xnb_pkt pkt; 1816 /* number of tx requests consumed to build the last packet */ 1817 int num_consumed; 1818 int nr_ents; 1819 1820 *mbufc = NULL; 1821 num_consumed = xnb_ring2pkt(&pkt, txb, txb->req_cons); 1822 if (num_consumed == 0) 1823 return 0; /* Nothing to receive */ 1824 1825 /* update statistics independent of errors */ 1826 if_inc_counter(ifnet, IFCOUNTER_IPACKETS, 1); 1827 1828 /* 1829 * if we got here, then 1 or more requests was consumed, but the packet 1830 * is not necessarily valid. 1831 */ 1832 if (xnb_pkt_is_valid(&pkt) == 0) { 1833 /* got a garbage packet, respond and drop it */ 1834 xnb_txpkt2rsp(&pkt, txb, 1); 1835 txb->req_cons += num_consumed; 1836 DPRINTF("xnb_intr: garbage packet, num_consumed=%d\n", 1837 num_consumed); 1838 if_inc_counter(ifnet, IFCOUNTER_IERRORS, 1); 1839 return EINVAL; 1840 } 1841 1842 *mbufc = xnb_pkt2mbufc(&pkt, ifnet); 1843 1844 if (*mbufc == NULL) { 1845 /* 1846 * Couldn't allocate mbufs. Respond and drop the packet. Do 1847 * not consume the requests 1848 */ 1849 xnb_txpkt2rsp(&pkt, txb, 1); 1850 DPRINTF("xnb_intr: Couldn't allocate mbufs, num_consumed=%d\n", 1851 num_consumed); 1852 if_inc_counter(ifnet, IFCOUNTER_IQDROPS, 1); 1853 return ENOMEM; 1854 } 1855 1856 nr_ents = xnb_txpkt2gnttab(&pkt, *mbufc, gnttab, txb, otherend); 1857 1858 if (nr_ents > 0) { 1859 int __unused hv_ret = HYPERVISOR_grant_table_op(GNTTABOP_copy, 1860 gnttab, nr_ents); 1861 KASSERT(hv_ret == 0, 1862 ("HYPERVISOR_grant_table_op returned %d\n", hv_ret)); 1863 xnb_update_mbufc(*mbufc, gnttab, nr_ents); 1864 } 1865 1866 xnb_txpkt2rsp(&pkt, txb, 0); 1867 txb->req_cons += num_consumed; 1868 return 0; 1869 } 1870 1871 /** 1872 * Create an xnb_pkt based on the contents of an mbuf chain. 1873 * \param[in] mbufc mbuf chain to transform into a packet 1874 * \param[out] pkt Storage for the newly generated xnb_pkt 1875 * \param[in] start The ring index of the first available slot in the rx 1876 * ring 1877 * \param[in] space The number of free slots in the rx ring 1878 * \retval 0 Success 1879 * \retval EINVAL mbufc was corrupt or not convertible into a pkt 1880 * \retval EAGAIN There was not enough space in the ring to queue the 1881 * packet 1882 */ 1883 static int 1884 xnb_mbufc2pkt(const struct mbuf *mbufc, struct xnb_pkt *pkt, 1885 RING_IDX start, int space) 1886 { 1887 1888 int retval = 0; 1889 1890 if ((mbufc == NULL) || 1891 ( (mbufc->m_flags & M_PKTHDR) == 0) || 1892 (mbufc->m_pkthdr.len == 0)) { 1893 xnb_pkt_invalidate(pkt); 1894 retval = EINVAL; 1895 } else { 1896 int slots_required; 1897 1898 xnb_pkt_validate(pkt); 1899 pkt->flags = 0; 1900 pkt->size = mbufc->m_pkthdr.len; 1901 pkt->car = start; 1902 pkt->car_size = mbufc->m_len; 1903 1904 if (mbufc->m_pkthdr.csum_flags & CSUM_TSO) { 1905 pkt->flags |= NETRXF_extra_info; 1906 pkt->extra.u.gso.size = mbufc->m_pkthdr.tso_segsz; 1907 pkt->extra.u.gso.type = XEN_NETIF_GSO_TYPE_TCPV4; 1908 pkt->extra.u.gso.pad = 0; 1909 pkt->extra.u.gso.features = 0; 1910 pkt->extra.type = XEN_NETIF_EXTRA_TYPE_GSO; 1911 pkt->extra.flags = 0; 1912 pkt->cdr = start + 2; 1913 } else { 1914 pkt->cdr = start + 1; 1915 } 1916 if (mbufc->m_pkthdr.csum_flags & (CSUM_TSO | CSUM_DELAY_DATA)) { 1917 pkt->flags |= 1918 (NETRXF_csum_blank | NETRXF_data_validated); 1919 } 1920 1921 /* 1922 * Each ring response can have up to PAGE_SIZE of data. 1923 * Assume that we can defragment the mbuf chain efficiently 1924 * into responses so that each response but the last uses all 1925 * PAGE_SIZE bytes. 1926 */ 1927 pkt->list_len = howmany(pkt->size, PAGE_SIZE); 1928 1929 if (pkt->list_len > 1) { 1930 pkt->flags |= NETRXF_more_data; 1931 } 1932 1933 slots_required = pkt->list_len + 1934 (pkt->flags & NETRXF_extra_info ? 1 : 0); 1935 if (slots_required > space) { 1936 xnb_pkt_invalidate(pkt); 1937 retval = EAGAIN; 1938 } 1939 } 1940 1941 return retval; 1942 } 1943 1944 /** 1945 * Build a gnttab_copy table that can be used to copy data from an mbuf chain 1946 * to the frontend's shared buffers. Does not actually perform the copy. 1947 * Always uses gref's on the other end's side. 1948 * \param[in] pkt pkt's associated responses form the dest for the copy 1949 * operatoin 1950 * \param[in] mbufc The source for the copy operation 1951 * \param[out] gnttab Storage for the returned grant table 1952 * \param[in] rxb Pointer to the backend ring structure 1953 * \param[in] otherend_id The domain ID of the other end of the copy 1954 * \return The number of gnttab entries filled 1955 */ 1956 static int 1957 xnb_rxpkt2gnttab(const struct xnb_pkt *pkt, const struct mbuf *mbufc, 1958 gnttab_copy_table gnttab, const netif_rx_back_ring_t *rxb, 1959 domid_t otherend_id) 1960 { 1961 1962 const struct mbuf *mbuf = mbufc;/* current mbuf within the chain */ 1963 int gnt_idx = 0; /* index into grant table */ 1964 RING_IDX r_idx = pkt->car; /* index into rx ring buffer */ 1965 int r_ofs = 0; /* offset of next data within rx request's data area */ 1966 int m_ofs = 0; /* offset of next data within mbuf's data area */ 1967 /* size in bytes that still needs to be represented in the table */ 1968 uint16_t size_remaining; 1969 1970 size_remaining = (xnb_pkt_is_valid(pkt) != 0) ? pkt->size : 0; 1971 1972 while (size_remaining > 0) { 1973 const netif_rx_request_t *rxq = RING_GET_REQUEST(rxb, r_idx); 1974 const size_t mbuf_space = mbuf->m_len - m_ofs; 1975 /* Xen shared pages have an implied size of PAGE_SIZE */ 1976 const size_t req_size = PAGE_SIZE; 1977 const size_t pkt_space = req_size - r_ofs; 1978 /* 1979 * space is the largest amount of data that can be copied in the 1980 * grant table's next entry 1981 */ 1982 const size_t space = MIN(pkt_space, mbuf_space); 1983 1984 /* TODO: handle this error condition without panicing */ 1985 KASSERT(gnt_idx < GNTTAB_LEN, ("Grant table is too short")); 1986 1987 gnttab[gnt_idx].dest.u.ref = rxq->gref; 1988 gnttab[gnt_idx].dest.domid = otherend_id; 1989 gnttab[gnt_idx].dest.offset = r_ofs; 1990 gnttab[gnt_idx].source.u.gmfn = virt_to_mfn( 1991 mtod(mbuf, vm_offset_t) + m_ofs); 1992 gnttab[gnt_idx].source.offset = virt_to_offset( 1993 mtod(mbuf, vm_offset_t) + m_ofs); 1994 gnttab[gnt_idx].source.domid = DOMID_SELF; 1995 gnttab[gnt_idx].len = space; 1996 gnttab[gnt_idx].flags = GNTCOPY_dest_gref; 1997 1998 gnt_idx++; 1999 2000 r_ofs += space; 2001 m_ofs += space; 2002 size_remaining -= space; 2003 if (req_size - r_ofs <= 0) { 2004 /* Must move to the next rx request */ 2005 r_ofs = 0; 2006 r_idx = (r_idx == pkt->car) ? pkt->cdr : r_idx + 1; 2007 } 2008 if (mbuf->m_len - m_ofs <= 0) { 2009 /* Must move to the next mbuf */ 2010 m_ofs = 0; 2011 mbuf = mbuf->m_next; 2012 } 2013 } 2014 2015 return gnt_idx; 2016 } 2017 2018 /** 2019 * Generates responses for all the requests that constituted pkt. Builds 2020 * responses and writes them to the ring, but doesn't push the shared ring 2021 * indices. 2022 * \param[in] pkt the packet that needs a response 2023 * \param[in] gnttab The grant copy table corresponding to this packet. 2024 * Used to determine how many rsp->netif_rx_response_t's to 2025 * generate. 2026 * \param[in] n_entries Number of relevant entries in the grant table 2027 * \param[out] ring Responses go here 2028 * \return The number of RX requests that were consumed to generate 2029 * the responses 2030 */ 2031 static int 2032 xnb_rxpkt2rsp(const struct xnb_pkt *pkt, const gnttab_copy_table gnttab, 2033 int n_entries, netif_rx_back_ring_t *ring) 2034 { 2035 /* 2036 * This code makes the following assumptions: 2037 * * All entries in gnttab set GNTCOPY_dest_gref 2038 * * The entries in gnttab are grouped by their grefs: any two 2039 * entries with the same gref must be adjacent 2040 */ 2041 int error = 0; 2042 int gnt_idx, i; 2043 int n_responses = 0; 2044 grant_ref_t last_gref = GRANT_REF_INVALID; 2045 RING_IDX r_idx; 2046 2047 KASSERT(gnttab != NULL, ("Received a null granttable copy")); 2048 2049 /* 2050 * In the event of an error, we only need to send one response to the 2051 * netfront. In that case, we musn't write any data to the responses 2052 * after the one we send. So we must loop all the way through gnttab 2053 * looking for errors before we generate any responses 2054 * 2055 * Since we're looping through the grant table anyway, we'll count the 2056 * number of different gref's in it, which will tell us how many 2057 * responses to generate 2058 */ 2059 for (gnt_idx = 0; gnt_idx < n_entries; gnt_idx++) { 2060 int16_t status = gnttab[gnt_idx].status; 2061 if (status != GNTST_okay) { 2062 DPRINTF( 2063 "Got error %d for hypervisor gnttab_copy status\n", 2064 status); 2065 error = 1; 2066 break; 2067 } 2068 if (gnttab[gnt_idx].dest.u.ref != last_gref) { 2069 n_responses++; 2070 last_gref = gnttab[gnt_idx].dest.u.ref; 2071 } 2072 } 2073 2074 if (error != 0) { 2075 uint16_t id; 2076 netif_rx_response_t *rsp; 2077 2078 id = RING_GET_REQUEST(ring, ring->rsp_prod_pvt)->id; 2079 rsp = RING_GET_RESPONSE(ring, ring->rsp_prod_pvt); 2080 rsp->id = id; 2081 rsp->status = NETIF_RSP_ERROR; 2082 n_responses = 1; 2083 } else { 2084 gnt_idx = 0; 2085 const int has_extra = pkt->flags & NETRXF_extra_info; 2086 if (has_extra != 0) 2087 n_responses++; 2088 2089 for (i = 0; i < n_responses; i++) { 2090 netif_rx_request_t rxq; 2091 netif_rx_response_t *rsp; 2092 2093 r_idx = ring->rsp_prod_pvt + i; 2094 /* 2095 * We copy the structure of rxq instead of making a 2096 * pointer because it shares the same memory as rsp. 2097 */ 2098 rxq = *(RING_GET_REQUEST(ring, r_idx)); 2099 rsp = RING_GET_RESPONSE(ring, r_idx); 2100 if (has_extra && (i == 1)) { 2101 netif_extra_info_t *ext = 2102 (netif_extra_info_t*)rsp; 2103 ext->type = XEN_NETIF_EXTRA_TYPE_GSO; 2104 ext->flags = 0; 2105 ext->u.gso.size = pkt->extra.u.gso.size; 2106 ext->u.gso.type = XEN_NETIF_GSO_TYPE_TCPV4; 2107 ext->u.gso.pad = 0; 2108 ext->u.gso.features = 0; 2109 } else { 2110 rsp->id = rxq.id; 2111 rsp->status = GNTST_okay; 2112 rsp->offset = 0; 2113 rsp->flags = 0; 2114 if (i < pkt->list_len - 1) 2115 rsp->flags |= NETRXF_more_data; 2116 if ((i == 0) && has_extra) 2117 rsp->flags |= NETRXF_extra_info; 2118 if ((i == 0) && 2119 (pkt->flags & NETRXF_data_validated)) { 2120 rsp->flags |= NETRXF_data_validated; 2121 rsp->flags |= NETRXF_csum_blank; 2122 } 2123 rsp->status = 0; 2124 for (; gnttab[gnt_idx].dest.u.ref == rxq.gref; 2125 gnt_idx++) { 2126 rsp->status += gnttab[gnt_idx].len; 2127 } 2128 } 2129 } 2130 } 2131 2132 ring->req_cons += n_responses; 2133 ring->rsp_prod_pvt += n_responses; 2134 return n_responses; 2135 } 2136 2137 #if defined(INET) || defined(INET6) 2138 /** 2139 * Add IP, TCP, and/or UDP checksums to every mbuf in a chain. The first mbuf 2140 * in the chain must start with a struct ether_header. 2141 * 2142 * XXX This function will perform incorrectly on UDP packets that are split up 2143 * into multiple ethernet frames. 2144 */ 2145 static void 2146 xnb_add_mbuf_cksum(struct mbuf *mbufc) 2147 { 2148 struct ether_header *eh; 2149 struct ip *iph; 2150 uint16_t ether_type; 2151 2152 eh = mtod(mbufc, struct ether_header*); 2153 ether_type = ntohs(eh->ether_type); 2154 if (ether_type != ETHERTYPE_IP) { 2155 /* Nothing to calculate */ 2156 return; 2157 } 2158 2159 iph = (struct ip*)(eh + 1); 2160 if (mbufc->m_pkthdr.csum_flags & CSUM_IP_VALID) { 2161 iph->ip_sum = 0; 2162 iph->ip_sum = in_cksum_hdr(iph); 2163 } 2164 2165 switch (iph->ip_p) { 2166 case IPPROTO_TCP: 2167 if (mbufc->m_pkthdr.csum_flags & CSUM_IP_VALID) { 2168 size_t tcplen = ntohs(iph->ip_len) - sizeof(struct ip); 2169 struct tcphdr *th = (struct tcphdr*)(iph + 1); 2170 th->th_sum = in_pseudo(iph->ip_src.s_addr, 2171 iph->ip_dst.s_addr, htons(IPPROTO_TCP + tcplen)); 2172 th->th_sum = in_cksum_skip(mbufc, 2173 sizeof(struct ether_header) + ntohs(iph->ip_len), 2174 sizeof(struct ether_header) + (iph->ip_hl << 2)); 2175 } 2176 break; 2177 case IPPROTO_UDP: 2178 if (mbufc->m_pkthdr.csum_flags & CSUM_IP_VALID) { 2179 size_t udplen = ntohs(iph->ip_len) - sizeof(struct ip); 2180 struct udphdr *uh = (struct udphdr*)(iph + 1); 2181 uh->uh_sum = in_pseudo(iph->ip_src.s_addr, 2182 iph->ip_dst.s_addr, htons(IPPROTO_UDP + udplen)); 2183 uh->uh_sum = in_cksum_skip(mbufc, 2184 sizeof(struct ether_header) + ntohs(iph->ip_len), 2185 sizeof(struct ether_header) + (iph->ip_hl << 2)); 2186 } 2187 break; 2188 default: 2189 break; 2190 } 2191 } 2192 #endif /* INET || INET6 */ 2193 2194 static void 2195 xnb_stop(struct xnb_softc *xnb) 2196 { 2197 struct ifnet *ifp; 2198 2199 mtx_assert(&xnb->sc_lock, MA_OWNED); 2200 ifp = xnb->xnb_ifp; 2201 ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); 2202 if_link_state_change(ifp, LINK_STATE_DOWN); 2203 } 2204 2205 static int 2206 xnb_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data) 2207 { 2208 struct xnb_softc *xnb = ifp->if_softc; 2209 struct ifreq *ifr = (struct ifreq*) data; 2210 #ifdef INET 2211 struct ifaddr *ifa = (struct ifaddr*)data; 2212 #endif 2213 int error = 0; 2214 2215 switch (cmd) { 2216 case SIOCSIFFLAGS: 2217 mtx_lock(&xnb->sc_lock); 2218 if (ifp->if_flags & IFF_UP) { 2219 xnb_ifinit_locked(xnb); 2220 } else { 2221 if (ifp->if_drv_flags & IFF_DRV_RUNNING) { 2222 xnb_stop(xnb); 2223 } 2224 } 2225 /* 2226 * Note: netfront sets a variable named xn_if_flags 2227 * here, but that variable is never read 2228 */ 2229 mtx_unlock(&xnb->sc_lock); 2230 break; 2231 case SIOCSIFADDR: 2232 #ifdef INET 2233 mtx_lock(&xnb->sc_lock); 2234 if (ifa->ifa_addr->sa_family == AF_INET) { 2235 ifp->if_flags |= IFF_UP; 2236 if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) { 2237 ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | 2238 IFF_DRV_OACTIVE); 2239 if_link_state_change(ifp, 2240 LINK_STATE_DOWN); 2241 ifp->if_drv_flags |= IFF_DRV_RUNNING; 2242 ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; 2243 if_link_state_change(ifp, 2244 LINK_STATE_UP); 2245 } 2246 arp_ifinit(ifp, ifa); 2247 mtx_unlock(&xnb->sc_lock); 2248 } else { 2249 mtx_unlock(&xnb->sc_lock); 2250 #endif 2251 error = ether_ioctl(ifp, cmd, data); 2252 #ifdef INET 2253 } 2254 #endif 2255 break; 2256 case SIOCSIFCAP: 2257 mtx_lock(&xnb->sc_lock); 2258 if (ifr->ifr_reqcap & IFCAP_TXCSUM) { 2259 ifp->if_capenable |= IFCAP_TXCSUM; 2260 ifp->if_hwassist |= XNB_CSUM_FEATURES; 2261 } else { 2262 ifp->if_capenable &= ~(IFCAP_TXCSUM); 2263 ifp->if_hwassist &= ~(XNB_CSUM_FEATURES); 2264 } 2265 if ((ifr->ifr_reqcap & IFCAP_RXCSUM)) { 2266 ifp->if_capenable |= IFCAP_RXCSUM; 2267 } else { 2268 ifp->if_capenable &= ~(IFCAP_RXCSUM); 2269 } 2270 /* 2271 * TODO enable TSO4 and LRO once we no longer need 2272 * to calculate checksums in software 2273 */ 2274 #if 0 2275 if (ifr->if_reqcap |= IFCAP_TSO4) { 2276 if (IFCAP_TXCSUM & ifp->if_capenable) { 2277 printf("xnb: Xen netif requires that " 2278 "TXCSUM be enabled in order " 2279 "to use TSO4\n"); 2280 error = EINVAL; 2281 } else { 2282 ifp->if_capenable |= IFCAP_TSO4; 2283 ifp->if_hwassist |= CSUM_TSO; 2284 } 2285 } else { 2286 ifp->if_capenable &= ~(IFCAP_TSO4); 2287 ifp->if_hwassist &= ~(CSUM_TSO); 2288 } 2289 if (ifr->ifreqcap |= IFCAP_LRO) { 2290 ifp->if_capenable |= IFCAP_LRO; 2291 } else { 2292 ifp->if_capenable &= ~(IFCAP_LRO); 2293 } 2294 #endif 2295 mtx_unlock(&xnb->sc_lock); 2296 break; 2297 case SIOCSIFMTU: 2298 ifp->if_mtu = ifr->ifr_mtu; 2299 ifp->if_drv_flags &= ~IFF_DRV_RUNNING; 2300 xnb_ifinit(xnb); 2301 break; 2302 case SIOCADDMULTI: 2303 case SIOCDELMULTI: 2304 case SIOCSIFMEDIA: 2305 case SIOCGIFMEDIA: 2306 error = ifmedia_ioctl(ifp, ifr, &xnb->sc_media, cmd); 2307 break; 2308 default: 2309 error = ether_ioctl(ifp, cmd, data); 2310 break; 2311 } 2312 return (error); 2313 } 2314 2315 static void 2316 xnb_start_locked(struct ifnet *ifp) 2317 { 2318 netif_rx_back_ring_t *rxb; 2319 struct xnb_softc *xnb; 2320 struct mbuf *mbufc; 2321 RING_IDX req_prod_local; 2322 2323 xnb = ifp->if_softc; 2324 rxb = &xnb->ring_configs[XNB_RING_TYPE_RX].back_ring.rx_ring; 2325 2326 if (!xnb->carrier) 2327 return; 2328 2329 do { 2330 int out_of_space = 0; 2331 int notify; 2332 req_prod_local = rxb->sring->req_prod; 2333 xen_rmb(); 2334 for (;;) { 2335 int error; 2336 2337 IF_DEQUEUE(&ifp->if_snd, mbufc); 2338 if (mbufc == NULL) 2339 break; 2340 error = xnb_send(rxb, xnb->otherend_id, mbufc, 2341 xnb->rx_gnttab); 2342 switch (error) { 2343 case EAGAIN: 2344 /* 2345 * Insufficient space in the ring. 2346 * Requeue pkt and send when space is 2347 * available. 2348 */ 2349 IF_PREPEND(&ifp->if_snd, mbufc); 2350 /* 2351 * Perhaps the frontend missed an IRQ 2352 * and went to sleep. Notify it to wake 2353 * it up. 2354 */ 2355 out_of_space = 1; 2356 break; 2357 2358 case EINVAL: 2359 /* OS gave a corrupt packet. Drop it.*/ 2360 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); 2361 /* FALLTHROUGH */ 2362 default: 2363 /* Send succeeded, or packet had error. 2364 * Free the packet */ 2365 if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); 2366 if (mbufc) 2367 m_freem(mbufc); 2368 break; 2369 } 2370 if (out_of_space != 0) 2371 break; 2372 } 2373 2374 RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(rxb, notify); 2375 if ((notify != 0) || (out_of_space != 0)) 2376 xen_intr_signal(xnb->xen_intr_handle); 2377 rxb->sring->req_event = req_prod_local + 1; 2378 xen_mb(); 2379 } while (rxb->sring->req_prod != req_prod_local) ; 2380 } 2381 2382 /** 2383 * Sends one packet to the ring. Blocks until the packet is on the ring 2384 * \param[in] mbufc Contains one packet to send. Caller must free 2385 * \param[in,out] rxb The packet will be pushed onto this ring, but the 2386 * otherend will not be notified. 2387 * \param[in] otherend The domain ID of the other end of the connection 2388 * \retval EAGAIN The ring did not have enough space for the packet. 2389 * The ring has not been modified 2390 * \param[in,out] gnttab Pointer to enough memory for a grant table. We make 2391 * this a function parameter so that we will take less 2392 * stack space. 2393 * \retval EINVAL mbufc was corrupt or not convertible into a pkt 2394 */ 2395 static int 2396 xnb_send(netif_rx_back_ring_t *ring, domid_t otherend, const struct mbuf *mbufc, 2397 gnttab_copy_table gnttab) 2398 { 2399 struct xnb_pkt pkt; 2400 int error, n_entries, n_reqs; 2401 RING_IDX space; 2402 2403 space = ring->sring->req_prod - ring->req_cons; 2404 error = xnb_mbufc2pkt(mbufc, &pkt, ring->rsp_prod_pvt, space); 2405 if (error != 0) 2406 return error; 2407 n_entries = xnb_rxpkt2gnttab(&pkt, mbufc, gnttab, ring, otherend); 2408 if (n_entries != 0) { 2409 int __unused hv_ret = HYPERVISOR_grant_table_op(GNTTABOP_copy, 2410 gnttab, n_entries); 2411 KASSERT(hv_ret == 0, ("HYPERVISOR_grant_table_op returned %d\n", 2412 hv_ret)); 2413 } 2414 2415 n_reqs = xnb_rxpkt2rsp(&pkt, gnttab, n_entries, ring); 2416 2417 return 0; 2418 } 2419 2420 static void 2421 xnb_start(struct ifnet *ifp) 2422 { 2423 struct xnb_softc *xnb; 2424 2425 xnb = ifp->if_softc; 2426 mtx_lock(&xnb->rx_lock); 2427 xnb_start_locked(ifp); 2428 mtx_unlock(&xnb->rx_lock); 2429 } 2430 2431 /* equivalent of network_open() in Linux */ 2432 static void 2433 xnb_ifinit_locked(struct xnb_softc *xnb) 2434 { 2435 struct ifnet *ifp; 2436 2437 ifp = xnb->xnb_ifp; 2438 2439 mtx_assert(&xnb->sc_lock, MA_OWNED); 2440 2441 if (ifp->if_drv_flags & IFF_DRV_RUNNING) 2442 return; 2443 2444 xnb_stop(xnb); 2445 2446 ifp->if_drv_flags |= IFF_DRV_RUNNING; 2447 ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; 2448 if_link_state_change(ifp, LINK_STATE_UP); 2449 } 2450 2451 2452 static void 2453 xnb_ifinit(void *xsc) 2454 { 2455 struct xnb_softc *xnb = xsc; 2456 2457 mtx_lock(&xnb->sc_lock); 2458 xnb_ifinit_locked(xnb); 2459 mtx_unlock(&xnb->sc_lock); 2460 } 2461 2462 /** 2463 * Callback used by the generic networking code to tell us when our carrier 2464 * state has changed. Since we don't have a physical carrier, we don't care 2465 */ 2466 static int 2467 xnb_ifmedia_upd(struct ifnet *ifp) 2468 { 2469 return (0); 2470 } 2471 2472 /** 2473 * Callback used by the generic networking code to ask us what our carrier 2474 * state is. Since we don't have a physical carrier, this is very simple 2475 */ 2476 static void 2477 xnb_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr) 2478 { 2479 ifmr->ifm_status = IFM_AVALID|IFM_ACTIVE; 2480 ifmr->ifm_active = IFM_ETHER|IFM_MANUAL; 2481 } 2482 2483 2484 /*---------------------------- NewBus Registration ---------------------------*/ 2485 static device_method_t xnb_methods[] = { 2486 /* Device interface */ 2487 DEVMETHOD(device_probe, xnb_probe), 2488 DEVMETHOD(device_attach, xnb_attach), 2489 DEVMETHOD(device_detach, xnb_detach), 2490 DEVMETHOD(device_shutdown, bus_generic_shutdown), 2491 DEVMETHOD(device_suspend, xnb_suspend), 2492 DEVMETHOD(device_resume, xnb_resume), 2493 2494 /* Xenbus interface */ 2495 DEVMETHOD(xenbus_otherend_changed, xnb_frontend_changed), 2496 2497 { 0, 0 } 2498 }; 2499 2500 static driver_t xnb_driver = { 2501 "xnb", 2502 xnb_methods, 2503 sizeof(struct xnb_softc), 2504 }; 2505 devclass_t xnb_devclass; 2506 2507 DRIVER_MODULE(xnb, xenbusb_back, xnb_driver, xnb_devclass, 0, 0); 2508 2509 2510 /*-------------------------- Unit Tests -------------------------------------*/ 2511 #ifdef XNB_DEBUG 2512 #include "netback_unit_tests.c" 2513 #endif 2514