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