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