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