Home | History | Annotate | Line # | Download | only in pci
if_iwn.c revision 1.4
      1 /*	$NetBSD: if_iwn.c,v 1.4 2008/02/10 10:33:10 skrll Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 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_iwn.c,v 1.4 2008/02/10 10:33:10 skrll Exp $");
     22 
     23 
     24 /*
     25  * Driver for Intel Wireless WiFi Link 4965AGN 802.11 network adapters.
     26  */
     27 
     28 #include "bpfilter.h"
     29 
     30 #include <sys/param.h>
     31 #include <sys/sockio.h>
     32 #include <sys/sysctl.h>
     33 #include <sys/mbuf.h>
     34 #include <sys/kernel.h>
     35 #include <sys/socket.h>
     36 #include <sys/systm.h>
     37 #include <sys/malloc.h>
     38 #include <sys/conf.h>
     39 #include <sys/kauth.h>
     40 #include <sys/callout.h>
     41 
     42 #include <machine/bus.h>
     43 #include <machine/endian.h>
     44 #include <machine/intr.h>
     45 
     46 #include <dev/pci/pcireg.h>
     47 #include <dev/pci/pcivar.h>
     48 #include <dev/pci/pcidevs.h>
     49 
     50 #if NBPFILTER > 0
     51 #include <net/bpf.h>
     52 #endif
     53 #include <net/if.h>
     54 #include <net/if_arp.h>
     55 #include <net/if_dl.h>
     56 #include <net/if_media.h>
     57 #include <net/if_types.h>
     58 
     59 #include <netinet/in.h>
     60 #include <netinet/in_systm.h>
     61 #include <netinet/in_var.h>
     62 #include <net/if_ether.h>
     63 #include <netinet/ip.h>
     64 
     65 #include <net80211/ieee80211_var.h>
     66 #include <net80211/ieee80211_amrr.h>
     67 #include <net80211/ieee80211_radiotap.h>
     68 
     69 #include <dev/firmload.h>
     70 
     71 #include <dev/pci/if_iwnreg.h>
     72 #include <dev/pci/if_iwnvar.h>
     73 
     74 #if 0
     75 static const struct pci_matchid iwn_devices[] = {
     76 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_PRO_WL_4965AGN_1 },
     77 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_PRO_WL_4965AGN_2 }
     78 };
     79 #endif
     80 
     81 /*
     82  * Supported rates for 802.11a/b/g modes (in 500Kbps unit).
     83  */
     84 static const struct ieee80211_rateset iwn_rateset_11a =
     85 	{ 8, { 12, 18, 24, 36, 48, 72, 96, 108 } };
     86 
     87 static const struct ieee80211_rateset iwn_rateset_11b =
     88 	{ 4, { 2, 4, 11, 22 } };
     89 
     90 static const struct ieee80211_rateset iwn_rateset_11g =
     91 	{ 12, { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 } };
     92 
     93 
     94 #define EDCA_NUM_AC     4
     95 static int		iwn_match(device_t , struct cfdata *, void *);
     96 static void		iwn_attach(device_t , device_t, void *);
     97 static int		iwn_detach(device_t, int);
     98 
     99 static void		iwn_radiotap_attach(struct iwn_softc *);
    100 static int		iwn_dma_contig_alloc(bus_dma_tag_t, struct iwn_dma_info *,
    101     void **, bus_size_t, bus_size_t, int);
    102 static void		iwn_dma_contig_free(struct iwn_dma_info *);
    103 static int		iwn_alloc_shared(struct iwn_softc *);
    104 static void		iwn_free_shared(struct iwn_softc *);
    105 static int		iwn_alloc_kw(struct iwn_softc *);
    106 static void		iwn_free_kw(struct iwn_softc *);
    107 static int		iwn_alloc_fwmem(struct iwn_softc *);
    108 static void		iwn_free_fwmem(struct iwn_softc *);
    109 static struct		iwn_rbuf *iwn_alloc_rbuf(struct iwn_softc *);
    110 static void		iwn_free_rbuf(struct mbuf *, void *, size_t, void *);
    111 static int		iwn_alloc_rpool(struct iwn_softc *);
    112 static void		iwn_free_rpool(struct iwn_softc *);
    113 static int		iwn_alloc_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
    114 static void		iwn_reset_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
    115 static void		iwn_free_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
    116 static int		iwn_alloc_tx_ring(struct iwn_softc *, struct iwn_tx_ring *,
    117     int, int);
    118 static void		iwn_reset_tx_ring(struct iwn_softc *, struct iwn_tx_ring *);
    119 static void		iwn_free_tx_ring(struct iwn_softc *, struct iwn_tx_ring *);
    120 static struct		ieee80211_node *iwn_node_alloc(struct ieee80211_node_table *);
    121 static void		iwn_newassoc(struct ieee80211_node *, int);
    122 static int		iwn_media_change(struct ifnet *);
    123 static int		iwn_newstate(struct ieee80211com *, enum ieee80211_state, int);
    124 static void		iwn_mem_lock(struct iwn_softc *);
    125 static void		iwn_mem_unlock(struct iwn_softc *);
    126 static uint32_t	iwn_mem_read(struct iwn_softc *, uint32_t);
    127 static void		iwn_mem_write(struct iwn_softc *, uint32_t, uint32_t);
    128 static void		iwn_mem_write_region_4(struct iwn_softc *, uint32_t,
    129     const uint32_t *, int);
    130 static int		iwn_eeprom_lock(struct iwn_softc *);
    131 static void		iwn_eeprom_unlock(struct iwn_softc *);
    132 static int		iwn_read_prom_data(struct iwn_softc *, uint32_t, void *, int);
    133 static int		iwn_load_microcode(struct iwn_softc *, const uint8_t *, int);
    134 static int		iwn_load_firmware(struct iwn_softc *);
    135 static void		iwn_calib_timeout(void *);
    136 static void		iwn_iter_func(void *, struct ieee80211_node *);
    137 static void		iwn_ampdu_rx_start(struct iwn_softc *, struct iwn_rx_desc *);
    138 static void		iwn_rx_intr(struct iwn_softc *, struct iwn_rx_desc *,
    139     struct iwn_rx_data *);
    140 static void		iwn_rx_statistics(struct iwn_softc *, struct iwn_rx_desc *);
    141 static void		iwn_tx_intr(struct iwn_softc *, struct iwn_rx_desc *);
    142 static void		iwn_cmd_intr(struct iwn_softc *, struct iwn_rx_desc *);
    143 static void		iwn_notif_intr(struct iwn_softc *);
    144 static int		iwn_intr(void *);
    145 static void		iwn_read_eeprom(struct iwn_softc *);
    146 static void		iwn_read_eeprom_channels(struct iwn_softc *, int);
    147 static void		iwn_print_power_group(struct iwn_softc *, int);
    148 static uint8_t		iwn_plcp_signal(int);
    149 static int		iwn_tx_data(struct iwn_softc *, struct mbuf *,
    150     struct ieee80211_node *, int);
    151 static void		iwn_start(struct ifnet *);
    152 static void		iwn_watchdog(struct ifnet *);
    153 static int		iwn_ioctl(struct ifnet *, u_long, void *);
    154 static int		iwn_cmd(struct iwn_softc *, int, const void *, int, int);
    155 static int              iwn_wme_update(struct ieee80211com *);
    156 static int		iwn_setup_node_mrr(struct iwn_softc *, uint8_t, int);
    157 static void		iwn_set_led(struct iwn_softc *, uint8_t, uint8_t, uint8_t);
    158 static int		iwn_set_critical_temp(struct iwn_softc *);
    159 static void		iwn_enable_tsf(struct iwn_softc *, struct ieee80211_node *);
    160 static void		iwn_power_calibration(struct iwn_softc *, int);
    161 static int		iwn_set_txpower(struct iwn_softc *,
    162     struct ieee80211_channel *, int);
    163 static int		iwn_get_rssi(const struct iwn_rx_stat *);
    164 static int		iwn_get_noise(const struct iwn_rx_general_stats *);
    165 static int		iwn_get_temperature(struct iwn_softc *);
    166 static int		iwn_init_sensitivity(struct iwn_softc *);
    167 static void		iwn_compute_differential_gain(struct iwn_softc *,
    168     const struct iwn_rx_general_stats *);
    169 static void		iwn_tune_sensitivity(struct iwn_softc *,
    170     const struct iwn_rx_stats *);
    171 static int		iwn_send_sensitivity(struct iwn_softc *);
    172 /*static int              iwn_setup_beacon(struct iwn_softc *, struct ieee80211_node *);*/
    173 static int		iwn_auth(struct iwn_softc *);
    174 static int		iwn_run(struct iwn_softc *);
    175 static int		iwn_scan(struct iwn_softc *, uint16_t);
    176 static int		iwn_config(struct iwn_softc *);
    177 static void		iwn_post_alive(struct iwn_softc *);
    178 static void		iwn_stop_master(struct iwn_softc *);
    179 static int		iwn_reset(struct iwn_softc *);
    180 static void		iwn_hw_config(struct iwn_softc *);
    181 static int		iwn_init(struct ifnet *);
    182 static void		iwn_stop(struct ifnet *, int);
    183 static void		iwn_fix_channel(struct ieee80211com *, struct mbuf *);
    184 static bool		iwn_resume(device_t dv);
    185 
    186 
    187 
    188 #define IWN_DEBUG
    189 
    190 #ifdef IWN_DEBUG
    191 #define DPRINTF(x)	do { if (iwn_debug > 0) printf x; } while (0)
    192 #define DPRINTFN(n, x)	do { if (iwn_debug >= (n)) printf x; } while (0)
    193 int iwn_debug = 2;
    194 #else
    195 #define DPRINTF(x)
    196 #define DPRINTFN(n, x)
    197 #endif
    198 
    199 CFATTACH_DECL_NEW(iwn, sizeof(struct iwn_softc), iwn_match, iwn_attach,
    200     iwn_detach, NULL);
    201 
    202 static int
    203 iwn_match(device_t parent, struct cfdata *match __unused, void *aux)
    204 {
    205 	struct pci_attach_args *pa = aux;
    206 
    207 	if (PCI_VENDOR(pa->pa_id) != PCI_VENDOR_INTEL)
    208 		return 0;
    209 
    210 	if (PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_INTEL_PRO_WL_4965AGN_1 ||
    211 	    PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_INTEL_PRO_WL_4965AGN_2)
    212 		return 1;
    213 
    214 	return 0;
    215 }
    216 
    217 /* Base Address Register */
    218 #define IWN_PCI_BAR0	0x10
    219 
    220 static void
    221 iwn_attach(device_t parent __unused, device_t self, void *aux)
    222 {
    223 	struct iwn_softc *sc = device_private(self);
    224 	struct ieee80211com *ic = &sc->sc_ic;
    225 	struct ifnet *ifp = &sc->sc_ec.ec_if;
    226 	struct pci_attach_args *pa = aux;
    227 	const char *intrstr;
    228 	char devinfo[256];
    229 	pci_intr_handle_t ih;
    230 	pcireg_t memtype, data;
    231 	int i, error, revision;
    232 
    233 	sc->sc_dev = self;
    234 	sc->sc_pct = pa->pa_pc;
    235 	sc->sc_pcitag = pa->pa_tag;
    236 
    237 	callout_init(&sc->calib_to, 0);
    238 	callout_setfunc(&sc->calib_to, iwn_calib_timeout, sc);
    239 
    240 	pci_devinfo(pa->pa_id, pa->pa_class, 0, devinfo, sizeof devinfo);
    241 	revision = PCI_REVISION(pa->pa_class);
    242 	aprint_normal(": %s (rev. 0x%2x)\n", devinfo, revision);
    243 
    244 
    245 	/* clear device specific PCI configuration register 0x41 */
    246 	data = pci_conf_read(sc->sc_pct, sc->sc_pcitag, 0x40);
    247 	data &= ~0x0000ff00;
    248 	pci_conf_write(sc->sc_pct, sc->sc_pcitag, 0x40, data);
    249 
    250 	data = pci_conf_read(sc->sc_pct, sc->sc_pcitag, PCI_COMMAND_STATUS_REG);
    251 	data |= PCI_COMMAND_MASTER_ENABLE;
    252 	pci_conf_write(sc->sc_pct, sc->sc_pcitag, PCI_COMMAND_STATUS_REG, data);
    253 
    254 	/* enable bus-mastering */
    255 	data = pci_conf_read(sc->sc_pct, sc->sc_pcitag, PCI_COMMAND_STATUS_REG);
    256 	data |= PCI_COMMAND_MASTER_ENABLE;
    257 	pci_conf_write(sc->sc_pct, sc->sc_pcitag, PCI_COMMAND_STATUS_REG, data);
    258 
    259 	/* map the register window */
    260 	memtype = pci_mapreg_type(pa->pa_pc, pa->pa_tag, IWN_PCI_BAR0);
    261 	error = pci_mapreg_map(pa, IWN_PCI_BAR0, memtype, 0, &sc->sc_st,
    262 	    &sc->sc_sh, NULL, &sc->sc_sz);
    263 	if (error != 0) {
    264 		aprint_error_dev(self, "could not map memory space\n");
    265 		return;
    266 	}
    267 
    268 	sc->sc_dmat = pa->pa_dmat;
    269 
    270 	if (pci_intr_map(pa, &ih) != 0) {
    271 		aprint_error_dev(self, "could not map interrupt\n");
    272 		return;
    273 	}
    274 
    275 	intrstr = pci_intr_string(sc->sc_pct, ih);
    276 	sc->sc_ih = pci_intr_establish(sc->sc_pct, ih, IPL_NET, iwn_intr, sc);
    277 
    278 	if (sc->sc_ih == NULL) {
    279 		aprint_error_dev(self, "could not establish interrupt");
    280 		if (intrstr != NULL)
    281 			aprint_error(" at %s", intrstr);
    282 		aprint_error("\n");
    283 		return;
    284 	}
    285 	aprint_normal_dev(self, "interrupting at %s\n", intrstr);
    286 
    287 	if (iwn_reset(sc) != 0) {
    288 		aprint_error_dev(self, "could not reset adapter\n");
    289 		return;
    290 	}
    291 
    292 	/*
    293 	 * Allocate DMA memory for firmware transfers.
    294 	 */
    295 	if ((error = iwn_alloc_fwmem(sc)) != 0) {
    296 		aprint_error_dev(self, "could not allocate firmware memory\n");
    297 		return;
    298 	}
    299 
    300 	/*
    301 	 * Allocate a "keep warm" page.
    302 	 */
    303 	if ((error = iwn_alloc_kw(sc)) != 0) {
    304 		aprint_error_dev(self, "could not allocate keep warm page\n");
    305 		goto fail1;
    306 	}
    307 
    308 	/*
    309 	 * Allocate shared area (communication area).
    310 	 */
    311 	if ((error = iwn_alloc_shared(sc)) != 0) {
    312 		aprint_error_dev(self, "could not allocate shared area\n");
    313 		goto fail2;
    314 	}
    315 
    316 	/*
    317 	 * Allocate Rx buffers and Tx/Rx rings.
    318 	 */
    319 	if ((error = iwn_alloc_rpool(sc)) != 0) {
    320 		aprint_error_dev(self, "could not allocate Rx buffers\n");
    321 		goto fail3;
    322 	}
    323 
    324 	for (i = 0; i < IWN_NTXQUEUES; i++) {
    325 		struct iwn_tx_ring *txq = &sc->txq[i];
    326 		error = iwn_alloc_tx_ring(sc, txq, IWN_TX_RING_COUNT, i);
    327 		if (error != 0) {
    328 			aprint_error_dev(self, "could not allocate Tx ring %d\n", i);
    329 			goto fail4;
    330 		}
    331 	}
    332 
    333 	if (iwn_alloc_rx_ring(sc, &sc->rxq) != 0)  {
    334 		aprint_error_dev(self, "could not allocate Rx ring\n");
    335 		goto fail4;
    336 	}
    337 
    338 
    339 	ic->ic_ifp = ifp;
    340 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
    341 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
    342 	ic->ic_state = IEEE80211_S_INIT;
    343 
    344 	/* set device capabilities */
    345 	ic->ic_caps =
    346 	    IEEE80211_C_IBSS |		/* IBSS mode support */
    347 	    IEEE80211_C_WPA  |          /* 802.11i */
    348 	    IEEE80211_C_MONITOR |	/* monitor mode supported */
    349 	    IEEE80211_C_TXPMGT |	/* tx power management */
    350 	    IEEE80211_C_SHSLOT |	/* short slot time supported */
    351 	    IEEE80211_C_SHPREAMBLE|	/* short preamble supported */
    352 	    IEEE80211_C_WME;            /* 802.11e */
    353 
    354 	/* read supported channels and MAC address from EEPROM */
    355 	iwn_read_eeprom(sc);
    356 
    357 	/* set supported .11a, .11b and .11g rates */
    358 	ic->ic_sup_rates[IEEE80211_MODE_11A] = iwn_rateset_11a;
    359 	ic->ic_sup_rates[IEEE80211_MODE_11B] = iwn_rateset_11b;
    360 	ic->ic_sup_rates[IEEE80211_MODE_11G] = iwn_rateset_11g;
    361 
    362 	/* IBSS channel undefined for now */
    363 	ic->ic_ibss_chan = &ic->ic_channels[0];
    364 
    365 	ifp->if_softc = sc;
    366 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
    367 	ifp->if_init = iwn_init;
    368 	ifp->if_stop = iwn_stop;
    369 	ifp->if_ioctl = iwn_ioctl;
    370 	ifp->if_start = iwn_start;
    371 	ifp->if_watchdog = iwn_watchdog;
    372 	IFQ_SET_READY(&ifp->if_snd);
    373 	memcpy(ifp->if_xname, device_xname(self), IFNAMSIZ);
    374 
    375 	if_attach(ifp);
    376 	ieee80211_ifattach(ic);
    377 	ic->ic_node_alloc = iwn_node_alloc;
    378 	ic->ic_newassoc = iwn_newassoc;
    379 	ic->ic_wme.wme_update = iwn_wme_update;
    380 
    381 	/* override state transition machine */
    382 	sc->sc_newstate = ic->ic_newstate;
    383 	ic->ic_newstate = iwn_newstate;
    384 	ieee80211_media_init(ic, iwn_media_change, ieee80211_media_status);
    385 
    386 	sc->amrr.amrr_min_success_threshold =  1;
    387 	sc->amrr.amrr_max_success_threshold = 15;
    388 
    389 	if (!pmf_device_register(self, NULL, iwn_resume))
    390 		aprint_error_dev(self, "couldn't establish power handler\n");
    391 	else
    392 		pmf_class_network_register(self, ifp);
    393 
    394 	iwn_radiotap_attach(sc);
    395 
    396 	ieee80211_announce(ic);
    397 
    398 	return;
    399 
    400 	/* free allocated memory if something failed during attachment */
    401 fail4:	while (--i >= 0)
    402 		iwn_free_tx_ring(sc, &sc->txq[i]);
    403 	iwn_free_rpool(sc);
    404 fail3:	iwn_free_shared(sc);
    405 fail2:	iwn_free_kw(sc);
    406 fail1:	iwn_free_fwmem(sc);
    407 }
    408 
    409 static int
    410 iwn_detach(struct device* self, int flags __unused)
    411 {
    412 	struct iwn_softc *sc = (struct iwn_softc *)self;
    413 	struct ifnet *ifp = sc->sc_ic.ic_ifp;
    414 	int ac;
    415 
    416 	iwn_stop(ifp, 1);
    417 
    418 #if NBPFILTER > 0
    419 	if (ifp != NULL)
    420 		bpfdetach(ifp);
    421 #endif
    422 	ieee80211_ifdetach(&sc->sc_ic);
    423 	if (ifp != NULL)
    424 		if_detach(ifp);
    425 
    426 	for (ac = 0; ac < IWN_NTXQUEUES; ac++)
    427 		iwn_free_tx_ring(sc, &sc->txq[ac]);
    428 	iwn_free_rx_ring(sc, &sc->rxq);
    429 	iwn_free_rpool(sc);
    430 	iwn_free_shared(sc);
    431 
    432 	if (sc->sc_ih != NULL) {
    433 		pci_intr_disestablish(sc->sc_pct, sc->sc_ih);
    434 		sc->sc_ih = NULL;
    435 	}
    436 
    437 	bus_space_unmap(sc->sc_st, sc->sc_sh, sc->sc_sz);
    438 
    439 	return 0;
    440 }
    441 
    442 /*
    443  * Attach the interface to 802.11 radiotap.
    444  */
    445 static void
    446 iwn_radiotap_attach(struct iwn_softc *sc)
    447 {
    448 	struct ifnet *ifp = sc->sc_ic.ic_ifp;
    449 
    450 #if NBPFILTER > 0
    451 	bpfattach2(ifp, DLT_IEEE802_11_RADIO,
    452 	    sizeof (struct ieee80211_frame) + IEEE80211_RADIOTAP_HDRLEN,
    453 	    &sc->sc_drvbpf);
    454 
    455 	sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
    456 	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
    457 	sc->sc_rxtap.wr_ihdr.it_present = htole32(IWN_RX_RADIOTAP_PRESENT);
    458 
    459 	sc->sc_txtap_len = sizeof sc->sc_txtapu;
    460 	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
    461 	sc->sc_txtap.wt_ihdr.it_present = htole32(IWN_TX_RADIOTAP_PRESENT);
    462 #endif
    463 }
    464 
    465 
    466 /*
    467  * Build a beacon frame that the firmware will broadcast periodically in
    468  * IBSS or HostAP modes.
    469  */
    470 #if 0
    471 static int
    472 iwn_setup_beacon(struct iwn_softc *sc, struct ieee80211_node *ni)
    473 {
    474 	struct ieee80211com *ic = &sc->sc_ic;
    475 	struct iwn_tx_ring *ring = &sc->txq[4];
    476 	struct iwn_tx_desc *desc;
    477 	struct iwn_tx_data *data;
    478 	struct iwn_tx_cmd *cmd;
    479 	struct iwn_cmd_beacon *bcn;
    480 	struct ieee80211_beacon_offsets bo;
    481 	struct mbuf *m0;
    482 	bus_addr_t paddr;
    483 	int error;
    484 
    485 	desc = &ring->desc[ring->cur];
    486 	data = &ring->data[ring->cur];
    487 
    488 	m0 = ieee80211_beacon_alloc(ic, ni, &bo);
    489 	if (m0 == NULL) {
    490 		aprint_error_dev(sc->sc_dev, "could not allocate beacon frame\n");
    491 		return ENOMEM;
    492 	}
    493 
    494 	cmd = &ring->cmd[ring->cur];
    495 	cmd->code = IWN_CMD_SET_BEACON;
    496 	cmd->flags = 0;
    497 	cmd->qid = ring->qid;
    498 	cmd->idx = ring->cur;
    499 
    500 	bcn = (struct iwn_cmd_beacon *)cmd->data;
    501 	memset(bcn, 0, sizeof (struct iwn_cmd_beacon));
    502 	bcn->id = IWN_ID_BROADCAST;
    503 	bcn->ofdm_mask = 0xff;
    504 	bcn->cck_mask = 0x0f;
    505 	bcn->lifetime = htole32(IWN_LIFETIME_INFINITE);
    506 	bcn->len = htole16(m0->m_pkthdr.len);
    507 	bcn->rate = (ic->ic_curmode == IEEE80211_MODE_11A) ?
    508 	    iwn_plcp_signal(12) : iwn_plcp_signal(2);
    509 	bcn->flags = htole32(IWN_TX_AUTO_SEQ | IWN_TX_INSERT_TSTAMP);
    510 
    511 	/* save and trim IEEE802.11 header */
    512 	m_copydata(m0, 0, sizeof (struct ieee80211_frame), (void *)&bcn->wh);
    513 	m_adj(m0, sizeof (struct ieee80211_frame));
    514 
    515 	/* assume beacon frame is contiguous */
    516 	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
    517 	    BUS_DMA_READ | BUS_DMA_NOWAIT);
    518 	if (error) {
    519 		aprint_error_dev(sc->sc_dev, "could not map beacon\n");
    520 		m_freem(m0);
    521 		return error;
    522 	}
    523 
    524 	data->m = m0;
    525 
    526 	/* first scatter/gather segment is used by the beacon command */
    527 	paddr = ring->cmd_dma.paddr + ring->cur * sizeof (struct iwn_tx_cmd);
    528 
    529 	IWN_SET_DESC_NSEGS(desc, 2);
    530 	IWN_SET_DESC_SEG(desc, 0, paddr , 4 + sizeof(struct iwn_cmd_beacon));
    531 	IWN_SET_DESC_SEG(desc, 1,  data->map->dm_segs[0].ds_addr,
    532 	    data->map->dm_segs[1].ds_len);
    533 
    534 
    535 	/* kick cmd ring */
    536 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
    537 	IWN_WRITE(sc, IWN_TX_WIDX, ring->qid << 8 | ring->cur);
    538 
    539 	return 0;
    540 }
    541 #endif
    542 
    543 static int
    544 iwn_dma_contig_alloc(bus_dma_tag_t tag, struct iwn_dma_info *dma, void **kvap,
    545     bus_size_t size, bus_size_t alignment, int flags)
    546 {
    547 	int nsegs, error;
    548 
    549 	dma->tag = tag;
    550 	dma->size = size;
    551 
    552 	error = bus_dmamap_create(tag, size, 1, size, 0, flags, &dma->map);
    553 	if (error != 0)
    554 		goto fail;
    555 
    556 	error = bus_dmamem_alloc(tag, size, alignment, 0, &dma->seg, 1, &nsegs,
    557 	    flags);
    558 	if (error != 0)
    559 		goto fail;
    560 
    561 	error = bus_dmamem_map(tag, &dma->seg, 1, size, &dma->vaddr, flags);
    562 	if (error != 0)
    563 		goto fail;
    564 
    565 	error = bus_dmamap_load(tag, dma->map, dma->vaddr, size, NULL, flags);
    566 	if (error != 0)
    567 		goto fail;
    568 
    569 	memset(dma->vaddr, 0, size);
    570 
    571 	dma->paddr = dma->map->dm_segs[0].ds_addr;
    572 	if (kvap != NULL)
    573 		*kvap = dma->vaddr;
    574 
    575 	return 0;
    576 
    577 fail:	iwn_dma_contig_free(dma);
    578 	return error;
    579 }
    580 
    581 static void
    582 iwn_dma_contig_free(struct iwn_dma_info *dma)
    583 {
    584 	if (dma->map != NULL) {
    585 		if (dma->vaddr != NULL) {
    586 			bus_dmamap_unload(dma->tag, dma->map);
    587 			bus_dmamem_unmap(dma->tag, dma->vaddr, dma->size);
    588 			bus_dmamem_free(dma->tag, &dma->seg, 1);
    589 			dma->vaddr = NULL;
    590 		}
    591 		bus_dmamap_destroy(dma->tag, dma->map);
    592 		dma->map = NULL;
    593 	}
    594 }
    595 
    596 static int
    597 iwn_alloc_shared(struct iwn_softc *sc)
    598 {
    599         int error;
    600   	/* must be aligned on a 1KB boundary */
    601 	error = iwn_dma_contig_alloc(sc->sc_dmat, &sc->shared_dma,
    602 	    (void **)&sc->shared, sizeof (struct iwn_shared),
    603 	    1024,BUS_DMA_NOWAIT);
    604 	if (error != 0)
    605 		aprint_error_dev(sc->sc_dev,
    606 		    "could not allocate shared area DMA memory\n");
    607 
    608 	return error;
    609 
    610 }
    611 
    612 static void
    613 iwn_free_shared(struct iwn_softc *sc)
    614 {
    615 	iwn_dma_contig_free(&sc->shared_dma);
    616 }
    617 
    618 static int
    619 iwn_alloc_kw(struct iwn_softc *sc)
    620 {
    621 	/* must be aligned on a 16-byte boundary */
    622 	return iwn_dma_contig_alloc(sc->sc_dmat, &sc->kw_dma, NULL,
    623 	    PAGE_SIZE, PAGE_SIZE, BUS_DMA_NOWAIT);
    624 }
    625 
    626 static void
    627 iwn_free_kw(struct iwn_softc *sc)
    628 {
    629 	iwn_dma_contig_free(&sc->kw_dma);
    630 }
    631 
    632 static int
    633 iwn_alloc_fwmem(struct iwn_softc *sc)
    634 {
    635 	int error;
    636 	/* allocate enough contiguous space to store text and data */
    637 	error = iwn_dma_contig_alloc(sc->sc_dmat, &sc->fw_dma, NULL,
    638 	    IWN_FW_MAIN_TEXT_MAXSZ + IWN_FW_MAIN_DATA_MAXSZ, 16,
    639 	    BUS_DMA_NOWAIT);
    640 
    641 	if (error != 0){
    642 		aprint_error_dev(sc->sc_dev,
    643 		    "could not allocate firmware transfer area DMA memory\n" );
    644 
    645 	}
    646 	return error;
    647 }
    648 
    649 static void
    650 iwn_free_fwmem(struct iwn_softc *sc)
    651 {
    652 	iwn_dma_contig_free(&sc->fw_dma);
    653 }
    654 
    655 static struct iwn_rbuf *
    656 iwn_alloc_rbuf(struct iwn_softc *sc)
    657 {
    658 	struct iwn_rbuf *rbuf;
    659 
    660 	rbuf = SLIST_FIRST(&sc->rxq.freelist);
    661 	if (rbuf == NULL)
    662 		return NULL;
    663 	SLIST_REMOVE_HEAD(&sc->rxq.freelist, next);
    664 	sc->rxq.nb_free_entries --;
    665 	return rbuf;
    666 }
    667 
    668 /*
    669  * This is called automatically by the network stack when the mbuf to which
    670  * our Rx buffer is attached is freed.
    671  */
    672 static void
    673 iwn_free_rbuf(struct mbuf* m, void *buf,  size_t size, void *arg)
    674 {
    675 	struct iwn_rbuf *rbuf = arg;
    676 	struct iwn_softc *sc = rbuf->sc;
    677 
    678 	/* put the buffer back in the free list */
    679 	SLIST_INSERT_HEAD(&sc->rxq.freelist, rbuf, next);
    680 
    681 	sc->rxq.nb_free_entries ++;
    682 
    683 	if (__predict_true(m != NULL))
    684 		pool_cache_put(mb_cache, m);
    685 }
    686 
    687 
    688 static int
    689 iwn_alloc_rpool(struct iwn_softc *sc)
    690 {
    691 	struct iwn_rx_ring *ring = &sc->rxq;
    692 	struct iwn_rbuf *rbuf;
    693 	int i, error;
    694 
    695 	/* allocate a big chunk of DMA'able memory.. */
    696 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->buf_dma, NULL,
    697 	    IWN_RBUF_COUNT * IWN_RBUF_SIZE, IWN_BUF_ALIGN, BUS_DMA_NOWAIT);
    698 	if (error != 0) {
    699 		aprint_error_dev(sc->sc_dev,
    700 		    "could not allocate Rx buffers DMA memory\n");
    701 		return error;
    702 	}
    703 
    704 	/* ..and split it into chunks of "rbufsz" bytes */
    705 	SLIST_INIT(&ring->freelist);
    706 	for (i = 0; i < IWN_RBUF_COUNT; i++) {
    707 		rbuf = &ring->rbuf[i];
    708 
    709 		rbuf->sc = sc;	/* backpointer for callbacks */
    710 		rbuf->vaddr = (char *)ring->buf_dma.vaddr + i * IWN_RBUF_SIZE;
    711 		rbuf->paddr = ring->buf_dma.paddr + i * IWN_RBUF_SIZE;
    712 
    713 		SLIST_INSERT_HEAD(&ring->freelist, rbuf, next);
    714 	}
    715 	ring->nb_free_entries = IWN_RBUF_COUNT;
    716 	return 0;
    717 }
    718 
    719 static void
    720 iwn_free_rpool(struct iwn_softc *sc)
    721 {
    722 	iwn_dma_contig_free(&sc->rxq.buf_dma);
    723 }
    724 
    725 static int
    726 iwn_alloc_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
    727 {
    728         struct iwn_rx_data *data;
    729         struct iwn_rbuf *rbuf;
    730         int i, error;
    731 
    732 	ring->cur = 0;
    733 
    734 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->desc_dma,
    735 	    (void **)&ring->desc, IWN_RX_RING_COUNT * sizeof (struct iwn_rx_desc),
    736 	    IWN_RING_DMA_ALIGN, BUS_DMA_NOWAIT);
    737 	if (error != 0) {
    738 		aprint_error_dev(sc->sc_dev,
    739 		    "could not allocate rx ring DMA memory\n");
    740 		goto fail;
    741 	}
    742 
    743 	/*
    744 	 * Setup Rx buffers.
    745 	 */
    746 	for (i = 0; i < IWN_RX_RING_COUNT; i++) {
    747 		data = &ring->data[i];
    748 
    749 		MGETHDR(data->m, M_DONTWAIT, MT_DATA);
    750 		if (data->m == NULL) {
    751 			aprint_error_dev(sc->sc_dev, "could not allocate rx mbuf\n");
    752 			error = ENOMEM;
    753 			goto fail;
    754 		}
    755 		if ((rbuf = iwn_alloc_rbuf(sc)) == NULL) {
    756 			m_freem(data->m);
    757 			data->m = NULL;
    758 			aprint_error_dev(sc->sc_dev, "could not allocate rx buffer\n");
    759 			error = ENOMEM;
    760 			goto fail;
    761 		}
    762 		/* attach Rx buffer to mbuf */
    763 		MEXTADD(data->m, rbuf->vaddr, IWN_RBUF_SIZE, 0, iwn_free_rbuf,
    764 		    rbuf);
    765 
    766 		data->m->m_flags |= M_EXT_RW;
    767 		/* Rx buffers are aligned on a 256-byte boundary */
    768 		ring->desc[i] = htole32(rbuf->paddr >> 8);
    769 	}
    770 
    771 	return 0;
    772 
    773 fail:	iwn_free_rx_ring(sc, ring);
    774 	return error;
    775 }
    776 
    777 static void
    778 iwn_reset_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
    779 {
    780 	int ntries;
    781 
    782 	iwn_mem_lock(sc);
    783 
    784 	IWN_WRITE(sc, IWN_RX_CONFIG, 0);
    785 	for (ntries = 0; ntries < 100; ntries++) {
    786 		if (IWN_READ(sc, IWN_RX_STATUS) & IWN_RX_IDLE)
    787 			break;
    788 		DELAY(10);
    789 	}
    790 #ifdef IWN_DEBUG
    791 	if (ntries == 100 && iwn_debug > 0)
    792 		aprint_error_dev(sc->sc_dev, "timeout resetting Rx ring\n");
    793 #endif
    794 	iwn_mem_unlock(sc);
    795 
    796 	ring->cur = 0;
    797 }
    798 
    799 static void
    800 iwn_free_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
    801 {
    802 	int i;
    803 
    804 	iwn_dma_contig_free(&ring->desc_dma);
    805 
    806 	for (i = 0; i < IWN_RX_RING_COUNT; i++) {
    807 		if (ring->data[i].m != NULL)
    808 			m_freem(ring->data[i].m);
    809 	}
    810 }
    811 
    812 static int
    813 iwn_alloc_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring, int count,
    814     int qid)
    815 {
    816 	struct iwn_tx_data *data;
    817 	int i, error;
    818 
    819 	ring->qid = qid;
    820 	ring->count = count;
    821 	ring->queued = 0;
    822 	ring->cur = 0;
    823 
    824 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->desc_dma,
    825 	    (void **)&ring->desc, count * sizeof (struct iwn_tx_desc),
    826 	    IWN_RING_DMA_ALIGN, BUS_DMA_NOWAIT);
    827 	if (error != 0) {
    828 		aprint_error_dev(sc->sc_dev, "could not allocate tx ring DMA memory\n");
    829 		goto fail;
    830 	}
    831 
    832 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->cmd_dma,
    833 	    (void **)&ring->cmd, count * sizeof (struct iwn_tx_cmd), 4,
    834 	    BUS_DMA_NOWAIT);
    835 	if (error != 0) {
    836 		aprint_error_dev(sc->sc_dev, "could not allocate tx cmd DMA memory\n");
    837 		goto fail;
    838 	}
    839 
    840 	ring->data = malloc(count * sizeof (struct iwn_tx_data), M_DEVBUF, M_NOWAIT);
    841 
    842 	if (ring->data == NULL) {
    843 		aprint_error_dev(sc->sc_dev,"could not allocate tx data slots\n");
    844 		goto fail;
    845 	}
    846 
    847 	memset(ring->data, 0, count * sizeof (struct iwn_tx_data));
    848 
    849 	for (i = 0; i < count; i++) {
    850 		data = &ring->data[i];
    851 
    852 		error = bus_dmamap_create(sc->sc_dmat, MCLBYTES,
    853 		    IWN_MAX_SCATTER - 1, MCLBYTES, 0, BUS_DMA_NOWAIT,
    854 		    &data->map);
    855 		if (error != 0) {
    856 			aprint_error_dev(sc->sc_dev, "could not create tx buf DMA map\n");
    857 			goto fail;
    858 		}
    859 	}
    860 
    861 	return 0;
    862 
    863 fail:	iwn_free_tx_ring(sc, ring);
    864 	return error;
    865 }
    866 
    867 static void
    868 iwn_reset_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
    869 {
    870         struct iwn_tx_data *data;
    871 	uint32_t tmp;
    872 	int i, ntries;
    873 
    874 	iwn_mem_lock(sc);
    875 
    876 	IWN_WRITE(sc, IWN_TX_CONFIG(ring->qid), 0);
    877 	for (ntries = 0; ntries < 100; ntries++) {
    878 		tmp = IWN_READ(sc, IWN_TX_STATUS);
    879 		if ((tmp & IWN_TX_IDLE(ring->qid)) == IWN_TX_IDLE(ring->qid))
    880 			break;
    881 		DELAY(10);
    882 	}
    883 #ifdef IWN_DEBUG
    884 	if (ntries == 100 && iwn_debug > 1) {
    885 		aprint_error_dev(sc->sc_dev, "timeout resetting Tx ring %d\n", ring->qid);
    886 	}
    887 #endif
    888 	iwn_mem_unlock(sc);
    889 
    890 	for (i = 0; i < ring->count; i++) {
    891 		data = &ring->data[i];
    892 
    893 		if (data->m != NULL) {
    894 			bus_dmamap_unload(sc->sc_dmat, data->map);
    895 			m_freem(data->m);
    896 			data->m = NULL;
    897 		}
    898 	}
    899 
    900 	ring->queued = 0;
    901 	ring->cur = 0;
    902 }
    903 
    904 static void
    905 iwn_free_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
    906 {
    907 	struct iwn_tx_data *data;
    908 	int i;
    909 
    910 	iwn_dma_contig_free(&ring->desc_dma);
    911 	iwn_dma_contig_free(&ring->cmd_dma);
    912 
    913 	if (ring->data != NULL) {
    914 		for (i = 0; i < ring->count; i++) {
    915 			data = &ring->data[i];
    916 
    917 			if (data->m != NULL) {
    918 				bus_dmamap_unload(sc->sc_dmat, data->map);
    919 				m_freem(data->m);
    920 			}
    921 		}
    922 		free(ring->data, M_DEVBUF);
    923 	}
    924 }
    925 
    926 /*ARGUSED*/
    927 struct ieee80211_node *
    928 iwn_node_alloc(struct ieee80211_node_table *nt __unused)
    929 {
    930 	struct iwn_node *wn;
    931 
    932 	wn = malloc(sizeof (struct iwn_node), M_DEVBUF, M_NOWAIT);
    933 
    934 	if (wn != NULL)
    935 		memset(wn, 0, sizeof (struct iwn_node));
    936 	return (struct ieee80211_node *)wn;
    937 
    938 }
    939 
    940 static void
    941 iwn_newassoc(struct ieee80211_node *ni, int isnew)
    942 {
    943 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
    944 	int i;
    945 
    946 	ieee80211_amrr_node_init(&sc->amrr, &((struct iwn_node *)ni)->amn);
    947 
    948 	/* set rate to some reasonable initial value */
    949 	for (i = ni->ni_rates.rs_nrates - 1;
    950 	     i > 0 && (ni->ni_rates.rs_rates[i] & IEEE80211_RATE_VAL) > 72;
    951 	     i--);
    952 	ni->ni_txrate = i;
    953 }
    954 
    955 static int
    956 iwn_media_change(struct ifnet *ifp)
    957 {
    958 	int error;
    959 
    960 	error = ieee80211_media_change(ifp);
    961 	if (error != ENETRESET)
    962 		return error;
    963 
    964 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
    965 		iwn_init(ifp);
    966 
    967 	return 0;
    968 }
    969 
    970 static int
    971 iwn_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
    972 {
    973 	struct ifnet *ifp = ic->ic_ifp;
    974 	struct iwn_softc *sc = ifp->if_softc;
    975 	int error;
    976 
    977 	callout_stop(&sc->calib_to);
    978 
    979 	switch (nstate) {
    980 
    981 	case IEEE80211_S_SCAN:
    982 
    983 		if (sc->is_scanning)
    984 			break;
    985 
    986 		sc->is_scanning = true;
    987 		ieee80211_node_table_reset(&ic->ic_scan);
    988 		ic->ic_flags |= IEEE80211_F_SCAN | IEEE80211_F_ASCAN;
    989 
    990 		/* make the link LED blink while we're scanning */
    991 		iwn_set_led(sc, IWN_LED_LINK, 20, 2);
    992 
    993 		if ((error = iwn_scan(sc, IEEE80211_CHAN_G)) != 0) {
    994 			aprint_error_dev(sc->sc_dev, "could not initiate scan\n");
    995 			ic->ic_flags &= ~(IEEE80211_F_SCAN | IEEE80211_F_ASCAN);
    996 			return error;
    997 		}
    998 		ic->ic_state = nstate;
    999 		return 0;
   1000 
   1001 	case IEEE80211_S_ASSOC:
   1002 		if (ic->ic_state != IEEE80211_S_RUN)
   1003 			break;
   1004 		/* FALLTHROUGH */
   1005 	case IEEE80211_S_AUTH:
   1006 		/* reset state to handle reassociations correctly */
   1007 		sc->config.associd = 0;
   1008 		sc->config.filter &= ~htole32(IWN_FILTER_BSS);
   1009 		/*sc->calib.state = IWN_CALIB_STATE_INIT;*/
   1010 
   1011 		if ((error = iwn_auth(sc)) != 0) {
   1012 			aprint_error_dev(sc->sc_dev, "could not move to auth state\n");
   1013 			return error;
   1014 		}
   1015 		break;
   1016 
   1017 	case IEEE80211_S_RUN:
   1018 		if ((error = iwn_run(sc)) != 0) {
   1019 			aprint_error_dev(sc->sc_dev, "could not move to run state\n");
   1020 			return error;
   1021 		}
   1022 
   1023 #if 0
   1024 		/* JAF - code has changed here. need to verify iwn_run handles this properly XXX added to iwn_run */
   1025 		if (ic->ic_opmode != IEEE80211_M_STA) {
   1026 			(void) iwn_auth(sc);    /* XXX */
   1027 			iwn_setup_beacon(sc, ni);
   1028 		}
   1029 #endif
   1030 
   1031 
   1032 		break;
   1033 
   1034 	case IEEE80211_S_INIT:
   1035 		sc->is_scanning = false;
   1036 		break;
   1037 	}
   1038 
   1039 	return sc->sc_newstate(ic, nstate, arg);
   1040 }
   1041 
   1042 /*
   1043  * Grab exclusive access to NIC memory.
   1044  */
   1045 static void
   1046 iwn_mem_lock(struct iwn_softc *sc)
   1047 {
   1048 	uint32_t tmp;
   1049 	int ntries;
   1050 
   1051 	tmp = IWN_READ(sc, IWN_GPIO_CTL);
   1052 	IWN_WRITE(sc, IWN_GPIO_CTL, tmp | IWN_GPIO_MAC);
   1053 
   1054 	/* spin until we actually get the lock */
   1055 	for (ntries = 0; ntries < 1000; ntries++) {
   1056 		if ((IWN_READ(sc, IWN_GPIO_CTL) &
   1057 			(IWN_GPIO_CLOCK | IWN_GPIO_SLEEP)) == IWN_GPIO_CLOCK)
   1058 			break;
   1059 		DELAY(10);
   1060 	}
   1061 	if (ntries == 1000)
   1062 		aprint_error_dev(sc->sc_dev, "could not lock memory\n");
   1063 }
   1064 
   1065 /*
   1066  * Release lock on NIC memory.
   1067  */
   1068 static void
   1069 iwn_mem_unlock(struct iwn_softc *sc)
   1070 {
   1071 	uint32_t tmp = IWN_READ(sc, IWN_GPIO_CTL);
   1072 	IWN_WRITE(sc, IWN_GPIO_CTL, tmp & ~IWN_GPIO_MAC);
   1073 }
   1074 
   1075 static uint32_t
   1076 iwn_mem_read(struct iwn_softc *sc, uint32_t addr)
   1077 {
   1078 	IWN_WRITE(sc, IWN_READ_MEM_ADDR, IWN_MEM_4 | addr);
   1079 	return IWN_READ(sc, IWN_READ_MEM_DATA);
   1080 }
   1081 
   1082 static void
   1083 iwn_mem_write(struct iwn_softc *sc, uint32_t addr, uint32_t data)
   1084 {
   1085 	IWN_WRITE(sc, IWN_WRITE_MEM_ADDR, IWN_MEM_4 | addr);
   1086 	IWN_WRITE(sc, IWN_WRITE_MEM_DATA, data);
   1087 }
   1088 
   1089 static void
   1090 iwn_mem_write_region_4(struct iwn_softc *sc, uint32_t addr,
   1091     const uint32_t *data, int wlen)
   1092 {
   1093 	for (; wlen > 0; wlen--, data++, addr += 4)
   1094 		iwn_mem_write(sc, addr, *data);
   1095 }
   1096 
   1097 static int
   1098 iwn_eeprom_lock(struct iwn_softc *sc)
   1099 {
   1100 	uint32_t tmp;
   1101 	int ntries;
   1102 
   1103 	tmp = IWN_READ(sc, IWN_HWCONFIG);
   1104 	IWN_WRITE(sc, IWN_HWCONFIG, tmp | IWN_HW_EEPROM_LOCKED);
   1105 
   1106 	/* spin until we actually get the lock */
   1107 	for (ntries = 0; ntries < 100; ntries++) {
   1108 		if (IWN_READ(sc, IWN_HWCONFIG) & IWN_HW_EEPROM_LOCKED)
   1109 			return 0;
   1110 		DELAY(10);
   1111 	}
   1112 	return ETIMEDOUT;
   1113 }
   1114 
   1115 static void
   1116 iwn_eeprom_unlock(struct iwn_softc *sc)
   1117 {
   1118 	uint32_t tmp = IWN_READ(sc, IWN_HWCONFIG);
   1119 	IWN_WRITE(sc, IWN_HWCONFIG, tmp & ~IWN_HW_EEPROM_LOCKED);
   1120 }
   1121 
   1122 /*
   1123  * Read `len' bytes from the EEPROM.  We access the EEPROM through the MAC
   1124  * instead of using the traditional bit-bang method.
   1125  */
   1126 static int
   1127 iwn_read_prom_data(struct iwn_softc *sc, uint32_t addr, void *data, int len)
   1128 {
   1129 	uint8_t *out = data;
   1130 	uint32_t val;
   1131 	int ntries;
   1132 
   1133 	iwn_mem_lock(sc);
   1134 	for (; len > 0; len -= 2, addr++) {
   1135 		IWN_WRITE(sc, IWN_EEPROM_CTL, addr << 2);
   1136 		IWN_WRITE(sc, IWN_EEPROM_CTL,
   1137 		    IWN_READ(sc, IWN_EEPROM_CTL) & ~IWN_EEPROM_CMD);
   1138 
   1139 		for (ntries = 0; ntries < 10; ntries++) {
   1140 			if ((val = IWN_READ(sc, IWN_EEPROM_CTL)) &
   1141 			    IWN_EEPROM_READY)
   1142 				break;
   1143 			DELAY(5);
   1144 		}
   1145 		if (ntries == 10) {
   1146 			aprint_error_dev(sc->sc_dev, "could not read EEPROM\n");
   1147 			return ETIMEDOUT;
   1148 		}
   1149 		*out++ = val >> 16;
   1150 		if (len > 1)
   1151 			*out++ = val >> 24;
   1152 	}
   1153 	iwn_mem_unlock(sc);
   1154 
   1155 	return 0;
   1156 }
   1157 
   1158 /*
   1159  * The firmware boot code is small and is intended to be copied directly into
   1160  * the NIC internal memory.
   1161  */
   1162 static int
   1163 iwn_load_microcode(struct iwn_softc *sc, const uint8_t *ucode, int size)
   1164 {
   1165 	int ntries;
   1166 
   1167 	size /= sizeof (uint32_t);
   1168 
   1169 	iwn_mem_lock(sc);
   1170 
   1171 	/* copy microcode image into NIC memory */
   1172 	iwn_mem_write_region_4(sc, IWN_MEM_UCODE_BASE,
   1173 	    (const uint32_t *)ucode, size);
   1174 
   1175 	iwn_mem_write(sc, IWN_MEM_UCODE_SRC, 0);
   1176 	iwn_mem_write(sc, IWN_MEM_UCODE_DST, IWN_FW_TEXT);
   1177 	iwn_mem_write(sc, IWN_MEM_UCODE_SIZE, size);
   1178 
   1179 	/* run microcode */
   1180 	iwn_mem_write(sc, IWN_MEM_UCODE_CTL, IWN_UC_RUN);
   1181 
   1182 	/* wait for transfer to complete */
   1183 	for (ntries = 0; ntries < 1000; ntries++) {
   1184 		if (!(iwn_mem_read(sc, IWN_MEM_UCODE_CTL) & IWN_UC_RUN))
   1185 			break;
   1186 		DELAY(10);
   1187 	}
   1188 	if (ntries == 1000) {
   1189 		iwn_mem_unlock(sc);
   1190 		aprint_error_dev(sc->sc_dev, "could not load boot firmware\n");
   1191 		return ETIMEDOUT;
   1192 	}
   1193 	iwn_mem_write(sc, IWN_MEM_UCODE_CTL, IWN_UC_ENABLE);
   1194 
   1195 	iwn_mem_unlock(sc);
   1196 
   1197 	return 0;
   1198 }
   1199 
   1200 static int
   1201 iwn_load_firmware(struct iwn_softc *sc)
   1202 {
   1203 	struct iwn_dma_info *dma = &sc->fw_dma;
   1204 	struct iwn_firmware_hdr hdr;
   1205 	const uint8_t *init_text, *init_data, *main_text, *main_data;
   1206 	const uint8_t *boot_text;
   1207 	uint32_t init_textsz, init_datasz, main_textsz, main_datasz;
   1208 	uint32_t boot_textsz;
   1209 	firmware_handle_t fw;
   1210 	u_char *dfw;
   1211 	size_t size;
   1212 	int error;
   1213 
   1214 	/* load firmware image from disk */
   1215 	if ((error = firmware_open("if_iwn","iwlwifi-4965.ucode", &fw) != 0)) {
   1216 		aprint_error_dev(sc->sc_dev, "could not read firmware file\n");
   1217 		goto fail1;
   1218 	}
   1219 
   1220 	size = firmware_get_size(fw);
   1221 
   1222 	/* extract firmware header information */
   1223 	if (size < sizeof (struct iwn_firmware_hdr)) {
   1224 		aprint_error_dev(sc->sc_dev, "truncated firmware header: %zu bytes\n", size);
   1225 
   1226 		error = EINVAL;
   1227 		goto fail2;
   1228 	}
   1229 
   1230 
   1231 	if ((error = firmware_read(fw, 0, &hdr,
   1232 		    sizeof (struct iwn_firmware_hdr))) != 0) {
   1233 		aprint_error_dev(sc->sc_dev, "can't get firmware header\n");
   1234 		goto fail2;
   1235 	}
   1236 
   1237 	main_textsz = le32toh(hdr.main_textsz);
   1238 	main_datasz = le32toh(hdr.main_datasz);
   1239 	init_textsz = le32toh(hdr.init_textsz);
   1240 	init_datasz = le32toh(hdr.init_datasz);
   1241 	boot_textsz = le32toh(hdr.boot_textsz);
   1242 
   1243 	/* sanity-check firmware segments sizes */
   1244 	if (main_textsz > IWN_FW_MAIN_TEXT_MAXSZ ||
   1245 	    main_datasz > IWN_FW_MAIN_DATA_MAXSZ ||
   1246 	    init_textsz > IWN_FW_INIT_TEXT_MAXSZ ||
   1247 	    init_datasz > IWN_FW_INIT_DATA_MAXSZ ||
   1248 	    boot_textsz > IWN_FW_BOOT_TEXT_MAXSZ ||
   1249 	    (boot_textsz & 3) != 0) {
   1250 		aprint_error_dev(sc->sc_dev, "invalid firmware header\n");
   1251 		error = EINVAL;
   1252 		goto fail2;
   1253 	}
   1254 
   1255 	/* check that all firmware segments are present */
   1256 	if (size < sizeof (struct iwn_firmware_hdr) + main_textsz +
   1257 	    main_datasz + init_textsz + init_datasz + boot_textsz) {
   1258 		aprint_error_dev(sc->sc_dev, "firmware file too short: %zu bytes\n", size);
   1259 		error = EINVAL;
   1260 		goto fail2;
   1261 	}
   1262 
   1263 	dfw = firmware_malloc(size);
   1264 	if (dfw == NULL) {
   1265 		aprint_error_dev(sc->sc_dev, "not enough memory to stock firmware\n");
   1266 		error = ENOMEM;
   1267 		goto fail2;
   1268 	}
   1269 
   1270 	if ((error = firmware_read(fw, 0, dfw, size)) != 0) {
   1271 		aprint_error_dev(sc->sc_dev, "can't get firmware\n");
   1272 		goto fail2;
   1273 	}
   1274 
   1275 	/* get pointers to firmware segments */
   1276 	main_text = dfw + sizeof (struct iwn_firmware_hdr);
   1277 	main_data = main_text + main_textsz;
   1278 	init_text = main_data + main_datasz;
   1279 	init_data = init_text + init_textsz;
   1280 	boot_text = init_data + init_datasz;
   1281 
   1282 	/* copy initialization images into pre-allocated DMA-safe memory */
   1283 	memcpy(dma->vaddr, init_data, init_datasz);
   1284 	memcpy((char *)dma->vaddr + IWN_FW_INIT_DATA_MAXSZ, init_text, init_textsz);
   1285 
   1286 	/* tell adapter where to find initialization images */
   1287 	iwn_mem_lock(sc);
   1288 	iwn_mem_write(sc, IWN_MEM_DATA_BASE, dma->paddr >> 4);
   1289 	iwn_mem_write(sc, IWN_MEM_DATA_SIZE, init_datasz);
   1290 	iwn_mem_write(sc, IWN_MEM_TEXT_BASE,
   1291 	    (dma->paddr + IWN_FW_INIT_DATA_MAXSZ) >> 4);
   1292 	iwn_mem_write(sc, IWN_MEM_TEXT_SIZE, init_textsz);
   1293 	iwn_mem_unlock(sc);
   1294 
   1295 	/* load firmware boot code */
   1296 	if ((error = iwn_load_microcode(sc, boot_text, boot_textsz)) != 0) {
   1297 		aprint_error_dev(sc->sc_dev, "could not load boot firmware\n");
   1298 		goto fail3;
   1299 	}
   1300 
   1301 	/* now press "execute" ;-) */
   1302 	IWN_WRITE(sc, IWN_RESET, 0);
   1303 
   1304 	/* ..and wait at most one second for adapter to initialize */
   1305 	if ((error = tsleep(sc, PCATCH, "iwninit", hz)) != 0) {
   1306 		/* this isn't what was supposed to happen.. */
   1307 		aprint_error_dev(sc->sc_dev, "timeout waiting for adapter to initialize\n");
   1308 	}
   1309 
   1310 	/* copy runtime images into pre-allocated DMA-safe memory */
   1311 	memcpy((char *)dma->vaddr, main_data, main_datasz);
   1312 	memcpy((char *)dma->vaddr + IWN_FW_MAIN_DATA_MAXSZ, main_text, main_textsz);
   1313 
   1314 	/* tell adapter where to find runtime images */
   1315 	iwn_mem_lock(sc);
   1316 	iwn_mem_write(sc, IWN_MEM_DATA_BASE, dma->paddr >> 4);
   1317 	iwn_mem_write(sc, IWN_MEM_DATA_SIZE, main_datasz);
   1318 	iwn_mem_write(sc, IWN_MEM_TEXT_BASE,
   1319 	    (dma->paddr + IWN_FW_MAIN_DATA_MAXSZ) >> 4);
   1320 	iwn_mem_write(sc, IWN_MEM_TEXT_SIZE, IWN_FW_UPDATED | main_textsz);
   1321 	iwn_mem_unlock(sc);
   1322 
   1323 	/* wait at most one second for second alive notification */
   1324 	if ((error = tsleep(sc, PCATCH, "iwninit", hz)) != 0) {
   1325 		/* this isn't what was supposed to happen.. */
   1326 		aprint_error_dev(sc->sc_dev, "timeout waiting for adapter to initialize\n");
   1327 	}
   1328 
   1329 fail3: firmware_free(dfw,size);
   1330 fail2:	firmware_close(fw);
   1331 fail1:	return error;
   1332 }
   1333 
   1334 static void
   1335 iwn_calib_timeout(void *arg)
   1336 {
   1337 	struct iwn_softc *sc = arg;
   1338 	struct ieee80211com *ic = &sc->sc_ic;
   1339 	int s;
   1340 
   1341 	/* automatic rate control triggered every 500ms */
   1342 	if (ic->ic_fixed_rate == -1) {
   1343 		s = splnet();
   1344 		if (ic->ic_opmode == IEEE80211_M_STA)
   1345 			iwn_iter_func(sc, ic->ic_bss);
   1346 		else
   1347 			ieee80211_iterate_nodes(&ic->ic_sta, iwn_iter_func, sc);
   1348 		splx(s);
   1349 	}
   1350 
   1351 	/* automatic calibration every 60s */
   1352 	if (++sc->calib_cnt >= 120) {
   1353 		DPRINTF(("sending request for statistics\n"));
   1354 		(void)iwn_cmd(sc, IWN_CMD_GET_STATISTICS, NULL, 0, 1);
   1355 		sc->calib_cnt = 0;
   1356 	}
   1357 
   1358 	callout_schedule(&sc->calib_to, hz/2);
   1359 
   1360 }
   1361 
   1362 static void
   1363 iwn_iter_func(void *arg, struct ieee80211_node *ni)
   1364 {
   1365 	struct iwn_softc *sc = arg;
   1366 	struct iwn_node *wn = (struct iwn_node *)ni;
   1367 
   1368 	ieee80211_amrr_choose(&sc->amrr, ni, &wn->amn);
   1369 }
   1370 
   1371 static void
   1372 iwn_ampdu_rx_start(struct iwn_softc *sc, struct iwn_rx_desc *desc)
   1373 {
   1374 	struct iwn_rx_stat *stat;
   1375 
   1376 	DPRINTFN(2, ("received AMPDU stats\n"));
   1377 	/* save Rx statistics, they will be used on IWN_AMPDU_RX_DONE */
   1378 	stat = (struct iwn_rx_stat *)(desc + 1);
   1379 	memcpy(&sc->last_rx_stat, stat, sizeof (*stat));
   1380 	sc->last_rx_valid = 1;
   1381 }
   1382 
   1383 void
   1384 iwn_rx_intr(struct iwn_softc *sc, struct iwn_rx_desc *desc,
   1385     struct iwn_rx_data *data)
   1386 {
   1387 	struct ieee80211com *ic = &sc->sc_ic;
   1388 	struct ifnet *ifp = ic->ic_ifp;
   1389 	struct iwn_rx_ring *ring = &sc->rxq;
   1390 	struct iwn_rbuf *rbuf;
   1391 	struct ieee80211_frame *wh;
   1392 	struct ieee80211_node *ni;
   1393 	struct mbuf *m, *mnew;
   1394 	struct iwn_rx_stat *stat;
   1395 	char *head;
   1396 	uint32_t *tail;
   1397 	int len, rssi;
   1398 
   1399 	if (desc->type == IWN_AMPDU_RX_DONE) {
   1400 		/* check for prior AMPDU_RX_START */
   1401 		if (!sc->last_rx_valid) {
   1402 			DPRINTF(("missing AMPDU_RX_START\n"));
   1403 			ifp->if_ierrors++;
   1404 			return;
   1405 		}
   1406 		sc->last_rx_valid = 0;
   1407 		stat = &sc->last_rx_stat;
   1408 	} else
   1409 		stat = (struct iwn_rx_stat *)(desc + 1);
   1410 
   1411 	if (stat->cfg_phy_len > IWN_STAT_MAXLEN) {
   1412 		aprint_error_dev(sc->sc_dev, "invalid rx statistic header\n");
   1413 		ifp->if_ierrors++;
   1414 		return;
   1415 	}
   1416 
   1417 	if (desc->type == IWN_AMPDU_RX_DONE) {
   1418 		struct iwn_rx_ampdu *ampdu =
   1419 		    (struct iwn_rx_ampdu *)(desc + 1);
   1420 		head = (char *)(ampdu + 1);
   1421 		len = le16toh(ampdu->len);
   1422 	} else {
   1423 		head = (char *)(stat + 1) + stat->cfg_phy_len;
   1424 		len = le16toh(stat->len);
   1425 	}
   1426 
   1427 	/* discard Rx frames with bad CRC early */
   1428 	tail = (uint32_t *)(head + len);
   1429 	if ((le32toh(*tail) & IWN_RX_NOERROR) != IWN_RX_NOERROR) {
   1430 		DPRINTFN(2, ("rx flags error %x\n", le32toh(*tail)));
   1431 		ifp->if_ierrors++;
   1432 		return;
   1433 	}
   1434 	/* XXX for ieee80211_find_rxnode() */
   1435 	if (len < sizeof (struct ieee80211_frame)) {
   1436 		DPRINTF(("frame too short: %d\n", len));
   1437 		ic->ic_stats.is_rx_tooshort++;
   1438 		ifp->if_ierrors++;
   1439 		return;
   1440 	}
   1441 
   1442 	m = data->m;
   1443 
   1444 	/* finalize mbuf */
   1445 	m->m_pkthdr.rcvif = ifp;
   1446 	m->m_data = head;
   1447 	m->m_pkthdr.len = m->m_len = len;
   1448 
   1449 	if ((rbuf = SLIST_FIRST(&sc->rxq.freelist)) != NULL) {
   1450 		MGETHDR(mnew, M_DONTWAIT, MT_DATA);
   1451 		if (mnew == NULL) {
   1452 			ic->ic_stats.is_rx_nobuf++;
   1453 			ifp->if_ierrors++;
   1454 			return;
   1455 		}
   1456 
   1457 		/* attach Rx buffer to mbuf */
   1458 		MEXTADD(mnew, rbuf->vaddr, IWN_RBUF_SIZE, 0, iwn_free_rbuf,
   1459 		    rbuf);
   1460 		mnew->m_flags |= M_EXT_RW;
   1461 		SLIST_REMOVE_HEAD(&sc->rxq.freelist, next);
   1462 
   1463 		data->m = mnew;
   1464 
   1465 		/* update Rx descriptor */
   1466 		ring->desc[ring->cur] = htole32(rbuf->paddr >> 8);
   1467 	} else {
   1468 		/* no free rbufs, copy frame */
   1469 		m = m_dup(m, 0, M_COPYALL, M_DONTWAIT);
   1470 		if (m == NULL) {
   1471 			/* no free mbufs either, drop frame */
   1472 			ic->ic_stats.is_rx_nobuf++;
   1473 			ifp->if_ierrors++;
   1474 			return;
   1475 		}
   1476 	}
   1477 
   1478 	rssi = iwn_get_rssi(stat);
   1479 
   1480 	if (ic->ic_state == IEEE80211_S_SCAN)
   1481 		iwn_fix_channel(ic, m);
   1482 
   1483 #if NBPFILTER > 0
   1484 	if (sc->sc_drvbpf != NULL) {
   1485 		struct iwn_rx_radiotap_header *tap = &sc->sc_rxtap;
   1486 
   1487 		tap->wr_flags = 0;
   1488 		tap->wr_chan_freq =
   1489 		    htole16(ic->ic_channels[stat->chan].ic_freq);
   1490 		tap->wr_chan_flags =
   1491 		    htole16(ic->ic_channels[stat->chan].ic_flags);
   1492 		tap->wr_dbm_antsignal = (int8_t)rssi;
   1493 		tap->wr_dbm_antnoise = (int8_t)sc->noise;
   1494 		tap->wr_tsft = stat->tstamp;
   1495 		switch (stat->rate) {
   1496 			/* CCK rates */
   1497 		case  10: tap->wr_rate =   2; break;
   1498 		case  20: tap->wr_rate =   4; break;
   1499 		case  55: tap->wr_rate =  11; break;
   1500 		case 110: tap->wr_rate =  22; break;
   1501 			/* OFDM rates */
   1502 		case 0xd: tap->wr_rate =  12; break;
   1503 		case 0xf: tap->wr_rate =  18; break;
   1504 		case 0x5: tap->wr_rate =  24; break;
   1505 		case 0x7: tap->wr_rate =  36; break;
   1506 		case 0x9: tap->wr_rate =  48; break;
   1507 		case 0xb: tap->wr_rate =  72; break;
   1508 		case 0x1: tap->wr_rate =  96; break;
   1509 		case 0x3: tap->wr_rate = 108; break;
   1510 			/* unknown rate: should not happen */
   1511 		default:  tap->wr_rate =   0;
   1512 		}
   1513 
   1514 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_rxtap_len, m);
   1515 	}
   1516 #endif
   1517 
   1518 	/* grab a reference to the source node */
   1519 	wh = mtod(m, struct ieee80211_frame *);
   1520 	ni = ieee80211_find_rxnode(ic,(struct ieee80211_frame_min *)wh);
   1521 
   1522 	/* send the frame to the 802.11 layer */
   1523 	ieee80211_input(ic, m, ni, rssi, 0);
   1524 
   1525 	/* node is no longer needed */
   1526 	ieee80211_free_node(ni);
   1527 }
   1528 
   1529 
   1530 /*
   1531  * XXX: Hack to set the current channel to the value advertised in beacons or
   1532  * probe responses. Only used during AP detection.
   1533  * XXX: Duplicated from if_iwi.c
   1534  */
   1535 static void
   1536 iwn_fix_channel(struct ieee80211com *ic, struct mbuf *m)
   1537 {
   1538 	struct ieee80211_frame *wh;
   1539 	uint8_t subtype;
   1540 	uint8_t *frm, *efrm;
   1541 
   1542 	wh = mtod(m, struct ieee80211_frame *);
   1543 
   1544 	if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_MGT)
   1545 		return;
   1546 
   1547 	subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
   1548 
   1549 	if (subtype != IEEE80211_FC0_SUBTYPE_BEACON &&
   1550 	    subtype != IEEE80211_FC0_SUBTYPE_PROBE_RESP)
   1551 		return;
   1552 
   1553 	frm = (uint8_t *)(wh + 1);
   1554 	efrm = mtod(m, uint8_t *) + m->m_len;
   1555 
   1556 	frm += 12;	/* skip tstamp, bintval and capinfo fields */
   1557 	while (frm < efrm) {
   1558 		if (*frm == IEEE80211_ELEMID_DSPARMS)
   1559 #if IEEE80211_CHAN_MAX < 255
   1560 			if (frm[2] <= IEEE80211_CHAN_MAX)
   1561 #endif
   1562 				ic->ic_curchan = &ic->ic_channels[frm[2]];
   1563 
   1564 		frm += frm[1] + 2;
   1565 	}
   1566 }
   1567 
   1568 static void
   1569 iwn_rx_statistics(struct iwn_softc *sc, struct iwn_rx_desc *desc)
   1570 {
   1571 	struct ieee80211com *ic = &sc->sc_ic;
   1572 	struct iwn_calib_state *calib = &sc->calib;
   1573 	struct iwn_stats *stats = (struct iwn_stats *)(desc + 1);
   1574 
   1575 	/* ignore beacon statistics received during a scan */
   1576 	if (ic->ic_state != IEEE80211_S_RUN)
   1577 		return;
   1578 
   1579 	DPRINTFN(3, ("received statistics (cmd=%d)\n", desc->type));
   1580 	sc->calib_cnt = 0;	/* reset timeout */
   1581 
   1582 	/* test if temperature has changed */
   1583 	if (stats->general.temp != sc->rawtemp) {
   1584 		int temp;
   1585 
   1586 		sc->rawtemp = stats->general.temp;
   1587 		temp = iwn_get_temperature(sc);
   1588 		DPRINTFN(2, ("temperature=%d\n", temp));
   1589 
   1590 		/* update Tx power if need be */
   1591 		iwn_power_calibration(sc, temp);
   1592 	}
   1593 
   1594 	if (desc->type != IWN_BEACON_STATISTICS)
   1595 		return;	/* reply to a statistics request */
   1596 
   1597 	sc->noise = iwn_get_noise(&stats->rx.general);
   1598 	DPRINTFN(3, ("noise=%d\n", sc->noise));
   1599 
   1600 	/* test that RSSI and noise are present in stats report */
   1601 	if (le32toh(stats->rx.general.flags) != 1) {
   1602 		DPRINTF(("received statistics without RSSI\n"));
   1603 		return;
   1604 	}
   1605 
   1606 	if (calib->state == IWN_CALIB_STATE_ASSOC)
   1607 		iwn_compute_differential_gain(sc, &stats->rx.general);
   1608 	else if (calib->state == IWN_CALIB_STATE_RUN)
   1609 		iwn_tune_sensitivity(sc, &stats->rx);
   1610 }
   1611 
   1612 static void
   1613 iwn_tx_intr(struct iwn_softc *sc, struct iwn_rx_desc *desc)
   1614 {
   1615 	struct ifnet *ifp = sc->sc_ic.ic_ifp;
   1616 	struct iwn_tx_ring *ring = &sc->txq[desc->qid & 0xf];
   1617 	struct iwn_tx_data *txdata = &ring->data[desc->idx];
   1618 	struct iwn_tx_stat *stat = (struct iwn_tx_stat *)(desc + 1);
   1619 	struct iwn_node *wn = (struct iwn_node *)txdata->ni;
   1620 	uint32_t status;
   1621 
   1622 	DPRINTFN(4, ("tx done: qid=%d idx=%d retries=%d nkill=%d rate=%x "
   1623 		"duration=%d status=%x\n", desc->qid, desc->idx, stat->ntries,
   1624 		stat->nkill, stat->rate, le16toh(stat->duration),
   1625 		le32toh(stat->status)));
   1626 
   1627 	/*
   1628 	 * Update rate control statistics for the node.
   1629 	 */
   1630 	wn->amn.amn_txcnt++;
   1631 	if (stat->ntries > 0) {
   1632 		DPRINTFN(3, ("tx intr ntries %d\n", stat->ntries));
   1633 		wn->amn.amn_retrycnt++;
   1634 	}
   1635 
   1636 	status = le32toh(stat->status) & 0xff;
   1637 	if (status != 1 && status != 2)
   1638 		ifp->if_oerrors++;
   1639 	else
   1640 		ifp->if_opackets++;
   1641 
   1642 	bus_dmamap_unload(sc->sc_dmat, txdata->map);
   1643 	m_freem(txdata->m);
   1644 	txdata->m = NULL;
   1645 	ieee80211_free_node(txdata->ni);
   1646 	txdata->ni = NULL;
   1647 
   1648 	ring->queued--;
   1649 
   1650 	sc->sc_tx_timer = 0;
   1651 	ifp->if_flags &= ~IFF_OACTIVE;
   1652 	iwn_start(ifp);
   1653 }
   1654 
   1655 static void
   1656 iwn_cmd_intr(struct iwn_softc *sc, struct iwn_rx_desc *desc)
   1657 {
   1658 	struct iwn_tx_ring *ring = &sc->txq[4];
   1659 	struct iwn_tx_data *data;
   1660 
   1661 	if ((desc->qid & 0xf) != 4)
   1662 		return;	/* not a command ack */
   1663 
   1664 	data = &ring->data[desc->idx];
   1665 
   1666 	/* if the command was mapped in a mbuf, free it */
   1667 	if (data->m != NULL) {
   1668 		bus_dmamap_unload(sc->sc_dmat, data->map);
   1669 		m_freem(data->m);
   1670 		data->m = NULL;
   1671 	}
   1672 
   1673 	wakeup(&ring->cmd[desc->idx]);
   1674 }
   1675 
   1676 static void
   1677 iwn_notif_intr(struct iwn_softc *sc)
   1678 {
   1679 	struct ieee80211com *ic = &sc->sc_ic;
   1680 	struct ifnet *ifp = ic->ic_ifp;
   1681 	uint16_t hw;
   1682 
   1683 	hw = le16toh(sc->shared->closed_count);
   1684 	while (sc->rxq.cur != hw) {
   1685 		struct iwn_rx_data *data = &sc->rxq.data[sc->rxq.cur];
   1686 		struct iwn_rx_desc *desc = (void *)data->m->m_ext.ext_buf;
   1687 
   1688 		DPRINTFN(4,("rx notification qid=%x idx=%d flags=%x type=%d "
   1689 			"len=%d\n", desc->qid, desc->idx, desc->flags, desc->type,
   1690 			le32toh(desc->len)));
   1691 
   1692 		if (!(desc->qid & 0x80))	/* reply to a command */
   1693 			iwn_cmd_intr(sc, desc);
   1694 
   1695 		switch (desc->type) {
   1696 		case IWN_RX_DONE:
   1697 		case IWN_AMPDU_RX_DONE:
   1698 			iwn_rx_intr(sc, desc, data);
   1699 			break;
   1700 
   1701 		case IWN_AMPDU_RX_START:
   1702 			iwn_ampdu_rx_start(sc, desc);
   1703 			break;
   1704 
   1705 		case IWN_TX_DONE:
   1706 			/* a 802.11 frame has been transmitted */
   1707 			iwn_tx_intr(sc, desc);
   1708 			break;
   1709 
   1710 		case IWN_RX_STATISTICS:
   1711 		case IWN_BEACON_STATISTICS:
   1712 			iwn_rx_statistics(sc, desc);
   1713 			break;
   1714 
   1715 		case IWN_BEACON_MISSED:
   1716 		{
   1717 			struct iwn_beacon_missed *miss =
   1718 			    (struct iwn_beacon_missed *)(desc + 1);
   1719 			/*
   1720 			 * If more than 5 consecutive beacons are missed,
   1721 			 * reinitialize the sensitivity state machine.
   1722 			 */
   1723 			DPRINTFN(2, ("beacons missed %d/%d\n",
   1724 				le32toh(miss->consecutive), le32toh(miss->total)));
   1725 			if (ic->ic_state == IEEE80211_S_RUN &&
   1726 			    le32toh(miss->consecutive) > 5)
   1727 				(void)iwn_init_sensitivity(sc);
   1728 			break;
   1729 		}
   1730 
   1731 		case IWN_UC_READY:
   1732 		{
   1733 			struct iwn_ucode_info *uc =
   1734 			    (struct iwn_ucode_info *)(desc + 1);
   1735 
   1736 			/* the microcontroller is ready */
   1737 			DPRINTF(("microcode alive notification version=%d.%d "
   1738 				"subtype=%x alive=%x\n", uc->major, uc->minor,
   1739 				uc->subtype, le32toh(uc->valid)));
   1740 
   1741 			if (le32toh(uc->valid) != 1) {
   1742 				aprint_error_dev(sc->sc_dev, "microcontroller initialization "
   1743 				    "failed\n");
   1744 				break;
   1745 			}
   1746 			if (uc->subtype == IWN_UCODE_INIT) {
   1747 				/* save microcontroller's report */
   1748 				memcpy(&sc->ucode_info, uc, sizeof (*uc));
   1749 			}
   1750 			break;
   1751 		}
   1752 		case IWN_STATE_CHANGED:
   1753 		{
   1754 			uint32_t *status = (uint32_t *)(desc + 1);
   1755 
   1756 			/* enabled/disabled notification */
   1757 			DPRINTF(("state changed to %x\n", le32toh(*status)));
   1758 
   1759 			if (le32toh(*status) & 1) {
   1760 				/* the radio button has to be pushed */
   1761 				aprint_error_dev(sc->sc_dev, "Radio transmitter is off\n");
   1762 				/* turn the interface down */
   1763 				ifp->if_flags &= ~IFF_UP;
   1764 				iwn_stop(ifp, 1);
   1765 				return;	/* no further processing */
   1766 			}
   1767 			break;
   1768 		}
   1769 		case IWN_START_SCAN:
   1770 		{
   1771 			struct iwn_start_scan *scan =
   1772 			    (struct iwn_start_scan *)(desc + 1);
   1773 
   1774 			DPRINTFN(2, ("scanning channel %d status %x\n",
   1775 				scan->chan, le32toh(scan->status)));
   1776 
   1777 			/* fix current channel */
   1778 			ic->ic_bss->ni_chan = &ic->ic_channels[scan->chan];
   1779 			break;
   1780 		}
   1781 		case IWN_STOP_SCAN:
   1782 		{
   1783 			struct iwn_stop_scan *scan =
   1784 			    (struct iwn_stop_scan *)(desc + 1);
   1785 
   1786 			DPRINTF(("scan finished nchan=%d status=%d chan=%d\n",
   1787 				scan->nchan, scan->status, scan->chan));
   1788 
   1789 			if (scan->status == 1 && scan->chan <= 14) {
   1790 				/*
   1791 				 * We just finished scanning 802.11g channels,
   1792 				 * start scanning 802.11a ones.
   1793 				 */
   1794 				if (iwn_scan(sc, IEEE80211_CHAN_A) == 0)
   1795 					break;
   1796 			}
   1797 			sc->is_scanning = false;
   1798 			ieee80211_end_scan(ic);
   1799 			break;
   1800 		}
   1801 		}
   1802 
   1803 		sc->rxq.cur = (sc->rxq.cur + 1) % IWN_RX_RING_COUNT;
   1804 	}
   1805 
   1806 	/* tell the firmware what we have processed */
   1807 	hw = (hw == 0) ? IWN_RX_RING_COUNT - 1 : hw - 1;
   1808 	IWN_WRITE(sc, IWN_RX_WIDX, hw & ~7);
   1809 }
   1810 
   1811 static int
   1812 iwn_intr(void *arg)
   1813 {
   1814 	struct iwn_softc *sc = arg;
   1815 	struct ifnet *ifp = sc->sc_ic.ic_ifp;
   1816 	uint32_t r1, r2;
   1817 
   1818 	/* disable interrupts */
   1819 	IWN_WRITE(sc, IWN_MASK, 0);
   1820 
   1821 	r1 = IWN_READ(sc, IWN_INTR);
   1822 	r2 = IWN_READ(sc, IWN_INTR_STATUS);
   1823 
   1824 	if (r1 == 0 && r2 == 0) {
   1825 		if (ifp->if_flags & IFF_UP)
   1826 			IWN_WRITE(sc, IWN_MASK, IWN_INTR_MASK);
   1827 		return 0;	/* not for us */
   1828 	}
   1829 
   1830 	if (r1 == 0xffffffff)
   1831 		return 0;	/* hardware gone */
   1832 
   1833 	/* ack interrupts */
   1834 	IWN_WRITE(sc, IWN_INTR, r1);
   1835 	IWN_WRITE(sc, IWN_INTR_STATUS, r2);
   1836 
   1837 	DPRINTFN(5, ("interrupt reg1=%x reg2=%x\n", r1, r2));
   1838 
   1839 	if (r1 & IWN_RF_TOGGLED) {
   1840 		uint32_t tmp = IWN_READ(sc, IWN_GPIO_CTL);
   1841 		aprint_error_dev(sc->sc_dev, "RF switch: radio %s\n",
   1842 		    (tmp & IWN_GPIO_RF_ENABLED) ? "enabled" : "disabled");
   1843 	}
   1844 	if (r1 & IWN_CT_REACHED) {
   1845 		aprint_error_dev(sc->sc_dev, "critical temperature reached!\n");
   1846 	}
   1847 	if (r1 & (IWN_SW_ERROR | IWN_HW_ERROR)) {
   1848 		aprint_error_dev(sc->sc_dev, "fatal firmware error\n");
   1849 		sc->sc_ic.ic_ifp->if_flags &= ~IFF_UP;
   1850 		iwn_stop(sc->sc_ic.ic_ifp, 1);
   1851 		return 1;
   1852 	}
   1853 
   1854 	if ((r1 & (IWN_RX_INTR | IWN_SW_RX_INTR)) ||
   1855 	    (r2 & IWN_RX_STATUS_INTR))
   1856 		iwn_notif_intr(sc);
   1857 
   1858 	if (r1 & IWN_ALIVE_INTR)
   1859 		wakeup(sc);
   1860 
   1861 	/* re-enable interrupts */
   1862 	if (ifp->if_flags & IFF_UP)
   1863 		IWN_WRITE(sc, IWN_MASK, IWN_INTR_MASK);
   1864 
   1865 	return 1;
   1866 }
   1867 
   1868 static uint8_t
   1869 iwn_plcp_signal(int rate)
   1870 {
   1871 	switch (rate) {
   1872 		/* CCK rates (returned values are device-dependent) */
   1873 	case 2:		return 10;
   1874 	case 4:		return 20;
   1875 	case 11:	return 55;
   1876 	case 22:	return 110;
   1877 
   1878 		/* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
   1879 		/* R1-R4, (u)ral is R4-R1 */
   1880 	case 12:	return 0xd;
   1881 	case 18:	return 0xf;
   1882 	case 24:	return 0x5;
   1883 	case 36:	return 0x7;
   1884 	case 48:	return 0x9;
   1885 	case 72:	return 0xb;
   1886 	case 96:	return 0x1;
   1887 	case 108:	return 0x3;
   1888 	case 120:	return 0x3;
   1889 	}
   1890 	/* unknown rate (should not get there) */
   1891 	return 0;
   1892 }
   1893 
   1894 /* determine if a given rate is CCK or OFDM */
   1895 #define IWN_RATE_IS_OFDM(rate) ((rate) >= 12 && (rate) != 22)
   1896 
   1897 static int
   1898 iwn_tx_data(struct iwn_softc *sc, struct mbuf *m0, struct ieee80211_node *ni,
   1899     int ac)
   1900 {
   1901 	struct ieee80211com *ic = &sc->sc_ic;
   1902 	struct iwn_tx_ring *ring = &sc->txq[ac];
   1903 	struct iwn_tx_desc *desc;
   1904 	struct iwn_tx_data *data;
   1905 	struct iwn_tx_cmd *cmd;
   1906 	struct iwn_cmd_data *tx;
   1907 	struct ieee80211_frame *wh;
   1908 	struct ieee80211_key *k;
   1909 	const struct chanAccParams *cap;
   1910 	struct mbuf *mnew;
   1911 	bus_addr_t paddr;
   1912 	uint32_t flags;
   1913 	uint8_t type;
   1914 	int i, error, pad, rate, hdrlen, noack = 0;
   1915 
   1916 	desc = &ring->desc[ring->cur];
   1917 	data = &ring->data[ring->cur];
   1918 
   1919 	wh = mtod(m0, struct ieee80211_frame *);
   1920 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
   1921 	/* JAF XXX two lines above were not in wpi. check we don't duplicate this */
   1922 
   1923 	if (IEEE80211_QOS_HAS_SEQ(wh)) {
   1924 		hdrlen = sizeof (struct ieee80211_qosframe);
   1925 		cap = &ic->ic_wme.wme_chanParams;
   1926 		noack = cap->cap_wmeParams[ac].wmep_noackPolicy;
   1927 	} else
   1928 		hdrlen = sizeof (struct ieee80211_frame);
   1929 
   1930 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
   1931 		k = ieee80211_crypto_encap(ic, ni, m0);
   1932 		if (k == NULL) {
   1933 			m_freem(m0);
   1934 			return ENOBUFS;
   1935 		}
   1936 		/* packet header may have moved, reset our local pointer */
   1937 		wh = mtod(m0, struct ieee80211_frame *);
   1938 	}
   1939 
   1940 	/* pickup a rate */
   1941 	if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
   1942 	    IEEE80211_FC0_TYPE_MGT) {
   1943 		/* mgmt frames are sent at the lowest available bit-rate */
   1944 		rate = ni->ni_rates.rs_rates[0];
   1945 	} else {
   1946 		if (ic->ic_fixed_rate != -1) {
   1947 			rate = ic->ic_sup_rates[ic->ic_curmode].
   1948 			    rs_rates[ic->ic_fixed_rate];
   1949 		} else
   1950 			rate = ni->ni_rates.rs_rates[ni->ni_txrate];
   1951 	}
   1952 	rate &= IEEE80211_RATE_VAL;
   1953 
   1954 #if NBPFILTER > 0
   1955 	if (sc->sc_drvbpf != NULL) {
   1956 		struct iwn_tx_radiotap_header *tap = &sc->sc_txtap;
   1957 
   1958 		tap->wt_flags = 0;
   1959 		tap->wt_chan_freq = htole16(ni->ni_chan->ic_freq);
   1960 		tap->wt_chan_flags = htole16(ni->ni_chan->ic_flags);
   1961 		tap->wt_rate = rate;
   1962 		tap->wt_hwqueue = ac;
   1963 		if (wh->i_fc[1] & IEEE80211_FC1_WEP)
   1964 			tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
   1965 
   1966 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m0);
   1967 	}
   1968 #endif
   1969 
   1970 	cmd = &ring->cmd[ring->cur];
   1971 	cmd->code = IWN_CMD_TX_DATA;
   1972 	cmd->flags = 0;
   1973 	cmd->qid = ring->qid;
   1974 	cmd->idx = ring->cur;
   1975 
   1976 	tx = (struct iwn_cmd_data *)cmd->data;
   1977 
   1978 	flags = IWN_TX_AUTO_SEQ;
   1979 	if (!noack && !IEEE80211_IS_MULTICAST(wh->i_addr1)){
   1980 		flags |= IWN_TX_NEED_ACK;
   1981 	}else if (m0->m_pkthdr.len + IEEE80211_CRC_LEN > ic->ic_rtsthreshold)
   1982 		flags |= htole32(IWN_TX_NEED_RTS | IWN_TX_FULL_TXOP);
   1983 
   1984 	tx->id = IEEE80211_IS_MULTICAST(wh->i_addr1) ? IWN_ID_BROADCAST : IWN_ID_BSS;
   1985 
   1986 	if (type == IEEE80211_FC0_TYPE_MGT) {
   1987 		uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
   1988 
   1989 		/* tell h/w to set timestamp in probe responses */
   1990 		if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
   1991 			flags |= IWN_TX_INSERT_TSTAMP;
   1992 
   1993 		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
   1994 		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
   1995 			tx->timeout = htole16(3);
   1996 		else
   1997 			tx->timeout = htole16(2);
   1998 	} else
   1999 		tx->timeout = htole16(0);
   2000 
   2001 	if (hdrlen & 3) {
   2002 		/* first segment's length must be a multiple of 4 */
   2003 		flags |= IWN_TX_NEED_PADDING;
   2004 		pad = 4 - (hdrlen & 3);
   2005 	} else
   2006 		pad = 0;
   2007 
   2008 	tx->flags = htole32(flags);
   2009 	tx->len = htole16(m0->m_pkthdr.len);
   2010 	tx->rate = iwn_plcp_signal(rate);
   2011 	tx->rts_ntries = 60;
   2012 	tx->data_ntries = 15;
   2013 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
   2014 
   2015 	/* XXX alternate between Ant A and Ant B ? */
   2016 	tx->rflags = IWN_RFLAG_ANT_B;
   2017 	if (tx->id == IWN_ID_BROADCAST) {
   2018 		tx->ridx = IWN_MAX_TX_RETRIES - 1;
   2019 		if (!IWN_RATE_IS_OFDM(rate))
   2020 			tx->rflags |= IWN_RFLAG_CCK;
   2021 	} else {
   2022 		tx->ridx = 0;
   2023 		/* tell adapter to ignore rflags */
   2024 		tx->flags |= htole32(IWN_TX_USE_NODE_RATE);
   2025 	}
   2026 
   2027 	/* copy and trim IEEE802.11 header */
   2028 	memcpy((uint8_t *)(tx + 1), wh, hdrlen);
   2029 	m_adj(m0, hdrlen);
   2030 
   2031 	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
   2032 	    BUS_DMA_WRITE | BUS_DMA_NOWAIT);
   2033 	if (error != 0 && error != EFBIG) {
   2034 		aprint_error_dev(sc->sc_dev, "could not map mbuf (error %d)\n", error);
   2035 		m_freem(m0);
   2036 		return error;
   2037 	}
   2038 	if (error != 0) {
   2039 		/* too many fragments, linearize */
   2040 
   2041 		MGETHDR(mnew, M_DONTWAIT, MT_DATA);
   2042 		if (mnew == NULL) {
   2043 			m_freem(m0);
   2044 			return ENOMEM;
   2045 		}
   2046 		M_COPY_PKTHDR(mnew, m0);
   2047 		if (m0->m_pkthdr.len > MHLEN) {
   2048 			MCLGET(mnew, M_DONTWAIT);
   2049 			if (!(mnew->m_flags & M_EXT)) {
   2050 				m_freem(m0);
   2051 				m_freem(mnew);
   2052 				return ENOMEM;
   2053 			}
   2054 		}
   2055 
   2056 		m_copydata(m0, 0, m0->m_pkthdr.len, mtod(mnew, void *));
   2057 		m_freem(m0);
   2058 		mnew->m_len = mnew->m_pkthdr.len;
   2059 		m0 = mnew;
   2060 
   2061 		error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
   2062 		    BUS_DMA_WRITE | BUS_DMA_NOWAIT);
   2063 		if (error != 0) {
   2064 			aprint_error_dev(sc->sc_dev, "could not map mbuf (error %d)\n", error);
   2065 			m_freem(m0);
   2066 			return error;
   2067 		}
   2068 	}
   2069 
   2070 	data->m = m0;
   2071 	data->ni = ni;
   2072 
   2073 	DPRINTFN(4, ("sending data: qid=%d idx=%d len=%d nsegs=%d\n",
   2074 		ring->qid, ring->cur, m0->m_pkthdr.len, data->map->dm_nsegs));
   2075 
   2076 	paddr = ring->cmd_dma.paddr + ring->cur * sizeof (struct iwn_tx_cmd);
   2077 	tx->loaddr = htole32(paddr + 4 +
   2078 	    offsetof(struct iwn_cmd_data, ntries));
   2079 	tx->hiaddr = 0;	/* limit to 32-bit physical addresses */
   2080 
   2081 	/* first scatter/gather segment is used by the tx data command */
   2082 	IWN_SET_DESC_NSEGS(desc, 1 + data->map->dm_nsegs);
   2083 	IWN_SET_DESC_SEG(desc, 0, paddr, 4 + sizeof (*tx) + hdrlen + pad);
   2084 	for (i = 1; i <= data->map->dm_nsegs; i++) {
   2085 		IWN_SET_DESC_SEG(desc, i, data->map->dm_segs[i - 1].ds_addr,
   2086 		    data->map->dm_segs[i - 1].ds_len);
   2087 	}
   2088 	sc->shared->len[ring->qid][ring->cur] =
   2089 	    htole16(hdrlen + m0->m_pkthdr.len + 8);
   2090 	if (ring->cur < IWN_TX_WINDOW) {
   2091 		sc->shared->len[ring->qid][ring->cur + IWN_TX_RING_COUNT] =
   2092 		    htole16(hdrlen + m0->m_pkthdr.len + 8);
   2093 	}
   2094 
   2095 	ring->queued++;
   2096 
   2097 	/* kick ring */
   2098 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
   2099 	IWN_WRITE(sc, IWN_TX_WIDX, ring->qid << 8 | ring->cur);
   2100 
   2101 	return 0;
   2102 }
   2103 
   2104 static void
   2105 iwn_start(struct ifnet *ifp)
   2106 {
   2107 	struct iwn_softc *sc = ifp->if_softc;
   2108 	struct ieee80211com *ic = &sc->sc_ic;
   2109 	struct ieee80211_node *ni;
   2110 	struct ether_header *eh;
   2111 	struct mbuf *m0;
   2112 	int ac;
   2113 
   2114 	/*
   2115 	 * net80211 may still try to send management frames even if the
   2116 	 * IFF_RUNNING flag is not set...
   2117 	 */
   2118 	if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
   2119 		return;
   2120 
   2121 	for (;;) {
   2122 		IF_DEQUEUE(&ic->ic_mgtq, m0);
   2123 		if (m0 != NULL) {
   2124 			/* management frames go into ring 0 */
   2125 
   2126 
   2127 			ni = (struct ieee80211_node *)m0->m_pkthdr.rcvif;
   2128 			m0->m_pkthdr.rcvif = NULL;
   2129 
   2130 			/* management goes into ring 0 */
   2131 			if (sc->txq[0].queued > sc->txq[0].count - 8) {
   2132 				ifp->if_oerrors++;
   2133 				continue;
   2134 			}
   2135 
   2136 #if NBPFILTER > 0
   2137 			if (ic->ic_rawbpf != NULL)
   2138 				bpf_mtap(ic->ic_rawbpf, m0);
   2139 #endif
   2140 			if (iwn_tx_data(sc, m0, ni, 0) != 0) {
   2141 				ifp->if_oerrors++;
   2142 				break;
   2143 			}
   2144 		} else {
   2145 			if (ic->ic_state != IEEE80211_S_RUN)
   2146 				break;
   2147 			IFQ_POLL(&ifp->if_snd, m0);
   2148 			if (m0 == NULL)
   2149 				break;
   2150 
   2151 			if (m0->m_len < sizeof (*eh) &&
   2152 			    (m0 = m_pullup(m0, sizeof (*eh))) != NULL) {
   2153 				ifp->if_oerrors++;
   2154 				continue;
   2155 			}
   2156 			eh = mtod(m0, struct ether_header *);
   2157 			ni = ieee80211_find_txnode(ic, eh->ether_dhost);
   2158 			if (ni == NULL) {
   2159 				m_freem(m0);
   2160 				ifp->if_oerrors++;
   2161 				continue;
   2162 			}
   2163 			/*JAF C266 */
   2164 			/* classify mbuf so we can find which tx ring to use */
   2165 			if (ieee80211_classify(ic, m0, ni) != 0) {
   2166 				m_freem(m0);
   2167 				ieee80211_free_node(ni);
   2168 				ifp->if_oerrors++;
   2169 				continue;
   2170 			}
   2171 
   2172 			/* no QoS encapsulation for EAPOL frames */
   2173 			ac = (eh->ether_type != htons(ETHERTYPE_PAE)) ?
   2174 			    M_WME_GETAC(m0) : WME_AC_BE;
   2175 
   2176 			if (sc->txq[ac].queued > sc->txq[ac].count - 8) {
   2177 
   2178 				/* there is no place left in this ring */
   2179 				ifp->if_flags |= IFF_OACTIVE;
   2180 				break;
   2181 			}
   2182 			IFQ_DEQUEUE(&ifp->if_snd, m0);
   2183 #if NBPFILTER > 0
   2184 			if (ifp->if_bpf != NULL)
   2185 				bpf_mtap(ifp->if_bpf, m0);
   2186 #endif
   2187 			m0 = ieee80211_encap(ic, m0, ni);
   2188 			if (m0 == NULL) {
   2189 				ieee80211_free_node(ni);
   2190 				ifp->if_oerrors++;
   2191 				continue;
   2192 			}
   2193 #if NBPFILTER > 0
   2194 			if (ic->ic_rawbpf != NULL)
   2195 				bpf_mtap(ic->ic_rawbpf, m0);
   2196 #endif
   2197 			if (iwn_tx_data(sc, m0, ni, ac) != 0) {
   2198 				ieee80211_free_node(ni);
   2199 				ifp->if_oerrors++;
   2200 				break;
   2201 			}
   2202 		}
   2203 
   2204 		sc->sc_tx_timer = 5;
   2205 		ifp->if_timer = 1;
   2206 	}
   2207 }
   2208 
   2209 static void
   2210 iwn_watchdog(struct ifnet *ifp)
   2211 {
   2212 	struct iwn_softc *sc = ifp->if_softc;
   2213 
   2214 	ifp->if_timer = 0;
   2215 
   2216 	if (sc->sc_tx_timer > 0) {
   2217 		if (--sc->sc_tx_timer == 0) {
   2218 			aprint_error_dev(sc->sc_dev, "device timeout\n");
   2219 			ifp->if_flags &= ~IFF_UP;
   2220 			iwn_stop(ifp, 1);
   2221 			ifp->if_oerrors++;
   2222 			return;
   2223 		}
   2224 		ifp->if_timer = 1;
   2225 	}
   2226 
   2227 	ieee80211_watchdog(&sc->sc_ic);
   2228 }
   2229 
   2230 static int
   2231 iwn_ioctl(struct ifnet *ifp, u_long cmd, void * data)
   2232 {
   2233 
   2234 #define IS_RUNNING(ifp)							\
   2235 	((ifp->if_flags & IFF_UP) && (ifp->if_flags & IFF_RUNNING))
   2236 
   2237 	struct iwn_softc *sc = ifp->if_softc;
   2238 	struct ieee80211com *ic = &sc->sc_ic;
   2239 	int s, error = 0;
   2240 
   2241 	s = splnet();
   2242 
   2243 	switch (cmd) {
   2244 	case SIOCSIFFLAGS:
   2245 		if (ifp->if_flags & IFF_UP) {
   2246 			if (!(ifp->if_flags & IFF_RUNNING))
   2247 				iwn_init(ifp);
   2248 		} else {
   2249 			if (ifp->if_flags & IFF_RUNNING)
   2250 				iwn_stop(ifp, 1);
   2251 		}
   2252 		break;
   2253 
   2254 	case SIOCADDMULTI:
   2255 	case SIOCDELMULTI:
   2256 		/* XXX no h/w multicast filter? --dyoung */
   2257 		if ((error = ether_ioctl(ifp, cmd, data)) == ENETRESET) {
   2258 			/* setup multicast filter, etc */
   2259 			error = 0;
   2260 		}
   2261 		break;
   2262 
   2263 	default:
   2264 		error = ieee80211_ioctl(ic, cmd, data);
   2265 	}
   2266 
   2267 	if (error == ENETRESET) {
   2268 		if (IS_RUNNING(ifp) &&
   2269 		    (ic->ic_roaming != IEEE80211_ROAMING_MANUAL))
   2270 			iwn_init(ifp);
   2271 		error = 0;
   2272 	}
   2273 
   2274 	splx(s);
   2275 	return error;
   2276 
   2277 #undef IS_RUNNING
   2278 }
   2279 
   2280 static void
   2281 iwn_read_eeprom(struct iwn_softc *sc)
   2282 {
   2283 	struct ieee80211com *ic = &sc->sc_ic;
   2284 	char domain[4];
   2285 	uint16_t val;
   2286 	int i, error;
   2287 
   2288 	if ((error = iwn_eeprom_lock(sc)) != 0) {
   2289 		aprint_error_dev(sc->sc_dev, "could not lock EEPROM (error=%d)\n", error);
   2290 		return;
   2291 	}
   2292 	/* read and print regulatory domain */
   2293 	iwn_read_prom_data(sc, IWN_EEPROM_DOMAIN, domain, 4);
   2294 	aprint_error_dev(sc->sc_dev, "%.4s", domain);
   2295 
   2296 	/* read and print MAC address */
   2297 	iwn_read_prom_data(sc, IWN_EEPROM_MAC, ic->ic_myaddr, 6);
   2298 	aprint_error(", address %s\n", ether_sprintf(ic->ic_myaddr));
   2299 
   2300 	/* read the list of authorized channels */
   2301 	for (i = 0; i < IWN_CHAN_BANDS_COUNT; i++)
   2302 		iwn_read_eeprom_channels(sc, i);
   2303 
   2304 	/* read maximum allowed Tx power for 2GHz and 5GHz bands */
   2305 	iwn_read_prom_data(sc, IWN_EEPROM_MAXPOW, &val, 2);
   2306 	sc->maxpwr2GHz = val & 0xff;
   2307 	sc->maxpwr5GHz = val >> 8;
   2308 	/* check that EEPROM values are correct */
   2309 	if (sc->maxpwr5GHz < 20 || sc->maxpwr5GHz > 50)
   2310 		sc->maxpwr5GHz = 38;
   2311 	if (sc->maxpwr2GHz < 20 || sc->maxpwr2GHz > 50)
   2312 		sc->maxpwr2GHz = 38;
   2313 	DPRINTF(("maxpwr 2GHz=%d 5GHz=%d\n", sc->maxpwr2GHz, sc->maxpwr5GHz));
   2314 
   2315 	/* read voltage at which samples were taken */
   2316 	iwn_read_prom_data(sc, IWN_EEPROM_VOLTAGE, &val, 2);
   2317 	sc->eeprom_voltage = (int16_t)le16toh(val);
   2318 	DPRINTF(("voltage=%d (in 0.3V)\n", sc->eeprom_voltage));
   2319 
   2320 	/* read power groups */
   2321 	iwn_read_prom_data(sc, IWN_EEPROM_BANDS, sc->bands, sizeof sc->bands);
   2322 #ifdef IWN_DEBUG
   2323 	if (iwn_debug > 0) {
   2324 		for (i = 0; i < IWN_NBANDS; i++)
   2325 			iwn_print_power_group(sc, i);
   2326 	}
   2327 #endif
   2328 	iwn_eeprom_unlock(sc);
   2329 }
   2330 
   2331 static void
   2332 iwn_read_eeprom_channels(struct iwn_softc *sc, int n)
   2333 {
   2334 	struct ieee80211com *ic = &sc->sc_ic;
   2335 	const struct iwn_chan_band *band = &iwn_bands[n];
   2336 	struct iwn_eeprom_chan channels[IWN_MAX_CHAN_PER_BAND];
   2337 	int chan, i;
   2338 
   2339 	iwn_read_prom_data(sc, band->addr, channels,
   2340 	    band->nchan * sizeof (struct iwn_eeprom_chan));
   2341 
   2342 	for (i = 0; i < band->nchan; i++) {
   2343 		if (!(channels[i].flags & IWN_EEPROM_CHAN_VALID))
   2344 			continue;
   2345 
   2346 		chan = band->chan[i];
   2347 
   2348 		if (n == 0) {	/* 2GHz band */
   2349 			ic->ic_channels[chan].ic_freq =
   2350 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_2GHZ);
   2351 			ic->ic_channels[chan].ic_flags =
   2352 			    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
   2353 			    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
   2354 
   2355 		} else {	/* 5GHz band */
   2356 			/*
   2357 			 * Some adapters support channels 7, 8, 11 and 12
   2358 			 * both in the 2GHz *and* 5GHz bands.
   2359 			 * Because of limitations in our net80211(9) stack,
   2360 			 * we can't support these channels in 5GHz band.
   2361 			 */
   2362 			if (chan <= 14)
   2363 				continue;
   2364 
   2365 			ic->ic_channels[chan].ic_freq =
   2366 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_5GHZ);
   2367 			ic->ic_channels[chan].ic_flags = IEEE80211_CHAN_A;
   2368 		}
   2369 
   2370 		/* is active scan allowed on this channel? */
   2371 		if (!(channels[i].flags & IWN_EEPROM_CHAN_ACTIVE)) {
   2372 			ic->ic_channels[chan].ic_flags |=
   2373 			    IEEE80211_CHAN_PASSIVE;
   2374 		}
   2375 
   2376 		/* save maximum allowed power for this channel */
   2377 		sc->maxpwr[chan] = channels[i].maxpwr;
   2378 
   2379 		DPRINTF(("adding chan %d flags=0x%x maxpwr=%d\n",
   2380 			chan, channels[i].flags, sc->maxpwr[chan]));
   2381 	}
   2382 }
   2383 
   2384 #ifdef IWN_DEBUG
   2385 static void
   2386 iwn_print_power_group(struct iwn_softc *sc, int i)
   2387 {
   2388 	struct iwn_eeprom_band *band = &sc->bands[i];
   2389 	struct iwn_eeprom_chan_samples *chans = band->chans;
   2390 	int j, c;
   2391 
   2392 	DPRINTF(("===band %d===\n", i));
   2393 	DPRINTF(("chan lo=%d, chan hi=%d\n", band->lo, band->hi));
   2394 	DPRINTF(("chan1 num=%d\n", chans[0].num));
   2395 	for (c = 0; c < IWN_NTXCHAINS; c++) {
   2396 		for (j = 0; j < IWN_NSAMPLES; j++) {
   2397 			DPRINTF(("chain %d, sample %d: temp=%d gain=%d "
   2398 				"power=%d pa_det=%d\n", c, j,
   2399 				chans[0].samples[c][j].temp,
   2400 				chans[0].samples[c][j].gain,
   2401 				chans[0].samples[c][j].power,
   2402 				chans[0].samples[c][j].pa_det));
   2403 		}
   2404 	}
   2405 	DPRINTF(("chan2 num=%d\n", chans[1].num));
   2406 	for (c = 0; c < IWN_NTXCHAINS; c++) {
   2407 		for (j = 0; j < IWN_NSAMPLES; j++) {
   2408 			DPRINTF(("chain %d, sample %d: temp=%d gain=%d "
   2409 				"power=%d pa_det=%d\n", c, j,
   2410 				chans[1].samples[c][j].temp,
   2411 				chans[1].samples[c][j].gain,
   2412 				chans[1].samples[c][j].power,
   2413 				chans[1].samples[c][j].pa_det));
   2414 		}
   2415 	}
   2416 }
   2417 #endif
   2418 
   2419 /*
   2420  * Send a command to the firmware.
   2421  */
   2422 static int
   2423 iwn_cmd(struct iwn_softc *sc, int code, const void *buf, int size, int async)
   2424 {
   2425 	struct iwn_tx_ring *ring = &sc->txq[4];
   2426 	struct iwn_tx_desc *desc;
   2427 	struct iwn_tx_cmd *cmd;
   2428 	bus_addr_t paddr;
   2429 
   2430 	KASSERT(size <= sizeof cmd->data);
   2431 
   2432 	desc = &ring->desc[ring->cur];
   2433 	cmd = &ring->cmd[ring->cur];
   2434 
   2435 	cmd->code = code;
   2436 	cmd->flags = 0;
   2437 	cmd->qid = ring->qid;
   2438 	cmd->idx = ring->cur;
   2439 	memcpy(cmd->data, buf, size);
   2440 
   2441 	paddr = ring->cmd_dma.paddr + ring->cur * sizeof (struct iwn_tx_cmd);
   2442 
   2443 	IWN_SET_DESC_NSEGS(desc, 1);
   2444 	IWN_SET_DESC_SEG(desc, 0, paddr, 4 + size);
   2445 	sc->shared->len[ring->qid][ring->cur] = htole16(8);
   2446 	if (ring->cur < IWN_TX_WINDOW) {
   2447 		sc->shared->len[ring->qid][ring->cur + IWN_TX_RING_COUNT] =
   2448 		    htole16(8);
   2449 	}
   2450 
   2451 	/* kick cmd ring */
   2452 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
   2453 	IWN_WRITE(sc, IWN_TX_WIDX, ring->qid << 8 | ring->cur);
   2454 
   2455 	return async ? 0 : tsleep(cmd, PCATCH, "iwncmd", hz);
   2456 }
   2457 
   2458 /*
   2459  * Configure hardware multi-rate retries for one node.
   2460  */
   2461 static int
   2462 iwn_setup_node_mrr(struct iwn_softc *sc, uint8_t id, int async)
   2463 {
   2464 	struct ieee80211com *ic = &sc->sc_ic;
   2465 	struct iwn_cmd_mrr mrr;
   2466 	int i, ridx;
   2467 
   2468 	memset(&mrr, 0, sizeof mrr);
   2469 	mrr.id = id;
   2470 	mrr.ssmask = 2;
   2471 	mrr.dsmask = 3;
   2472 	mrr.ampdu_disable = 3;
   2473 	mrr.ampdu_limit = 4000;
   2474 
   2475 	if (id == IWN_ID_BSS)
   2476 		ridx = IWN_OFDM54;
   2477 	else if (ic->ic_curmode == IEEE80211_MODE_11A)
   2478 		ridx = IWN_OFDM6;
   2479 	else
   2480 		ridx = IWN_CCK1;
   2481 	for (i = 0; i < IWN_MAX_TX_RETRIES; i++) {
   2482 		mrr.table[i].rate = iwn_ridx_to_plcp[ridx];
   2483 		mrr.table[i].rflags = IWN_RFLAG_ANT_B;
   2484 		if (ridx <= IWN_CCK11)
   2485 			mrr.table[i].rflags |= IWN_RFLAG_CCK;
   2486 		ridx = iwn_prev_ridx[ridx];
   2487 	}
   2488 	return iwn_cmd(sc, IWN_CMD_NODE_MRR_SETUP, &mrr, sizeof mrr, async);
   2489 }
   2490 
   2491 static int
   2492 iwn_wme_update(struct ieee80211com *ic)
   2493 {
   2494 #define IWN_EXP2(v)	htole16((1 << (v)) - 1)
   2495 #define IWN_USEC(v)	htole16(IEEE80211_TXOP_TO_US(v))
   2496 	struct iwn_softc *sc = ic->ic_ifp->if_softc;
   2497 	const struct wmeParams *wmep;
   2498 	struct iwn_wme_setup wme;
   2499 	int ac;
   2500 
   2501 	/* don't override default WME values if WME is not actually enabled */
   2502 	if (!(ic->ic_flags & IEEE80211_F_WME))
   2503 		return 0;
   2504 
   2505 	wme.flags = 0;
   2506 	for (ac = 0; ac < WME_NUM_AC; ac++) {
   2507 		wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
   2508 		wme.ac[ac].aifsn = wmep->wmep_aifsn;
   2509 		wme.ac[ac].cwmin = IWN_EXP2(wmep->wmep_logcwmin);
   2510 		wme.ac[ac].cwmax = IWN_EXP2(wmep->wmep_logcwmax);
   2511 		wme.ac[ac].txop  = IWN_USEC(wmep->wmep_txopLimit);
   2512 
   2513 		DPRINTF(("setting WME for queue %d aifsn=%d cwmin=%d cwmax=%d "
   2514 			"txop=%d\n", ac, wme.ac[ac].aifsn, wme.ac[ac].cwmin,
   2515 			wme.ac[ac].cwmax, wme.ac[ac].txop));
   2516 	}
   2517 
   2518 	return iwn_cmd(sc, IWN_CMD_SET_WME, &wme, sizeof wme, 1);
   2519 #undef IWN_USEC
   2520 #undef IWN_EXP2
   2521 }
   2522 
   2523 
   2524 
   2525 static void
   2526 iwn_set_led(struct iwn_softc *sc, uint8_t which, uint8_t off, uint8_t on)
   2527 {
   2528 	struct iwn_cmd_led led;
   2529 
   2530 	led.which = which;
   2531 	led.unit = htole32(100000);	/* on/off in unit of 100ms */
   2532 	led.off = off;
   2533 	led.on = on;
   2534 
   2535 	(void)iwn_cmd(sc, IWN_CMD_SET_LED, &led, sizeof led, 1);
   2536 }
   2537 
   2538 /*
   2539  * Set the critical temperature at which the firmware will automatically stop
   2540  * the radio transmitter.
   2541  */
   2542 static int
   2543 iwn_set_critical_temp(struct iwn_softc *sc)
   2544 {
   2545 	struct iwn_ucode_info *uc = &sc->ucode_info;
   2546 	struct iwn_critical_temp crit;
   2547 	uint32_t r1, r2, r3, temp;
   2548 
   2549 	IWN_WRITE(sc, IWN_UCODE_CLR, IWN_CTEMP_STOP_RF);
   2550 
   2551 	r1 = le32toh(uc->temp[0].chan20MHz);
   2552 	r2 = le32toh(uc->temp[1].chan20MHz);
   2553 	r3 = le32toh(uc->temp[2].chan20MHz);
   2554 	/* inverse function of iwn_get_temperature() */
   2555 
   2556 	temp = r2 + ((IWN_CTOK(110) * (r3 - r1)) / 259);
   2557 
   2558 	memset(&crit, 0, sizeof crit);
   2559 	crit.tempR = htole32(temp);
   2560 	DPRINTF(("setting critical temperature to %u\n", temp));
   2561 	return iwn_cmd(sc, IWN_CMD_SET_CRITICAL_TEMP, &crit, sizeof crit, 0);
   2562 }
   2563 
   2564 static void
   2565 iwn_enable_tsf(struct iwn_softc *sc, struct ieee80211_node *ni)
   2566 {
   2567 	struct iwn_cmd_tsf tsf;
   2568 	uint64_t val, mod;
   2569 
   2570 	memset(&tsf, 0, sizeof tsf);
   2571 	memcpy(&tsf.tstamp, ni->ni_tstamp.data, 8);
   2572 	tsf.bintval = htole16(ni->ni_intval);
   2573 	tsf.lintval = htole16(10);
   2574 
   2575 	/* compute remaining time until next beacon */
   2576 	val = (uint64_t)ni->ni_intval * 1024;	/* msecs -> usecs */
   2577 	mod = le64toh(tsf.tstamp) % val;
   2578 	tsf.binitval = htole32((uint32_t)(val - mod));
   2579 
   2580 	DPRINTF(("TSF bintval=%u tstamp=%" PRIu64 ", init=%" PRIu64 "\n",
   2581 	    ni->ni_intval, le64toh(tsf.tstamp), val - mod));
   2582 
   2583 	if (iwn_cmd(sc, IWN_CMD_TSF, &tsf, sizeof tsf, 1) != 0)
   2584 		aprint_error_dev(sc->sc_dev, "could not enable TSF\n");
   2585 }
   2586 
   2587 static void
   2588 iwn_power_calibration(struct iwn_softc *sc, int temp)
   2589 {
   2590 	struct ieee80211com *ic = &sc->sc_ic;
   2591 
   2592 	DPRINTF(("temperature %d->%d\n", sc->temp, temp));
   2593 
   2594 	/* adjust Tx power if need be (delta >= 3C) */
   2595 	if (abs(temp - sc->temp) < 3)
   2596 		return;
   2597 
   2598 	sc->temp = temp;
   2599 
   2600 	DPRINTF(("setting Tx power for channel %d\n",
   2601 		ieee80211_chan2ieee(ic, ic->ic_bss->ni_chan)));
   2602 	if (iwn_set_txpower(sc, ic->ic_bss->ni_chan, 1) != 0) {
   2603 		/* just warn, too bad for the automatic calibration... */
   2604 		aprint_error_dev(sc->sc_dev, "could not adjust Tx power\n");
   2605 	}
   2606 }
   2607 
   2608 /*
   2609  * Set Tx power for a given channel (each rate has its own power settings).
   2610  * This function takes into account the regulatory information from EEPROM,
   2611  * the current temperature and the current voltage.
   2612  */
   2613 static int
   2614 iwn_set_txpower(struct iwn_softc *sc, struct ieee80211_channel *ch, int async)
   2615 {
   2616 /* fixed-point arithmetic division using a n-bit fractional part */
   2617 #define fdivround(a, b, n)						\
   2618 	((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
   2619 /* linear interpolation */
   2620 #define interpolate(x, x1, y1, x2, y2, n)				\
   2621 	((y1) + fdivround(((int)(x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
   2622 
   2623 	static const int tdiv[IWN_NATTEN_GROUPS] = { 9, 8, 8, 8, 6 };
   2624 	struct ieee80211com *ic = &sc->sc_ic;
   2625 	struct iwn_ucode_info *uc = &sc->ucode_info;
   2626 	struct iwn_cmd_txpower cmd;
   2627 	struct iwn_eeprom_chan_samples *chans;
   2628 	const uint8_t *rf_gain, *dsp_gain;
   2629 	int32_t vdiff, tdiff;
   2630 	int i, c, grp, maxpwr;
   2631 	u_int chan;
   2632 
   2633 	/* get channel number */
   2634 	chan = ieee80211_chan2ieee(ic, ch);
   2635 
   2636 	memset(&cmd, 0, sizeof cmd);
   2637 	cmd.band = IEEE80211_IS_CHAN_5GHZ(ch) ? 0 : 1;
   2638 	cmd.chan = chan;
   2639 
   2640 	if (IEEE80211_IS_CHAN_5GHZ(ch)) {
   2641 		maxpwr   = sc->maxpwr5GHz;
   2642 		rf_gain  = iwn_rf_gain_5ghz;
   2643 		dsp_gain = iwn_dsp_gain_5ghz;
   2644 	} else {
   2645 		maxpwr   = sc->maxpwr2GHz;
   2646 		rf_gain  = iwn_rf_gain_2ghz;
   2647 		dsp_gain = iwn_dsp_gain_2ghz;
   2648 	}
   2649 
   2650 	/* compute voltage compensation */
   2651 	vdiff = ((int32_t)le32toh(uc->volt) - sc->eeprom_voltage) / 7;
   2652 	if (vdiff > 0)
   2653 		vdiff *= 2;
   2654 	if (abs(vdiff) > 2)
   2655 		vdiff = 0;
   2656 	DPRINTF(("voltage compensation=%d (UCODE=%d, EEPROM=%d)\n",
   2657 		vdiff, le32toh(uc->volt), sc->eeprom_voltage));
   2658 
   2659 	/* get channel's attenuation group */
   2660 	if (chan <= 20)		/* 1-20 */
   2661 		grp = 4;
   2662 	else if (chan <= 43)	/* 34-43 */
   2663 		grp = 0;
   2664 	else if (chan <= 70)	/* 44-70 */
   2665 		grp = 1;
   2666 	else if (chan <= 124)	/* 71-124 */
   2667 		grp = 2;
   2668 	else			/* 125-200 */
   2669 		grp = 3;
   2670 	DPRINTF(("chan %d, attenuation group=%d\n", chan, grp));
   2671 
   2672 	/* get channel's sub-band */
   2673 	for (i = 0; i < IWN_NBANDS; i++)
   2674 		if (sc->bands[i].lo != 0 &&
   2675 		    sc->bands[i].lo <= chan && chan <= sc->bands[i].hi)
   2676 			break;
   2677 	chans = sc->bands[i].chans;
   2678 	DPRINTF(("chan %d sub-band=%d\n", chan, i));
   2679 
   2680 	for (c = 0; c < IWN_NTXCHAINS; c++) {
   2681 		uint8_t power, gain, temp;
   2682 		int maxchpwr, pwr, ridx, idx;
   2683 
   2684 		power = interpolate(chan,
   2685 		    chans[0].num, chans[0].samples[c][1].power,
   2686 		    chans[1].num, chans[1].samples[c][1].power, 1);
   2687 		gain  = interpolate(chan,
   2688 		    chans[0].num, chans[0].samples[c][1].gain,
   2689 		    chans[1].num, chans[1].samples[c][1].gain, 1);
   2690 		temp  = interpolate(chan,
   2691 		    chans[0].num, chans[0].samples[c][1].temp,
   2692 		    chans[1].num, chans[1].samples[c][1].temp, 1);
   2693 		DPRINTF(("Tx chain %d: power=%d gain=%d temp=%d\n",
   2694 			c, power, gain, temp));
   2695 
   2696 		/* compute temperature compensation */
   2697 		tdiff = ((sc->temp - temp) * 2) / tdiv[grp];
   2698 		DPRINTF(("temperature compensation=%d (current=%d, "
   2699 			"EEPROM=%d)\n", tdiff, sc->temp, temp));
   2700 
   2701 		for (ridx = 0; ridx <= IWN_RIDX_MAX; ridx++) {
   2702 			maxchpwr = sc->maxpwr[chan] * 2;
   2703 			if ((ridx / 8) & 1) {
   2704 				/* MIMO: decrease Tx power (-3dB) */
   2705 				maxchpwr -= 6;
   2706 			}
   2707 
   2708 			pwr = maxpwr - 10;
   2709 
   2710 			/* decrease power for highest OFDM rates */
   2711 			if ((ridx % 8) == 5)		/* 48Mbit/s */
   2712 				pwr -= 5;
   2713 			else if ((ridx % 8) == 6)	/* 54Mbit/s */
   2714 				pwr -= 7;
   2715 			else if ((ridx % 8) == 7)	/* 60Mbit/s */
   2716 				pwr -= 10;
   2717 
   2718 			if (pwr > maxchpwr)
   2719 				pwr = maxchpwr;
   2720 
   2721 			idx = gain - (pwr - power) - tdiff - vdiff;
   2722 			if ((ridx / 8) & 1)	/* MIMO */
   2723 				idx += (int32_t)le32toh(uc->atten[grp][c]);
   2724 
   2725 			if (cmd.band == 0)
   2726 				idx += 9;	/* 5GHz */
   2727 			if (ridx == IWN_RIDX_MAX)
   2728 				idx += 5;	/* CCK */
   2729 
   2730 			/* make sure idx stays in a valid range */
   2731 			if (idx < 0)
   2732 				idx = 0;
   2733 			else if (idx > IWN_MAX_PWR_INDEX)
   2734 				idx = IWN_MAX_PWR_INDEX;
   2735 
   2736 			DPRINTF(("Tx chain %d, rate idx %d: power=%d\n",
   2737 				c, ridx, idx));
   2738 			cmd.power[ridx].rf_gain[c] = rf_gain[idx];
   2739 			cmd.power[ridx].dsp_gain[c] = dsp_gain[idx];
   2740 		}
   2741 	}
   2742 
   2743 	DPRINTF(("setting tx power for chan %d\n", chan));
   2744 	return iwn_cmd(sc, IWN_CMD_TXPOWER, &cmd, sizeof cmd, async);
   2745 
   2746 #undef interpolate
   2747 #undef fdivround
   2748 }
   2749 
   2750 /*
   2751  * Get the best (maximum) RSSI among Rx antennas (in dBm).
   2752  */
   2753 static int
   2754 iwn_get_rssi(const struct iwn_rx_stat *stat)
   2755 {
   2756 	uint8_t mask, agc;
   2757 	int rssi;
   2758 
   2759 	mask = (le16toh(stat->antenna) >> 4) & 0x7;
   2760 	agc  = (le16toh(stat->agc) >> 7) & 0x7f;
   2761 
   2762 	rssi = 0;
   2763 	if (mask & (1 << 0))	/* Ant A */
   2764 		rssi = max(rssi, stat->rssi[0]);
   2765 	if (mask & (1 << 1))	/* Ant B */
   2766 		rssi = max(rssi, stat->rssi[2]);
   2767 	if (mask & (1 << 2))	/* Ant C */
   2768 		rssi = max(rssi, stat->rssi[4]);
   2769 
   2770 	return rssi - agc - IWN_RSSI_TO_DBM;
   2771 }
   2772 
   2773 /*
   2774  * Get the average noise among Rx antennas (in dBm).
   2775  */
   2776 static int
   2777 iwn_get_noise(const struct iwn_rx_general_stats *stats)
   2778 {
   2779 	int i, total, nbant, noise;
   2780 
   2781 	total = nbant = 0;
   2782 	for (i = 0; i < 3; i++) {
   2783 		if ((noise = le32toh(stats->noise[i]) & 0xff) == 0)
   2784 			continue;
   2785 		total += noise;
   2786 		nbant++;
   2787 	}
   2788 	/* there should be at least one antenna but check anyway */
   2789 	return (nbant == 0) ? -127 : (total / nbant) - 107;
   2790 }
   2791 
   2792 /*
   2793  * Read temperature (in degC) from the on-board thermal sensor.
   2794  */
   2795 static int
   2796 iwn_get_temperature(struct iwn_softc *sc)
   2797 {
   2798 	struct iwn_ucode_info *uc = &sc->ucode_info;
   2799 	int32_t r1, r2, r3, r4, temp;
   2800 
   2801 	r1 = le32toh(uc->temp[0].chan20MHz);
   2802 	r2 = le32toh(uc->temp[1].chan20MHz);
   2803 	r3 = le32toh(uc->temp[2].chan20MHz);
   2804 	r4 = le32toh(sc->rawtemp);
   2805 
   2806 	if (r1 == r3)	/* prevents division by 0 (should not happen) */
   2807 		return 0;
   2808 
   2809 	/* sign-extend 23-bit R4 value to 32-bit */
   2810 	r4 = (r4 << 8) >> 8;
   2811 	/* compute temperature */
   2812 	temp = (259 * (r4 - r2)) / (r3 - r1);
   2813 	temp = (temp * 97) / 100 + 8;
   2814 
   2815 	DPRINTF(("temperature %dK/%dC\n", temp, IWN_KTOC(temp)));
   2816 	return IWN_KTOC(temp);
   2817 }
   2818 
   2819 /*
   2820  * Initialize sensitivity calibration state machine.
   2821  */
   2822 static int
   2823 iwn_init_sensitivity(struct iwn_softc *sc)
   2824 {
   2825 	struct iwn_calib_state *calib = &sc->calib;
   2826 	struct iwn_phy_calib_cmd cmd;
   2827 	int error;
   2828 
   2829 	/* reset calibration state */
   2830 	memset(calib, 0, sizeof (*calib));
   2831 	calib->state = IWN_CALIB_STATE_INIT;
   2832 	calib->cck_state = IWN_CCK_STATE_HIFA;
   2833 	/* initial values taken from the reference driver */
   2834 	calib->corr_ofdm_x1     = 105;
   2835 	calib->corr_ofdm_mrc_x1 = 220;
   2836 	calib->corr_ofdm_x4     =  90;
   2837 	calib->corr_ofdm_mrc_x4 = 170;
   2838 	calib->corr_cck_x4      = 125;
   2839 	calib->corr_cck_mrc_x4  = 200;
   2840 	calib->energy_cck       = 100;
   2841 
   2842 	/* write initial sensitivity values */
   2843 	if ((error = iwn_send_sensitivity(sc)) != 0)
   2844 		return error;
   2845 
   2846 	memset(&cmd, 0, sizeof cmd);
   2847 	cmd.code = IWN_SET_DIFF_GAIN;
   2848 	/* differential gains initially set to 0 for all 3 antennas */
   2849 	DPRINTF(("setting differential gains\n"));
   2850 	return iwn_cmd(sc, IWN_PHY_CALIB, &cmd, sizeof cmd, 1);
   2851 }
   2852 
   2853 /*
   2854  * Collect noise and RSSI statistics for the first 20 beacons received
   2855  * after association and use them to determine connected antennas and
   2856  * set differential gains.
   2857  */
   2858 static void
   2859 iwn_compute_differential_gain(struct iwn_softc *sc,
   2860     const struct iwn_rx_general_stats *stats)
   2861 {
   2862 	struct iwn_calib_state *calib = &sc->calib;
   2863 	struct iwn_phy_calib_cmd cmd;
   2864 	int i, val;
   2865 
   2866 	/* accumulate RSSI and noise for all 3 antennas */
   2867 	for (i = 0; i < 3; i++) {
   2868 		calib->rssi[i] += le32toh(stats->rssi[i]) & 0xff;
   2869 		calib->noise[i] += le32toh(stats->noise[i]) & 0xff;
   2870 	}
   2871 
   2872 	/* we update differential gain only once after 20 beacons */
   2873 	if (++calib->nbeacons < 20)
   2874 		return;
   2875 
   2876 	/* determine antenna with highest average RSSI */
   2877 	val = max(calib->rssi[0], calib->rssi[1]);
   2878 	val = max(calib->rssi[2], val);
   2879 
   2880 	/* determine which antennas are connected */
   2881 	sc->antmsk = 0;
   2882 	for (i = 0; i < 3; i++)
   2883 		if (val - calib->rssi[i] <= 15 * 20)
   2884 			sc->antmsk |= 1 << i;
   2885 	/* if neither Ant A and Ant B are connected.. */
   2886 	if ((sc->antmsk & (1 << 0 | 1 << 1)) == 0)
   2887 		sc->antmsk |= 1 << 1;	/* ..mark Ant B as connected! */
   2888 
   2889 	/* get minimal noise among connected antennas */
   2890 	val = INT_MAX;	/* ok, there's at least one */
   2891 	for (i = 0; i < 3; i++)
   2892 		if (sc->antmsk & (1 << i))
   2893 			val = min(calib->noise[i], val);
   2894 
   2895 	memset(&cmd, 0, sizeof cmd);
   2896 	cmd.code = IWN_SET_DIFF_GAIN;
   2897 	/* set differential gains for connected antennas */
   2898 	for (i = 0; i < 3; i++) {
   2899 		if (sc->antmsk & (1 << i)) {
   2900 			cmd.gain[i] = (calib->noise[i] - val) / 30;
   2901 			/* limit differential gain to 3 */
   2902 			cmd.gain[i] = min(cmd.gain[i], 3);
   2903 			cmd.gain[i] |= IWN_GAIN_SET;
   2904 		}
   2905 	}
   2906 	DPRINTF(("setting differential gains Ant A/B/C: %x/%x/%x (%x)\n",
   2907 		cmd.gain[0], cmd.gain[1], cmd.gain[2], sc->antmsk));
   2908 	if (iwn_cmd(sc, IWN_PHY_CALIB, &cmd, sizeof cmd, 1) == 0)
   2909 		calib->state = IWN_CALIB_STATE_RUN;
   2910 }
   2911 
   2912 /*
   2913  * Tune RF Rx sensitivity based on the number of false alarms detected
   2914  * during the last beacon period.
   2915  */
   2916 static void
   2917 iwn_tune_sensitivity(struct iwn_softc *sc, const struct iwn_rx_stats *stats)
   2918 {
   2919 #define inc_clip(val, inc, max)						\
   2920 	if ((val) < (max)) {						\
   2921 		if ((val) < (max) - (inc))				\
   2922 			(val) += (inc);					\
   2923 		else							\
   2924 			(val) = (max);					\
   2925 		needs_update = 1;					\
   2926 	}
   2927 #define dec_clip(val, dec, min)						\
   2928 	if ((val) > (min)) {						\
   2929 		if ((val) > (min) + (dec))				\
   2930 			(val) -= (dec);					\
   2931 		else							\
   2932 			(val) = (min);					\
   2933 		needs_update = 1;					\
   2934 	}
   2935 
   2936 	struct iwn_calib_state *calib = &sc->calib;
   2937 	uint32_t val, rxena, fa;
   2938 	uint32_t energy[3], energy_min;
   2939 	uint8_t noise[3], noise_ref;
   2940 	int i, needs_update = 0;
   2941 
   2942 	/* check that we've been enabled long enough */
   2943 	if ((rxena = le32toh(stats->general.load)) == 0)
   2944 		return;
   2945 
   2946 	/* compute number of false alarms since last call for OFDM */
   2947 	fa  = le32toh(stats->ofdm.bad_plcp) - calib->bad_plcp_ofdm;
   2948 	fa += le32toh(stats->ofdm.fa) - calib->fa_ofdm;
   2949 	fa *= 200 * 1024;	/* 200TU */
   2950 
   2951 	/* save counters values for next call */
   2952 	calib->bad_plcp_ofdm = le32toh(stats->ofdm.bad_plcp);
   2953 	calib->fa_ofdm = le32toh(stats->ofdm.fa);
   2954 
   2955 	if (fa > 50 * rxena) {
   2956 		/* high false alarm count, decrease sensitivity */
   2957 		DPRINTFN(2, ("OFDM high false alarm count: %u\n", fa));
   2958 		inc_clip(calib->corr_ofdm_x1,     1, 140);
   2959 		inc_clip(calib->corr_ofdm_mrc_x1, 1, 270);
   2960 		inc_clip(calib->corr_ofdm_x4,     1, 120);
   2961 		inc_clip(calib->corr_ofdm_mrc_x4, 1, 210);
   2962 
   2963 	} else if (fa < 5 * rxena) {
   2964 		/* low false alarm count, increase sensitivity */
   2965 		DPRINTFN(2, ("OFDM low false alarm count: %u\n", fa));
   2966 		dec_clip(calib->corr_ofdm_x1,     1, 105);
   2967 		dec_clip(calib->corr_ofdm_mrc_x1, 1, 220);
   2968 		dec_clip(calib->corr_ofdm_x4,     1,  85);
   2969 		dec_clip(calib->corr_ofdm_mrc_x4, 1, 170);
   2970 	}
   2971 
   2972 	/* compute maximum noise among 3 antennas */
   2973 	for (i = 0; i < 3; i++)
   2974 		noise[i] = (le32toh(stats->general.noise[i]) >> 8) & 0xff;
   2975 	val = max(noise[0], noise[1]);
   2976 	val = max(noise[2], val);
   2977 	/* insert it into our samples table */
   2978 	calib->noise_samples[calib->cur_noise_sample] = val;
   2979 	calib->cur_noise_sample = (calib->cur_noise_sample + 1) % 20;
   2980 
   2981 	/* compute maximum noise among last 20 samples */
   2982 	noise_ref = calib->noise_samples[0];
   2983 	for (i = 1; i < 20; i++)
   2984 		noise_ref = max(noise_ref, calib->noise_samples[i]);
   2985 
   2986 	/* compute maximum energy among 3 antennas */
   2987 	for (i = 0; i < 3; i++)
   2988 		energy[i] = le32toh(stats->general.energy[i]);
   2989 	val = min(energy[0], energy[1]);
   2990 	val = min(energy[2], val);
   2991 	/* insert it into our samples table */
   2992 	calib->energy_samples[calib->cur_energy_sample] = val;
   2993 	calib->cur_energy_sample = (calib->cur_energy_sample + 1) % 10;
   2994 
   2995 	/* compute minimum energy among last 10 samples */
   2996 	energy_min = calib->energy_samples[0];
   2997 	for (i = 1; i < 10; i++)
   2998 		energy_min = max(energy_min, calib->energy_samples[i]);
   2999 	energy_min += 6;
   3000 
   3001 	/* compute number of false alarms since last call for CCK */
   3002 	fa  = le32toh(stats->cck.bad_plcp) - calib->bad_plcp_cck;
   3003 	fa += le32toh(stats->cck.fa) - calib->fa_cck;
   3004 	fa *= 200 * 1024;	/* 200TU */
   3005 
   3006 	/* save counters values for next call */
   3007 	calib->bad_plcp_cck = le32toh(stats->cck.bad_plcp);
   3008 	calib->fa_cck = le32toh(stats->cck.fa);
   3009 
   3010 	if (fa > 50 * rxena) {
   3011 		/* high false alarm count, decrease sensitivity */
   3012 		DPRINTFN(2, ("CCK high false alarm count: %u\n", fa));
   3013 		calib->cck_state = IWN_CCK_STATE_HIFA;
   3014 		calib->low_fa = 0;
   3015 
   3016 		if (calib->corr_cck_x4 > 160) {
   3017 			calib->noise_ref = noise_ref;
   3018 			if (calib->energy_cck > 2)
   3019 				dec_clip(calib->energy_cck, 2, energy_min);
   3020 		}
   3021 		if (calib->corr_cck_x4 < 160) {
   3022 			calib->corr_cck_x4 = 161;
   3023 			needs_update = 1;
   3024 		} else
   3025 			inc_clip(calib->corr_cck_x4, 3, 200);
   3026 
   3027 		inc_clip(calib->corr_cck_mrc_x4, 3, 400);
   3028 
   3029 	} else if (fa < 5 * rxena) {
   3030 		/* low false alarm count, increase sensitivity */
   3031 		DPRINTFN(2, ("CCK low false alarm count: %u\n", fa));
   3032 		calib->cck_state = IWN_CCK_STATE_LOFA;
   3033 		calib->low_fa++;
   3034 
   3035 		if (calib->cck_state != 0 &&
   3036 		    ((calib->noise_ref - noise_ref) > 2 ||
   3037 			calib->low_fa > 100)) {
   3038 			inc_clip(calib->energy_cck,      2,  97);
   3039 			dec_clip(calib->corr_cck_x4,     3, 125);
   3040 			dec_clip(calib->corr_cck_mrc_x4, 3, 200);
   3041 		}
   3042 	} else {
   3043 		/* not worth to increase or decrease sensitivity */
   3044 		DPRINTFN(2, ("CCK normal false alarm count: %u\n", fa));
   3045 		calib->low_fa = 0;
   3046 		calib->noise_ref = noise_ref;
   3047 
   3048 		if (calib->cck_state == IWN_CCK_STATE_HIFA) {
   3049 			/* previous interval had many false alarms */
   3050 			dec_clip(calib->energy_cck, 8, energy_min);
   3051 		}
   3052 		calib->cck_state = IWN_CCK_STATE_INIT;
   3053 	}
   3054 
   3055 	if (needs_update)
   3056 		(void)iwn_send_sensitivity(sc);
   3057 #undef dec_clip
   3058 #undef inc_clip
   3059 }
   3060 
   3061 static int
   3062 iwn_send_sensitivity(struct iwn_softc *sc)
   3063 {
   3064 	struct iwn_calib_state *calib = &sc->calib;
   3065 	struct iwn_sensitivity_cmd cmd;
   3066 
   3067 	memset(&cmd, 0, sizeof cmd);
   3068 	cmd.which = IWN_SENSITIVITY_WORKTBL;
   3069 	/* OFDM modulation */
   3070 	cmd.corr_ofdm_x1     = le16toh(calib->corr_ofdm_x1);
   3071 	cmd.corr_ofdm_mrc_x1 = le16toh(calib->corr_ofdm_mrc_x1);
   3072 	cmd.corr_ofdm_x4     = le16toh(calib->corr_ofdm_x4);
   3073 	cmd.corr_ofdm_mrc_x4 = le16toh(calib->corr_ofdm_mrc_x4);
   3074 	cmd.energy_ofdm      = le16toh(100);
   3075 	cmd.energy_ofdm_th   = le16toh(62);
   3076 	/* CCK modulation */
   3077 	cmd.corr_cck_x4      = le16toh(calib->corr_cck_x4);
   3078 	cmd.corr_cck_mrc_x4  = le16toh(calib->corr_cck_mrc_x4);
   3079 	cmd.energy_cck       = le16toh(calib->energy_cck);
   3080 	/* Barker modulation: use default values */
   3081 	cmd.corr_barker      = le16toh(190);
   3082 	cmd.corr_barker_mrc  = le16toh(390);
   3083 
   3084 	DPRINTFN(2, ("setting sensitivity\n"));
   3085 	return iwn_cmd(sc, IWN_SENSITIVITY, &cmd, sizeof cmd, 1);
   3086 }
   3087 
   3088 static int
   3089 iwn_auth(struct iwn_softc *sc)
   3090 {
   3091 	struct ieee80211com *ic = &sc->sc_ic;
   3092 	struct ieee80211_node *ni = ic->ic_bss;
   3093 	struct iwn_node_info node;
   3094 	int error;
   3095 
   3096 	/* update adapter's configuration */
   3097 	IEEE80211_ADDR_COPY(sc->config.bssid, ni->ni_bssid);
   3098 	sc->config.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
   3099 	sc->config.flags = htole32(IWN_CONFIG_TSF);
   3100 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) {
   3101 		sc->config.flags |= htole32(IWN_CONFIG_AUTO |
   3102 		    IWN_CONFIG_24GHZ);
   3103 	}
   3104 	switch (ic->ic_curmode) {
   3105 	case IEEE80211_MODE_11A:
   3106 		sc->config.cck_mask  = 0;
   3107 		sc->config.ofdm_mask = 0x15;
   3108 		break;
   3109 	case IEEE80211_MODE_11B:
   3110 		sc->config.cck_mask  = 0x03;
   3111 		sc->config.ofdm_mask = 0;
   3112 		break;
   3113 	default:	/* assume 802.11b/g */
   3114 		sc->config.cck_mask  = 0xf;
   3115 		sc->config.ofdm_mask = 0x15;
   3116 	}
   3117 	DPRINTF(("config chan %d flags %x cck %x ofdm %x\n", sc->config.chan,
   3118 		sc->config.flags, sc->config.cck_mask, sc->config.ofdm_mask));
   3119 	error = iwn_cmd(sc, IWN_CMD_CONFIGURE, &sc->config,
   3120 	    sizeof (struct iwn_config), 1);
   3121 	if (error != 0) {
   3122 		aprint_error_dev(sc->sc_dev, "could not configure\n");
   3123 		return error;
   3124 	}
   3125 
   3126 	/* configuration has changed, set Tx power accordingly */
   3127 	if ((error = iwn_set_txpower(sc, ni->ni_chan, 1)) != 0) {
   3128 		aprint_error_dev(sc->sc_dev, "could not set Tx power\n");
   3129 		return error;
   3130 	}
   3131 
   3132 	/*
   3133 	 * Reconfiguring clears the adapter's nodes table so we must
   3134 	 * add the broadcast node again.
   3135 	 */
   3136 	memset(&node, 0, sizeof node);
   3137 	IEEE80211_ADDR_COPY(node.macaddr, etherbroadcastaddr);
   3138 	node.id = IWN_ID_BROADCAST;
   3139 	DPRINTF(("adding broadcast node\n"));
   3140 	error = iwn_cmd(sc, IWN_CMD_ADD_NODE, &node, sizeof node, 1);
   3141 	if (error != 0) {
   3142 		aprint_error_dev(sc->sc_dev, "could not add broadcast node\n");
   3143 		return error;
   3144 	}
   3145 	DPRINTF(("setting MRR for node %d\n", node.id));
   3146 	if ((error = iwn_setup_node_mrr(sc, node.id, 1)) != 0) {
   3147 		aprint_error_dev(sc->sc_dev, "could not setup MRR for broadcast node\n");
   3148 		return error;
   3149 	}
   3150 
   3151 	return 0;
   3152 }
   3153 
   3154 /*
   3155  * Configure the adapter for associated state.
   3156  */
   3157 static int
   3158 iwn_run(struct iwn_softc *sc)
   3159 {
   3160 	struct ieee80211com *ic = &sc->sc_ic;
   3161 	struct ieee80211_node *ni = ic->ic_bss;
   3162 	struct iwn_node_info node;
   3163 	int error;
   3164 
   3165 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
   3166 		/* link LED blinks while monitoring */
   3167 		iwn_set_led(sc, IWN_LED_LINK, 5, 5);
   3168 		return 0;
   3169 	}
   3170 
   3171 #if 0
   3172 	if (ic->ic_opmode != IEEE80211_M_STA) {
   3173 		(void) iwn_auth(sc);    /* XXX */
   3174 		iwn_setup_beacon(sc, ni);
   3175 	}
   3176 #endif
   3177 
   3178 	iwn_enable_tsf(sc, ni);
   3179 
   3180 	/* update adapter's configuration */
   3181 	sc->config.associd = htole16(ni->ni_associd & ~0xc000);
   3182 	/* short preamble/slot time are negotiated when associating */
   3183 	sc->config.flags &= ~htole32(IWN_CONFIG_SHPREAMBLE |
   3184 	    IWN_CONFIG_SHSLOT);
   3185 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
   3186 		sc->config.flags |= htole32(IWN_CONFIG_SHSLOT);
   3187 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
   3188 		sc->config.flags |= htole32(IWN_CONFIG_SHPREAMBLE);
   3189 	sc->config.filter |= htole32(IWN_FILTER_BSS);
   3190 
   3191 	DPRINTF(("config chan %d flags %x\n", sc->config.chan,
   3192 		sc->config.flags));
   3193 	error = iwn_cmd(sc, IWN_CMD_CONFIGURE, &sc->config,
   3194 	    sizeof (struct iwn_config), 1);
   3195 	if (error != 0) {
   3196 		aprint_error_dev(sc->sc_dev, "could not update configuration\n");
   3197 		return error;
   3198 	}
   3199 
   3200 	/* configuration has changed, set Tx power accordingly */
   3201 	if ((error = iwn_set_txpower(sc, ni->ni_chan, 1)) != 0) {
   3202 		aprint_error_dev(sc->sc_dev, "could not set Tx power\n");
   3203 		return error;
   3204 	}
   3205 
   3206 	/* add BSS node */
   3207 	memset(&node, 0, sizeof node);
   3208 	IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr);
   3209 	node.id = IWN_ID_BSS;
   3210 	node.htflags = htole32(3 << IWN_AMDPU_SIZE_FACTOR_SHIFT |
   3211 	    5 << IWN_AMDPU_DENSITY_SHIFT);
   3212 	DPRINTF(("adding BSS node\n"));
   3213 	error = iwn_cmd(sc, IWN_CMD_ADD_NODE, &node, sizeof node, 1);
   3214 	if (error != 0) {
   3215 		aprint_error_dev(sc->sc_dev, "could not add BSS node\n");
   3216 		return error;
   3217 	}
   3218 	DPRINTF(("setting MRR for node %d\n", node.id));
   3219 	if ((error = iwn_setup_node_mrr(sc, node.id, 1)) != 0) {
   3220 		aprint_error_dev(sc->sc_dev, "could not setup MRR for node %d\n", node.id);
   3221 		return error;
   3222 	}
   3223 
   3224 	if (ic->ic_opmode == IEEE80211_M_STA) {
   3225 		/* fake a join to init the tx rate */
   3226 		iwn_newassoc(ni, 1);
   3227 	}
   3228 
   3229 	if ((error = iwn_init_sensitivity(sc)) != 0) {
   3230 		aprint_error_dev(sc->sc_dev, "could not set sensitivity\n");
   3231 		return error;
   3232 	}
   3233 
   3234 	/* start periodic calibration timer */
   3235 	sc->calib.state = IWN_CALIB_STATE_ASSOC;
   3236 	sc->calib_cnt = 0;
   3237 	callout_schedule(&sc->calib_to, hz / 2);
   3238 
   3239 	/* link LED always on while associated */
   3240 	iwn_set_led(sc, IWN_LED_LINK, 0, 1);
   3241 
   3242 	return 0;
   3243 }
   3244 
   3245 /*
   3246  * Send a scan request to the firmware.  Since this command is huge, we map it
   3247  * into a mbuf instead of using the pre-allocated set of commands.
   3248  */
   3249 static int
   3250 iwn_scan(struct iwn_softc *sc, uint16_t flags)
   3251 {
   3252 	struct ieee80211com *ic = &sc->sc_ic;
   3253 	struct iwn_tx_ring *ring = &sc->txq[4];
   3254 	struct iwn_tx_desc *desc;
   3255 	struct iwn_tx_data *data;
   3256 	struct iwn_tx_cmd *cmd;
   3257 	struct iwn_cmd_data *tx;
   3258 	struct iwn_scan_hdr *hdr;
   3259 	struct iwn_scan_essid *essid;
   3260 	struct iwn_scan_chan *chan;
   3261 	struct ieee80211_frame *wh;
   3262 	struct ieee80211_rateset *rs;
   3263 	struct ieee80211_channel *c;
   3264 	enum ieee80211_phymode mode;
   3265 	uint8_t *frm;
   3266 	int pktlen, error, nrates;
   3267 
   3268 	desc = &ring->desc[ring->cur];
   3269 	data = &ring->data[ring->cur];
   3270 
   3271 	MGETHDR(data->m, M_DONTWAIT, MT_DATA);
   3272 	if (data->m == NULL) {
   3273 		aprint_error_dev(sc->sc_dev, "could not allocate mbuf for scan command\n");
   3274 		return ENOMEM;
   3275 	}
   3276 	MCLGET(data->m, M_DONTWAIT);
   3277 	if (!(data->m->m_flags & M_EXT)) {
   3278 		m_freem(data->m);
   3279 		data->m = NULL;
   3280 		aprint_error_dev(sc->sc_dev, "could not allocate mbuf for scan command\n");
   3281 		return ENOMEM;
   3282 	}
   3283 
   3284 	cmd = mtod(data->m, struct iwn_tx_cmd *);
   3285 	cmd->code = IWN_CMD_SCAN;
   3286 	cmd->flags = 0;
   3287 	cmd->qid = ring->qid;
   3288 	cmd->idx = ring->cur;
   3289 
   3290 	hdr = (struct iwn_scan_hdr *)cmd->data;
   3291 	memset(hdr, 0, sizeof (struct iwn_scan_hdr));
   3292 	/*
   3293 	 * Move to the next channel if no packets are received within 5 msecs
   3294 	 * after sending the probe request (this helps to reduce the duration
   3295 	 * of active scans).
   3296 	 */
   3297 	hdr->quiet = htole16(5);	/* timeout in milliseconds */
   3298 	hdr->plcp_threshold = htole16(1);	/* min # of packets */
   3299 
   3300 	/* select Ant B and Ant C for scanning */
   3301 	hdr->rxchain = htole16(0x3e1 | 7 << IWN_RXCHAIN_ANTMSK_SHIFT);
   3302 
   3303 	tx = (struct iwn_cmd_data *)(hdr + 1);
   3304 	memset(tx, 0, sizeof (struct iwn_cmd_data));
   3305 	tx->flags = htole32(IWN_TX_AUTO_SEQ | 0x200); // XXX
   3306 	tx->id = IWN_ID_BROADCAST;
   3307 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
   3308 	tx->rflags = IWN_RFLAG_ANT_B;
   3309 
   3310 	if (flags & IEEE80211_CHAN_A) {
   3311 		hdr->crc_threshold = htole16(1);
   3312 		/* send probe requests at 6Mbps */
   3313 		tx->rate = iwn_ridx_to_plcp[IWN_OFDM6];
   3314 	} else {
   3315 		hdr->flags = htole32(IWN_CONFIG_24GHZ | IWN_CONFIG_AUTO);
   3316 		/* send probe requests at 1Mbps */
   3317 		tx->rate = iwn_ridx_to_plcp[IWN_CCK1];
   3318 		tx->rflags |= IWN_RFLAG_CCK;
   3319 	}
   3320 
   3321 	essid = (struct iwn_scan_essid *)(tx + 1);
   3322 	memset(essid, 0, 4 * sizeof (struct iwn_scan_essid));
   3323 	essid[0].id  = IEEE80211_ELEMID_SSID;
   3324 	essid[0].len = ic->ic_des_esslen;
   3325 	memcpy(essid[0].data, ic->ic_des_essid, ic->ic_des_esslen);
   3326 
   3327 	/*
   3328 	 * Build a probe request frame.  Most of the following code is a
   3329 	 * copy & paste of what is done in net80211.
   3330 	 */
   3331 	wh = (struct ieee80211_frame *)&essid[4];
   3332 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
   3333 	    IEEE80211_FC0_SUBTYPE_PROBE_REQ;
   3334 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
   3335 	IEEE80211_ADDR_COPY(wh->i_addr1, etherbroadcastaddr);
   3336 	IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
   3337 	IEEE80211_ADDR_COPY(wh->i_addr3, etherbroadcastaddr);
   3338 	*(u_int16_t *)&wh->i_dur[0] = 0;	/* filled by h/w */
   3339 	*(u_int16_t *)&wh->i_seq[0] = 0;	/* filled by h/w */
   3340 
   3341 	frm = (uint8_t *)(wh + 1);
   3342 
   3343 	/* add empty SSID IE (firmware generates it for directed scans) */
   3344 	*frm++ = IEEE80211_ELEMID_SSID;
   3345 	*frm++ = 0;
   3346 
   3347 	mode = ieee80211_chan2mode(ic, ic->ic_ibss_chan);
   3348 	rs = &ic->ic_sup_rates[mode];
   3349 
   3350 	/* add supported rates IE */
   3351 
   3352 	*frm++ = IEEE80211_ELEMID_RATES;
   3353 	nrates = rs->rs_nrates;
   3354 	if (nrates > IEEE80211_RATE_SIZE)
   3355 		nrates = IEEE80211_RATE_SIZE;
   3356 	*frm++ = nrates;
   3357 	memcpy(frm, rs->rs_rates, nrates);
   3358 	frm += nrates;
   3359 
   3360 	/* add supported xrates IE */
   3361 
   3362 	if (rs->rs_nrates > IEEE80211_RATE_SIZE) {
   3363 		nrates = rs->rs_nrates - IEEE80211_RATE_SIZE;
   3364 		*frm++ = IEEE80211_ELEMID_XRATES;
   3365 		*frm++ = nrates;
   3366 		memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates);
   3367 		frm += nrates;
   3368 	}
   3369 
   3370 	/* setup length of probe request */
   3371 	tx->len = htole16(frm - (uint8_t *)wh);
   3372 
   3373 	chan = (struct iwn_scan_chan *)frm;
   3374 	for (c  = &ic->ic_channels[1];
   3375 	     c <= &ic->ic_channels[IEEE80211_CHAN_MAX]; c++) {
   3376 		if ((c->ic_flags & flags) != flags)
   3377 			continue;
   3378 
   3379 		chan->chan = ieee80211_chan2ieee(ic, c);
   3380 		chan->flags = 0;
   3381 		if (!(c->ic_flags & IEEE80211_CHAN_PASSIVE)) {
   3382 			chan->flags |= IWN_CHAN_ACTIVE;
   3383 			if (ic->ic_des_esslen != 0)
   3384 				chan->flags |= IWN_CHAN_DIRECT;
   3385 		}
   3386 		chan->dsp_gain = 0x6e;
   3387 		if (IEEE80211_IS_CHAN_5GHZ(c)) {
   3388 			chan->rf_gain = 0x3b;
   3389 			chan->active  = htole16(10);
   3390 			chan->passive = htole16(110);
   3391 		} else {
   3392 			chan->rf_gain = 0x28;
   3393 			chan->active  = htole16(20);
   3394 			chan->passive = htole16(120);
   3395 		}
   3396 		hdr->nchan++;
   3397 		chan++;
   3398 
   3399 		frm += sizeof (struct iwn_scan_chan);
   3400 	}
   3401 
   3402 	hdr->len = htole16(frm - (uint8_t *)hdr);
   3403 	pktlen = frm - (uint8_t *)cmd;
   3404 
   3405 	error = bus_dmamap_load(sc->sc_dmat, data->map, cmd, pktlen, NULL,
   3406 	    BUS_DMA_NOWAIT);
   3407 	if (error) {
   3408 		aprint_error_dev(sc->sc_dev, "could not map scan command\n");
   3409 		m_freem(data->m);
   3410 		data->m = NULL;
   3411 		return error;
   3412 	}
   3413 
   3414 	IWN_SET_DESC_NSEGS(desc, 1);
   3415 	IWN_SET_DESC_SEG(desc, 0, data->map->dm_segs[0].ds_addr,
   3416 	    data->map->dm_segs[0].ds_len);
   3417 	sc->shared->len[ring->qid][ring->cur] = htole16(8);
   3418 	if (ring->cur < IWN_TX_WINDOW) {
   3419 		sc->shared->len[ring->qid][ring->cur + IWN_TX_RING_COUNT] =
   3420 		    htole16(8);
   3421 	}
   3422 
   3423 	/* kick cmd ring */
   3424 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
   3425 	IWN_WRITE(sc, IWN_TX_WIDX, ring->qid << 8 | ring->cur);
   3426 
   3427 	return 0;	/* will be notified async. of failure/success */
   3428 }
   3429 
   3430 static int
   3431 iwn_config(struct iwn_softc *sc)
   3432 {
   3433 	struct ieee80211com *ic = &sc->sc_ic;
   3434 	struct ifnet *ifp = ic->ic_ifp;
   3435 	struct iwn_power power;
   3436 	struct iwn_bluetooth bluetooth;
   3437 	struct iwn_node_info node;
   3438 	int error;
   3439 
   3440 	/* set power mode */
   3441 	memset(&power, 0, sizeof power);
   3442 	power.flags = htole16(IWN_POWER_CAM | 0x8);
   3443 	DPRINTF(("setting power mode\n"));
   3444 	error = iwn_cmd(sc, IWN_CMD_SET_POWER_MODE, &power, sizeof power, 0);
   3445 	if (error != 0) {
   3446 		aprint_error_dev(sc->sc_dev, "could not set power mode\n");
   3447 		return error;
   3448 	}
   3449 
   3450 	/* configure bluetooth coexistence */
   3451 	memset(&bluetooth, 0, sizeof bluetooth);
   3452 	bluetooth.flags = 3;
   3453 	bluetooth.lead = 0xaa;
   3454 	bluetooth.kill = 1;
   3455 	DPRINTF(("configuring bluetooth coexistence\n"));
   3456 	error = iwn_cmd(sc, IWN_CMD_BLUETOOTH, &bluetooth, sizeof bluetooth,
   3457 	    0);
   3458 	if (error != 0) {
   3459 		aprint_error_dev(sc->sc_dev, "could not configure bluetooth coexistence\n");
   3460 		return error;
   3461 	}
   3462 
   3463 	/* configure adapter */
   3464 	memset(&sc->config, 0, sizeof (struct iwn_config));
   3465 	IEEE80211_ADDR_COPY(ic->ic_myaddr, CLLADDR(ifp->if_sadl));
   3466 	IEEE80211_ADDR_COPY(sc->config.myaddr, ic->ic_myaddr);
   3467 	IEEE80211_ADDR_COPY(sc->config.wlap, ic->ic_myaddr);
   3468 	/* set default channel */
   3469 	sc->config.chan = ieee80211_chan2ieee(ic, ic->ic_ibss_chan);
   3470 	sc->config.flags = htole32(IWN_CONFIG_TSF);
   3471 	if (IEEE80211_IS_CHAN_2GHZ(ic->ic_ibss_chan)) {
   3472 		sc->config.flags |= htole32(IWN_CONFIG_AUTO |
   3473 		    IWN_CONFIG_24GHZ);
   3474 	}
   3475 	sc->config.filter = 0;
   3476 	switch (ic->ic_opmode) {
   3477 	case IEEE80211_M_STA:
   3478 		sc->config.mode = IWN_MODE_STA;
   3479 		sc->config.filter |= htole32(IWN_FILTER_MULTICAST);
   3480 		break;
   3481 	case IEEE80211_M_IBSS:
   3482 	case IEEE80211_M_AHDEMO:
   3483 		sc->config.mode = IWN_MODE_IBSS;
   3484 		break;
   3485 	case IEEE80211_M_HOSTAP:
   3486 		sc->config.mode = IWN_MODE_HOSTAP;
   3487 		break;
   3488 	case IEEE80211_M_MONITOR:
   3489 		sc->config.mode = IWN_MODE_MONITOR;
   3490 		sc->config.filter |= htole32(IWN_FILTER_MULTICAST |
   3491 		    IWN_FILTER_CTL | IWN_FILTER_PROMISC);
   3492 		break;
   3493 	}
   3494 	sc->config.cck_mask  = 0x0f;	/* not yet negotiated */
   3495 	sc->config.ofdm_mask = 0xff;	/* not yet negotiated */
   3496 	sc->config.ht_single_mask = 0xff;
   3497 	sc->config.ht_dual_mask = 0xff;
   3498 	sc->config.rxchain = htole16(0x2800 | 7 << IWN_RXCHAIN_ANTMSK_SHIFT);
   3499 	DPRINTF(("setting configuration\n"));
   3500 	error = iwn_cmd(sc, IWN_CMD_CONFIGURE, &sc->config,
   3501 	    sizeof (struct iwn_config), 0);
   3502 	if (error != 0) {
   3503 		aprint_error_dev(sc->sc_dev, "configure command failed\n");
   3504 		return error;
   3505 	}
   3506 
   3507 	/* configuration has changed, set Tx power accordingly */
   3508 	if ((error = iwn_set_txpower(sc, ic->ic_ibss_chan, 0)) != 0) {
   3509 		aprint_error_dev(sc->sc_dev, "could not set Tx power\n");
   3510 		return error;
   3511 	}
   3512 
   3513 	/* add broadcast node */
   3514 	memset(&node, 0, sizeof node);
   3515 	IEEE80211_ADDR_COPY(node.macaddr, etherbroadcastaddr);
   3516 	node.id = IWN_ID_BROADCAST;
   3517 	DPRINTF(("adding broadcast node\n"));
   3518 	error = iwn_cmd(sc, IWN_CMD_ADD_NODE, &node, sizeof node, 0);
   3519 	if (error != 0) {
   3520 		aprint_error_dev(sc->sc_dev, "could not add broadcast node\n");
   3521 		return error;
   3522 	}
   3523 	DPRINTF(("setting MRR for node %d\n", node.id));
   3524 	if ((error = iwn_setup_node_mrr(sc, node.id, 0)) != 0) {
   3525 		aprint_error_dev(sc->sc_dev, "could not setup MRR for node %d\n", node.id);
   3526 		return error;
   3527 	}
   3528 
   3529 	if ((error = iwn_set_critical_temp(sc)) != 0) {
   3530 		aprint_error_dev(sc->sc_dev, "could not set critical temperature\n");
   3531 		return error;
   3532 	}
   3533 
   3534 	return 0;
   3535 }
   3536 
   3537 /*
   3538  * Do post-alive initialization of the NIC (after firmware upload).
   3539  */
   3540 static void
   3541 iwn_post_alive(struct iwn_softc *sc)
   3542 {
   3543 	uint32_t base;
   3544 	uint16_t offset;
   3545 	int qid;
   3546 
   3547 	iwn_mem_lock(sc);
   3548 
   3549 	/* clear SRAM */
   3550 	base = iwn_mem_read(sc, IWN_SRAM_BASE);
   3551 	for (offset = 0x380; offset < 0x520; offset += 4) {
   3552 		IWN_WRITE(sc, IWN_MEM_WADDR, base + offset);
   3553 		IWN_WRITE(sc, IWN_MEM_WDATA, 0);
   3554 	}
   3555 
   3556 	/* shared area is aligned on a 1K boundary */
   3557 	iwn_mem_write(sc, IWN_SRAM_BASE, sc->shared_dma.paddr >> 10);
   3558 	iwn_mem_write(sc, IWN_SELECT_QCHAIN, 0);
   3559 
   3560 	for (qid = 0; qid < IWN_NTXQUEUES; qid++) {
   3561 		iwn_mem_write(sc, IWN_QUEUE_RIDX(qid), 0);
   3562 		IWN_WRITE(sc, IWN_TX_WIDX, qid << 8 | 0);
   3563 
   3564 		/* set sched. window size */
   3565 		IWN_WRITE(sc, IWN_MEM_WADDR, base + IWN_QUEUE_OFFSET(qid));
   3566 		IWN_WRITE(sc, IWN_MEM_WDATA, 64);
   3567 		/* set sched. frame limit */
   3568 		IWN_WRITE(sc, IWN_MEM_WADDR, base + IWN_QUEUE_OFFSET(qid) + 4);
   3569 		IWN_WRITE(sc, IWN_MEM_WDATA, 64 << 16);
   3570 	}
   3571 
   3572 	/* enable interrupts for all 16 queues */
   3573 	iwn_mem_write(sc, IWN_QUEUE_INTR_MASK, 0xffff);
   3574 
   3575 	/* identify active Tx rings (0-7) */
   3576 	iwn_mem_write(sc, IWN_TX_ACTIVE, 0xff);
   3577 
   3578 	/* mark Tx rings (4 EDCA + cmd + 2 HCCA) as active */
   3579 	for (qid = 0; qid < 7; qid++) {
   3580 		iwn_mem_write(sc, IWN_TXQ_STATUS(qid),
   3581 		    IWN_TXQ_STATUS_ACTIVE | qid << 1);
   3582 	}
   3583 
   3584 	iwn_mem_unlock(sc);
   3585 }
   3586 
   3587 static void
   3588 iwn_stop_master(struct iwn_softc *sc)
   3589 {
   3590 	uint32_t tmp;
   3591 	int ntries;
   3592 
   3593 	tmp = IWN_READ(sc, IWN_RESET);
   3594 	IWN_WRITE(sc, IWN_RESET, tmp | IWN_STOP_MASTER);
   3595 
   3596 	tmp = IWN_READ(sc, IWN_GPIO_CTL);
   3597 	if ((tmp & IWN_GPIO_PWR_STATUS) == IWN_GPIO_PWR_SLEEP)
   3598 		return;	/* already asleep */
   3599 
   3600 	for (ntries = 0; ntries < 100; ntries++) {
   3601 		if (IWN_READ(sc, IWN_RESET) & IWN_MASTER_DISABLED)
   3602 			break;
   3603 		DELAY(10);
   3604 	}
   3605 	if (ntries == 100) {
   3606 		aprint_error_dev(sc->sc_dev, "timeout waiting for master\n");
   3607 	}
   3608 }
   3609 
   3610 static int
   3611 iwn_reset(struct iwn_softc *sc)
   3612 {
   3613 	uint32_t tmp;
   3614 	int ntries;
   3615 
   3616 	/* clear any pending interrupts */
   3617 	IWN_WRITE(sc, IWN_INTR, 0xffffffff);
   3618 
   3619 	tmp = IWN_READ(sc, IWN_CHICKEN);
   3620 	IWN_WRITE(sc, IWN_CHICKEN, tmp | IWN_CHICKEN_DISLOS);
   3621 
   3622 	tmp = IWN_READ(sc, IWN_GPIO_CTL);
   3623 	IWN_WRITE(sc, IWN_GPIO_CTL, tmp | IWN_GPIO_INIT);
   3624 
   3625 	/* wait for clock stabilization */
   3626 	for (ntries = 0; ntries < 1000; ntries++) {
   3627 		if (IWN_READ(sc, IWN_GPIO_CTL) & IWN_GPIO_CLOCK)
   3628 			break;
   3629 		DELAY(10);
   3630 	}
   3631 	if (ntries == 1000) {
   3632 		aprint_error_dev(sc->sc_dev, "timeout waiting for clock stabilization\n");
   3633 		return ETIMEDOUT;
   3634 	}
   3635 	return 0;
   3636 }
   3637 
   3638 static void
   3639 iwn_hw_config(struct iwn_softc *sc)
   3640 {
   3641 	uint32_t tmp, hw;
   3642 
   3643 	/* enable interrupts mitigation */
   3644 	IWN_WRITE(sc, IWN_INTR_MIT, 512 / 32);
   3645 
   3646 	/* voodoo from the reference driver */
   3647 	tmp = pci_conf_read(sc->sc_pct, sc->sc_pcitag, PCI_CLASS_REG);
   3648 	tmp = PCI_REVISION(tmp);
   3649 	if ((tmp & 0x80) && (tmp & 0x7f) < 8) {
   3650 		/* enable "no snoop" field */
   3651 		tmp = pci_conf_read(sc->sc_pct, sc->sc_pcitag, 0xe8);
   3652 		tmp &= ~IWN_DIS_NOSNOOP;
   3653 		pci_conf_write(sc->sc_pct, sc->sc_pcitag, 0xe8, tmp);
   3654 	}
   3655 
   3656 	/* disable L1 entry to work around a hardware bug */
   3657 	tmp = pci_conf_read(sc->sc_pct, sc->sc_pcitag, 0xf0);
   3658 	tmp &= ~IWN_ENA_L1;
   3659 	pci_conf_write(sc->sc_pct, sc->sc_pcitag, 0xf0, tmp);
   3660 
   3661 	hw = IWN_READ(sc, IWN_HWCONFIG);
   3662 	IWN_WRITE(sc, IWN_HWCONFIG, hw | 0x310);
   3663 
   3664 	iwn_mem_lock(sc);
   3665 	tmp = iwn_mem_read(sc, IWN_MEM_POWER);
   3666 	iwn_mem_write(sc, IWN_MEM_POWER, tmp | IWN_POWER_RESET);
   3667 	DELAY(5);
   3668 	tmp = iwn_mem_read(sc, IWN_MEM_POWER);
   3669 	iwn_mem_write(sc, IWN_MEM_POWER, tmp & ~IWN_POWER_RESET);
   3670 	iwn_mem_unlock(sc);
   3671 }
   3672 
   3673 static int
   3674 iwn_init(struct ifnet *ifp)
   3675 {
   3676 	struct iwn_softc *sc = ifp->if_softc;
   3677 	struct ieee80211com *ic = &sc->sc_ic;
   3678 	uint32_t tmp;
   3679 	int error, qid;
   3680 
   3681 	iwn_stop(ifp, 1);
   3682 	if ((error = iwn_reset(sc)) != 0) {
   3683 		aprint_error_dev(sc->sc_dev, "could not reset adapter\n");
   3684 		goto fail1;
   3685 	}
   3686 
   3687 	iwn_mem_lock(sc);
   3688 	iwn_mem_read(sc, IWN_CLOCK_CTL);
   3689 	iwn_mem_write(sc, IWN_CLOCK_CTL, 0xa00);
   3690 	iwn_mem_read(sc, IWN_CLOCK_CTL);
   3691 	iwn_mem_unlock(sc);
   3692 
   3693 	DELAY(20);
   3694 
   3695 	iwn_mem_lock(sc);
   3696 	tmp = iwn_mem_read(sc, IWN_MEM_PCIDEV);
   3697 	iwn_mem_write(sc, IWN_MEM_PCIDEV, tmp | 0x800);
   3698 	iwn_mem_unlock(sc);
   3699 
   3700 	iwn_mem_lock(sc);
   3701 	tmp = iwn_mem_read(sc, IWN_MEM_POWER);
   3702 	iwn_mem_write(sc, IWN_MEM_POWER, tmp & ~0x03000000);
   3703 	iwn_mem_unlock(sc);
   3704 
   3705 	iwn_hw_config(sc);
   3706 
   3707 	/* init Rx ring */
   3708 	iwn_mem_lock(sc);
   3709 	IWN_WRITE(sc, IWN_RX_CONFIG, 0);
   3710 	IWN_WRITE(sc, IWN_RX_WIDX, 0);
   3711 	/* Rx ring is aligned on a 256-byte boundary */
   3712 	IWN_WRITE(sc, IWN_RX_BASE, sc->rxq.desc_dma.paddr >> 8);
   3713 	/* shared area is aligned on a 16-byte boundary */
   3714 	IWN_WRITE(sc, IWN_RW_WIDX_PTR, (sc->shared_dma.paddr +
   3715 		offsetof(struct iwn_shared, closed_count)) >> 4);
   3716 	IWN_WRITE(sc, IWN_RX_CONFIG, 0x80601000);
   3717 	iwn_mem_unlock(sc);
   3718 
   3719 	IWN_WRITE(sc, IWN_RX_WIDX, (IWN_RX_RING_COUNT - 1) & ~7);
   3720 
   3721 	iwn_mem_lock(sc);
   3722 	iwn_mem_write(sc, IWN_TX_ACTIVE, 0);
   3723 
   3724 	/* set physical address of "keep warm" page */
   3725 	IWN_WRITE(sc, IWN_KW_BASE, sc->kw_dma.paddr >> 4);
   3726 
   3727 	/* init Tx rings */
   3728 	for (qid = 0; qid < IWN_NTXQUEUES; qid++) {
   3729 		struct iwn_tx_ring *txq = &sc->txq[qid];
   3730 		IWN_WRITE(sc, IWN_TX_BASE(qid), txq->desc_dma.paddr >> 8);
   3731 		IWN_WRITE(sc, IWN_TX_CONFIG(qid), 0x80000008);
   3732 	}
   3733 	iwn_mem_unlock(sc);
   3734 
   3735 	/* clear "radio off" and "disable command" bits (reversed logic) */
   3736 	IWN_WRITE(sc, IWN_UCODE_CLR, IWN_RADIO_OFF);
   3737 	IWN_WRITE(sc, IWN_UCODE_CLR, IWN_DISABLE_CMD);
   3738 
   3739 	/* clear any pending interrupts */
   3740 	IWN_WRITE(sc, IWN_INTR, 0xffffffff);
   3741 	/* enable interrupts */
   3742 	IWN_WRITE(sc, IWN_MASK, IWN_INTR_MASK);
   3743 
   3744 	/* not sure why/if this is necessary... */
   3745 	IWN_WRITE(sc, IWN_UCODE_CLR, IWN_RADIO_OFF);
   3746 	IWN_WRITE(sc, IWN_UCODE_CLR, IWN_RADIO_OFF);
   3747 
   3748 	/* check that the radio is not disabled by RF switch */
   3749 	if (!(IWN_READ(sc, IWN_GPIO_CTL) & IWN_GPIO_RF_ENABLED)) {
   3750 		aprint_error_dev(sc->sc_dev, "radio is disabled by hardware switch\n");
   3751 		error = EBUSY;	/* XXX ;-) */
   3752 		goto fail1;
   3753 	}
   3754 
   3755 	if ((error = iwn_load_firmware(sc)) != 0) {
   3756 		aprint_error_dev(sc->sc_dev, "could not load firmware\n");
   3757 		goto fail1;
   3758 	}
   3759 
   3760 	/* firmware has notified us that it is alive.. */
   3761 	iwn_post_alive(sc);	/* ..do post alive initialization */
   3762 
   3763 	sc->rawtemp = sc->ucode_info.temp[3].chan20MHz;
   3764 	sc->temp = iwn_get_temperature(sc);
   3765 	DPRINTF(("temperature=%d\n", sc->temp));
   3766 
   3767 	if ((error = iwn_config(sc)) != 0) {
   3768 		aprint_error_dev(sc->sc_dev, "could not configure device\n");
   3769 		goto fail1;
   3770 	}
   3771 
   3772 	DPRINTF(("iwn_config end\n"));
   3773 
   3774 	ifp->if_flags &= ~IFF_OACTIVE;
   3775 	ifp->if_flags |= IFF_RUNNING;
   3776 
   3777 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
   3778 		if (ic->ic_opmode != IEEE80211_ROAMING_MANUAL)
   3779 			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
   3780 	}
   3781 	else
   3782 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
   3783 
   3784 	DPRINTF(("iwn_init ok\n"));
   3785 	return 0;
   3786 
   3787 fail1:
   3788 	DPRINTF(("iwn_init error\n"));
   3789 	iwn_stop(ifp, 1);
   3790 	return error;
   3791 }
   3792 
   3793 static void
   3794 iwn_stop(struct ifnet *ifp, int disable)
   3795 {
   3796 	struct iwn_softc *sc = ifp->if_softc;
   3797 	struct ieee80211com *ic = &sc->sc_ic;
   3798 	uint32_t tmp;
   3799 	int i;
   3800 
   3801 	ifp->if_timer = sc->sc_tx_timer = 0;
   3802 	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
   3803 
   3804 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
   3805 
   3806 	IWN_WRITE(sc, IWN_RESET, IWN_NEVO_RESET);
   3807 
   3808 	/* disable interrupts */
   3809 	IWN_WRITE(sc, IWN_MASK, 0);
   3810 	IWN_WRITE(sc, IWN_INTR, 0xffffffff);
   3811 	IWN_WRITE(sc, IWN_INTR_STATUS, 0xffffffff);
   3812 
   3813 	/* make sure we no longer hold the memory lock */
   3814 	iwn_mem_unlock(sc);
   3815 
   3816 	/* reset all Tx rings */
   3817 	for (i = 0; i < IWN_NTXQUEUES; i++)
   3818 		iwn_reset_tx_ring(sc, &sc->txq[i]);
   3819 
   3820 	/* reset Rx ring */
   3821 	iwn_reset_rx_ring(sc, &sc->rxq);
   3822 
   3823 	iwn_mem_lock(sc);
   3824 	iwn_mem_write(sc, IWN_MEM_CLOCK2, 0x200);
   3825 	iwn_mem_unlock(sc);
   3826 
   3827 	DELAY(5);
   3828 
   3829 	iwn_stop_master(sc);
   3830 	tmp = IWN_READ(sc, IWN_RESET);
   3831 	IWN_WRITE(sc, IWN_RESET, tmp | IWN_SW_RESET);
   3832 }
   3833 
   3834 static bool
   3835 iwn_resume(device_t dv)
   3836 {
   3837 	struct iwn_softc *sc = device_private(dv);
   3838 
   3839 	pci_disable_retry(sc->sc_pct, sc->sc_pcitag);
   3840 	(void)iwn_reset(sc);
   3841 
   3842 	return true;
   3843 }
   3844