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