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