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