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