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