The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/dev/iwn/if_iwn.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

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

Cache object: b157cd5616b995b24bd3004836360ccf


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.