Home | History | Annotate | Line # | Download | only in pci
if_wpi.c revision 1.17.4.11
      1 /*  $NetBSD: if_wpi.c,v 1.17.4.11 2007/11/21 21:55:30 joerg Exp $    */
      2 
      3 /*-
      4  * Copyright (c) 2006, 2007
      5  *	Damien Bergamini <damien.bergamini (at) free.fr>
      6  *
      7  * Permission to use, copy, modify, and distribute this software for any
      8  * purpose with or without fee is hereby granted, provided that the above
      9  * copyright notice and this permission notice appear in all copies.
     10  *
     11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     18  */
     19 
     20 #include <sys/cdefs.h>
     21 __KERNEL_RCSID(0, "$NetBSD: if_wpi.c,v 1.17.4.11 2007/11/21 21:55:30 joerg Exp $");
     22 
     23 /*
     24  * Driver for Intel PRO/Wireless 3945ABG 802.11 network adapters.
     25  */
     26 
     27 #include "bpfilter.h"
     28 
     29 #include <sys/param.h>
     30 #include <sys/sockio.h>
     31 #include <sys/sysctl.h>
     32 #include <sys/mbuf.h>
     33 #include <sys/kernel.h>
     34 #include <sys/socket.h>
     35 #include <sys/systm.h>
     36 #include <sys/malloc.h>
     37 #include <sys/conf.h>
     38 #include <sys/kauth.h>
     39 #include <sys/callout.h>
     40 
     41 #include <sys/bus.h>
     42 #include <machine/endian.h>
     43 #include <sys/intr.h>
     44 
     45 #include <dev/pci/pcireg.h>
     46 #include <dev/pci/pcivar.h>
     47 #include <dev/pci/pcidevs.h>
     48 
     49 #if NBPFILTER > 0
     50 #include <net/bpf.h>
     51 #endif
     52 #include <net/if.h>
     53 #include <net/if_arp.h>
     54 #include <net/if_dl.h>
     55 #include <net/if_ether.h>
     56 #include <net/if_media.h>
     57 #include <net/if_types.h>
     58 
     59 #include <net80211/ieee80211_var.h>
     60 #include <net80211/ieee80211_amrr.h>
     61 #include <net80211/ieee80211_radiotap.h>
     62 
     63 #include <netinet/in.h>
     64 #include <netinet/in_systm.h>
     65 #include <netinet/in_var.h>
     66 #include <netinet/ip.h>
     67 
     68 #include <dev/firmload.h>
     69 
     70 #include <dev/pci/if_wpireg.h>
     71 #include <dev/pci/if_wpivar.h>
     72 
     73 #ifdef WPI_DEBUG
     74 #define DPRINTF(x)	if (wpi_debug > 0) printf x
     75 #define DPRINTFN(n, x)	if (wpi_debug >= (n)) printf x
     76 int wpi_debug = 1;
     77 #else
     78 #define DPRINTF(x)
     79 #define DPRINTFN(n, x)
     80 #endif
     81 
     82 /*
     83  * Supported rates for 802.11a/b/g modes (in 500Kbps unit).
     84  */
     85 static const struct ieee80211_rateset wpi_rateset_11a =
     86 	{ 8, { 12, 18, 24, 36, 48, 72, 96, 108 } };
     87 
     88 static const struct ieee80211_rateset wpi_rateset_11b =
     89 	{ 4, { 2, 4, 11, 22 } };
     90 
     91 static const struct ieee80211_rateset wpi_rateset_11g =
     92 	{ 12, { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 } };
     93 
     94 static int  wpi_match(device_t, struct cfdata *, void *);
     95 static void wpi_attach(device_t, device_t, void *);
     96 static int  wpi_detach(device_t , int);
     97 static int  wpi_dma_contig_alloc(bus_dma_tag_t, struct wpi_dma_info *,
     98 	void **, bus_size_t, bus_size_t, int);
     99 static void wpi_dma_contig_free(struct wpi_dma_info *);
    100 static int  wpi_alloc_shared(struct wpi_softc *);
    101 static void wpi_free_shared(struct wpi_softc *);
    102 static int  wpi_alloc_fwmem(struct wpi_softc *);
    103 static void wpi_free_fwmem(struct wpi_softc *);
    104 static struct wpi_rbuf *wpi_alloc_rbuf(struct wpi_softc *);
    105 static void wpi_free_rbuf(struct mbuf *, void *, size_t, void *);
    106 static int  wpi_alloc_rpool(struct wpi_softc *);
    107 static void wpi_free_rpool(struct wpi_softc *);
    108 static int  wpi_alloc_rx_ring(struct wpi_softc *, struct wpi_rx_ring *);
    109 static void wpi_reset_rx_ring(struct wpi_softc *, struct wpi_rx_ring *);
    110 static void wpi_free_rx_ring(struct wpi_softc *, struct wpi_rx_ring *);
    111 static int  wpi_alloc_tx_ring(struct wpi_softc *, struct wpi_tx_ring *, int,
    112 	int);
    113 static void wpi_reset_tx_ring(struct wpi_softc *, struct wpi_tx_ring *);
    114 static void wpi_free_tx_ring(struct wpi_softc *, struct wpi_tx_ring *);
    115 static struct ieee80211_node * wpi_node_alloc(struct ieee80211_node_table *);
    116 static void wpi_newassoc(struct ieee80211_node *, int);
    117 static int  wpi_media_change(struct ifnet *);
    118 static int  wpi_newstate(struct ieee80211com *, enum ieee80211_state, int);
    119 static void	wpi_fix_channel(struct ieee80211com *, struct mbuf *);
    120 static void wpi_mem_lock(struct wpi_softc *);
    121 static void wpi_mem_unlock(struct wpi_softc *);
    122 static uint32_t wpi_mem_read(struct wpi_softc *, uint16_t);
    123 static void wpi_mem_write(struct wpi_softc *, uint16_t, uint32_t);
    124 static void wpi_mem_write_region_4(struct wpi_softc *, uint16_t,
    125 								   const uint32_t *, int);
    126 static int  wpi_read_prom_data(struct wpi_softc *, uint32_t, void *, int);
    127 static int  wpi_load_microcode(struct wpi_softc *,  const uint8_t *, int);
    128 static int  wpi_load_firmware(struct wpi_softc *);
    129 static void wpi_calib_timeout(void *);
    130 static void wpi_iter_func(void *, struct ieee80211_node *);
    131 static void wpi_power_calibration(struct wpi_softc *, int);
    132 static void wpi_rx_intr(struct wpi_softc *, struct wpi_rx_desc *,
    133 	struct wpi_rx_data *);
    134 static void wpi_tx_intr(struct wpi_softc *, struct wpi_rx_desc *);
    135 static void wpi_cmd_intr(struct wpi_softc *, struct wpi_rx_desc *);
    136 static void wpi_notif_intr(struct wpi_softc *);
    137 static int  wpi_intr(void *);
    138 static void wpi_read_eeprom(struct wpi_softc *);
    139 static void wpi_read_eeprom_channels(struct wpi_softc *, int);
    140 static void wpi_read_eeprom_group(struct wpi_softc *, int);
    141 static uint8_t wpi_plcp_signal(int);
    142 static int  wpi_tx_data(struct wpi_softc *, struct mbuf *,
    143 	struct ieee80211_node *, int);
    144 static void wpi_start(struct ifnet *);
    145 static void wpi_watchdog(struct ifnet *);
    146 static int  wpi_ioctl(struct ifnet *, u_long, void *);
    147 static int  wpi_cmd(struct wpi_softc *, int, const void *, int, int);
    148 static int  wpi_wme_update(struct ieee80211com *);
    149 static int  wpi_mrr_setup(struct wpi_softc *);
    150 static void wpi_set_led(struct wpi_softc *, uint8_t, uint8_t, uint8_t);
    151 static void wpi_enable_tsf(struct wpi_softc *, struct ieee80211_node *);
    152 static int  wpi_set_txpower(struct wpi_softc *,
    153 			    struct ieee80211_channel *, int);
    154 static int  wpi_get_power_index(struct wpi_softc *,
    155 		struct wpi_power_group *, struct ieee80211_channel *, int);
    156 static int  wpi_setup_beacon(struct wpi_softc *, struct ieee80211_node *);
    157 static int  wpi_auth(struct wpi_softc *);
    158 static int  wpi_scan(struct wpi_softc *, uint16_t);
    159 static int  wpi_config(struct wpi_softc *);
    160 static void wpi_stop_master(struct wpi_softc *);
    161 static int  wpi_power_up(struct wpi_softc *);
    162 static int  wpi_reset(struct wpi_softc *);
    163 static void wpi_hw_config(struct wpi_softc *);
    164 static int  wpi_init(struct ifnet *);
    165 static void wpi_stop(struct ifnet *, int);
    166 static bool wpi_resume(device_t);
    167 
    168 CFATTACH_DECL_NEW(wpi, sizeof (struct wpi_softc), wpi_match, wpi_attach,
    169 	wpi_detach, NULL);
    170 
    171 static int
    172 wpi_match(device_t parent, struct cfdata *match __unused, void *aux)
    173 {
    174 	struct pci_attach_args *pa = aux;
    175 
    176 	if (PCI_VENDOR(pa->pa_id) != PCI_VENDOR_INTEL)
    177 		return 0;
    178 
    179 	if (PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_INTEL_PRO_WL_3945ABG_1 ||
    180 	    PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_INTEL_PRO_WL_3945ABG_2)
    181 		return 1;
    182 
    183 	return 0;
    184 }
    185 
    186 /* Base Address Register */
    187 #define WPI_PCI_BAR0	0x10
    188 
    189 static void
    190 wpi_attach(device_t parent __unused, device_t self, void *aux)
    191 {
    192 	struct wpi_softc *sc = device_private(self);
    193 	struct ieee80211com *ic = &sc->sc_ic;
    194 	struct ifnet *ifp = &sc->sc_ec.ec_if;
    195 	struct pci_attach_args *pa = aux;
    196 	const char *intrstr;
    197 	char devinfo[256];
    198 	bus_space_tag_t memt;
    199 	bus_space_handle_t memh;
    200 	pci_intr_handle_t ih;
    201 	pcireg_t data;
    202 	int error, ac, revision;
    203 
    204 	sc->sc_pct = pa->pa_pc;
    205 	sc->sc_pcitag = pa->pa_tag;
    206 
    207 	callout_init(&sc->calib_to, 0);
    208 	callout_setfunc(&sc->calib_to, wpi_calib_timeout, sc);
    209 
    210 	pci_devinfo(pa->pa_id, pa->pa_class, 0, devinfo, sizeof devinfo);
    211 	revision = PCI_REVISION(pa->pa_class);
    212 	aprint_normal(": %s (rev. 0x%02x)\n", devinfo, revision);
    213 
    214 	pci_disable_retry(pa->pa_pc, pa->pa_tag);
    215 
    216 	/* enable bus-mastering */
    217 	data = pci_conf_read(sc->sc_pct, sc->sc_pcitag, PCI_COMMAND_STATUS_REG);
    218 	data |= PCI_COMMAND_MASTER_ENABLE;
    219 	pci_conf_write(sc->sc_pct, sc->sc_pcitag, PCI_COMMAND_STATUS_REG, data);
    220 
    221 	/* map the register window */
    222 	error = pci_mapreg_map(pa, WPI_PCI_BAR0, PCI_MAPREG_TYPE_MEM |
    223 		PCI_MAPREG_MEM_TYPE_32BIT, 0, &memt, &memh, NULL, &sc->sc_sz);
    224 	if (error != 0) {
    225 		aprint_error_dev(self, "could not map memory space\n");
    226 		return;
    227 	}
    228 
    229 	sc->sc_st = memt;
    230 	sc->sc_sh = memh;
    231 	sc->sc_dmat = pa->pa_dmat;
    232 
    233 	if (pci_intr_map(pa, &ih) != 0) {
    234 		aprint_error_dev(self, "could not map interrupt\n");
    235 		return;
    236 	}
    237 
    238 	intrstr = pci_intr_string(sc->sc_pct, ih);
    239 	sc->sc_ih = pci_intr_establish(sc->sc_pct, ih, IPL_NET, wpi_intr, sc);
    240 	if (sc->sc_ih == NULL) {
    241 		aprint_error_dev(self, "could not establish interrupt");
    242 		if (intrstr != NULL)
    243 			aprint_error(" at %s", intrstr);
    244 		aprint_error("\n");
    245 		return;
    246 	}
    247 	aprint_normal_dev(self, "interrupting at %s\n", intrstr);
    248 
    249 	if (wpi_reset(sc) != 0) {
    250 		aprint_error_dev(self, "could not reset adapter\n");
    251 		return;
    252 	}
    253 
    254  	/*
    255 	 * Allocate DMA memory for firmware transfers.
    256 	 */
    257 	if ((error = wpi_alloc_fwmem(sc)) != 0) {
    258 		aprint_error("could not allocate firmware memory\n");
    259 		return;
    260 	}
    261 
    262 	/*
    263 	 * Allocate shared page and Tx/Rx rings.
    264 	 */
    265 	if ((error = wpi_alloc_shared(sc)) != 0) {
    266 		aprint_error_dev(self, "could not allocate shared area\n");
    267 		goto fail1;
    268 	}
    269 
    270 	if ((error = wpi_alloc_rpool(sc)) != 0) {
    271 		aprint_error_dev(self, "could not allocate Rx buffers\n");
    272 		goto fail2;
    273 	}
    274 
    275 	for (ac = 0; ac < 4; ac++) {
    276 		error = wpi_alloc_tx_ring(sc, &sc->txq[ac], WPI_TX_RING_COUNT, ac);
    277 		if (error != 0) {
    278 			aprint_error_dev(self, "could not allocate Tx ring %d\n", ac);
    279 			goto fail3;
    280 		}
    281 	}
    282 
    283 	error = wpi_alloc_tx_ring(sc, &sc->cmdq, WPI_CMD_RING_COUNT, 4);
    284 	if (error != 0) {
    285 		aprint_error_dev(self, "could not allocate command ring\n");
    286 		goto fail3;
    287 	}
    288 
    289 	if (wpi_alloc_rx_ring(sc, &sc->rxq) != 0) {
    290 		aprint_error_dev(self, "could not allocate Rx ring\n");
    291 		goto fail4;
    292 	}
    293 
    294 	ic->ic_ifp = ifp;
    295 	ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
    296 	ic->ic_opmode = IEEE80211_M_STA; /* default to BSS mode */
    297 	ic->ic_state = IEEE80211_S_INIT;
    298 
    299 	/* set device capabilities */
    300 	ic->ic_caps =
    301 		IEEE80211_C_IBSS |       /* IBSS mode support */
    302 		IEEE80211_C_WPA |        /* 802.11i */
    303 		IEEE80211_C_MONITOR |    /* monitor mode supported */
    304 		IEEE80211_C_TXPMGT |     /* tx power management */
    305 		IEEE80211_C_SHSLOT |     /* short slot time supported */
    306 		IEEE80211_C_SHPREAMBLE | /* short preamble supported */
    307 		IEEE80211_C_WME;         /* 802.11e */
    308 
    309 	/* read supported channels and MAC address from EEPROM */
    310 	wpi_read_eeprom(sc);
    311 
    312 	/* set supported .11a, .11b, .11g rates */
    313 	ic->ic_sup_rates[IEEE80211_MODE_11A] = wpi_rateset_11a;
    314 	ic->ic_sup_rates[IEEE80211_MODE_11B] = wpi_rateset_11b;
    315 	ic->ic_sup_rates[IEEE80211_MODE_11G] = wpi_rateset_11g;
    316 
    317 	ic->ic_ibss_chan = &ic->ic_channels[0];
    318 
    319 	ifp->if_softc = sc;
    320 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
    321 	ifp->if_init = wpi_init;
    322 	ifp->if_stop = wpi_stop;
    323 	ifp->if_ioctl = wpi_ioctl;
    324 	ifp->if_start = wpi_start;
    325 	ifp->if_watchdog = wpi_watchdog;
    326 	IFQ_SET_READY(&ifp->if_snd);
    327 	memcpy(ifp->if_xname, device_xname(self), IFNAMSIZ);
    328 
    329 	if_attach(ifp);
    330 	ieee80211_ifattach(ic);
    331 	/* override default methods */
    332 	ic->ic_node_alloc = wpi_node_alloc;
    333 	ic->ic_newassoc = wpi_newassoc;
    334 	ic->ic_wme.wme_update = wpi_wme_update;
    335 
    336 	/* override state transition machine */
    337 	sc->sc_newstate = ic->ic_newstate;
    338 	ic->ic_newstate = wpi_newstate;
    339 	ieee80211_media_init(ic, wpi_media_change, ieee80211_media_status);
    340 
    341 	sc->amrr.amrr_min_success_threshold = 1;
    342 	sc->amrr.amrr_max_success_threshold = 15;
    343 
    344 	if (!pnp_device_register(self, NULL, wpi_resume))
    345 		aprint_error_dev(self, "couldn't establish power handler\n");
    346 	else
    347 		pnp_class_network_register(self, ifp);
    348 
    349 #if NBPFILTER > 0
    350 	bpfattach2(ifp, DLT_IEEE802_11_RADIO,
    351 		sizeof (struct ieee80211_frame) + IEEE80211_RADIOTAP_HDRLEN,
    352 		&sc->sc_drvbpf);
    353 
    354 	sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
    355 	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
    356 	sc->sc_rxtap.wr_ihdr.it_present = htole32(WPI_RX_RADIOTAP_PRESENT);
    357 
    358 	sc->sc_txtap_len = sizeof sc->sc_txtapu;
    359 	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
    360 	sc->sc_txtap.wt_ihdr.it_present = htole32(WPI_TX_RADIOTAP_PRESENT);
    361 #endif
    362 
    363 	ieee80211_announce(ic);
    364 
    365 	return;
    366 
    367 fail4:  wpi_free_tx_ring(sc, &sc->cmdq);
    368 fail3:  while (--ac >= 0)
    369 			wpi_free_tx_ring(sc, &sc->txq[ac]);
    370 	wpi_free_rpool(sc);
    371 fail2:	wpi_free_shared(sc);
    372 fail1:	wpi_free_fwmem(sc);
    373 }
    374 
    375 static int
    376 wpi_detach(device_t self, int flags __unused)
    377 {
    378 	struct wpi_softc *sc = device_private(self);
    379 	struct ifnet *ifp = sc->sc_ic.ic_ifp;
    380 	int ac;
    381 
    382 	wpi_stop(ifp, 1);
    383 
    384 #if NBPFILTER > 0
    385 	if (ifp != NULL)
    386 		bpfdetach(ifp);
    387 #endif
    388 	ieee80211_ifdetach(&sc->sc_ic);
    389 	if (ifp != NULL)
    390 		if_detach(ifp);
    391 
    392 	for (ac = 0; ac < 4; ac++)
    393 		wpi_free_tx_ring(sc, &sc->txq[ac]);
    394 	wpi_free_tx_ring(sc, &sc->cmdq);
    395 	wpi_free_rx_ring(sc, &sc->rxq);
    396 	wpi_free_rpool(sc);
    397 	wpi_free_shared(sc);
    398 
    399 	if (sc->sc_ih != NULL) {
    400 		pci_intr_disestablish(sc->sc_pct, sc->sc_ih);
    401 		sc->sc_ih = NULL;
    402 	}
    403 
    404 	bus_space_unmap(sc->sc_st, sc->sc_sh, sc->sc_sz);
    405 
    406 	return 0;
    407 }
    408 
    409 static int
    410 wpi_dma_contig_alloc(bus_dma_tag_t tag, struct wpi_dma_info *dma,
    411 	void **kvap, bus_size_t size, bus_size_t alignment, int flags)
    412 {
    413 	int nsegs, error;
    414 
    415 	dma->tag = tag;
    416 	dma->size = size;
    417 
    418 	error = bus_dmamap_create(tag, size, 1, size, 0, flags, &dma->map);
    419 	if (error != 0)
    420 		goto fail;
    421 
    422 	error = bus_dmamem_alloc(tag, size, alignment, 0, &dma->seg, 1, &nsegs,
    423 	    flags);
    424 	if (error != 0)
    425 		goto fail;
    426 
    427 	error = bus_dmamem_map(tag, &dma->seg, 1, size, &dma->vaddr, flags);
    428 	if (error != 0)
    429 		goto fail;
    430 
    431 	error = bus_dmamap_load(tag, dma->map, dma->vaddr, size, NULL, flags);
    432 	if (error != 0)
    433 		goto fail;
    434 
    435 	memset(dma->vaddr, 0, size);
    436 
    437 	dma->paddr = dma->map->dm_segs[0].ds_addr;
    438 	if (kvap != NULL)
    439 		*kvap = dma->vaddr;
    440 
    441 	return 0;
    442 
    443 fail:   wpi_dma_contig_free(dma);
    444 	return error;
    445 }
    446 
    447 static void
    448 wpi_dma_contig_free(struct wpi_dma_info *dma)
    449 {
    450 	if (dma->map != NULL) {
    451 		if (dma->vaddr != NULL) {
    452 			bus_dmamap_unload(dma->tag, dma->map);
    453 			bus_dmamem_unmap(dma->tag, dma->vaddr, dma->size);
    454 			bus_dmamem_free(dma->tag, &dma->seg, 1);
    455 			dma->vaddr = NULL;
    456 		}
    457 		bus_dmamap_destroy(dma->tag, dma->map);
    458 		dma->map = NULL;
    459 	}
    460 }
    461 
    462 /*
    463  * Allocate a shared page between host and NIC.
    464  */
    465 static int
    466 wpi_alloc_shared(struct wpi_softc *sc)
    467 {
    468 	int error;
    469 	/* must be aligned on a 4K-page boundary */
    470 	error = wpi_dma_contig_alloc(sc->sc_dmat, &sc->shared_dma,
    471 			(void **)&sc->shared, sizeof (struct wpi_shared),
    472 			WPI_BUF_ALIGN,BUS_DMA_NOWAIT);
    473 	if (error != 0)
    474 		aprint_error_dev(sc->sc_dev,
    475 				"could not allocate shared area DMA memory\n");
    476 
    477 	return error;
    478 }
    479 
    480 static void
    481 wpi_free_shared(struct wpi_softc *sc)
    482 {
    483 	wpi_dma_contig_free(&sc->shared_dma);
    484 }
    485 
    486 /*
    487  * Allocate DMA-safe memory for firmware transfer.
    488  */
    489 static int
    490 wpi_alloc_fwmem(struct wpi_softc *sc)
    491 {
    492 	int error;
    493 	/* allocate enough contiguous space to store text and data */
    494 	error = wpi_dma_contig_alloc(sc->sc_dmat, &sc->fw_dma, NULL,
    495 	    WPI_FW_MAIN_TEXT_MAXSZ + WPI_FW_MAIN_DATA_MAXSZ, 0,
    496 	    BUS_DMA_NOWAIT);
    497 
    498 	if (error != 0)
    499 		aprint_error_dev(sc->sc_dev,
    500 			"could not allocate firmware transfer area"
    501 			"DMA memory\n");
    502 	return error;
    503 }
    504 
    505 static void
    506 wpi_free_fwmem(struct wpi_softc *sc)
    507 {
    508 	wpi_dma_contig_free(&sc->fw_dma);
    509 }
    510 
    511 
    512 static struct wpi_rbuf *
    513 wpi_alloc_rbuf(struct wpi_softc *sc)
    514 {
    515 	struct wpi_rbuf *rbuf;
    516 
    517 	rbuf = SLIST_FIRST(&sc->rxq.freelist);
    518 	if (rbuf == NULL)
    519 		return NULL;
    520 	SLIST_REMOVE_HEAD(&sc->rxq.freelist, next);
    521 	sc->rxq.nb_free_entries --;
    522 
    523 	return rbuf;
    524 }
    525 
    526 /*
    527  * This is called automatically by the network stack when the mbuf to which our
    528  * Rx buffer is attached is freed.
    529  */
    530 static void
    531 wpi_free_rbuf(struct mbuf* m, void *buf, size_t size, void *arg)
    532 {
    533 	struct wpi_rbuf *rbuf = arg;
    534 	struct wpi_softc *sc = rbuf->sc;
    535 
    536 	/* put the buffer back in the free list */
    537 
    538 	SLIST_INSERT_HEAD(&sc->rxq.freelist, rbuf, next);
    539 	sc->rxq.nb_free_entries ++;
    540 
    541 	if (__predict_true(m != NULL))
    542 		pool_cache_put(mb_cache, m);
    543 }
    544 
    545 static int
    546 wpi_alloc_rpool(struct wpi_softc *sc)
    547 {
    548 	struct wpi_rx_ring *ring = &sc->rxq;
    549 	struct wpi_rbuf *rbuf;
    550 	int i, error;
    551 
    552 	/* allocate a big chunk of DMA'able memory.. */
    553 	error = wpi_dma_contig_alloc(sc->sc_dmat, &ring->buf_dma, NULL,
    554 	    WPI_RBUF_COUNT * WPI_RBUF_SIZE, WPI_BUF_ALIGN, BUS_DMA_NOWAIT);
    555 	if (error != 0) {
    556 		aprint_normal_dev(sc->sc_dev,
    557 						  "could not allocate Rx buffers DMA memory\n");
    558 		return error;
    559 	}
    560 
    561 	/* ..and split it into 3KB chunks */
    562 	SLIST_INIT(&ring->freelist);
    563 	for (i = 0; i < WPI_RBUF_COUNT; i++) {
    564 		rbuf = &ring->rbuf[i];
    565 		rbuf->sc = sc;	/* backpointer for callbacks */
    566 		rbuf->vaddr = (char *)ring->buf_dma.vaddr + i * WPI_RBUF_SIZE;
    567 		rbuf->paddr = ring->buf_dma.paddr + i * WPI_RBUF_SIZE;
    568 
    569 		SLIST_INSERT_HEAD(&ring->freelist, rbuf, next);
    570 	}
    571 
    572 	ring->nb_free_entries = WPI_RBUF_COUNT;
    573 	return 0;
    574 }
    575 
    576 static void
    577 wpi_free_rpool(struct wpi_softc *sc)
    578 {
    579 	wpi_dma_contig_free(&sc->rxq.buf_dma);
    580 }
    581 
    582 static int
    583 wpi_alloc_rx_ring(struct wpi_softc *sc, struct wpi_rx_ring *ring)
    584 {
    585 	struct wpi_rx_data *data;
    586 	struct wpi_rbuf *rbuf;
    587 	int i, error;
    588 
    589 	ring->cur = 0;
    590 
    591 	error = wpi_dma_contig_alloc(sc->sc_dmat, &ring->desc_dma,
    592 		(void **)&ring->desc,
    593 		WPI_RX_RING_COUNT * sizeof (struct wpi_rx_desc),
    594 		WPI_RING_DMA_ALIGN, BUS_DMA_NOWAIT);
    595 	if (error != 0) {
    596 		aprint_error_dev(sc->sc_dev, "could not allocate rx ring DMA memory\n");
    597 		goto fail;
    598 	}
    599 
    600 	/*
    601 	 * Setup Rx buffers.
    602 	 */
    603 	for (i = 0; i < WPI_RX_RING_COUNT; i++) {
    604 		data = &ring->data[i];
    605 
    606 		MGETHDR(data->m, M_DONTWAIT, MT_DATA);
    607 		if (data->m == NULL) {
    608 			aprint_error_dev(sc->sc_dev, "could not allocate rx mbuf\n");
    609 			error = ENOMEM;
    610 			goto fail;
    611 		}
    612 		if ((rbuf = wpi_alloc_rbuf(sc)) == NULL) {
    613 			m_freem(data->m);
    614 			data->m = NULL;
    615 			aprint_error_dev(sc->sc_dev, "could not allocate rx cluster\n");
    616 			error = ENOMEM;
    617 			goto fail;
    618 		}
    619 		/* attach Rx buffer to mbuf */
    620 		MEXTADD(data->m, rbuf->vaddr, WPI_RBUF_SIZE, 0, wpi_free_rbuf,
    621 		    rbuf);
    622 		data->m->m_flags |= M_EXT_RW;
    623 
    624 		ring->desc[i] = htole32(rbuf->paddr);
    625 	}
    626 
    627 	return 0;
    628 
    629 fail:	wpi_free_rx_ring(sc, ring);
    630 	return error;
    631 }
    632 
    633 static void
    634 wpi_reset_rx_ring(struct wpi_softc *sc, struct wpi_rx_ring *ring)
    635 {
    636 	int ntries;
    637 
    638 	wpi_mem_lock(sc);
    639 
    640 	WPI_WRITE(sc, WPI_RX_CONFIG, 0);
    641 	for (ntries = 0; ntries < 100; ntries++) {
    642 		if (WPI_READ(sc, WPI_RX_STATUS) & WPI_RX_IDLE)
    643 			break;
    644 		DELAY(10);
    645 	}
    646 #ifdef WPI_DEBUG
    647 	if (ntries == 100 && wpi_debug > 0)
    648 		aprint_error_dev(sc->sc_dev, "timeout resetting Rx ring\n");
    649 #endif
    650 	wpi_mem_unlock(sc);
    651 
    652 	ring->cur = 0;
    653 }
    654 
    655 static void
    656 wpi_free_rx_ring(struct wpi_softc *sc, struct wpi_rx_ring *ring)
    657 {
    658 	int i;
    659 
    660 	wpi_dma_contig_free(&ring->desc_dma);
    661 
    662 	for (i = 0; i < WPI_RX_RING_COUNT; i++) {
    663 		if (ring->data[i].m != NULL)
    664 			m_freem(ring->data[i].m);
    665 	}
    666 }
    667 
    668 static int
    669 wpi_alloc_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring, int count,
    670 	int qid)
    671 {
    672 	struct wpi_tx_data *data;
    673 	int i, error;
    674 
    675 	ring->qid = qid;
    676 	ring->count = count;
    677 	ring->queued = 0;
    678 	ring->cur = 0;
    679 
    680 	error = wpi_dma_contig_alloc(sc->sc_dmat, &ring->desc_dma,
    681 		(void **)&ring->desc, count * sizeof (struct wpi_tx_desc),
    682 		WPI_RING_DMA_ALIGN, BUS_DMA_NOWAIT);
    683 	if (error != 0) {
    684 		aprint_error_dev(sc->sc_dev, "could not allocate tx ring DMA memory\n");
    685 		goto fail;
    686 	}
    687 
    688 	/* update shared page with ring's base address */
    689 	sc->shared->txbase[qid] = htole32(ring->desc_dma.paddr);
    690 
    691 	error = wpi_dma_contig_alloc(sc->sc_dmat, &ring->cmd_dma,
    692 		(void **)&ring->cmd,
    693 		count * sizeof (struct wpi_tx_cmd), 4, BUS_DMA_NOWAIT);
    694 	if (error != 0) {
    695 		aprint_error_dev(sc->sc_dev, "could not allocate tx cmd DMA memory\n");
    696 		goto fail;
    697 	}
    698 
    699 	ring->data = malloc(count * sizeof (struct wpi_tx_data), M_DEVBUF,
    700 		M_NOWAIT);
    701 	if (ring->data == NULL) {
    702 		aprint_error_dev(sc->sc_dev, "could not allocate tx data slots\n");
    703 		goto fail;
    704 	}
    705 
    706 	memset(ring->data, 0, count * sizeof (struct wpi_tx_data));
    707 
    708 	for (i = 0; i < count; i++) {
    709 		data = &ring->data[i];
    710 
    711 		error = bus_dmamap_create(sc->sc_dmat, MCLBYTES,
    712 			WPI_MAX_SCATTER - 1, MCLBYTES, 0, BUS_DMA_NOWAIT,
    713 			&data->map);
    714 		if (error != 0) {
    715 			aprint_error_dev(sc->sc_dev, "could not create tx buf DMA map\n");
    716 			goto fail;
    717 		}
    718 	}
    719 
    720 	return 0;
    721 
    722 fail:	wpi_free_tx_ring(sc, ring);
    723 	return error;
    724 }
    725 
    726 static void
    727 wpi_reset_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring)
    728 {
    729 	struct wpi_tx_data *data;
    730 	int i, ntries;
    731 
    732 	wpi_mem_lock(sc);
    733 
    734 	WPI_WRITE(sc, WPI_TX_CONFIG(ring->qid), 0);
    735 	for (ntries = 0; ntries < 100; ntries++) {
    736 		if (WPI_READ(sc, WPI_TX_STATUS) & WPI_TX_IDLE(ring->qid))
    737 			break;
    738 		DELAY(10);
    739 	}
    740 #ifdef WPI_DEBUG
    741 	if (ntries == 100 && wpi_debug > 0) {
    742 		aprint_error_dev(sc->sc_dev, "timeout resetting Tx ring %d\n",
    743 									   ring->qid);
    744 	}
    745 #endif
    746 	wpi_mem_unlock(sc);
    747 
    748 	for (i = 0; i < ring->count; i++) {
    749 		data = &ring->data[i];
    750 
    751 		if (data->m != NULL) {
    752 			bus_dmamap_unload(sc->sc_dmat, data->map);
    753 			m_freem(data->m);
    754 			data->m = NULL;
    755 		}
    756 	}
    757 
    758 	ring->queued = 0;
    759 	ring->cur = 0;
    760 }
    761 
    762 static void
    763 wpi_free_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring)
    764 {
    765 	struct wpi_tx_data *data;
    766 	int i;
    767 
    768 	wpi_dma_contig_free(&ring->desc_dma);
    769 	wpi_dma_contig_free(&ring->cmd_dma);
    770 
    771 	if (ring->data != NULL) {
    772 		for (i = 0; i < ring->count; i++) {
    773 			data = &ring->data[i];
    774 
    775 			if (data->m != NULL) {
    776 				bus_dmamap_unload(sc->sc_dmat, data->map);
    777 				m_freem(data->m);
    778 			}
    779 		}
    780 		free(ring->data, M_DEVBUF);
    781 	}
    782 }
    783 
    784 /*ARGUSED*/
    785 static struct ieee80211_node *
    786 wpi_node_alloc(struct ieee80211_node_table *nt __unused)
    787 {
    788 	struct wpi_node *wn;
    789 
    790 	wn = malloc(sizeof (struct wpi_node), M_DEVBUF, M_NOWAIT);
    791 
    792 	if (wn != NULL)
    793 		memset(wn, 0, sizeof (struct wpi_node));
    794 	return (struct ieee80211_node *)wn;
    795 }
    796 
    797 static void
    798 wpi_newassoc(struct ieee80211_node *ni, int isnew)
    799 {
    800 	struct wpi_softc *sc = ni->ni_ic->ic_ifp->if_softc;
    801 	int i;
    802 
    803 	ieee80211_amrr_node_init(&sc->amrr, &((struct wpi_node *)ni)->amn);
    804 
    805 	/* set rate to some reasonable initial value */
    806 	for (i = ni->ni_rates.rs_nrates - 1;
    807 	     i > 0 && (ni->ni_rates.rs_rates[i] & IEEE80211_RATE_VAL) > 72;
    808 	     i--);
    809 	ni->ni_txrate = i;
    810 }
    811 
    812 static int
    813 wpi_media_change(struct ifnet *ifp)
    814 {
    815 	int error;
    816 
    817 	error = ieee80211_media_change(ifp);
    818 	if (error != ENETRESET)
    819 		return error;
    820 
    821 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
    822 		wpi_init(ifp);
    823 
    824 	return 0;
    825 }
    826 
    827 static int
    828 wpi_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
    829 {
    830 	struct ifnet *ifp = ic->ic_ifp;
    831 	struct wpi_softc *sc = ifp->if_softc;
    832 	struct ieee80211_node *ni;
    833 	int error;
    834 
    835 	callout_stop(&sc->calib_to);
    836 
    837 	switch (nstate) {
    838 	case IEEE80211_S_SCAN:
    839 
    840 		if (sc->is_scanning)
    841 			break;
    842 
    843 		sc->is_scanning = true;
    844 		ieee80211_node_table_reset(&ic->ic_scan);
    845 		ic->ic_flags |= IEEE80211_F_SCAN | IEEE80211_F_ASCAN;
    846 
    847 		/* make the link LED blink while we're scanning */
    848 		wpi_set_led(sc, WPI_LED_LINK, 20, 2);
    849 
    850 		if ((error = wpi_scan(sc, IEEE80211_CHAN_G)) != 0) {
    851 			aprint_error_dev(sc->sc_dev, "could not initiate scan\n");
    852 			ic->ic_flags &= ~(IEEE80211_F_SCAN | IEEE80211_F_ASCAN);
    853 			return error;
    854 		}
    855 
    856 		ic->ic_state = nstate;
    857 		return 0;
    858 
    859 	case IEEE80211_S_ASSOC:
    860 		if (ic->ic_state != IEEE80211_S_RUN)
    861 			break;
    862 		/* FALLTHROUGH */
    863 	case IEEE80211_S_AUTH:
    864 		sc->config.associd = 0;
    865 		sc->config.filter &= ~htole32(WPI_FILTER_BSS);
    866 		if ((error = wpi_auth(sc)) != 0) {
    867 			aprint_error_dev(sc->sc_dev,
    868 							"could not send authentication request\n");
    869 			return error;
    870 		}
    871 		break;
    872 
    873 	case IEEE80211_S_RUN:
    874 		if (ic->ic_opmode == IEEE80211_M_MONITOR) {
    875 			/* link LED blinks while monitoring */
    876 			wpi_set_led(sc, WPI_LED_LINK, 5, 5);
    877 			break;
    878 		}
    879 
    880 		ni = ic->ic_bss;
    881 
    882 		if (ic->ic_opmode != IEEE80211_M_STA) {
    883 			(void) wpi_auth(sc);    /* XXX */
    884 			wpi_setup_beacon(sc, ni);
    885 		}
    886 
    887 		wpi_enable_tsf(sc, ni);
    888 
    889 		/* update adapter's configuration */
    890 		sc->config.associd = htole16(ni->ni_associd & ~0xc000);
    891 		/* short preamble/slot time are negotiated when associating */
    892 		sc->config.flags &= ~htole32(WPI_CONFIG_SHPREAMBLE |
    893 			WPI_CONFIG_SHSLOT);
    894 		if (ic->ic_flags & IEEE80211_F_SHSLOT)
    895 			sc->config.flags |= htole32(WPI_CONFIG_SHSLOT);
    896 		if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
    897 			sc->config.flags |= htole32(WPI_CONFIG_SHPREAMBLE);
    898 		sc->config.filter |= htole32(WPI_FILTER_BSS);
    899 		if (ic->ic_opmode != IEEE80211_M_STA)
    900 			sc->config.filter |= htole32(WPI_FILTER_BEACON);
    901 
    902 /* XXX put somewhere HC_QOS_SUPPORT_ASSOC + HC_IBSS_START */
    903 
    904 		DPRINTF(("config chan %d flags %x\n", sc->config.chan,
    905 			sc->config.flags));
    906 		error = wpi_cmd(sc, WPI_CMD_CONFIGURE, &sc->config,
    907 			sizeof (struct wpi_config), 1);
    908 		if (error != 0) {
    909 			aprint_error_dev(sc->sc_dev, "could not update configuration\n");
    910 			return error;
    911 		}
    912 
    913 		/* configuration has changed, set Tx power accordingly */
    914 		if ((error = wpi_set_txpower(sc, ni->ni_chan, 1)) != 0) {
    915 			aprint_error_dev(sc->sc_dev, "could not set Tx power\n");
    916 			return error;
    917 		}
    918 
    919 		if (ic->ic_opmode == IEEE80211_M_STA) {
    920 			/* fake a join to init the tx rate */
    921 			wpi_newassoc(ni, 1);
    922 		}
    923 
    924 		/* start periodic calibration timer */
    925 		sc->calib_cnt = 0;
    926 		callout_schedule(&sc->calib_to, hz/2);
    927 
    928 		/* link LED always on while associated */
    929 		wpi_set_led(sc, WPI_LED_LINK, 0, 1);
    930 		break;
    931 
    932 	case IEEE80211_S_INIT:
    933 		sc->is_scanning = false;
    934 		break;
    935 	}
    936 
    937 	return sc->sc_newstate(ic, nstate, arg);
    938 }
    939 
    940 /*
    941  * XXX: Hack to set the current channel to the value advertised in beacons or
    942  * probe responses. Only used during AP detection.
    943  * XXX: Duplicated from if_iwi.c
    944  */
    945 static void
    946 wpi_fix_channel(struct ieee80211com *ic, struct mbuf *m)
    947 {
    948 	struct ieee80211_frame *wh;
    949 	uint8_t subtype;
    950 	uint8_t *frm, *efrm;
    951 
    952 	wh = mtod(m, struct ieee80211_frame *);
    953 
    954 	if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_MGT)
    955 		return;
    956 
    957 	subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
    958 
    959 	if (subtype != IEEE80211_FC0_SUBTYPE_BEACON &&
    960 	    subtype != IEEE80211_FC0_SUBTYPE_PROBE_RESP)
    961 		return;
    962 
    963 	frm = (uint8_t *)(wh + 1);
    964 	efrm = mtod(m, uint8_t *) + m->m_len;
    965 
    966 	frm += 12;	/* skip tstamp, bintval and capinfo fields */
    967 	while (frm < efrm) {
    968 		if (*frm == IEEE80211_ELEMID_DSPARMS)
    969 #if IEEE80211_CHAN_MAX < 255
    970 		if (frm[2] <= IEEE80211_CHAN_MAX)
    971 #endif
    972 			ic->ic_curchan = &ic->ic_channels[frm[2]];
    973 
    974 		frm += frm[1] + 2;
    975 	}
    976 }
    977 
    978 /*
    979  * Grab exclusive access to NIC memory.
    980  */
    981 static void
    982 wpi_mem_lock(struct wpi_softc *sc)
    983 {
    984 	uint32_t tmp;
    985 	int ntries;
    986 
    987 	tmp = WPI_READ(sc, WPI_GPIO_CTL);
    988 	WPI_WRITE(sc, WPI_GPIO_CTL, tmp | WPI_GPIO_MAC);
    989 
    990 	/* spin until we actually get the lock */
    991 	for (ntries = 0; ntries < 1000; ntries++) {
    992 		if ((WPI_READ(sc, WPI_GPIO_CTL) &
    993 			(WPI_GPIO_CLOCK | WPI_GPIO_SLEEP)) == WPI_GPIO_CLOCK)
    994 			break;
    995 		DELAY(10);
    996 	}
    997 	if (ntries == 1000)
    998 		aprint_error_dev(sc->sc_dev, "could not lock memory\n");
    999 }
   1000 
   1001 /*
   1002  * Release lock on NIC memory.
   1003  */
   1004 static void
   1005 wpi_mem_unlock(struct wpi_softc *sc)
   1006 {
   1007 	uint32_t tmp = WPI_READ(sc, WPI_GPIO_CTL);
   1008 	WPI_WRITE(sc, WPI_GPIO_CTL, tmp & ~WPI_GPIO_MAC);
   1009 }
   1010 
   1011 static uint32_t
   1012 wpi_mem_read(struct wpi_softc *sc, uint16_t addr)
   1013 {
   1014 	WPI_WRITE(sc, WPI_READ_MEM_ADDR, WPI_MEM_4 | addr);
   1015 	return WPI_READ(sc, WPI_READ_MEM_DATA);
   1016 }
   1017 
   1018 static void
   1019 wpi_mem_write(struct wpi_softc *sc, uint16_t addr, uint32_t data)
   1020 {
   1021 	WPI_WRITE(sc, WPI_WRITE_MEM_ADDR, WPI_MEM_4 | addr);
   1022 	WPI_WRITE(sc, WPI_WRITE_MEM_DATA, data);
   1023 }
   1024 
   1025 static void
   1026 wpi_mem_write_region_4(struct wpi_softc *sc, uint16_t addr,
   1027 						const uint32_t *data, int wlen)
   1028 {
   1029 	for (; wlen > 0; wlen--, data++, addr += 4)
   1030 		wpi_mem_write(sc, addr, *data);
   1031 }
   1032 
   1033 
   1034 /*
   1035  * Read `len' bytes from the EEPROM.  We access the EEPROM through the MAC
   1036  * instead of using the traditional bit-bang method.
   1037  */
   1038 static int
   1039 wpi_read_prom_data(struct wpi_softc *sc, uint32_t addr, void *data, int len)
   1040 {
   1041 	uint8_t *out = data;
   1042 	uint32_t val;
   1043 	int ntries;
   1044 
   1045 	wpi_mem_lock(sc);
   1046 	for (; len > 0; len -= 2, addr++) {
   1047 		WPI_WRITE(sc, WPI_EEPROM_CTL, addr << 2);
   1048 
   1049 		for (ntries = 0; ntries < 10; ntries++) {
   1050 			if ((val = WPI_READ(sc, WPI_EEPROM_CTL)) &
   1051 			    WPI_EEPROM_READY)
   1052 				break;
   1053 			DELAY(5);
   1054 		}
   1055 		if (ntries == 10) {
   1056 			aprint_error_dev(sc->sc_dev, "could not read EEPROM\n");
   1057 			return ETIMEDOUT;
   1058 		}
   1059 		*out++ = val >> 16;
   1060 		if (len > 1)
   1061 			*out++ = val >> 24;
   1062 	}
   1063 	wpi_mem_unlock(sc);
   1064 
   1065 	return 0;
   1066 }
   1067 
   1068 /*
   1069  * The firmware boot code is small and is intended to be copied directly into
   1070  * the NIC internal memory.
   1071  */
   1072 int
   1073 wpi_load_microcode(struct wpi_softc *sc, const uint8_t *ucode, int size)
   1074 {
   1075 	int ntries;
   1076 
   1077 	size /= sizeof (uint32_t);
   1078 
   1079 	wpi_mem_lock(sc);
   1080 
   1081 	/* copy microcode image into NIC memory */
   1082 	wpi_mem_write_region_4(sc, WPI_MEM_UCODE_BASE,
   1083 	    (const uint32_t *)ucode, size);
   1084 
   1085 	wpi_mem_write(sc, WPI_MEM_UCODE_SRC, 0);
   1086 	wpi_mem_write(sc, WPI_MEM_UCODE_DST, WPI_FW_TEXT);
   1087 	wpi_mem_write(sc, WPI_MEM_UCODE_SIZE, size);
   1088 
   1089 	/* run microcode */
   1090 	wpi_mem_write(sc, WPI_MEM_UCODE_CTL, WPI_UC_RUN);
   1091 
   1092 	/* wait for transfer to complete */
   1093 	for (ntries = 0; ntries < 1000; ntries++) {
   1094 		if (!(wpi_mem_read(sc, WPI_MEM_UCODE_CTL) & WPI_UC_RUN))
   1095 			break;
   1096 		DELAY(10);
   1097 	}
   1098 	if (ntries == 1000) {
   1099 		wpi_mem_unlock(sc);
   1100 		aprint_error_dev(sc->sc_dev, "could not load boot firmware\n");
   1101 		return ETIMEDOUT;
   1102 	}
   1103 	wpi_mem_write(sc, WPI_MEM_UCODE_CTL, WPI_UC_ENABLE);
   1104 
   1105 	wpi_mem_unlock(sc);
   1106 
   1107 	return 0;
   1108 }
   1109 
   1110 static int
   1111 wpi_load_firmware(struct wpi_softc *sc)
   1112 {
   1113 	struct wpi_dma_info *dma = &sc->fw_dma;
   1114 	struct wpi_firmware_hdr hdr;
   1115 	const uint8_t *init_text, *init_data, *main_text, *main_data;
   1116 	const uint8_t *boot_text;
   1117 	uint32_t init_textsz, init_datasz, main_textsz, main_datasz;
   1118 	uint32_t boot_textsz;
   1119 	firmware_handle_t fw;
   1120 	u_char *dfw;
   1121 	size_t size;
   1122 	int error;
   1123 
   1124 	/* load firmware image from disk */
   1125 	if ((error = firmware_open("if_wpi","iwlwifi-3945.ucode", &fw) != 0)) {
   1126 		aprint_error_dev(sc->sc_dev, "could not read firmware file\n");
   1127 		goto fail1;
   1128 	}
   1129 
   1130 	size = firmware_get_size(fw);
   1131 
   1132 	/* extract firmware header information */
   1133 	if (size < sizeof (struct wpi_firmware_hdr)) {
   1134 		aprint_error_dev(sc->sc_dev, "truncated firmware header: %zu bytes\n",
   1135 		    			 size);
   1136 		error = EINVAL;
   1137 		goto fail2;
   1138 	}
   1139 
   1140 	if ((error = firmware_read(fw, 0, &hdr,
   1141 		sizeof (struct wpi_firmware_hdr))) != 0) {
   1142 		aprint_error_dev(sc->sc_dev, "can't get firmware header\n");
   1143 		goto fail2;
   1144 	}
   1145 
   1146 	main_textsz = le32toh(hdr.main_textsz);
   1147 	main_datasz = le32toh(hdr.main_datasz);
   1148 	init_textsz = le32toh(hdr.init_textsz);
   1149 	init_datasz = le32toh(hdr.init_datasz);
   1150 	boot_textsz = le32toh(hdr.boot_textsz);
   1151 
   1152 	/* sanity-check firmware segments sizes */
   1153 	if (main_textsz > WPI_FW_MAIN_TEXT_MAXSZ ||
   1154 	    main_datasz > WPI_FW_MAIN_DATA_MAXSZ ||
   1155 	    init_textsz > WPI_FW_INIT_TEXT_MAXSZ ||
   1156 	    init_datasz > WPI_FW_INIT_DATA_MAXSZ ||
   1157 	    boot_textsz > WPI_FW_BOOT_TEXT_MAXSZ ||
   1158 	    (boot_textsz & 3) != 0) {
   1159 		aprint_error_dev(sc->sc_dev, "invalid firmware header\n");
   1160 		error = EINVAL;
   1161 		goto fail2;
   1162 	}
   1163 
   1164 	/* check that all firmware segments are present */
   1165 	if (size < sizeof (struct wpi_firmware_hdr) + main_textsz +
   1166 		main_datasz + init_textsz + init_datasz + boot_textsz) {
   1167 		aprint_error_dev(sc->sc_dev, "firmware file too short: %zu bytes\n",
   1168 		    			 size);
   1169 		error = EINVAL;
   1170 		goto fail2;
   1171 	}
   1172 
   1173 	dfw = firmware_malloc(size);
   1174 	if (dfw == NULL) {
   1175 		aprint_error_dev(sc->sc_dev, "not enough memory to stock firmware\n");
   1176 		error = ENOMEM;
   1177 		goto fail2;
   1178 	}
   1179 
   1180 	if ((error = firmware_read(fw, 0, dfw, size)) != 0) {
   1181 		aprint_error_dev(sc->sc_dev, "can't get firmware\n");
   1182 		goto fail2;
   1183 	}
   1184 
   1185 	/* get pointers to firmware segments */
   1186 	main_text = dfw + sizeof (struct wpi_firmware_hdr);
   1187 	main_data = main_text + main_textsz;
   1188 	init_text = main_data + main_datasz;
   1189 	init_data = init_text + init_textsz;
   1190 	boot_text = init_data + init_datasz;
   1191 
   1192 	/* copy initialization images into pre-allocated DMA-safe memory */
   1193 	memcpy(dma->vaddr, init_data, init_datasz);
   1194 	memcpy((char*)dma->vaddr + WPI_FW_INIT_DATA_MAXSZ, init_text, init_textsz);
   1195 
   1196 	/* tell adapter where to find initialization images */
   1197 	wpi_mem_lock(sc);
   1198 	wpi_mem_write(sc, WPI_MEM_DATA_BASE, dma->paddr);
   1199 	wpi_mem_write(sc, WPI_MEM_DATA_SIZE, init_datasz);
   1200 	wpi_mem_write(sc, WPI_MEM_TEXT_BASE,
   1201 	    dma->paddr + WPI_FW_INIT_DATA_MAXSZ);
   1202 	wpi_mem_write(sc, WPI_MEM_TEXT_SIZE, init_textsz);
   1203 	wpi_mem_unlock(sc);
   1204 
   1205 	/* load firmware boot code */
   1206 	if ((error = wpi_load_microcode(sc, boot_text, boot_textsz)) != 0) {
   1207 		aprint_error_dev(sc->sc_dev, "could not load boot firmware\n");
   1208 		goto fail3;
   1209 	}
   1210 
   1211 	/* now press "execute" ;-) */
   1212 	WPI_WRITE(sc, WPI_RESET, 0);
   1213 
   1214 	/* ..and wait at most one second for adapter to initialize */
   1215 	if ((error = tsleep(sc, PCATCH, "wpiinit", hz)) != 0) {
   1216 		/* this isn't what was supposed to happen.. */
   1217 		aprint_error_dev(sc->sc_dev,
   1218 					"timeout waiting for adapter to initialize\n");
   1219 	}
   1220 
   1221 	/* copy runtime images into pre-allocated DMA-safe memory */
   1222 	memcpy(dma->vaddr, main_data, main_datasz);
   1223 	memcpy((char*)dma->vaddr + WPI_FW_MAIN_DATA_MAXSZ, main_text, main_textsz);
   1224 
   1225 	/* tell adapter where to find runtime images */
   1226 	wpi_mem_lock(sc);
   1227 	wpi_mem_write(sc, WPI_MEM_DATA_BASE, dma->paddr);
   1228 	wpi_mem_write(sc, WPI_MEM_DATA_SIZE, main_datasz);
   1229 	wpi_mem_write(sc, WPI_MEM_TEXT_BASE,
   1230 	    dma->paddr + WPI_FW_MAIN_DATA_MAXSZ);
   1231 	wpi_mem_write(sc, WPI_MEM_TEXT_SIZE, WPI_FW_UPDATED | main_textsz);
   1232 	wpi_mem_unlock(sc);
   1233 
   1234 	/* wait at most one second for second alive notification */
   1235 	if ((error = tsleep(sc, PCATCH, "wpiinit", hz)) != 0) {
   1236 		/* this isn't what was supposed to happen.. */
   1237 		aprint_error_dev(sc->sc_dev,
   1238 						"timeout waiting for adapter to initialize\n");
   1239 	}
   1240 
   1241 
   1242 fail3: 	firmware_free(dfw,size);
   1243 fail2:	firmware_close(fw);
   1244 fail1:	return error;
   1245 }
   1246 
   1247 static void
   1248 wpi_calib_timeout(void *arg)
   1249 {
   1250 	struct wpi_softc *sc = arg;
   1251 	struct ieee80211com *ic = &sc->sc_ic;
   1252 	int temp, s;
   1253 
   1254 	/* automatic rate control triggered every 500ms */
   1255 	if (ic->ic_fixed_rate == -1) {
   1256 		s = splnet();
   1257 		if (ic->ic_opmode == IEEE80211_M_STA)
   1258 			wpi_iter_func(sc, ic->ic_bss);
   1259 		else
   1260                 	ieee80211_iterate_nodes(&ic->ic_sta, wpi_iter_func, sc);
   1261 		splx(s);
   1262 	}
   1263 
   1264 	/* update sensor data */
   1265 	temp = (int)WPI_READ(sc, WPI_TEMPERATURE);
   1266 
   1267 	/* automatic power calibration every 60s */
   1268 	if (++sc->calib_cnt >= 120) {
   1269 		wpi_power_calibration(sc, temp);
   1270 		sc->calib_cnt = 0;
   1271 	}
   1272 
   1273 	callout_schedule(&sc->calib_to, hz/2);
   1274 }
   1275 
   1276 static void
   1277 wpi_iter_func(void *arg, struct ieee80211_node *ni)
   1278 {
   1279 	struct wpi_softc *sc = arg;
   1280 	struct wpi_node *wn = (struct wpi_node *)ni;
   1281 
   1282 	ieee80211_amrr_choose(&sc->amrr, ni, &wn->amn);
   1283 }
   1284 
   1285 /*
   1286  * This function is called periodically (every 60 seconds) to adjust output
   1287  * power to temperature changes.
   1288  */
   1289 void
   1290 wpi_power_calibration(struct wpi_softc *sc, int temp)
   1291 {
   1292 	/* sanity-check read value */
   1293 	if (temp < -260 || temp > 25) {
   1294 		/* this can't be correct, ignore */
   1295 		DPRINTF(("out-of-range temperature reported: %d\n", temp));
   1296 		return;
   1297 	}
   1298 
   1299 	DPRINTF(("temperature %d->%d\n", sc->temp, temp));
   1300 
   1301 	/* adjust Tx power if need be */
   1302 	if (abs(temp - sc->temp) <= 6)
   1303 		return;
   1304 
   1305 	sc->temp = temp;
   1306 
   1307 	if (wpi_set_txpower(sc, sc->sc_ic.ic_bss->ni_chan, 1) != 0) {
   1308 		/* just warn, too bad for the automatic calibration... */
   1309 		aprint_error_dev(sc->sc_dev, "could not adjust Tx power\n");
   1310 	}
   1311 }
   1312 
   1313 static void
   1314 wpi_rx_intr(struct wpi_softc *sc, struct wpi_rx_desc *desc,
   1315 	struct wpi_rx_data *data)
   1316 {
   1317 	struct ieee80211com *ic = &sc->sc_ic;
   1318 	struct ifnet *ifp = ic->ic_ifp;
   1319 	struct wpi_rx_ring *ring = &sc->rxq;
   1320 	struct wpi_rx_stat *stat;
   1321 	struct wpi_rx_head *head;
   1322 	struct wpi_rx_tail *tail;
   1323 	struct wpi_rbuf *rbuf;
   1324 	struct ieee80211_frame *wh;
   1325 	struct ieee80211_node *ni;
   1326 	struct mbuf *m, *mnew;
   1327 	int data_off ;
   1328 
   1329 	stat = (struct wpi_rx_stat *)(desc + 1);
   1330 
   1331 	if (stat->len > WPI_STAT_MAXLEN) {
   1332 		aprint_error_dev(sc->sc_dev, "invalid rx statistic header\n");
   1333 		ifp->if_ierrors++;
   1334 		return;
   1335 	}
   1336 
   1337 	head = (struct wpi_rx_head *)((char *)(stat + 1) + stat->len);
   1338 	tail = (struct wpi_rx_tail *)((char *)(head + 1) + le16toh(head->len));
   1339 
   1340 	DPRINTFN(4, ("rx intr: idx=%d len=%d stat len=%d rssi=%d rate=%x "
   1341 		"chan=%d tstamp=%" PRId64 "\n", ring->cur, le32toh(desc->len),
   1342 		le16toh(head->len), (int8_t)stat->rssi, head->rate, head->chan,
   1343 		le64toh(tail->tstamp)));
   1344 
   1345 	/*
   1346 	 * Discard Rx frames with bad CRC early (XXX we may want to pass them
   1347 	 * to radiotap in monitor mode).
   1348 	 */
   1349 	if ((le32toh(tail->flags) & WPI_RX_NOERROR) != WPI_RX_NOERROR) {
   1350 		DPRINTF(("rx tail flags error %x\n", le32toh(tail->flags)));
   1351 		ifp->if_ierrors++;
   1352 		return;
   1353 	}
   1354 
   1355 	/* Compute where are the useful datas */
   1356 	data_off = (char*)(head + 1) - mtod(data->m, char*);
   1357 
   1358 	/*
   1359 	 * If the number of free entry is too low
   1360 	 * just dup the data->m socket and reuse the same rbuf entry
   1361 	 */
   1362 	if (sc->rxq.nb_free_entries <= WPI_RBUF_LOW_LIMIT) {
   1363 
   1364 		/* Prepare the mbuf for the m_dup */
   1365 		data->m->m_pkthdr.len = data->m->m_len = le16toh(head->len);
   1366 		data->m->m_data = (char*) data->m->m_data + data_off;
   1367 
   1368 		m = m_dup(data->m,0,M_COPYALL,M_DONTWAIT);
   1369 
   1370 		/* Restore the m_data pointer for future use */
   1371 		data->m->m_data = (char*) data->m->m_data - data_off;
   1372 
   1373 		if (m == NULL) {
   1374 			ifp->if_ierrors++;
   1375 			return;
   1376 		}
   1377 	} else {
   1378 
   1379 		MGETHDR(mnew, M_DONTWAIT, MT_DATA);
   1380 		if (mnew == NULL) {
   1381 			ifp->if_ierrors++;
   1382 			return;
   1383 		}
   1384 
   1385 		rbuf = wpi_alloc_rbuf(sc);
   1386 		KASSERT(rbuf != NULL);
   1387 
   1388  		/* attach Rx buffer to mbuf */
   1389 		MEXTADD(mnew, rbuf->vaddr, WPI_RBUF_SIZE, 0, wpi_free_rbuf,
   1390 		 	rbuf);
   1391 		mnew->m_flags |= M_EXT_RW;
   1392 
   1393 		m = data->m;
   1394 		data->m = mnew;
   1395 
   1396 		/* update Rx descriptor */
   1397 		ring->desc[ring->cur] = htole32(rbuf->paddr);
   1398 
   1399 		m->m_data = (char*)m->m_data + data_off;
   1400 		m->m_pkthdr.len = m->m_len = le16toh(head->len);
   1401 	}
   1402 
   1403 	/* finalize mbuf */
   1404 	m->m_pkthdr.rcvif = ifp;
   1405 
   1406 	if (ic->ic_state == IEEE80211_S_SCAN)
   1407 		wpi_fix_channel(ic, m);
   1408 
   1409 #if NBPFILTER > 0
   1410 	if (sc->sc_drvbpf != NULL) {
   1411 		struct wpi_rx_radiotap_header *tap = &sc->sc_rxtap;
   1412 
   1413 		tap->wr_flags = 0;
   1414 		tap->wr_chan_freq =
   1415 			htole16(ic->ic_channels[head->chan].ic_freq);
   1416 		tap->wr_chan_flags =
   1417 			htole16(ic->ic_channels[head->chan].ic_flags);
   1418 		tap->wr_dbm_antsignal = (int8_t)(stat->rssi - WPI_RSSI_OFFSET);
   1419 		tap->wr_dbm_antnoise = (int8_t)le16toh(stat->noise);
   1420 		tap->wr_tsft = tail->tstamp;
   1421 		tap->wr_antenna = (le16toh(head->flags) >> 4) & 0xf;
   1422 		switch (head->rate) {
   1423 		/* CCK rates */
   1424 		case  10: tap->wr_rate =   2; break;
   1425 		case  20: tap->wr_rate =   4; break;
   1426 		case  55: tap->wr_rate =  11; break;
   1427 		case 110: tap->wr_rate =  22; break;
   1428 		/* OFDM rates */
   1429 		case 0xd: tap->wr_rate =  12; break;
   1430 		case 0xf: tap->wr_rate =  18; break;
   1431 		case 0x5: tap->wr_rate =  24; break;
   1432 		case 0x7: tap->wr_rate =  36; break;
   1433 		case 0x9: tap->wr_rate =  48; break;
   1434 		case 0xb: tap->wr_rate =  72; break;
   1435 		case 0x1: tap->wr_rate =  96; break;
   1436 		case 0x3: tap->wr_rate = 108; break;
   1437 		/* unknown rate: should not happen */
   1438 		default:  tap->wr_rate =   0;
   1439 		}
   1440 		if (le16toh(head->flags) & 0x4)
   1441 			tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
   1442 
   1443 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_rxtap_len, m);
   1444 	}
   1445 #endif
   1446 
   1447 	/* grab a reference to the source node */
   1448 	wh = mtod(m, struct ieee80211_frame *);
   1449 	ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
   1450 
   1451 	/* send the frame to the 802.11 layer */
   1452 	ieee80211_input(ic, m, ni, stat->rssi, 0);
   1453 
   1454 	/* release node reference */
   1455 	ieee80211_free_node(ni);
   1456 }
   1457 
   1458 static void
   1459 wpi_tx_intr(struct wpi_softc *sc, struct wpi_rx_desc *desc)
   1460 {
   1461 	struct ifnet *ifp = sc->sc_ic.ic_ifp;
   1462 	struct wpi_tx_ring *ring = &sc->txq[desc->qid & 0x3];
   1463 	struct wpi_tx_data *txdata = &ring->data[desc->idx];
   1464 	struct wpi_tx_stat *stat = (struct wpi_tx_stat *)(desc + 1);
   1465 	struct wpi_node *wn = (struct wpi_node *)txdata->ni;
   1466 
   1467 	DPRINTFN(4, ("tx done: qid=%d idx=%d retries=%d nkill=%d rate=%x "
   1468 		"duration=%d status=%x\n", desc->qid, desc->idx, stat->ntries,
   1469 		stat->nkill, stat->rate, le32toh(stat->duration),
   1470 		le32toh(stat->status)));
   1471 
   1472 	/*
   1473 	 * Update rate control statistics for the node.
   1474 	 * XXX we should not count mgmt frames since they're always sent at
   1475 	 * the lowest available bit-rate.
   1476 	 */
   1477 	wn->amn.amn_txcnt++;
   1478 	if (stat->ntries > 0) {
   1479 		DPRINTFN(3, ("tx intr ntries %d\n", stat->ntries));
   1480 		wn->amn.amn_retrycnt++;
   1481 	}
   1482 
   1483 	if ((le32toh(stat->status) & 0xff) != 1)
   1484 		ifp->if_oerrors++;
   1485 	else
   1486 		ifp->if_opackets++;
   1487 
   1488 	bus_dmamap_unload(sc->sc_dmat, txdata->map);
   1489 	m_freem(txdata->m);
   1490 	txdata->m = NULL;
   1491 	ieee80211_free_node(txdata->ni);
   1492 	txdata->ni = NULL;
   1493 
   1494 	ring->queued--;
   1495 
   1496 	sc->sc_tx_timer = 0;
   1497 	ifp->if_flags &= ~IFF_OACTIVE;
   1498 	wpi_start(ifp);
   1499 }
   1500 
   1501 static void
   1502 wpi_cmd_intr(struct wpi_softc *sc, struct wpi_rx_desc *desc)
   1503 {
   1504 	struct wpi_tx_ring *ring = &sc->cmdq;
   1505 	struct wpi_tx_data *data;
   1506 
   1507 	if ((desc->qid & 7) != 4)
   1508 		return;	/* not a command ack */
   1509 
   1510 	data = &ring->data[desc->idx];
   1511 
   1512 	/* if the command was mapped in a mbuf, free it */
   1513 	if (data->m != NULL) {
   1514 		bus_dmamap_unload(sc->sc_dmat, data->map);
   1515 		m_freem(data->m);
   1516 		data->m = NULL;
   1517 	}
   1518 
   1519 	wakeup(&ring->cmd[desc->idx]);
   1520 }
   1521 
   1522 static void
   1523 wpi_notif_intr(struct wpi_softc *sc)
   1524 {
   1525 	struct ieee80211com *ic = &sc->sc_ic;
   1526 	struct ifnet *ifp =  ic->ic_ifp;
   1527 	struct wpi_rx_desc *desc;
   1528 	struct wpi_rx_data *data;
   1529 	uint32_t hw;
   1530 
   1531 	hw = le32toh(sc->shared->next);
   1532 	while (sc->rxq.cur != hw) {
   1533 		data = &sc->rxq.data[sc->rxq.cur];
   1534 
   1535 		desc = mtod(data->m, struct wpi_rx_desc *);
   1536 
   1537 		DPRINTFN(4, ("rx notification qid=%x idx=%d flags=%x type=%d "
   1538 			"len=%d\n", desc->qid, desc->idx, desc->flags,
   1539 			desc->type, le32toh(desc->len)));
   1540 
   1541 		if (!(desc->qid & 0x80))	/* reply to a command */
   1542 			wpi_cmd_intr(sc, desc);
   1543 
   1544 		switch (desc->type) {
   1545 		case WPI_RX_DONE:
   1546 			/* a 802.11 frame was received */
   1547 			wpi_rx_intr(sc, desc, data);
   1548 			break;
   1549 
   1550 		case WPI_TX_DONE:
   1551 			/* a 802.11 frame has been transmitted */
   1552 			wpi_tx_intr(sc, desc);
   1553 			break;
   1554 
   1555 		case WPI_UC_READY:
   1556 		{
   1557 			struct wpi_ucode_info *uc =
   1558 				(struct wpi_ucode_info *)(desc + 1);
   1559 
   1560 			/* the microcontroller is ready */
   1561 			DPRINTF(("microcode alive notification version %x "
   1562 				"alive %x\n", le32toh(uc->version),
   1563 				le32toh(uc->valid)));
   1564 
   1565 			if (le32toh(uc->valid) != 1) {
   1566 				aprint_error_dev(sc->sc_dev,
   1567 					"microcontroller initialization failed\n");
   1568 			}
   1569 			break;
   1570 		}
   1571 		case WPI_STATE_CHANGED:
   1572 		{
   1573 			uint32_t *status = (uint32_t *)(desc + 1);
   1574 
   1575 			/* enabled/disabled notification */
   1576 			DPRINTF(("state changed to %x\n", le32toh(*status)));
   1577 
   1578 			if (le32toh(*status) & 1) {
   1579 				/* the radio button has to be pushed */
   1580 				aprint_error_dev(sc->sc_dev, "Radio transmitter is off\n");
   1581 				/* turn the interface down */
   1582 				ifp->if_flags &= ~IFF_UP;
   1583 				wpi_stop(ifp, 1);
   1584 				return;	/* no further processing */
   1585 			}
   1586 			break;
   1587 		}
   1588 		case WPI_START_SCAN:
   1589 		{
   1590 			struct wpi_start_scan *scan =
   1591 				(struct wpi_start_scan *)(desc + 1);
   1592 
   1593 			DPRINTFN(2, ("scanning channel %d status %x\n",
   1594 				scan->chan, le32toh(scan->status)));
   1595 
   1596 			/* fix current channel */
   1597 			ic->ic_bss->ni_chan = &ic->ic_channels[scan->chan];
   1598 			break;
   1599 		}
   1600 		case WPI_STOP_SCAN:
   1601 		{
   1602 			struct wpi_stop_scan *scan =
   1603 				(struct wpi_stop_scan *)(desc + 1);
   1604 
   1605 			DPRINTF(("scan finished nchan=%d status=%d chan=%d\n",
   1606 				scan->nchan, scan->status, scan->chan));
   1607 
   1608 			if (scan->status == 1 && scan->chan <= 14) {
   1609 				/*
   1610 				 * We just finished scanning 802.11g channels,
   1611 				 * start scanning 802.11a ones.
   1612 				 */
   1613 				if (wpi_scan(sc, IEEE80211_CHAN_A) == 0)
   1614 					break;
   1615 			}
   1616 			sc->is_scanning = false;
   1617 			ieee80211_end_scan(ic);
   1618 			break;
   1619 		}
   1620 		}
   1621 
   1622 		sc->rxq.cur = (sc->rxq.cur + 1) % WPI_RX_RING_COUNT;
   1623 	}
   1624 
   1625 	/* tell the firmware what we have processed */
   1626 	hw = (hw == 0) ? WPI_RX_RING_COUNT - 1 : hw - 1;
   1627 	WPI_WRITE(sc, WPI_RX_WIDX, hw & ~7);
   1628 }
   1629 
   1630 static int
   1631 wpi_intr(void *arg)
   1632 {
   1633 	struct wpi_softc *sc = arg;
   1634 	struct ifnet *ifp = sc->sc_ic.ic_ifp;
   1635 	uint32_t r;
   1636 
   1637 	r = WPI_READ(sc, WPI_INTR);
   1638 	if (r == 0 || r == 0xffffffff)
   1639 		return 0;	/* not for us */
   1640 
   1641 	DPRINTFN(5, ("interrupt reg %x\n", r));
   1642 
   1643 	/* disable interrupts */
   1644 	WPI_WRITE(sc, WPI_MASK, 0);
   1645 	/* ack interrupts */
   1646 	WPI_WRITE(sc, WPI_INTR, r);
   1647 
   1648 	if (r & (WPI_SW_ERROR | WPI_HW_ERROR)) {
   1649 		aprint_error_dev(sc->sc_dev, "fatal firmware error\n");
   1650 		sc->sc_ic.ic_ifp->if_flags &= ~IFF_UP;
   1651 		wpi_stop(sc->sc_ic.ic_ifp, 1);
   1652 		return 1;
   1653 	}
   1654 
   1655 	if (r & WPI_RX_INTR)
   1656 		wpi_notif_intr(sc);
   1657 
   1658 	if (r & WPI_ALIVE_INTR)	/* firmware initialized */
   1659 		wakeup(sc);
   1660 
   1661 	/* re-enable interrupts */
   1662 	if (ifp->if_flags & IFF_UP)
   1663 		WPI_WRITE(sc, WPI_MASK, WPI_INTR_MASK);
   1664 
   1665 	return 1;
   1666 }
   1667 
   1668 static uint8_t
   1669 wpi_plcp_signal(int rate)
   1670 {
   1671 	switch (rate) {
   1672 	/* CCK rates (returned values are device-dependent) */
   1673 	case 2:		return 10;
   1674 	case 4:		return 20;
   1675 	case 11:	return 55;
   1676 	case 22:	return 110;
   1677 
   1678 	/* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
   1679 	/* R1-R4, (u)ral is R4-R1 */
   1680 	case 12:	return 0xd;
   1681 	case 18:	return 0xf;
   1682 	case 24:	return 0x5;
   1683 	case 36:	return 0x7;
   1684 	case 48:	return 0x9;
   1685 	case 72:	return 0xb;
   1686 	case 96:	return 0x1;
   1687 	case 108:	return 0x3;
   1688 
   1689 	/* unsupported rates (should not get there) */
   1690 	default:	return 0;
   1691 	}
   1692 }
   1693 
   1694 /* quickly determine if a given rate is CCK or OFDM */
   1695 #define WPI_RATE_IS_OFDM(rate) ((rate) >= 12 && (rate) != 22)
   1696 
   1697 static int
   1698 wpi_tx_data(struct wpi_softc *sc, struct mbuf *m0, struct ieee80211_node *ni,
   1699 	int ac)
   1700 {
   1701 	struct ieee80211com *ic = &sc->sc_ic;
   1702 	struct wpi_tx_ring *ring = &sc->txq[ac];
   1703 	struct wpi_tx_desc *desc;
   1704 	struct wpi_tx_data *data;
   1705 	struct wpi_tx_cmd *cmd;
   1706 	struct wpi_cmd_data *tx;
   1707 	struct ieee80211_frame *wh;
   1708 	struct ieee80211_key *k;
   1709 	const struct chanAccParams *cap;
   1710 	struct mbuf *mnew;
   1711 	int i, error, rate, hdrlen, noack = 0;
   1712 
   1713 	desc = &ring->desc[ring->cur];
   1714 	data = &ring->data[ring->cur];
   1715 
   1716 	wh = mtod(m0, struct ieee80211_frame *);
   1717 
   1718 	if (IEEE80211_QOS_HAS_SEQ(wh)) {
   1719 		cap = &ic->ic_wme.wme_chanParams;
   1720 		noack = cap->cap_wmeParams[ac].wmep_noackPolicy;
   1721 	}
   1722 
   1723 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
   1724 		k = ieee80211_crypto_encap(ic, ni, m0);
   1725 		if (k == NULL) {
   1726 			m_freem(m0);
   1727 			return ENOBUFS;
   1728 		}
   1729 
   1730 		/* packet header may have moved, reset our local pointer */
   1731 		wh = mtod(m0, struct ieee80211_frame *);
   1732 	}
   1733 
   1734 	hdrlen = ieee80211_anyhdrsize(wh);
   1735 
   1736 	/* pickup a rate */
   1737 	if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
   1738 		IEEE80211_FC0_TYPE_MGT) {
   1739 		/* mgmt frames are sent at the lowest available bit-rate */
   1740 		rate = ni->ni_rates.rs_rates[0];
   1741 	} else {
   1742 		if (ic->ic_fixed_rate != -1) {
   1743 			rate = ic->ic_sup_rates[ic->ic_curmode].
   1744 				rs_rates[ic->ic_fixed_rate];
   1745 		} else
   1746 			rate = ni->ni_rates.rs_rates[ni->ni_txrate];
   1747 	}
   1748 	rate &= IEEE80211_RATE_VAL;
   1749 
   1750 
   1751 #if NBPFILTER > 0
   1752 	if (sc->sc_drvbpf != NULL) {
   1753 		struct wpi_tx_radiotap_header *tap = &sc->sc_txtap;
   1754 
   1755 		tap->wt_flags = 0;
   1756 		tap->wt_chan_freq = htole16(ni->ni_chan->ic_freq);
   1757 		tap->wt_chan_flags = htole16(ni->ni_chan->ic_flags);
   1758 		tap->wt_rate = rate;
   1759 		tap->wt_hwqueue = ac;
   1760 		if (wh->i_fc[1] & IEEE80211_FC1_WEP)
   1761 			tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
   1762 
   1763 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m0);
   1764 	}
   1765 #endif
   1766 
   1767 	cmd = &ring->cmd[ring->cur];
   1768 	cmd->code = WPI_CMD_TX_DATA;
   1769 	cmd->flags = 0;
   1770 	cmd->qid = ring->qid;
   1771 	cmd->idx = ring->cur;
   1772 
   1773 	tx = (struct wpi_cmd_data *)cmd->data;
   1774 	tx->flags = 0;
   1775 
   1776 	if (!noack && !IEEE80211_IS_MULTICAST(wh->i_addr1)) {
   1777 		tx->flags |= htole32(WPI_TX_NEED_ACK);
   1778 	} else if (m0->m_pkthdr.len + IEEE80211_CRC_LEN > ic->ic_rtsthreshold)
   1779 		tx->flags |= htole32(WPI_TX_NEED_RTS | WPI_TX_FULL_TXOP);
   1780 
   1781 	tx->flags |= htole32(WPI_TX_AUTO_SEQ);
   1782 
   1783 	/* retrieve destination node's id */
   1784 	tx->id = IEEE80211_IS_MULTICAST(wh->i_addr1) ? WPI_ID_BROADCAST :
   1785 		WPI_ID_BSS;
   1786 
   1787 	if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
   1788 		IEEE80211_FC0_TYPE_MGT) {
   1789 		/* tell h/w to set timestamp in probe responses */
   1790 		if ((wh->i_fc[0] &
   1791 		    (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
   1792 		    (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP))
   1793 			tx->flags |= htole32(WPI_TX_INSERT_TSTAMP);
   1794 
   1795 		if (((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
   1796 			 IEEE80211_FC0_SUBTYPE_ASSOC_REQ) ||
   1797 			((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
   1798 			 IEEE80211_FC0_SUBTYPE_REASSOC_REQ))
   1799 			tx->timeout = htole16(3);
   1800 		else
   1801 			tx->timeout = htole16(2);
   1802 	} else
   1803 		tx->timeout = htole16(0);
   1804 
   1805 	tx->rate = wpi_plcp_signal(rate);
   1806 
   1807 	/* be very persistant at sending frames out */
   1808 	tx->rts_ntries = 7;
   1809 	tx->data_ntries = 15;
   1810 
   1811 	tx->ofdm_mask = 0xff;
   1812 	tx->cck_mask = 0xf;
   1813 	tx->lifetime = htole32(WPI_LIFETIME_INFINITE);
   1814 
   1815 	tx->len = htole16(m0->m_pkthdr.len);
   1816 
   1817 	/* save and trim IEEE802.11 header */
   1818 	memcpy((uint8_t *)(tx + 1), wh, hdrlen);
   1819 	m_adj(m0, hdrlen);
   1820 
   1821 	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
   1822 		BUS_DMA_WRITE | BUS_DMA_NOWAIT);
   1823 	if (error != 0 && error != EFBIG) {
   1824 		aprint_error_dev(sc->sc_dev, "could not map mbuf (error %d)\n", error);
   1825 		m_freem(m0);
   1826 		return error;
   1827 	}
   1828 	if (error != 0) {
   1829 		/* too many fragments, linearize */
   1830 		MGETHDR(mnew, M_DONTWAIT, MT_DATA);
   1831 		if (mnew == NULL) {
   1832 			m_freem(m0);
   1833 			return ENOMEM;
   1834 		}
   1835 
   1836 		M_COPY_PKTHDR(mnew, m0);
   1837 		if (m0->m_pkthdr.len > MHLEN) {
   1838 			MCLGET(mnew, M_DONTWAIT);
   1839 			if (!(mnew->m_flags & M_EXT)) {
   1840 				m_freem(m0);
   1841 				m_freem(mnew);
   1842 				return ENOMEM;
   1843 			}
   1844 		}
   1845 
   1846 		m_copydata(m0, 0, m0->m_pkthdr.len, mtod(mnew, void *));
   1847 		m_freem(m0);
   1848 		mnew->m_len = mnew->m_pkthdr.len;
   1849 		m0 = mnew;
   1850 
   1851 		error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
   1852 			BUS_DMA_WRITE | BUS_DMA_NOWAIT);
   1853 		if (error != 0) {
   1854 			aprint_error_dev(sc->sc_dev, "could not map mbuf (error %d)\n",
   1855 							 error);
   1856 			m_freem(m0);
   1857 			return error;
   1858 		}
   1859 	}
   1860 
   1861 	data->m = m0;
   1862 	data->ni = ni;
   1863 
   1864 	DPRINTFN(4, ("sending data: qid=%d idx=%d len=%d nsegs=%d\n",
   1865 		ring->qid, ring->cur, m0->m_pkthdr.len, data->map->dm_nsegs));
   1866 
   1867 	/* first scatter/gather segment is used by the tx data command */
   1868 	desc->flags = htole32(WPI_PAD32(m0->m_pkthdr.len) << 28 |
   1869 		(1 + data->map->dm_nsegs) << 24);
   1870 	desc->segs[0].addr = htole32(ring->cmd_dma.paddr +
   1871 		ring->cur * sizeof (struct wpi_tx_cmd));
   1872 	desc->segs[0].len  = htole32(4 + sizeof (struct wpi_cmd_data) +
   1873 						 ((hdrlen + 3) & ~3));
   1874 
   1875 	for (i = 1; i <= data->map->dm_nsegs; i++) {
   1876 		desc->segs[i].addr =
   1877 			htole32(data->map->dm_segs[i - 1].ds_addr);
   1878 		desc->segs[i].len  =
   1879 			htole32(data->map->dm_segs[i - 1].ds_len);
   1880 	}
   1881 
   1882 	ring->queued++;
   1883 
   1884 	/* kick ring */
   1885 	ring->cur = (ring->cur + 1) % WPI_TX_RING_COUNT;
   1886 	WPI_WRITE(sc, WPI_TX_WIDX, ring->qid << 8 | ring->cur);
   1887 
   1888 	return 0;
   1889 }
   1890 
   1891 static void
   1892 wpi_start(struct ifnet *ifp)
   1893 {
   1894 	struct wpi_softc *sc = ifp->if_softc;
   1895 	struct ieee80211com *ic = &sc->sc_ic;
   1896 	struct ieee80211_node *ni;
   1897 	struct ether_header *eh;
   1898 	struct mbuf *m0;
   1899 	int ac;
   1900 
   1901 	/*
   1902 	 * net80211 may still try to send management frames even if the
   1903 	 * IFF_RUNNING flag is not set...
   1904 	 */
   1905 	if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
   1906 		return;
   1907 
   1908 	for (;;) {
   1909 		IF_DEQUEUE(&ic->ic_mgtq, m0);
   1910 		if (m0 != NULL) {
   1911 
   1912 			ni = (struct ieee80211_node *)m0->m_pkthdr.rcvif;
   1913 			m0->m_pkthdr.rcvif = NULL;
   1914 
   1915 			/* management frames go into ring 0 */
   1916 			if (sc->txq[0].queued > sc->txq[0].count - 8) {
   1917 				ifp->if_oerrors++;
   1918 				continue;
   1919 			}
   1920 #if NBPFILTER > 0
   1921 			if (ic->ic_rawbpf != NULL)
   1922 				bpf_mtap(ic->ic_rawbpf, m0);
   1923 #endif
   1924 			if (wpi_tx_data(sc, m0, ni, 0) != 0) {
   1925 				ifp->if_oerrors++;
   1926 				break;
   1927 			}
   1928 		} else {
   1929 			if (ic->ic_state != IEEE80211_S_RUN)
   1930 				break;
   1931 			IFQ_POLL(&ifp->if_snd, m0);
   1932 			if (m0 == NULL)
   1933 				break;
   1934 
   1935 			if (m0->m_len < sizeof (*eh) &&
   1936 			    (m0 = m_pullup(m0, sizeof (*eh))) != NULL) {
   1937 				ifp->if_oerrors++;
   1938 				continue;
   1939 			}
   1940 			eh = mtod(m0, struct ether_header *);
   1941 			ni = ieee80211_find_txnode(ic, eh->ether_dhost);
   1942 			if (ni == NULL) {
   1943 				m_freem(m0);
   1944 				ifp->if_oerrors++;
   1945 				continue;
   1946 			}
   1947 
   1948 			/* classify mbuf so we can find which tx ring to use */
   1949 			if (ieee80211_classify(ic, m0, ni) != 0) {
   1950 				m_freem(m0);
   1951 				ieee80211_free_node(ni);
   1952 				ifp->if_oerrors++;
   1953 				continue;
   1954 			}
   1955 
   1956 			/* no QoS encapsulation for EAPOL frames */
   1957 			ac = (eh->ether_type != htons(ETHERTYPE_PAE)) ?
   1958 			    M_WME_GETAC(m0) : WME_AC_BE;
   1959 
   1960 			if (sc->txq[ac].queued > sc->txq[ac].count - 8) {
   1961 				/* there is no place left in this ring */
   1962 				ifp->if_flags |= IFF_OACTIVE;
   1963 				break;
   1964 			}
   1965 			IFQ_DEQUEUE(&ifp->if_snd, m0);
   1966 #if NBPFILTER > 0
   1967 			if (ifp->if_bpf != NULL)
   1968 				bpf_mtap(ifp->if_bpf, m0);
   1969 #endif
   1970 			m0 = ieee80211_encap(ic, m0, ni);
   1971 			if (m0 == NULL) {
   1972 				ieee80211_free_node(ni);
   1973 				ifp->if_oerrors++;
   1974 				continue;
   1975 			}
   1976 #if NBPFILTER > 0
   1977 			if (ic->ic_rawbpf != NULL)
   1978 				bpf_mtap(ic->ic_rawbpf, m0);
   1979 #endif
   1980 			if (wpi_tx_data(sc, m0, ni, ac) != 0) {
   1981 				ieee80211_free_node(ni);
   1982 				ifp->if_oerrors++;
   1983 				break;
   1984 			}
   1985 		}
   1986 
   1987 		sc->sc_tx_timer = 5;
   1988 		ifp->if_timer = 1;
   1989 	}
   1990 }
   1991 
   1992 static void
   1993 wpi_watchdog(struct ifnet *ifp)
   1994 {
   1995 	struct wpi_softc *sc = ifp->if_softc;
   1996 
   1997 	ifp->if_timer = 0;
   1998 
   1999 	if (sc->sc_tx_timer > 0) {
   2000 		if (--sc->sc_tx_timer == 0) {
   2001 			aprint_error_dev(sc->sc_dev, "device timeout\n");
   2002 			ifp->if_oerrors++;
   2003 			ifp->if_flags &= ~IFF_UP;
   2004 			wpi_stop(ifp, 1);
   2005 			return;
   2006 		}
   2007 		ifp->if_timer = 1;
   2008 	}
   2009 
   2010 	ieee80211_watchdog(&sc->sc_ic);
   2011 }
   2012 
   2013 static int
   2014 wpi_ioctl(struct ifnet *ifp, u_long cmd, void *data)
   2015 {
   2016 #define IS_RUNNING(ifp) \
   2017 	((ifp->if_flags & IFF_UP) && (ifp->if_flags & IFF_RUNNING))
   2018 
   2019 	struct wpi_softc *sc = ifp->if_softc;
   2020 	struct ieee80211com *ic = &sc->sc_ic;
   2021 	int s, error = 0;
   2022 
   2023 	s = splnet();
   2024 
   2025 	switch (cmd) {
   2026 	case SIOCSIFFLAGS:
   2027 		if (ifp->if_flags & IFF_UP) {
   2028 			if (!(ifp->if_flags & IFF_RUNNING))
   2029 				wpi_init(ifp);
   2030 		} else {
   2031 			if (ifp->if_flags & IFF_RUNNING)
   2032 				wpi_stop(ifp, 1);
   2033 		}
   2034 		break;
   2035 
   2036 	case SIOCADDMULTI:
   2037 	case SIOCDELMULTI:
   2038 		/* XXX no h/w multicast filter? --dyoung */
   2039 		if ((error = ether_ioctl(ifp, cmd, data)) == ENETRESET) {
   2040 			/* setup multicast filter, etc */
   2041 			error = 0;
   2042 		}
   2043 		break;
   2044 
   2045 	default:
   2046 		error = ieee80211_ioctl(ic, cmd, data);
   2047 	}
   2048 
   2049 	if (error == ENETRESET) {
   2050 		if (IS_RUNNING(ifp) &&
   2051 			(ic->ic_roaming != IEEE80211_ROAMING_MANUAL))
   2052 			wpi_init(ifp);
   2053 		error = 0;
   2054 	}
   2055 
   2056 	splx(s);
   2057 	return error;
   2058 
   2059 #undef IS_RUNNING
   2060 }
   2061 
   2062 /*
   2063  * Extract various information from EEPROM.
   2064  */
   2065 static void
   2066 wpi_read_eeprom(struct wpi_softc *sc)
   2067 {
   2068 	struct ieee80211com *ic = &sc->sc_ic;
   2069 	char domain[4];
   2070 	int i;
   2071 
   2072 	wpi_read_prom_data(sc, WPI_EEPROM_CAPABILITIES, &sc->cap, 1);
   2073 	wpi_read_prom_data(sc, WPI_EEPROM_REVISION, &sc->rev, 2);
   2074 	wpi_read_prom_data(sc, WPI_EEPROM_TYPE, &sc->type, 1);
   2075 
   2076 	DPRINTF(("cap=%x rev=%x type=%x\n", sc->cap, le16toh(sc->rev),
   2077 	    sc->type));
   2078 
   2079 	/* read and print regulatory domain */
   2080 	wpi_read_prom_data(sc, WPI_EEPROM_DOMAIN, domain, 4);
   2081 	aprint_normal(", %.4s", domain);
   2082 
   2083 	/* read and print MAC address */
   2084 	wpi_read_prom_data(sc, WPI_EEPROM_MAC, ic->ic_myaddr, 6);
   2085 	aprint_normal(", address %s\n", ether_sprintf(ic->ic_myaddr));
   2086 
   2087 	/* read the list of authorized channels */
   2088 	for (i = 0; i < WPI_CHAN_BANDS_COUNT; i++)
   2089 		wpi_read_eeprom_channels(sc, i);
   2090 
   2091 	/* read the list of power groups */
   2092 	for (i = 0; i < WPI_POWER_GROUPS_COUNT; i++)
   2093 		wpi_read_eeprom_group(sc, i);
   2094 }
   2095 
   2096 static void
   2097 wpi_read_eeprom_channels(struct wpi_softc *sc, int n)
   2098 {
   2099 	struct ieee80211com *ic = &sc->sc_ic;
   2100 	const struct wpi_chan_band *band = &wpi_bands[n];
   2101 	struct wpi_eeprom_chan channels[WPI_MAX_CHAN_PER_BAND];
   2102 	int chan, i;
   2103 
   2104 	wpi_read_prom_data(sc, band->addr, channels,
   2105 	    band->nchan * sizeof (struct wpi_eeprom_chan));
   2106 
   2107 	for (i = 0; i < band->nchan; i++) {
   2108 		if (!(channels[i].flags & WPI_EEPROM_CHAN_VALID))
   2109 			continue;
   2110 
   2111 		chan = band->chan[i];
   2112 
   2113 		if (n == 0) {	/* 2GHz band */
   2114 			ic->ic_channels[chan].ic_freq =
   2115 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_2GHZ);
   2116 			ic->ic_channels[chan].ic_flags =
   2117 			    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
   2118 			    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
   2119 
   2120 		} else {	/* 5GHz band */
   2121 			/*
   2122 			 * Some 3945abg adapters support channels 7, 8, 11
   2123 			 * and 12 in the 2GHz *and* 5GHz bands.
   2124 			 * Because of limitations in our net80211(9) stack,
   2125 			 * we can't support these channels in 5GHz band.
   2126 			 */
   2127 			if (chan <= 14)
   2128 				continue;
   2129 
   2130 			ic->ic_channels[chan].ic_freq =
   2131 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_5GHZ);
   2132 			ic->ic_channels[chan].ic_flags = IEEE80211_CHAN_A;
   2133 		}
   2134 
   2135 		/* is active scan allowed on this channel? */
   2136 		if (!(channels[i].flags & WPI_EEPROM_CHAN_ACTIVE)) {
   2137 			ic->ic_channels[chan].ic_flags |=
   2138 			    IEEE80211_CHAN_PASSIVE;
   2139 		}
   2140 
   2141 		/* save maximum allowed power for this channel */
   2142 		sc->maxpwr[chan] = channels[i].maxpwr;
   2143 
   2144 		DPRINTF(("adding chan %d flags=0x%x maxpwr=%d\n",
   2145 		    chan, channels[i].flags, sc->maxpwr[chan]));
   2146 	}
   2147 }
   2148 
   2149 static void
   2150 wpi_read_eeprom_group(struct wpi_softc *sc, int n)
   2151 {
   2152 	struct wpi_power_group *group = &sc->groups[n];
   2153 	struct wpi_eeprom_group rgroup;
   2154 	int i;
   2155 
   2156 	wpi_read_prom_data(sc, WPI_EEPROM_POWER_GRP + n * 32, &rgroup,
   2157 	    sizeof rgroup);
   2158 
   2159 	/* save power group information */
   2160 	group->chan   = rgroup.chan;
   2161 	group->maxpwr = rgroup.maxpwr;
   2162 	/* temperature at which the samples were taken */
   2163 	group->temp   = (int16_t)le16toh(rgroup.temp);
   2164 
   2165 	DPRINTF(("power group %d: chan=%d maxpwr=%d temp=%d\n", n,
   2166 	    group->chan, group->maxpwr, group->temp));
   2167 
   2168 	for (i = 0; i < WPI_SAMPLES_COUNT; i++) {
   2169 		group->samples[i].index = rgroup.samples[i].index;
   2170 		group->samples[i].power = rgroup.samples[i].power;
   2171 
   2172 		DPRINTF(("\tsample %d: index=%d power=%d\n", i,
   2173 		    group->samples[i].index, group->samples[i].power));
   2174 	}
   2175 }
   2176 
   2177 /*
   2178  * Send a command to the firmware.
   2179  */
   2180 static int
   2181 wpi_cmd(struct wpi_softc *sc, int code, const void *buf, int size, int async)
   2182 {
   2183 	struct wpi_tx_ring *ring = &sc->cmdq;
   2184 	struct wpi_tx_desc *desc;
   2185 	struct wpi_tx_cmd *cmd;
   2186 
   2187 	KASSERT(size <= sizeof cmd->data);
   2188 
   2189 	desc = &ring->desc[ring->cur];
   2190 	cmd = &ring->cmd[ring->cur];
   2191 
   2192 	cmd->code = code;
   2193 	cmd->flags = 0;
   2194 	cmd->qid = ring->qid;
   2195 	cmd->idx = ring->cur;
   2196 	memcpy(cmd->data, buf, size);
   2197 
   2198 	desc->flags = htole32(WPI_PAD32(size) << 28 | 1 << 24);
   2199 	desc->segs[0].addr = htole32(ring->cmd_dma.paddr +
   2200 		ring->cur * sizeof (struct wpi_tx_cmd));
   2201 	desc->segs[0].len  = htole32(4 + size);
   2202 
   2203 	/* kick cmd ring */
   2204 	ring->cur = (ring->cur + 1) % WPI_CMD_RING_COUNT;
   2205 	WPI_WRITE(sc, WPI_TX_WIDX, ring->qid << 8 | ring->cur);
   2206 
   2207 	return async ? 0 : tsleep(cmd, PCATCH, "wpicmd", hz);
   2208 }
   2209 
   2210 static int
   2211 wpi_wme_update(struct ieee80211com *ic)
   2212 {
   2213 #define WPI_EXP2(v)	htole16((1 << (v)) - 1)
   2214 #define WPI_USEC(v)	htole16(IEEE80211_TXOP_TO_US(v))
   2215 	struct wpi_softc *sc = ic->ic_ifp->if_softc;
   2216 	const struct wmeParams *wmep;
   2217 	struct wpi_wme_setup wme;
   2218 	int ac;
   2219 
   2220 	/* don't override default WME values if WME is not actually enabled */
   2221 	if (!(ic->ic_flags & IEEE80211_F_WME))
   2222 		return 0;
   2223 
   2224 	wme.flags = 0;
   2225 	for (ac = 0; ac < WME_NUM_AC; ac++) {
   2226 		wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
   2227 		wme.ac[ac].aifsn = wmep->wmep_aifsn;
   2228 		wme.ac[ac].cwmin = WPI_EXP2(wmep->wmep_logcwmin);
   2229 		wme.ac[ac].cwmax = WPI_EXP2(wmep->wmep_logcwmax);
   2230 		wme.ac[ac].txop  = WPI_USEC(wmep->wmep_txopLimit);
   2231 
   2232 		DPRINTF(("setting WME for queue %d aifsn=%d cwmin=%d cwmax=%d "
   2233 		    "txop=%d\n", ac, wme.ac[ac].aifsn, wme.ac[ac].cwmin,
   2234 		    wme.ac[ac].cwmax, wme.ac[ac].txop));
   2235 	}
   2236 
   2237 	return wpi_cmd(sc, WPI_CMD_SET_WME, &wme, sizeof wme, 1);
   2238 #undef WPI_USEC
   2239 #undef WPI_EXP2
   2240 }
   2241 
   2242 /*
   2243  * Configure h/w multi-rate retries.
   2244  */
   2245 static int
   2246 wpi_mrr_setup(struct wpi_softc *sc)
   2247 {
   2248 	struct ieee80211com *ic = &sc->sc_ic;
   2249 	struct wpi_mrr_setup mrr;
   2250 	int i, error;
   2251 
   2252 	/* CCK rates (not used with 802.11a) */
   2253 	for (i = WPI_CCK1; i <= WPI_CCK11; i++) {
   2254 		mrr.rates[i].flags = 0;
   2255 		mrr.rates[i].plcp = wpi_ridx_to_plcp[i];
   2256 		/* fallback to the immediate lower CCK rate (if any) */
   2257 		mrr.rates[i].next = (i == WPI_CCK1) ? WPI_CCK1 : i - 1;
   2258 		/* try one time at this rate before falling back to "next" */
   2259 		mrr.rates[i].ntries = 1;
   2260 	}
   2261 
   2262 	/* OFDM rates (not used with 802.11b) */
   2263 	for (i = WPI_OFDM6; i <= WPI_OFDM54; i++) {
   2264 		mrr.rates[i].flags = 0;
   2265 		mrr.rates[i].plcp = wpi_ridx_to_plcp[i];
   2266 		/* fallback to the immediate lower rate (if any) */
   2267 		/* we allow fallback from OFDM/6 to CCK/2 in 11b/g mode */
   2268 		mrr.rates[i].next = (i == WPI_OFDM6) ?
   2269 		    ((ic->ic_curmode == IEEE80211_MODE_11A) ?
   2270 			WPI_OFDM6 : WPI_CCK2) :
   2271 		    i - 1;
   2272 		/* try one time at this rate before falling back to "next" */
   2273 		mrr.rates[i].ntries = 1;
   2274 	}
   2275 
   2276 	/* setup MRR for control frames */
   2277 	mrr.which = htole32(WPI_MRR_CTL);
   2278 	error = wpi_cmd(sc, WPI_CMD_MRR_SETUP, &mrr, sizeof mrr, 0);
   2279 	if (error != 0) {
   2280 		aprint_error_dev(sc->sc_dev, "could not setup MRR for control frames\n");
   2281 		return error;
   2282 	}
   2283 
   2284 	/* setup MRR for data frames */
   2285 	mrr.which = htole32(WPI_MRR_DATA);
   2286 	error = wpi_cmd(sc, WPI_CMD_MRR_SETUP, &mrr, sizeof mrr, 0);
   2287 	if (error != 0) {
   2288 		aprint_error_dev(sc->sc_dev, "could not setup MRR for data frames\n");
   2289 		return error;
   2290 	}
   2291 
   2292 	return 0;
   2293 }
   2294 
   2295 static void
   2296 wpi_set_led(struct wpi_softc *sc, uint8_t which, uint8_t off, uint8_t on)
   2297 {
   2298 	struct wpi_cmd_led led;
   2299 
   2300 	led.which = which;
   2301 	led.unit = htole32(100000);	/* on/off in unit of 100ms */
   2302 	led.off = off;
   2303 	led.on = on;
   2304 
   2305 	(void)wpi_cmd(sc, WPI_CMD_SET_LED, &led, sizeof led, 1);
   2306 }
   2307 
   2308 static void
   2309 wpi_enable_tsf(struct wpi_softc *sc, struct ieee80211_node *ni)
   2310 {
   2311 	struct wpi_cmd_tsf tsf;
   2312 	uint64_t val, mod;
   2313 
   2314 	memset(&tsf, 0, sizeof tsf);
   2315 	memcpy(&tsf.tstamp, ni->ni_tstamp.data, 8);
   2316 	tsf.bintval = htole16(ni->ni_intval);
   2317 	tsf.lintval = htole16(10);
   2318 
   2319 	/* compute remaining time until next beacon */
   2320 	val = (uint64_t)ni->ni_intval  * 1024;	/* msecs -> usecs */
   2321 	mod = le64toh(tsf.tstamp) % val;
   2322 	tsf.binitval = htole32((uint32_t)(val - mod));
   2323 
   2324 	DPRINTF(("TSF bintval=%u tstamp=%" PRId64 ", init=%u\n",
   2325 	    ni->ni_intval, le64toh(tsf.tstamp), (uint32_t)(val - mod)));
   2326 
   2327 	if (wpi_cmd(sc, WPI_CMD_TSF, &tsf, sizeof tsf, 1) != 0)
   2328 		aprint_error_dev(sc->sc_dev, "could not enable TSF\n");
   2329 }
   2330 
   2331 /*
   2332  * Update Tx power to match what is defined for channel `c'.
   2333  */
   2334 static int
   2335 wpi_set_txpower(struct wpi_softc *sc, struct ieee80211_channel *c, int async)
   2336 {
   2337 	struct ieee80211com *ic = &sc->sc_ic;
   2338 	struct wpi_power_group *group;
   2339 	struct wpi_cmd_txpower txpower;
   2340 	u_int chan;
   2341 	int i;
   2342 
   2343 	/* get channel number */
   2344 	chan = ieee80211_chan2ieee(ic, c);
   2345 
   2346 	/* find the power group to which this channel belongs */
   2347 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
   2348 		for (group = &sc->groups[1]; group < &sc->groups[4]; group++)
   2349 			if (chan <= group->chan)
   2350 				break;
   2351 	} else
   2352 		group = &sc->groups[0];
   2353 
   2354 	memset(&txpower, 0, sizeof txpower);
   2355 	txpower.band = IEEE80211_IS_CHAN_5GHZ(c) ? 0 : 1;
   2356 	txpower.chan = htole16(chan);
   2357 
   2358 	/* set Tx power for all OFDM and CCK rates */
   2359 	for (i = 0; i <= 11 ; i++) {
   2360 		/* retrieve Tx power for this channel/rate combination */
   2361 		int idx = wpi_get_power_index(sc, group, c,
   2362 		    wpi_ridx_to_rate[i]);
   2363 
   2364 		txpower.rates[i].plcp = wpi_ridx_to_plcp[i];
   2365 
   2366 		if (IEEE80211_IS_CHAN_5GHZ(c)) {
   2367 			txpower.rates[i].rf_gain = wpi_rf_gain_5ghz[idx];
   2368 			txpower.rates[i].dsp_gain = wpi_dsp_gain_5ghz[idx];
   2369 		} else {
   2370 			txpower.rates[i].rf_gain = wpi_rf_gain_2ghz[idx];
   2371 			txpower.rates[i].dsp_gain = wpi_dsp_gain_2ghz[idx];
   2372 		}
   2373 		DPRINTF(("chan %d/rate %d: power index %d\n", chan,
   2374 		    wpi_ridx_to_rate[i], idx));
   2375 	}
   2376 
   2377 	return wpi_cmd(sc, WPI_CMD_TXPOWER, &txpower, sizeof txpower, async);
   2378 }
   2379 
   2380 /*
   2381  * Determine Tx power index for a given channel/rate combination.
   2382  * This takes into account the regulatory information from EEPROM and the
   2383  * current temperature.
   2384  */
   2385 static int
   2386 wpi_get_power_index(struct wpi_softc *sc, struct wpi_power_group *group,
   2387     struct ieee80211_channel *c, int rate)
   2388 {
   2389 /* fixed-point arithmetic division using a n-bit fractional part */
   2390 #define fdivround(a, b, n)	\
   2391 	((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
   2392 
   2393 /* linear interpolation */
   2394 #define interpolate(x, x1, y1, x2, y2, n)	\
   2395 	((y1) + fdivround(((x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
   2396 
   2397 	struct ieee80211com *ic = &sc->sc_ic;
   2398 	struct wpi_power_sample *sample;
   2399 	int pwr, idx;
   2400 	u_int chan;
   2401 
   2402 	/* get channel number */
   2403 	chan = ieee80211_chan2ieee(ic, c);
   2404 
   2405 	/* default power is group's maximum power - 3dB */
   2406 	pwr = group->maxpwr / 2;
   2407 
   2408 	/* decrease power for highest OFDM rates to reduce distortion */
   2409 	switch (rate) {
   2410 	case 72:	/* 36Mb/s */
   2411 		pwr -= IEEE80211_IS_CHAN_2GHZ(c) ? 0 :  5;
   2412 		break;
   2413 	case 96:	/* 48Mb/s */
   2414 		pwr -= IEEE80211_IS_CHAN_2GHZ(c) ? 7 : 10;
   2415 		break;
   2416 	case 108:	/* 54Mb/s */
   2417 		pwr -= IEEE80211_IS_CHAN_2GHZ(c) ? 9 : 12;
   2418 		break;
   2419 	}
   2420 
   2421 	/* never exceed channel's maximum allowed Tx power */
   2422 	pwr = min(pwr, sc->maxpwr[chan]);
   2423 
   2424 	/* retrieve power index into gain tables from samples */
   2425 	for (sample = group->samples; sample < &group->samples[3]; sample++)
   2426 		if (pwr > sample[1].power)
   2427 			break;
   2428 	/* fixed-point linear interpolation using a 19-bit fractional part */
   2429 	idx = interpolate(pwr, sample[0].power, sample[0].index,
   2430 	    sample[1].power, sample[1].index, 19);
   2431 
   2432 	/*
   2433 	 * Adjust power index based on current temperature:
   2434 	 * - if cooler than factory-calibrated: decrease output power
   2435 	 * - if warmer than factory-calibrated: increase output power
   2436 	 */
   2437 	idx -= (sc->temp - group->temp) * 11 / 100;
   2438 
   2439 	/* decrease power for CCK rates (-5dB) */
   2440 	if (!WPI_RATE_IS_OFDM(rate))
   2441 		idx += 10;
   2442 
   2443 	/* keep power index in a valid range */
   2444 	if (idx < 0)
   2445 		return 0;
   2446 	if (idx > WPI_MAX_PWR_INDEX)
   2447 		return WPI_MAX_PWR_INDEX;
   2448 	return idx;
   2449 
   2450 #undef interpolate
   2451 #undef fdivround
   2452 }
   2453 
   2454 /*
   2455  * Build a beacon frame that the firmware will broadcast periodically in
   2456  * IBSS or HostAP modes.
   2457  */
   2458 static int
   2459 wpi_setup_beacon(struct wpi_softc *sc, struct ieee80211_node *ni)
   2460 {
   2461 	struct ieee80211com *ic = &sc->sc_ic;
   2462 	struct wpi_tx_ring *ring = &sc->cmdq;
   2463 	struct wpi_tx_desc *desc;
   2464 	struct wpi_tx_data *data;
   2465 	struct wpi_tx_cmd *cmd;
   2466 	struct wpi_cmd_beacon *bcn;
   2467 	struct ieee80211_beacon_offsets bo;
   2468 	struct mbuf *m0;
   2469 	int error;
   2470 
   2471 	desc = &ring->desc[ring->cur];
   2472 	data = &ring->data[ring->cur];
   2473 
   2474 	m0 = ieee80211_beacon_alloc(ic, ni, &bo);
   2475 	if (m0 == NULL) {
   2476 		aprint_error_dev(sc->sc_dev, "could not allocate beacon frame\n");
   2477 		return ENOMEM;
   2478 	}
   2479 
   2480 	cmd = &ring->cmd[ring->cur];
   2481 	cmd->code = WPI_CMD_SET_BEACON;
   2482 	cmd->flags = 0;
   2483 	cmd->qid = ring->qid;
   2484 	cmd->idx = ring->cur;
   2485 
   2486 	bcn = (struct wpi_cmd_beacon *)cmd->data;
   2487 	memset(bcn, 0, sizeof (struct wpi_cmd_beacon));
   2488 	bcn->id = WPI_ID_BROADCAST;
   2489 	bcn->ofdm_mask = 0xff;
   2490 	bcn->cck_mask = 0x0f;
   2491 	bcn->lifetime = htole32(WPI_LIFETIME_INFINITE);
   2492 	bcn->len = htole16(m0->m_pkthdr.len);
   2493 	bcn->rate = (ic->ic_curmode == IEEE80211_MODE_11A) ?
   2494 		wpi_plcp_signal(12) : wpi_plcp_signal(2);
   2495 	bcn->flags = htole32(WPI_TX_AUTO_SEQ | WPI_TX_INSERT_TSTAMP);
   2496 
   2497 	/* save and trim IEEE802.11 header */
   2498 	m_copydata(m0, 0, sizeof (struct ieee80211_frame), (void *)&bcn->wh);
   2499 	m_adj(m0, sizeof (struct ieee80211_frame));
   2500 
   2501 	/* assume beacon frame is contiguous */
   2502 	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
   2503 		BUS_DMA_READ | BUS_DMA_NOWAIT);
   2504 	if (error) {
   2505 		aprint_error_dev(sc->sc_dev, "could not map beacon\n");
   2506 		m_freem(m0);
   2507 		return error;
   2508 	}
   2509 
   2510 	data->m = m0;
   2511 
   2512 	/* first scatter/gather segment is used by the beacon command */
   2513 	desc->flags = htole32(WPI_PAD32(m0->m_pkthdr.len) << 28 | 2 << 24);
   2514 	desc->segs[0].addr = htole32(ring->cmd_dma.paddr +
   2515 		ring->cur * sizeof (struct wpi_tx_cmd));
   2516 	desc->segs[0].len  = htole32(4 + sizeof (struct wpi_cmd_beacon));
   2517 	desc->segs[1].addr = htole32(data->map->dm_segs[0].ds_addr);
   2518 	desc->segs[1].len  = htole32(data->map->dm_segs[0].ds_len);
   2519 
   2520 	/* kick cmd ring */
   2521 	ring->cur = (ring->cur + 1) % WPI_CMD_RING_COUNT;
   2522 	WPI_WRITE(sc, WPI_TX_WIDX, ring->qid << 8 | ring->cur);
   2523 
   2524 	return 0;
   2525 }
   2526 
   2527 static int
   2528 wpi_auth(struct wpi_softc *sc)
   2529 {
   2530 	struct ieee80211com *ic = &sc->sc_ic;
   2531 	struct ieee80211_node *ni = ic->ic_bss;
   2532 	struct wpi_node_info node;
   2533 	int error;
   2534 
   2535 	/* update adapter's configuration */
   2536 	IEEE80211_ADDR_COPY(sc->config.bssid, ni->ni_bssid);
   2537 	sc->config.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
   2538 	sc->config.flags = htole32(WPI_CONFIG_TSF);
   2539 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) {
   2540 		sc->config.flags |= htole32(WPI_CONFIG_AUTO |
   2541 		    WPI_CONFIG_24GHZ);
   2542 	}
   2543 	switch (ic->ic_curmode) {
   2544 	case IEEE80211_MODE_11A:
   2545 		sc->config.cck_mask  = 0;
   2546 		sc->config.ofdm_mask = 0x15;
   2547 		break;
   2548 	case IEEE80211_MODE_11B:
   2549 		sc->config.cck_mask  = 0x03;
   2550 		sc->config.ofdm_mask = 0;
   2551 		break;
   2552 	default:	/* assume 802.11b/g */
   2553 		sc->config.cck_mask  = 0x0f;
   2554 		sc->config.ofdm_mask = 0x15;
   2555 	}
   2556 
   2557 	DPRINTF(("config chan %d flags %x cck %x ofdm %x\n", sc->config.chan,
   2558 		sc->config.flags, sc->config.cck_mask, sc->config.ofdm_mask));
   2559 	error = wpi_cmd(sc, WPI_CMD_CONFIGURE, &sc->config,
   2560 		sizeof (struct wpi_config), 1);
   2561 	if (error != 0) {
   2562 		aprint_error_dev(sc->sc_dev, "could not configure\n");
   2563 		return error;
   2564 	}
   2565 
   2566 	/* configuration has changed, set Tx power accordingly */
   2567 	if ((error = wpi_set_txpower(sc, ni->ni_chan, 1)) != 0) {
   2568 		aprint_error_dev(sc->sc_dev, "could not set Tx power\n");
   2569 		return error;
   2570 	}
   2571 
   2572 	/* add default node */
   2573 	memset(&node, 0, sizeof node);
   2574 	IEEE80211_ADDR_COPY(node.bssid, ni->ni_bssid);
   2575 	node.id = WPI_ID_BSS;
   2576 	node.rate = (ic->ic_curmode == IEEE80211_MODE_11A) ?
   2577 	    wpi_plcp_signal(12) : wpi_plcp_signal(2);
   2578 	node.action = htole32(WPI_ACTION_SET_RATE);
   2579 	node.antenna = WPI_ANTENNA_BOTH;
   2580 	error = wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, 1);
   2581 	if (error != 0) {
   2582 		aprint_error_dev(sc->sc_dev, "could not add BSS node\n");
   2583 		return error;
   2584 	}
   2585 
   2586 	return 0;
   2587 }
   2588 
   2589 /*
   2590  * Send a scan request to the firmware.  Since this command is huge, we map it
   2591  * into a mbuf instead of using the pre-allocated set of commands.
   2592  */
   2593 static int
   2594 wpi_scan(struct wpi_softc *sc, uint16_t flags)
   2595 {
   2596 	struct ieee80211com *ic = &sc->sc_ic;
   2597 	struct wpi_tx_ring *ring = &sc->cmdq;
   2598 	struct wpi_tx_desc *desc;
   2599 	struct wpi_tx_data *data;
   2600 	struct wpi_tx_cmd *cmd;
   2601 	struct wpi_scan_hdr *hdr;
   2602 	struct wpi_scan_chan *chan;
   2603 	struct ieee80211_frame *wh;
   2604 	struct ieee80211_rateset *rs;
   2605 	struct ieee80211_channel *c;
   2606 	enum ieee80211_phymode mode;
   2607 	uint8_t *frm;
   2608 	int nrates, pktlen, error;
   2609 
   2610 	desc = &ring->desc[ring->cur];
   2611 	data = &ring->data[ring->cur];
   2612 
   2613 	MGETHDR(data->m, M_DONTWAIT, MT_DATA);
   2614 	if (data->m == NULL) {
   2615 		aprint_error_dev(sc->sc_dev,
   2616 						"could not allocate mbuf for scan command\n");
   2617 		return ENOMEM;
   2618 	}
   2619 
   2620 	MCLGET(data->m, M_DONTWAIT);
   2621 	if (!(data->m->m_flags & M_EXT)) {
   2622 		m_freem(data->m);
   2623 		data->m = NULL;
   2624 		aprint_error_dev(sc->sc_dev,
   2625 						 "could not allocate mbuf for scan command\n");
   2626 		return ENOMEM;
   2627 	}
   2628 
   2629 	cmd = mtod(data->m, struct wpi_tx_cmd *);
   2630 	cmd->code = WPI_CMD_SCAN;
   2631 	cmd->flags = 0;
   2632 	cmd->qid = ring->qid;
   2633 	cmd->idx = ring->cur;
   2634 
   2635 	hdr = (struct wpi_scan_hdr *)cmd->data;
   2636 	memset(hdr, 0, sizeof (struct wpi_scan_hdr));
   2637 	hdr->txflags = htole32(WPI_TX_AUTO_SEQ);
   2638 	hdr->id = WPI_ID_BROADCAST;
   2639 	hdr->lifetime = htole32(WPI_LIFETIME_INFINITE);
   2640 
   2641 	/*
   2642 	 * Move to the next channel if no packets are received within 5 msecs
   2643 	 * after sending the probe request (this helps to reduce the duration
   2644 	 * of active scans).
   2645 	 */
   2646 	hdr->quiet = htole16(5);        /* timeout in milliseconds */
   2647 	hdr->plcp_threshold = htole16(1);	/* min # of packets */
   2648 
   2649 	if (flags & IEEE80211_CHAN_A) {
   2650 		hdr->crc_threshold = htole16(1);
   2651 		/* send probe requests at 6Mbps */
   2652 		hdr->rate = wpi_plcp_signal(12);
   2653 	} else {
   2654 		hdr->flags = htole32(WPI_CONFIG_24GHZ | WPI_CONFIG_AUTO);
   2655 		/* send probe requests at 1Mbps */
   2656 		hdr->rate = wpi_plcp_signal(2);
   2657 	}
   2658 
   2659 	/* for directed scans, firmware inserts the essid IE itself */
   2660 	hdr->essid[0].id  = IEEE80211_ELEMID_SSID;
   2661 	hdr->essid[0].len = ic->ic_des_esslen;
   2662 	memcpy(hdr->essid[0].data, ic->ic_des_essid, ic->ic_des_esslen);
   2663 
   2664 	/*
   2665 	 * Build a probe request frame.  Most of the following code is a
   2666 	 * copy & paste of what is done in net80211.
   2667 	 */
   2668 	wh = (struct ieee80211_frame *)(hdr + 1);
   2669 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
   2670 		IEEE80211_FC0_SUBTYPE_PROBE_REQ;
   2671 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
   2672 	IEEE80211_ADDR_COPY(wh->i_addr1, etherbroadcastaddr);
   2673 	IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
   2674 	IEEE80211_ADDR_COPY(wh->i_addr3, etherbroadcastaddr);
   2675 	*(u_int16_t *)&wh->i_dur[0] = 0;	/* filled by h/w */
   2676 	*(u_int16_t *)&wh->i_seq[0] = 0;	/* filled by h/w */
   2677 
   2678 	frm = (uint8_t *)(wh + 1);
   2679 
   2680 	/* add empty essid IE (firmware generates it for directed scans) */
   2681 	*frm++ = IEEE80211_ELEMID_SSID;
   2682 	*frm++ = 0;
   2683 
   2684 	mode = ieee80211_chan2mode(ic, ic->ic_ibss_chan);
   2685 	rs = &ic->ic_sup_rates[mode];
   2686 
   2687 	/* add supported rates IE */
   2688 	*frm++ = IEEE80211_ELEMID_RATES;
   2689 	nrates = rs->rs_nrates;
   2690 	if (nrates > IEEE80211_RATE_SIZE)
   2691 		nrates = IEEE80211_RATE_SIZE;
   2692 	*frm++ = nrates;
   2693 	memcpy(frm, rs->rs_rates, nrates);
   2694 	frm += nrates;
   2695 
   2696 	/* add supported xrates IE */
   2697 	if (rs->rs_nrates > IEEE80211_RATE_SIZE) {
   2698 		nrates = rs->rs_nrates - IEEE80211_RATE_SIZE;
   2699 		*frm++ = IEEE80211_ELEMID_XRATES;
   2700 		*frm++ = nrates;
   2701 		memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates);
   2702 		frm += nrates;
   2703 	}
   2704 
   2705 	/* setup length of probe request */
   2706 	hdr->paylen = htole16(frm - (uint8_t *)wh);
   2707 
   2708 	chan = (struct wpi_scan_chan *)frm;
   2709 	for (c  = &ic->ic_channels[1];
   2710 	     c <= &ic->ic_channels[IEEE80211_CHAN_MAX]; c++) {
   2711 		if ((c->ic_flags & flags) != flags)
   2712 			continue;
   2713 
   2714 		chan->chan = ieee80211_chan2ieee(ic, c);
   2715 		chan->flags = 0;
   2716 		if (!(c->ic_flags & IEEE80211_CHAN_PASSIVE)) {
   2717 			chan->flags |= WPI_CHAN_ACTIVE;
   2718 			if (ic->ic_des_esslen != 0)
   2719 				chan->flags |= WPI_CHAN_DIRECT;
   2720 		}
   2721 		chan->dsp_gain = 0x6e;
   2722 		if (IEEE80211_IS_CHAN_5GHZ(c)) {
   2723 			chan->rf_gain = 0x3b;
   2724 			chan->active = htole16(10);
   2725 			chan->passive = htole16(110);
   2726 		} else {
   2727 			chan->rf_gain = 0x28;
   2728 			chan->active = htole16(20);
   2729 			chan->passive = htole16(120);
   2730 		}
   2731 		hdr->nchan++;
   2732 		chan++;
   2733 
   2734 		frm += sizeof (struct wpi_scan_chan);
   2735 	}
   2736 	hdr->len = htole16(frm - (uint8_t *)hdr);
   2737 	pktlen = frm - (uint8_t *)cmd;
   2738 
   2739 	error = bus_dmamap_load(sc->sc_dmat, data->map, cmd, pktlen,
   2740 		NULL, BUS_DMA_NOWAIT);
   2741 	if (error) {
   2742 		aprint_error_dev(sc->sc_dev, "could not map scan command\n");
   2743 		m_freem(data->m);
   2744 		data->m = NULL;
   2745 		return error;
   2746 	}
   2747 
   2748 	desc->flags = htole32(WPI_PAD32(pktlen) << 28 | 1 << 24);
   2749 	desc->segs[0].addr = htole32(data->map->dm_segs[0].ds_addr);
   2750 	desc->segs[0].len  = htole32(data->map->dm_segs[0].ds_len);
   2751 
   2752 	/* kick cmd ring */
   2753 	ring->cur = (ring->cur + 1) % WPI_CMD_RING_COUNT;
   2754 	WPI_WRITE(sc, WPI_TX_WIDX, ring->qid << 8 | ring->cur);
   2755 
   2756 	return 0;	/* will be notified async. of failure/success */
   2757 }
   2758 
   2759 static int
   2760 wpi_config(struct wpi_softc *sc)
   2761 {
   2762 	struct ieee80211com *ic = &sc->sc_ic;
   2763 	struct ifnet *ifp = ic->ic_ifp;
   2764 	struct wpi_power power;
   2765 	struct wpi_bluetooth bluetooth;
   2766 	struct wpi_node_info node;
   2767 	int error;
   2768 
   2769 	memset(&power, 0, sizeof power);
   2770 	power.flags = htole32(WPI_POWER_CAM | 0x8);
   2771 	error = wpi_cmd(sc, WPI_CMD_SET_POWER_MODE, &power, sizeof power, 0);
   2772 	if (error != 0) {
   2773 		aprint_error_dev(sc->sc_dev, "could not set power mode\n");
   2774 		return error;
   2775 	}
   2776 
   2777 	/* configure bluetooth coexistence */
   2778 	memset(&bluetooth, 0, sizeof bluetooth);
   2779 	bluetooth.flags = 3;
   2780 	bluetooth.lead = 0xaa;
   2781 	bluetooth.kill = 1;
   2782 	error = wpi_cmd(sc, WPI_CMD_BLUETOOTH, &bluetooth, sizeof bluetooth,
   2783 		0);
   2784 	if (error != 0) {
   2785 		aprint_error_dev(sc->sc_dev,
   2786 			"could not configure bluetooth coexistence\n");
   2787 		return error;
   2788 	}
   2789 
   2790 	/* configure adapter */
   2791 	memset(&sc->config, 0, sizeof (struct wpi_config));
   2792 	IEEE80211_ADDR_COPY(ic->ic_myaddr, CLLADDR(ifp->if_sadl));
   2793 	IEEE80211_ADDR_COPY(sc->config.myaddr, ic->ic_myaddr);
   2794 	/*set default channel*/
   2795 	sc->config.chan = ieee80211_chan2ieee(ic, ic->ic_ibss_chan);
   2796 	sc->config.flags = htole32(WPI_CONFIG_TSF);
   2797 	if (IEEE80211_IS_CHAN_2GHZ(ic->ic_ibss_chan)) {
   2798 		sc->config.flags |= htole32(WPI_CONFIG_AUTO |
   2799 		    WPI_CONFIG_24GHZ);
   2800 	}
   2801 	sc->config.filter = 0;
   2802 	switch (ic->ic_opmode) {
   2803 	case IEEE80211_M_STA:
   2804 		sc->config.mode = WPI_MODE_STA;
   2805 		sc->config.filter |= htole32(WPI_FILTER_MULTICAST);
   2806 		break;
   2807 	case IEEE80211_M_IBSS:
   2808 	case IEEE80211_M_AHDEMO:
   2809 		sc->config.mode = WPI_MODE_IBSS;
   2810 		break;
   2811 	case IEEE80211_M_HOSTAP:
   2812 		sc->config.mode = WPI_MODE_HOSTAP;
   2813 		break;
   2814 	case IEEE80211_M_MONITOR:
   2815 		sc->config.mode = WPI_MODE_MONITOR;
   2816 		sc->config.filter |= htole32(WPI_FILTER_MULTICAST |
   2817 			WPI_FILTER_CTL | WPI_FILTER_PROMISC);
   2818 		break;
   2819 	}
   2820 	sc->config.cck_mask  = 0x0f;	/* not yet negotiated */
   2821 	sc->config.ofdm_mask = 0xff;	/* not yet negotiated */
   2822 	error = wpi_cmd(sc, WPI_CMD_CONFIGURE, &sc->config,
   2823 		sizeof (struct wpi_config), 0);
   2824 	if (error != 0) {
   2825 		aprint_error_dev(sc->sc_dev, "configure command failed\n");
   2826 		return error;
   2827 	}
   2828 
   2829 	/* configuration has changed, set Tx power accordingly */
   2830 	if ((error = wpi_set_txpower(sc, ic->ic_ibss_chan, 0)) != 0) {
   2831 		aprint_error_dev(sc->sc_dev, "could not set Tx power\n");
   2832 		return error;
   2833 	}
   2834 
   2835 	/* add broadcast node */
   2836 	memset(&node, 0, sizeof node);
   2837 	IEEE80211_ADDR_COPY(node.bssid, etherbroadcastaddr);
   2838 	node.id = WPI_ID_BROADCAST;
   2839 	node.rate = wpi_plcp_signal(2);
   2840 	node.action = htole32(WPI_ACTION_SET_RATE);
   2841 	node.antenna = WPI_ANTENNA_BOTH;
   2842 	error = wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, 0);
   2843 	if (error != 0) {
   2844 		aprint_error_dev(sc->sc_dev, "could not add broadcast node\n");
   2845 		return error;
   2846 	}
   2847 
   2848 	if ((error = wpi_mrr_setup(sc)) != 0) {
   2849 		aprint_error_dev(sc->sc_dev, "could not setup MRR\n");
   2850 		return error;
   2851 	}
   2852 
   2853 	return 0;
   2854 }
   2855 
   2856 static void
   2857 wpi_stop_master(struct wpi_softc *sc)
   2858 {
   2859 	uint32_t tmp;
   2860 	int ntries;
   2861 
   2862 	tmp = WPI_READ(sc, WPI_RESET);
   2863 	WPI_WRITE(sc, WPI_RESET, tmp | WPI_STOP_MASTER);
   2864 
   2865 	tmp = WPI_READ(sc, WPI_GPIO_CTL);
   2866 	if ((tmp & WPI_GPIO_PWR_STATUS) == WPI_GPIO_PWR_SLEEP)
   2867 		return;	/* already asleep */
   2868 
   2869 	for (ntries = 0; ntries < 100; ntries++) {
   2870 		if (WPI_READ(sc, WPI_RESET) & WPI_MASTER_DISABLED)
   2871 			break;
   2872 		DELAY(10);
   2873 	}
   2874 	if (ntries == 100) {
   2875 		aprint_error_dev(sc->sc_dev, "timeout waiting for master\n");
   2876 	}
   2877 }
   2878 
   2879 static int
   2880 wpi_power_up(struct wpi_softc *sc)
   2881 {
   2882 	uint32_t tmp;
   2883 	int ntries;
   2884 
   2885 	wpi_mem_lock(sc);
   2886 	tmp = wpi_mem_read(sc, WPI_MEM_POWER);
   2887 	wpi_mem_write(sc, WPI_MEM_POWER, tmp & ~0x03000000);
   2888 	wpi_mem_unlock(sc);
   2889 
   2890 	for (ntries = 0; ntries < 5000; ntries++) {
   2891 		if (WPI_READ(sc, WPI_GPIO_STATUS) & WPI_POWERED)
   2892 			break;
   2893 		DELAY(10);
   2894 	}
   2895 	if (ntries == 5000) {
   2896 		aprint_error_dev(sc->sc_dev, "timeout waiting for NIC to power up\n");
   2897 		return ETIMEDOUT;
   2898 	}
   2899 	return 0;
   2900 }
   2901 
   2902 static int
   2903 wpi_reset(struct wpi_softc *sc)
   2904 {
   2905 	uint32_t tmp;
   2906 	int ntries;
   2907 
   2908 	/* clear any pending interrupts */
   2909 	WPI_WRITE(sc, WPI_INTR, 0xffffffff);
   2910 
   2911 	tmp = WPI_READ(sc, WPI_PLL_CTL);
   2912 	WPI_WRITE(sc, WPI_PLL_CTL, tmp | WPI_PLL_INIT);
   2913 
   2914 	tmp = WPI_READ(sc, WPI_CHICKEN);
   2915 	WPI_WRITE(sc, WPI_CHICKEN, tmp | WPI_CHICKEN_RXNOLOS);
   2916 
   2917 	tmp = WPI_READ(sc, WPI_GPIO_CTL);
   2918 	WPI_WRITE(sc, WPI_GPIO_CTL, tmp | WPI_GPIO_INIT);
   2919 
   2920 	/* wait for clock stabilization */
   2921 	for (ntries = 0; ntries < 1000; ntries++) {
   2922 		if (WPI_READ(sc, WPI_GPIO_CTL) & WPI_GPIO_CLOCK)
   2923 			break;
   2924 		DELAY(10);
   2925 	}
   2926 	if (ntries == 1000) {
   2927 		aprint_error_dev(sc->sc_dev,
   2928 						 "timeout waiting for clock stabilization\n");
   2929 		return ETIMEDOUT;
   2930 	}
   2931 
   2932 	/* initialize EEPROM */
   2933 	tmp = WPI_READ(sc, WPI_EEPROM_STATUS);
   2934 	if ((tmp & WPI_EEPROM_VERSION) == 0) {
   2935 		aprint_error_dev(sc->sc_dev, "EEPROM not found\n");
   2936 		return EIO;
   2937 	}
   2938 	WPI_WRITE(sc, WPI_EEPROM_STATUS, tmp & ~WPI_EEPROM_LOCKED);
   2939 
   2940 	return 0;
   2941 }
   2942 
   2943 static void
   2944 wpi_hw_config(struct wpi_softc *sc)
   2945 {
   2946 	uint32_t rev, hw;
   2947 
   2948 	/* voodoo from the reference driver */
   2949 	hw = WPI_READ(sc, WPI_HWCONFIG);
   2950 
   2951 	rev = pci_conf_read(sc->sc_pct, sc->sc_pcitag, PCI_CLASS_REG);
   2952 	rev = PCI_REVISION(rev);
   2953 	if ((rev & 0xc0) == 0x40)
   2954 		hw |= WPI_HW_ALM_MB;
   2955 	else if (!(rev & 0x80))
   2956 		hw |= WPI_HW_ALM_MM;
   2957 
   2958 	if (sc->cap == 0x80)
   2959 		hw |= WPI_HW_SKU_MRC;
   2960 
   2961 	hw &= ~WPI_HW_REV_D;
   2962 	if ((le16toh(sc->rev) & 0xf0) == 0xd0)
   2963 		hw |= WPI_HW_REV_D;
   2964 
   2965 	if (sc->type > 1)
   2966 		hw |= WPI_HW_TYPE_B;
   2967 
   2968 	DPRINTF(("setting h/w config %x\n", hw));
   2969 	WPI_WRITE(sc, WPI_HWCONFIG, hw);
   2970 }
   2971 
   2972 static int
   2973 wpi_init(struct ifnet *ifp)
   2974 {
   2975 	struct wpi_softc *sc = ifp->if_softc;
   2976 	struct ieee80211com *ic = &sc->sc_ic;
   2977 	uint32_t tmp;
   2978 	int qid, ntries, error;
   2979 
   2980 	wpi_stop(ifp,1);
   2981 	(void)wpi_reset(sc);
   2982 
   2983 	wpi_mem_lock(sc);
   2984 	wpi_mem_write(sc, WPI_MEM_CLOCK1, 0xa00);
   2985 	DELAY(20);
   2986 	tmp = wpi_mem_read(sc, WPI_MEM_PCIDEV);
   2987 	wpi_mem_write(sc, WPI_MEM_PCIDEV, tmp | 0x800);
   2988 	wpi_mem_unlock(sc);
   2989 
   2990 	(void)wpi_power_up(sc);
   2991 	wpi_hw_config(sc);
   2992 
   2993 	/* init Rx ring */
   2994 	wpi_mem_lock(sc);
   2995 	WPI_WRITE(sc, WPI_RX_BASE, sc->rxq.desc_dma.paddr);
   2996 	WPI_WRITE(sc, WPI_RX_RIDX_PTR, sc->shared_dma.paddr +
   2997 	    offsetof(struct wpi_shared, next));
   2998 	WPI_WRITE(sc, WPI_RX_WIDX, (WPI_RX_RING_COUNT - 1) & ~7);
   2999 	WPI_WRITE(sc, WPI_RX_CONFIG, 0xa9601010);
   3000 	wpi_mem_unlock(sc);
   3001 
   3002 	/* init Tx rings */
   3003 	wpi_mem_lock(sc);
   3004 	wpi_mem_write(sc, WPI_MEM_MODE, 2); /* bypass mode */
   3005 	wpi_mem_write(sc, WPI_MEM_RA, 1);   /* enable RA0 */
   3006 	wpi_mem_write(sc, WPI_MEM_TXCFG, 0x3f); /* enable all 6 Tx rings */
   3007 	wpi_mem_write(sc, WPI_MEM_BYPASS1, 0x10000);
   3008 	wpi_mem_write(sc, WPI_MEM_BYPASS2, 0x30002);
   3009 	wpi_mem_write(sc, WPI_MEM_MAGIC4, 4);
   3010 	wpi_mem_write(sc, WPI_MEM_MAGIC5, 5);
   3011 
   3012 	WPI_WRITE(sc, WPI_TX_BASE_PTR, sc->shared_dma.paddr);
   3013 	WPI_WRITE(sc, WPI_MSG_CONFIG, 0xffff05a5);
   3014 
   3015 	for (qid = 0; qid < 6; qid++) {
   3016 		WPI_WRITE(sc, WPI_TX_CTL(qid), 0);
   3017 		WPI_WRITE(sc, WPI_TX_BASE(qid), 0);
   3018 		WPI_WRITE(sc, WPI_TX_CONFIG(qid), 0x80200008);
   3019 	}
   3020 	wpi_mem_unlock(sc);
   3021 
   3022 	/* clear "radio off" and "disable command" bits (reversed logic) */
   3023 	WPI_WRITE(sc, WPI_UCODE_CLR, WPI_RADIO_OFF);
   3024 	WPI_WRITE(sc, WPI_UCODE_CLR, WPI_DISABLE_CMD);
   3025 
   3026 	/* clear any pending interrupts */
   3027 	WPI_WRITE(sc, WPI_INTR, 0xffffffff);
   3028 	/* enable interrupts */
   3029 	WPI_WRITE(sc, WPI_MASK, WPI_INTR_MASK);
   3030 
   3031 	/* not sure why/if this is necessary... */
   3032 	WPI_WRITE(sc, WPI_UCODE_CLR, WPI_RADIO_OFF);
   3033 	WPI_WRITE(sc, WPI_UCODE_CLR, WPI_RADIO_OFF);
   3034 
   3035 	if ((error = wpi_load_firmware(sc)) != 0) {
   3036 		aprint_error_dev(sc->sc_dev, "could not load firmware\n");
   3037 		goto fail1;
   3038 	}
   3039 
   3040 	/* wait for thermal sensors to calibrate */
   3041 	for (ntries = 0; ntries < 1000; ntries++) {
   3042 		if ((sc->temp = (int)WPI_READ(sc, WPI_TEMPERATURE)) != 0)
   3043 			break;
   3044 		DELAY(10);
   3045 	}
   3046 	if (ntries == 1000) {
   3047 		aprint_error_dev(sc->sc_dev,
   3048 						 "timeout waiting for thermal sensors calibration\n");
   3049 		error = ETIMEDOUT;
   3050 		goto fail1;
   3051 	}
   3052 
   3053 	DPRINTF(("temperature %d\n", sc->temp));
   3054 
   3055 	if ((error = wpi_config(sc)) != 0) {
   3056 		aprint_error_dev(sc->sc_dev, "could not configure device\n");
   3057 		goto fail1;
   3058 	}
   3059 
   3060 	ifp->if_flags &= ~IFF_OACTIVE;
   3061 	ifp->if_flags |= IFF_RUNNING;
   3062 
   3063 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
   3064 		if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
   3065 			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
   3066 	}
   3067 	else
   3068 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
   3069 
   3070 	return 0;
   3071 
   3072 fail1:	wpi_stop(ifp, 1);
   3073 	return error;
   3074 }
   3075 
   3076 
   3077 static void
   3078 wpi_stop(struct ifnet *ifp, int disable)
   3079 {
   3080 	struct wpi_softc *sc = ifp->if_softc;
   3081 	struct ieee80211com *ic = &sc->sc_ic;
   3082 	uint32_t tmp;
   3083 	int ac;
   3084 
   3085 	ifp->if_timer = sc->sc_tx_timer = 0;
   3086 	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
   3087 
   3088 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
   3089 
   3090 	/* disable interrupts */
   3091 	WPI_WRITE(sc, WPI_MASK, 0);
   3092 	WPI_WRITE(sc, WPI_INTR, WPI_INTR_MASK);
   3093 	WPI_WRITE(sc, WPI_INTR_STATUS, 0xff);
   3094 	WPI_WRITE(sc, WPI_INTR_STATUS, 0x00070000);
   3095 
   3096 	wpi_mem_lock(sc);
   3097 	wpi_mem_write(sc, WPI_MEM_MODE, 0);
   3098 	wpi_mem_unlock(sc);
   3099 
   3100 	/* reset all Tx rings */
   3101 	for (ac = 0; ac < 4; ac++)
   3102 		wpi_reset_tx_ring(sc, &sc->txq[ac]);
   3103 	wpi_reset_tx_ring(sc, &sc->cmdq);
   3104 
   3105 	/* reset Rx ring */
   3106 	wpi_reset_rx_ring(sc, &sc->rxq);
   3107 
   3108 	wpi_mem_lock(sc);
   3109 	wpi_mem_write(sc, WPI_MEM_CLOCK2, 0x200);
   3110 	wpi_mem_unlock(sc);
   3111 
   3112 	DELAY(5);
   3113 
   3114 	wpi_stop_master(sc);
   3115 
   3116 	tmp = WPI_READ(sc, WPI_RESET);
   3117 	WPI_WRITE(sc, WPI_RESET, tmp | WPI_SW_RESET);
   3118 }
   3119 
   3120 static bool
   3121 wpi_resume(device_t dv)
   3122 {
   3123 	struct wpi_softc *sc = device_private(dv);
   3124 
   3125 	pci_disable_retry(sc->sc_pct, sc->sc_pcitag);
   3126 	(void)wpi_reset(sc);
   3127 
   3128 	return true;
   3129 }
   3130