Home | History | Annotate | Line # | Download | only in pci
if_iwn.c revision 1.67
      1 /*	$NetBSD: if_iwn.c,v 1.67 2013/07/28 11:46:24 prlw1 Exp $	*/
      2 /*	$OpenBSD: if_iwn.c,v 1.119 2013/05/29 23:16:52 yuo Exp $	*/
      3 
      4 /*-
      5  * Copyright (c) 2007-2010 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 /*
     21  * Driver for Intel WiFi Link 4965 and 1000/5000/6000 Series 802.11 network
     22  * adapters.
     23  */
     24 #include <sys/cdefs.h>
     25 __KERNEL_RCSID(0, "$NetBSD: if_iwn.c,v 1.67 2013/07/28 11:46:24 prlw1 Exp $");
     26 
     27 #define IWN_USE_RBUF	/* Use local storage for RX */
     28 #undef IWN_HWCRYPTO	/* XXX does not even compile yet */
     29 
     30 #include <sys/param.h>
     31 #include <sys/sockio.h>
     32 #include <sys/proc.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 #ifdef notyetMODULE
     39 #include <sys/module.h>
     40 #endif
     41 #include <sys/mutex.h>
     42 #include <sys/conf.h>
     43 #include <sys/kauth.h>
     44 #include <sys/callout.h>
     45 
     46 #include <dev/sysmon/sysmonvar.h>
     47 
     48 #include <sys/bus.h>
     49 #include <machine/endian.h>
     50 #include <machine/intr.h>
     51 
     52 #include <dev/pci/pcireg.h>
     53 #include <dev/pci/pcivar.h>
     54 #include <dev/pci/pcidevs.h>
     55 
     56 #include <net/bpf.h>
     57 #include <net/if.h>
     58 #include <net/if_arp.h>
     59 #include <net/if_dl.h>
     60 #include <net/if_media.h>
     61 #include <net/if_types.h>
     62 
     63 #include <netinet/in.h>
     64 #include <netinet/in_systm.h>
     65 #include <netinet/in_var.h>
     66 #include <net/if_ether.h>
     67 #include <netinet/ip.h>
     68 
     69 #include <net80211/ieee80211_var.h>
     70 #include <net80211/ieee80211_amrr.h>
     71 #include <net80211/ieee80211_radiotap.h>
     72 
     73 #include <dev/firmload.h>
     74 
     75 #include <dev/pci/if_iwnreg.h>
     76 #include <dev/pci/if_iwnvar.h>
     77 
     78 static const pci_product_id_t iwn_devices[] = {
     79 	PCI_PRODUCT_INTEL_WIFI_LINK_1030_1,
     80 	PCI_PRODUCT_INTEL_WIFI_LINK_1030_2,
     81 	PCI_PRODUCT_INTEL_WIFI_LINK_4965_1,
     82 	PCI_PRODUCT_INTEL_WIFI_LINK_4965_2,
     83 	PCI_PRODUCT_INTEL_WIFI_LINK_4965_3,
     84 	PCI_PRODUCT_INTEL_WIFI_LINK_4965_4,
     85 	PCI_PRODUCT_INTEL_WIFI_LINK_5100_1,
     86 	PCI_PRODUCT_INTEL_WIFI_LINK_5100_2,
     87 	PCI_PRODUCT_INTEL_WIFI_LINK_5150_1,
     88 	PCI_PRODUCT_INTEL_WIFI_LINK_5150_2,
     89 	PCI_PRODUCT_INTEL_WIFI_LINK_5300_1,
     90 	PCI_PRODUCT_INTEL_WIFI_LINK_5300_2,
     91 	PCI_PRODUCT_INTEL_WIFI_LINK_5350_1,
     92 	PCI_PRODUCT_INTEL_WIFI_LINK_5350_2,
     93 	PCI_PRODUCT_INTEL_WIFI_LINK_1000_1,
     94 	PCI_PRODUCT_INTEL_WIFI_LINK_1000_2,
     95 	PCI_PRODUCT_INTEL_WIFI_LINK_6000_3X3_1,
     96 	PCI_PRODUCT_INTEL_WIFI_LINK_6000_3X3_2,
     97 	PCI_PRODUCT_INTEL_WIFI_LINK_6000_IPA_1,
     98 	PCI_PRODUCT_INTEL_WIFI_LINK_6000_IPA_2,
     99 	PCI_PRODUCT_INTEL_WIFI_LINK_6050_2X2_1,
    100 	PCI_PRODUCT_INTEL_WIFI_LINK_6050_2X2_2,
    101 	PCI_PRODUCT_INTEL_WIFI_LINK_6005_2X2_1,
    102 	PCI_PRODUCT_INTEL_WIFI_LINK_6005_2X2_2,
    103 	PCI_PRODUCT_INTEL_WIFI_LINK_6230_1,
    104 	PCI_PRODUCT_INTEL_WIFI_LINK_6230_2,
    105 };
    106 
    107 /*
    108  * Supported rates for 802.11a/b/g modes (in 500Kbps unit).
    109  */
    110 static const struct ieee80211_rateset iwn_rateset_11a =
    111 	{ 8, { 12, 18, 24, 36, 48, 72, 96, 108 } };
    112 
    113 static const struct ieee80211_rateset iwn_rateset_11b =
    114 	{ 4, { 2, 4, 11, 22 } };
    115 
    116 static const struct ieee80211_rateset iwn_rateset_11g =
    117 	{ 12, { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 } };
    118 
    119 static int	iwn_match(device_t , struct cfdata *, void *);
    120 static void	iwn_attach(device_t , device_t , void *);
    121 static int	iwn4965_attach(struct iwn_softc *, pci_product_id_t);
    122 static int	iwn5000_attach(struct iwn_softc *, pci_product_id_t);
    123 static void	iwn_radiotap_attach(struct iwn_softc *);
    124 static int	iwn_detach(device_t , int);
    125 #if 0
    126 static void	iwn_power(int, void *);
    127 #endif
    128 static bool	iwn_resume(device_t, const pmf_qual_t *);
    129 static int	iwn_nic_lock(struct iwn_softc *);
    130 static int	iwn_eeprom_lock(struct iwn_softc *);
    131 static int	iwn_init_otprom(struct iwn_softc *);
    132 static int	iwn_read_prom_data(struct iwn_softc *, uint32_t, void *, int);
    133 static int	iwn_dma_contig_alloc(bus_dma_tag_t, struct iwn_dma_info *,
    134 		    void **, bus_size_t, bus_size_t);
    135 static void	iwn_dma_contig_free(struct iwn_dma_info *);
    136 static int	iwn_alloc_sched(struct iwn_softc *);
    137 static void	iwn_free_sched(struct iwn_softc *);
    138 static int	iwn_alloc_kw(struct iwn_softc *);
    139 static void	iwn_free_kw(struct iwn_softc *);
    140 static int	iwn_alloc_ict(struct iwn_softc *);
    141 static void	iwn_free_ict(struct iwn_softc *);
    142 static int	iwn_alloc_fwmem(struct iwn_softc *);
    143 static void	iwn_free_fwmem(struct iwn_softc *);
    144 static int	iwn_alloc_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
    145 static void	iwn_reset_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
    146 static void	iwn_free_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
    147 static int	iwn_alloc_tx_ring(struct iwn_softc *, struct iwn_tx_ring *,
    148 		    int);
    149 static void	iwn_reset_tx_ring(struct iwn_softc *, struct iwn_tx_ring *);
    150 static void	iwn_free_tx_ring(struct iwn_softc *, struct iwn_tx_ring *);
    151 static void	iwn5000_ict_reset(struct iwn_softc *);
    152 static int	iwn_read_eeprom(struct iwn_softc *);
    153 static void	iwn4965_read_eeprom(struct iwn_softc *);
    154 
    155 #ifdef IWN_DEBUG
    156 static void	iwn4965_print_power_group(struct iwn_softc *, int);
    157 #endif
    158 static void	iwn5000_read_eeprom(struct iwn_softc *);
    159 static void	iwn_read_eeprom_channels(struct iwn_softc *, int, uint32_t);
    160 static void	iwn_read_eeprom_enhinfo(struct iwn_softc *);
    161 static struct	ieee80211_node *iwn_node_alloc(struct ieee80211_node_table *);
    162 static void	iwn_newassoc(struct ieee80211_node *, int);
    163 static int	iwn_media_change(struct ifnet *);
    164 static int	iwn_newstate(struct ieee80211com *, enum ieee80211_state, int);
    165 static void	iwn_iter_func(void *, struct ieee80211_node *);
    166 static void	iwn_calib_timeout(void *);
    167 static void	iwn_rx_phy(struct iwn_softc *, struct iwn_rx_desc *,
    168 		    struct iwn_rx_data *);
    169 static void	iwn_rx_done(struct iwn_softc *, struct iwn_rx_desc *,
    170 		    struct iwn_rx_data *);
    171 #ifndef IEEE80211_NO_HT
    172 static void	iwn_rx_compressed_ba(struct iwn_softc *, struct iwn_rx_desc *,
    173 		    struct iwn_rx_data *);
    174 #endif
    175 static void	iwn5000_rx_calib_results(struct iwn_softc *,
    176 		    struct iwn_rx_desc *, struct iwn_rx_data *);
    177 static void	iwn_rx_statistics(struct iwn_softc *, struct iwn_rx_desc *,
    178 		    struct iwn_rx_data *);
    179 static void	iwn4965_tx_done(struct iwn_softc *, struct iwn_rx_desc *,
    180 		    struct iwn_rx_data *);
    181 static void	iwn5000_tx_done(struct iwn_softc *, struct iwn_rx_desc *,
    182 		    struct iwn_rx_data *);
    183 static void	iwn_tx_done(struct iwn_softc *, struct iwn_rx_desc *, int,
    184 		    uint8_t);
    185 static void	iwn_cmd_done(struct iwn_softc *, struct iwn_rx_desc *);
    186 static void	iwn_notif_intr(struct iwn_softc *);
    187 static void	iwn_wakeup_intr(struct iwn_softc *);
    188 static void	iwn_fatal_intr(struct iwn_softc *);
    189 static int	iwn_intr(void *);
    190 static void	iwn4965_update_sched(struct iwn_softc *, int, int, uint8_t,
    191 		    uint16_t);
    192 static void	iwn5000_update_sched(struct iwn_softc *, int, int, uint8_t,
    193 		    uint16_t);
    194 #ifdef notyet
    195 static void	iwn5000_reset_sched(struct iwn_softc *, int, int);
    196 #endif
    197 static int	iwn_tx(struct iwn_softc *, struct mbuf *,
    198 		    struct ieee80211_node *, int);
    199 static void	iwn_start(struct ifnet *);
    200 static void	iwn_watchdog(struct ifnet *);
    201 static int	iwn_ioctl(struct ifnet *, u_long, void *);
    202 static int	iwn_cmd(struct iwn_softc *, int, const void *, int, int);
    203 static int	iwn4965_add_node(struct iwn_softc *, struct iwn_node_info *,
    204 		    int);
    205 static int	iwn5000_add_node(struct iwn_softc *, struct iwn_node_info *,
    206 		    int);
    207 static int	iwn_set_link_quality(struct iwn_softc *,
    208 		    struct ieee80211_node *);
    209 static int	iwn_add_broadcast_node(struct iwn_softc *, int);
    210 static void	iwn_set_led(struct iwn_softc *, uint8_t, uint8_t, uint8_t);
    211 static int	iwn_set_critical_temp(struct iwn_softc *);
    212 static int	iwn_set_timing(struct iwn_softc *, struct ieee80211_node *);
    213 static void	iwn4965_power_calibration(struct iwn_softc *, int);
    214 static int	iwn4965_set_txpower(struct iwn_softc *, int);
    215 static int	iwn5000_set_txpower(struct iwn_softc *, int);
    216 static int	iwn4965_get_rssi(const struct iwn_rx_stat *);
    217 static int	iwn5000_get_rssi(const struct iwn_rx_stat *);
    218 static int	iwn_get_noise(const struct iwn_rx_general_stats *);
    219 static int	iwn4965_get_temperature(struct iwn_softc *);
    220 static int	iwn5000_get_temperature(struct iwn_softc *);
    221 static int	iwn_init_sensitivity(struct iwn_softc *);
    222 static void	iwn_collect_noise(struct iwn_softc *,
    223 		    const struct iwn_rx_general_stats *);
    224 static int	iwn4965_init_gains(struct iwn_softc *);
    225 static int	iwn5000_init_gains(struct iwn_softc *);
    226 static int	iwn4965_set_gains(struct iwn_softc *);
    227 static int	iwn5000_set_gains(struct iwn_softc *);
    228 static void	iwn_tune_sensitivity(struct iwn_softc *,
    229 		    const struct iwn_rx_stats *);
    230 static int	iwn_send_sensitivity(struct iwn_softc *);
    231 static int	iwn_set_pslevel(struct iwn_softc *, int, int, int);
    232 static int	iwn5000_runtime_calib(struct iwn_softc *);
    233 
    234 static int	iwn_config_bt_coex_bluetooth(struct iwn_softc *);
    235 static int	iwn_config_bt_coex_prio_table(struct iwn_softc *);
    236 static int	iwn_config_bt_coex_adv1(struct iwn_softc *);
    237 
    238 static int	iwn_config(struct iwn_softc *);
    239 static int	iwn_scan(struct iwn_softc *, uint16_t);
    240 static int	iwn_auth(struct iwn_softc *);
    241 static int	iwn_run(struct iwn_softc *);
    242 #ifdef IWN_HWCRYPTO
    243 static int	iwn_set_key(struct ieee80211com *, struct ieee80211_node *,
    244 		    struct ieee80211_key *);
    245 static void	iwn_delete_key(struct ieee80211com *, struct ieee80211_node *,
    246 		    struct ieee80211_key *);
    247 #endif
    248 static int	iwn_wme_update(struct ieee80211com *);
    249 #ifndef IEEE80211_NO_HT
    250 static int	iwn_ampdu_rx_start(struct ieee80211com *,
    251 		    struct ieee80211_node *, uint8_t);
    252 static void	iwn_ampdu_rx_stop(struct ieee80211com *,
    253 		    struct ieee80211_node *, uint8_t);
    254 static int	iwn_ampdu_tx_start(struct ieee80211com *,
    255 		    struct ieee80211_node *, uint8_t);
    256 static void	iwn_ampdu_tx_stop(struct ieee80211com *,
    257 		    struct ieee80211_node *, uint8_t);
    258 static void	iwn4965_ampdu_tx_start(struct iwn_softc *,
    259 		    struct ieee80211_node *, uint8_t, uint16_t);
    260 static void	iwn4965_ampdu_tx_stop(struct iwn_softc *,
    261 		    uint8_t, uint16_t);
    262 static void	iwn5000_ampdu_tx_start(struct iwn_softc *,
    263 		    struct ieee80211_node *, uint8_t, uint16_t);
    264 static void	iwn5000_ampdu_tx_stop(struct iwn_softc *,
    265 		    uint8_t, uint16_t);
    266 #endif
    267 static int	iwn5000_query_calibration(struct iwn_softc *);
    268 static int	iwn5000_send_calibration(struct iwn_softc *);
    269 static int	iwn5000_send_wimax_coex(struct iwn_softc *);
    270 static int	iwn4965_post_alive(struct iwn_softc *);
    271 static int	iwn5000_post_alive(struct iwn_softc *);
    272 static int	iwn4965_load_bootcode(struct iwn_softc *, const uint8_t *,
    273 		    int);
    274 static int	iwn4965_load_firmware(struct iwn_softc *);
    275 static int	iwn5000_load_firmware_section(struct iwn_softc *, uint32_t,
    276 		    const uint8_t *, int);
    277 static int	iwn5000_load_firmware(struct iwn_softc *);
    278 static int	iwn_read_firmware_leg(struct iwn_softc *,
    279 		    struct iwn_fw_info *);
    280 static int	iwn_read_firmware_tlv(struct iwn_softc *,
    281 		    struct iwn_fw_info *, uint16_t);
    282 static int	iwn_read_firmware(struct iwn_softc *);
    283 static int	iwn_clock_wait(struct iwn_softc *);
    284 static int	iwn_apm_init(struct iwn_softc *);
    285 static void	iwn_apm_stop_master(struct iwn_softc *);
    286 static void	iwn_apm_stop(struct iwn_softc *);
    287 static int	iwn4965_nic_config(struct iwn_softc *);
    288 static int	iwn5000_nic_config(struct iwn_softc *);
    289 static int	iwn_hw_prepare(struct iwn_softc *);
    290 static int	iwn_hw_init(struct iwn_softc *);
    291 static void	iwn_hw_stop(struct iwn_softc *);
    292 static int	iwn_init(struct ifnet *);
    293 static void	iwn_stop(struct ifnet *, int);
    294 
    295 /* XXX MCLGETI alternative */
    296 static struct	mbuf *MCLGETIalt(struct iwn_softc *, int,
    297 		    struct ifnet *, u_int);
    298 #ifdef IWN_USE_RBUF
    299 static struct	iwn_rbuf *iwn_alloc_rbuf(struct iwn_softc *);
    300 static void	iwn_free_rbuf(struct mbuf *, void *, size_t, void *);
    301 static int	iwn_alloc_rpool(struct iwn_softc *);
    302 static void	iwn_free_rpool(struct iwn_softc *);
    303 #endif
    304 
    305 /* XXX needed by iwn_scan */
    306 static u_int8_t	*ieee80211_add_ssid(u_int8_t *, const u_int8_t *, u_int);
    307 static u_int8_t	*ieee80211_add_rates(u_int8_t *,
    308     const struct ieee80211_rateset *);
    309 static u_int8_t	*ieee80211_add_xrates(u_int8_t *,
    310     const struct ieee80211_rateset *);
    311 
    312 static void	iwn_fix_channel(struct ieee80211com *, struct mbuf *);
    313 
    314 #ifdef IWN_DEBUG
    315 #define DPRINTF(x)	do { if (iwn_debug > 0) printf x; } while (0)
    316 #define DPRINTFN(n, x)	do { if (iwn_debug >= (n)) printf x; } while (0)
    317 int iwn_debug = 0;
    318 #else
    319 #define DPRINTF(x)
    320 #define DPRINTFN(n, x)
    321 #endif
    322 
    323 CFATTACH_DECL_NEW(iwn, sizeof(struct iwn_softc), iwn_match, iwn_attach,
    324 	iwn_detach, NULL);
    325 
    326 static int
    327 iwn_match(device_t parent, cfdata_t match __unused, void *aux)
    328 {
    329 	struct pci_attach_args *pa = aux;
    330 	size_t i;
    331 
    332 	if (PCI_VENDOR(pa->pa_id) != PCI_VENDOR_INTEL)
    333 		return 0;
    334 
    335 	for (i = 0; i < __arraycount(iwn_devices); i++)
    336 		if (PCI_PRODUCT(pa->pa_id) == iwn_devices[i])
    337 			return 1;
    338 
    339 	return 0;
    340 }
    341 
    342 static void
    343 iwn_attach(device_t parent __unused, device_t self, void *aux)
    344 {
    345 	struct iwn_softc *sc = device_private(self);
    346 	struct ieee80211com *ic = &sc->sc_ic;
    347 	struct ifnet *ifp = &sc->sc_ec.ec_if;
    348 	struct pci_attach_args *pa = aux;
    349 	const char *intrstr;
    350 	pci_intr_handle_t ih;
    351 	pcireg_t memtype, reg;
    352 	int i, error;
    353 
    354 	sc->sc_dev = self;
    355 	sc->sc_pct = pa->pa_pc;
    356 	sc->sc_pcitag = pa->pa_tag;
    357 	sc->sc_dmat = pa->pa_dmat;
    358 	mutex_init(&sc->sc_mtx, MUTEX_DEFAULT, IPL_NONE);
    359 
    360 	callout_init(&sc->calib_to, 0);
    361 	callout_setfunc(&sc->calib_to, iwn_calib_timeout, sc);
    362 
    363 	pci_aprint_devinfo(pa, NULL);
    364 
    365 	/*
    366 	 * Get the offset of the PCI Express Capability Structure in PCI
    367 	 * Configuration Space.
    368 	 */
    369 	error = pci_get_capability(sc->sc_pct, sc->sc_pcitag,
    370 	    PCI_CAP_PCIEXPRESS, &sc->sc_cap_off, NULL);
    371 	if (error == 0) {
    372 		aprint_error(": PCIe capability structure not found!\n");
    373 		return;
    374 	}
    375 
    376 	/* Clear device-specific "PCI retry timeout" register (41h). */
    377 	reg = pci_conf_read(sc->sc_pct, sc->sc_pcitag, 0x40);
    378 	if (reg & 0xff00)
    379 		pci_conf_write(sc->sc_pct, sc->sc_pcitag, 0x40, reg & ~0xff00);
    380 
    381 	/* Enable bus-mastering and hardware bug workaround. */
    382 	/* XXX verify the bus-mastering is really needed (not in OpenBSD) */
    383 	reg = pci_conf_read(sc->sc_pct, sc->sc_pcitag, PCI_COMMAND_STATUS_REG);
    384 	reg |= PCI_COMMAND_MASTER_ENABLE;
    385 	if (reg & PCI_COMMAND_INTERRUPT_DISABLE) {
    386 		DPRINTF(("PCIe INTx Disable set\n"));
    387 		reg &= ~PCI_COMMAND_INTERRUPT_DISABLE;
    388 	}
    389 	pci_conf_write(sc->sc_pct, sc->sc_pcitag, PCI_COMMAND_STATUS_REG, reg);
    390 
    391 	memtype = pci_mapreg_type(pa->pa_pc, pa->pa_tag, IWN_PCI_BAR0);
    392 	error = pci_mapreg_map(pa, IWN_PCI_BAR0, memtype, 0, &sc->sc_st,
    393 	    &sc->sc_sh, NULL, &sc->sc_sz);
    394 	if (error != 0) {
    395 		aprint_error(": can't map mem space\n");
    396 		return;
    397 	}
    398 
    399 	/* Install interrupt handler. */
    400 	if (pci_intr_map(pa, &ih) != 0) {
    401 		aprint_error(": can't map interrupt\n");
    402 		return;
    403 	}
    404 	intrstr = pci_intr_string(sc->sc_pct, ih);
    405 	sc->sc_ih = pci_intr_establish(sc->sc_pct, ih, IPL_NET, iwn_intr, sc);
    406 	if (sc->sc_ih == NULL) {
    407 		aprint_error(": can't establish interrupt");
    408 		if (intrstr != NULL)
    409 			aprint_error(" at %s", intrstr);
    410 		aprint_error("\n");
    411 		return;
    412 	}
    413 	aprint_normal_dev(self, "interrupting at %s\n", intrstr);
    414 
    415 	/* Read hardware revision and attach. */
    416 	sc->hw_type = (IWN_READ(sc, IWN_HW_REV) >> 4) & 0xf;
    417 	if (sc->hw_type == IWN_HW_REV_TYPE_4965)
    418 		error = iwn4965_attach(sc, PCI_PRODUCT(pa->pa_id));
    419 	else
    420 		error = iwn5000_attach(sc, PCI_PRODUCT(pa->pa_id));
    421 	if (error != 0) {
    422 		aprint_error(": could not attach device\n");
    423 		return;
    424 	}
    425 
    426 	if ((error = iwn_hw_prepare(sc)) != 0) {
    427 		aprint_error(": hardware not ready\n");
    428 		return;
    429 	}
    430 
    431 	/* Read MAC address, channels, etc from EEPROM. */
    432 	if ((error = iwn_read_eeprom(sc)) != 0) {
    433 		aprint_error(": could not read EEPROM\n");
    434 		return;
    435 	}
    436 
    437 	/* Allocate DMA memory for firmware transfers. */
    438 	if ((error = iwn_alloc_fwmem(sc)) != 0) {
    439 		aprint_error(": could not allocate memory for firmware\n");
    440 		return;
    441 	}
    442 
    443 	/* Allocate "Keep Warm" page. */
    444 	if ((error = iwn_alloc_kw(sc)) != 0) {
    445 		aprint_error(": could not allocate keep warm page\n");
    446 		goto fail1;
    447 	}
    448 
    449 	/* Allocate ICT table for 5000 Series. */
    450 	if (sc->hw_type != IWN_HW_REV_TYPE_4965 &&
    451 	    (error = iwn_alloc_ict(sc)) != 0) {
    452 		aprint_error(": could not allocate ICT table\n");
    453 		goto fail2;
    454 	}
    455 
    456 	/* Allocate TX scheduler "rings". */
    457 	if ((error = iwn_alloc_sched(sc)) != 0) {
    458 		aprint_error(": could not allocate TX scheduler rings\n");
    459 		goto fail3;
    460 	}
    461 
    462 #ifdef IWN_USE_RBUF
    463 	/* Allocate RX buffers. */
    464 	if ((error = iwn_alloc_rpool(sc)) != 0) {
    465 		aprint_error_dev(self, "could not allocate RX buffers\n");
    466 		goto fail3;
    467 	}
    468 #endif
    469 
    470 	/* Allocate TX rings (16 on 4965AGN, 20 on >=5000). */
    471 	for (i = 0; i < sc->ntxqs; i++) {
    472 		if ((error = iwn_alloc_tx_ring(sc, &sc->txq[i], i)) != 0) {
    473 			aprint_error(": could not allocate TX ring %d\n", i);
    474 			goto fail4;
    475 		}
    476 	}
    477 
    478 	/* Allocate RX ring. */
    479 	if ((error = iwn_alloc_rx_ring(sc, &sc->rxq)) != 0) {
    480 		aprint_error(": could not allocate RX ring\n");
    481 		goto fail4;
    482 	}
    483 
    484 	/* Clear pending interrupts. */
    485 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
    486 
    487 	/* Count the number of available chains. */
    488 	sc->ntxchains =
    489 	    ((sc->txchainmask >> 2) & 1) +
    490 	    ((sc->txchainmask >> 1) & 1) +
    491 	    ((sc->txchainmask >> 0) & 1);
    492 	sc->nrxchains =
    493 	    ((sc->rxchainmask >> 2) & 1) +
    494 	    ((sc->rxchainmask >> 1) & 1) +
    495 	    ((sc->rxchainmask >> 0) & 1);
    496 	aprint_normal_dev(self, "MIMO %dT%dR, %.4s, address %s\n",
    497 	    sc->ntxchains, sc->nrxchains, sc->eeprom_domain,
    498 	    ether_sprintf(ic->ic_myaddr));
    499 
    500 	ic->ic_ifp = ifp;
    501 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
    502 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
    503 	ic->ic_state = IEEE80211_S_INIT;
    504 
    505 	/* Set device capabilities. */
    506 	/* XXX OpenBSD has IEEE80211_C_WEP, IEEE80211_C_RSN,
    507 	 * and IEEE80211_C_PMGT too. */
    508 	ic->ic_caps =
    509 	    IEEE80211_C_IBSS |		/* IBSS mode support */
    510 	    IEEE80211_C_WPA |		/* 802.11i */
    511 	    IEEE80211_C_MONITOR |	/* monitor mode supported */
    512 	    IEEE80211_C_TXPMGT |	/* tx power management */
    513 	    IEEE80211_C_SHSLOT |	/* short slot time supported */
    514 	    IEEE80211_C_SHPREAMBLE |	/* short preamble supported */
    515 	    IEEE80211_C_WME;		/* 802.11e */
    516 
    517 #ifndef IEEE80211_NO_HT
    518 	if (sc->sc_flags & IWN_FLAG_HAS_11N) {
    519 		/* Set HT capabilities. */
    520 		ic->ic_htcaps =
    521 #if IWN_RBUF_SIZE == 8192
    522 		    IEEE80211_HTCAP_AMSDU7935 |
    523 #endif
    524 		    IEEE80211_HTCAP_CBW20_40 |
    525 		    IEEE80211_HTCAP_SGI20 |
    526 		    IEEE80211_HTCAP_SGI40;
    527 		if (sc->hw_type != IWN_HW_REV_TYPE_4965)
    528 			ic->ic_htcaps |= IEEE80211_HTCAP_GF;
    529 		if (sc->hw_type == IWN_HW_REV_TYPE_6050)
    530 			ic->ic_htcaps |= IEEE80211_HTCAP_SMPS_DYN;
    531 		else
    532 			ic->ic_htcaps |= IEEE80211_HTCAP_SMPS_DIS;
    533 	}
    534 #endif	/* !IEEE80211_NO_HT */
    535 
    536 	/* Set supported legacy rates. */
    537 	ic->ic_sup_rates[IEEE80211_MODE_11B] = iwn_rateset_11b;
    538 	ic->ic_sup_rates[IEEE80211_MODE_11G] = iwn_rateset_11g;
    539 	if (sc->sc_flags & IWN_FLAG_HAS_5GHZ) {
    540 		ic->ic_sup_rates[IEEE80211_MODE_11A] = iwn_rateset_11a;
    541 	}
    542 #ifndef IEEE80211_NO_HT
    543 	if (sc->sc_flags & IWN_FLAG_HAS_11N) {
    544 		/* Set supported HT rates. */
    545 		ic->ic_sup_mcs[0] = 0xff;		/* MCS 0-7 */
    546 		if (sc->nrxchains > 1)
    547 			ic->ic_sup_mcs[1] = 0xff;	/* MCS 7-15 */
    548 		if (sc->nrxchains > 2)
    549 			ic->ic_sup_mcs[2] = 0xff;	/* MCS 16-23 */
    550 	}
    551 #endif
    552 
    553 	/* IBSS channel undefined for now. */
    554 	ic->ic_ibss_chan = &ic->ic_channels[0];
    555 
    556 	ifp->if_softc = sc;
    557 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
    558 	ifp->if_init = iwn_init;
    559 	ifp->if_ioctl = iwn_ioctl;
    560 	ifp->if_start = iwn_start;
    561 	ifp->if_stop = iwn_stop;
    562 	ifp->if_watchdog = iwn_watchdog;
    563 	IFQ_SET_READY(&ifp->if_snd);
    564 	memcpy(ifp->if_xname, device_xname(self), IFNAMSIZ);
    565 
    566 	if_attach(ifp);
    567 	ieee80211_ifattach(ic);
    568 	ic->ic_node_alloc = iwn_node_alloc;
    569 	ic->ic_newassoc = iwn_newassoc;
    570 #ifdef IWN_HWCRYPTO
    571 	ic->ic_crypto.cs_key_set = iwn_set_key;
    572 	ic->ic_crypto.cs_key_delete = iwn_delete_key;
    573 #endif
    574 	ic->ic_wme.wme_update = iwn_wme_update;
    575 #ifndef IEEE80211_NO_HT
    576 	ic->ic_ampdu_rx_start = iwn_ampdu_rx_start;
    577 	ic->ic_ampdu_rx_stop = iwn_ampdu_rx_stop;
    578 	ic->ic_ampdu_tx_start = iwn_ampdu_tx_start;
    579 	ic->ic_ampdu_tx_stop = iwn_ampdu_tx_stop;
    580 #endif
    581 
    582 	/* Override 802.11 state transition machine. */
    583 	sc->sc_newstate = ic->ic_newstate;
    584 	ic->ic_newstate = iwn_newstate;
    585 	ieee80211_media_init(ic, iwn_media_change, ieee80211_media_status);
    586 
    587 	sc->amrr.amrr_min_success_threshold =  1;
    588 	sc->amrr.amrr_max_success_threshold = 15;
    589 
    590 	iwn_radiotap_attach(sc);
    591 
    592 	/*
    593 	 * XXX for NetBSD, OpenBSD timeout_set replaced by
    594 	 * callout_init and callout_setfunc, above.
    595 	*/
    596 
    597 	if (pmf_device_register(self, NULL, iwn_resume))
    598 		pmf_class_network_register(self, ifp);
    599 	else
    600 		aprint_error_dev(self, "couldn't establish power handler\n");
    601 
    602 	/* XXX NetBSD add call to ieee80211_announce for dmesg. */
    603 	ieee80211_announce(ic);
    604 
    605 	return;
    606 
    607 	/* Free allocated memory if something failed during attachment. */
    608 fail4:	while (--i >= 0)
    609 		iwn_free_tx_ring(sc, &sc->txq[i]);
    610 #ifdef IWN_USE_RBUF
    611 	iwn_free_rpool(sc);
    612 #endif
    613 	iwn_free_sched(sc);
    614 fail3:	if (sc->ict != NULL)
    615 		iwn_free_ict(sc);
    616 fail2:	iwn_free_kw(sc);
    617 fail1:	iwn_free_fwmem(sc);
    618 }
    619 
    620 int
    621 iwn4965_attach(struct iwn_softc *sc, pci_product_id_t pid)
    622 {
    623 	struct iwn_ops *ops = &sc->ops;
    624 
    625 	ops->load_firmware = iwn4965_load_firmware;
    626 	ops->read_eeprom = iwn4965_read_eeprom;
    627 	ops->post_alive = iwn4965_post_alive;
    628 	ops->nic_config = iwn4965_nic_config;
    629 	ops->config_bt_coex = iwn_config_bt_coex_bluetooth;
    630 	ops->update_sched = iwn4965_update_sched;
    631 	ops->get_temperature = iwn4965_get_temperature;
    632 	ops->get_rssi = iwn4965_get_rssi;
    633 	ops->set_txpower = iwn4965_set_txpower;
    634 	ops->init_gains = iwn4965_init_gains;
    635 	ops->set_gains = iwn4965_set_gains;
    636 	ops->add_node = iwn4965_add_node;
    637 	ops->tx_done = iwn4965_tx_done;
    638 #ifndef IEEE80211_NO_HT
    639 	ops->ampdu_tx_start = iwn4965_ampdu_tx_start;
    640 	ops->ampdu_tx_stop = iwn4965_ampdu_tx_stop;
    641 #endif
    642 	sc->ntxqs = IWN4965_NTXQUEUES;
    643 	sc->ndmachnls = IWN4965_NDMACHNLS;
    644 	sc->broadcast_id = IWN4965_ID_BROADCAST;
    645 	sc->rxonsz = IWN4965_RXONSZ;
    646 	sc->schedsz = IWN4965_SCHEDSZ;
    647 	sc->fw_text_maxsz = IWN4965_FW_TEXT_MAXSZ;
    648 	sc->fw_data_maxsz = IWN4965_FW_DATA_MAXSZ;
    649 	sc->fwsz = IWN4965_FWSZ;
    650 	sc->sched_txfact_addr = IWN4965_SCHED_TXFACT;
    651 	sc->limits = &iwn4965_sensitivity_limits;
    652 	sc->fwname = "iwlwifi-4965-2.ucode";
    653 	/* Override chains masks, ROM is known to be broken. */
    654 	sc->txchainmask = IWN_ANT_AB;
    655 	sc->rxchainmask = IWN_ANT_ABC;
    656 
    657 	return 0;
    658 }
    659 
    660 int
    661 iwn5000_attach(struct iwn_softc *sc, pci_product_id_t pid)
    662 {
    663 	struct iwn_ops *ops = &sc->ops;
    664 
    665 	ops->load_firmware = iwn5000_load_firmware;
    666 	ops->read_eeprom = iwn5000_read_eeprom;
    667 	ops->post_alive = iwn5000_post_alive;
    668 	ops->nic_config = iwn5000_nic_config;
    669 	ops->config_bt_coex = iwn_config_bt_coex_bluetooth;
    670 	ops->update_sched = iwn5000_update_sched;
    671 	ops->get_temperature = iwn5000_get_temperature;
    672 	ops->get_rssi = iwn5000_get_rssi;
    673 	ops->set_txpower = iwn5000_set_txpower;
    674 	ops->init_gains = iwn5000_init_gains;
    675 	ops->set_gains = iwn5000_set_gains;
    676 	ops->add_node = iwn5000_add_node;
    677 	ops->tx_done = iwn5000_tx_done;
    678 #ifndef IEEE80211_NO_HT
    679 	ops->ampdu_tx_start = iwn5000_ampdu_tx_start;
    680 	ops->ampdu_tx_stop = iwn5000_ampdu_tx_stop;
    681 #endif
    682 	sc->ntxqs = IWN5000_NTXQUEUES;
    683 	sc->ndmachnls = IWN5000_NDMACHNLS;
    684 	sc->broadcast_id = IWN5000_ID_BROADCAST;
    685 	sc->rxonsz = IWN5000_RXONSZ;
    686 	sc->schedsz = IWN5000_SCHEDSZ;
    687 	sc->fw_text_maxsz = IWN5000_FW_TEXT_MAXSZ;
    688 	sc->fw_data_maxsz = IWN5000_FW_DATA_MAXSZ;
    689 	sc->fwsz = IWN5000_FWSZ;
    690 	sc->sched_txfact_addr = IWN5000_SCHED_TXFACT;
    691 
    692 	switch (sc->hw_type) {
    693 	case IWN_HW_REV_TYPE_5100:
    694 		sc->limits = &iwn5000_sensitivity_limits;
    695 		sc->fwname = "iwlwifi-5000-2.ucode";
    696 		/* Override chains masks, ROM is known to be broken. */
    697 		sc->txchainmask = IWN_ANT_B;
    698 		sc->rxchainmask = IWN_ANT_AB;
    699 		break;
    700 	case IWN_HW_REV_TYPE_5150:
    701 		sc->limits = &iwn5150_sensitivity_limits;
    702 		sc->fwname = "iwlwifi-5150-2.ucode";
    703 		break;
    704 	case IWN_HW_REV_TYPE_5300:
    705 	case IWN_HW_REV_TYPE_5350:
    706 		sc->limits = &iwn5000_sensitivity_limits;
    707 		sc->fwname = "iwlwifi-5000-2.ucode";
    708 		break;
    709 	case IWN_HW_REV_TYPE_1000:
    710 		sc->limits = &iwn1000_sensitivity_limits;
    711 		sc->fwname = "iwlwifi-1000-3.ucode";
    712 		break;
    713 	case IWN_HW_REV_TYPE_6000:
    714 		sc->limits = &iwn6000_sensitivity_limits;
    715 		sc->fwname = "iwlwifi-6000-4.ucode";
    716 		if (pid == PCI_PRODUCT_INTEL_WIFI_LINK_6000_IPA_1 ||
    717 		    pid == PCI_PRODUCT_INTEL_WIFI_LINK_6000_IPA_2) {
    718 			sc->sc_flags |= IWN_FLAG_INTERNAL_PA;
    719 			/* Override chains masks, ROM is known to be broken. */
    720 			sc->txchainmask = IWN_ANT_BC;
    721 			sc->rxchainmask = IWN_ANT_BC;
    722 		}
    723 		break;
    724 	case IWN_HW_REV_TYPE_6050:
    725 		sc->limits = &iwn6000_sensitivity_limits;
    726 		sc->fwname = "iwlwifi-6050-5.ucode";
    727 		break;
    728 	case IWN_HW_REV_TYPE_6005:
    729 		sc->limits = &iwn6000_sensitivity_limits;
    730 		/* Type 6030 cards return IWN_HW_REV_TYPE_6005 */
    731 		if (pid == PCI_PRODUCT_INTEL_WIFI_LINK_1030_1 ||
    732 		    pid == PCI_PRODUCT_INTEL_WIFI_LINK_1030_2 ||
    733 		    pid == PCI_PRODUCT_INTEL_WIFI_LINK_6230_1 ||
    734 		    pid == PCI_PRODUCT_INTEL_WIFI_LINK_6230_2) {
    735 			sc->fwname = "iwlwifi-6000g2b-6.ucode";
    736 			ops->config_bt_coex = iwn_config_bt_coex_adv1;
    737 		}
    738 		else
    739 			sc->fwname = "iwlwifi-6000g2a-5.ucode";
    740 		break;
    741 	default:
    742 		aprint_normal(": adapter type %d not supported\n", sc->hw_type);
    743 		return ENOTSUP;
    744 	}
    745 	return 0;
    746 }
    747 
    748 /*
    749  * Attach the interface to 802.11 radiotap.
    750  */
    751 static void
    752 iwn_radiotap_attach(struct iwn_softc *sc)
    753 {
    754 	struct ifnet *ifp = sc->sc_ic.ic_ifp;
    755 
    756 	bpf_attach2(ifp, DLT_IEEE802_11_RADIO,
    757 	    sizeof (struct ieee80211_frame) + IEEE80211_RADIOTAP_HDRLEN,
    758 	    &sc->sc_drvbpf);
    759 
    760 	sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
    761 	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
    762 	sc->sc_rxtap.wr_ihdr.it_present = htole32(IWN_RX_RADIOTAP_PRESENT);
    763 
    764 	sc->sc_txtap_len = sizeof sc->sc_txtapu;
    765 	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
    766 	sc->sc_txtap.wt_ihdr.it_present = htole32(IWN_TX_RADIOTAP_PRESENT);
    767 }
    768 
    769 static int
    770 iwn_detach(device_t self, int flags __unused)
    771 {
    772 	struct iwn_softc *sc = device_private(self);
    773 	struct ifnet *ifp = sc->sc_ic.ic_ifp;
    774 	int qid;
    775 
    776 	callout_stop(&sc->calib_to);
    777 
    778 	/* Uninstall interrupt handler. */
    779 	if (sc->sc_ih != NULL)
    780 		pci_intr_disestablish(sc->sc_pct, sc->sc_ih);
    781 
    782 	/* Free DMA resources. */
    783 	iwn_free_rx_ring(sc, &sc->rxq);
    784 	for (qid = 0; qid < sc->ntxqs; qid++)
    785 		iwn_free_tx_ring(sc, &sc->txq[qid]);
    786 #ifdef IWN_USE_RBUF
    787 	iwn_free_rpool(sc);
    788 #endif
    789 	iwn_free_sched(sc);
    790 	iwn_free_kw(sc);
    791 	if (sc->ict != NULL)
    792 		iwn_free_ict(sc);
    793 	iwn_free_fwmem(sc);
    794 
    795 	bus_space_unmap(sc->sc_st, sc->sc_sh, sc->sc_sz);
    796 
    797 	ieee80211_ifdetach(&sc->sc_ic);
    798 	if_detach(ifp);
    799 
    800 	return 0;
    801 }
    802 
    803 #if 0
    804 /*
    805  * XXX Investigate if clearing the PCI retry timeout could eliminate
    806  * the repeated scan calls.  Also the calls to if_init and if_start
    807  * are similar to the effect of adding the call to ifioctl_common .
    808  */
    809 static void
    810 iwn_power(int why, void *arg)
    811 {
    812 	struct iwn_softc *sc = arg;
    813 	struct ifnet *ifp;
    814 	pcireg_t reg;
    815 	int s;
    816 
    817 	if (why != PWR_RESUME)
    818 		return;
    819 
    820 	/* Clear device-specific "PCI retry timeout" register (41h). */
    821 	reg = pci_conf_read(sc->sc_pct, sc->sc_pcitag, 0x40);
    822 	if (reg & 0xff00)
    823 		pci_conf_write(sc->sc_pct, sc->sc_pcitag, 0x40, reg & ~0xff00);
    824 
    825 	s = splnet();
    826 	ifp = &sc->sc_ic.ic_if;
    827 	if (ifp->if_flags & IFF_UP) {
    828 		ifp->if_init(ifp);
    829 		if (ifp->if_flags & IFF_RUNNING)
    830 			ifp->if_start(ifp);
    831 	}
    832 	splx(s);
    833 }
    834 #endif
    835 
    836 static bool
    837 iwn_resume(device_t dv, const pmf_qual_t *qual)
    838 {
    839 	return true;
    840 }
    841 
    842 static int
    843 iwn_nic_lock(struct iwn_softc *sc)
    844 {
    845 	int ntries;
    846 
    847 	/* Request exclusive access to NIC. */
    848 	IWN_SETBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_MAC_ACCESS_REQ);
    849 
    850 	/* Spin until we actually get the lock. */
    851 	for (ntries = 0; ntries < 1000; ntries++) {
    852 		if ((IWN_READ(sc, IWN_GP_CNTRL) &
    853 		     (IWN_GP_CNTRL_MAC_ACCESS_ENA | IWN_GP_CNTRL_SLEEP)) ==
    854 		    IWN_GP_CNTRL_MAC_ACCESS_ENA)
    855 			return 0;
    856 		DELAY(10);
    857 	}
    858 	return ETIMEDOUT;
    859 }
    860 
    861 static __inline void
    862 iwn_nic_unlock(struct iwn_softc *sc)
    863 {
    864 	IWN_CLRBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_MAC_ACCESS_REQ);
    865 }
    866 
    867 static __inline uint32_t
    868 iwn_prph_read(struct iwn_softc *sc, uint32_t addr)
    869 {
    870 	IWN_WRITE(sc, IWN_PRPH_RADDR, IWN_PRPH_DWORD | addr);
    871 	IWN_BARRIER_READ_WRITE(sc);
    872 	return IWN_READ(sc, IWN_PRPH_RDATA);
    873 }
    874 
    875 static __inline void
    876 iwn_prph_write(struct iwn_softc *sc, uint32_t addr, uint32_t data)
    877 {
    878 	IWN_WRITE(sc, IWN_PRPH_WADDR, IWN_PRPH_DWORD | addr);
    879 	IWN_BARRIER_WRITE(sc);
    880 	IWN_WRITE(sc, IWN_PRPH_WDATA, data);
    881 }
    882 
    883 static __inline void
    884 iwn_prph_setbits(struct iwn_softc *sc, uint32_t addr, uint32_t mask)
    885 {
    886 	iwn_prph_write(sc, addr, iwn_prph_read(sc, addr) | mask);
    887 }
    888 
    889 static __inline void
    890 iwn_prph_clrbits(struct iwn_softc *sc, uint32_t addr, uint32_t mask)
    891 {
    892 	iwn_prph_write(sc, addr, iwn_prph_read(sc, addr) & ~mask);
    893 }
    894 
    895 static __inline void
    896 iwn_prph_write_region_4(struct iwn_softc *sc, uint32_t addr,
    897     const uint32_t *data, int count)
    898 {
    899 	for (; count > 0; count--, data++, addr += 4)
    900 		iwn_prph_write(sc, addr, *data);
    901 }
    902 
    903 static __inline uint32_t
    904 iwn_mem_read(struct iwn_softc *sc, uint32_t addr)
    905 {
    906 	IWN_WRITE(sc, IWN_MEM_RADDR, addr);
    907 	IWN_BARRIER_READ_WRITE(sc);
    908 	return IWN_READ(sc, IWN_MEM_RDATA);
    909 }
    910 
    911 static __inline void
    912 iwn_mem_write(struct iwn_softc *sc, uint32_t addr, uint32_t data)
    913 {
    914 	IWN_WRITE(sc, IWN_MEM_WADDR, addr);
    915 	IWN_BARRIER_WRITE(sc);
    916 	IWN_WRITE(sc, IWN_MEM_WDATA, data);
    917 }
    918 
    919 static __inline void
    920 iwn_mem_write_2(struct iwn_softc *sc, uint32_t addr, uint16_t data)
    921 {
    922 	uint32_t tmp;
    923 
    924 	tmp = iwn_mem_read(sc, addr & ~3);
    925 	if (addr & 3)
    926 		tmp = (tmp & 0x0000ffff) | data << 16;
    927 	else
    928 		tmp = (tmp & 0xffff0000) | data;
    929 	iwn_mem_write(sc, addr & ~3, tmp);
    930 }
    931 
    932 static __inline void
    933 iwn_mem_read_region_4(struct iwn_softc *sc, uint32_t addr, uint32_t *data,
    934     int count)
    935 {
    936 	for (; count > 0; count--, addr += 4)
    937 		*data++ = iwn_mem_read(sc, addr);
    938 }
    939 
    940 static __inline void
    941 iwn_mem_set_region_4(struct iwn_softc *sc, uint32_t addr, uint32_t val,
    942     int count)
    943 {
    944 	for (; count > 0; count--, addr += 4)
    945 		iwn_mem_write(sc, addr, val);
    946 }
    947 
    948 static int
    949 iwn_eeprom_lock(struct iwn_softc *sc)
    950 {
    951 	int i, ntries;
    952 
    953 	for (i = 0; i < 100; i++) {
    954 		/* Request exclusive access to EEPROM. */
    955 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
    956 		    IWN_HW_IF_CONFIG_EEPROM_LOCKED);
    957 
    958 		/* Spin until we actually get the lock. */
    959 		for (ntries = 0; ntries < 100; ntries++) {
    960 			if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
    961 			    IWN_HW_IF_CONFIG_EEPROM_LOCKED)
    962 				return 0;
    963 			DELAY(10);
    964 		}
    965 	}
    966 	return ETIMEDOUT;
    967 }
    968 
    969 static __inline void
    970 iwn_eeprom_unlock(struct iwn_softc *sc)
    971 {
    972 	IWN_CLRBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_EEPROM_LOCKED);
    973 }
    974 
    975 /*
    976  * Initialize access by host to One Time Programmable ROM.
    977  * NB: This kind of ROM can be found on 1000 or 6000 Series only.
    978  */
    979 static int
    980 iwn_init_otprom(struct iwn_softc *sc)
    981 {
    982 	uint16_t prev = 0, base, next;
    983 	int count, error;
    984 
    985 	/* Wait for clock stabilization before accessing prph. */
    986 	if ((error = iwn_clock_wait(sc)) != 0)
    987 		return error;
    988 
    989 	if ((error = iwn_nic_lock(sc)) != 0)
    990 		return error;
    991 	iwn_prph_setbits(sc, IWN_APMG_PS, IWN_APMG_PS_RESET_REQ);
    992 	DELAY(5);
    993 	iwn_prph_clrbits(sc, IWN_APMG_PS, IWN_APMG_PS_RESET_REQ);
    994 	iwn_nic_unlock(sc);
    995 
    996 	/* Set auto clock gate disable bit for HW with OTP shadow RAM. */
    997 	if (sc->hw_type != IWN_HW_REV_TYPE_1000) {
    998 		IWN_SETBITS(sc, IWN_DBG_LINK_PWR_MGMT,
    999 		    IWN_RESET_LINK_PWR_MGMT_DIS);
   1000 	}
   1001 	IWN_CLRBITS(sc, IWN_EEPROM_GP, IWN_EEPROM_GP_IF_OWNER);
   1002 	/* Clear ECC status. */
   1003 	IWN_SETBITS(sc, IWN_OTP_GP,
   1004 	    IWN_OTP_GP_ECC_CORR_STTS | IWN_OTP_GP_ECC_UNCORR_STTS);
   1005 
   1006 	/*
   1007 	 * Find the block before last block (contains the EEPROM image)
   1008 	 * for HW without OTP shadow RAM.
   1009 	 */
   1010 	if (sc->hw_type == IWN_HW_REV_TYPE_1000) {
   1011 		/* Switch to absolute addressing mode. */
   1012 		IWN_CLRBITS(sc, IWN_OTP_GP, IWN_OTP_GP_RELATIVE_ACCESS);
   1013 		base = 0;
   1014 		for (count = 0; count < IWN1000_OTP_NBLOCKS; count++) {
   1015 			error = iwn_read_prom_data(sc, base, &next, 2);
   1016 			if (error != 0)
   1017 				return error;
   1018 			if (next == 0)	/* End of linked-list. */
   1019 				break;
   1020 			prev = base;
   1021 			base = le16toh(next);
   1022 		}
   1023 		if (count == 0 || count == IWN1000_OTP_NBLOCKS)
   1024 			return EIO;
   1025 		/* Skip "next" word. */
   1026 		sc->prom_base = prev + 1;
   1027 	}
   1028 	return 0;
   1029 }
   1030 
   1031 static int
   1032 iwn_read_prom_data(struct iwn_softc *sc, uint32_t addr, void *data, int count)
   1033 {
   1034 	uint8_t *out = data;
   1035 	uint32_t val, tmp;
   1036 	int ntries;
   1037 
   1038 	addr += sc->prom_base;
   1039 	for (; count > 0; count -= 2, addr++) {
   1040 		IWN_WRITE(sc, IWN_EEPROM, addr << 2);
   1041 		for (ntries = 0; ntries < 10; ntries++) {
   1042 			val = IWN_READ(sc, IWN_EEPROM);
   1043 			if (val & IWN_EEPROM_READ_VALID)
   1044 				break;
   1045 			DELAY(5);
   1046 		}
   1047 		if (ntries == 10) {
   1048 			aprint_error_dev(sc->sc_dev,
   1049 			    "timeout reading ROM at 0x%x\n", addr);
   1050 			return ETIMEDOUT;
   1051 		}
   1052 		if (sc->sc_flags & IWN_FLAG_HAS_OTPROM) {
   1053 			/* OTPROM, check for ECC errors. */
   1054 			tmp = IWN_READ(sc, IWN_OTP_GP);
   1055 			if (tmp & IWN_OTP_GP_ECC_UNCORR_STTS) {
   1056 				aprint_error_dev(sc->sc_dev,
   1057 				    "OTPROM ECC error at 0x%x\n", addr);
   1058 				return EIO;
   1059 			}
   1060 			if (tmp & IWN_OTP_GP_ECC_CORR_STTS) {
   1061 				/* Correctable ECC error, clear bit. */
   1062 				IWN_SETBITS(sc, IWN_OTP_GP,
   1063 				    IWN_OTP_GP_ECC_CORR_STTS);
   1064 			}
   1065 		}
   1066 		*out++ = val >> 16;
   1067 		if (count > 1)
   1068 			*out++ = val >> 24;
   1069 	}
   1070 	return 0;
   1071 }
   1072 
   1073 static int
   1074 iwn_dma_contig_alloc(bus_dma_tag_t tag, struct iwn_dma_info *dma, void **kvap,
   1075     bus_size_t size, bus_size_t alignment)
   1076 {
   1077 	int nsegs, error;
   1078 
   1079 	dma->tag = tag;
   1080 	dma->size = size;
   1081 
   1082 	error = bus_dmamap_create(tag, size, 1, size, 0, BUS_DMA_NOWAIT,
   1083 	    &dma->map);
   1084 	if (error != 0)
   1085 		goto fail;
   1086 
   1087 	error = bus_dmamem_alloc(tag, size, alignment, 0, &dma->seg, 1, &nsegs,
   1088 	    BUS_DMA_NOWAIT); /* XXX OpenBSD adds BUS_DMA_ZERO */
   1089 	if (error != 0)
   1090 		goto fail;
   1091 
   1092 	error = bus_dmamem_map(tag, &dma->seg, 1, size, &dma->vaddr,
   1093 	    BUS_DMA_NOWAIT); /* XXX OpenBSD adds BUS_DMA_COHERENT */
   1094 	if (error != 0)
   1095 		goto fail;
   1096 
   1097 	error = bus_dmamap_load(tag, dma->map, dma->vaddr, size, NULL,
   1098 	    BUS_DMA_NOWAIT);
   1099 	if (error != 0)
   1100 		goto fail;
   1101 
   1102 	/* XXX Presumably needed because of missing BUS_DMA_ZERO, above. */
   1103 	memset(dma->vaddr, 0, size);
   1104 	bus_dmamap_sync(tag, dma->map, 0, size, BUS_DMASYNC_PREWRITE);
   1105 
   1106 	dma->paddr = dma->map->dm_segs[0].ds_addr;
   1107 	if (kvap != NULL)
   1108 		*kvap = dma->vaddr;
   1109 
   1110 	return 0;
   1111 
   1112 fail:	iwn_dma_contig_free(dma);
   1113 	return error;
   1114 }
   1115 
   1116 static void
   1117 iwn_dma_contig_free(struct iwn_dma_info *dma)
   1118 {
   1119 	if (dma->map != NULL) {
   1120 		if (dma->vaddr != NULL) {
   1121 			bus_dmamap_sync(dma->tag, dma->map, 0, dma->size,
   1122 			    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
   1123 			bus_dmamap_unload(dma->tag, dma->map);
   1124 			bus_dmamem_unmap(dma->tag, dma->vaddr, dma->size);
   1125 			bus_dmamem_free(dma->tag, &dma->seg, 1);
   1126 			dma->vaddr = NULL;
   1127 		}
   1128 		bus_dmamap_destroy(dma->tag, dma->map);
   1129 		dma->map = NULL;
   1130 	}
   1131 }
   1132 
   1133 static int
   1134 iwn_alloc_sched(struct iwn_softc *sc)
   1135 {
   1136 	/* TX scheduler rings must be aligned on a 1KB boundary. */
   1137 	return iwn_dma_contig_alloc(sc->sc_dmat, &sc->sched_dma,
   1138 	    (void **)&sc->sched, sc->schedsz, 1024);
   1139 }
   1140 
   1141 static void
   1142 iwn_free_sched(struct iwn_softc *sc)
   1143 {
   1144 	iwn_dma_contig_free(&sc->sched_dma);
   1145 }
   1146 
   1147 static int
   1148 iwn_alloc_kw(struct iwn_softc *sc)
   1149 {
   1150 	/* "Keep Warm" page must be aligned on a 4KB boundary. */
   1151 	return iwn_dma_contig_alloc(sc->sc_dmat, &sc->kw_dma, NULL, 4096,
   1152 	    4096);
   1153 }
   1154 
   1155 static void
   1156 iwn_free_kw(struct iwn_softc *sc)
   1157 {
   1158 	iwn_dma_contig_free(&sc->kw_dma);
   1159 }
   1160 
   1161 static int
   1162 iwn_alloc_ict(struct iwn_softc *sc)
   1163 {
   1164 	/* ICT table must be aligned on a 4KB boundary. */
   1165 	return iwn_dma_contig_alloc(sc->sc_dmat, &sc->ict_dma,
   1166 	    (void **)&sc->ict, IWN_ICT_SIZE, 4096);
   1167 }
   1168 
   1169 static void
   1170 iwn_free_ict(struct iwn_softc *sc)
   1171 {
   1172 	iwn_dma_contig_free(&sc->ict_dma);
   1173 }
   1174 
   1175 static int
   1176 iwn_alloc_fwmem(struct iwn_softc *sc)
   1177 {
   1178 	/* Must be aligned on a 16-byte boundary. */
   1179 	return iwn_dma_contig_alloc(sc->sc_dmat, &sc->fw_dma, NULL,
   1180 	    sc->fwsz, 16);
   1181 }
   1182 
   1183 static void
   1184 iwn_free_fwmem(struct iwn_softc *sc)
   1185 {
   1186 	iwn_dma_contig_free(&sc->fw_dma);
   1187 }
   1188 
   1189 static int
   1190 iwn_alloc_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
   1191 {
   1192 	bus_size_t size;
   1193 	int i, error;
   1194 
   1195 	ring->cur = 0;
   1196 
   1197 	/* Allocate RX descriptors (256-byte aligned). */
   1198 	size = IWN_RX_RING_COUNT * sizeof (uint32_t);
   1199 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->desc_dma,
   1200 	    (void **)&ring->desc, size, 256);
   1201 	if (error != 0) {
   1202 		aprint_error_dev(sc->sc_dev,
   1203 		    "could not allocate RX ring DMA memory\n");
   1204 		goto fail;
   1205 	}
   1206 
   1207 	/* Allocate RX status area (16-byte aligned). */
   1208 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->stat_dma,
   1209 	    (void **)&ring->stat, sizeof (struct iwn_rx_status), 16);
   1210 	if (error != 0) {
   1211 		aprint_error_dev(sc->sc_dev,
   1212 		    "could not allocate RX status DMA memory\n");
   1213 		goto fail;
   1214 	}
   1215 
   1216 	/*
   1217 	 * Allocate and map RX buffers.
   1218 	 */
   1219 	for (i = 0; i < IWN_RX_RING_COUNT; i++) {
   1220 		struct iwn_rx_data *data = &ring->data[i];
   1221 
   1222 		error = bus_dmamap_create(sc->sc_dmat, IWN_RBUF_SIZE, 1,
   1223 		    IWN_RBUF_SIZE, 0, BUS_DMA_NOWAIT | BUS_DMA_ALLOCNOW,
   1224 		    &data->map);
   1225 		if (error != 0) {
   1226 			aprint_error_dev(sc->sc_dev,
   1227 			    "could not create RX buf DMA map\n");
   1228 			goto fail;
   1229 		}
   1230 
   1231 		data->m = MCLGETIalt(sc, M_DONTWAIT, NULL, IWN_RBUF_SIZE);
   1232 		if (data->m == NULL) {
   1233 			aprint_error_dev(sc->sc_dev,
   1234 			    "could not allocate RX mbuf\n");
   1235 			error = ENOBUFS;
   1236 			goto fail;
   1237 		}
   1238 
   1239 		error = bus_dmamap_load(sc->sc_dmat, data->map,
   1240 		    mtod(data->m, void *), IWN_RBUF_SIZE, NULL,
   1241 		    BUS_DMA_NOWAIT | BUS_DMA_READ);
   1242 		if (error != 0) {
   1243 			aprint_error_dev(sc->sc_dev,
   1244 			    "can't not map mbuf (error %d)\n", error);
   1245 			goto fail;
   1246 		}
   1247 
   1248 		/* Set physical address of RX buffer (256-byte aligned). */
   1249 		ring->desc[i] = htole32(data->map->dm_segs[0].ds_addr >> 8);
   1250 	}
   1251 
   1252 	bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map, 0, size,
   1253 	    BUS_DMASYNC_PREWRITE);
   1254 
   1255 	return 0;
   1256 
   1257 fail:	iwn_free_rx_ring(sc, ring);
   1258 	return error;
   1259 }
   1260 
   1261 static void
   1262 iwn_reset_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
   1263 {
   1264 	int ntries;
   1265 
   1266 	if (iwn_nic_lock(sc) == 0) {
   1267 		IWN_WRITE(sc, IWN_FH_RX_CONFIG, 0);
   1268 		for (ntries = 0; ntries < 1000; ntries++) {
   1269 			if (IWN_READ(sc, IWN_FH_RX_STATUS) &
   1270 			    IWN_FH_RX_STATUS_IDLE)
   1271 				break;
   1272 			DELAY(10);
   1273 		}
   1274 		iwn_nic_unlock(sc);
   1275 	}
   1276 	ring->cur = 0;
   1277 	sc->last_rx_valid = 0;
   1278 }
   1279 
   1280 static void
   1281 iwn_free_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
   1282 {
   1283 	int i;
   1284 
   1285 	iwn_dma_contig_free(&ring->desc_dma);
   1286 	iwn_dma_contig_free(&ring->stat_dma);
   1287 
   1288 	for (i = 0; i < IWN_RX_RING_COUNT; i++) {
   1289 		struct iwn_rx_data *data = &ring->data[i];
   1290 
   1291 		if (data->m != NULL) {
   1292 			bus_dmamap_sync(sc->sc_dmat, data->map, 0,
   1293 			    data->map->dm_mapsize, BUS_DMASYNC_POSTREAD);
   1294 			bus_dmamap_unload(sc->sc_dmat, data->map);
   1295 			m_freem(data->m);
   1296 		}
   1297 		if (data->map != NULL)
   1298 			bus_dmamap_destroy(sc->sc_dmat, data->map);
   1299 	}
   1300 }
   1301 
   1302 static int
   1303 iwn_alloc_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring, int qid)
   1304 {
   1305 	bus_addr_t paddr;
   1306 	bus_size_t size;
   1307 	int i, error;
   1308 
   1309 	ring->qid = qid;
   1310 	ring->queued = 0;
   1311 	ring->cur = 0;
   1312 
   1313 	/* Allocate TX descriptors (256-byte aligned). */
   1314 	size = IWN_TX_RING_COUNT * sizeof (struct iwn_tx_desc);
   1315 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->desc_dma,
   1316 	    (void **)&ring->desc, size, 256);
   1317 	if (error != 0) {
   1318 		aprint_error_dev(sc->sc_dev,
   1319 		    "could not allocate TX ring DMA memory\n");
   1320 		goto fail;
   1321 	}
   1322 	/*
   1323 	 * We only use rings 0 through 4 (4 EDCA + cmd) so there is no need
   1324 	 * to allocate commands space for other rings.
   1325 	 * XXX Do we really need to allocate descriptors for other rings?
   1326 	 */
   1327 	if (qid > 4)
   1328 		return 0;
   1329 
   1330 	size = IWN_TX_RING_COUNT * sizeof (struct iwn_tx_cmd);
   1331 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->cmd_dma,
   1332 	    (void **)&ring->cmd, size, 4);
   1333 	if (error != 0) {
   1334 		aprint_error_dev(sc->sc_dev,
   1335 		    "could not allocate TX cmd DMA memory\n");
   1336 		goto fail;
   1337 	}
   1338 
   1339 	paddr = ring->cmd_dma.paddr;
   1340 	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
   1341 		struct iwn_tx_data *data = &ring->data[i];
   1342 
   1343 		data->cmd_paddr = paddr;
   1344 		data->scratch_paddr = paddr + 12;
   1345 		paddr += sizeof (struct iwn_tx_cmd);
   1346 
   1347 		error = bus_dmamap_create(sc->sc_dmat, MCLBYTES,
   1348 		    IWN_MAX_SCATTER - 1, MCLBYTES, 0, BUS_DMA_NOWAIT,
   1349 		    &data->map);
   1350 		if (error != 0) {
   1351 			aprint_error_dev(sc->sc_dev,
   1352 			    "could not create TX buf DMA map\n");
   1353 			goto fail;
   1354 		}
   1355 	}
   1356 	return 0;
   1357 
   1358 fail:	iwn_free_tx_ring(sc, ring);
   1359 	return error;
   1360 }
   1361 
   1362 static void
   1363 iwn_reset_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
   1364 {
   1365 	int i;
   1366 
   1367 	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
   1368 		struct iwn_tx_data *data = &ring->data[i];
   1369 
   1370 		if (data->m != NULL) {
   1371 			bus_dmamap_sync(sc->sc_dmat, data->map, 0,
   1372 			    data->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
   1373 			bus_dmamap_unload(sc->sc_dmat, data->map);
   1374 			m_freem(data->m);
   1375 			data->m = NULL;
   1376 		}
   1377 	}
   1378 	/* Clear TX descriptors. */
   1379 	memset(ring->desc, 0, ring->desc_dma.size);
   1380 	bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map, 0,
   1381 	    ring->desc_dma.size, BUS_DMASYNC_PREWRITE);
   1382 	sc->qfullmsk &= ~(1 << ring->qid);
   1383 	ring->queued = 0;
   1384 	ring->cur = 0;
   1385 }
   1386 
   1387 static void
   1388 iwn_free_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
   1389 {
   1390 	int i;
   1391 
   1392 	iwn_dma_contig_free(&ring->desc_dma);
   1393 	iwn_dma_contig_free(&ring->cmd_dma);
   1394 
   1395 	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
   1396 		struct iwn_tx_data *data = &ring->data[i];
   1397 
   1398 		if (data->m != NULL) {
   1399 			bus_dmamap_sync(sc->sc_dmat, data->map, 0,
   1400 			    data->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
   1401 			bus_dmamap_unload(sc->sc_dmat, data->map);
   1402 			m_freem(data->m);
   1403 		}
   1404 		if (data->map != NULL)
   1405 			bus_dmamap_destroy(sc->sc_dmat, data->map);
   1406 	}
   1407 }
   1408 
   1409 static void
   1410 iwn5000_ict_reset(struct iwn_softc *sc)
   1411 {
   1412 	/* Disable interrupts. */
   1413 	IWN_WRITE(sc, IWN_INT_MASK, 0);
   1414 
   1415 	/* Reset ICT table. */
   1416 	memset(sc->ict, 0, IWN_ICT_SIZE);
   1417 	sc->ict_cur = 0;
   1418 
   1419 	/* Set physical address of ICT table (4KB aligned). */
   1420 	DPRINTF(("enabling ICT\n"));
   1421 	IWN_WRITE(sc, IWN_DRAM_INT_TBL, IWN_DRAM_INT_TBL_ENABLE |
   1422 	    IWN_DRAM_INT_TBL_WRAP_CHECK | sc->ict_dma.paddr >> 12);
   1423 
   1424 	/* Enable periodic RX interrupt. */
   1425 	sc->int_mask |= IWN_INT_RX_PERIODIC;
   1426 	/* Switch to ICT interrupt mode in driver. */
   1427 	sc->sc_flags |= IWN_FLAG_USE_ICT;
   1428 
   1429 	/* Re-enable interrupts. */
   1430 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
   1431 	IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
   1432 }
   1433 
   1434 static int
   1435 iwn_read_eeprom(struct iwn_softc *sc)
   1436 {
   1437 	struct iwn_ops *ops = &sc->ops;
   1438 	struct ieee80211com *ic = &sc->sc_ic;
   1439 	uint16_t val;
   1440 	int error;
   1441 
   1442 	/* Check whether adapter has an EEPROM or an OTPROM. */
   1443 	if (sc->hw_type >= IWN_HW_REV_TYPE_1000 &&
   1444 	    (IWN_READ(sc, IWN_OTP_GP) & IWN_OTP_GP_DEV_SEL_OTP))
   1445 		sc->sc_flags |= IWN_FLAG_HAS_OTPROM;
   1446 	DPRINTF(("%s found\n", (sc->sc_flags & IWN_FLAG_HAS_OTPROM) ?
   1447 	    "OTPROM" : "EEPROM"));
   1448 
   1449 	/* Adapter has to be powered on for EEPROM access to work. */
   1450 	if ((error = iwn_apm_init(sc)) != 0) {
   1451 		aprint_error_dev(sc->sc_dev,
   1452 		    "could not power ON adapter\n");
   1453 		return error;
   1454 	}
   1455 
   1456 	if ((IWN_READ(sc, IWN_EEPROM_GP) & 0x7) == 0) {
   1457 		aprint_error_dev(sc->sc_dev,
   1458 		    "bad ROM signature\n");
   1459 		return EIO;
   1460 	}
   1461 	if ((error = iwn_eeprom_lock(sc)) != 0) {
   1462 		aprint_error_dev(sc->sc_dev,
   1463 		    "could not lock ROM (error=%d)\n", error);
   1464 		return error;
   1465 	}
   1466 	if (sc->sc_flags & IWN_FLAG_HAS_OTPROM) {
   1467 		if ((error = iwn_init_otprom(sc)) != 0) {
   1468 			aprint_error_dev(sc->sc_dev,
   1469 			    "could not initialize OTPROM\n");
   1470 			return error;
   1471 		}
   1472 	}
   1473 
   1474 	iwn_read_prom_data(sc, IWN_EEPROM_SKU_CAP, &val, 2);
   1475 	DPRINTF(("SKU capabilities=0x%04x\n", le16toh(val)));
   1476 	/* Check if HT support is bonded out. */
   1477 	if (val & htole16(IWN_EEPROM_SKU_CAP_11N))
   1478 		sc->sc_flags |= IWN_FLAG_HAS_11N;
   1479 
   1480 	iwn_read_prom_data(sc, IWN_EEPROM_RFCFG, &val, 2);
   1481 	sc->rfcfg = le16toh(val);
   1482 	DPRINTF(("radio config=0x%04x\n", sc->rfcfg));
   1483 	/* Read Tx/Rx chains from ROM unless it's known to be broken. */
   1484 	if (sc->txchainmask == 0)
   1485 		sc->txchainmask = IWN_RFCFG_TXANTMSK(sc->rfcfg);
   1486 	if (sc->rxchainmask == 0)
   1487 		sc->rxchainmask = IWN_RFCFG_RXANTMSK(sc->rfcfg);
   1488 
   1489 	/* Read MAC address. */
   1490 	iwn_read_prom_data(sc, IWN_EEPROM_MAC, ic->ic_myaddr, 6);
   1491 
   1492 	/* Read adapter-specific information from EEPROM. */
   1493 	ops->read_eeprom(sc);
   1494 
   1495 	iwn_apm_stop(sc);	/* Power OFF adapter. */
   1496 
   1497 	iwn_eeprom_unlock(sc);
   1498 	return 0;
   1499 }
   1500 
   1501 static void
   1502 iwn4965_read_eeprom(struct iwn_softc *sc)
   1503 {
   1504 	uint32_t addr;
   1505 	uint16_t val;
   1506 	int i;
   1507 
   1508 	/* Read regulatory domain (4 ASCII characters). */
   1509 	iwn_read_prom_data(sc, IWN4965_EEPROM_DOMAIN, sc->eeprom_domain, 4);
   1510 
   1511 	/* Read the list of authorized channels (20MHz ones only). */
   1512 	for (i = 0; i < 5; i++) {
   1513 		addr = iwn4965_regulatory_bands[i];
   1514 		iwn_read_eeprom_channels(sc, i, addr);
   1515 	}
   1516 
   1517 	/* Read maximum allowed TX power for 2GHz and 5GHz bands. */
   1518 	iwn_read_prom_data(sc, IWN4965_EEPROM_MAXPOW, &val, 2);
   1519 	sc->maxpwr2GHz = val & 0xff;
   1520 	sc->maxpwr5GHz = val >> 8;
   1521 	/* Check that EEPROM values are within valid range. */
   1522 	if (sc->maxpwr5GHz < 20 || sc->maxpwr5GHz > 50)
   1523 		sc->maxpwr5GHz = 38;
   1524 	if (sc->maxpwr2GHz < 20 || sc->maxpwr2GHz > 50)
   1525 		sc->maxpwr2GHz = 38;
   1526 	DPRINTF(("maxpwr 2GHz=%d 5GHz=%d\n", sc->maxpwr2GHz, sc->maxpwr5GHz));
   1527 
   1528 	/* Read samples for each TX power group. */
   1529 	iwn_read_prom_data(sc, IWN4965_EEPROM_BANDS, sc->bands,
   1530 	    sizeof sc->bands);
   1531 
   1532 	/* Read voltage at which samples were taken. */
   1533 	iwn_read_prom_data(sc, IWN4965_EEPROM_VOLTAGE, &val, 2);
   1534 	sc->eeprom_voltage = (int16_t)le16toh(val);
   1535 	DPRINTF(("voltage=%d (in 0.3V)\n", sc->eeprom_voltage));
   1536 
   1537 #ifdef IWN_DEBUG
   1538 	/* Print samples. */
   1539 	if (iwn_debug > 0) {
   1540 		for (i = 0; i < IWN_NBANDS; i++)
   1541 			iwn4965_print_power_group(sc, i);
   1542 	}
   1543 #endif
   1544 }
   1545 
   1546 #ifdef IWN_DEBUG
   1547 static void
   1548 iwn4965_print_power_group(struct iwn_softc *sc, int i)
   1549 {
   1550 	struct iwn4965_eeprom_band *band = &sc->bands[i];
   1551 	struct iwn4965_eeprom_chan_samples *chans = band->chans;
   1552 	int j, c;
   1553 
   1554 	aprint_normal("===band %d===\n", i);
   1555 	aprint_normal("chan lo=%d, chan hi=%d\n", band->lo, band->hi);
   1556 	aprint_normal("chan1 num=%d\n", chans[0].num);
   1557 	for (c = 0; c < 2; c++) {
   1558 		for (j = 0; j < IWN_NSAMPLES; j++) {
   1559 			aprint_normal("chain %d, sample %d: temp=%d gain=%d "
   1560 			    "power=%d pa_det=%d\n", c, j,
   1561 			    chans[0].samples[c][j].temp,
   1562 			    chans[0].samples[c][j].gain,
   1563 			    chans[0].samples[c][j].power,
   1564 			    chans[0].samples[c][j].pa_det);
   1565 		}
   1566 	}
   1567 	aprint_normal("chan2 num=%d\n", chans[1].num);
   1568 	for (c = 0; c < 2; c++) {
   1569 		for (j = 0; j < IWN_NSAMPLES; j++) {
   1570 			aprint_normal("chain %d, sample %d: temp=%d gain=%d "
   1571 			    "power=%d pa_det=%d\n", c, j,
   1572 			    chans[1].samples[c][j].temp,
   1573 			    chans[1].samples[c][j].gain,
   1574 			    chans[1].samples[c][j].power,
   1575 			    chans[1].samples[c][j].pa_det);
   1576 		}
   1577 	}
   1578 }
   1579 #endif
   1580 
   1581 static void
   1582 iwn5000_read_eeprom(struct iwn_softc *sc)
   1583 {
   1584 	struct iwn5000_eeprom_calib_hdr hdr;
   1585 	int32_t volt;
   1586 	uint32_t base, addr;
   1587 	uint16_t val;
   1588 	int i;
   1589 
   1590 	/* Read regulatory domain (4 ASCII characters). */
   1591 	iwn_read_prom_data(sc, IWN5000_EEPROM_REG, &val, 2);
   1592 	base = le16toh(val);
   1593 	iwn_read_prom_data(sc, base + IWN5000_EEPROM_DOMAIN,
   1594 	    sc->eeprom_domain, 4);
   1595 
   1596 	/* Read the list of authorized channels (20MHz ones only). */
   1597 	for (i = 0; i < 5; i++) {
   1598 		addr = base + iwn5000_regulatory_bands[i];
   1599 		iwn_read_eeprom_channels(sc, i, addr);
   1600 	}
   1601 
   1602 	/* Read enhanced TX power information for 6000 Series. */
   1603 	if (sc->hw_type >= IWN_HW_REV_TYPE_6000)
   1604 		iwn_read_eeprom_enhinfo(sc);
   1605 
   1606 	iwn_read_prom_data(sc, IWN5000_EEPROM_CAL, &val, 2);
   1607 	base = le16toh(val);
   1608 	iwn_read_prom_data(sc, base, &hdr, sizeof hdr);
   1609 	DPRINTF(("calib version=%u pa type=%u voltage=%u\n",
   1610 	    hdr.version, hdr.pa_type, le16toh(hdr.volt)));
   1611 	sc->calib_ver = hdr.version;
   1612 
   1613 	if (sc->hw_type == IWN_HW_REV_TYPE_5150) {
   1614 		/* Compute temperature offset. */
   1615 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_TEMP, &val, 2);
   1616 		sc->eeprom_temp = le16toh(val);
   1617 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_VOLT, &val, 2);
   1618 		volt = le16toh(val);
   1619 		sc->temp_off = sc->eeprom_temp - (volt / -5);
   1620 		DPRINTF(("temp=%d volt=%d offset=%dK\n",
   1621 		    sc->eeprom_temp, volt, sc->temp_off));
   1622 	} else {
   1623 		/* Read crystal calibration. */
   1624 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_CRYSTAL,
   1625 		    &sc->eeprom_crystal, sizeof (uint32_t));
   1626 		DPRINTF(("crystal calibration 0x%08x\n",
   1627 		    le32toh(sc->eeprom_crystal)));
   1628 	}
   1629 }
   1630 
   1631 static void
   1632 iwn_read_eeprom_channels(struct iwn_softc *sc, int n, uint32_t addr)
   1633 {
   1634 	struct ieee80211com *ic = &sc->sc_ic;
   1635 	const struct iwn_chan_band *band = &iwn_bands[n];
   1636 	struct iwn_eeprom_chan channels[IWN_MAX_CHAN_PER_BAND];
   1637 	uint8_t chan;
   1638 	int i;
   1639 
   1640 	iwn_read_prom_data(sc, addr, channels,
   1641 	    band->nchan * sizeof (struct iwn_eeprom_chan));
   1642 
   1643 	for (i = 0; i < band->nchan; i++) {
   1644 		if (!(channels[i].flags & IWN_EEPROM_CHAN_VALID))
   1645 			continue;
   1646 
   1647 		chan = band->chan[i];
   1648 
   1649 		if (n == 0) {	/* 2GHz band */
   1650 			ic->ic_channels[chan].ic_freq =
   1651 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_2GHZ);
   1652 			ic->ic_channels[chan].ic_flags =
   1653 			    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
   1654 			    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
   1655 
   1656 		} else {	/* 5GHz band */
   1657 			/*
   1658 			 * Some adapters support channels 7, 8, 11 and 12
   1659 			 * both in the 2GHz and 4.9GHz bands.
   1660 			 * Because of limitations in our net80211 layer,
   1661 			 * we don't support them in the 4.9GHz band.
   1662 			 */
   1663 			if (chan <= 14)
   1664 				continue;
   1665 
   1666 			ic->ic_channels[chan].ic_freq =
   1667 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_5GHZ);
   1668 			ic->ic_channels[chan].ic_flags = IEEE80211_CHAN_A;
   1669 			/* We have at least one valid 5GHz channel. */
   1670 			sc->sc_flags |= IWN_FLAG_HAS_5GHZ;
   1671 		}
   1672 
   1673 		/* Is active scan allowed on this channel? */
   1674 		if (!(channels[i].flags & IWN_EEPROM_CHAN_ACTIVE)) {
   1675 			ic->ic_channels[chan].ic_flags |=
   1676 			    IEEE80211_CHAN_PASSIVE;
   1677 		}
   1678 
   1679 		/* Save maximum allowed TX power for this channel. */
   1680 		sc->maxpwr[chan] = channels[i].maxpwr;
   1681 
   1682 		DPRINTF(("adding chan %d flags=0x%x maxpwr=%d\n",
   1683 		    chan, channels[i].flags, sc->maxpwr[chan]));
   1684 	}
   1685 }
   1686 
   1687 static void
   1688 iwn_read_eeprom_enhinfo(struct iwn_softc *sc)
   1689 {
   1690 	struct iwn_eeprom_enhinfo enhinfo[35];
   1691 	uint16_t val, base;
   1692 	int8_t maxpwr;
   1693 	int i;
   1694 
   1695 	iwn_read_prom_data(sc, IWN5000_EEPROM_REG, &val, 2);
   1696 	base = le16toh(val);
   1697 	iwn_read_prom_data(sc, base + IWN6000_EEPROM_ENHINFO,
   1698 	    enhinfo, sizeof enhinfo);
   1699 
   1700 	memset(sc->enh_maxpwr, 0, sizeof sc->enh_maxpwr);
   1701 	for (i = 0; i < __arraycount(enhinfo); i++) {
   1702 		if (enhinfo[i].chan == 0 || enhinfo[i].reserved != 0)
   1703 			continue;	/* Skip invalid entries. */
   1704 
   1705 		maxpwr = 0;
   1706 		if (sc->txchainmask & IWN_ANT_A)
   1707 			maxpwr = MAX(maxpwr, enhinfo[i].chain[0]);
   1708 		if (sc->txchainmask & IWN_ANT_B)
   1709 			maxpwr = MAX(maxpwr, enhinfo[i].chain[1]);
   1710 		if (sc->txchainmask & IWN_ANT_C)
   1711 			maxpwr = MAX(maxpwr, enhinfo[i].chain[2]);
   1712 		if (sc->ntxchains == 2)
   1713 			maxpwr = MAX(maxpwr, enhinfo[i].mimo2);
   1714 		else if (sc->ntxchains == 3)
   1715 			maxpwr = MAX(maxpwr, enhinfo[i].mimo3);
   1716 		maxpwr /= 2;	/* Convert half-dBm to dBm. */
   1717 
   1718 		DPRINTF(("enhinfo %d, maxpwr=%d\n", i, maxpwr));
   1719 		sc->enh_maxpwr[i] = maxpwr;
   1720 	}
   1721 }
   1722 
   1723 static struct ieee80211_node *
   1724 iwn_node_alloc(struct ieee80211_node_table *ic __unused)
   1725 {
   1726 	return malloc(sizeof (struct iwn_node), M_80211_NODE, M_NOWAIT | M_ZERO);
   1727 }
   1728 
   1729 static void
   1730 iwn_newassoc(struct ieee80211_node *ni, int isnew)
   1731 {
   1732 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
   1733 	struct iwn_node *wn = (void *)ni;
   1734 	uint8_t rate;
   1735 	int ridx, i;
   1736 
   1737 	ieee80211_amrr_node_init(&sc->amrr, &wn->amn);
   1738 	/* Start at lowest available bit-rate, AMRR will raise. */
   1739 	ni->ni_txrate = 0;
   1740 
   1741 	for (i = 0; i < ni->ni_rates.rs_nrates; i++) {
   1742 		rate = ni->ni_rates.rs_rates[i] & IEEE80211_RATE_VAL;
   1743 		/* Map 802.11 rate to HW rate index. */
   1744 		for (ridx = 0; ridx <= IWN_RIDX_MAX; ridx++)
   1745 			if (iwn_rates[ridx].rate == rate)
   1746 				break;
   1747 		wn->ridx[i] = ridx;
   1748 	}
   1749 }
   1750 
   1751 static int
   1752 iwn_media_change(struct ifnet *ifp)
   1753 {
   1754 	struct iwn_softc *sc = ifp->if_softc;
   1755 	struct ieee80211com *ic = &sc->sc_ic;
   1756 	uint8_t rate, ridx;
   1757 	int error;
   1758 
   1759 	error = ieee80211_media_change(ifp);
   1760 	if (error != ENETRESET)
   1761 		return error;
   1762 
   1763 	if (ic->ic_fixed_rate != -1) {
   1764 		rate = ic->ic_sup_rates[ic->ic_curmode].
   1765 		    rs_rates[ic->ic_fixed_rate] & IEEE80211_RATE_VAL;
   1766 		/* Map 802.11 rate to HW rate index. */
   1767 		for (ridx = 0; ridx <= IWN_RIDX_MAX; ridx++)
   1768 			if (iwn_rates[ridx].rate == rate)
   1769 				break;
   1770 		sc->fixed_ridx = ridx;
   1771 	}
   1772 
   1773 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
   1774 	    (IFF_UP | IFF_RUNNING)) {
   1775 		iwn_stop(ifp, 0);
   1776 		error = iwn_init(ifp);
   1777 	}
   1778 	return error;
   1779 }
   1780 
   1781 static int
   1782 iwn_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
   1783 {
   1784 	struct ifnet *ifp = ic->ic_ifp;
   1785 	struct iwn_softc *sc = ifp->if_softc;
   1786 	int error;
   1787 
   1788 	callout_stop(&sc->calib_to);
   1789 
   1790 	switch (nstate) {
   1791 	case IEEE80211_S_SCAN:
   1792 		/* XXX Do not abort a running scan. */
   1793 		if (sc->sc_flags & IWN_FLAG_SCANNING) {
   1794 			if (ic->ic_state != nstate)
   1795 				aprint_error_dev(sc->sc_dev, "scan request(%d) "
   1796 				    "while scanning(%d) ignored\n", nstate,
   1797 				    ic->ic_state);
   1798 			break;
   1799 		}
   1800 
   1801 		/* XXX Not sure if call and flags are needed. */
   1802 		ieee80211_node_table_reset(&ic->ic_scan);
   1803 		ic->ic_flags |= IEEE80211_F_SCAN | IEEE80211_F_ASCAN;
   1804 		sc->sc_flags |= IWN_FLAG_SCANNING;
   1805 
   1806 		/* Make the link LED blink while we're scanning. */
   1807 		iwn_set_led(sc, IWN_LED_LINK, 10, 10);
   1808 
   1809 		if ((error = iwn_scan(sc, IEEE80211_CHAN_2GHZ)) != 0) {
   1810 			aprint_error_dev(sc->sc_dev,
   1811 			    "could not initiate scan\n");
   1812 			return error;
   1813 		}
   1814 		ic->ic_state = nstate;
   1815 		return 0;
   1816 
   1817 	case IEEE80211_S_ASSOC:
   1818 		if (ic->ic_state != IEEE80211_S_RUN)
   1819 			break;
   1820 		/* FALLTHROUGH */
   1821 	case IEEE80211_S_AUTH:
   1822 		/* Reset state to handle reassociations correctly. */
   1823 		sc->rxon.associd = 0;
   1824 		sc->rxon.filter &= ~htole32(IWN_FILTER_BSS);
   1825 		sc->calib.state = IWN_CALIB_STATE_INIT;
   1826 
   1827 		if ((error = iwn_auth(sc)) != 0) {
   1828 			aprint_error_dev(sc->sc_dev,
   1829 			    "could not move to auth state\n");
   1830 			return error;
   1831 		}
   1832 		break;
   1833 
   1834 	case IEEE80211_S_RUN:
   1835 		if ((error = iwn_run(sc)) != 0) {
   1836 			aprint_error_dev(sc->sc_dev,
   1837 			    "could not move to run state\n");
   1838 			return error;
   1839 		}
   1840 		break;
   1841 
   1842 	case IEEE80211_S_INIT:
   1843 		sc->sc_flags &= ~IWN_FLAG_SCANNING;
   1844 		sc->calib.state = IWN_CALIB_STATE_INIT;
   1845 		break;
   1846 	}
   1847 
   1848 	return sc->sc_newstate(ic, nstate, arg);
   1849 }
   1850 
   1851 static void
   1852 iwn_iter_func(void *arg, struct ieee80211_node *ni)
   1853 {
   1854 	struct iwn_softc *sc = arg;
   1855 	struct iwn_node *wn = (struct iwn_node *)ni;
   1856 
   1857 	ieee80211_amrr_choose(&sc->amrr, ni, &wn->amn);
   1858 }
   1859 
   1860 static void
   1861 iwn_calib_timeout(void *arg)
   1862 {
   1863 	struct iwn_softc *sc = arg;
   1864 	struct ieee80211com *ic = &sc->sc_ic;
   1865 	int s;
   1866 
   1867 	s = splnet();
   1868 	if (ic->ic_fixed_rate == -1) {
   1869 		if (ic->ic_opmode == IEEE80211_M_STA)
   1870 			iwn_iter_func(sc, ic->ic_bss);
   1871 		else
   1872 			ieee80211_iterate_nodes(&ic->ic_sta, iwn_iter_func, sc);
   1873 	}
   1874 	/* Force automatic TX power calibration every 60 secs. */
   1875 	if (++sc->calib_cnt >= 120) {
   1876 		uint32_t flags = 0;
   1877 
   1878 		DPRINTF(("sending request for statistics\n"));
   1879 		(void)iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags,
   1880 		    sizeof flags, 1);
   1881 		sc->calib_cnt = 0;
   1882 	}
   1883 	splx(s);
   1884 
   1885 	/* Automatic rate control triggered every 500ms. */
   1886 	callout_schedule(&sc->calib_to, hz/2);
   1887 }
   1888 
   1889 /*
   1890  * Process an RX_PHY firmware notification.  This is usually immediately
   1891  * followed by an MPDU_RX_DONE notification.
   1892  */
   1893 static void
   1894 iwn_rx_phy(struct iwn_softc *sc, struct iwn_rx_desc *desc,
   1895     struct iwn_rx_data *data)
   1896 {
   1897 	struct iwn_rx_stat *stat = (struct iwn_rx_stat *)(desc + 1);
   1898 
   1899 	DPRINTFN(2, ("received PHY stats\n"));
   1900 	bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc),
   1901 	    sizeof (*stat), BUS_DMASYNC_POSTREAD);
   1902 
   1903 	/* Save RX statistics, they will be used on MPDU_RX_DONE. */
   1904 	memcpy(&sc->last_rx_stat, stat, sizeof (*stat));
   1905 	sc->last_rx_valid = 1;
   1906 }
   1907 
   1908 /*
   1909  * Process an RX_DONE (4965AGN only) or MPDU_RX_DONE firmware notification.
   1910  * Each MPDU_RX_DONE notification must be preceded by an RX_PHY one.
   1911  */
   1912 static void
   1913 iwn_rx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
   1914     struct iwn_rx_data *data)
   1915 {
   1916 	struct iwn_ops *ops = &sc->ops;
   1917 	struct ieee80211com *ic = &sc->sc_ic;
   1918 	struct ifnet *ifp = ic->ic_ifp;
   1919 	struct iwn_rx_ring *ring = &sc->rxq;
   1920 	struct ieee80211_frame *wh;
   1921 	struct ieee80211_node *ni;
   1922 	struct mbuf *m, *m1;
   1923 	struct iwn_rx_stat *stat;
   1924 	char	*head;
   1925 	uint32_t flags;
   1926 	int error, len, rssi;
   1927 
   1928 	if (desc->type == IWN_MPDU_RX_DONE) {
   1929 		/* Check for prior RX_PHY notification. */
   1930 		if (!sc->last_rx_valid) {
   1931 			DPRINTF(("missing RX_PHY\n"));
   1932 			return;
   1933 		}
   1934 		sc->last_rx_valid = 0;
   1935 		stat = &sc->last_rx_stat;
   1936 	} else
   1937 		stat = (struct iwn_rx_stat *)(desc + 1);
   1938 
   1939 	bus_dmamap_sync(sc->sc_dmat, data->map, 0, IWN_RBUF_SIZE,
   1940 	    BUS_DMASYNC_POSTREAD);
   1941 
   1942 	if (stat->cfg_phy_len > IWN_STAT_MAXLEN) {
   1943 		aprint_error_dev(sc->sc_dev,
   1944 		    "invalid RX statistic header\n");
   1945 		return;
   1946 	}
   1947 	if (desc->type == IWN_MPDU_RX_DONE) {
   1948 		struct iwn_rx_mpdu *mpdu = (struct iwn_rx_mpdu *)(desc + 1);
   1949 		head = (char *)(mpdu + 1);
   1950 		len = le16toh(mpdu->len);
   1951 	} else {
   1952 		head = (char *)(stat + 1) + stat->cfg_phy_len;
   1953 		len = le16toh(stat->len);
   1954 	}
   1955 
   1956 	flags = le32toh(*(uint32_t *)(head + len));
   1957 
   1958 	/* Discard frames with a bad FCS early. */
   1959 	if ((flags & IWN_RX_NOERROR) != IWN_RX_NOERROR) {
   1960 		DPRINTFN(2, ("RX flags error %x\n", flags));
   1961 		ifp->if_ierrors++;
   1962 		return;
   1963 	}
   1964 	/* Discard frames that are too short. */
   1965 	if (len < sizeof (*wh)) {
   1966 		DPRINTF(("frame too short: %d\n", len));
   1967 		ic->ic_stats.is_rx_tooshort++;
   1968 		ifp->if_ierrors++;
   1969 		return;
   1970 	}
   1971 
   1972 	m1 = MCLGETIalt(sc, M_DONTWAIT, NULL, IWN_RBUF_SIZE);
   1973 	if (m1 == NULL) {
   1974 		ic->ic_stats.is_rx_nobuf++;
   1975 		ifp->if_ierrors++;
   1976 		return;
   1977 	}
   1978 	bus_dmamap_unload(sc->sc_dmat, data->map);
   1979 
   1980 	error = bus_dmamap_load(sc->sc_dmat, data->map, mtod(m1, void *),
   1981 	    IWN_RBUF_SIZE, NULL, BUS_DMA_NOWAIT | BUS_DMA_READ);
   1982 	if (error != 0) {
   1983 		m_freem(m1);
   1984 
   1985 		/* Try to reload the old mbuf. */
   1986 		error = bus_dmamap_load(sc->sc_dmat, data->map,
   1987 		    mtod(data->m, void *), IWN_RBUF_SIZE, NULL,
   1988 		    BUS_DMA_NOWAIT | BUS_DMA_READ);
   1989 		if (error != 0) {
   1990 			panic("%s: could not load old RX mbuf",
   1991 			    device_xname(sc->sc_dev));
   1992 		}
   1993 		/* Physical address may have changed. */
   1994 		ring->desc[ring->cur] =
   1995 		    htole32(data->map->dm_segs[0].ds_addr >> 8);
   1996 		bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map,
   1997 		    ring->cur * sizeof (uint32_t), sizeof (uint32_t),
   1998 		    BUS_DMASYNC_PREWRITE);
   1999 		ifp->if_ierrors++;
   2000 		return;
   2001 	}
   2002 
   2003 	m = data->m;
   2004 	data->m = m1;
   2005 	/* Update RX descriptor. */
   2006 	ring->desc[ring->cur] = htole32(data->map->dm_segs[0].ds_addr >> 8);
   2007 	bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map,
   2008 	    ring->cur * sizeof (uint32_t), sizeof (uint32_t),
   2009 	    BUS_DMASYNC_PREWRITE);
   2010 
   2011 	/* Finalize mbuf. */
   2012 	m->m_pkthdr.rcvif = ifp;
   2013 	m->m_data = head;
   2014 	m->m_pkthdr.len = m->m_len = len;
   2015 
   2016 	/* Grab a reference to the source node. */
   2017 	wh = mtod(m, struct ieee80211_frame *);
   2018 	ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
   2019 
   2020 	/* XXX OpenBSD adds decryption here (see also comments in iwn_tx). */
   2021 	/* NetBSD does decryption in ieee80211_input. */
   2022 
   2023 	rssi = ops->get_rssi(stat);
   2024 
   2025 	/* XXX Added for NetBSD: scans never stop without it */
   2026 	if (ic->ic_state == IEEE80211_S_SCAN)
   2027 		iwn_fix_channel(ic, m);
   2028 
   2029 	if (sc->sc_drvbpf != NULL) {
   2030 		struct iwn_rx_radiotap_header *tap = &sc->sc_rxtap;
   2031 
   2032 		tap->wr_flags = 0;
   2033 		if (stat->flags & htole16(IWN_STAT_FLAG_SHPREAMBLE))
   2034 			tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
   2035 		tap->wr_chan_freq =
   2036 		    htole16(ic->ic_channels[stat->chan].ic_freq);
   2037 		tap->wr_chan_flags =
   2038 		    htole16(ic->ic_channels[stat->chan].ic_flags);
   2039 		tap->wr_dbm_antsignal = (int8_t)rssi;
   2040 		tap->wr_dbm_antnoise = (int8_t)sc->noise;
   2041 		tap->wr_tsft = stat->tstamp;
   2042 		switch (stat->rate) {
   2043 		/* CCK rates. */
   2044 		case  10: tap->wr_rate =   2; break;
   2045 		case  20: tap->wr_rate =   4; break;
   2046 		case  55: tap->wr_rate =  11; break;
   2047 		case 110: tap->wr_rate =  22; break;
   2048 		/* OFDM rates. */
   2049 		case 0xd: tap->wr_rate =  12; break;
   2050 		case 0xf: tap->wr_rate =  18; break;
   2051 		case 0x5: tap->wr_rate =  24; break;
   2052 		case 0x7: tap->wr_rate =  36; break;
   2053 		case 0x9: tap->wr_rate =  48; break;
   2054 		case 0xb: tap->wr_rate =  72; break;
   2055 		case 0x1: tap->wr_rate =  96; break;
   2056 		case 0x3: tap->wr_rate = 108; break;
   2057 		/* Unknown rate: should not happen. */
   2058 		default:  tap->wr_rate =   0;
   2059 		}
   2060 
   2061 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_rxtap_len, m);
   2062 	}
   2063 
   2064 	/* Send the frame to the 802.11 layer. */
   2065 	ieee80211_input(ic, m, ni, rssi, 0);
   2066 
   2067 	/* Node is no longer needed. */
   2068 	ieee80211_free_node(ni);
   2069 }
   2070 
   2071 #ifndef IEEE80211_NO_HT
   2072 /* Process an incoming Compressed BlockAck. */
   2073 static void
   2074 iwn_rx_compressed_ba(struct iwn_softc *sc, struct iwn_rx_desc *desc,
   2075     struct iwn_rx_data *data)
   2076 {
   2077 	struct iwn_compressed_ba *ba = (struct iwn_compressed_ba *)(desc + 1);
   2078 	struct iwn_tx_ring *txq;
   2079 
   2080 	bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc), sizeof (*ba),
   2081 	    BUS_DMASYNC_POSTREAD);
   2082 
   2083 	txq = &sc->txq[le16toh(ba->qid)];
   2084 	/* XXX TBD */
   2085 }
   2086 #endif
   2087 
   2088 /*
   2089  * Process a CALIBRATION_RESULT notification sent by the initialization
   2090  * firmware on response to a CMD_CALIB_CONFIG command (5000 only).
   2091  */
   2092 static void
   2093 iwn5000_rx_calib_results(struct iwn_softc *sc, struct iwn_rx_desc *desc,
   2094     struct iwn_rx_data *data)
   2095 {
   2096 	struct iwn_phy_calib *calib = (struct iwn_phy_calib *)(desc + 1);
   2097 	int len, idx = -1;
   2098 
   2099 	/* Runtime firmware should not send such a notification. */
   2100 	if (sc->sc_flags & IWN_FLAG_CALIB_DONE)
   2101 		return;
   2102 
   2103 	len = (le32toh(desc->len) & 0x3fff) - 4;
   2104 	bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc), len,
   2105 	    BUS_DMASYNC_POSTREAD);
   2106 
   2107 	switch (calib->code) {
   2108 	case IWN5000_PHY_CALIB_DC:
   2109 		if (sc->hw_type == IWN_HW_REV_TYPE_5150)
   2110 			idx = 0;
   2111 		break;
   2112 	case IWN5000_PHY_CALIB_LO:
   2113 		idx = 1;
   2114 		break;
   2115 	case IWN5000_PHY_CALIB_TX_IQ:
   2116 		idx = 2;
   2117 		break;
   2118 	case IWN5000_PHY_CALIB_TX_IQ_PERIODIC:
   2119 		if (sc->hw_type < IWN_HW_REV_TYPE_6000 &&
   2120 		    sc->hw_type != IWN_HW_REV_TYPE_5150)
   2121 			idx = 3;
   2122 		break;
   2123 	case IWN5000_PHY_CALIB_BASE_BAND:
   2124 		idx = 4;
   2125 		break;
   2126 	}
   2127 	if (idx == -1)	/* Ignore other results. */
   2128 		return;
   2129 
   2130 	/* Save calibration result. */
   2131 	if (sc->calibcmd[idx].buf != NULL)
   2132 		free(sc->calibcmd[idx].buf, M_DEVBUF);
   2133 	sc->calibcmd[idx].buf = malloc(len, M_DEVBUF, M_NOWAIT);
   2134 	if (sc->calibcmd[idx].buf == NULL) {
   2135 		DPRINTF(("not enough memory for calibration result %d\n",
   2136 		    calib->code));
   2137 		return;
   2138 	}
   2139 	DPRINTF(("saving calibration result code=%d len=%d\n",
   2140 	    calib->code, len));
   2141 	sc->calibcmd[idx].len = len;
   2142 	memcpy(sc->calibcmd[idx].buf, calib, len);
   2143 }
   2144 
   2145 /*
   2146  * Process an RX_STATISTICS or BEACON_STATISTICS firmware notification.
   2147  * The latter is sent by the firmware after each received beacon.
   2148  */
   2149 static void
   2150 iwn_rx_statistics(struct iwn_softc *sc, struct iwn_rx_desc *desc,
   2151     struct iwn_rx_data *data)
   2152 {
   2153 	struct iwn_ops *ops = &sc->ops;
   2154 	struct ieee80211com *ic = &sc->sc_ic;
   2155 	struct iwn_calib_state *calib = &sc->calib;
   2156 	struct iwn_stats *stats = (struct iwn_stats *)(desc + 1);
   2157 	int temp;
   2158 
   2159 	/* Ignore statistics received during a scan. */
   2160 	if (ic->ic_state != IEEE80211_S_RUN)
   2161 		return;
   2162 
   2163 	bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc),
   2164 	    sizeof (*stats), BUS_DMASYNC_POSTREAD);
   2165 
   2166 	DPRINTFN(3, ("received statistics (cmd=%d)\n", desc->type));
   2167 	sc->calib_cnt = 0;	/* Reset TX power calibration timeout. */
   2168 
   2169 	/* Test if temperature has changed. */
   2170 	if (stats->general.temp != sc->rawtemp) {
   2171 		/* Convert "raw" temperature to degC. */
   2172 		sc->rawtemp = stats->general.temp;
   2173 		temp = ops->get_temperature(sc);
   2174 		DPRINTFN(2, ("temperature=%dC\n", temp));
   2175 
   2176 		/* Update TX power if need be (4965AGN only). */
   2177 		if (sc->hw_type == IWN_HW_REV_TYPE_4965)
   2178 			iwn4965_power_calibration(sc, temp);
   2179 	}
   2180 
   2181 	if (desc->type != IWN_BEACON_STATISTICS)
   2182 		return;	/* Reply to a statistics request. */
   2183 
   2184 	sc->noise = iwn_get_noise(&stats->rx.general);
   2185 
   2186 	/* Test that RSSI and noise are present in stats report. */
   2187 	if (le32toh(stats->rx.general.flags) != 1) {
   2188 		DPRINTF(("received statistics without RSSI\n"));
   2189 		return;
   2190 	}
   2191 
   2192 	/*
   2193 	 * XXX Differential gain calibration makes the 6005 firmware
   2194 	 * crap out, so skip it for now.  This effectively disables
   2195 	 * sensitivity tuning as well.
   2196 	 */
   2197 	if (sc->hw_type == IWN_HW_REV_TYPE_6005)
   2198 		return;
   2199 
   2200 	if (calib->state == IWN_CALIB_STATE_ASSOC)
   2201 		iwn_collect_noise(sc, &stats->rx.general);
   2202 	else if (calib->state == IWN_CALIB_STATE_RUN)
   2203 		iwn_tune_sensitivity(sc, &stats->rx);
   2204 }
   2205 
   2206 /*
   2207  * Process a TX_DONE firmware notification.  Unfortunately, the 4965AGN
   2208  * and 5000 adapters have different incompatible TX status formats.
   2209  */
   2210 static void
   2211 iwn4965_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
   2212     struct iwn_rx_data *data)
   2213 {
   2214 	struct iwn4965_tx_stat *stat = (struct iwn4965_tx_stat *)(desc + 1);
   2215 
   2216 	bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc),
   2217 	    sizeof (*stat), BUS_DMASYNC_POSTREAD);
   2218 	iwn_tx_done(sc, desc, stat->ackfailcnt, le32toh(stat->status) & 0xff);
   2219 }
   2220 
   2221 static void
   2222 iwn5000_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
   2223     struct iwn_rx_data *data)
   2224 {
   2225 	struct iwn5000_tx_stat *stat = (struct iwn5000_tx_stat *)(desc + 1);
   2226 
   2227 #ifdef notyet
   2228 	/* Reset TX scheduler slot. */
   2229 	iwn5000_reset_sched(sc, desc->qid & 0xf, desc->idx);
   2230 #endif
   2231 
   2232 	bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc),
   2233 	    sizeof (*stat), BUS_DMASYNC_POSTREAD);
   2234 	iwn_tx_done(sc, desc, stat->ackfailcnt, le16toh(stat->status) & 0xff);
   2235 }
   2236 
   2237 /*
   2238  * Adapter-independent backend for TX_DONE firmware notifications.
   2239  */
   2240 static void
   2241 iwn_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc, int ackfailcnt,
   2242     uint8_t status)
   2243 {
   2244 	struct ieee80211com *ic = &sc->sc_ic;
   2245 	struct ifnet *ifp = ic->ic_ifp;
   2246 	struct iwn_tx_ring *ring = &sc->txq[desc->qid & 0xf];
   2247 	struct iwn_tx_data *data = &ring->data[desc->idx];
   2248 	struct iwn_node *wn = (struct iwn_node *)data->ni;
   2249 
   2250 	/* Update rate control statistics. */
   2251 	wn->amn.amn_txcnt++;
   2252 	if (ackfailcnt > 0)
   2253 		wn->amn.amn_retrycnt++;
   2254 
   2255 	if (status != 1 && status != 2)
   2256 		ifp->if_oerrors++;
   2257 	else
   2258 		ifp->if_opackets++;
   2259 
   2260 	/* Unmap and free mbuf. */
   2261 	bus_dmamap_sync(sc->sc_dmat, data->map, 0, data->map->dm_mapsize,
   2262 	    BUS_DMASYNC_POSTWRITE);
   2263 	bus_dmamap_unload(sc->sc_dmat, data->map);
   2264 	m_freem(data->m);
   2265 	data->m = NULL;
   2266 	ieee80211_free_node(data->ni);
   2267 	data->ni = NULL;
   2268 
   2269 	sc->sc_tx_timer = 0;
   2270 	if (--ring->queued < IWN_TX_RING_LOMARK) {
   2271 		sc->qfullmsk &= ~(1 << ring->qid);
   2272 		if (sc->qfullmsk == 0 && (ifp->if_flags & IFF_OACTIVE)) {
   2273 			ifp->if_flags &= ~IFF_OACTIVE;
   2274 			(*ifp->if_start)(ifp);
   2275 		}
   2276 	}
   2277 }
   2278 
   2279 /*
   2280  * Process a "command done" firmware notification.  This is where we wakeup
   2281  * processes waiting for a synchronous command completion.
   2282  */
   2283 static void
   2284 iwn_cmd_done(struct iwn_softc *sc, struct iwn_rx_desc *desc)
   2285 {
   2286 	struct iwn_tx_ring *ring = &sc->txq[4];
   2287 	struct iwn_tx_data *data;
   2288 
   2289 	if ((desc->qid & 0xf) != 4)
   2290 		return;	/* Not a command ack. */
   2291 
   2292 	data = &ring->data[desc->idx];
   2293 
   2294 	/* If the command was mapped in an mbuf, free it. */
   2295 	if (data->m != NULL) {
   2296 		bus_dmamap_sync(sc->sc_dmat, data->map, 0,
   2297 		    data->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
   2298 		bus_dmamap_unload(sc->sc_dmat, data->map);
   2299 		m_freem(data->m);
   2300 		data->m = NULL;
   2301 	}
   2302 	wakeup(&ring->desc[desc->idx]);
   2303 }
   2304 
   2305 /*
   2306  * Process an INT_FH_RX or INT_SW_RX interrupt.
   2307  */
   2308 static void
   2309 iwn_notif_intr(struct iwn_softc *sc)
   2310 {
   2311 	struct iwn_ops *ops = &sc->ops;
   2312 	struct ieee80211com *ic = &sc->sc_ic;
   2313 	struct ifnet *ifp = ic->ic_ifp;
   2314 	uint16_t hw;
   2315 
   2316 	bus_dmamap_sync(sc->sc_dmat, sc->rxq.stat_dma.map,
   2317 	    0, sc->rxq.stat_dma.size, BUS_DMASYNC_POSTREAD);
   2318 
   2319 	hw = le16toh(sc->rxq.stat->closed_count) & 0xfff;
   2320 	while (sc->rxq.cur != hw) {
   2321 		struct iwn_rx_data *data = &sc->rxq.data[sc->rxq.cur];
   2322 		struct iwn_rx_desc *desc;
   2323 
   2324 		bus_dmamap_sync(sc->sc_dmat, data->map, 0, sizeof (*desc),
   2325 		    BUS_DMASYNC_POSTREAD);
   2326 		desc = mtod(data->m, struct iwn_rx_desc *);
   2327 
   2328 		DPRINTFN(4, ("notification qid=%d idx=%d flags=%x type=%d\n",
   2329 		    desc->qid & 0xf, desc->idx, desc->flags, desc->type));
   2330 
   2331 		if (!(desc->qid & 0x80))	/* Reply to a command. */
   2332 			iwn_cmd_done(sc, desc);
   2333 
   2334 		switch (desc->type) {
   2335 		case IWN_RX_PHY:
   2336 			iwn_rx_phy(sc, desc, data);
   2337 			break;
   2338 
   2339 		case IWN_RX_DONE:		/* 4965AGN only. */
   2340 		case IWN_MPDU_RX_DONE:
   2341 			/* An 802.11 frame has been received. */
   2342 			iwn_rx_done(sc, desc, data);
   2343 			break;
   2344 #ifndef IEEE80211_NO_HT
   2345 		case IWN_RX_COMPRESSED_BA:
   2346 			/* A Compressed BlockAck has been received. */
   2347 			iwn_rx_compressed_ba(sc, desc, data);
   2348 			break;
   2349 #endif
   2350 		case IWN_TX_DONE:
   2351 			/* An 802.11 frame has been transmitted. */
   2352 			ops->tx_done(sc, desc, data);
   2353 			break;
   2354 
   2355 		case IWN_RX_STATISTICS:
   2356 		case IWN_BEACON_STATISTICS:
   2357 			iwn_rx_statistics(sc, desc, data);
   2358 			break;
   2359 
   2360 		case IWN_BEACON_MISSED:
   2361 		{
   2362 			struct iwn_beacon_missed *miss =
   2363 			    (struct iwn_beacon_missed *)(desc + 1);
   2364 
   2365 			bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc),
   2366 			    sizeof (*miss), BUS_DMASYNC_POSTREAD);
   2367 			/*
   2368 			 * If more than 5 consecutive beacons are missed,
   2369 			 * reinitialize the sensitivity state machine.
   2370 			 */
   2371 			DPRINTF(("beacons missed %d/%d\n",
   2372 			    le32toh(miss->consecutive), le32toh(miss->total)));
   2373 			if (ic->ic_state == IEEE80211_S_RUN &&
   2374 			    le32toh(miss->consecutive) > 5)
   2375 				(void)iwn_init_sensitivity(sc);
   2376 			break;
   2377 		}
   2378 		case IWN_UC_READY:
   2379 		{
   2380 			struct iwn_ucode_info *uc =
   2381 			    (struct iwn_ucode_info *)(desc + 1);
   2382 
   2383 			/* The microcontroller is ready. */
   2384 			bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc),
   2385 			    sizeof (*uc), BUS_DMASYNC_POSTREAD);
   2386 			DPRINTF(("microcode alive notification version=%d.%d "
   2387 			    "subtype=%x alive=%x\n", uc->major, uc->minor,
   2388 			    uc->subtype, le32toh(uc->valid)));
   2389 
   2390 			if (le32toh(uc->valid) != 1) {
   2391 				aprint_error_dev(sc->sc_dev,
   2392 				    "microcontroller initialization "
   2393 				    "failed\n");
   2394 				break;
   2395 			}
   2396 			if (uc->subtype == IWN_UCODE_INIT) {
   2397 				/* Save microcontroller report. */
   2398 				memcpy(&sc->ucode_info, uc, sizeof (*uc));
   2399 			}
   2400 			/* Save the address of the error log in SRAM. */
   2401 			sc->errptr = le32toh(uc->errptr);
   2402 			break;
   2403 		}
   2404 		case IWN_STATE_CHANGED:
   2405 		{
   2406 			uint32_t *status = (uint32_t *)(desc + 1);
   2407 
   2408 			/* Enabled/disabled notification. */
   2409 			bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc),
   2410 			    sizeof (*status), BUS_DMASYNC_POSTREAD);
   2411 			DPRINTF(("state changed to %x\n", le32toh(*status)));
   2412 
   2413 			if (le32toh(*status) & 1) {
   2414 				/* The radio button has to be pushed. */
   2415 				aprint_error_dev(sc->sc_dev,
   2416 				    "Radio transmitter is off\n");
   2417 				/* Turn the interface down. */
   2418 				ifp->if_flags &= ~IFF_UP;
   2419 				iwn_stop(ifp, 1);
   2420 				return;	/* No further processing. */
   2421 			}
   2422 			break;
   2423 		}
   2424 		case IWN_START_SCAN:
   2425 		{
   2426 			struct iwn_start_scan *scan =
   2427 			    (struct iwn_start_scan *)(desc + 1);
   2428 
   2429 			bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc),
   2430 			    sizeof (*scan), BUS_DMASYNC_POSTREAD);
   2431 			DPRINTFN(2, ("scanning channel %d status %x\n",
   2432 			    scan->chan, le32toh(scan->status)));
   2433 
   2434 			/* Fix current channel. */
   2435 			ic->ic_bss->ni_chan = &ic->ic_channels[scan->chan];
   2436 			break;
   2437 		}
   2438 		case IWN_STOP_SCAN:
   2439 		{
   2440 			struct iwn_stop_scan *scan =
   2441 			    (struct iwn_stop_scan *)(desc + 1);
   2442 
   2443 			bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc),
   2444 			    sizeof (*scan), BUS_DMASYNC_POSTREAD);
   2445 			DPRINTF(("scan finished nchan=%d status=%d chan=%d\n",
   2446 			    scan->nchan, scan->status, scan->chan));
   2447 
   2448 			if (scan->status == 1 && scan->chan <= 14 &&
   2449 			    (sc->sc_flags & IWN_FLAG_HAS_5GHZ)) {
   2450 				/*
   2451 				 * We just finished scanning 2GHz channels,
   2452 				 * start scanning 5GHz ones.
   2453 				 */
   2454 				if (iwn_scan(sc, IEEE80211_CHAN_5GHZ) == 0)
   2455 					break;
   2456 			}
   2457 			sc->sc_flags &= ~IWN_FLAG_SCANNING;
   2458 			ieee80211_end_scan(ic);
   2459 			break;
   2460 		}
   2461 		case IWN5000_CALIBRATION_RESULT:
   2462 			iwn5000_rx_calib_results(sc, desc, data);
   2463 			break;
   2464 
   2465 		case IWN5000_CALIBRATION_DONE:
   2466 			sc->sc_flags |= IWN_FLAG_CALIB_DONE;
   2467 			wakeup(sc);
   2468 			break;
   2469 		}
   2470 
   2471 		sc->rxq.cur = (sc->rxq.cur + 1) % IWN_RX_RING_COUNT;
   2472 	}
   2473 
   2474 	/* Tell the firmware what we have processed. */
   2475 	hw = (hw == 0) ? IWN_RX_RING_COUNT - 1 : hw - 1;
   2476 	IWN_WRITE(sc, IWN_FH_RX_WPTR, hw & ~7);
   2477 }
   2478 
   2479 /*
   2480  * Process an INT_WAKEUP interrupt raised when the microcontroller wakes up
   2481  * from power-down sleep mode.
   2482  */
   2483 static void
   2484 iwn_wakeup_intr(struct iwn_softc *sc)
   2485 {
   2486 	int qid;
   2487 
   2488 	DPRINTF(("ucode wakeup from power-down sleep\n"));
   2489 
   2490 	/* Wakeup RX and TX rings. */
   2491 	IWN_WRITE(sc, IWN_FH_RX_WPTR, sc->rxq.cur & ~7);
   2492 	for (qid = 0; qid < sc->ntxqs; qid++) {
   2493 		struct iwn_tx_ring *ring = &sc->txq[qid];
   2494 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | ring->cur);
   2495 	}
   2496 }
   2497 
   2498 /*
   2499  * Dump the error log of the firmware when a firmware panic occurs.  Although
   2500  * we can't debug the firmware because it is neither open source nor free, it
   2501  * can help us to identify certain classes of problems.
   2502  */
   2503 static void
   2504 iwn_fatal_intr(struct iwn_softc *sc)
   2505 {
   2506 	struct iwn_fw_dump dump;
   2507 	int i;
   2508 
   2509 	/* Force a complete recalibration on next init. */
   2510 	sc->sc_flags &= ~IWN_FLAG_CALIB_DONE;
   2511 
   2512 	/* Check that the error log address is valid. */
   2513 	if (sc->errptr < IWN_FW_DATA_BASE ||
   2514 	    sc->errptr + sizeof (dump) >
   2515 	    IWN_FW_DATA_BASE + sc->fw_data_maxsz) {
   2516 		aprint_error_dev(sc->sc_dev,
   2517 		    "bad firmware error log address 0x%08x\n", sc->errptr);
   2518 		return;
   2519 	}
   2520 	if (iwn_nic_lock(sc) != 0) {
   2521 		aprint_error_dev(sc->sc_dev,
   2522 		    "could not read firmware error log\n");
   2523 		return;
   2524 	}
   2525 	/* Read firmware error log from SRAM. */
   2526 	iwn_mem_read_region_4(sc, sc->errptr, (uint32_t *)&dump,
   2527 	    sizeof (dump) / sizeof (uint32_t));
   2528 	iwn_nic_unlock(sc);
   2529 
   2530 	if (dump.valid == 0) {
   2531 		aprint_error_dev(sc->sc_dev,
   2532 		    "firmware error log is empty\n");
   2533 		return;
   2534 	}
   2535 	aprint_error("firmware error log:\n");
   2536 	aprint_error("  error type      = \"%s\" (0x%08X)\n",
   2537 	    (dump.id < __arraycount(iwn_fw_errmsg)) ?
   2538 		iwn_fw_errmsg[dump.id] : "UNKNOWN",
   2539 	    dump.id);
   2540 	aprint_error("  program counter = 0x%08X\n", dump.pc);
   2541 	aprint_error("  source line     = 0x%08X\n", dump.src_line);
   2542 	aprint_error("  error data      = 0x%08X%08X\n",
   2543 	    dump.error_data[0], dump.error_data[1]);
   2544 	aprint_error("  branch link     = 0x%08X%08X\n",
   2545 	    dump.branch_link[0], dump.branch_link[1]);
   2546 	aprint_error("  interrupt link  = 0x%08X%08X\n",
   2547 	    dump.interrupt_link[0], dump.interrupt_link[1]);
   2548 	aprint_error("  time            = %u\n", dump.time[0]);
   2549 
   2550 	/* Dump driver status (TX and RX rings) while we're here. */
   2551 	aprint_error("driver status:\n");
   2552 	for (i = 0; i < sc->ntxqs; i++) {
   2553 		struct iwn_tx_ring *ring = &sc->txq[i];
   2554 		aprint_error("  tx ring %2d: qid=%-2d cur=%-3d queued=%-3d\n",
   2555 		    i, ring->qid, ring->cur, ring->queued);
   2556 	}
   2557 	aprint_error("  rx ring: cur=%d\n", sc->rxq.cur);
   2558 	aprint_error("  802.11 state %d\n", sc->sc_ic.ic_state);
   2559 }
   2560 
   2561 static int
   2562 iwn_intr(void *arg)
   2563 {
   2564 	struct iwn_softc *sc = arg;
   2565 	struct ifnet *ifp = sc->sc_ic.ic_ifp;
   2566 	uint32_t r1, r2, tmp;
   2567 
   2568 	/* Disable interrupts. */
   2569 	IWN_WRITE(sc, IWN_INT_MASK, 0);
   2570 
   2571 	/* Read interrupts from ICT (fast) or from registers (slow). */
   2572 	if (sc->sc_flags & IWN_FLAG_USE_ICT) {
   2573 		tmp = 0;
   2574 		while (sc->ict[sc->ict_cur] != 0) {
   2575 			tmp |= sc->ict[sc->ict_cur];
   2576 			sc->ict[sc->ict_cur] = 0;	/* Acknowledge. */
   2577 			sc->ict_cur = (sc->ict_cur + 1) % IWN_ICT_COUNT;
   2578 		}
   2579 		tmp = le32toh(tmp);
   2580 		if (tmp == 0xffffffff)	/* Shouldn't happen. */
   2581 			tmp = 0;
   2582 		else if (tmp & 0xc0000)	/* Workaround a HW bug. */
   2583 			tmp |= 0x8000;
   2584 		r1 = (tmp & 0xff00) << 16 | (tmp & 0xff);
   2585 		r2 = 0;	/* Unused. */
   2586 	} else {
   2587 		r1 = IWN_READ(sc, IWN_INT);
   2588 		if (r1 == 0xffffffff || (r1 & 0xfffffff0) == 0xa5a5a5a0)
   2589 			return 0;	/* Hardware gone! */
   2590 		r2 = IWN_READ(sc, IWN_FH_INT);
   2591 	}
   2592 	if (r1 == 0 && r2 == 0) {
   2593 		if (ifp->if_flags & IFF_UP)
   2594 			IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
   2595 		return 0;	/* Interrupt not for us. */
   2596 	}
   2597 
   2598 	/* Acknowledge interrupts. */
   2599 	IWN_WRITE(sc, IWN_INT, r1);
   2600 	if (!(sc->sc_flags & IWN_FLAG_USE_ICT))
   2601 		IWN_WRITE(sc, IWN_FH_INT, r2);
   2602 
   2603 	if (r1 & IWN_INT_RF_TOGGLED) {
   2604 		tmp = IWN_READ(sc, IWN_GP_CNTRL);
   2605 		aprint_error_dev(sc->sc_dev,
   2606 		    "RF switch: radio %s\n",
   2607 		    (tmp & IWN_GP_CNTRL_RFKILL) ? "enabled" : "disabled");
   2608 	}
   2609 	if (r1 & IWN_INT_CT_REACHED) {
   2610 		aprint_error_dev(sc->sc_dev,
   2611 		    "critical temperature reached!\n");
   2612 	}
   2613 	if (r1 & (IWN_INT_SW_ERR | IWN_INT_HW_ERR)) {
   2614 		aprint_error_dev(sc->sc_dev,
   2615 		    "fatal firmware error\n");
   2616 		/* Dump firmware error log and stop. */
   2617 		iwn_fatal_intr(sc);
   2618 		ifp->if_flags &= ~IFF_UP;
   2619 		iwn_stop(ifp, 1);
   2620 		return 1;
   2621 	}
   2622 	if ((r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX | IWN_INT_RX_PERIODIC)) ||
   2623 	    (r2 & IWN_FH_INT_RX)) {
   2624 		if (sc->sc_flags & IWN_FLAG_USE_ICT) {
   2625 			if (r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX))
   2626 				IWN_WRITE(sc, IWN_FH_INT, IWN_FH_INT_RX);
   2627 			IWN_WRITE_1(sc, IWN_INT_PERIODIC,
   2628 			    IWN_INT_PERIODIC_DIS);
   2629 			iwn_notif_intr(sc);
   2630 			if (r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX)) {
   2631 				IWN_WRITE_1(sc, IWN_INT_PERIODIC,
   2632 				    IWN_INT_PERIODIC_ENA);
   2633 			}
   2634 		} else
   2635 			iwn_notif_intr(sc);
   2636 	}
   2637 
   2638 	if ((r1 & IWN_INT_FH_TX) || (r2 & IWN_FH_INT_TX)) {
   2639 		if (sc->sc_flags & IWN_FLAG_USE_ICT)
   2640 			IWN_WRITE(sc, IWN_FH_INT, IWN_FH_INT_TX);
   2641 		wakeup(sc);	/* FH DMA transfer completed. */
   2642 	}
   2643 
   2644 	if (r1 & IWN_INT_ALIVE)
   2645 		wakeup(sc);	/* Firmware is alive. */
   2646 
   2647 	if (r1 & IWN_INT_WAKEUP)
   2648 		iwn_wakeup_intr(sc);
   2649 
   2650 	/* Re-enable interrupts. */
   2651 	if (ifp->if_flags & IFF_UP)
   2652 		IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
   2653 
   2654 	return 1;
   2655 }
   2656 
   2657 /*
   2658  * Update TX scheduler ring when transmitting an 802.11 frame (4965AGN and
   2659  * 5000 adapters use a slightly different format).
   2660  */
   2661 static void
   2662 iwn4965_update_sched(struct iwn_softc *sc, int qid, int idx, uint8_t id,
   2663     uint16_t len)
   2664 {
   2665 	uint16_t *w = &sc->sched[qid * IWN4965_SCHED_COUNT + idx];
   2666 
   2667 	*w = htole16(len + 8);
   2668 	bus_dmamap_sync(sc->sc_dmat, sc->sched_dma.map,
   2669 	    (char *)(void *)w - (char *)(void *)sc->sched_dma.vaddr,
   2670 	    sizeof (uint16_t),
   2671 	    BUS_DMASYNC_PREWRITE);
   2672 	if (idx < IWN_SCHED_WINSZ) {
   2673 		*(w + IWN_TX_RING_COUNT) = *w;
   2674 		bus_dmamap_sync(sc->sc_dmat, sc->sched_dma.map,
   2675 		    (char *)(void *)(w + IWN_TX_RING_COUNT) -
   2676 		    (char *)(void *)sc->sched_dma.vaddr,
   2677 		    sizeof (uint16_t), BUS_DMASYNC_PREWRITE);
   2678 	}
   2679 }
   2680 
   2681 static void
   2682 iwn5000_update_sched(struct iwn_softc *sc, int qid, int idx, uint8_t id,
   2683     uint16_t len)
   2684 {
   2685 	uint16_t *w = &sc->sched[qid * IWN5000_SCHED_COUNT + idx];
   2686 
   2687 	*w = htole16(id << 12 | (len + 8));
   2688 	bus_dmamap_sync(sc->sc_dmat, sc->sched_dma.map,
   2689 	    (char *)(void *)w - (char *)(void *)sc->sched_dma.vaddr,
   2690 	    sizeof (uint16_t), BUS_DMASYNC_PREWRITE);
   2691 	if (idx < IWN_SCHED_WINSZ) {
   2692 		*(w + IWN_TX_RING_COUNT) = *w;
   2693 		bus_dmamap_sync(sc->sc_dmat, sc->sched_dma.map,
   2694 		    (char *)(void *)(w + IWN_TX_RING_COUNT) -
   2695 		    (char *)(void *)sc->sched_dma.vaddr,
   2696 		    sizeof (uint16_t), BUS_DMASYNC_PREWRITE);
   2697 	}
   2698 }
   2699 
   2700 #ifdef notyet
   2701 static void
   2702 iwn5000_reset_sched(struct iwn_softc *sc, int qid, int idx)
   2703 {
   2704 	uint16_t *w = &sc->sched[qid * IWN5000_SCHED_COUNT + idx];
   2705 
   2706 	*w = (*w & htole16(0xf000)) | htole16(1);
   2707 	bus_dmamap_sync(sc->sc_dmat, sc->sched_dma.map,
   2708 	    (char *)(void *)w - (char *)(void *)sc->sched_dma.vaddr,
   2709 	    sizeof (uint16_t), BUS_DMASYNC_PREWRITE);
   2710 	if (idx < IWN_SCHED_WINSZ) {
   2711 		*(w + IWN_TX_RING_COUNT) = *w;
   2712 		bus_dmamap_sync(sc->sc_dmat, sc->sched_dma.map,
   2713 		    (char *)(void *)(w + IWN_TX_RING_COUNT) -
   2714 		    (char *)(void *)sc->sched_dma.vaddr,
   2715 		    sizeof (uint16_t), BUS_DMASYNC_PREWRITE);
   2716 	}
   2717 }
   2718 #endif
   2719 
   2720 static int
   2721 iwn_tx(struct iwn_softc *sc, struct mbuf *m, struct ieee80211_node *ni, int ac)
   2722 {
   2723 	struct ieee80211com *ic = &sc->sc_ic;
   2724 	struct iwn_node *wn = (void *)ni;
   2725 	struct iwn_tx_ring *ring;
   2726 	struct iwn_tx_desc *desc;
   2727 	struct iwn_tx_data *data;
   2728 	struct iwn_tx_cmd *cmd;
   2729 	struct iwn_cmd_data *tx;
   2730 	const struct iwn_rate *rinfo;
   2731 	struct ieee80211_frame *wh;
   2732 	struct ieee80211_key *k = NULL;
   2733 	struct mbuf *m1;
   2734 	uint32_t flags;
   2735 	u_int hdrlen;
   2736 	bus_dma_segment_t *seg;
   2737 	uint8_t tid, ridx, txant, type;
   2738 	int i, totlen, error, pad;
   2739 
   2740 	const struct chanAccParams *cap;
   2741 	int noack;
   2742 	int hdrlen2;
   2743 
   2744 	wh = mtod(m, struct ieee80211_frame *);
   2745 	hdrlen = ieee80211_anyhdrsize(wh);
   2746 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
   2747 
   2748 	hdrlen2 = (ieee80211_has_qos(wh)) ?
   2749 	    sizeof (struct ieee80211_qosframe) :
   2750 	    sizeof (struct ieee80211_frame);
   2751 
   2752 	if (hdrlen != hdrlen2)
   2753 	    aprint_error_dev(sc->sc_dev, "hdrlen error (%d != %d)\n",
   2754 		hdrlen, hdrlen2);
   2755 
   2756 	/* XXX OpenBSD sets a different tid when using QOS */
   2757 	tid = 0;
   2758 	if (ieee80211_has_qos(wh)) {
   2759 		cap = &ic->ic_wme.wme_chanParams;
   2760 		noack = cap->cap_wmeParams[ac].wmep_noackPolicy;
   2761 	}
   2762 	else
   2763 		noack = 0;
   2764 
   2765 	ring = &sc->txq[ac];
   2766 	desc = &ring->desc[ring->cur];
   2767 	data = &ring->data[ring->cur];
   2768 
   2769 	/* Choose a TX rate index. */
   2770 	if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
   2771 	    type != IEEE80211_FC0_TYPE_DATA) {
   2772 		ridx = (ic->ic_curmode == IEEE80211_MODE_11A) ?
   2773 		    IWN_RIDX_OFDM6 : IWN_RIDX_CCK1;
   2774 	} else if (ic->ic_fixed_rate != -1) {
   2775 		ridx = sc->fixed_ridx;
   2776 	} else
   2777 		ridx = wn->ridx[ni->ni_txrate];
   2778 	rinfo = &iwn_rates[ridx];
   2779 
   2780 	/* Encrypt the frame if need be. */
   2781 	/*
   2782 	 * XXX For now, NetBSD swaps the encryption and bpf sections
   2783 	 * in order to match old code and other drivers. Tests with
   2784 	 * tcpdump indicates that the order is irrelevant, however,
   2785 	 * as bpf produces unencrypted data for both ordering choices.
   2786 	 */
   2787 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
   2788 		k = ieee80211_crypto_encap(ic, ni, m);
   2789 		if (k == NULL) {
   2790 			m_freem(m);
   2791 			return ENOBUFS;
   2792 		}
   2793 		/* Packet header may have moved, reset our local pointer. */
   2794 		wh = mtod(m, struct ieee80211_frame *);
   2795 	}
   2796 	totlen = m->m_pkthdr.len;
   2797 
   2798 	if (sc->sc_drvbpf != NULL) {
   2799 		struct iwn_tx_radiotap_header *tap = &sc->sc_txtap;
   2800 
   2801 		tap->wt_flags = 0;
   2802 		tap->wt_chan_freq = htole16(ni->ni_chan->ic_freq);
   2803 		tap->wt_chan_flags = htole16(ni->ni_chan->ic_flags);
   2804 		tap->wt_rate = rinfo->rate;
   2805 		tap->wt_hwqueue = ac;
   2806 		if (wh->i_fc[1] & IEEE80211_FC1_WEP)
   2807 			tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
   2808 
   2809 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m);
   2810 	}
   2811 
   2812 	/* Prepare TX firmware command. */
   2813 	cmd = &ring->cmd[ring->cur];
   2814 	cmd->code = IWN_CMD_TX_DATA;
   2815 	cmd->flags = 0;
   2816 	cmd->qid = ring->qid;
   2817 	cmd->idx = ring->cur;
   2818 
   2819 	tx = (struct iwn_cmd_data *)cmd->data;
   2820 	/* NB: No need to clear tx, all fields are reinitialized here. */
   2821 	tx->scratch = 0;	/* clear "scratch" area */
   2822 
   2823 	flags = 0;
   2824 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
   2825 		/* Unicast frame, check if an ACK is expected. */
   2826 		if (!noack)
   2827 			flags |= IWN_TX_NEED_ACK;
   2828 	}
   2829 
   2830 #ifdef notyet
   2831 	/* XXX NetBSD does not define IEEE80211_FC0_SUBTYPE_BAR */
   2832 	if ((wh->i_fc[0] &
   2833 	    (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
   2834 	    (IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_BAR))
   2835 		flags |= IWN_TX_IMM_BA;		/* Cannot happen yet. */
   2836 #endif
   2837 
   2838 	if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG)
   2839 		flags |= IWN_TX_MORE_FRAG;	/* Cannot happen yet. */
   2840 
   2841 	/* Check if frame must be protected using RTS/CTS or CTS-to-self. */
   2842 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
   2843 		/* NB: Group frames are sent using CCK in 802.11b/g. */
   2844 		if (totlen + IEEE80211_CRC_LEN > ic->ic_rtsthreshold) {
   2845 			flags |= IWN_TX_NEED_RTS;
   2846 		} else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
   2847 		    ridx >= IWN_RIDX_OFDM6) {
   2848 			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
   2849 				flags |= IWN_TX_NEED_CTS;
   2850 			else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
   2851 				flags |= IWN_TX_NEED_RTS;
   2852 		}
   2853 		if (flags & (IWN_TX_NEED_RTS | IWN_TX_NEED_CTS)) {
   2854 			if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
   2855 				/* 5000 autoselects RTS/CTS or CTS-to-self. */
   2856 				flags &= ~(IWN_TX_NEED_RTS | IWN_TX_NEED_CTS);
   2857 				flags |= IWN_TX_NEED_PROTECTION;
   2858 			} else
   2859 				flags |= IWN_TX_FULL_TXOP;
   2860 		}
   2861 	}
   2862 
   2863 	if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
   2864 	    type != IEEE80211_FC0_TYPE_DATA)
   2865 		tx->id = sc->broadcast_id;
   2866 	else
   2867 		tx->id = wn->id;
   2868 
   2869 	if (type == IEEE80211_FC0_TYPE_MGT) {
   2870 		uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
   2871 
   2872 #ifndef IEEE80211_STA_ONLY
   2873 		/* Tell HW to set timestamp in probe responses. */
   2874 		/* XXX NetBSD rev 1.11 added probe requests here but */
   2875 		/* probe requests do not take timestamps (from Bergamini). */
   2876 		if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
   2877 			flags |= IWN_TX_INSERT_TSTAMP;
   2878 #endif
   2879 		/* XXX NetBSD rev 1.11 and 1.20 added AUTH/DAUTH and RTS/CTS */
   2880 		/* changes here. These are not needed (from Bergamini). */
   2881 		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
   2882 		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
   2883 			tx->timeout = htole16(3);
   2884 		else
   2885 			tx->timeout = htole16(2);
   2886 	} else
   2887 		tx->timeout = htole16(0);
   2888 
   2889 	if (hdrlen & 3) {
   2890 		/* First segment length must be a multiple of 4. */
   2891 		flags |= IWN_TX_NEED_PADDING;
   2892 		pad = 4 - (hdrlen & 3);
   2893 	} else
   2894 		pad = 0;
   2895 
   2896 	tx->len = htole16(totlen);
   2897 	tx->tid = tid;
   2898 	tx->rts_ntries = 60;
   2899 	tx->data_ntries = 15;
   2900 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
   2901 	tx->plcp = rinfo->plcp;
   2902 	tx->rflags = rinfo->flags;
   2903 	if (tx->id == sc->broadcast_id) {
   2904 		/* Group or management frame. */
   2905 		tx->linkq = 0;
   2906 		/* XXX Alternate between antenna A and B? */
   2907 		txant = IWN_LSB(sc->txchainmask);
   2908 		tx->rflags |= IWN_RFLAG_ANT(txant);
   2909 	} else {
   2910 		tx->linkq = ni->ni_rates.rs_nrates - ni->ni_txrate - 1;
   2911 		flags |= IWN_TX_LINKQ;	/* enable MRR */
   2912 	}
   2913 	/* Set physical address of "scratch area". */
   2914 	tx->loaddr = htole32(IWN_LOADDR(data->scratch_paddr));
   2915 	tx->hiaddr = IWN_HIADDR(data->scratch_paddr);
   2916 
   2917 	/* Copy 802.11 header in TX command. */
   2918 	/* XXX NetBSD changed this in rev 1.20 */
   2919 	memcpy(((uint8_t *)tx) + sizeof(*tx), wh, hdrlen);
   2920 
   2921 	/* Trim 802.11 header. */
   2922 	m_adj(m, hdrlen);
   2923 	tx->security = 0;
   2924 	tx->flags = htole32(flags);
   2925 
   2926 	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m,
   2927 	    BUS_DMA_NOWAIT | BUS_DMA_WRITE);
   2928 	if (error != 0) {
   2929 		if (error != EFBIG) {
   2930 			aprint_error_dev(sc->sc_dev,
   2931 			    "can't map mbuf (error %d)\n", error);
   2932 			m_freem(m);
   2933 			return error;
   2934 		}
   2935 		/* Too many DMA segments, linearize mbuf. */
   2936 		MGETHDR(m1, M_DONTWAIT, MT_DATA);
   2937 		if (m1 == NULL) {
   2938 			m_freem(m);
   2939 			return ENOBUFS;
   2940 		}
   2941 		if (m->m_pkthdr.len > MHLEN) {
   2942 			MCLGET(m1, M_DONTWAIT);
   2943 			if (!(m1->m_flags & M_EXT)) {
   2944 				m_freem(m);
   2945 				m_freem(m1);
   2946 				return ENOBUFS;
   2947 			}
   2948 		}
   2949 		m_copydata(m, 0, m->m_pkthdr.len, mtod(m1, void *));
   2950 		m1->m_pkthdr.len = m1->m_len = m->m_pkthdr.len;
   2951 		m_freem(m);
   2952 		m = m1;
   2953 
   2954 		error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m,
   2955 		    BUS_DMA_NOWAIT | BUS_DMA_WRITE);
   2956 		if (error != 0) {
   2957 			aprint_error_dev(sc->sc_dev,
   2958 			    "can't map mbuf (error %d)\n", error);
   2959 			m_freem(m);
   2960 			return error;
   2961 		}
   2962 	}
   2963 
   2964 	data->m = m;
   2965 	data->ni = ni;
   2966 
   2967 	DPRINTFN(4, ("sending data: qid=%d idx=%d len=%d nsegs=%d\n",
   2968 	    ring->qid, ring->cur, m->m_pkthdr.len, data->map->dm_nsegs));
   2969 
   2970 	/* Fill TX descriptor. */
   2971 	desc->nsegs = 1 + data->map->dm_nsegs;
   2972 	/* First DMA segment is used by the TX command. */
   2973 	desc->segs[0].addr = htole32(IWN_LOADDR(data->cmd_paddr));
   2974 	desc->segs[0].len  = htole16(IWN_HIADDR(data->cmd_paddr) |
   2975 	    (4 + sizeof (*tx) + hdrlen + pad) << 4);
   2976 	/* Other DMA segments are for data payload. */
   2977 	seg = data->map->dm_segs;
   2978 	for (i = 1; i <= data->map->dm_nsegs; i++) {
   2979 		desc->segs[i].addr = htole32(IWN_LOADDR(seg->ds_addr));
   2980 		desc->segs[i].len  = htole16(IWN_HIADDR(seg->ds_addr) |
   2981 		    seg->ds_len << 4);
   2982 		seg++;
   2983 	}
   2984 
   2985 	bus_dmamap_sync(sc->sc_dmat, data->map, 0, data->map->dm_mapsize,
   2986 	    BUS_DMASYNC_PREWRITE);
   2987 	bus_dmamap_sync(sc->sc_dmat, ring->cmd_dma.map,
   2988 	    (char *)(void *)cmd - (char *)(void *)ring->cmd_dma.vaddr,
   2989 	    sizeof (*cmd), BUS_DMASYNC_PREWRITE);
   2990 	bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map,
   2991 	    (char *)(void *)desc - (char *)(void *)ring->desc_dma.vaddr,
   2992 	    sizeof (*desc), BUS_DMASYNC_PREWRITE);
   2993 
   2994 #ifdef notyet
   2995 	/* Update TX scheduler. */
   2996 	ops->update_sched(sc, ring->qid, ring->cur, tx->id, totlen);
   2997 #endif
   2998 
   2999 	/* Kick TX ring. */
   3000 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
   3001 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
   3002 
   3003 	/* Mark TX ring as full if we reach a certain threshold. */
   3004 	if (++ring->queued > IWN_TX_RING_HIMARK)
   3005 		sc->qfullmsk |= 1 << ring->qid;
   3006 
   3007 	return 0;
   3008 }
   3009 
   3010 static void
   3011 iwn_start(struct ifnet *ifp)
   3012 {
   3013 	struct iwn_softc *sc = ifp->if_softc;
   3014 	struct ieee80211com *ic = &sc->sc_ic;
   3015 	struct ieee80211_node *ni;
   3016 	struct ether_header *eh;
   3017 	struct mbuf *m;
   3018 	int ac;
   3019 
   3020 	if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
   3021 		return;
   3022 
   3023 	for (;;) {
   3024 		if (sc->qfullmsk != 0) {
   3025 			ifp->if_flags |= IFF_OACTIVE;
   3026 			break;
   3027 		}
   3028 		/* Send pending management frames first. */
   3029 		IF_DEQUEUE(&ic->ic_mgtq, m);
   3030 		if (m != NULL) {
   3031 			ni = (void *)m->m_pkthdr.rcvif;
   3032 			ac = 0;
   3033 			goto sendit;
   3034 		}
   3035 		if (ic->ic_state != IEEE80211_S_RUN)
   3036 			break;
   3037 
   3038 		/* Encapsulate and send data frames. */
   3039 		IFQ_DEQUEUE(&ifp->if_snd, m);
   3040 		if (m == NULL)
   3041 			break;
   3042 		if (m->m_len < sizeof (*eh) &&
   3043 		    (m = m_pullup(m, sizeof (*eh))) == NULL) {
   3044 			ifp->if_oerrors++;
   3045 			continue;
   3046 		}
   3047 		eh = mtod(m, struct ether_header *);
   3048 		ni = ieee80211_find_txnode(ic, eh->ether_dhost);
   3049 		if (ni == NULL) {
   3050 			m_freem(m);
   3051 			ifp->if_oerrors++;
   3052 			continue;
   3053 		}
   3054 		/* classify mbuf so we can find which tx ring to use */
   3055 		if (ieee80211_classify(ic, m, ni) != 0) {
   3056 			m_freem(m);
   3057 			ieee80211_free_node(ni);
   3058 			ifp->if_oerrors++;
   3059 			continue;
   3060 		}
   3061 
   3062 		/* No QoS encapsulation for EAPOL frames. */
   3063 		ac = (eh->ether_type != htons(ETHERTYPE_PAE)) ?
   3064 		    M_WME_GETAC(m) : WME_AC_BE;
   3065 
   3066 		bpf_mtap(ifp, m);
   3067 
   3068 		if ((m = ieee80211_encap(ic, m, ni)) == NULL) {
   3069 			ieee80211_free_node(ni);
   3070 			ifp->if_oerrors++;
   3071 			continue;
   3072 		}
   3073 sendit:
   3074 		bpf_mtap3(ic->ic_rawbpf, m);
   3075 
   3076 		if (iwn_tx(sc, m, ni, ac) != 0) {
   3077 			ieee80211_free_node(ni);
   3078 			ifp->if_oerrors++;
   3079 			continue;
   3080 		}
   3081 
   3082 		sc->sc_tx_timer = 5;
   3083 		ifp->if_timer = 1;
   3084 	}
   3085 }
   3086 
   3087 static void
   3088 iwn_watchdog(struct ifnet *ifp)
   3089 {
   3090 	struct iwn_softc *sc = ifp->if_softc;
   3091 
   3092 	ifp->if_timer = 0;
   3093 
   3094 	if (sc->sc_tx_timer > 0) {
   3095 		if (--sc->sc_tx_timer == 0) {
   3096 			aprint_error_dev(sc->sc_dev,
   3097 			    "device timeout\n");
   3098 			ifp->if_flags &= ~IFF_UP;
   3099 			iwn_stop(ifp, 1);
   3100 			ifp->if_oerrors++;
   3101 			return;
   3102 		}
   3103 		ifp->if_timer = 1;
   3104 	}
   3105 
   3106 	ieee80211_watchdog(&sc->sc_ic);
   3107 }
   3108 
   3109 static int
   3110 iwn_ioctl(struct ifnet *ifp, u_long cmd, void *data)
   3111 {
   3112 	struct iwn_softc *sc = ifp->if_softc;
   3113 	struct ieee80211com *ic = &sc->sc_ic;
   3114 	struct ifaddr *ifa;
   3115 	const struct sockaddr *sa;
   3116 	int s, error = 0;
   3117 
   3118 	s = splnet();
   3119 
   3120 	switch (cmd) {
   3121 	case SIOCSIFADDR:
   3122 		ifa = (struct ifaddr *)data;
   3123 		ifp->if_flags |= IFF_UP;
   3124 #ifdef INET
   3125 		if (ifa->ifa_addr->sa_family == AF_INET)
   3126 			arp_ifinit(&ic->ic_ac, ifa);
   3127 #endif
   3128 		/* FALLTHROUGH */
   3129 	case SIOCSIFFLAGS:
   3130 		/* XXX Added as it is in every NetBSD driver */
   3131 		if ((error = ifioctl_common(ifp, cmd, data)) != 0)
   3132 			break;
   3133 		if (ifp->if_flags & IFF_UP) {
   3134 			if (!(ifp->if_flags & IFF_RUNNING))
   3135 				error = iwn_init(ifp);
   3136 		} else {
   3137 			if (ifp->if_flags & IFF_RUNNING)
   3138 				iwn_stop(ifp, 1);
   3139 		}
   3140 		break;
   3141 
   3142 	case SIOCADDMULTI:
   3143 	case SIOCDELMULTI:
   3144 		sa = ifreq_getaddr(SIOCADDMULTI, (struct ifreq *)data);
   3145 		error = (cmd == SIOCADDMULTI) ?
   3146 		    ether_addmulti(sa, &sc->sc_ec) :
   3147 		    ether_delmulti(sa, &sc->sc_ec);
   3148 
   3149 		if (error == ENETRESET)
   3150 			error = 0;
   3151 		break;
   3152 
   3153 	default:
   3154 		error = ieee80211_ioctl(ic, cmd, data);
   3155 	}
   3156 
   3157 	if (error == ENETRESET) {
   3158 		error = 0;
   3159 		if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
   3160 		    (IFF_UP | IFF_RUNNING)) {
   3161 			iwn_stop(ifp, 0);
   3162 			error = iwn_init(ifp);
   3163 		}
   3164 	}
   3165 
   3166 	splx(s);
   3167 	return error;
   3168 }
   3169 
   3170 /*
   3171  * Send a command to the firmware.
   3172  */
   3173 static int
   3174 iwn_cmd(struct iwn_softc *sc, int code, const void *buf, int size, int async)
   3175 {
   3176 	struct iwn_tx_ring *ring = &sc->txq[4];
   3177 	struct iwn_tx_desc *desc;
   3178 	struct iwn_tx_data *data;
   3179 	struct iwn_tx_cmd *cmd;
   3180 	struct mbuf *m;
   3181 	bus_addr_t paddr;
   3182 	int totlen, error;
   3183 
   3184 	desc = &ring->desc[ring->cur];
   3185 	data = &ring->data[ring->cur];
   3186 	totlen = 4 + size;
   3187 
   3188 	if (size > sizeof cmd->data) {
   3189 		/* Command is too large to fit in a descriptor. */
   3190 		if (totlen > MCLBYTES)
   3191 			return EINVAL;
   3192 		MGETHDR(m, M_DONTWAIT, MT_DATA);
   3193 		if (m == NULL)
   3194 			return ENOMEM;
   3195 		if (totlen > MHLEN) {
   3196 			MCLGET(m, M_DONTWAIT);
   3197 			if (!(m->m_flags & M_EXT)) {
   3198 				m_freem(m);
   3199 				return ENOMEM;
   3200 			}
   3201 		}
   3202 		cmd = mtod(m, struct iwn_tx_cmd *);
   3203 		error = bus_dmamap_load(sc->sc_dmat, data->map, cmd, totlen,
   3204 		    NULL, BUS_DMA_NOWAIT | BUS_DMA_WRITE);
   3205 		if (error != 0) {
   3206 			m_freem(m);
   3207 			return error;
   3208 		}
   3209 		data->m = m;
   3210 		paddr = data->map->dm_segs[0].ds_addr;
   3211 	} else {
   3212 		cmd = &ring->cmd[ring->cur];
   3213 		paddr = data->cmd_paddr;
   3214 	}
   3215 
   3216 	cmd->code = code;
   3217 	cmd->flags = 0;
   3218 	cmd->qid = ring->qid;
   3219 	cmd->idx = ring->cur;
   3220 	memcpy(cmd->data, buf, size);
   3221 
   3222 	desc->nsegs = 1;
   3223 	desc->segs[0].addr = htole32(IWN_LOADDR(paddr));
   3224 	desc->segs[0].len  = htole16(IWN_HIADDR(paddr) | totlen << 4);
   3225 
   3226 	if (size > sizeof cmd->data) {
   3227 		bus_dmamap_sync(sc->sc_dmat, data->map, 0, totlen,
   3228 		    BUS_DMASYNC_PREWRITE);
   3229 	} else {
   3230 		bus_dmamap_sync(sc->sc_dmat, ring->cmd_dma.map,
   3231 		    (char *)(void *)cmd - (char *)(void *)ring->cmd_dma.vaddr,
   3232 		    totlen, BUS_DMASYNC_PREWRITE);
   3233 	}
   3234 	bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map,
   3235 	    (char *)(void *)desc - (char *)(void *)ring->desc_dma.vaddr,
   3236 	    sizeof (*desc), BUS_DMASYNC_PREWRITE);
   3237 
   3238 #ifdef notyet
   3239 	/* Update TX scheduler. */
   3240 	ops->update_sched(sc, ring->qid, ring->cur, 0, 0);
   3241 #endif
   3242 	DPRINTFN(4, ("iwn_cmd %d size=%d %s\n", code, size, async ? " (async)" : ""));
   3243 
   3244 	/* Kick command ring. */
   3245 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
   3246 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
   3247 
   3248 	return async ? 0 : tsleep(desc, PCATCH, "iwncmd", hz);
   3249 }
   3250 
   3251 static int
   3252 iwn4965_add_node(struct iwn_softc *sc, struct iwn_node_info *node, int async)
   3253 {
   3254 	struct iwn4965_node_info hnode;
   3255 	char *src, *dst;
   3256 
   3257 	/*
   3258 	 * We use the node structure for 5000 Series internally (it is
   3259 	 * a superset of the one for 4965AGN). We thus copy the common
   3260 	 * fields before sending the command.
   3261 	 */
   3262 	src = (char *)node;
   3263 	dst = (char *)&hnode;
   3264 	memcpy(dst, src, 48);
   3265 	/* Skip TSC, RX MIC and TX MIC fields from ``src''. */
   3266 	memcpy(dst + 48, src + 72, 20);
   3267 	return iwn_cmd(sc, IWN_CMD_ADD_NODE, &hnode, sizeof hnode, async);
   3268 }
   3269 
   3270 static int
   3271 iwn5000_add_node(struct iwn_softc *sc, struct iwn_node_info *node, int async)
   3272 {
   3273 	/* Direct mapping. */
   3274 	return iwn_cmd(sc, IWN_CMD_ADD_NODE, node, sizeof (*node), async);
   3275 }
   3276 
   3277 static int
   3278 iwn_set_link_quality(struct iwn_softc *sc, struct ieee80211_node *ni)
   3279 {
   3280 	struct iwn_node *wn = (void *)ni;
   3281 	struct ieee80211_rateset *rs = &ni->ni_rates;
   3282 	struct iwn_cmd_link_quality linkq;
   3283 	const struct iwn_rate *rinfo;
   3284 	uint8_t txant;
   3285 	int i, txrate;
   3286 
   3287 	/* Use the first valid TX antenna. */
   3288 	txant = IWN_LSB(sc->txchainmask);
   3289 
   3290 	memset(&linkq, 0, sizeof linkq);
   3291 	linkq.id = wn->id;
   3292 	linkq.antmsk_1stream = txant;
   3293 	linkq.antmsk_2stream = IWN_ANT_AB;
   3294 	linkq.ampdu_max = 31;
   3295 	linkq.ampdu_threshold = 3;
   3296 	linkq.ampdu_limit = htole16(4000);	/* 4ms */
   3297 
   3298 	/* Start at highest available bit-rate. */
   3299 	txrate = rs->rs_nrates - 1;
   3300 	for (i = 0; i < IWN_MAX_TX_RETRIES; i++) {
   3301 		rinfo = &iwn_rates[wn->ridx[txrate]];
   3302 		linkq.retry[i].plcp = rinfo->plcp;
   3303 		linkq.retry[i].rflags = rinfo->flags;
   3304 		linkq.retry[i].rflags |= IWN_RFLAG_ANT(txant);
   3305 		/* Next retry at immediate lower bit-rate. */
   3306 		if (txrate > 0)
   3307 			txrate--;
   3308 	}
   3309 	return iwn_cmd(sc, IWN_CMD_LINK_QUALITY, &linkq, sizeof linkq, 1);
   3310 }
   3311 
   3312 /*
   3313  * Broadcast node is used to send group-addressed and management frames.
   3314  */
   3315 static int
   3316 iwn_add_broadcast_node(struct iwn_softc *sc, int async)
   3317 {
   3318 	struct iwn_ops *ops = &sc->ops;
   3319 	struct iwn_node_info node;
   3320 	struct iwn_cmd_link_quality linkq;
   3321 	const struct iwn_rate *rinfo;
   3322 	uint8_t txant;
   3323 	int i, error;
   3324 
   3325 	memset(&node, 0, sizeof node);
   3326 	IEEE80211_ADDR_COPY(node.macaddr, etherbroadcastaddr);
   3327 	node.id = sc->broadcast_id;
   3328 	DPRINTF(("adding broadcast node\n"));
   3329 	if ((error = ops->add_node(sc, &node, async)) != 0)
   3330 		return error;
   3331 
   3332 	/* Use the first valid TX antenna. */
   3333 	txant = IWN_LSB(sc->txchainmask);
   3334 
   3335 	memset(&linkq, 0, sizeof linkq);
   3336 	linkq.id = sc->broadcast_id;
   3337 	linkq.antmsk_1stream = txant;
   3338 	linkq.antmsk_2stream = IWN_ANT_AB;
   3339 	linkq.ampdu_max = 64;
   3340 	linkq.ampdu_threshold = 3;
   3341 	linkq.ampdu_limit = htole16(4000);	/* 4ms */
   3342 
   3343 	/* Use lowest mandatory bit-rate. */
   3344 	rinfo = (sc->sc_ic.ic_curmode != IEEE80211_MODE_11A) ?
   3345 	    &iwn_rates[IWN_RIDX_CCK1] : &iwn_rates[IWN_RIDX_OFDM6];
   3346 	linkq.retry[0].plcp = rinfo->plcp;
   3347 	linkq.retry[0].rflags = rinfo->flags;
   3348 	linkq.retry[0].rflags |= IWN_RFLAG_ANT(txant);
   3349 	/* Use same bit-rate for all TX retries. */
   3350 	for (i = 1; i < IWN_MAX_TX_RETRIES; i++) {
   3351 		linkq.retry[i].plcp = linkq.retry[0].plcp;
   3352 		linkq.retry[i].rflags = linkq.retry[0].rflags;
   3353 	}
   3354 	return iwn_cmd(sc, IWN_CMD_LINK_QUALITY, &linkq, sizeof linkq, async);
   3355 }
   3356 
   3357 static void
   3358 iwn_set_led(struct iwn_softc *sc, uint8_t which, uint8_t off, uint8_t on)
   3359 {
   3360 	struct iwn_cmd_led led;
   3361 
   3362 	/* Clear microcode LED ownership. */
   3363 	IWN_CLRBITS(sc, IWN_LED, IWN_LED_BSM_CTRL);
   3364 
   3365 	led.which = which;
   3366 	led.unit = htole32(10000);	/* on/off in unit of 100ms */
   3367 	led.off = off;
   3368 	led.on = on;
   3369 	(void)iwn_cmd(sc, IWN_CMD_SET_LED, &led, sizeof led, 1);
   3370 }
   3371 
   3372 /*
   3373  * Set the critical temperature at which the firmware will stop the radio
   3374  * and notify us.
   3375  */
   3376 static int
   3377 iwn_set_critical_temp(struct iwn_softc *sc)
   3378 {
   3379 	struct iwn_critical_temp crit;
   3380 	int32_t temp;
   3381 
   3382 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CTEMP_STOP_RF);
   3383 
   3384 	if (sc->hw_type == IWN_HW_REV_TYPE_5150)
   3385 		temp = (IWN_CTOK(110) - sc->temp_off) * -5;
   3386 	else if (sc->hw_type == IWN_HW_REV_TYPE_4965)
   3387 		temp = IWN_CTOK(110);
   3388 	else
   3389 		temp = 110;
   3390 	memset(&crit, 0, sizeof crit);
   3391 	crit.tempR = htole32(temp);
   3392 	DPRINTF(("setting critical temperature to %d\n", temp));
   3393 	return iwn_cmd(sc, IWN_CMD_SET_CRITICAL_TEMP, &crit, sizeof crit, 0);
   3394 }
   3395 
   3396 static int
   3397 iwn_set_timing(struct iwn_softc *sc, struct ieee80211_node *ni)
   3398 {
   3399 	struct iwn_cmd_timing cmd;
   3400 	uint64_t val, mod;
   3401 
   3402 	memset(&cmd, 0, sizeof cmd);
   3403 	memcpy(&cmd.tstamp, ni->ni_tstamp.data, sizeof (uint64_t));
   3404 	cmd.bintval = htole16(ni->ni_intval);
   3405 	cmd.lintval = htole16(10);
   3406 
   3407 	/* Compute remaining time until next beacon. */
   3408 	val = (uint64_t)ni->ni_intval * 1024;	/* msecs -> usecs */
   3409 	mod = le64toh(cmd.tstamp) % val;
   3410 	cmd.binitval = htole32((uint32_t)(val - mod));
   3411 
   3412 	DPRINTF(("timing bintval=%u, tstamp=%" PRIu64 ", init=%" PRIu32 "\n",
   3413 	    ni->ni_intval, le64toh(cmd.tstamp), (uint32_t)(val - mod)));
   3414 
   3415 	return iwn_cmd(sc, IWN_CMD_TIMING, &cmd, sizeof cmd, 1);
   3416 }
   3417 
   3418 static void
   3419 iwn4965_power_calibration(struct iwn_softc *sc, int temp)
   3420 {
   3421 	/* Adjust TX power if need be (delta >= 3 degC). */
   3422 	DPRINTF(("temperature %d->%d\n", sc->temp, temp));
   3423 	if (abs(temp - sc->temp) >= 3) {
   3424 		/* Record temperature of last calibration. */
   3425 		sc->temp = temp;
   3426 		(void)iwn4965_set_txpower(sc, 1);
   3427 	}
   3428 }
   3429 
   3430 /*
   3431  * Set TX power for current channel (each rate has its own power settings).
   3432  * This function takes into account the regulatory information from EEPROM,
   3433  * the current temperature and the current voltage.
   3434  */
   3435 static int
   3436 iwn4965_set_txpower(struct iwn_softc *sc, int async)
   3437 {
   3438 /* Fixed-point arithmetic division using a n-bit fractional part. */
   3439 #define fdivround(a, b, n)	\
   3440 	((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
   3441 /* Linear interpolation. */
   3442 #define interpolate(x, x1, y1, x2, y2, n)	\
   3443 	((y1) + fdivround(((int)(x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
   3444 
   3445 	static const int tdiv[IWN_NATTEN_GROUPS] = { 9, 8, 8, 8, 6 };
   3446 	struct ieee80211com *ic = &sc->sc_ic;
   3447 	struct iwn_ucode_info *uc = &sc->ucode_info;
   3448 	struct ieee80211_channel *ch;
   3449 	struct iwn4965_cmd_txpower cmd;
   3450 	struct iwn4965_eeprom_chan_samples *chans;
   3451 	const uint8_t *rf_gain, *dsp_gain;
   3452 	int32_t vdiff, tdiff;
   3453 	int i, c, grp, maxpwr;
   3454 	uint8_t chan;
   3455 
   3456 	/* Retrieve current channel from last RXON. */
   3457 	chan = sc->rxon.chan;
   3458 	DPRINTF(("setting TX power for channel %d\n", chan));
   3459 	ch = &ic->ic_channels[chan];
   3460 
   3461 	memset(&cmd, 0, sizeof cmd);
   3462 	cmd.band = IEEE80211_IS_CHAN_5GHZ(ch) ? 0 : 1;
   3463 	cmd.chan = chan;
   3464 
   3465 	if (IEEE80211_IS_CHAN_5GHZ(ch)) {
   3466 		maxpwr   = sc->maxpwr5GHz;
   3467 		rf_gain  = iwn4965_rf_gain_5ghz;
   3468 		dsp_gain = iwn4965_dsp_gain_5ghz;
   3469 	} else {
   3470 		maxpwr   = sc->maxpwr2GHz;
   3471 		rf_gain  = iwn4965_rf_gain_2ghz;
   3472 		dsp_gain = iwn4965_dsp_gain_2ghz;
   3473 	}
   3474 
   3475 	/* Compute voltage compensation. */
   3476 	vdiff = ((int32_t)le32toh(uc->volt) - sc->eeprom_voltage) / 7;
   3477 	if (vdiff > 0)
   3478 		vdiff *= 2;
   3479 	if (abs(vdiff) > 2)
   3480 		vdiff = 0;
   3481 	DPRINTF(("voltage compensation=%d (UCODE=%d, EEPROM=%d)\n",
   3482 	    vdiff, le32toh(uc->volt), sc->eeprom_voltage));
   3483 
   3484 	/* Get channel attenuation group. */
   3485 	if (chan <= 20)		/* 1-20 */
   3486 		grp = 4;
   3487 	else if (chan <= 43)	/* 34-43 */
   3488 		grp = 0;
   3489 	else if (chan <= 70)	/* 44-70 */
   3490 		grp = 1;
   3491 	else if (chan <= 124)	/* 71-124 */
   3492 		grp = 2;
   3493 	else			/* 125-200 */
   3494 		grp = 3;
   3495 	DPRINTF(("chan %d, attenuation group=%d\n", chan, grp));
   3496 
   3497 	/* Get channel sub-band. */
   3498 	for (i = 0; i < IWN_NBANDS; i++)
   3499 		if (sc->bands[i].lo != 0 &&
   3500 		    sc->bands[i].lo <= chan && chan <= sc->bands[i].hi)
   3501 			break;
   3502 	if (i == IWN_NBANDS)	/* Can't happen in real-life. */
   3503 		return EINVAL;
   3504 	chans = sc->bands[i].chans;
   3505 	DPRINTF(("chan %d sub-band=%d\n", chan, i));
   3506 
   3507 	for (c = 0; c < 2; c++) {
   3508 		uint8_t power, gain, temp;
   3509 		int maxchpwr, pwr, ridx, idx;
   3510 
   3511 		power = interpolate(chan,
   3512 		    chans[0].num, chans[0].samples[c][1].power,
   3513 		    chans[1].num, chans[1].samples[c][1].power, 1);
   3514 		gain  = interpolate(chan,
   3515 		    chans[0].num, chans[0].samples[c][1].gain,
   3516 		    chans[1].num, chans[1].samples[c][1].gain, 1);
   3517 		temp  = interpolate(chan,
   3518 		    chans[0].num, chans[0].samples[c][1].temp,
   3519 		    chans[1].num, chans[1].samples[c][1].temp, 1);
   3520 		DPRINTF(("TX chain %d: power=%d gain=%d temp=%d\n",
   3521 		    c, power, gain, temp));
   3522 
   3523 		/* Compute temperature compensation. */
   3524 		tdiff = ((sc->temp - temp) * 2) / tdiv[grp];
   3525 		DPRINTF(("temperature compensation=%d (current=%d, "
   3526 		    "EEPROM=%d)\n", tdiff, sc->temp, temp));
   3527 
   3528 		for (ridx = 0; ridx <= IWN_RIDX_MAX; ridx++) {
   3529 			/* Convert dBm to half-dBm. */
   3530 			maxchpwr = sc->maxpwr[chan] * 2;
   3531 			if ((ridx / 8) & 1)
   3532 				maxchpwr -= 6;	/* MIMO 2T: -3dB */
   3533 
   3534 			pwr = maxpwr;
   3535 
   3536 			/* Adjust TX power based on rate. */
   3537 			if ((ridx % 8) == 5)
   3538 				pwr -= 15;	/* OFDM48: -7.5dB */
   3539 			else if ((ridx % 8) == 6)
   3540 				pwr -= 17;	/* OFDM54: -8.5dB */
   3541 			else if ((ridx % 8) == 7)
   3542 				pwr -= 20;	/* OFDM60: -10dB */
   3543 			else
   3544 				pwr -= 10;	/* Others: -5dB */
   3545 
   3546 			/* Do not exceed channel max TX power. */
   3547 			if (pwr > maxchpwr)
   3548 				pwr = maxchpwr;
   3549 
   3550 			idx = gain - (pwr - power) - tdiff - vdiff;
   3551 			if ((ridx / 8) & 1)	/* MIMO */
   3552 				idx += (int32_t)le32toh(uc->atten[grp][c]);
   3553 
   3554 			if (cmd.band == 0)
   3555 				idx += 9;	/* 5GHz */
   3556 			if (ridx == IWN_RIDX_MAX)
   3557 				idx += 5;	/* CCK */
   3558 
   3559 			/* Make sure idx stays in a valid range. */
   3560 			if (idx < 0)
   3561 				idx = 0;
   3562 			else if (idx > IWN4965_MAX_PWR_INDEX)
   3563 				idx = IWN4965_MAX_PWR_INDEX;
   3564 
   3565 			DPRINTF(("TX chain %d, rate idx %d: power=%d\n",
   3566 			    c, ridx, idx));
   3567 			cmd.power[ridx].rf_gain[c] = rf_gain[idx];
   3568 			cmd.power[ridx].dsp_gain[c] = dsp_gain[idx];
   3569 		}
   3570 	}
   3571 
   3572 	DPRINTF(("setting TX power for chan %d\n", chan));
   3573 	return iwn_cmd(sc, IWN_CMD_TXPOWER, &cmd, sizeof cmd, async);
   3574 
   3575 #undef interpolate
   3576 #undef fdivround
   3577 }
   3578 
   3579 static int
   3580 iwn5000_set_txpower(struct iwn_softc *sc, int async)
   3581 {
   3582 	struct iwn5000_cmd_txpower cmd;
   3583 
   3584 	/*
   3585 	 * TX power calibration is handled automatically by the firmware
   3586 	 * for 5000 Series.
   3587 	 */
   3588 	memset(&cmd, 0, sizeof cmd);
   3589 	cmd.global_limit = 2 * IWN5000_TXPOWER_MAX_DBM;	/* 16 dBm */
   3590 	cmd.flags = IWN5000_TXPOWER_NO_CLOSED;
   3591 	cmd.srv_limit = IWN5000_TXPOWER_AUTO;
   3592 	DPRINTF(("setting TX power\n"));
   3593 	return iwn_cmd(sc, IWN_CMD_TXPOWER_DBM, &cmd, sizeof cmd, async);
   3594 }
   3595 
   3596 /*
   3597  * Retrieve the maximum RSSI (in dBm) among receivers.
   3598  */
   3599 static int
   3600 iwn4965_get_rssi(const struct iwn_rx_stat *stat)
   3601 {
   3602 	const struct iwn4965_rx_phystat *phy = (const void *)stat->phybuf;
   3603 	uint8_t mask, agc;
   3604 	int rssi;
   3605 
   3606 	mask = (le16toh(phy->antenna) >> 4) & IWN_ANT_ABC;
   3607 	agc  = (le16toh(phy->agc) >> 7) & 0x7f;
   3608 
   3609 	rssi = 0;
   3610 	if (mask & IWN_ANT_A)
   3611 		rssi = MAX(rssi, phy->rssi[0]);
   3612 	if (mask & IWN_ANT_B)
   3613 		rssi = MAX(rssi, phy->rssi[2]);
   3614 	if (mask & IWN_ANT_C)
   3615 		rssi = MAX(rssi, phy->rssi[4]);
   3616 
   3617 	return rssi - agc - IWN_RSSI_TO_DBM;
   3618 }
   3619 
   3620 static int
   3621 iwn5000_get_rssi(const struct iwn_rx_stat *stat)
   3622 {
   3623 	const struct iwn5000_rx_phystat *phy = (const void *)stat->phybuf;
   3624 	uint8_t agc;
   3625 	int rssi;
   3626 
   3627 	agc = (le32toh(phy->agc) >> 9) & 0x7f;
   3628 
   3629 	rssi = MAX(le16toh(phy->rssi[0]) & 0xff,
   3630 		   le16toh(phy->rssi[1]) & 0xff);
   3631 	rssi = MAX(le16toh(phy->rssi[2]) & 0xff, rssi);
   3632 
   3633 	return rssi - agc - IWN_RSSI_TO_DBM;
   3634 }
   3635 
   3636 /*
   3637  * Retrieve the average noise (in dBm) among receivers.
   3638  */
   3639 static int
   3640 iwn_get_noise(const struct iwn_rx_general_stats *stats)
   3641 {
   3642 	int i, total, nbant, noise;
   3643 
   3644 	total = nbant = 0;
   3645 	for (i = 0; i < 3; i++) {
   3646 		if ((noise = le32toh(stats->noise[i]) & 0xff) == 0)
   3647 			continue;
   3648 		total += noise;
   3649 		nbant++;
   3650 	}
   3651 	/* There should be at least one antenna but check anyway. */
   3652 	return (nbant == 0) ? -127 : (total / nbant) - 107;
   3653 }
   3654 
   3655 /*
   3656  * Compute temperature (in degC) from last received statistics.
   3657  */
   3658 static int
   3659 iwn4965_get_temperature(struct iwn_softc *sc)
   3660 {
   3661 	struct iwn_ucode_info *uc = &sc->ucode_info;
   3662 	int32_t r1, r2, r3, r4, temp;
   3663 
   3664 	r1 = le32toh(uc->temp[0].chan20MHz);
   3665 	r2 = le32toh(uc->temp[1].chan20MHz);
   3666 	r3 = le32toh(uc->temp[2].chan20MHz);
   3667 	r4 = le32toh(sc->rawtemp);
   3668 
   3669 	if (r1 == r3)	/* Prevents division by 0 (should not happen). */
   3670 		return 0;
   3671 
   3672 	/* Sign-extend 23-bit R4 value to 32-bit. */
   3673 	r4 = ((r4 & 0xffffff) ^ 0x800000) - 0x800000;
   3674 	/* Compute temperature in Kelvin. */
   3675 	temp = (259 * (r4 - r2)) / (r3 - r1);
   3676 	temp = (temp * 97) / 100 + 8;
   3677 
   3678 	DPRINTF(("temperature %dK/%dC\n", temp, IWN_KTOC(temp)));
   3679 	return IWN_KTOC(temp);
   3680 }
   3681 
   3682 static int
   3683 iwn5000_get_temperature(struct iwn_softc *sc)
   3684 {
   3685 	int32_t temp;
   3686 
   3687 	/*
   3688 	 * Temperature is not used by the driver for 5000 Series because
   3689 	 * TX power calibration is handled by firmware.  We export it to
   3690 	 * users through the sensor framework though.
   3691 	 */
   3692 	temp = le32toh(sc->rawtemp);
   3693 	if (sc->hw_type == IWN_HW_REV_TYPE_5150) {
   3694 		temp = (temp / -5) + sc->temp_off;
   3695 		temp = IWN_KTOC(temp);
   3696 	}
   3697 	return temp;
   3698 }
   3699 
   3700 /*
   3701  * Initialize sensitivity calibration state machine.
   3702  */
   3703 static int
   3704 iwn_init_sensitivity(struct iwn_softc *sc)
   3705 {
   3706 	struct iwn_ops *ops = &sc->ops;
   3707 	struct iwn_calib_state *calib = &sc->calib;
   3708 	uint32_t flags;
   3709 	int error;
   3710 
   3711 	/* Reset calibration state machine. */
   3712 	memset(calib, 0, sizeof (*calib));
   3713 	calib->state = IWN_CALIB_STATE_INIT;
   3714 	calib->cck_state = IWN_CCK_STATE_HIFA;
   3715 	/* Set initial correlation values. */
   3716 	calib->ofdm_x1     = sc->limits->min_ofdm_x1;
   3717 	calib->ofdm_mrc_x1 = sc->limits->min_ofdm_mrc_x1;
   3718 	calib->ofdm_x4     = sc->limits->min_ofdm_x4;
   3719 	calib->ofdm_mrc_x4 = sc->limits->min_ofdm_mrc_x4;
   3720 	calib->cck_x4      = 125;
   3721 	calib->cck_mrc_x4  = sc->limits->min_cck_mrc_x4;
   3722 	calib->energy_cck  = sc->limits->energy_cck;
   3723 
   3724 	/* Write initial sensitivity. */
   3725 	if ((error = iwn_send_sensitivity(sc)) != 0)
   3726 		return error;
   3727 
   3728 	/* Write initial gains. */
   3729 	if ((error = ops->init_gains(sc)) != 0)
   3730 		return error;
   3731 
   3732 	/* Request statistics at each beacon interval. */
   3733 	flags = 0;
   3734 	DPRINTF(("sending request for statistics\n"));
   3735 	return iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags, sizeof flags, 1);
   3736 }
   3737 
   3738 /*
   3739  * Collect noise and RSSI statistics for the first 20 beacons received
   3740  * after association and use them to determine connected antennas and
   3741  * to set differential gains.
   3742  */
   3743 static void
   3744 iwn_collect_noise(struct iwn_softc *sc,
   3745     const struct iwn_rx_general_stats *stats)
   3746 {
   3747 	struct iwn_ops *ops = &sc->ops;
   3748 	struct iwn_calib_state *calib = &sc->calib;
   3749 	uint32_t val;
   3750 	int i;
   3751 
   3752 	/* Accumulate RSSI and noise for all 3 antennas. */
   3753 	for (i = 0; i < 3; i++) {
   3754 		calib->rssi[i] += le32toh(stats->rssi[i]) & 0xff;
   3755 		calib->noise[i] += le32toh(stats->noise[i]) & 0xff;
   3756 	}
   3757 	/* NB: We update differential gains only once after 20 beacons. */
   3758 	if (++calib->nbeacons < 20)
   3759 		return;
   3760 
   3761 	/* Determine highest average RSSI. */
   3762 	val = MAX(calib->rssi[0], calib->rssi[1]);
   3763 	val = MAX(calib->rssi[2], val);
   3764 
   3765 	/* Determine which antennas are connected. */
   3766 	sc->chainmask = sc->rxchainmask;
   3767 	for (i = 0; i < 3; i++)
   3768 		if (val - calib->rssi[i] > 15 * 20)
   3769 			sc->chainmask &= ~(1 << i);
   3770 	DPRINTF(("RX chains mask: theoretical=0x%x, actual=0x%x\n",
   3771 	    sc->rxchainmask, sc->chainmask));
   3772 
   3773 	/* If none of the TX antennas are connected, keep at least one. */
   3774 	if ((sc->chainmask & sc->txchainmask) == 0)
   3775 		sc->chainmask |= IWN_LSB(sc->txchainmask);
   3776 
   3777 	(void)ops->set_gains(sc);
   3778 	calib->state = IWN_CALIB_STATE_RUN;
   3779 
   3780 #ifdef notyet
   3781 	/* XXX Disable RX chains with no antennas connected. */
   3782 	sc->rxon.rxchain = htole16(IWN_RXCHAIN_SEL(sc->chainmask));
   3783 	(void)iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, sc->rxonsz, 1);
   3784 #endif
   3785 
   3786 	/* Enable power-saving mode if requested by user. */
   3787 	if (sc->sc_ic.ic_flags & IEEE80211_F_PMGTON)
   3788 		(void)iwn_set_pslevel(sc, 0, 3, 1);
   3789 }
   3790 
   3791 static int
   3792 iwn4965_init_gains(struct iwn_softc *sc)
   3793 {
   3794 	struct iwn_phy_calib_gain cmd;
   3795 
   3796 	memset(&cmd, 0, sizeof cmd);
   3797 	cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN;
   3798 	/* Differential gains initially set to 0 for all 3 antennas. */
   3799 	DPRINTF(("setting initial differential gains\n"));
   3800 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
   3801 }
   3802 
   3803 static int
   3804 iwn5000_init_gains(struct iwn_softc *sc)
   3805 {
   3806 	struct iwn_phy_calib cmd;
   3807 
   3808 	memset(&cmd, 0, sizeof cmd);
   3809 	cmd.code = IWN5000_PHY_CALIB_RESET_NOISE_GAIN;
   3810 	cmd.ngroups = 1;
   3811 	cmd.isvalid = 1;
   3812 	DPRINTF(("setting initial differential gains\n"));
   3813 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
   3814 }
   3815 
   3816 static int
   3817 iwn4965_set_gains(struct iwn_softc *sc)
   3818 {
   3819 	struct iwn_calib_state *calib = &sc->calib;
   3820 	struct iwn_phy_calib_gain cmd;
   3821 	int i, delta, noise;
   3822 
   3823 	/* Get minimal noise among connected antennas. */
   3824 	noise = INT_MAX;	/* NB: There's at least one antenna. */
   3825 	for (i = 0; i < 3; i++)
   3826 		if (sc->chainmask & (1 << i))
   3827 			noise = MIN(calib->noise[i], noise);
   3828 
   3829 	memset(&cmd, 0, sizeof cmd);
   3830 	cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN;
   3831 	/* Set differential gains for connected antennas. */
   3832 	for (i = 0; i < 3; i++) {
   3833 		if (sc->chainmask & (1 << i)) {
   3834 			/* Compute attenuation (in unit of 1.5dB). */
   3835 			delta = (noise - (int32_t)calib->noise[i]) / 30;
   3836 			/* NB: delta <= 0 */
   3837 			/* Limit to [-4.5dB,0]. */
   3838 			cmd.gain[i] = MIN(abs(delta), 3);
   3839 			if (delta < 0)
   3840 				cmd.gain[i] |= 1 << 2;	/* sign bit */
   3841 		}
   3842 	}
   3843 	DPRINTF(("setting differential gains Ant A/B/C: %x/%x/%x (%x)\n",
   3844 	    cmd.gain[0], cmd.gain[1], cmd.gain[2], sc->chainmask));
   3845 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
   3846 }
   3847 
   3848 static int
   3849 iwn5000_set_gains(struct iwn_softc *sc)
   3850 {
   3851 	struct iwn_calib_state *calib = &sc->calib;
   3852 	struct iwn_phy_calib_gain cmd;
   3853 	int i, ant, div, delta;
   3854 
   3855 	/* We collected 20 beacons and !=6050 need a 1.5 factor. */
   3856 	div = (sc->hw_type == IWN_HW_REV_TYPE_6050) ? 20 : 30;
   3857 
   3858 	memset(&cmd, 0, sizeof cmd);
   3859 	cmd.code = IWN5000_PHY_CALIB_NOISE_GAIN;
   3860 	cmd.ngroups = 1;
   3861 	cmd.isvalid = 1;
   3862 	/* Get first available RX antenna as referential. */
   3863 	ant = IWN_LSB(sc->rxchainmask);
   3864 	/* Set differential gains for other antennas. */
   3865 	for (i = ant + 1; i < 3; i++) {
   3866 		if (sc->chainmask & (1 << i)) {
   3867 			/* The delta is relative to antenna "ant". */
   3868 			delta = ((int32_t)calib->noise[ant] -
   3869 			    (int32_t)calib->noise[i]) / div;
   3870 			/* Limit to [-4.5dB,+4.5dB]. */
   3871 			cmd.gain[i - 1] = MIN(abs(delta), 3);
   3872 			if (delta < 0)
   3873 				cmd.gain[i - 1] |= 1 << 2;	/* sign bit */
   3874 		}
   3875 	}
   3876 	DPRINTF(("setting differential gains: %x/%x (%x)\n",
   3877 	    cmd.gain[0], cmd.gain[1], sc->chainmask));
   3878 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
   3879 }
   3880 
   3881 /*
   3882  * Tune RF RX sensitivity based on the number of false alarms detected
   3883  * during the last beacon period.
   3884  */
   3885 static void
   3886 iwn_tune_sensitivity(struct iwn_softc *sc, const struct iwn_rx_stats *stats)
   3887 {
   3888 #define inc(val, inc, max)			\
   3889 	if ((val) < (max)) {			\
   3890 		if ((val) < (max) - (inc))	\
   3891 			(val) += (inc);		\
   3892 		else				\
   3893 			(val) = (max);		\
   3894 		needs_update = 1;		\
   3895 	}
   3896 #define dec(val, dec, min)			\
   3897 	if ((val) > (min)) {			\
   3898 		if ((val) > (min) + (dec))	\
   3899 			(val) -= (dec);		\
   3900 		else				\
   3901 			(val) = (min);		\
   3902 		needs_update = 1;		\
   3903 	}
   3904 
   3905 	const struct iwn_sensitivity_limits *limits = sc->limits;
   3906 	struct iwn_calib_state *calib = &sc->calib;
   3907 	uint32_t val, rxena, fa;
   3908 	uint32_t energy[3], energy_min;
   3909 	uint8_t noise[3], noise_ref;
   3910 	int i, needs_update = 0;
   3911 
   3912 	/* Check that we've been enabled long enough. */
   3913 	if ((rxena = le32toh(stats->general.load)) == 0)
   3914 		return;
   3915 
   3916 	/* Compute number of false alarms since last call for OFDM. */
   3917 	fa  = le32toh(stats->ofdm.bad_plcp) - calib->bad_plcp_ofdm;
   3918 	fa += le32toh(stats->ofdm.fa) - calib->fa_ofdm;
   3919 	fa *= 200 * 1024;	/* 200TU */
   3920 
   3921 	/* Save counters values for next call. */
   3922 	calib->bad_plcp_ofdm = le32toh(stats->ofdm.bad_plcp);
   3923 	calib->fa_ofdm = le32toh(stats->ofdm.fa);
   3924 
   3925 	if (fa > 50 * rxena) {
   3926 		/* High false alarm count, decrease sensitivity. */
   3927 		DPRINTFN(2, ("OFDM high false alarm count: %u\n", fa));
   3928 		inc(calib->ofdm_x1,     1, limits->max_ofdm_x1);
   3929 		inc(calib->ofdm_mrc_x1, 1, limits->max_ofdm_mrc_x1);
   3930 		inc(calib->ofdm_x4,     1, limits->max_ofdm_x4);
   3931 		inc(calib->ofdm_mrc_x4, 1, limits->max_ofdm_mrc_x4);
   3932 
   3933 	} else if (fa < 5 * rxena) {
   3934 		/* Low false alarm count, increase sensitivity. */
   3935 		DPRINTFN(2, ("OFDM low false alarm count: %u\n", fa));
   3936 		dec(calib->ofdm_x1,     1, limits->min_ofdm_x1);
   3937 		dec(calib->ofdm_mrc_x1, 1, limits->min_ofdm_mrc_x1);
   3938 		dec(calib->ofdm_x4,     1, limits->min_ofdm_x4);
   3939 		dec(calib->ofdm_mrc_x4, 1, limits->min_ofdm_mrc_x4);
   3940 	}
   3941 
   3942 	/* Compute maximum noise among 3 receivers. */
   3943 	for (i = 0; i < 3; i++)
   3944 		noise[i] = (le32toh(stats->general.noise[i]) >> 8) & 0xff;
   3945 	val = MAX(noise[0], noise[1]);
   3946 	val = MAX(noise[2], val);
   3947 	/* Insert it into our samples table. */
   3948 	calib->noise_samples[calib->cur_noise_sample] = val;
   3949 	calib->cur_noise_sample = (calib->cur_noise_sample + 1) % 20;
   3950 
   3951 	/* Compute maximum noise among last 20 samples. */
   3952 	noise_ref = calib->noise_samples[0];
   3953 	for (i = 1; i < 20; i++)
   3954 		noise_ref = MAX(noise_ref, calib->noise_samples[i]);
   3955 
   3956 	/* Compute maximum energy among 3 receivers. */
   3957 	for (i = 0; i < 3; i++)
   3958 		energy[i] = le32toh(stats->general.energy[i]);
   3959 	val = MIN(energy[0], energy[1]);
   3960 	val = MIN(energy[2], val);
   3961 	/* Insert it into our samples table. */
   3962 	calib->energy_samples[calib->cur_energy_sample] = val;
   3963 	calib->cur_energy_sample = (calib->cur_energy_sample + 1) % 10;
   3964 
   3965 	/* Compute minimum energy among last 10 samples. */
   3966 	energy_min = calib->energy_samples[0];
   3967 	for (i = 1; i < 10; i++)
   3968 		energy_min = MAX(energy_min, calib->energy_samples[i]);
   3969 	energy_min += 6;
   3970 
   3971 	/* Compute number of false alarms since last call for CCK. */
   3972 	fa  = le32toh(stats->cck.bad_plcp) - calib->bad_plcp_cck;
   3973 	fa += le32toh(stats->cck.fa) - calib->fa_cck;
   3974 	fa *= 200 * 1024;	/* 200TU */
   3975 
   3976 	/* Save counters values for next call. */
   3977 	calib->bad_plcp_cck = le32toh(stats->cck.bad_plcp);
   3978 	calib->fa_cck = le32toh(stats->cck.fa);
   3979 
   3980 	if (fa > 50 * rxena) {
   3981 		/* High false alarm count, decrease sensitivity. */
   3982 		DPRINTFN(2, ("CCK high false alarm count: %u\n", fa));
   3983 		calib->cck_state = IWN_CCK_STATE_HIFA;
   3984 		calib->low_fa = 0;
   3985 
   3986 		if (calib->cck_x4 > 160) {
   3987 			calib->noise_ref = noise_ref;
   3988 			if (calib->energy_cck > 2)
   3989 				dec(calib->energy_cck, 2, energy_min);
   3990 		}
   3991 		if (calib->cck_x4 < 160) {
   3992 			calib->cck_x4 = 161;
   3993 			needs_update = 1;
   3994 		} else
   3995 			inc(calib->cck_x4, 3, limits->max_cck_x4);
   3996 
   3997 		inc(calib->cck_mrc_x4, 3, limits->max_cck_mrc_x4);
   3998 
   3999 	} else if (fa < 5 * rxena) {
   4000 		/* Low false alarm count, increase sensitivity. */
   4001 		DPRINTFN(2, ("CCK low false alarm count: %u\n", fa));
   4002 		calib->cck_state = IWN_CCK_STATE_LOFA;
   4003 		calib->low_fa++;
   4004 
   4005 		if (calib->cck_state != IWN_CCK_STATE_INIT &&
   4006 		    (((int32_t)calib->noise_ref - (int32_t)noise_ref) > 2 ||
   4007 		     calib->low_fa > 100)) {
   4008 			inc(calib->energy_cck, 2, limits->min_energy_cck);
   4009 			dec(calib->cck_x4,     3, limits->min_cck_x4);
   4010 			dec(calib->cck_mrc_x4, 3, limits->min_cck_mrc_x4);
   4011 		}
   4012 	} else {
   4013 		/* Not worth to increase or decrease sensitivity. */
   4014 		DPRINTFN(2, ("CCK normal false alarm count: %u\n", fa));
   4015 		calib->low_fa = 0;
   4016 		calib->noise_ref = noise_ref;
   4017 
   4018 		if (calib->cck_state == IWN_CCK_STATE_HIFA) {
   4019 			/* Previous interval had many false alarms. */
   4020 			dec(calib->energy_cck, 8, energy_min);
   4021 		}
   4022 		calib->cck_state = IWN_CCK_STATE_INIT;
   4023 	}
   4024 
   4025 	if (needs_update)
   4026 		(void)iwn_send_sensitivity(sc);
   4027 #undef dec
   4028 #undef inc
   4029 }
   4030 
   4031 static int
   4032 iwn_send_sensitivity(struct iwn_softc *sc)
   4033 {
   4034 	struct iwn_calib_state *calib = &sc->calib;
   4035 	struct iwn_sensitivity_cmd cmd;
   4036 
   4037 	memset(&cmd, 0, sizeof cmd);
   4038 	cmd.which = IWN_SENSITIVITY_WORKTBL;
   4039 	/* OFDM modulation. */
   4040 	cmd.corr_ofdm_x1     = htole16(calib->ofdm_x1);
   4041 	cmd.corr_ofdm_mrc_x1 = htole16(calib->ofdm_mrc_x1);
   4042 	cmd.corr_ofdm_x4     = htole16(calib->ofdm_x4);
   4043 	cmd.corr_ofdm_mrc_x4 = htole16(calib->ofdm_mrc_x4);
   4044 	cmd.energy_ofdm      = htole16(sc->limits->energy_ofdm);
   4045 	cmd.energy_ofdm_th   = htole16(62);
   4046 	/* CCK modulation. */
   4047 	cmd.corr_cck_x4      = htole16(calib->cck_x4);
   4048 	cmd.corr_cck_mrc_x4  = htole16(calib->cck_mrc_x4);
   4049 	cmd.energy_cck       = htole16(calib->energy_cck);
   4050 	/* Barker modulation: use default values. */
   4051 	cmd.corr_barker      = htole16(190);
   4052 	cmd.corr_barker_mrc  = htole16(390);
   4053 
   4054 	DPRINTFN(2, ("setting sensitivity %d/%d/%d/%d/%d/%d/%d\n",
   4055 	    calib->ofdm_x1, calib->ofdm_mrc_x1, calib->ofdm_x4,
   4056 	    calib->ofdm_mrc_x4, calib->cck_x4, calib->cck_mrc_x4,
   4057 	    calib->energy_cck));
   4058 	return iwn_cmd(sc, IWN_CMD_SET_SENSITIVITY, &cmd, sizeof cmd, 1);
   4059 }
   4060 
   4061 /*
   4062  * Set STA mode power saving level (between 0 and 5).
   4063  * Level 0 is CAM (Continuously Aware Mode), 5 is for maximum power saving.
   4064  */
   4065 static int
   4066 iwn_set_pslevel(struct iwn_softc *sc, int dtim, int level, int async)
   4067 {
   4068 	struct iwn_pmgt_cmd cmd;
   4069 	const struct iwn_pmgt *pmgt;
   4070 	uint32_t maxp, skip_dtim;
   4071 	pcireg_t reg;
   4072 	int i;
   4073 
   4074 	/* Select which PS parameters to use. */
   4075 	if (dtim <= 2)
   4076 		pmgt = &iwn_pmgt[0][level];
   4077 	else if (dtim <= 10)
   4078 		pmgt = &iwn_pmgt[1][level];
   4079 	else
   4080 		pmgt = &iwn_pmgt[2][level];
   4081 
   4082 	memset(&cmd, 0, sizeof cmd);
   4083 	if (level != 0)	/* not CAM */
   4084 		cmd.flags |= htole16(IWN_PS_ALLOW_SLEEP);
   4085 	if (level == 5)
   4086 		cmd.flags |= htole16(IWN_PS_FAST_PD);
   4087 	/* Retrieve PCIe Active State Power Management (ASPM). */
   4088 	reg = pci_conf_read(sc->sc_pct, sc->sc_pcitag,
   4089 	    sc->sc_cap_off + PCIE_LCSR);
   4090 	if (!(reg & PCIE_LCSR_ASPM_L0S))	/* L0s Entry disabled. */
   4091 		cmd.flags |= htole16(IWN_PS_PCI_PMGT);
   4092 	cmd.rxtimeout = htole32(pmgt->rxtimeout * 1024);
   4093 	cmd.txtimeout = htole32(pmgt->txtimeout * 1024);
   4094 
   4095 	if (dtim == 0) {
   4096 		dtim = 1;
   4097 		skip_dtim = 0;
   4098 	} else
   4099 		skip_dtim = pmgt->skip_dtim;
   4100 	if (skip_dtim != 0) {
   4101 		cmd.flags |= htole16(IWN_PS_SLEEP_OVER_DTIM);
   4102 		maxp = pmgt->intval[4];
   4103 		if (maxp == (uint32_t)-1)
   4104 			maxp = dtim * (skip_dtim + 1);
   4105 		else if (maxp > dtim)
   4106 			maxp = (maxp / dtim) * dtim;
   4107 	} else
   4108 		maxp = dtim;
   4109 	for (i = 0; i < 5; i++)
   4110 		cmd.intval[i] = htole32(MIN(maxp, pmgt->intval[i]));
   4111 
   4112 	DPRINTF(("setting power saving level to %d\n", level));
   4113 	return iwn_cmd(sc, IWN_CMD_SET_POWER_MODE, &cmd, sizeof cmd, async);
   4114 }
   4115 
   4116 int
   4117 iwn5000_runtime_calib(struct iwn_softc *sc)
   4118 {
   4119 	struct iwn5000_calib_config cmd;
   4120 
   4121 	memset(&cmd, 0, sizeof cmd);
   4122 	cmd.ucode.once.enable = 0xffffffff;
   4123 	cmd.ucode.once.start = IWN5000_CALIB_DC;
   4124 	DPRINTF(("configuring runtime calibration\n"));
   4125 	return iwn_cmd(sc, IWN5000_CMD_CALIB_CONFIG, &cmd, sizeof(cmd), 0);
   4126 }
   4127 
   4128 static int
   4129 iwn_config_bt_coex_bluetooth(struct iwn_softc *sc)
   4130 {
   4131 	struct iwn_bluetooth bluetooth;
   4132 
   4133 	memset(&bluetooth, 0, sizeof bluetooth);
   4134 	bluetooth.flags = IWN_BT_COEX_ENABLE;
   4135 	bluetooth.lead_time = IWN_BT_LEAD_TIME_DEF;
   4136 	bluetooth.max_kill = IWN_BT_MAX_KILL_DEF;
   4137 
   4138 	DPRINTF(("configuring bluetooth coexistence\n"));
   4139 	return iwn_cmd(sc, IWN_CMD_BT_COEX, &bluetooth, sizeof bluetooth, 0);
   4140 }
   4141 
   4142 static int
   4143 iwn_config_bt_coex_prio_table(struct iwn_softc *sc)
   4144 {
   4145 	uint8_t prio_table[16];
   4146 
   4147 	memset(&prio_table, 0, sizeof prio_table);
   4148 	prio_table[ 0] =  6;	/* init calibration 1		*/
   4149 	prio_table[ 1] =  7;	/* init calibration 2		*/
   4150 	prio_table[ 2] =  2;	/* periodic calib low 1		*/
   4151 	prio_table[ 3] =  3;	/* periodic calib low 2		*/
   4152 	prio_table[ 4] =  4;	/* periodic calib high 1	*/
   4153 	prio_table[ 5] =  5;	/* periodic calib high 2	*/
   4154 	prio_table[ 6] =  6;	/* dtim				*/
   4155 	prio_table[ 7] =  8;	/* scan52			*/
   4156 	prio_table[ 8] = 10;	/* scan24			*/
   4157 
   4158 	DPRINTF(("sending priority lookup table\n"));
   4159 	return iwn_cmd(sc, IWN_CMD_BT_COEX_PRIO_TABLE,
   4160 	               &prio_table, sizeof prio_table, 0);
   4161 }
   4162 
   4163 static int
   4164 iwn_config_bt_coex_adv1(struct iwn_softc *sc)
   4165 {
   4166 	int error;
   4167 	struct iwn_bt_adv1 d;
   4168 
   4169 	memset(&d, 0, sizeof d);
   4170 	d.basic.bt.flags = IWN_BT_COEX_ENABLE;
   4171 	d.basic.bt.lead_time = IWN_BT_LEAD_TIME_DEF;
   4172 	d.basic.bt.max_kill = IWN_BT_MAX_KILL_DEF;
   4173 	d.basic.bt.bt3_timer_t7_value = IWN_BT_BT3_T7_DEF;
   4174 	d.basic.bt.kill_ack_mask = IWN_BT_KILL_ACK_MASK_DEF;
   4175 	d.basic.bt.kill_cts_mask = IWN_BT_KILL_CTS_MASK_DEF;
   4176 	d.basic.bt3_prio_sample_time = IWN_BT_BT3_PRIO_SAMPLE_DEF;
   4177 	d.basic.bt3_timer_t2_value = IWN_BT_BT3_T2_DEF;
   4178 	d.basic.bt3_lookup_table[ 0] = htole32(0xaaaaaaaa); /* Normal */
   4179 	d.basic.bt3_lookup_table[ 1] = htole32(0xaaaaaaaa);
   4180 	d.basic.bt3_lookup_table[ 2] = htole32(0xaeaaaaaa);
   4181 	d.basic.bt3_lookup_table[ 3] = htole32(0xaaaaaaaa);
   4182 	d.basic.bt3_lookup_table[ 4] = htole32(0xcc00ff28);
   4183 	d.basic.bt3_lookup_table[ 5] = htole32(0x0000aaaa);
   4184 	d.basic.bt3_lookup_table[ 6] = htole32(0xcc00aaaa);
   4185 	d.basic.bt3_lookup_table[ 7] = htole32(0x0000aaaa);
   4186 	d.basic.bt3_lookup_table[ 8] = htole32(0xc0004000);
   4187 	d.basic.bt3_lookup_table[ 9] = htole32(0x00004000);
   4188 	d.basic.bt3_lookup_table[10] = htole32(0xf0005000);
   4189 	d.basic.bt3_lookup_table[11] = htole32(0xf0005000);
   4190 	d.basic.reduce_txpower = 0; /* as not implemented */
   4191 	d.basic.valid = IWN_BT_ALL_VALID_MASK;
   4192 	d.prio_boost = IWN_BT_PRIO_BOOST_DEF;
   4193 	d.tx_prio_boost = 0;
   4194 	d.rx_prio_boost = 0;
   4195 
   4196 	DPRINTF(("configuring advanced bluetooth coexistence v1\n"));
   4197 	error = iwn_cmd(sc, IWN_CMD_BT_COEX, &d, sizeof d, 0);
   4198 	if (error != 0) {
   4199 		aprint_error_dev(sc->sc_dev,
   4200 			"could not configure advanced bluetooth coexistence\n");
   4201 		return error;
   4202 	}
   4203 
   4204 	error = iwn_config_bt_coex_prio_table(sc);
   4205 	if (error != 0) {
   4206 		aprint_error_dev(sc->sc_dev,
   4207 			"could not configure send BT priority table\n");
   4208 		return error;
   4209 	}
   4210 
   4211 	return error;
   4212 }
   4213 
   4214 static int
   4215 iwn_config(struct iwn_softc *sc)
   4216 {
   4217 	struct iwn_ops *ops = &sc->ops;
   4218 	struct ieee80211com *ic = &sc->sc_ic;
   4219 	struct ifnet *ifp = ic->ic_ifp;
   4220 	uint32_t txmask;
   4221 	uint16_t rxchain;
   4222 	int error;
   4223 
   4224 	error = ops->config_bt_coex(sc);
   4225 	if (error != 0) {
   4226 		aprint_error_dev(sc->sc_dev,
   4227 			"could not configure bluetooth coexistence\n");
   4228 		return error;
   4229 	}
   4230 
   4231 	if (sc->hw_type == IWN_HW_REV_TYPE_6050 ||
   4232 	    sc->hw_type == IWN_HW_REV_TYPE_6005) {
   4233 		/* Configure runtime DC calibration. */
   4234 		error = iwn5000_runtime_calib(sc);
   4235 		if (error != 0) {
   4236 			aprint_error_dev(sc->sc_dev,
   4237 			    "could not configure runtime calibration\n");
   4238 			return error;
   4239 		}
   4240 	}
   4241 
   4242 	/* Configure valid TX chains for 5000 Series. */
   4243 	if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
   4244 		txmask = htole32(sc->txchainmask);
   4245 		DPRINTF(("configuring valid TX chains 0x%x\n", txmask));
   4246 		error = iwn_cmd(sc, IWN5000_CMD_TX_ANT_CONFIG, &txmask,
   4247 		    sizeof txmask, 0);
   4248 		if (error != 0) {
   4249 			aprint_error_dev(sc->sc_dev,
   4250 			    "could not configure valid TX chains\n");
   4251 			return error;
   4252 		}
   4253 	}
   4254 
   4255 	/* Set mode, channel, RX filter and enable RX. */
   4256 	memset(&sc->rxon, 0, sizeof (struct iwn_rxon));
   4257 	IEEE80211_ADDR_COPY(ic->ic_myaddr, CLLADDR(ifp->if_sadl));
   4258 	IEEE80211_ADDR_COPY(sc->rxon.myaddr, ic->ic_myaddr);
   4259 	IEEE80211_ADDR_COPY(sc->rxon.wlap, ic->ic_myaddr);
   4260 	sc->rxon.chan = ieee80211_chan2ieee(ic, ic->ic_ibss_chan);
   4261 	sc->rxon.flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
   4262 	if (IEEE80211_IS_CHAN_2GHZ(ic->ic_ibss_chan))
   4263 		sc->rxon.flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
   4264 	switch (ic->ic_opmode) {
   4265 	case IEEE80211_M_STA:
   4266 		sc->rxon.mode = IWN_MODE_STA;
   4267 		sc->rxon.filter = htole32(IWN_FILTER_MULTICAST);
   4268 		break;
   4269 	case IEEE80211_M_MONITOR:
   4270 		sc->rxon.mode = IWN_MODE_MONITOR;
   4271 		sc->rxon.filter = htole32(IWN_FILTER_MULTICAST |
   4272 		    IWN_FILTER_CTL | IWN_FILTER_PROMISC);
   4273 		break;
   4274 	default:
   4275 		/* Should not get there. */
   4276 		break;
   4277 	}
   4278 	sc->rxon.cck_mask  = 0x0f;	/* not yet negotiated */
   4279 	sc->rxon.ofdm_mask = 0xff;	/* not yet negotiated */
   4280 	sc->rxon.ht_single_mask = 0xff;
   4281 	sc->rxon.ht_dual_mask = 0xff;
   4282 	sc->rxon.ht_triple_mask = 0xff;
   4283 	rxchain =
   4284 	    IWN_RXCHAIN_VALID(sc->rxchainmask) |
   4285 	    IWN_RXCHAIN_MIMO_COUNT(2) |
   4286 	    IWN_RXCHAIN_IDLE_COUNT(2);
   4287 	sc->rxon.rxchain = htole16(rxchain);
   4288 	DPRINTF(("setting configuration\n"));
   4289 	error = iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, sc->rxonsz, 0);
   4290 	if (error != 0) {
   4291 		aprint_error_dev(sc->sc_dev,
   4292 		    "RXON command failed\n");
   4293 		return error;
   4294 	}
   4295 
   4296 	if ((error = iwn_add_broadcast_node(sc, 0)) != 0) {
   4297 		aprint_error_dev(sc->sc_dev,
   4298 		    "could not add broadcast node\n");
   4299 		return error;
   4300 	}
   4301 
   4302 	/* Configuration has changed, set TX power accordingly. */
   4303 	if ((error = ops->set_txpower(sc, 0)) != 0) {
   4304 		aprint_error_dev(sc->sc_dev,
   4305 		    "could not set TX power\n");
   4306 		return error;
   4307 	}
   4308 
   4309 	if ((error = iwn_set_critical_temp(sc)) != 0) {
   4310 		aprint_error_dev(sc->sc_dev,
   4311 		    "could not set critical temperature\n");
   4312 		return error;
   4313 	}
   4314 
   4315 	/* Set power saving level to CAM during initialization. */
   4316 	if ((error = iwn_set_pslevel(sc, 0, 0, 0)) != 0) {
   4317 		aprint_error_dev(sc->sc_dev,
   4318 		    "could not set power saving level\n");
   4319 		return error;
   4320 	}
   4321 	return 0;
   4322 }
   4323 
   4324 static int
   4325 iwn_scan(struct iwn_softc *sc, uint16_t flags)
   4326 {
   4327 	struct ieee80211com *ic = &sc->sc_ic;
   4328 	struct iwn_scan_hdr *hdr;
   4329 	struct iwn_cmd_data *tx;
   4330 	struct iwn_scan_essid *essid;
   4331 	struct iwn_scan_chan *chan;
   4332 	struct ieee80211_frame *wh;
   4333 	struct ieee80211_rateset *rs;
   4334 	struct ieee80211_channel *c;
   4335 	uint8_t *buf, *frm;
   4336 	uint16_t rxchain;
   4337 	uint8_t txant;
   4338 	int buflen, error;
   4339 
   4340 	buf = malloc(IWN_SCAN_MAXSZ, M_DEVBUF, M_NOWAIT | M_ZERO);
   4341 	if (buf == NULL) {
   4342 		aprint_error_dev(sc->sc_dev,
   4343 		    "could not allocate buffer for scan command\n");
   4344 		return ENOMEM;
   4345 	}
   4346 	hdr = (struct iwn_scan_hdr *)buf;
   4347 	/*
   4348 	 * Move to the next channel if no frames are received within 10ms
   4349 	 * after sending the probe request.
   4350 	 */
   4351 	hdr->quiet_time = htole16(10);		/* timeout in milliseconds */
   4352 	hdr->quiet_threshold = htole16(1);	/* min # of packets */
   4353 
   4354 	/* Select antennas for scanning. */
   4355 	rxchain =
   4356 	    IWN_RXCHAIN_VALID(sc->rxchainmask) |
   4357 	    IWN_RXCHAIN_FORCE_MIMO_SEL(sc->rxchainmask) |
   4358 	    IWN_RXCHAIN_DRIVER_FORCE;
   4359 	if ((flags & IEEE80211_CHAN_5GHZ) &&
   4360 	    sc->hw_type == IWN_HW_REV_TYPE_4965) {
   4361 		/* Ant A must be avoided in 5GHz because of an HW bug. */
   4362 		rxchain |= IWN_RXCHAIN_FORCE_SEL(IWN_ANT_BC);
   4363 	} else	/* Use all available RX antennas. */
   4364 		rxchain |= IWN_RXCHAIN_FORCE_SEL(sc->rxchainmask);
   4365 	hdr->rxchain = htole16(rxchain);
   4366 	hdr->filter = htole32(IWN_FILTER_MULTICAST | IWN_FILTER_BEACON);
   4367 
   4368 	tx = (struct iwn_cmd_data *)(hdr + 1);
   4369 	tx->flags = htole32(IWN_TX_AUTO_SEQ);
   4370 	tx->id = sc->broadcast_id;
   4371 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
   4372 
   4373 	if (flags & IEEE80211_CHAN_5GHZ) {
   4374 		hdr->crc_threshold = 0xffff;
   4375 		/* Send probe requests at 6Mbps. */
   4376 		tx->plcp = iwn_rates[IWN_RIDX_OFDM6].plcp;
   4377 		rs = &ic->ic_sup_rates[IEEE80211_MODE_11A];
   4378 	} else {
   4379 		hdr->flags = htole32(IWN_RXON_24GHZ | IWN_RXON_AUTO);
   4380 		/* Send probe requests at 1Mbps. */
   4381 		tx->plcp = iwn_rates[IWN_RIDX_CCK1].plcp;
   4382 		tx->rflags = IWN_RFLAG_CCK;
   4383 		rs = &ic->ic_sup_rates[IEEE80211_MODE_11G];
   4384 	}
   4385 	/* Use the first valid TX antenna. */
   4386 	txant = IWN_LSB(sc->txchainmask);
   4387 	tx->rflags |= IWN_RFLAG_ANT(txant);
   4388 
   4389 	essid = (struct iwn_scan_essid *)(tx + 1);
   4390 	if (ic->ic_des_esslen != 0) {
   4391 		essid[0].id = IEEE80211_ELEMID_SSID;
   4392 		essid[0].len = ic->ic_des_esslen;
   4393 		memcpy(essid[0].data, ic->ic_des_essid, ic->ic_des_esslen);
   4394 	}
   4395 	/*
   4396 	 * Build a probe request frame.  Most of the following code is a
   4397 	 * copy & paste of what is done in net80211.
   4398 	 */
   4399 	wh = (struct ieee80211_frame *)(essid + 20);
   4400 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
   4401 	    IEEE80211_FC0_SUBTYPE_PROBE_REQ;
   4402 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
   4403 	IEEE80211_ADDR_COPY(wh->i_addr1, etherbroadcastaddr);
   4404 	IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
   4405 	IEEE80211_ADDR_COPY(wh->i_addr3, etherbroadcastaddr);
   4406 	*(uint16_t *)&wh->i_dur[0] = 0;	/* filled by HW */
   4407 	*(uint16_t *)&wh->i_seq[0] = 0;	/* filled by HW */
   4408 
   4409 	frm = (uint8_t *)(wh + 1);
   4410 	frm = ieee80211_add_ssid(frm, NULL, 0);
   4411 	frm = ieee80211_add_rates(frm, rs);
   4412 #ifndef IEEE80211_NO_HT
   4413 	if (ic->ic_flags & IEEE80211_F_HTON)
   4414 		frm = ieee80211_add_htcaps(frm, ic);
   4415 #endif
   4416 	if (rs->rs_nrates > IEEE80211_RATE_SIZE)
   4417 		frm = ieee80211_add_xrates(frm, rs);
   4418 
   4419 	/* Set length of probe request. */
   4420 	tx->len = htole16(frm - (uint8_t *)wh);
   4421 
   4422 	chan = (struct iwn_scan_chan *)frm;
   4423 	for (c  = &ic->ic_channels[1];
   4424 	     c <= &ic->ic_channels[IEEE80211_CHAN_MAX]; c++) {
   4425 		if ((c->ic_flags & flags) != flags)
   4426 			continue;
   4427 
   4428 		chan->chan = htole16(ieee80211_chan2ieee(ic, c));
   4429 		DPRINTFN(2, ("adding channel %d\n", chan->chan));
   4430 		chan->flags = 0;
   4431 		if (!(c->ic_flags & IEEE80211_CHAN_PASSIVE))
   4432 			chan->flags |= htole32(IWN_CHAN_ACTIVE);
   4433 		if (ic->ic_des_esslen != 0)
   4434 			chan->flags |= htole32(IWN_CHAN_NPBREQS(1));
   4435 		chan->dsp_gain = 0x6e;
   4436 		if (IEEE80211_IS_CHAN_5GHZ(c)) {
   4437 			chan->rf_gain = 0x3b;
   4438 			chan->active  = htole16(24);
   4439 			chan->passive = htole16(110);
   4440 		} else {
   4441 			chan->rf_gain = 0x28;
   4442 			chan->active  = htole16(36);
   4443 			chan->passive = htole16(120);
   4444 		}
   4445 		hdr->nchan++;
   4446 		chan++;
   4447 	}
   4448 
   4449 	buflen = (uint8_t *)chan - buf;
   4450 	hdr->len = htole16(buflen);
   4451 
   4452 	DPRINTF(("sending scan command nchan=%d\n", hdr->nchan));
   4453 	error = iwn_cmd(sc, IWN_CMD_SCAN, buf, buflen, 1);
   4454 	free(buf, M_DEVBUF);
   4455 	return error;
   4456 }
   4457 
   4458 static int
   4459 iwn_auth(struct iwn_softc *sc)
   4460 {
   4461 	struct iwn_ops *ops = &sc->ops;
   4462 	struct ieee80211com *ic = &sc->sc_ic;
   4463 	struct ieee80211_node *ni = ic->ic_bss;
   4464 	int error;
   4465 
   4466 	/* Update adapter configuration. */
   4467 	IEEE80211_ADDR_COPY(sc->rxon.bssid, ni->ni_bssid);
   4468 	sc->rxon.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
   4469 	sc->rxon.flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
   4470 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
   4471 		sc->rxon.flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
   4472 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
   4473 		sc->rxon.flags |= htole32(IWN_RXON_SHSLOT);
   4474 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
   4475 		sc->rxon.flags |= htole32(IWN_RXON_SHPREAMBLE);
   4476 	switch (ic->ic_curmode) {
   4477 	case IEEE80211_MODE_11A:
   4478 		sc->rxon.cck_mask  = 0;
   4479 		sc->rxon.ofdm_mask = 0x15;
   4480 		break;
   4481 	case IEEE80211_MODE_11B:
   4482 		sc->rxon.cck_mask  = 0x03;
   4483 		sc->rxon.ofdm_mask = 0;
   4484 		break;
   4485 	default:	/* Assume 802.11b/g. */
   4486 		sc->rxon.cck_mask  = 0x0f;
   4487 		sc->rxon.ofdm_mask = 0x15;
   4488 	}
   4489 	DPRINTF(("rxon chan %d flags %x cck %x ofdm %x\n", sc->rxon.chan,
   4490 	    sc->rxon.flags, sc->rxon.cck_mask, sc->rxon.ofdm_mask));
   4491 	error = iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, sc->rxonsz, 1);
   4492 	if (error != 0) {
   4493 		aprint_error_dev(sc->sc_dev,
   4494 		    "RXON command failed\n");
   4495 		return error;
   4496 	}
   4497 
   4498 	/* Configuration has changed, set TX power accordingly. */
   4499 	if ((error = ops->set_txpower(sc, 1)) != 0) {
   4500 		aprint_error_dev(sc->sc_dev,
   4501 		    "could not set TX power\n");
   4502 		return error;
   4503 	}
   4504 	/*
   4505 	 * Reconfiguring RXON clears the firmware nodes table so we must
   4506 	 * add the broadcast node again.
   4507 	 */
   4508 	if ((error = iwn_add_broadcast_node(sc, 1)) != 0) {
   4509 		aprint_error_dev(sc->sc_dev,
   4510 		    "could not add broadcast node\n");
   4511 		return error;
   4512 	}
   4513 	return 0;
   4514 }
   4515 
   4516 static int
   4517 iwn_run(struct iwn_softc *sc)
   4518 {
   4519 	struct iwn_ops *ops = &sc->ops;
   4520 	struct ieee80211com *ic = &sc->sc_ic;
   4521 	struct ieee80211_node *ni = ic->ic_bss;
   4522 	struct iwn_node_info node;
   4523 	int error;
   4524 
   4525 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
   4526 		/* Link LED blinks while monitoring. */
   4527 		iwn_set_led(sc, IWN_LED_LINK, 5, 5);
   4528 		return 0;
   4529 	}
   4530 	if ((error = iwn_set_timing(sc, ni)) != 0) {
   4531 		aprint_error_dev(sc->sc_dev,
   4532 		    "could not set timing\n");
   4533 		return error;
   4534 	}
   4535 
   4536 	/* Update adapter configuration. */
   4537 	sc->rxon.associd = htole16(IEEE80211_AID(ni->ni_associd));
   4538 	/* Short preamble and slot time are negotiated when associating. */
   4539 	sc->rxon.flags &= ~htole32(IWN_RXON_SHPREAMBLE | IWN_RXON_SHSLOT);
   4540 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
   4541 		sc->rxon.flags |= htole32(IWN_RXON_SHSLOT);
   4542 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
   4543 		sc->rxon.flags |= htole32(IWN_RXON_SHPREAMBLE);
   4544 	sc->rxon.filter |= htole32(IWN_FILTER_BSS);
   4545 	DPRINTF(("rxon chan %d flags %x\n", sc->rxon.chan, sc->rxon.flags));
   4546 	error = iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, sc->rxonsz, 1);
   4547 	if (error != 0) {
   4548 		aprint_error_dev(sc->sc_dev,
   4549 		    "could not update configuration\n");
   4550 		return error;
   4551 	}
   4552 
   4553 	/* Configuration has changed, set TX power accordingly. */
   4554 	if ((error = ops->set_txpower(sc, 1)) != 0) {
   4555 		aprint_error_dev(sc->sc_dev,
   4556 		    "could not set TX power\n");
   4557 		return error;
   4558 	}
   4559 
   4560 	/* Fake a join to initialize the TX rate. */
   4561 	((struct iwn_node *)ni)->id = IWN_ID_BSS;
   4562 	iwn_newassoc(ni, 1);
   4563 
   4564 	/* Add BSS node. */
   4565 	memset(&node, 0, sizeof node);
   4566 	IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr);
   4567 	node.id = IWN_ID_BSS;
   4568 #ifdef notyet
   4569 	node.htflags = htole32(IWN_AMDPU_SIZE_FACTOR(3) |
   4570 	    IWN_AMDPU_DENSITY(5));	/* 2us */
   4571 #endif
   4572 	DPRINTF(("adding BSS node\n"));
   4573 	error = ops->add_node(sc, &node, 1);
   4574 	if (error != 0) {
   4575 		aprint_error_dev(sc->sc_dev,
   4576 		    "could not add BSS node\n");
   4577 		return error;
   4578 	}
   4579 	DPRINTF(("setting link quality for node %d\n", node.id));
   4580 	if ((error = iwn_set_link_quality(sc, ni)) != 0) {
   4581 		aprint_error_dev(sc->sc_dev,
   4582 		    "could not setup link quality for node %d\n", node.id);
   4583 		return error;
   4584 	}
   4585 
   4586 	if ((error = iwn_init_sensitivity(sc)) != 0) {
   4587 		aprint_error_dev(sc->sc_dev,
   4588 		    "could not set sensitivity\n");
   4589 		return error;
   4590 	}
   4591 	/* Start periodic calibration timer. */
   4592 	sc->calib.state = IWN_CALIB_STATE_ASSOC;
   4593 	sc->calib_cnt = 0;
   4594 	callout_schedule(&sc->calib_to, hz/2);
   4595 
   4596 	/* Link LED always on while associated. */
   4597 	iwn_set_led(sc, IWN_LED_LINK, 0, 1);
   4598 	return 0;
   4599 }
   4600 
   4601 #ifdef IWN_HWCRYPTO
   4602 /*
   4603  * We support CCMP hardware encryption/decryption of unicast frames only.
   4604  * HW support for TKIP really sucks.  We should let TKIP die anyway.
   4605  */
   4606 static int
   4607 iwn_set_key(struct ieee80211com *ic, struct ieee80211_node *ni,
   4608     struct ieee80211_key *k)
   4609 {
   4610 	struct iwn_softc *sc = ic->ic_softc;
   4611 	struct iwn_ops *ops = &sc->ops;
   4612 	struct iwn_node *wn = (void *)ni;
   4613 	struct iwn_node_info node;
   4614 	uint16_t kflags;
   4615 
   4616 	if ((k->k_flags & IEEE80211_KEY_GROUP) ||
   4617 	    k->k_cipher != IEEE80211_CIPHER_CCMP)
   4618 		return ieee80211_set_key(ic, ni, k);
   4619 
   4620 	kflags = IWN_KFLAG_CCMP | IWN_KFLAG_MAP | IWN_KFLAG_KID(k->k_id);
   4621 	if (k->k_flags & IEEE80211_KEY_GROUP)
   4622 		kflags |= IWN_KFLAG_GROUP;
   4623 
   4624 	memset(&node, 0, sizeof node);
   4625 	node.id = (k->k_flags & IEEE80211_KEY_GROUP) ?
   4626 	    sc->broadcast_id : wn->id;
   4627 	node.control = IWN_NODE_UPDATE;
   4628 	node.flags = IWN_FLAG_SET_KEY;
   4629 	node.kflags = htole16(kflags);
   4630 	node.kid = k->k_id;
   4631 	memcpy(node.key, k->k_key, k->k_len);
   4632 	DPRINTF(("set key id=%d for node %d\n", k->k_id, node.id));
   4633 	return ops->add_node(sc, &node, 1);
   4634 }
   4635 
   4636 static void
   4637 iwn_delete_key(struct ieee80211com *ic, struct ieee80211_node *ni,
   4638     struct ieee80211_key *k)
   4639 {
   4640 	struct iwn_softc *sc = ic->ic_softc;
   4641 	struct iwn_ops *ops = &sc->ops;
   4642 	struct iwn_node *wn = (void *)ni;
   4643 	struct iwn_node_info node;
   4644 
   4645 	if ((k->k_flags & IEEE80211_KEY_GROUP) ||
   4646 	    k->k_cipher != IEEE80211_CIPHER_CCMP) {
   4647 		/* See comment about other ciphers above. */
   4648 		ieee80211_delete_key(ic, ni, k);
   4649 		return;
   4650 	}
   4651 	if (ic->ic_state != IEEE80211_S_RUN)
   4652 		return;	/* Nothing to do. */
   4653 	memset(&node, 0, sizeof node);
   4654 	node.id = (k->k_flags & IEEE80211_KEY_GROUP) ?
   4655 	    sc->broadcast_id : wn->id;
   4656 	node.control = IWN_NODE_UPDATE;
   4657 	node.flags = IWN_FLAG_SET_KEY;
   4658 	node.kflags = htole16(IWN_KFLAG_INVALID);
   4659 	node.kid = 0xff;
   4660 	DPRINTF(("delete keys for node %d\n", node.id));
   4661 	(void)ops->add_node(sc, &node, 1);
   4662 }
   4663 #endif
   4664 
   4665 /* XXX Added for NetBSD (copied from rev 1.39). */
   4666 
   4667 static int
   4668 iwn_wme_update(struct ieee80211com *ic)
   4669 {
   4670 #define IWN_EXP2(v)    htole16((1 << (v)) - 1)
   4671 #define IWN_USEC(v)    htole16(IEEE80211_TXOP_TO_US(v))
   4672 	struct iwn_softc *sc = ic->ic_ifp->if_softc;
   4673 	const struct wmeParams *wmep;
   4674 	struct iwn_edca_params cmd;
   4675 	int ac;
   4676 
   4677 	/* don't override default WME values if WME is not actually enabled */
   4678 	if (!(ic->ic_flags & IEEE80211_F_WME))
   4679 		return 0;
   4680 	cmd.flags = 0;
   4681 	for (ac = 0; ac < WME_NUM_AC; ac++) {
   4682 		wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
   4683 		cmd.ac[ac].aifsn = wmep->wmep_aifsn;
   4684 		cmd.ac[ac].cwmin = IWN_EXP2(wmep->wmep_logcwmin);
   4685 		cmd.ac[ac].cwmax = IWN_EXP2(wmep->wmep_logcwmax);
   4686 		cmd.ac[ac].txoplimit  = IWN_USEC(wmep->wmep_txopLimit);
   4687 
   4688 		DPRINTF(("setting WME for queue %d aifsn=%d cwmin=%d cwmax=%d "
   4689 					"txop=%d\n", ac, cmd.ac[ac].aifsn,
   4690 					cmd.ac[ac].cwmin,
   4691 					cmd.ac[ac].cwmax, cmd.ac[ac].txoplimit));
   4692 	}
   4693 	return iwn_cmd(sc, IWN_CMD_EDCA_PARAMS, &cmd, sizeof cmd, 1);
   4694 #undef IWN_USEC
   4695 #undef IWN_EXP2
   4696 }
   4697 
   4698 #ifndef IEEE80211_NO_HT
   4699 /*
   4700  * This function is called by upper layer when an ADDBA request is received
   4701  * from another STA and before the ADDBA response is sent.
   4702  */
   4703 static int
   4704 iwn_ampdu_rx_start(struct ieee80211com *ic, struct ieee80211_node *ni,
   4705     uint8_t tid)
   4706 {
   4707 	struct ieee80211_rx_ba *ba = &ni->ni_rx_ba[tid];
   4708 	struct iwn_softc *sc = ic->ic_softc;
   4709 	struct iwn_ops *ops = &sc->ops;
   4710 	struct iwn_node *wn = (void *)ni;
   4711 	struct iwn_node_info node;
   4712 
   4713 	memset(&node, 0, sizeof node);
   4714 	node.id = wn->id;
   4715 	node.control = IWN_NODE_UPDATE;
   4716 	node.flags = IWN_FLAG_SET_ADDBA;
   4717 	node.addba_tid = tid;
   4718 	node.addba_ssn = htole16(ba->ba_winstart);
   4719 	DPRINTFN(2, ("ADDBA RA=%d TID=%d SSN=%d\n", wn->id, tid,
   4720 	    ba->ba_winstart));
   4721 	return ops->add_node(sc, &node, 1);
   4722 }
   4723 
   4724 /*
   4725  * This function is called by upper layer on teardown of an HT-immediate
   4726  * Block Ack agreement (eg. uppon receipt of a DELBA frame).
   4727  */
   4728 static void
   4729 iwn_ampdu_rx_stop(struct ieee80211com *ic, struct ieee80211_node *ni,
   4730     uint8_t tid)
   4731 {
   4732 	struct iwn_softc *sc = ic->ic_softc;
   4733 	struct iwn_ops *ops = &sc->ops;
   4734 	struct iwn_node *wn = (void *)ni;
   4735 	struct iwn_node_info node;
   4736 
   4737 	memset(&node, 0, sizeof node);
   4738 	node.id = wn->id;
   4739 	node.control = IWN_NODE_UPDATE;
   4740 	node.flags = IWN_FLAG_SET_DELBA;
   4741 	node.delba_tid = tid;
   4742 	DPRINTFN(2, ("DELBA RA=%d TID=%d\n", wn->id, tid));
   4743 	(void)ops->add_node(sc, &node, 1);
   4744 }
   4745 
   4746 /*
   4747  * This function is called by upper layer when an ADDBA response is received
   4748  * from another STA.
   4749  */
   4750 static int
   4751 iwn_ampdu_tx_start(struct ieee80211com *ic, struct ieee80211_node *ni,
   4752     uint8_t tid)
   4753 {
   4754 	struct ieee80211_tx_ba *ba = &ni->ni_tx_ba[tid];
   4755 	struct iwn_softc *sc = ic->ic_softc;
   4756 	struct iwn_ops *ops = &sc->ops;
   4757 	struct iwn_node *wn = (void *)ni;
   4758 	struct iwn_node_info node;
   4759 	int error;
   4760 
   4761 	/* Enable TX for the specified RA/TID. */
   4762 	wn->disable_tid &= ~(1 << tid);
   4763 	memset(&node, 0, sizeof node);
   4764 	node.id = wn->id;
   4765 	node.control = IWN_NODE_UPDATE;
   4766 	node.flags = IWN_FLAG_SET_DISABLE_TID;
   4767 	node.disable_tid = htole16(wn->disable_tid);
   4768 	error = ops->add_node(sc, &node, 1);
   4769 	if (error != 0)
   4770 		return error;
   4771 
   4772 	if ((error = iwn_nic_lock(sc)) != 0)
   4773 		return error;
   4774 	ops->ampdu_tx_start(sc, ni, tid, ba->ba_winstart);
   4775 	iwn_nic_unlock(sc);
   4776 	return 0;
   4777 }
   4778 
   4779 static void
   4780 iwn_ampdu_tx_stop(struct ieee80211com *ic, struct ieee80211_node *ni,
   4781     uint8_t tid)
   4782 {
   4783 	struct ieee80211_tx_ba *ba = &ni->ni_tx_ba[tid];
   4784 	struct iwn_softc *sc = ic->ic_softc;
   4785 	struct iwn_ops *ops = &sc->ops;
   4786 
   4787 	if (iwn_nic_lock(sc) != 0)
   4788 		return;
   4789 	ops->ampdu_tx_stop(sc, tid, ba->ba_winstart);
   4790 	iwn_nic_unlock(sc);
   4791 }
   4792 
   4793 static void
   4794 iwn4965_ampdu_tx_start(struct iwn_softc *sc, struct ieee80211_node *ni,
   4795     uint8_t tid, uint16_t ssn)
   4796 {
   4797 	struct iwn_node *wn = (void *)ni;
   4798 	int qid = 7 + tid;
   4799 
   4800 	/* Stop TX scheduler while we're changing its configuration. */
   4801 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
   4802 	    IWN4965_TXQ_STATUS_CHGACT);
   4803 
   4804 	/* Assign RA/TID translation to the queue. */
   4805 	iwn_mem_write_2(sc, sc->sched_base + IWN4965_SCHED_TRANS_TBL(qid),
   4806 	    wn->id << 4 | tid);
   4807 
   4808 	/* Enable chain-building mode for the queue. */
   4809 	iwn_prph_setbits(sc, IWN4965_SCHED_QCHAIN_SEL, 1 << qid);
   4810 
   4811 	/* Set starting sequence number from the ADDBA request. */
   4812 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
   4813 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), ssn);
   4814 
   4815 	/* Set scheduler window size. */
   4816 	iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid),
   4817 	    IWN_SCHED_WINSZ);
   4818 	/* Set scheduler frame limit. */
   4819 	iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid) + 4,
   4820 	    IWN_SCHED_LIMIT << 16);
   4821 
   4822 	/* Enable interrupts for the queue. */
   4823 	iwn_prph_setbits(sc, IWN4965_SCHED_INTR_MASK, 1 << qid);
   4824 
   4825 	/* Mark the queue as active. */
   4826 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
   4827 	    IWN4965_TXQ_STATUS_ACTIVE | IWN4965_TXQ_STATUS_AGGR_ENA |
   4828 	    iwn_tid2fifo[tid] << 1);
   4829 }
   4830 
   4831 static void
   4832 iwn4965_ampdu_tx_stop(struct iwn_softc *sc, uint8_t tid, uint16_t ssn)
   4833 {
   4834 	int qid = 7 + tid;
   4835 
   4836 	/* Stop TX scheduler while we're changing its configuration. */
   4837 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
   4838 	    IWN4965_TXQ_STATUS_CHGACT);
   4839 
   4840 	/* Set starting sequence number from the ADDBA request. */
   4841 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
   4842 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), ssn);
   4843 
   4844 	/* Disable interrupts for the queue. */
   4845 	iwn_prph_clrbits(sc, IWN4965_SCHED_INTR_MASK, 1 << qid);
   4846 
   4847 	/* Mark the queue as inactive. */
   4848 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
   4849 	    IWN4965_TXQ_STATUS_INACTIVE | iwn_tid2fifo[tid] << 1);
   4850 }
   4851 
   4852 static void
   4853 iwn5000_ampdu_tx_start(struct iwn_softc *sc, struct ieee80211_node *ni,
   4854     uint8_t tid, uint16_t ssn)
   4855 {
   4856 	struct iwn_node *wn = (void *)ni;
   4857 	int qid = 10 + tid;
   4858 
   4859 	/* Stop TX scheduler while we're changing its configuration. */
   4860 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
   4861 	    IWN5000_TXQ_STATUS_CHGACT);
   4862 
   4863 	/* Assign RA/TID translation to the queue. */
   4864 	iwn_mem_write_2(sc, sc->sched_base + IWN5000_SCHED_TRANS_TBL(qid),
   4865 	    wn->id << 4 | tid);
   4866 
   4867 	/* Enable chain-building mode for the queue. */
   4868 	iwn_prph_setbits(sc, IWN5000_SCHED_QCHAIN_SEL, 1 << qid);
   4869 
   4870 	/* Enable aggregation for the queue. */
   4871 	iwn_prph_setbits(sc, IWN5000_SCHED_AGGR_SEL, 1 << qid);
   4872 
   4873 	/* Set starting sequence number from the ADDBA request. */
   4874 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
   4875 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), ssn);
   4876 
   4877 	/* Set scheduler window size and frame limit. */
   4878 	iwn_mem_write(sc, sc->sched_base + IWN5000_SCHED_QUEUE_OFFSET(qid) + 4,
   4879 	    IWN_SCHED_LIMIT << 16 | IWN_SCHED_WINSZ);
   4880 
   4881 	/* Enable interrupts for the queue. */
   4882 	iwn_prph_setbits(sc, IWN5000_SCHED_INTR_MASK, 1 << qid);
   4883 
   4884 	/* Mark the queue as active. */
   4885 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
   4886 	    IWN5000_TXQ_STATUS_ACTIVE | iwn_tid2fifo[tid]);
   4887 }
   4888 
   4889 static void
   4890 iwn5000_ampdu_tx_stop(struct iwn_softc *sc, uint8_t tid, uint16_t ssn)
   4891 {
   4892 	int qid = 10 + tid;
   4893 
   4894 	/* Stop TX scheduler while we're changing its configuration. */
   4895 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
   4896 	    IWN5000_TXQ_STATUS_CHGACT);
   4897 
   4898 	/* Disable aggregation for the queue. */
   4899 	iwn_prph_clrbits(sc, IWN5000_SCHED_AGGR_SEL, 1 << qid);
   4900 
   4901 	/* Set starting sequence number from the ADDBA request. */
   4902 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
   4903 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), ssn);
   4904 
   4905 	/* Disable interrupts for the queue. */
   4906 	iwn_prph_clrbits(sc, IWN5000_SCHED_INTR_MASK, 1 << qid);
   4907 
   4908 	/* Mark the queue as inactive. */
   4909 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
   4910 	    IWN5000_TXQ_STATUS_INACTIVE | iwn_tid2fifo[tid]);
   4911 }
   4912 #endif	/* !IEEE80211_NO_HT */
   4913 
   4914 /*
   4915  * Query calibration tables from the initialization firmware.  We do this
   4916  * only once at first boot.  Called from a process context.
   4917  */
   4918 static int
   4919 iwn5000_query_calibration(struct iwn_softc *sc)
   4920 {
   4921 	struct iwn5000_calib_config cmd;
   4922 	int error;
   4923 
   4924 	memset(&cmd, 0, sizeof cmd);
   4925 	cmd.ucode.once.enable = 0xffffffff;
   4926 	cmd.ucode.once.start  = 0xffffffff;
   4927 	cmd.ucode.once.send   = 0xffffffff;
   4928 	cmd.ucode.flags       = 0xffffffff;
   4929 	DPRINTF(("sending calibration query\n"));
   4930 	error = iwn_cmd(sc, IWN5000_CMD_CALIB_CONFIG, &cmd, sizeof cmd, 0);
   4931 	if (error != 0)
   4932 		return error;
   4933 
   4934 	/* Wait at most two seconds for calibration to complete. */
   4935 	if (!(sc->sc_flags & IWN_FLAG_CALIB_DONE))
   4936 		error = tsleep(sc, PCATCH, "iwncal", 2 * hz);
   4937 	return error;
   4938 }
   4939 
   4940 /*
   4941  * Send calibration results to the runtime firmware.  These results were
   4942  * obtained on first boot from the initialization firmware.
   4943  */
   4944 static int
   4945 iwn5000_send_calibration(struct iwn_softc *sc)
   4946 {
   4947 	int idx, error;
   4948 
   4949 	for (idx = 0; idx < 5; idx++) {
   4950 		if (sc->calibcmd[idx].buf == NULL)
   4951 			continue;	/* No results available. */
   4952 		DPRINTF(("send calibration result idx=%d len=%d\n",
   4953 		    idx, sc->calibcmd[idx].len));
   4954 		error = iwn_cmd(sc, IWN_CMD_PHY_CALIB, sc->calibcmd[idx].buf,
   4955 		    sc->calibcmd[idx].len, 0);
   4956 		if (error != 0) {
   4957 			aprint_error_dev(sc->sc_dev,
   4958 			    "could not send calibration result\n");
   4959 			return error;
   4960 		}
   4961 	}
   4962 	return 0;
   4963 }
   4964 
   4965 static int
   4966 iwn5000_send_wimax_coex(struct iwn_softc *sc)
   4967 {
   4968 	struct iwn5000_wimax_coex wimax;
   4969 
   4970 #ifdef notyet
   4971 	if (sc->hw_type == IWN_HW_REV_TYPE_6050) {
   4972 		/* Enable WiMAX coexistence for combo adapters. */
   4973 		wimax.flags =
   4974 		    IWN_WIMAX_COEX_ASSOC_WA_UNMASK |
   4975 		    IWN_WIMAX_COEX_UNASSOC_WA_UNMASK |
   4976 		    IWN_WIMAX_COEX_STA_TABLE_VALID |
   4977 		    IWN_WIMAX_COEX_ENABLE;
   4978 		memcpy(wimax.events, iwn6050_wimax_events,
   4979 		    sizeof iwn6050_wimax_events);
   4980 	} else
   4981 #endif
   4982 	{
   4983 		/* Disable WiMAX coexistence. */
   4984 		wimax.flags = 0;
   4985 		memset(wimax.events, 0, sizeof wimax.events);
   4986 	}
   4987 	DPRINTF(("Configuring WiMAX coexistence\n"));
   4988 	return iwn_cmd(sc, IWN5000_CMD_WIMAX_COEX, &wimax, sizeof wimax, 0);
   4989 }
   4990 
   4991 /*
   4992  * This function is called after the runtime firmware notifies us of its
   4993  * readiness (called in a process context).
   4994  */
   4995 static int
   4996 iwn4965_post_alive(struct iwn_softc *sc)
   4997 {
   4998 	int error, qid;
   4999 
   5000 	if ((error = iwn_nic_lock(sc)) != 0)
   5001 		return error;
   5002 
   5003 	/* Clear TX scheduler state in SRAM. */
   5004 	sc->sched_base = iwn_prph_read(sc, IWN_SCHED_SRAM_ADDR);
   5005 	iwn_mem_set_region_4(sc, sc->sched_base + IWN4965_SCHED_CTX_OFF, 0,
   5006 	    IWN4965_SCHED_CTX_LEN / sizeof (uint32_t));
   5007 
   5008 	/* Set physical address of TX scheduler rings (1KB aligned). */
   5009 	iwn_prph_write(sc, IWN4965_SCHED_DRAM_ADDR, sc->sched_dma.paddr >> 10);
   5010 
   5011 	IWN_SETBITS(sc, IWN_FH_TX_CHICKEN, IWN_FH_TX_CHICKEN_SCHED_RETRY);
   5012 
   5013 	/* Disable chain mode for all our 16 queues. */
   5014 	iwn_prph_write(sc, IWN4965_SCHED_QCHAIN_SEL, 0);
   5015 
   5016 	for (qid = 0; qid < IWN4965_NTXQUEUES; qid++) {
   5017 		iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), 0);
   5018 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | 0);
   5019 
   5020 		/* Set scheduler window size. */
   5021 		iwn_mem_write(sc, sc->sched_base +
   5022 		    IWN4965_SCHED_QUEUE_OFFSET(qid), IWN_SCHED_WINSZ);
   5023 		/* Set scheduler frame limit. */
   5024 		iwn_mem_write(sc, sc->sched_base +
   5025 		    IWN4965_SCHED_QUEUE_OFFSET(qid) + 4,
   5026 		    IWN_SCHED_LIMIT << 16);
   5027 	}
   5028 
   5029 	/* Enable interrupts for all our 16 queues. */
   5030 	iwn_prph_write(sc, IWN4965_SCHED_INTR_MASK, 0xffff);
   5031 	/* Identify TX FIFO rings (0-7). */
   5032 	iwn_prph_write(sc, IWN4965_SCHED_TXFACT, 0xff);
   5033 
   5034 	/* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
   5035 	for (qid = 0; qid < 7; qid++) {
   5036 		static uint8_t qid2fifo[] = { 3, 2, 1, 0, 4, 5, 6 };
   5037 		iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
   5038 		    IWN4965_TXQ_STATUS_ACTIVE | qid2fifo[qid] << 1);
   5039 	}
   5040 	iwn_nic_unlock(sc);
   5041 	return 0;
   5042 }
   5043 
   5044 /*
   5045  * This function is called after the initialization or runtime firmware
   5046  * notifies us of its readiness (called in a process context).
   5047  */
   5048 static int
   5049 iwn5000_post_alive(struct iwn_softc *sc)
   5050 {
   5051 	int error, qid;
   5052 
   5053 	/* Switch to using ICT interrupt mode. */
   5054 	iwn5000_ict_reset(sc);
   5055 
   5056 	if ((error = iwn_nic_lock(sc)) != 0)
   5057 		return error;
   5058 
   5059 	/* Clear TX scheduler state in SRAM. */
   5060 	sc->sched_base = iwn_prph_read(sc, IWN_SCHED_SRAM_ADDR);
   5061 	iwn_mem_set_region_4(sc, sc->sched_base + IWN5000_SCHED_CTX_OFF, 0,
   5062 	    IWN5000_SCHED_CTX_LEN / sizeof (uint32_t));
   5063 
   5064 	/* Set physical address of TX scheduler rings (1KB aligned). */
   5065 	iwn_prph_write(sc, IWN5000_SCHED_DRAM_ADDR, sc->sched_dma.paddr >> 10);
   5066 
   5067 	IWN_SETBITS(sc, IWN_FH_TX_CHICKEN, IWN_FH_TX_CHICKEN_SCHED_RETRY);
   5068 
   5069 	/* Enable chain mode for all queues, except command queue. */
   5070 	iwn_prph_write(sc, IWN5000_SCHED_QCHAIN_SEL, 0xfffef);
   5071 	iwn_prph_write(sc, IWN5000_SCHED_AGGR_SEL, 0);
   5072 
   5073 	for (qid = 0; qid < IWN5000_NTXQUEUES; qid++) {
   5074 		iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), 0);
   5075 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | 0);
   5076 
   5077 		iwn_mem_write(sc, sc->sched_base +
   5078 		    IWN5000_SCHED_QUEUE_OFFSET(qid), 0);
   5079 		/* Set scheduler window size and frame limit. */
   5080 		iwn_mem_write(sc, sc->sched_base +
   5081 		    IWN5000_SCHED_QUEUE_OFFSET(qid) + 4,
   5082 		    IWN_SCHED_LIMIT << 16 | IWN_SCHED_WINSZ);
   5083 	}
   5084 
   5085 	/* Enable interrupts for all our 20 queues. */
   5086 	iwn_prph_write(sc, IWN5000_SCHED_INTR_MASK, 0xfffff);
   5087 	/* Identify TX FIFO rings (0-7). */
   5088 	iwn_prph_write(sc, IWN5000_SCHED_TXFACT, 0xff);
   5089 
   5090 	/* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
   5091 	for (qid = 0; qid < 7; qid++) {
   5092 		static uint8_t qid2fifo[] = { 3, 2, 1, 0, 7, 5, 6 };
   5093 		iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
   5094 		    IWN5000_TXQ_STATUS_ACTIVE | qid2fifo[qid]);
   5095 	}
   5096 	iwn_nic_unlock(sc);
   5097 
   5098 	/* Configure WiMAX coexistence for combo adapters. */
   5099 	error = iwn5000_send_wimax_coex(sc);
   5100 	if (error != 0) {
   5101 		aprint_error_dev(sc->sc_dev,
   5102 		    "could not configure WiMAX coexistence\n");
   5103 		return error;
   5104 	}
   5105 	if (sc->hw_type != IWN_HW_REV_TYPE_5150) {
   5106 		struct iwn5000_phy_calib_crystal cmd;
   5107 
   5108 		/* Perform crystal calibration. */
   5109 		memset(&cmd, 0, sizeof cmd);
   5110 		cmd.code = IWN5000_PHY_CALIB_CRYSTAL;
   5111 		cmd.ngroups = 1;
   5112 		cmd.isvalid = 1;
   5113 		cmd.cap_pin[0] = le32toh(sc->eeprom_crystal) & 0xff;
   5114 		cmd.cap_pin[1] = (le32toh(sc->eeprom_crystal) >> 16) & 0xff;
   5115 		DPRINTF(("sending crystal calibration %d, %d\n",
   5116 		    cmd.cap_pin[0], cmd.cap_pin[1]));
   5117 		error = iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
   5118 		if (error != 0) {
   5119 			aprint_error_dev(sc->sc_dev,
   5120 			    "crystal calibration failed\n");
   5121 			return error;
   5122 		}
   5123 	}
   5124 	if (!(sc->sc_flags & IWN_FLAG_CALIB_DONE)) {
   5125 		/* Query calibration from the initialization firmware. */
   5126 		if ((error = iwn5000_query_calibration(sc)) != 0) {
   5127 			aprint_error_dev(sc->sc_dev,
   5128 			    "could not query calibration\n");
   5129 			return error;
   5130 		}
   5131 		/*
   5132 		 * We have the calibration results now, reboot with the
   5133 		 * runtime firmware (call ourselves recursively!)
   5134 		 */
   5135 		iwn_hw_stop(sc);
   5136 		error = iwn_hw_init(sc);
   5137 	} else {
   5138 		/* Send calibration results to runtime firmware. */
   5139 		error = iwn5000_send_calibration(sc);
   5140 	}
   5141 	return error;
   5142 }
   5143 
   5144 /*
   5145  * The firmware boot code is small and is intended to be copied directly into
   5146  * the NIC internal memory (no DMA transfer).
   5147  */
   5148 static int
   5149 iwn4965_load_bootcode(struct iwn_softc *sc, const uint8_t *ucode, int size)
   5150 {
   5151 	int error, ntries;
   5152 
   5153 	size /= sizeof (uint32_t);
   5154 
   5155 	if ((error = iwn_nic_lock(sc)) != 0)
   5156 		return error;
   5157 
   5158 	/* Copy microcode image into NIC memory. */
   5159 	iwn_prph_write_region_4(sc, IWN_BSM_SRAM_BASE,
   5160 	    (const uint32_t *)ucode, size);
   5161 
   5162 	iwn_prph_write(sc, IWN_BSM_WR_MEM_SRC, 0);
   5163 	iwn_prph_write(sc, IWN_BSM_WR_MEM_DST, IWN_FW_TEXT_BASE);
   5164 	iwn_prph_write(sc, IWN_BSM_WR_DWCOUNT, size);
   5165 
   5166 	/* Start boot load now. */
   5167 	iwn_prph_write(sc, IWN_BSM_WR_CTRL, IWN_BSM_WR_CTRL_START);
   5168 
   5169 	/* Wait for transfer to complete. */
   5170 	for (ntries = 0; ntries < 1000; ntries++) {
   5171 		if (!(iwn_prph_read(sc, IWN_BSM_WR_CTRL) &
   5172 		    IWN_BSM_WR_CTRL_START))
   5173 			break;
   5174 		DELAY(10);
   5175 	}
   5176 	if (ntries == 1000) {
   5177 		aprint_error_dev(sc->sc_dev,
   5178 		    "could not load boot firmware\n");
   5179 		iwn_nic_unlock(sc);
   5180 		return ETIMEDOUT;
   5181 	}
   5182 
   5183 	/* Enable boot after power up. */
   5184 	iwn_prph_write(sc, IWN_BSM_WR_CTRL, IWN_BSM_WR_CTRL_START_EN);
   5185 
   5186 	iwn_nic_unlock(sc);
   5187 	return 0;
   5188 }
   5189 
   5190 static int
   5191 iwn4965_load_firmware(struct iwn_softc *sc)
   5192 {
   5193 	struct iwn_fw_info *fw = &sc->fw;
   5194 	struct iwn_dma_info *dma = &sc->fw_dma;
   5195 	int error;
   5196 
   5197 	/* Copy initialization sections into pre-allocated DMA-safe memory. */
   5198 	memcpy(dma->vaddr, fw->init.data, fw->init.datasz);
   5199 	bus_dmamap_sync(sc->sc_dmat, dma->map, 0, fw->init.datasz,
   5200 	    BUS_DMASYNC_PREWRITE);
   5201 	memcpy((char *)dma->vaddr + IWN4965_FW_DATA_MAXSZ,
   5202 	    fw->init.text, fw->init.textsz);
   5203 	bus_dmamap_sync(sc->sc_dmat, dma->map, IWN4965_FW_DATA_MAXSZ,
   5204 	    fw->init.textsz, BUS_DMASYNC_PREWRITE);
   5205 
   5206 	/* Tell adapter where to find initialization sections. */
   5207 	if ((error = iwn_nic_lock(sc)) != 0)
   5208 		return error;
   5209 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_ADDR, dma->paddr >> 4);
   5210 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_SIZE, fw->init.datasz);
   5211 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_ADDR,
   5212 	    (dma->paddr + IWN4965_FW_DATA_MAXSZ) >> 4);
   5213 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_SIZE, fw->init.textsz);
   5214 	iwn_nic_unlock(sc);
   5215 
   5216 	/* Load firmware boot code. */
   5217 	error = iwn4965_load_bootcode(sc, fw->boot.text, fw->boot.textsz);
   5218 	if (error != 0) {
   5219 		aprint_error_dev(sc->sc_dev,
   5220 		    "could not load boot firmware\n");
   5221 		return error;
   5222 	}
   5223 	/* Now press "execute". */
   5224 	IWN_WRITE(sc, IWN_RESET, 0);
   5225 
   5226 	/* Wait at most one second for first alive notification. */
   5227 	if ((error = tsleep(sc, PCATCH, "iwninit", hz)) != 0) {
   5228 		aprint_error_dev(sc->sc_dev,
   5229 		    "timeout waiting for adapter to initialize\n");
   5230 		return error;
   5231 	}
   5232 
   5233 	/* Retrieve current temperature for initial TX power calibration. */
   5234 	sc->rawtemp = sc->ucode_info.temp[3].chan20MHz;
   5235 	sc->temp = iwn4965_get_temperature(sc);
   5236 
   5237 	/* Copy runtime sections into pre-allocated DMA-safe memory. */
   5238 	memcpy(dma->vaddr, fw->main.data, fw->main.datasz);
   5239 	bus_dmamap_sync(sc->sc_dmat, dma->map, 0, fw->main.datasz,
   5240 	    BUS_DMASYNC_PREWRITE);
   5241 	memcpy((char *)dma->vaddr + IWN4965_FW_DATA_MAXSZ,
   5242 	    fw->main.text, fw->main.textsz);
   5243 	bus_dmamap_sync(sc->sc_dmat, dma->map, IWN4965_FW_DATA_MAXSZ,
   5244 	    fw->main.textsz, BUS_DMASYNC_PREWRITE);
   5245 
   5246 	/* Tell adapter where to find runtime sections. */
   5247 	if ((error = iwn_nic_lock(sc)) != 0)
   5248 		return error;
   5249 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_ADDR, dma->paddr >> 4);
   5250 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_SIZE, fw->main.datasz);
   5251 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_ADDR,
   5252 	    (dma->paddr + IWN4965_FW_DATA_MAXSZ) >> 4);
   5253 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_SIZE,
   5254 	    IWN_FW_UPDATED | fw->main.textsz);
   5255 	iwn_nic_unlock(sc);
   5256 
   5257 	return 0;
   5258 }
   5259 
   5260 static int
   5261 iwn5000_load_firmware_section(struct iwn_softc *sc, uint32_t dst,
   5262     const uint8_t *section, int size)
   5263 {
   5264 	struct iwn_dma_info *dma = &sc->fw_dma;
   5265 	int error;
   5266 
   5267 	/* Copy firmware section into pre-allocated DMA-safe memory. */
   5268 	memcpy(dma->vaddr, section, size);
   5269 	bus_dmamap_sync(sc->sc_dmat, dma->map, 0, size, BUS_DMASYNC_PREWRITE);
   5270 
   5271 	if ((error = iwn_nic_lock(sc)) != 0)
   5272 		return error;
   5273 
   5274 	IWN_WRITE(sc, IWN_FH_TX_CONFIG(IWN_SRVC_DMACHNL),
   5275 	    IWN_FH_TX_CONFIG_DMA_PAUSE);
   5276 
   5277 	IWN_WRITE(sc, IWN_FH_SRAM_ADDR(IWN_SRVC_DMACHNL), dst);
   5278 	IWN_WRITE(sc, IWN_FH_TFBD_CTRL0(IWN_SRVC_DMACHNL),
   5279 	    IWN_LOADDR(dma->paddr));
   5280 	IWN_WRITE(sc, IWN_FH_TFBD_CTRL1(IWN_SRVC_DMACHNL),
   5281 	    IWN_HIADDR(dma->paddr) << 28 | size);
   5282 	IWN_WRITE(sc, IWN_FH_TXBUF_STATUS(IWN_SRVC_DMACHNL),
   5283 	    IWN_FH_TXBUF_STATUS_TBNUM(1) |
   5284 	    IWN_FH_TXBUF_STATUS_TBIDX(1) |
   5285 	    IWN_FH_TXBUF_STATUS_TFBD_VALID);
   5286 
   5287 	/* Kick Flow Handler to start DMA transfer. */
   5288 	IWN_WRITE(sc, IWN_FH_TX_CONFIG(IWN_SRVC_DMACHNL),
   5289 	    IWN_FH_TX_CONFIG_DMA_ENA | IWN_FH_TX_CONFIG_CIRQ_HOST_ENDTFD);
   5290 
   5291 	iwn_nic_unlock(sc);
   5292 
   5293 	/* Wait at most five seconds for FH DMA transfer to complete. */
   5294 	return tsleep(sc, PCATCH, "iwninit", 5 * hz);
   5295 }
   5296 
   5297 static int
   5298 iwn5000_load_firmware(struct iwn_softc *sc)
   5299 {
   5300 	struct iwn_fw_part *fw;
   5301 	int error;
   5302 
   5303 	/* Load the initialization firmware on first boot only. */
   5304 	fw = (sc->sc_flags & IWN_FLAG_CALIB_DONE) ?
   5305 	    &sc->fw.main : &sc->fw.init;
   5306 
   5307 	error = iwn5000_load_firmware_section(sc, IWN_FW_TEXT_BASE,
   5308 	    fw->text, fw->textsz);
   5309 	if (error != 0) {
   5310 		aprint_error_dev(sc->sc_dev,
   5311 		    "could not load firmware %s section\n", ".text");
   5312 		return error;
   5313 	}
   5314 	error = iwn5000_load_firmware_section(sc, IWN_FW_DATA_BASE,
   5315 	    fw->data, fw->datasz);
   5316 	if (error != 0) {
   5317 		aprint_error_dev(sc->sc_dev,
   5318 		    "could not load firmware %s section\n", ".data");
   5319 		return error;
   5320 	}
   5321 
   5322 	/* Now press "execute". */
   5323 	IWN_WRITE(sc, IWN_RESET, 0);
   5324 	return 0;
   5325 }
   5326 
   5327 /*
   5328  * Extract text and data sections from a legacy firmware image.
   5329  */
   5330 static int
   5331 iwn_read_firmware_leg(struct iwn_softc *sc, struct iwn_fw_info *fw)
   5332 {
   5333 	const uint32_t *ptr;
   5334 	size_t hdrlen = 24;
   5335 	uint32_t rev;
   5336 
   5337 	ptr = (const uint32_t *)fw->data;
   5338 	rev = le32toh(*ptr++);
   5339 
   5340 	/* Check firmware API version. */
   5341 	if (IWN_FW_API(rev) <= 1) {
   5342 		aprint_error_dev(sc->sc_dev,
   5343 		    "bad firmware, need API version >=2\n");
   5344 		return EINVAL;
   5345 	}
   5346 	if (IWN_FW_API(rev) >= 3) {
   5347 		/* Skip build number (version 2 header). */
   5348 		hdrlen += 4;
   5349 		ptr++;
   5350 	}
   5351 	if (fw->size < hdrlen) {
   5352 		aprint_error_dev(sc->sc_dev,
   5353 		    "firmware too short: %zd bytes\n", fw->size);
   5354 		return EINVAL;
   5355 	}
   5356 	fw->main.textsz = le32toh(*ptr++);
   5357 	fw->main.datasz = le32toh(*ptr++);
   5358 	fw->init.textsz = le32toh(*ptr++);
   5359 	fw->init.datasz = le32toh(*ptr++);
   5360 	fw->boot.textsz = le32toh(*ptr++);
   5361 
   5362 	/* Check that all firmware sections fit. */
   5363 	if (fw->size < hdrlen + fw->main.textsz + fw->main.datasz +
   5364 	    fw->init.textsz + fw->init.datasz + fw->boot.textsz) {
   5365 		aprint_error_dev(sc->sc_dev,
   5366 		    "firmware too short: %zd bytes\n", fw->size);
   5367 		return EINVAL;
   5368 	}
   5369 
   5370 	/* Get pointers to firmware sections. */
   5371 	fw->main.text = (const uint8_t *)ptr;
   5372 	fw->main.data = fw->main.text + fw->main.textsz;
   5373 	fw->init.text = fw->main.data + fw->main.datasz;
   5374 	fw->init.data = fw->init.text + fw->init.textsz;
   5375 	fw->boot.text = fw->init.data + fw->init.datasz;
   5376 	return 0;
   5377 }
   5378 
   5379 /*
   5380  * Extract text and data sections from a TLV firmware image.
   5381  */
   5382 static int
   5383 iwn_read_firmware_tlv(struct iwn_softc *sc, struct iwn_fw_info *fw,
   5384     uint16_t alt)
   5385 {
   5386 	const struct iwn_fw_tlv_hdr *hdr;
   5387 	const struct iwn_fw_tlv *tlv;
   5388 	const uint8_t *ptr, *end;
   5389 	uint64_t altmask;
   5390 	uint32_t len;
   5391 
   5392 	if (fw->size < sizeof (*hdr)) {
   5393 		aprint_error_dev(sc->sc_dev,
   5394 		    "firmware too short: %zd bytes\n", fw->size);
   5395 		return EINVAL;
   5396 	}
   5397 	hdr = (const struct iwn_fw_tlv_hdr *)fw->data;
   5398 	if (hdr->signature != htole32(IWN_FW_SIGNATURE)) {
   5399 		aprint_error_dev(sc->sc_dev,
   5400 		    "bad firmware signature 0x%08x\n", le32toh(hdr->signature));
   5401 		return EINVAL;
   5402 	}
   5403 	DPRINTF(("FW: \"%.64s\", build 0x%x\n", hdr->descr,
   5404 	    le32toh(hdr->build)));
   5405 
   5406 	/*
   5407 	 * Select the closest supported alternative that is less than
   5408 	 * or equal to the specified one.
   5409 	 */
   5410 	altmask = le64toh(hdr->altmask);
   5411 	while (alt > 0 && !(altmask & (1ULL << alt)))
   5412 		alt--;	/* Downgrade. */
   5413 	DPRINTF(("using alternative %d\n", alt));
   5414 
   5415 	ptr = (const uint8_t *)(hdr + 1);
   5416 	end = (const uint8_t *)(fw->data + fw->size);
   5417 
   5418 	/* Parse type-length-value fields. */
   5419 	while (ptr + sizeof (*tlv) <= end) {
   5420 		tlv = (const struct iwn_fw_tlv *)ptr;
   5421 		len = le32toh(tlv->len);
   5422 
   5423 		ptr += sizeof (*tlv);
   5424 		if (ptr + len > end) {
   5425 			aprint_error_dev(sc->sc_dev,
   5426 			    "firmware too short: %zd bytes\n", fw->size);
   5427 			return EINVAL;
   5428 		}
   5429 		/* Skip other alternatives. */
   5430 		if (tlv->alt != 0 && tlv->alt != htole16(alt))
   5431 			goto next;
   5432 
   5433 		switch (le16toh(tlv->type)) {
   5434 		case IWN_FW_TLV_MAIN_TEXT:
   5435 			fw->main.text = ptr;
   5436 			fw->main.textsz = len;
   5437 			break;
   5438 		case IWN_FW_TLV_MAIN_DATA:
   5439 			fw->main.data = ptr;
   5440 			fw->main.datasz = len;
   5441 			break;
   5442 		case IWN_FW_TLV_INIT_TEXT:
   5443 			fw->init.text = ptr;
   5444 			fw->init.textsz = len;
   5445 			break;
   5446 		case IWN_FW_TLV_INIT_DATA:
   5447 			fw->init.data = ptr;
   5448 			fw->init.datasz = len;
   5449 			break;
   5450 		case IWN_FW_TLV_BOOT_TEXT:
   5451 			fw->boot.text = ptr;
   5452 			fw->boot.textsz = len;
   5453 			break;
   5454 		default:
   5455 			DPRINTF(("TLV type %d not handled\n",
   5456 			    le16toh(tlv->type)));
   5457 			break;
   5458 		}
   5459  next:		/* TLV fields are 32-bit aligned. */
   5460 		ptr += (len + 3) & ~3;
   5461 	}
   5462 	return 0;
   5463 }
   5464 
   5465 static int
   5466 iwn_read_firmware(struct iwn_softc *sc)
   5467 {
   5468 	struct iwn_fw_info *fw = &sc->fw;
   5469 	firmware_handle_t fwh;
   5470 	int error;
   5471 
   5472 	/* Initialize for error returns */
   5473 	fw->data = NULL;
   5474 	fw->size = 0;
   5475 
   5476 	/* Open firmware image. */
   5477 	if ((error = firmware_open("if_iwn", sc->fwname, &fwh)) != 0) {
   5478 		aprint_error_dev(sc->sc_dev,
   5479 		    "could not get firmware handle %s\n", sc->fwname);
   5480 		return error;
   5481 	}
   5482 	fw->size = firmware_get_size(fwh);
   5483 	if (fw->size < sizeof (uint32_t)) {
   5484 		aprint_error_dev(sc->sc_dev,
   5485 		    "firmware too short: %zd bytes\n", fw->size);
   5486 		firmware_close(fwh);
   5487 		return EINVAL;
   5488 	}
   5489 
   5490 	/* Read the firmware. */
   5491 	fw->data = firmware_malloc(fw->size);
   5492 	if (fw->data == NULL) {
   5493 		aprint_error_dev(sc->sc_dev,
   5494 		    "not enough memory to stock firmware %s\n", sc->fwname);
   5495 		firmware_close(fwh);
   5496 		return ENOMEM;
   5497 	}
   5498 	error = firmware_read(fwh, 0, fw->data, fw->size);
   5499 	firmware_close(fwh);
   5500 	if (error != 0) {
   5501 		aprint_error_dev(sc->sc_dev,
   5502 		    "could not read firmware %s\n", sc->fwname);
   5503 		goto out;
   5504 	}
   5505 
   5506 	/* Retrieve text and data sections. */
   5507 	if (*(const uint32_t *)fw->data != 0)	/* Legacy image. */
   5508 		error = iwn_read_firmware_leg(sc, fw);
   5509 	else
   5510 		error = iwn_read_firmware_tlv(sc, fw, 1);
   5511 	if (error != 0) {
   5512 		aprint_error_dev(sc->sc_dev,
   5513 		    "could not read firmware sections\n");
   5514 		goto out;
   5515 	}
   5516 
   5517 	/* Make sure text and data sections fit in hardware memory. */
   5518 	if (fw->main.textsz > sc->fw_text_maxsz ||
   5519 	    fw->main.datasz > sc->fw_data_maxsz ||
   5520 	    fw->init.textsz > sc->fw_text_maxsz ||
   5521 	    fw->init.datasz > sc->fw_data_maxsz ||
   5522 	    fw->boot.textsz > IWN_FW_BOOT_TEXT_MAXSZ ||
   5523 	    (fw->boot.textsz & 3) != 0) {
   5524 		aprint_error_dev(sc->sc_dev,
   5525 		    "firmware sections too large\n");
   5526 		goto out;
   5527 	}
   5528 
   5529 	/* We can proceed with loading the firmware. */
   5530 	return 0;
   5531 out:
   5532 	firmware_free(fw->data, fw->size);
   5533 	fw->data = NULL;
   5534 	fw->size = 0;
   5535 	return error ? error : EINVAL;
   5536 }
   5537 
   5538 static int
   5539 iwn_clock_wait(struct iwn_softc *sc)
   5540 {
   5541 	int ntries;
   5542 
   5543 	/* Set "initialization complete" bit. */
   5544 	IWN_SETBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_INIT_DONE);
   5545 
   5546 	/* Wait for clock stabilization. */
   5547 	for (ntries = 0; ntries < 2500; ntries++) {
   5548 		if (IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_MAC_CLOCK_READY)
   5549 			return 0;
   5550 		DELAY(10);
   5551 	}
   5552 	aprint_error_dev(sc->sc_dev,
   5553 	    "timeout waiting for clock stabilization\n");
   5554 	return ETIMEDOUT;
   5555 }
   5556 
   5557 static int
   5558 iwn_apm_init(struct iwn_softc *sc)
   5559 {
   5560 	pcireg_t reg;
   5561 	int error;
   5562 
   5563 	/* Disable L0s exit timer (NMI bug workaround). */
   5564 	IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_DIS_L0S_TIMER);
   5565 	/* Don't wait for ICH L0s (ICH bug workaround). */
   5566 	IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_L1A_NO_L0S_RX);
   5567 
   5568 	/* Set FH wait threshold to max (HW bug under stress workaround). */
   5569 	IWN_SETBITS(sc, IWN_DBG_HPET_MEM, 0xffff0000);
   5570 
   5571 	/* Enable HAP INTA to move adapter from L1a to L0s. */
   5572 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_HAP_WAKE_L1A);
   5573 
   5574 	/* Retrieve PCIe Active State Power Management (ASPM). */
   5575 	reg = pci_conf_read(sc->sc_pct, sc->sc_pcitag,
   5576 	    sc->sc_cap_off + PCIE_LCSR);
   5577 	/* Workaround for HW instability in PCIe L0->L0s->L1 transition. */
   5578 	if (reg & PCIE_LCSR_ASPM_L1)	/* L1 Entry enabled. */
   5579 		IWN_SETBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA);
   5580 	else
   5581 		IWN_CLRBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA);
   5582 
   5583 	if (sc->hw_type != IWN_HW_REV_TYPE_4965 &&
   5584 	    sc->hw_type <= IWN_HW_REV_TYPE_1000)
   5585 		IWN_SETBITS(sc, IWN_ANA_PLL, IWN_ANA_PLL_INIT);
   5586 
   5587 	/* Wait for clock stabilization before accessing prph. */
   5588 	if ((error = iwn_clock_wait(sc)) != 0)
   5589 		return error;
   5590 
   5591 	if ((error = iwn_nic_lock(sc)) != 0)
   5592 		return error;
   5593 	if (sc->hw_type == IWN_HW_REV_TYPE_4965) {
   5594 		/* Enable DMA and BSM (Bootstrap State Machine). */
   5595 		iwn_prph_write(sc, IWN_APMG_CLK_EN,
   5596 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT |
   5597 		    IWN_APMG_CLK_CTRL_BSM_CLK_RQT);
   5598 	} else {
   5599 		/* Enable DMA. */
   5600 		iwn_prph_write(sc, IWN_APMG_CLK_EN,
   5601 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT);
   5602 	}
   5603 	DELAY(20);
   5604 	/* Disable L1-Active. */
   5605 	iwn_prph_setbits(sc, IWN_APMG_PCI_STT, IWN_APMG_PCI_STT_L1A_DIS);
   5606 	iwn_nic_unlock(sc);
   5607 
   5608 	return 0;
   5609 }
   5610 
   5611 static void
   5612 iwn_apm_stop_master(struct iwn_softc *sc)
   5613 {
   5614 	int ntries;
   5615 
   5616 	/* Stop busmaster DMA activity. */
   5617 	IWN_SETBITS(sc, IWN_RESET, IWN_RESET_STOP_MASTER);
   5618 	for (ntries = 0; ntries < 100; ntries++) {
   5619 		if (IWN_READ(sc, IWN_RESET) & IWN_RESET_MASTER_DISABLED)
   5620 			return;
   5621 		DELAY(10);
   5622 	}
   5623 	aprint_error_dev(sc->sc_dev,
   5624 	    "timeout waiting for master\n");
   5625 }
   5626 
   5627 static void
   5628 iwn_apm_stop(struct iwn_softc *sc)
   5629 {
   5630 	iwn_apm_stop_master(sc);
   5631 
   5632 	/* Reset the entire device. */
   5633 	IWN_SETBITS(sc, IWN_RESET, IWN_RESET_SW);
   5634 	DELAY(10);
   5635 	/* Clear "initialization complete" bit. */
   5636 	IWN_CLRBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_INIT_DONE);
   5637 }
   5638 
   5639 static int
   5640 iwn4965_nic_config(struct iwn_softc *sc)
   5641 {
   5642 	if (IWN_RFCFG_TYPE(sc->rfcfg) == 1) {
   5643 		/*
   5644 		 * I don't believe this to be correct but this is what the
   5645 		 * vendor driver is doing. Probably the bits should not be
   5646 		 * shifted in IWN_RFCFG_*.
   5647 		 */
   5648 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
   5649 		    IWN_RFCFG_TYPE(sc->rfcfg) |
   5650 		    IWN_RFCFG_STEP(sc->rfcfg) |
   5651 		    IWN_RFCFG_DASH(sc->rfcfg));
   5652 	}
   5653 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
   5654 	    IWN_HW_IF_CONFIG_RADIO_SI | IWN_HW_IF_CONFIG_MAC_SI);
   5655 	return 0;
   5656 }
   5657 
   5658 static int
   5659 iwn5000_nic_config(struct iwn_softc *sc)
   5660 {
   5661 	uint32_t tmp;
   5662 	int error;
   5663 
   5664 	if (IWN_RFCFG_TYPE(sc->rfcfg) < 3) {
   5665 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
   5666 		    IWN_RFCFG_TYPE(sc->rfcfg) |
   5667 		    IWN_RFCFG_STEP(sc->rfcfg) |
   5668 		    IWN_RFCFG_DASH(sc->rfcfg));
   5669 	}
   5670 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
   5671 	    IWN_HW_IF_CONFIG_RADIO_SI | IWN_HW_IF_CONFIG_MAC_SI);
   5672 
   5673 	if ((error = iwn_nic_lock(sc)) != 0)
   5674 		return error;
   5675 	iwn_prph_setbits(sc, IWN_APMG_PS, IWN_APMG_PS_EARLY_PWROFF_DIS);
   5676 
   5677 	if (sc->hw_type == IWN_HW_REV_TYPE_1000) {
   5678 		/*
   5679 		 * Select first Switching Voltage Regulator (1.32V) to
   5680 		 * solve a stability issue related to noisy DC2DC line
   5681 		 * in the silicon of 1000 Series.
   5682 		 */
   5683 		tmp = iwn_prph_read(sc, IWN_APMG_DIGITAL_SVR);
   5684 		tmp &= ~IWN_APMG_DIGITAL_SVR_VOLTAGE_MASK;
   5685 		tmp |= IWN_APMG_DIGITAL_SVR_VOLTAGE_1_32;
   5686 		iwn_prph_write(sc, IWN_APMG_DIGITAL_SVR, tmp);
   5687 	}
   5688 	iwn_nic_unlock(sc);
   5689 
   5690 	if (sc->sc_flags & IWN_FLAG_INTERNAL_PA) {
   5691 		/* Use internal power amplifier only. */
   5692 		IWN_WRITE(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_RADIO_2X2_IPA);
   5693 	}
   5694 	if ((sc->hw_type == IWN_HW_REV_TYPE_6050 ||
   5695 		sc->hw_type == IWN_HW_REV_TYPE_6005) && sc->calib_ver >= 6) {
   5696 		/* Indicate that ROM calibration version is >=6. */
   5697 		IWN_SETBITS(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_CALIB_VER6);
   5698 	}
   5699 	if (sc->hw_type == IWN_HW_REV_TYPE_6005)
   5700 		IWN_SETBITS(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_6050_1X2);
   5701 	return 0;
   5702 }
   5703 
   5704 /*
   5705  * Take NIC ownership over Intel Active Management Technology (AMT).
   5706  */
   5707 static int
   5708 iwn_hw_prepare(struct iwn_softc *sc)
   5709 {
   5710 	int ntries;
   5711 
   5712 	/* Check if hardware is ready. */
   5713 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_NIC_READY);
   5714 	for (ntries = 0; ntries < 5; ntries++) {
   5715 		if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
   5716 		    IWN_HW_IF_CONFIG_NIC_READY)
   5717 			return 0;
   5718 		DELAY(10);
   5719 	}
   5720 
   5721 	/* Hardware not ready, force into ready state. */
   5722 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_PREPARE);
   5723 	for (ntries = 0; ntries < 15000; ntries++) {
   5724 		if (!(IWN_READ(sc, IWN_HW_IF_CONFIG) &
   5725 		    IWN_HW_IF_CONFIG_PREPARE_DONE))
   5726 			break;
   5727 		DELAY(10);
   5728 	}
   5729 	if (ntries == 15000)
   5730 		return ETIMEDOUT;
   5731 
   5732 	/* Hardware should be ready now. */
   5733 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_NIC_READY);
   5734 	for (ntries = 0; ntries < 5; ntries++) {
   5735 		if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
   5736 		    IWN_HW_IF_CONFIG_NIC_READY)
   5737 			return 0;
   5738 		DELAY(10);
   5739 	}
   5740 	return ETIMEDOUT;
   5741 }
   5742 
   5743 static int
   5744 iwn_hw_init(struct iwn_softc *sc)
   5745 {
   5746 	struct iwn_ops *ops = &sc->ops;
   5747 	int error, chnl, qid;
   5748 
   5749 	/* Clear pending interrupts. */
   5750 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
   5751 
   5752 	if ((error = iwn_apm_init(sc)) != 0) {
   5753 		aprint_error_dev(sc->sc_dev,
   5754 		    "could not power ON adapter\n");
   5755 		return error;
   5756 	}
   5757 
   5758 	/* Select VMAIN power source. */
   5759 	if ((error = iwn_nic_lock(sc)) != 0)
   5760 		return error;
   5761 	iwn_prph_clrbits(sc, IWN_APMG_PS, IWN_APMG_PS_PWR_SRC_MASK);
   5762 	iwn_nic_unlock(sc);
   5763 
   5764 	/* Perform adapter-specific initialization. */
   5765 	if ((error = ops->nic_config(sc)) != 0)
   5766 		return error;
   5767 
   5768 	/* Initialize RX ring. */
   5769 	if ((error = iwn_nic_lock(sc)) != 0)
   5770 		return error;
   5771 	IWN_WRITE(sc, IWN_FH_RX_CONFIG, 0);
   5772 	IWN_WRITE(sc, IWN_FH_RX_WPTR, 0);
   5773 	/* Set physical address of RX ring (256-byte aligned). */
   5774 	IWN_WRITE(sc, IWN_FH_RX_BASE, sc->rxq.desc_dma.paddr >> 8);
   5775 	/* Set physical address of RX status (16-byte aligned). */
   5776 	IWN_WRITE(sc, IWN_FH_STATUS_WPTR, sc->rxq.stat_dma.paddr >> 4);
   5777 	/* Enable RX. */
   5778 	IWN_WRITE(sc, IWN_FH_RX_CONFIG,
   5779 	    IWN_FH_RX_CONFIG_ENA           |
   5780 	    IWN_FH_RX_CONFIG_IGN_RXF_EMPTY |	/* HW bug workaround */
   5781 	    IWN_FH_RX_CONFIG_IRQ_DST_HOST  |
   5782 	    IWN_FH_RX_CONFIG_SINGLE_FRAME  |
   5783 	    IWN_FH_RX_CONFIG_RB_TIMEOUT(0) |
   5784 	    IWN_FH_RX_CONFIG_NRBD(IWN_RX_RING_COUNT_LOG));
   5785 	iwn_nic_unlock(sc);
   5786 	IWN_WRITE(sc, IWN_FH_RX_WPTR, (IWN_RX_RING_COUNT - 1) & ~7);
   5787 
   5788 	if ((error = iwn_nic_lock(sc)) != 0)
   5789 		return error;
   5790 
   5791 	/* Initialize TX scheduler. */
   5792 	iwn_prph_write(sc, sc->sched_txfact_addr, 0);
   5793 
   5794 	/* Set physical address of "keep warm" page (16-byte aligned). */
   5795 	IWN_WRITE(sc, IWN_FH_KW_ADDR, sc->kw_dma.paddr >> 4);
   5796 
   5797 	/* Initialize TX rings. */
   5798 	for (qid = 0; qid < sc->ntxqs; qid++) {
   5799 		struct iwn_tx_ring *txq = &sc->txq[qid];
   5800 
   5801 		/* Set physical address of TX ring (256-byte aligned). */
   5802 		IWN_WRITE(sc, IWN_FH_CBBC_QUEUE(qid),
   5803 		    txq->desc_dma.paddr >> 8);
   5804 	}
   5805 	iwn_nic_unlock(sc);
   5806 
   5807 	/* Enable DMA channels. */
   5808 	for (chnl = 0; chnl < sc->ndmachnls; chnl++) {
   5809 		IWN_WRITE(sc, IWN_FH_TX_CONFIG(chnl),
   5810 		    IWN_FH_TX_CONFIG_DMA_ENA |
   5811 		    IWN_FH_TX_CONFIG_DMA_CREDIT_ENA);
   5812 	}
   5813 
   5814 	/* Clear "radio off" and "commands blocked" bits. */
   5815 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
   5816 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CMD_BLOCKED);
   5817 
   5818 	/* Clear pending interrupts. */
   5819 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
   5820 	/* Enable interrupt coalescing. */
   5821 	IWN_WRITE(sc, IWN_INT_COALESCING, 512 / 8);
   5822 	/* Enable interrupts. */
   5823 	IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
   5824 
   5825 	/* _Really_ make sure "radio off" bit is cleared! */
   5826 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
   5827 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
   5828 
   5829 	/* Enable shadow registers. */
   5830 	if (sc->hw_type >= IWN_HW_REV_TYPE_6000)
   5831 		IWN_SETBITS(sc, IWN_SHADOW_REG_CTRL, 0x800fffff);
   5832 
   5833 	if ((error = ops->load_firmware(sc)) != 0) {
   5834 		aprint_error_dev(sc->sc_dev,
   5835 		    "could not load firmware\n");
   5836 		return error;
   5837 	}
   5838 	/* Wait at most one second for firmware alive notification. */
   5839 	if ((error = tsleep(sc, PCATCH, "iwninit", hz)) != 0) {
   5840 		aprint_error_dev(sc->sc_dev,
   5841 		    "timeout waiting for adapter to initialize\n");
   5842 		return error;
   5843 	}
   5844 	/* Do post-firmware initialization. */
   5845 	return ops->post_alive(sc);
   5846 }
   5847 
   5848 static void
   5849 iwn_hw_stop(struct iwn_softc *sc)
   5850 {
   5851 	int chnl, qid, ntries;
   5852 
   5853 	IWN_WRITE(sc, IWN_RESET, IWN_RESET_NEVO);
   5854 
   5855 	/* Disable interrupts. */
   5856 	IWN_WRITE(sc, IWN_INT_MASK, 0);
   5857 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
   5858 	IWN_WRITE(sc, IWN_FH_INT, 0xffffffff);
   5859 	sc->sc_flags &= ~IWN_FLAG_USE_ICT;
   5860 
   5861 	/* Make sure we no longer hold the NIC lock. */
   5862 	iwn_nic_unlock(sc);
   5863 
   5864 	/* Stop TX scheduler. */
   5865 	iwn_prph_write(sc, sc->sched_txfact_addr, 0);
   5866 
   5867 	/* Stop all DMA channels. */
   5868 	if (iwn_nic_lock(sc) == 0) {
   5869 		for (chnl = 0; chnl < sc->ndmachnls; chnl++) {
   5870 			IWN_WRITE(sc, IWN_FH_TX_CONFIG(chnl), 0);
   5871 			for (ntries = 0; ntries < 200; ntries++) {
   5872 				if (IWN_READ(sc, IWN_FH_TX_STATUS) &
   5873 				    IWN_FH_TX_STATUS_IDLE(chnl))
   5874 					break;
   5875 				DELAY(10);
   5876 			}
   5877 		}
   5878 		iwn_nic_unlock(sc);
   5879 	}
   5880 
   5881 	/* Stop RX ring. */
   5882 	iwn_reset_rx_ring(sc, &sc->rxq);
   5883 
   5884 	/* Reset all TX rings. */
   5885 	for (qid = 0; qid < sc->ntxqs; qid++)
   5886 		iwn_reset_tx_ring(sc, &sc->txq[qid]);
   5887 
   5888 	if (iwn_nic_lock(sc) == 0) {
   5889 		iwn_prph_write(sc, IWN_APMG_CLK_DIS,
   5890 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT);
   5891 		iwn_nic_unlock(sc);
   5892 	}
   5893 	DELAY(5);
   5894 	/* Power OFF adapter. */
   5895 	iwn_apm_stop(sc);
   5896 }
   5897 
   5898 static int
   5899 iwn_init(struct ifnet *ifp)
   5900 {
   5901 	struct iwn_softc *sc = ifp->if_softc;
   5902 	struct ieee80211com *ic = &sc->sc_ic;
   5903 	int error;
   5904 
   5905 	mutex_enter(&sc->sc_mtx);
   5906 	if (sc->sc_flags & IWN_FLAG_HW_INITED)
   5907 		goto out;
   5908 	if ((error = iwn_hw_prepare(sc)) != 0) {
   5909 		aprint_error_dev(sc->sc_dev,
   5910 		    "hardware not ready\n");
   5911 		goto fail;
   5912 	}
   5913 
   5914 	/* Check that the radio is not disabled by hardware switch. */
   5915 	if (!(IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_RFKILL)) {
   5916 		aprint_error_dev(sc->sc_dev,
   5917 		    "radio is disabled by hardware switch\n");
   5918 		error = EPERM;	/* :-) */
   5919 		goto fail;
   5920 	}
   5921 
   5922 	/* Read firmware images from the filesystem. */
   5923 	if ((error = iwn_read_firmware(sc)) != 0) {
   5924 		aprint_error_dev(sc->sc_dev,
   5925 		    "could not read firmware\n");
   5926 		goto fail;
   5927 	}
   5928 
   5929 	/* Initialize interrupt mask to default value. */
   5930 	sc->int_mask = IWN_INT_MASK_DEF;
   5931 	sc->sc_flags &= ~IWN_FLAG_USE_ICT;
   5932 
   5933 	/* Initialize hardware and upload firmware. */
   5934 	KASSERT(sc->fw.data != NULL && sc->fw.size > 0);
   5935 	error = iwn_hw_init(sc);
   5936 	firmware_free(sc->fw.data, sc->fw.size);
   5937 	sc->fw.data = NULL;
   5938 	sc->fw.size = 0;
   5939 	if (error != 0) {
   5940 		aprint_error_dev(sc->sc_dev,
   5941 		    "could not initialize hardware\n");
   5942 		goto fail;
   5943 	}
   5944 
   5945 	/* Configure adapter now that it is ready. */
   5946 	if ((error = iwn_config(sc)) != 0) {
   5947 		aprint_error_dev(sc->sc_dev,
   5948 		    "could not configure device\n");
   5949 		goto fail;
   5950 	}
   5951 
   5952 	ifp->if_flags &= ~IFF_OACTIVE;
   5953 	ifp->if_flags |= IFF_RUNNING;
   5954 
   5955 	if (ic->ic_opmode != IEEE80211_M_MONITOR)
   5956 		ieee80211_begin_scan(ic, 0);
   5957 	else
   5958 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
   5959 
   5960 	sc->sc_flags |= IWN_FLAG_HW_INITED;
   5961 out:
   5962 	mutex_exit(&sc->sc_mtx);
   5963 	return 0;
   5964 
   5965 fail:	mutex_exit(&sc->sc_mtx);
   5966 	iwn_stop(ifp, 1);
   5967 	return error;
   5968 }
   5969 
   5970 static void
   5971 iwn_stop(struct ifnet *ifp, int disable)
   5972 {
   5973 	struct iwn_softc *sc = ifp->if_softc;
   5974 	struct ieee80211com *ic = &sc->sc_ic;
   5975 
   5976 	if (!disable)
   5977 		mutex_enter(&sc->sc_mtx);
   5978 	sc->sc_flags &= ~IWN_FLAG_HW_INITED;
   5979 	ifp->if_timer = sc->sc_tx_timer = 0;
   5980 	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
   5981 
   5982 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
   5983 
   5984 	/* Power OFF hardware. */
   5985 	iwn_hw_stop(sc);
   5986 
   5987 	if (!disable)
   5988 		mutex_exit(&sc->sc_mtx);
   5989 }
   5990 
   5991 /*
   5992  * XXX MCLGETI alternative
   5993  *
   5994  * With IWN_USE_RBUF defined it uses the rbuf cache for receive buffers
   5995  * as long as there are available free buffers then it uses MEXTMALLOC.,
   5996  * Without IWN_USE_RBUF defined it uses MEXTMALLOC exclusively.
   5997  * The MCLGET4K code is used for testing an alternative mbuf cache.
   5998  */
   5999 
   6000 static struct mbuf *
   6001 MCLGETIalt(struct iwn_softc *sc, int how,
   6002     struct ifnet *ifp __unused, u_int size)
   6003 {
   6004 	struct mbuf *m;
   6005 #ifdef IWN_USE_RBUF
   6006 	struct iwn_rbuf *rbuf;
   6007 #endif
   6008 
   6009 	MGETHDR(m, how, MT_DATA);
   6010 	if (m == NULL)
   6011 		return NULL;
   6012 
   6013 #ifdef IWN_USE_RBUF
   6014 	if (sc->rxq.nb_free_entries > 0 &&
   6015 	    (rbuf = iwn_alloc_rbuf(sc)) != NULL) {
   6016 		/* Attach buffer to mbuf header. */
   6017 		MEXTADD(m, rbuf->vaddr, size, 0, iwn_free_rbuf, rbuf);
   6018 		m->m_flags |= M_EXT_RW;
   6019 	}
   6020 	else {
   6021 		MEXTMALLOC(m, size, how);
   6022 		if ((m->m_flags & M_EXT) == 0) {
   6023 			m_freem(m);
   6024 			return NULL;
   6025 		}
   6026 	}
   6027 
   6028 #else
   6029 #ifdef MCLGET4K
   6030 	if (size == 4096)
   6031 		MCLGET4K(m, how);
   6032 	else
   6033 		panic("size must be 4k");
   6034 #else
   6035 	MEXTMALLOC(m, size, how);
   6036 #endif
   6037 	if ((m->m_flags & M_EXT) == 0) {
   6038 		m_freem(m);
   6039 		return NULL;
   6040 	}
   6041 #endif
   6042 
   6043 	return m;
   6044 }
   6045 
   6046 #ifdef IWN_USE_RBUF
   6047 static struct iwn_rbuf *
   6048 iwn_alloc_rbuf(struct iwn_softc *sc)
   6049 {
   6050 	struct iwn_rbuf *rbuf;
   6051 	mutex_enter(&sc->rxq.freelist_mtx);
   6052 
   6053 	rbuf = SLIST_FIRST(&sc->rxq.freelist);
   6054 	if (rbuf != NULL) {
   6055 		SLIST_REMOVE_HEAD(&sc->rxq.freelist, next);
   6056 		sc->rxq.nb_free_entries --;
   6057 	}
   6058 	mutex_exit(&sc->rxq.freelist_mtx);
   6059 	return rbuf;
   6060 }
   6061 
   6062 /*
   6063  * This is called automatically by the network stack when the mbuf to which
   6064  * our RX buffer is attached is freed.
   6065  */
   6066 static void
   6067 iwn_free_rbuf(struct mbuf* m, void *buf,  size_t size, void *arg)
   6068 {
   6069 	struct iwn_rbuf *rbuf = arg;
   6070 	struct iwn_softc *sc = rbuf->sc;
   6071 
   6072 	/* Put the RX buffer back in the free list. */
   6073 	mutex_enter(&sc->rxq.freelist_mtx);
   6074 	SLIST_INSERT_HEAD(&sc->rxq.freelist, rbuf, next);
   6075 	mutex_exit(&sc->rxq.freelist_mtx);
   6076 
   6077 	sc->rxq.nb_free_entries ++;
   6078 	if (__predict_true(m != NULL))
   6079 		pool_cache_put(mb_cache, m);
   6080 }
   6081 
   6082 static int
   6083 iwn_alloc_rpool(struct iwn_softc *sc)
   6084 {
   6085 	struct iwn_rx_ring *ring = &sc->rxq;
   6086 	struct iwn_rbuf *rbuf;
   6087 	int i, error;
   6088 
   6089 	mutex_init(&ring->freelist_mtx, MUTEX_DEFAULT, IPL_NET);
   6090 
   6091 	/* Allocate a big chunk of DMA'able memory... */
   6092 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->buf_dma, NULL,
   6093 	    IWN_RBUF_COUNT * IWN_RBUF_SIZE, PAGE_SIZE);
   6094 	if (error != 0) {
   6095 		aprint_error_dev(sc->sc_dev,
   6096 		    "could not allocate RX buffers DMA memory\n");
   6097 		return error;
   6098 	}
   6099 	/* ...and split it into chunks of IWN_RBUF_SIZE bytes. */
   6100 	SLIST_INIT(&ring->freelist);
   6101 	for (i = 0; i < IWN_RBUF_COUNT; i++) {
   6102 		rbuf = &ring->rbuf[i];
   6103 
   6104 		rbuf->sc = sc;	/* Backpointer for callbacks. */
   6105 		rbuf->vaddr = (void *)((vaddr_t)ring->buf_dma.vaddr + i * IWN_RBUF_SIZE);
   6106 		rbuf->paddr = ring->buf_dma.paddr + i * IWN_RBUF_SIZE;
   6107 
   6108 		SLIST_INSERT_HEAD(&ring->freelist, rbuf, next);
   6109 	}
   6110 	ring->nb_free_entries = IWN_RBUF_COUNT;
   6111 	return 0;
   6112 }
   6113 
   6114 static void
   6115 iwn_free_rpool(struct iwn_softc *sc)
   6116 {
   6117 	iwn_dma_contig_free(&sc->rxq.buf_dma);
   6118 }
   6119 #endif
   6120 
   6121 /*
   6122  * XXX code from OpenBSD src/sys/net80211/ieee80211_output.c
   6123  * Copyright (c) 2001 Atsushi Onoe
   6124  * Copyright (c) 2002, 2003 Sam Leffler, Errno Consulting
   6125  * Copyright (c) 2007-2009 Damien Bergamini
   6126  * All rights reserved.
   6127  */
   6128 
   6129 /*
   6130  * Add an SSID element to a frame (see 7.3.2.1).
   6131  */
   6132 static u_int8_t *
   6133 ieee80211_add_ssid(u_int8_t *frm, const u_int8_t *ssid, u_int len)
   6134 {
   6135 	*frm++ = IEEE80211_ELEMID_SSID;
   6136 	*frm++ = len;
   6137 	memcpy(frm, ssid, len);
   6138 	return frm + len;
   6139 }
   6140 
   6141 /*
   6142  * Add a supported rates element to a frame (see 7.3.2.2).
   6143  */
   6144 static u_int8_t *
   6145 ieee80211_add_rates(u_int8_t *frm, const struct ieee80211_rateset *rs)
   6146 {
   6147 	int nrates;
   6148 
   6149 	*frm++ = IEEE80211_ELEMID_RATES;
   6150 	nrates = min(rs->rs_nrates, IEEE80211_RATE_SIZE);
   6151 	*frm++ = nrates;
   6152 	memcpy(frm, rs->rs_rates, nrates);
   6153 	return frm + nrates;
   6154 }
   6155 
   6156 /*
   6157  * Add an extended supported rates element to a frame (see 7.3.2.14).
   6158  */
   6159 static u_int8_t *
   6160 ieee80211_add_xrates(u_int8_t *frm, const struct ieee80211_rateset *rs)
   6161 {
   6162 	int nrates;
   6163 
   6164 	KASSERT(rs->rs_nrates > IEEE80211_RATE_SIZE);
   6165 
   6166 	*frm++ = IEEE80211_ELEMID_XRATES;
   6167 	nrates = rs->rs_nrates - IEEE80211_RATE_SIZE;
   6168 	*frm++ = nrates;
   6169 	memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates);
   6170 	return frm + nrates;
   6171 }
   6172 
   6173 /*
   6174  * XXX: Hack to set the current channel to the value advertised in beacons or
   6175  * probe responses. Only used during AP detection.
   6176  * XXX: Duplicated from if_iwi.c
   6177  */
   6178 static void
   6179 iwn_fix_channel(struct ieee80211com *ic, struct mbuf *m)
   6180 {
   6181 	struct ieee80211_frame *wh;
   6182 	uint8_t subtype;
   6183 	uint8_t *frm, *efrm;
   6184 
   6185 	wh = mtod(m, struct ieee80211_frame *);
   6186 
   6187 	if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_MGT)
   6188 		return;
   6189 
   6190 	subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
   6191 
   6192 	if (subtype != IEEE80211_FC0_SUBTYPE_BEACON &&
   6193 	    subtype != IEEE80211_FC0_SUBTYPE_PROBE_RESP)
   6194 		return;
   6195 
   6196 	frm = (uint8_t *)(wh + 1);
   6197 	efrm = mtod(m, uint8_t *) + m->m_len;
   6198 
   6199 	frm += 12;      /* skip tstamp, bintval and capinfo fields */
   6200 	while (frm < efrm) {
   6201 		if (*frm == IEEE80211_ELEMID_DSPARMS)
   6202 #if IEEE80211_CHAN_MAX < 255
   6203 		if (frm[2] <= IEEE80211_CHAN_MAX)
   6204 #endif
   6205 			ic->ic_curchan = &ic->ic_channels[frm[2]];
   6206 
   6207 		frm += frm[1] + 2;
   6208 	}
   6209 }
   6210 
   6211 #ifdef notyetMODULE
   6212 
   6213 MODULE(MODULE_CLASS_DRIVER, if_iwn, "pci");
   6214 
   6215 #ifdef _MODULE
   6216 #include "ioconf.c"
   6217 #endif
   6218 
   6219 static int
   6220 if_iwn_modcmd(modcmd_t cmd, void *data)
   6221 {
   6222 	int error = 0;
   6223 
   6224 	switch (cmd) {
   6225 	case MODULE_CMD_INIT:
   6226 #ifdef _MODULE
   6227 		error = config_init_component(cfdriver_ioconf_if_iwn,
   6228 			cfattach_ioconf_if_iwn, cfdata_ioconf_if_iwn);
   6229 #endif
   6230 		return error;
   6231 	case MODULE_CMD_FINI:
   6232 #ifdef _MODULE
   6233 		error = config_fini_component(cfdriver_ioconf_if_iwn,
   6234 			cfattach_ioconf_if_iwn, cfdata_ioconf_if_iwn);
   6235 #endif
   6236 		return error;
   6237 	case MODULE_CMD_AUTOUNLOAD:
   6238 #ifdef _MODULE
   6239 		/* XXX This is not optional! */
   6240 #endif
   6241 		return error;
   6242 	default:
   6243 		return ENOTTY;
   6244 	}
   6245 }
   6246 #endif
   6247