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