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