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