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