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