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