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