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