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