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 Damien Bergamini <damien.bergamini@free.fr>
    3  * Copyright (c) 2008 Benjamin Close <benjsc@FreeBSD.org>
    4  * Copyright (c) 2008 Sam Leffler, Errno Consulting
    5  * Copyright (c) 2011 Intel Corporation
    6  * Copyright (c) 2013 Cedric GROSS <c.gross@kreiz-it.fr>
    7  * Copyright (c) 2013 Adrian Chadd <adrian@FreeBSD.org>
    8  *
    9  * Permission to use, copy, modify, and distribute this software for any
   10  * purpose with or without fee is hereby granted, provided that the above
   11  * copyright notice and this permission notice appear in all copies.
   12  *
   13  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   14  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
   15  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
   16  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   17  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
   18  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
   19  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
   20  */
   21 
   22 /*
   23  * Driver for Intel WiFi Link 4965 and 1000/5000/6000 Series 802.11 network
   24  * adapters.
   25  */
   26 
   27 #include <sys/cdefs.h>
   28 __FBSDID("$FreeBSD: releng/11.0/sys/dev/iwn/if_iwn.c 300732 2016-05-26 11:12:36Z avos $");
   29 
   30 #include "opt_wlan.h"
   31 #include "opt_iwn.h"
   32 
   33 #include <sys/param.h>
   34 #include <sys/sockio.h>
   35 #include <sys/sysctl.h>
   36 #include <sys/mbuf.h>
   37 #include <sys/kernel.h>
   38 #include <sys/socket.h>
   39 #include <sys/systm.h>
   40 #include <sys/malloc.h>
   41 #include <sys/bus.h>
   42 #include <sys/conf.h>
   43 #include <sys/rman.h>
   44 #include <sys/endian.h>
   45 #include <sys/firmware.h>
   46 #include <sys/limits.h>
   47 #include <sys/module.h>
   48 #include <sys/priv.h>
   49 #include <sys/queue.h>
   50 #include <sys/taskqueue.h>
   51 
   52 #include <machine/bus.h>
   53 #include <machine/resource.h>
   54 #include <machine/clock.h>
   55 
   56 #include <dev/pci/pcireg.h>
   57 #include <dev/pci/pcivar.h>
   58 
   59 #include <net/if.h>
   60 #include <net/if_var.h>
   61 #include <net/if_dl.h>
   62 #include <net/if_media.h>
   63 
   64 #include <netinet/in.h>
   65 #include <netinet/if_ether.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 #include <dev/iwn/if_iwn_devid.h>
   75 #include <dev/iwn/if_iwn_chip_cfg.h>
   76 #include <dev/iwn/if_iwn_debug.h>
   77 #include <dev/iwn/if_iwn_ioctl.h>
   78 
   79 struct iwn_ident {
   80         uint16_t        vendor;
   81         uint16_t        device;
   82         const char      *name;
   83 };
   84 
   85 static const struct iwn_ident iwn_ident_table[] = {
   86         { 0x8086, IWN_DID_6x05_1, "Intel Centrino Advanced-N 6205"              },
   87         { 0x8086, IWN_DID_1000_1, "Intel Centrino Wireless-N 1000"              },
   88         { 0x8086, IWN_DID_1000_2, "Intel Centrino Wireless-N 1000"              },
   89         { 0x8086, IWN_DID_6x05_2, "Intel Centrino Advanced-N 6205"              },
   90         { 0x8086, IWN_DID_6050_1, "Intel Centrino Advanced-N + WiMAX 6250"      },
   91         { 0x8086, IWN_DID_6050_2, "Intel Centrino Advanced-N + WiMAX 6250"      },
   92         { 0x8086, IWN_DID_x030_1, "Intel Centrino Wireless-N 1030"              },
   93         { 0x8086, IWN_DID_x030_2, "Intel Centrino Wireless-N 1030"              },
   94         { 0x8086, IWN_DID_x030_3, "Intel Centrino Advanced-N 6230"              },
   95         { 0x8086, IWN_DID_x030_4, "Intel Centrino Advanced-N 6230"              },
   96         { 0x8086, IWN_DID_6150_1, "Intel Centrino Wireless-N + WiMAX 6150"      },
   97         { 0x8086, IWN_DID_6150_2, "Intel Centrino Wireless-N + WiMAX 6150"      },
   98         { 0x8086, IWN_DID_2x00_1, "Intel(R) Centrino(R) Wireless-N 2200 BGN"    },
   99         { 0x8086, IWN_DID_2x00_2, "Intel(R) Centrino(R) Wireless-N 2200 BGN"    },
  100         /* XXX 2200D is IWN_SDID_2x00_4; there's no way to express this here! */
  101         { 0x8086, IWN_DID_2x30_1, "Intel Centrino Wireless-N 2230"              },
  102         { 0x8086, IWN_DID_2x30_2, "Intel Centrino Wireless-N 2230"              },
  103         { 0x8086, IWN_DID_130_1, "Intel Centrino Wireless-N 130"                },
  104         { 0x8086, IWN_DID_130_2, "Intel Centrino Wireless-N 130"                },
  105         { 0x8086, IWN_DID_100_1, "Intel Centrino Wireless-N 100"                },
  106         { 0x8086, IWN_DID_100_2, "Intel Centrino Wireless-N 100"                },
  107         { 0x8086, IWN_DID_105_1, "Intel Centrino Wireless-N 105"                },
  108         { 0x8086, IWN_DID_105_2, "Intel Centrino Wireless-N 105"                },
  109         { 0x8086, IWN_DID_135_1, "Intel Centrino Wireless-N 135"                },
  110         { 0x8086, IWN_DID_135_2, "Intel Centrino Wireless-N 135"                },
  111         { 0x8086, IWN_DID_4965_1, "Intel Wireless WiFi Link 4965"               },
  112         { 0x8086, IWN_DID_6x00_1, "Intel Centrino Ultimate-N 6300"              },
  113         { 0x8086, IWN_DID_6x00_2, "Intel Centrino Advanced-N 6200"              },
  114         { 0x8086, IWN_DID_4965_2, "Intel Wireless WiFi Link 4965"               },
  115         { 0x8086, IWN_DID_4965_3, "Intel Wireless WiFi Link 4965"               },
  116         { 0x8086, IWN_DID_5x00_1, "Intel WiFi Link 5100"                        },
  117         { 0x8086, IWN_DID_4965_4, "Intel Wireless WiFi Link 4965"               },
  118         { 0x8086, IWN_DID_5x00_3, "Intel Ultimate N WiFi Link 5300"             },
  119         { 0x8086, IWN_DID_5x00_4, "Intel Ultimate N WiFi Link 5300"             },
  120         { 0x8086, IWN_DID_5x00_2, "Intel WiFi Link 5100"                        },
  121         { 0x8086, IWN_DID_6x00_3, "Intel Centrino Ultimate-N 6300"              },
  122         { 0x8086, IWN_DID_6x00_4, "Intel Centrino Advanced-N 6200"              },
  123         { 0x8086, IWN_DID_5x50_1, "Intel WiMAX/WiFi Link 5350"                  },
  124         { 0x8086, IWN_DID_5x50_2, "Intel WiMAX/WiFi Link 5350"                  },
  125         { 0x8086, IWN_DID_5x50_3, "Intel WiMAX/WiFi Link 5150"                  },
  126         { 0x8086, IWN_DID_5x50_4, "Intel WiMAX/WiFi Link 5150"                  },
  127         { 0x8086, IWN_DID_6035_1, "Intel Centrino Advanced 6235"                },
  128         { 0x8086, IWN_DID_6035_2, "Intel Centrino Advanced 6235"                },
  129         { 0, 0, NULL }
  130 };
  131 
  132 static int      iwn_probe(device_t);
  133 static int      iwn_attach(device_t);
  134 static int      iwn4965_attach(struct iwn_softc *, uint16_t);
  135 static int      iwn5000_attach(struct iwn_softc *, uint16_t);
  136 static int      iwn_config_specific(struct iwn_softc *, uint16_t);
  137 static void     iwn_radiotap_attach(struct iwn_softc *);
  138 static void     iwn_sysctlattach(struct iwn_softc *);
  139 static struct ieee80211vap *iwn_vap_create(struct ieee80211com *,
  140                     const char [IFNAMSIZ], int, enum ieee80211_opmode, int,
  141                     const uint8_t [IEEE80211_ADDR_LEN],
  142                     const uint8_t [IEEE80211_ADDR_LEN]);
  143 static void     iwn_vap_delete(struct ieee80211vap *);
  144 static int      iwn_detach(device_t);
  145 static int      iwn_shutdown(device_t);
  146 static int      iwn_suspend(device_t);
  147 static int      iwn_resume(device_t);
  148 static int      iwn_nic_lock(struct iwn_softc *);
  149 static int      iwn_eeprom_lock(struct iwn_softc *);
  150 static int      iwn_init_otprom(struct iwn_softc *);
  151 static int      iwn_read_prom_data(struct iwn_softc *, uint32_t, void *, int);
  152 static void     iwn_dma_map_addr(void *, bus_dma_segment_t *, int, int);
  153 static int      iwn_dma_contig_alloc(struct iwn_softc *, struct iwn_dma_info *,
  154                     void **, bus_size_t, bus_size_t);
  155 static void     iwn_dma_contig_free(struct iwn_dma_info *);
  156 static int      iwn_alloc_sched(struct iwn_softc *);
  157 static void     iwn_free_sched(struct iwn_softc *);
  158 static int      iwn_alloc_kw(struct iwn_softc *);
  159 static void     iwn_free_kw(struct iwn_softc *);
  160 static int      iwn_alloc_ict(struct iwn_softc *);
  161 static void     iwn_free_ict(struct iwn_softc *);
  162 static int      iwn_alloc_fwmem(struct iwn_softc *);
  163 static void     iwn_free_fwmem(struct iwn_softc *);
  164 static int      iwn_alloc_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
  165 static void     iwn_reset_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
  166 static void     iwn_free_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
  167 static int      iwn_alloc_tx_ring(struct iwn_softc *, struct iwn_tx_ring *,
  168                     int);
  169 static void     iwn_reset_tx_ring(struct iwn_softc *, struct iwn_tx_ring *);
  170 static void     iwn_free_tx_ring(struct iwn_softc *, struct iwn_tx_ring *);
  171 static void     iwn5000_ict_reset(struct iwn_softc *);
  172 static int      iwn_read_eeprom(struct iwn_softc *,
  173                     uint8_t macaddr[IEEE80211_ADDR_LEN]);
  174 static void     iwn4965_read_eeprom(struct iwn_softc *);
  175 #ifdef  IWN_DEBUG
  176 static void     iwn4965_print_power_group(struct iwn_softc *, int);
  177 #endif
  178 static void     iwn5000_read_eeprom(struct iwn_softc *);
  179 static uint32_t iwn_eeprom_channel_flags(struct iwn_eeprom_chan *);
  180 static void     iwn_read_eeprom_band(struct iwn_softc *, int, int, int *,
  181                     struct ieee80211_channel[]);
  182 static void     iwn_read_eeprom_ht40(struct iwn_softc *, int, int, int *,
  183                     struct ieee80211_channel[]);
  184 static void     iwn_read_eeprom_channels(struct iwn_softc *, int, uint32_t);
  185 static struct iwn_eeprom_chan *iwn_find_eeprom_channel(struct iwn_softc *,
  186                     struct ieee80211_channel *);
  187 static void     iwn_getradiocaps(struct ieee80211com *, int, int *,
  188                     struct ieee80211_channel[]);
  189 static int      iwn_setregdomain(struct ieee80211com *,
  190                     struct ieee80211_regdomain *, int,
  191                     struct ieee80211_channel[]);
  192 static void     iwn_read_eeprom_enhinfo(struct iwn_softc *);
  193 static struct ieee80211_node *iwn_node_alloc(struct ieee80211vap *,
  194                     const uint8_t mac[IEEE80211_ADDR_LEN]);
  195 static void     iwn_newassoc(struct ieee80211_node *, int);
  196 static int      iwn_media_change(struct ifnet *);
  197 static int      iwn_newstate(struct ieee80211vap *, enum ieee80211_state, int);
  198 static void     iwn_calib_timeout(void *);
  199 static void     iwn_rx_phy(struct iwn_softc *, struct iwn_rx_desc *,
  200                     struct iwn_rx_data *);
  201 static void     iwn_rx_done(struct iwn_softc *, struct iwn_rx_desc *,
  202                     struct iwn_rx_data *);
  203 static void     iwn_rx_compressed_ba(struct iwn_softc *, struct iwn_rx_desc *,
  204                     struct iwn_rx_data *);
  205 static void     iwn5000_rx_calib_results(struct iwn_softc *,
  206                     struct iwn_rx_desc *, struct iwn_rx_data *);
  207 static void     iwn_rx_statistics(struct iwn_softc *, struct iwn_rx_desc *,
  208                     struct iwn_rx_data *);
  209 static void     iwn4965_tx_done(struct iwn_softc *, struct iwn_rx_desc *,
  210                     struct iwn_rx_data *);
  211 static void     iwn5000_tx_done(struct iwn_softc *, struct iwn_rx_desc *,
  212                     struct iwn_rx_data *);
  213 static void     iwn_tx_done(struct iwn_softc *, struct iwn_rx_desc *, int,
  214                     uint8_t);
  215 static void     iwn_ampdu_tx_done(struct iwn_softc *, int, int, int, int, void *);
  216 static void     iwn_cmd_done(struct iwn_softc *, struct iwn_rx_desc *);
  217 static void     iwn_notif_intr(struct iwn_softc *);
  218 static void     iwn_wakeup_intr(struct iwn_softc *);
  219 static void     iwn_rftoggle_intr(struct iwn_softc *);
  220 static void     iwn_fatal_intr(struct iwn_softc *);
  221 static void     iwn_intr(void *);
  222 static void     iwn4965_update_sched(struct iwn_softc *, int, int, uint8_t,
  223                     uint16_t);
  224 static void     iwn5000_update_sched(struct iwn_softc *, int, int, uint8_t,
  225                     uint16_t);
  226 #ifdef notyet
  227 static void     iwn5000_reset_sched(struct iwn_softc *, int, int);
  228 #endif
  229 static int      iwn_tx_data(struct iwn_softc *, struct mbuf *,
  230                     struct ieee80211_node *);
  231 static int      iwn_tx_data_raw(struct iwn_softc *, struct mbuf *,
  232                     struct ieee80211_node *,
  233                     const struct ieee80211_bpf_params *params);
  234 static void     iwn_xmit_task(void *arg0, int pending);
  235 static int      iwn_raw_xmit(struct ieee80211_node *, struct mbuf *,
  236                     const struct ieee80211_bpf_params *);
  237 static int      iwn_transmit(struct ieee80211com *, struct mbuf *);
  238 static void     iwn_scan_timeout(void *);
  239 static void     iwn_watchdog(void *);
  240 static int      iwn_ioctl(struct ieee80211com *, u_long , void *);
  241 static void     iwn_parent(struct ieee80211com *);
  242 static int      iwn_cmd(struct iwn_softc *, int, const void *, int, int);
  243 static int      iwn4965_add_node(struct iwn_softc *, struct iwn_node_info *,
  244                     int);
  245 static int      iwn5000_add_node(struct iwn_softc *, struct iwn_node_info *,
  246                     int);
  247 static int      iwn_set_link_quality(struct iwn_softc *,
  248                     struct ieee80211_node *);
  249 static int      iwn_add_broadcast_node(struct iwn_softc *, int);
  250 static int      iwn_updateedca(struct ieee80211com *);
  251 static void     iwn_update_mcast(struct ieee80211com *);
  252 static void     iwn_set_led(struct iwn_softc *, uint8_t, uint8_t, uint8_t);
  253 static int      iwn_set_critical_temp(struct iwn_softc *);
  254 static int      iwn_set_timing(struct iwn_softc *, struct ieee80211_node *);
  255 static void     iwn4965_power_calibration(struct iwn_softc *, int);
  256 static int      iwn4965_set_txpower(struct iwn_softc *,
  257                     struct ieee80211_channel *, int);
  258 static int      iwn5000_set_txpower(struct iwn_softc *,
  259                     struct ieee80211_channel *, int);
  260 static int      iwn4965_get_rssi(struct iwn_softc *, struct iwn_rx_stat *);
  261 static int      iwn5000_get_rssi(struct iwn_softc *, struct iwn_rx_stat *);
  262 static int      iwn_get_noise(const struct iwn_rx_general_stats *);
  263 static int      iwn4965_get_temperature(struct iwn_softc *);
  264 static int      iwn5000_get_temperature(struct iwn_softc *);
  265 static int      iwn_init_sensitivity(struct iwn_softc *);
  266 static void     iwn_collect_noise(struct iwn_softc *,
  267                     const struct iwn_rx_general_stats *);
  268 static int      iwn4965_init_gains(struct iwn_softc *);
  269 static int      iwn5000_init_gains(struct iwn_softc *);
  270 static int      iwn4965_set_gains(struct iwn_softc *);
  271 static int      iwn5000_set_gains(struct iwn_softc *);
  272 static void     iwn_tune_sensitivity(struct iwn_softc *,
  273                     const struct iwn_rx_stats *);
  274 static void     iwn_save_stats_counters(struct iwn_softc *,
  275                     const struct iwn_stats *);
  276 static int      iwn_send_sensitivity(struct iwn_softc *);
  277 static void     iwn_check_rx_recovery(struct iwn_softc *, struct iwn_stats *);
  278 static int      iwn_set_pslevel(struct iwn_softc *, int, int, int);
  279 static int      iwn_send_btcoex(struct iwn_softc *);
  280 static int      iwn_send_advanced_btcoex(struct iwn_softc *);
  281 static int      iwn5000_runtime_calib(struct iwn_softc *);
  282 static int      iwn_config(struct iwn_softc *);
  283 static int      iwn_scan(struct iwn_softc *, struct ieee80211vap *,
  284                     struct ieee80211_scan_state *, struct ieee80211_channel *);
  285 static int      iwn_auth(struct iwn_softc *, struct ieee80211vap *vap);
  286 static int      iwn_run(struct iwn_softc *, struct ieee80211vap *vap);
  287 static int      iwn_ampdu_rx_start(struct ieee80211_node *,
  288                     struct ieee80211_rx_ampdu *, int, int, int);
  289 static void     iwn_ampdu_rx_stop(struct ieee80211_node *,
  290                     struct ieee80211_rx_ampdu *);
  291 static int      iwn_addba_request(struct ieee80211_node *,
  292                     struct ieee80211_tx_ampdu *, int, int, int);
  293 static int      iwn_addba_response(struct ieee80211_node *,
  294                     struct ieee80211_tx_ampdu *, int, int, int);
  295 static int      iwn_ampdu_tx_start(struct ieee80211com *,
  296                     struct ieee80211_node *, uint8_t);
  297 static void     iwn_ampdu_tx_stop(struct ieee80211_node *,
  298                     struct ieee80211_tx_ampdu *);
  299 static void     iwn4965_ampdu_tx_start(struct iwn_softc *,
  300                     struct ieee80211_node *, int, uint8_t, uint16_t);
  301 static void     iwn4965_ampdu_tx_stop(struct iwn_softc *, int,
  302                     uint8_t, uint16_t);
  303 static void     iwn5000_ampdu_tx_start(struct iwn_softc *,
  304                     struct ieee80211_node *, int, uint8_t, uint16_t);
  305 static void     iwn5000_ampdu_tx_stop(struct iwn_softc *, int,
  306                     uint8_t, uint16_t);
  307 static int      iwn5000_query_calibration(struct iwn_softc *);
  308 static int      iwn5000_send_calibration(struct iwn_softc *);
  309 static int      iwn5000_send_wimax_coex(struct iwn_softc *);
  310 static int      iwn5000_crystal_calib(struct iwn_softc *);
  311 static int      iwn5000_temp_offset_calib(struct iwn_softc *);
  312 static int      iwn5000_temp_offset_calibv2(struct iwn_softc *);
  313 static int      iwn4965_post_alive(struct iwn_softc *);
  314 static int      iwn5000_post_alive(struct iwn_softc *);
  315 static int      iwn4965_load_bootcode(struct iwn_softc *, const uint8_t *,
  316                     int);
  317 static int      iwn4965_load_firmware(struct iwn_softc *);
  318 static int      iwn5000_load_firmware_section(struct iwn_softc *, uint32_t,
  319                     const uint8_t *, int);
  320 static int      iwn5000_load_firmware(struct iwn_softc *);
  321 static int      iwn_read_firmware_leg(struct iwn_softc *,
  322                     struct iwn_fw_info *);
  323 static int      iwn_read_firmware_tlv(struct iwn_softc *,
  324                     struct iwn_fw_info *, uint16_t);
  325 static int      iwn_read_firmware(struct iwn_softc *);
  326 static void     iwn_unload_firmware(struct iwn_softc *);
  327 static int      iwn_clock_wait(struct iwn_softc *);
  328 static int      iwn_apm_init(struct iwn_softc *);
  329 static void     iwn_apm_stop_master(struct iwn_softc *);
  330 static void     iwn_apm_stop(struct iwn_softc *);
  331 static int      iwn4965_nic_config(struct iwn_softc *);
  332 static int      iwn5000_nic_config(struct iwn_softc *);
  333 static int      iwn_hw_prepare(struct iwn_softc *);
  334 static int      iwn_hw_init(struct iwn_softc *);
  335 static void     iwn_hw_stop(struct iwn_softc *);
  336 static void     iwn_radio_on(void *, int);
  337 static void     iwn_radio_off(void *, int);
  338 static void     iwn_panicked(void *, int);
  339 static void     iwn_init_locked(struct iwn_softc *);
  340 static void     iwn_init(struct iwn_softc *);
  341 static void     iwn_stop_locked(struct iwn_softc *);
  342 static void     iwn_stop(struct iwn_softc *);
  343 static void     iwn_scan_start(struct ieee80211com *);
  344 static void     iwn_scan_end(struct ieee80211com *);
  345 static void     iwn_set_channel(struct ieee80211com *);
  346 static void     iwn_scan_curchan(struct ieee80211_scan_state *, unsigned long);
  347 static void     iwn_scan_mindwell(struct ieee80211_scan_state *);
  348 #ifdef  IWN_DEBUG
  349 static char     *iwn_get_csr_string(int);
  350 static void     iwn_debug_register(struct iwn_softc *);
  351 #endif
  352 
  353 static device_method_t iwn_methods[] = {
  354         /* Device interface */
  355         DEVMETHOD(device_probe,         iwn_probe),
  356         DEVMETHOD(device_attach,        iwn_attach),
  357         DEVMETHOD(device_detach,        iwn_detach),
  358         DEVMETHOD(device_shutdown,      iwn_shutdown),
  359         DEVMETHOD(device_suspend,       iwn_suspend),
  360         DEVMETHOD(device_resume,        iwn_resume),
  361 
  362         DEVMETHOD_END
  363 };
  364 
  365 static driver_t iwn_driver = {
  366         "iwn",
  367         iwn_methods,
  368         sizeof(struct iwn_softc)
  369 };
  370 static devclass_t iwn_devclass;
  371 
  372 DRIVER_MODULE(iwn, pci, iwn_driver, iwn_devclass, NULL, NULL);
  373 
  374 MODULE_VERSION(iwn, 1);
  375 
  376 MODULE_DEPEND(iwn, firmware, 1, 1, 1);
  377 MODULE_DEPEND(iwn, pci, 1, 1, 1);
  378 MODULE_DEPEND(iwn, wlan, 1, 1, 1);
  379 
  380 static d_ioctl_t iwn_cdev_ioctl;
  381 static d_open_t iwn_cdev_open;
  382 static d_close_t iwn_cdev_close;
  383 
  384 static struct cdevsw iwn_cdevsw = {
  385         .d_version = D_VERSION,
  386         .d_flags = 0,
  387         .d_open = iwn_cdev_open,
  388         .d_close = iwn_cdev_close,
  389         .d_ioctl = iwn_cdev_ioctl,
  390         .d_name = "iwn",
  391 };
  392 
  393 static int
  394 iwn_probe(device_t dev)
  395 {
  396         const struct iwn_ident *ident;
  397 
  398         for (ident = iwn_ident_table; ident->name != NULL; ident++) {
  399                 if (pci_get_vendor(dev) == ident->vendor &&
  400                     pci_get_device(dev) == ident->device) {
  401                         device_set_desc(dev, ident->name);
  402                         return (BUS_PROBE_DEFAULT);
  403                 }
  404         }
  405         return ENXIO;
  406 }
  407 
  408 static int
  409 iwn_is_3stream_device(struct iwn_softc *sc)
  410 {
  411         /* XXX for now only 5300, until the 5350 can be tested */
  412         if (sc->hw_type == IWN_HW_REV_TYPE_5300)
  413                 return (1);
  414         return (0);
  415 }
  416 
  417 static int
  418 iwn_attach(device_t dev)
  419 {
  420         struct iwn_softc *sc = device_get_softc(dev);
  421         struct ieee80211com *ic;
  422         int i, error, rid;
  423 
  424         sc->sc_dev = dev;
  425 
  426 #ifdef  IWN_DEBUG
  427         error = resource_int_value(device_get_name(sc->sc_dev),
  428             device_get_unit(sc->sc_dev), "debug", &(sc->sc_debug));
  429         if (error != 0)
  430                 sc->sc_debug = 0;
  431 #else
  432         sc->sc_debug = 0;
  433 #endif
  434 
  435         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: begin\n",__func__);
  436 
  437         /*
  438          * Get the offset of the PCI Express Capability Structure in PCI
  439          * Configuration Space.
  440          */
  441         error = pci_find_cap(dev, PCIY_EXPRESS, &sc->sc_cap_off);
  442         if (error != 0) {
  443                 device_printf(dev, "PCIe capability structure not found!\n");
  444                 return error;
  445         }
  446 
  447         /* Clear device-specific "PCI retry timeout" register (41h). */
  448         pci_write_config(dev, 0x41, 0, 1);
  449 
  450         /* Enable bus-mastering. */
  451         pci_enable_busmaster(dev);
  452 
  453         rid = PCIR_BAR(0);
  454         sc->mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
  455             RF_ACTIVE);
  456         if (sc->mem == NULL) {
  457                 device_printf(dev, "can't map mem space\n");
  458                 error = ENOMEM;
  459                 return error;
  460         }
  461         sc->sc_st = rman_get_bustag(sc->mem);
  462         sc->sc_sh = rman_get_bushandle(sc->mem);
  463 
  464         i = 1;
  465         rid = 0;
  466         if (pci_alloc_msi(dev, &i) == 0)
  467                 rid = 1;
  468         /* Install interrupt handler. */
  469         sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE |
  470             (rid != 0 ? 0 : RF_SHAREABLE));
  471         if (sc->irq == NULL) {
  472                 device_printf(dev, "can't map interrupt\n");
  473                 error = ENOMEM;
  474                 goto fail;
  475         }
  476 
  477         IWN_LOCK_INIT(sc);
  478 
  479         /* Read hardware revision and attach. */
  480         sc->hw_type = (IWN_READ(sc, IWN_HW_REV) >> IWN_HW_REV_TYPE_SHIFT)
  481             & IWN_HW_REV_TYPE_MASK;
  482         sc->subdevice_id = pci_get_subdevice(dev);
  483 
  484         /*
  485          * 4965 versus 5000 and later have different methods.
  486          * Let's set those up first.
  487          */
  488         if (sc->hw_type == IWN_HW_REV_TYPE_4965)
  489                 error = iwn4965_attach(sc, pci_get_device(dev));
  490         else
  491                 error = iwn5000_attach(sc, pci_get_device(dev));
  492         if (error != 0) {
  493                 device_printf(dev, "could not attach device, error %d\n",
  494                     error);
  495                 goto fail;
  496         }
  497 
  498         /*
  499          * Next, let's setup the various parameters of each NIC.
  500          */
  501         error = iwn_config_specific(sc, pci_get_device(dev));
  502         if (error != 0) {
  503                 device_printf(dev, "could not attach device, error %d\n",
  504                     error);
  505                 goto fail;
  506         }
  507 
  508         if ((error = iwn_hw_prepare(sc)) != 0) {
  509                 device_printf(dev, "hardware not ready, error %d\n", error);
  510                 goto fail;
  511         }
  512 
  513         /* Allocate DMA memory for firmware transfers. */
  514         if ((error = iwn_alloc_fwmem(sc)) != 0) {
  515                 device_printf(dev,
  516                     "could not allocate memory for firmware, error %d\n",
  517                     error);
  518                 goto fail;
  519         }
  520 
  521         /* Allocate "Keep Warm" page. */
  522         if ((error = iwn_alloc_kw(sc)) != 0) {
  523                 device_printf(dev,
  524                     "could not allocate keep warm page, error %d\n", error);
  525                 goto fail;
  526         }
  527 
  528         /* Allocate ICT table for 5000 Series. */
  529         if (sc->hw_type != IWN_HW_REV_TYPE_4965 &&
  530             (error = iwn_alloc_ict(sc)) != 0) {
  531                 device_printf(dev, "could not allocate ICT table, error %d\n",
  532                     error);
  533                 goto fail;
  534         }
  535 
  536         /* Allocate TX scheduler "rings". */
  537         if ((error = iwn_alloc_sched(sc)) != 0) {
  538                 device_printf(dev,
  539                     "could not allocate TX scheduler rings, error %d\n", error);
  540                 goto fail;
  541         }
  542 
  543         /* Allocate TX rings (16 on 4965AGN, 20 on >=5000). */
  544         for (i = 0; i < sc->ntxqs; i++) {
  545                 if ((error = iwn_alloc_tx_ring(sc, &sc->txq[i], i)) != 0) {
  546                         device_printf(dev,
  547                             "could not allocate TX ring %d, error %d\n", i,
  548                             error);
  549                         goto fail;
  550                 }
  551         }
  552 
  553         /* Allocate RX ring. */
  554         if ((error = iwn_alloc_rx_ring(sc, &sc->rxq)) != 0) {
  555                 device_printf(dev, "could not allocate RX ring, error %d\n",
  556                     error);
  557                 goto fail;
  558         }
  559 
  560         /* Clear pending interrupts. */
  561         IWN_WRITE(sc, IWN_INT, 0xffffffff);
  562 
  563         ic = &sc->sc_ic;
  564         ic->ic_softc = sc;
  565         ic->ic_name = device_get_nameunit(dev);
  566         ic->ic_phytype = IEEE80211_T_OFDM;      /* not only, but not used */
  567         ic->ic_opmode = IEEE80211_M_STA;        /* default to BSS mode */
  568 
  569         /* Set device capabilities. */
  570         ic->ic_caps =
  571                   IEEE80211_C_STA               /* station mode supported */
  572                 | IEEE80211_C_MONITOR           /* monitor mode supported */
  573 #if 0
  574                 | IEEE80211_C_BGSCAN            /* background scanning */
  575 #endif
  576                 | IEEE80211_C_TXPMGT            /* tx power management */
  577                 | IEEE80211_C_SHSLOT            /* short slot time supported */
  578                 | IEEE80211_C_WPA
  579                 | IEEE80211_C_SHPREAMBLE        /* short preamble supported */
  580 #if 0
  581                 | IEEE80211_C_IBSS              /* ibss/adhoc mode */
  582 #endif
  583                 | IEEE80211_C_WME               /* WME */
  584                 | IEEE80211_C_PMGT              /* Station-side power mgmt */
  585                 ;
  586 
  587         /* Read MAC address, channels, etc from EEPROM. */
  588         if ((error = iwn_read_eeprom(sc, ic->ic_macaddr)) != 0) {
  589                 device_printf(dev, "could not read EEPROM, error %d\n",
  590                     error);
  591                 goto fail;
  592         }
  593 
  594         /* Count the number of available chains. */
  595         sc->ntxchains =
  596             ((sc->txchainmask >> 2) & 1) +
  597             ((sc->txchainmask >> 1) & 1) +
  598             ((sc->txchainmask >> 0) & 1);
  599         sc->nrxchains =
  600             ((sc->rxchainmask >> 2) & 1) +
  601             ((sc->rxchainmask >> 1) & 1) +
  602             ((sc->rxchainmask >> 0) & 1);
  603         if (bootverbose) {
  604                 device_printf(dev, "MIMO %dT%dR, %.4s, address %6D\n",
  605                     sc->ntxchains, sc->nrxchains, sc->eeprom_domain,
  606                     ic->ic_macaddr, ":");
  607         }
  608 
  609         if (sc->sc_flags & IWN_FLAG_HAS_11N) {
  610                 ic->ic_rxstream = sc->nrxchains;
  611                 ic->ic_txstream = sc->ntxchains;
  612 
  613                 /*
  614                  * Some of the 3 antenna devices (ie, the 4965) only supports
  615                  * 2x2 operation.  So correct the number of streams if
  616                  * it's not a 3-stream device.
  617                  */
  618                 if (! iwn_is_3stream_device(sc)) {
  619                         if (ic->ic_rxstream > 2)
  620                                 ic->ic_rxstream = 2;
  621                         if (ic->ic_txstream > 2)
  622                                 ic->ic_txstream = 2;
  623                 }
  624 
  625                 ic->ic_htcaps =
  626                           IEEE80211_HTCAP_SMPS_OFF      /* SMPS mode disabled */
  627                         | IEEE80211_HTCAP_SHORTGI20     /* short GI in 20MHz */
  628                         | IEEE80211_HTCAP_CHWIDTH40     /* 40MHz channel width*/
  629                         | IEEE80211_HTCAP_SHORTGI40     /* short GI in 40MHz */
  630 #ifdef notyet
  631                         | IEEE80211_HTCAP_GREENFIELD
  632 #if IWN_RBUF_SIZE == 8192
  633                         | IEEE80211_HTCAP_MAXAMSDU_7935 /* max A-MSDU length */
  634 #else
  635                         | IEEE80211_HTCAP_MAXAMSDU_3839 /* max A-MSDU length */
  636 #endif
  637 #endif
  638                         /* s/w capabilities */
  639                         | IEEE80211_HTC_HT              /* HT operation */
  640                         | IEEE80211_HTC_AMPDU           /* tx A-MPDU */
  641 #ifdef notyet
  642                         | IEEE80211_HTC_AMSDU           /* tx A-MSDU */
  643 #endif
  644                         ;
  645         }
  646 
  647         ieee80211_ifattach(ic);
  648         ic->ic_vap_create = iwn_vap_create;
  649         ic->ic_ioctl = iwn_ioctl;
  650         ic->ic_parent = iwn_parent;
  651         ic->ic_vap_delete = iwn_vap_delete;
  652         ic->ic_transmit = iwn_transmit;
  653         ic->ic_raw_xmit = iwn_raw_xmit;
  654         ic->ic_node_alloc = iwn_node_alloc;
  655         sc->sc_ampdu_rx_start = ic->ic_ampdu_rx_start;
  656         ic->ic_ampdu_rx_start = iwn_ampdu_rx_start;
  657         sc->sc_ampdu_rx_stop = ic->ic_ampdu_rx_stop;
  658         ic->ic_ampdu_rx_stop = iwn_ampdu_rx_stop;
  659         sc->sc_addba_request = ic->ic_addba_request;
  660         ic->ic_addba_request = iwn_addba_request;
  661         sc->sc_addba_response = ic->ic_addba_response;
  662         ic->ic_addba_response = iwn_addba_response;
  663         sc->sc_addba_stop = ic->ic_addba_stop;
  664         ic->ic_addba_stop = iwn_ampdu_tx_stop;
  665         ic->ic_newassoc = iwn_newassoc;
  666         ic->ic_wme.wme_update = iwn_updateedca;
  667         ic->ic_update_mcast = iwn_update_mcast;
  668         ic->ic_scan_start = iwn_scan_start;
  669         ic->ic_scan_end = iwn_scan_end;
  670         ic->ic_set_channel = iwn_set_channel;
  671         ic->ic_scan_curchan = iwn_scan_curchan;
  672         ic->ic_scan_mindwell = iwn_scan_mindwell;
  673         ic->ic_getradiocaps = iwn_getradiocaps;
  674         ic->ic_setregdomain = iwn_setregdomain;
  675 
  676         iwn_radiotap_attach(sc);
  677 
  678         callout_init_mtx(&sc->calib_to, &sc->sc_mtx, 0);
  679         callout_init_mtx(&sc->scan_timeout, &sc->sc_mtx, 0);
  680         callout_init_mtx(&sc->watchdog_to, &sc->sc_mtx, 0);
  681         TASK_INIT(&sc->sc_radioon_task, 0, iwn_radio_on, sc);
  682         TASK_INIT(&sc->sc_radiooff_task, 0, iwn_radio_off, sc);
  683         TASK_INIT(&sc->sc_panic_task, 0, iwn_panicked, sc);
  684         TASK_INIT(&sc->sc_xmit_task, 0, iwn_xmit_task, sc);
  685 
  686         mbufq_init(&sc->sc_xmit_queue, 1024);
  687 
  688         sc->sc_tq = taskqueue_create("iwn_taskq", M_WAITOK,
  689             taskqueue_thread_enqueue, &sc->sc_tq);
  690         error = taskqueue_start_threads(&sc->sc_tq, 1, 0, "iwn_taskq");
  691         if (error != 0) {
  692                 device_printf(dev, "can't start threads, error %d\n", error);
  693                 goto fail;
  694         }
  695 
  696         iwn_sysctlattach(sc);
  697 
  698         /*
  699          * Hook our interrupt after all initialization is complete.
  700          */
  701         error = bus_setup_intr(dev, sc->irq, INTR_TYPE_NET | INTR_MPSAFE,
  702             NULL, iwn_intr, sc, &sc->sc_ih);
  703         if (error != 0) {
  704                 device_printf(dev, "can't establish interrupt, error %d\n",
  705                     error);
  706                 goto fail;
  707         }
  708 
  709 #if 0
  710         device_printf(sc->sc_dev, "%s: rx_stats=%d, rx_stats_bt=%d\n",
  711             __func__,
  712             sizeof(struct iwn_stats),
  713             sizeof(struct iwn_stats_bt));
  714 #endif
  715 
  716         if (bootverbose)
  717                 ieee80211_announce(ic);
  718         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
  719 
  720         /* Add debug ioctl right at the end */
  721         sc->sc_cdev = make_dev(&iwn_cdevsw, device_get_unit(dev),
  722             UID_ROOT, GID_WHEEL, 0600, "%s", device_get_nameunit(dev));
  723         if (sc->sc_cdev == NULL) {
  724                 device_printf(dev, "failed to create debug character device\n");
  725         } else {
  726                 sc->sc_cdev->si_drv1 = sc;
  727         }
  728         return 0;
  729 fail:
  730         iwn_detach(dev);
  731         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end in error\n",__func__);
  732         return error;
  733 }
  734 
  735 /*
  736  * Define specific configuration based on device id and subdevice id
  737  * pid : PCI device id
  738  */
  739 static int
  740 iwn_config_specific(struct iwn_softc *sc, uint16_t pid)
  741 {
  742 
  743         switch (pid) {
  744 /* 4965 series */
  745         case IWN_DID_4965_1:
  746         case IWN_DID_4965_2:
  747         case IWN_DID_4965_3:
  748         case IWN_DID_4965_4:
  749                 sc->base_params = &iwn4965_base_params;
  750                 sc->limits = &iwn4965_sensitivity_limits;
  751                 sc->fwname = "iwn4965fw";
  752                 /* Override chains masks, ROM is known to be broken. */
  753                 sc->txchainmask = IWN_ANT_AB;
  754                 sc->rxchainmask = IWN_ANT_ABC;
  755                 /* Enable normal btcoex */
  756                 sc->sc_flags |= IWN_FLAG_BTCOEX;
  757                 break;
  758 /* 1000 Series */
  759         case IWN_DID_1000_1:
  760         case IWN_DID_1000_2:
  761                 switch(sc->subdevice_id) {
  762                         case    IWN_SDID_1000_1:
  763                         case    IWN_SDID_1000_2:
  764                         case    IWN_SDID_1000_3:
  765                         case    IWN_SDID_1000_4:
  766                         case    IWN_SDID_1000_5:
  767                         case    IWN_SDID_1000_6:
  768                         case    IWN_SDID_1000_7:
  769                         case    IWN_SDID_1000_8:
  770                         case    IWN_SDID_1000_9:
  771                         case    IWN_SDID_1000_10:
  772                         case    IWN_SDID_1000_11:
  773                         case    IWN_SDID_1000_12:
  774                                 sc->limits = &iwn1000_sensitivity_limits;
  775                                 sc->base_params = &iwn1000_base_params;
  776                                 sc->fwname = "iwn1000fw";
  777                                 break;
  778                         default:
  779                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
  780                                     "0x%04x rev %d not supported (subdevice)\n", pid,
  781                                     sc->subdevice_id,sc->hw_type);
  782                                 return ENOTSUP;
  783                 }
  784                 break;
  785 /* 6x00 Series */
  786         case IWN_DID_6x00_2:
  787         case IWN_DID_6x00_4:
  788         case IWN_DID_6x00_1:
  789         case IWN_DID_6x00_3:
  790                 sc->fwname = "iwn6000fw";
  791                 sc->limits = &iwn6000_sensitivity_limits;
  792                 switch(sc->subdevice_id) {
  793                         case IWN_SDID_6x00_1:
  794                         case IWN_SDID_6x00_2:
  795                         case IWN_SDID_6x00_8:
  796                                 //iwl6000_3agn_cfg
  797                                 sc->base_params = &iwn_6000_base_params;
  798                                 break;
  799                         case IWN_SDID_6x00_3:
  800                         case IWN_SDID_6x00_6:
  801                         case IWN_SDID_6x00_9:
  802                                 ////iwl6000i_2agn
  803                         case IWN_SDID_6x00_4:
  804                         case IWN_SDID_6x00_7:
  805                         case IWN_SDID_6x00_10:
  806                                 //iwl6000i_2abg_cfg
  807                         case IWN_SDID_6x00_5:
  808                                 //iwl6000i_2bg_cfg
  809                                 sc->base_params = &iwn_6000i_base_params;
  810                                 sc->sc_flags |= IWN_FLAG_INTERNAL_PA;
  811                                 sc->txchainmask = IWN_ANT_BC;
  812                                 sc->rxchainmask = IWN_ANT_BC;
  813                                 break;
  814                         default:
  815                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
  816                                     "0x%04x rev %d not supported (subdevice)\n", pid,
  817                                     sc->subdevice_id,sc->hw_type);
  818                                 return ENOTSUP;
  819                 }
  820                 break;
  821 /* 6x05 Series */
  822         case IWN_DID_6x05_1:
  823         case IWN_DID_6x05_2:
  824                 switch(sc->subdevice_id) {
  825                         case IWN_SDID_6x05_1:
  826                         case IWN_SDID_6x05_4:
  827                         case IWN_SDID_6x05_6:
  828                                 //iwl6005_2agn_cfg
  829                         case IWN_SDID_6x05_2:
  830                         case IWN_SDID_6x05_5:
  831                         case IWN_SDID_6x05_7:
  832                                 //iwl6005_2abg_cfg
  833                         case IWN_SDID_6x05_3:
  834                                 //iwl6005_2bg_cfg
  835                         case IWN_SDID_6x05_8:
  836                         case IWN_SDID_6x05_9:
  837                                 //iwl6005_2agn_sff_cfg
  838                         case IWN_SDID_6x05_10:
  839                                 //iwl6005_2agn_d_cfg
  840                         case IWN_SDID_6x05_11:
  841                                 //iwl6005_2agn_mow1_cfg
  842                         case IWN_SDID_6x05_12:
  843                                 //iwl6005_2agn_mow2_cfg
  844                                 sc->fwname = "iwn6000g2afw";
  845                                 sc->limits = &iwn6000_sensitivity_limits;
  846                                 sc->base_params = &iwn_6000g2_base_params;
  847                                 break;
  848                         default:
  849                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
  850                                     "0x%04x rev %d not supported (subdevice)\n", pid,
  851                                     sc->subdevice_id,sc->hw_type);
  852                                 return ENOTSUP;
  853                 }
  854                 break;
  855 /* 6x35 Series */
  856         case IWN_DID_6035_1:
  857         case IWN_DID_6035_2:
  858                 switch(sc->subdevice_id) {
  859                         case IWN_SDID_6035_1:
  860                         case IWN_SDID_6035_2:
  861                         case IWN_SDID_6035_3:
  862                         case IWN_SDID_6035_4:
  863                                 sc->fwname = "iwn6000g2bfw";
  864                                 sc->limits = &iwn6235_sensitivity_limits;
  865                                 sc->base_params = &iwn_6235_base_params;
  866                                 break;
  867                         default:
  868                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
  869                                     "0x%04x rev %d not supported (subdevice)\n", pid,
  870                                     sc->subdevice_id,sc->hw_type);
  871                                 return ENOTSUP;
  872                 }
  873                 break;
  874 /* 6x50 WiFi/WiMax Series */
  875         case IWN_DID_6050_1:
  876         case IWN_DID_6050_2:
  877                 switch(sc->subdevice_id) {
  878                         case IWN_SDID_6050_1:
  879                         case IWN_SDID_6050_3:
  880                         case IWN_SDID_6050_5:
  881                                 //iwl6050_2agn_cfg
  882                         case IWN_SDID_6050_2:
  883                         case IWN_SDID_6050_4:
  884                         case IWN_SDID_6050_6:
  885                                 //iwl6050_2abg_cfg
  886                                 sc->fwname = "iwn6050fw";
  887                                 sc->txchainmask = IWN_ANT_AB;
  888                                 sc->rxchainmask = IWN_ANT_AB;
  889                                 sc->limits = &iwn6000_sensitivity_limits;
  890                                 sc->base_params = &iwn_6050_base_params;
  891                                 break;
  892                         default:
  893                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
  894                                     "0x%04x rev %d not supported (subdevice)\n", pid,
  895                                     sc->subdevice_id,sc->hw_type);
  896                                 return ENOTSUP;
  897                 }
  898                 break;
  899 /* 6150 WiFi/WiMax Series */
  900         case IWN_DID_6150_1:
  901         case IWN_DID_6150_2:
  902                 switch(sc->subdevice_id) {
  903                         case IWN_SDID_6150_1:
  904                         case IWN_SDID_6150_3:
  905                         case IWN_SDID_6150_5:
  906                                 // iwl6150_bgn_cfg
  907                         case IWN_SDID_6150_2:
  908                         case IWN_SDID_6150_4:
  909                         case IWN_SDID_6150_6:
  910                                 //iwl6150_bg_cfg
  911                                 sc->fwname = "iwn6050fw";
  912                                 sc->limits = &iwn6000_sensitivity_limits;
  913                                 sc->base_params = &iwn_6150_base_params;
  914                                 break;
  915                         default:
  916                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
  917                                     "0x%04x rev %d not supported (subdevice)\n", pid,
  918                                     sc->subdevice_id,sc->hw_type);
  919                                 return ENOTSUP;
  920                 }
  921                 break;
  922 /* 6030 Series and 1030 Series */
  923         case IWN_DID_x030_1:
  924         case IWN_DID_x030_2:
  925         case IWN_DID_x030_3:
  926         case IWN_DID_x030_4:
  927                 switch(sc->subdevice_id) {
  928                         case IWN_SDID_x030_1:
  929                         case IWN_SDID_x030_3:
  930                         case IWN_SDID_x030_5:
  931                         // iwl1030_bgn_cfg
  932                         case IWN_SDID_x030_2:
  933                         case IWN_SDID_x030_4:
  934                         case IWN_SDID_x030_6:
  935                         //iwl1030_bg_cfg
  936                         case IWN_SDID_x030_7:
  937                         case IWN_SDID_x030_10:
  938                         case IWN_SDID_x030_14:
  939                         //iwl6030_2agn_cfg
  940                         case IWN_SDID_x030_8:
  941                         case IWN_SDID_x030_11:
  942                         case IWN_SDID_x030_15:
  943                         // iwl6030_2bgn_cfg
  944                         case IWN_SDID_x030_9:
  945                         case IWN_SDID_x030_12:
  946                         case IWN_SDID_x030_16:
  947                         // iwl6030_2abg_cfg
  948                         case IWN_SDID_x030_13:
  949                         //iwl6030_2bg_cfg
  950                                 sc->fwname = "iwn6000g2bfw";
  951                                 sc->limits = &iwn6000_sensitivity_limits;
  952                                 sc->base_params = &iwn_6000g2b_base_params;
  953                                 break;
  954                         default:
  955                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
  956                                     "0x%04x rev %d not supported (subdevice)\n", pid,
  957                                     sc->subdevice_id,sc->hw_type);
  958                                 return ENOTSUP;
  959                 }
  960                 break;
  961 /* 130 Series WiFi */
  962 /* XXX: This series will need adjustment for rate.
  963  * see rx_with_siso_diversity in linux kernel
  964  */
  965         case IWN_DID_130_1:
  966         case IWN_DID_130_2:
  967                 switch(sc->subdevice_id) {
  968                         case IWN_SDID_130_1:
  969                         case IWN_SDID_130_3:
  970                         case IWN_SDID_130_5:
  971                         //iwl130_bgn_cfg
  972                         case IWN_SDID_130_2:
  973                         case IWN_SDID_130_4:
  974                         case IWN_SDID_130_6:
  975                         //iwl130_bg_cfg
  976                                 sc->fwname = "iwn6000g2bfw";
  977                                 sc->limits = &iwn6000_sensitivity_limits;
  978                                 sc->base_params = &iwn_6000g2b_base_params;
  979                                 break;
  980                         default:
  981                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
  982                                     "0x%04x rev %d not supported (subdevice)\n", pid,
  983                                     sc->subdevice_id,sc->hw_type);
  984                                 return ENOTSUP;
  985                 }
  986                 break;
  987 /* 100 Series WiFi */
  988         case IWN_DID_100_1:
  989         case IWN_DID_100_2:
  990                 switch(sc->subdevice_id) {
  991                         case IWN_SDID_100_1:
  992                         case IWN_SDID_100_2:
  993                         case IWN_SDID_100_3:
  994                         case IWN_SDID_100_4:
  995                         case IWN_SDID_100_5:
  996                         case IWN_SDID_100_6:
  997                                 sc->limits = &iwn1000_sensitivity_limits;
  998                                 sc->base_params = &iwn1000_base_params;
  999                                 sc->fwname = "iwn100fw";
 1000                                 break;
 1001                         default:
 1002                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
 1003                                     "0x%04x rev %d not supported (subdevice)\n", pid,
 1004                                     sc->subdevice_id,sc->hw_type);
 1005                                 return ENOTSUP;
 1006                 }
 1007                 break;
 1008 
 1009 /* 105 Series */
 1010 /* XXX: This series will need adjustment for rate.
 1011  * see rx_with_siso_diversity in linux kernel
 1012  */
 1013         case IWN_DID_105_1:
 1014         case IWN_DID_105_2:
 1015                 switch(sc->subdevice_id) {
 1016                         case IWN_SDID_105_1:
 1017                         case IWN_SDID_105_2:
 1018                         case IWN_SDID_105_3:
 1019                         //iwl105_bgn_cfg
 1020                         case IWN_SDID_105_4:
 1021                         //iwl105_bgn_d_cfg
 1022                                 sc->limits = &iwn2030_sensitivity_limits;
 1023                                 sc->base_params = &iwn2000_base_params;
 1024                                 sc->fwname = "iwn105fw";
 1025                                 break;
 1026                         default:
 1027                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
 1028                                     "0x%04x rev %d not supported (subdevice)\n", pid,
 1029                                     sc->subdevice_id,sc->hw_type);
 1030                                 return ENOTSUP;
 1031                 }
 1032                 break;
 1033 
 1034 /* 135 Series */
 1035 /* XXX: This series will need adjustment for rate.
 1036  * see rx_with_siso_diversity in linux kernel
 1037  */
 1038         case IWN_DID_135_1:
 1039         case IWN_DID_135_2:
 1040                 switch(sc->subdevice_id) {
 1041                         case IWN_SDID_135_1:
 1042                         case IWN_SDID_135_2:
 1043                         case IWN_SDID_135_3:
 1044                                 sc->limits = &iwn2030_sensitivity_limits;
 1045                                 sc->base_params = &iwn2030_base_params;
 1046                                 sc->fwname = "iwn135fw";
 1047                                 break;
 1048                         default:
 1049                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
 1050                                     "0x%04x rev %d not supported (subdevice)\n", pid,
 1051                                     sc->subdevice_id,sc->hw_type);
 1052                                 return ENOTSUP;
 1053                 }
 1054                 break;
 1055 
 1056 /* 2x00 Series */
 1057         case IWN_DID_2x00_1:
 1058         case IWN_DID_2x00_2:
 1059                 switch(sc->subdevice_id) {
 1060                         case IWN_SDID_2x00_1:
 1061                         case IWN_SDID_2x00_2:
 1062                         case IWN_SDID_2x00_3:
 1063                         //iwl2000_2bgn_cfg
 1064                         case IWN_SDID_2x00_4:
 1065                         //iwl2000_2bgn_d_cfg
 1066                                 sc->limits = &iwn2030_sensitivity_limits;
 1067                                 sc->base_params = &iwn2000_base_params;
 1068                                 sc->fwname = "iwn2000fw";
 1069                                 break;
 1070                         default:
 1071                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
 1072                                     "0x%04x rev %d not supported (subdevice) \n",
 1073                                     pid, sc->subdevice_id, sc->hw_type);
 1074                                 return ENOTSUP;
 1075                 }
 1076                 break;
 1077 /* 2x30 Series */
 1078         case IWN_DID_2x30_1:
 1079         case IWN_DID_2x30_2:
 1080                 switch(sc->subdevice_id) {
 1081                         case IWN_SDID_2x30_1:
 1082                         case IWN_SDID_2x30_3:
 1083                         case IWN_SDID_2x30_5:
 1084                         //iwl100_bgn_cfg
 1085                         case IWN_SDID_2x30_2:
 1086                         case IWN_SDID_2x30_4:
 1087                         case IWN_SDID_2x30_6:
 1088                         //iwl100_bg_cfg
 1089                                 sc->limits = &iwn2030_sensitivity_limits;
 1090                                 sc->base_params = &iwn2030_base_params;
 1091                                 sc->fwname = "iwn2030fw";
 1092                                 break;
 1093                         default:
 1094                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
 1095                                     "0x%04x rev %d not supported (subdevice)\n", pid,
 1096                                     sc->subdevice_id,sc->hw_type);
 1097                                 return ENOTSUP;
 1098                 }
 1099                 break;
 1100 /* 5x00 Series */
 1101         case IWN_DID_5x00_1:
 1102         case IWN_DID_5x00_2:
 1103         case IWN_DID_5x00_3:
 1104         case IWN_DID_5x00_4:
 1105                 sc->limits = &iwn5000_sensitivity_limits;
 1106                 sc->base_params = &iwn5000_base_params;
 1107                 sc->fwname = "iwn5000fw";
 1108                 switch(sc->subdevice_id) {
 1109                         case IWN_SDID_5x00_1:
 1110                         case IWN_SDID_5x00_2:
 1111                         case IWN_SDID_5x00_3:
 1112                         case IWN_SDID_5x00_4:
 1113                         case IWN_SDID_5x00_9:
 1114                         case IWN_SDID_5x00_10:
 1115                         case IWN_SDID_5x00_11:
 1116                         case IWN_SDID_5x00_12:
 1117                         case IWN_SDID_5x00_17:
 1118                         case IWN_SDID_5x00_18:
 1119                         case IWN_SDID_5x00_19:
 1120                         case IWN_SDID_5x00_20:
 1121                         //iwl5100_agn_cfg
 1122                                 sc->txchainmask = IWN_ANT_B;
 1123                                 sc->rxchainmask = IWN_ANT_AB;
 1124                                 break;
 1125                         case IWN_SDID_5x00_5:
 1126                         case IWN_SDID_5x00_6:
 1127                         case IWN_SDID_5x00_13:
 1128                         case IWN_SDID_5x00_14:
 1129                         case IWN_SDID_5x00_21:
 1130                         case IWN_SDID_5x00_22:
 1131                         //iwl5100_bgn_cfg
 1132                                 sc->txchainmask = IWN_ANT_B;
 1133                                 sc->rxchainmask = IWN_ANT_AB;
 1134                                 break;
 1135                         case IWN_SDID_5x00_7:
 1136                         case IWN_SDID_5x00_8:
 1137                         case IWN_SDID_5x00_15:
 1138                         case IWN_SDID_5x00_16:
 1139                         case IWN_SDID_5x00_23:
 1140                         case IWN_SDID_5x00_24:
 1141                         //iwl5100_abg_cfg
 1142                                 sc->txchainmask = IWN_ANT_B;
 1143                                 sc->rxchainmask = IWN_ANT_AB;
 1144                                 break;
 1145                         case IWN_SDID_5x00_25:
 1146                         case IWN_SDID_5x00_26:
 1147                         case IWN_SDID_5x00_27:
 1148                         case IWN_SDID_5x00_28:
 1149                         case IWN_SDID_5x00_29:
 1150                         case IWN_SDID_5x00_30:
 1151                         case IWN_SDID_5x00_31:
 1152                         case IWN_SDID_5x00_32:
 1153                         case IWN_SDID_5x00_33:
 1154                         case IWN_SDID_5x00_34:
 1155                         case IWN_SDID_5x00_35:
 1156                         case IWN_SDID_5x00_36:
 1157                         //iwl5300_agn_cfg
 1158                                 sc->txchainmask = IWN_ANT_ABC;
 1159                                 sc->rxchainmask = IWN_ANT_ABC;
 1160                                 break;
 1161                         default:
 1162                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
 1163                                     "0x%04x rev %d not supported (subdevice)\n", pid,
 1164                                     sc->subdevice_id,sc->hw_type);
 1165                                 return ENOTSUP;
 1166                 }
 1167                 break;
 1168 /* 5x50 Series */
 1169         case IWN_DID_5x50_1:
 1170         case IWN_DID_5x50_2:
 1171         case IWN_DID_5x50_3:
 1172         case IWN_DID_5x50_4:
 1173                 sc->limits = &iwn5000_sensitivity_limits;
 1174                 sc->base_params = &iwn5000_base_params;
 1175                 sc->fwname = "iwn5000fw";
 1176                 switch(sc->subdevice_id) {
 1177                         case IWN_SDID_5x50_1:
 1178                         case IWN_SDID_5x50_2:
 1179                         case IWN_SDID_5x50_3:
 1180                         //iwl5350_agn_cfg
 1181                                 sc->limits = &iwn5000_sensitivity_limits;
 1182                                 sc->base_params = &iwn5000_base_params;
 1183                                 sc->fwname = "iwn5000fw";
 1184                                 break;
 1185                         case IWN_SDID_5x50_4:
 1186                         case IWN_SDID_5x50_5:
 1187                         case IWN_SDID_5x50_8:
 1188                         case IWN_SDID_5x50_9:
 1189                         case IWN_SDID_5x50_10:
 1190                         case IWN_SDID_5x50_11:
 1191                         //iwl5150_agn_cfg
 1192                         case IWN_SDID_5x50_6:
 1193                         case IWN_SDID_5x50_7:
 1194                         case IWN_SDID_5x50_12:
 1195                         case IWN_SDID_5x50_13:
 1196                         //iwl5150_abg_cfg
 1197                                 sc->limits = &iwn5000_sensitivity_limits;
 1198                                 sc->fwname = "iwn5150fw";
 1199                                 sc->base_params = &iwn_5x50_base_params;
 1200                                 break;
 1201                         default:
 1202                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
 1203                                     "0x%04x rev %d not supported (subdevice)\n", pid,
 1204                                     sc->subdevice_id,sc->hw_type);
 1205                                 return ENOTSUP;
 1206                 }
 1207                 break;
 1208         default:
 1209                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id : 0x%04x"
 1210                     "rev 0x%08x not supported (device)\n", pid, sc->subdevice_id,
 1211                      sc->hw_type);
 1212                 return ENOTSUP;
 1213         }
 1214         return 0;
 1215 }
 1216 
 1217 static int
 1218 iwn4965_attach(struct iwn_softc *sc, uint16_t pid)
 1219 {
 1220         struct iwn_ops *ops = &sc->ops;
 1221 
 1222         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 1223         ops->load_firmware = iwn4965_load_firmware;
 1224         ops->read_eeprom = iwn4965_read_eeprom;
 1225         ops->post_alive = iwn4965_post_alive;
 1226         ops->nic_config = iwn4965_nic_config;
 1227         ops->update_sched = iwn4965_update_sched;
 1228         ops->get_temperature = iwn4965_get_temperature;
 1229         ops->get_rssi = iwn4965_get_rssi;
 1230         ops->set_txpower = iwn4965_set_txpower;
 1231         ops->init_gains = iwn4965_init_gains;
 1232         ops->set_gains = iwn4965_set_gains;
 1233         ops->add_node = iwn4965_add_node;
 1234         ops->tx_done = iwn4965_tx_done;
 1235         ops->ampdu_tx_start = iwn4965_ampdu_tx_start;
 1236         ops->ampdu_tx_stop = iwn4965_ampdu_tx_stop;
 1237         sc->ntxqs = IWN4965_NTXQUEUES;
 1238         sc->firstaggqueue = IWN4965_FIRSTAGGQUEUE;
 1239         sc->ndmachnls = IWN4965_NDMACHNLS;
 1240         sc->broadcast_id = IWN4965_ID_BROADCAST;
 1241         sc->rxonsz = IWN4965_RXONSZ;
 1242         sc->schedsz = IWN4965_SCHEDSZ;
 1243         sc->fw_text_maxsz = IWN4965_FW_TEXT_MAXSZ;
 1244         sc->fw_data_maxsz = IWN4965_FW_DATA_MAXSZ;
 1245         sc->fwsz = IWN4965_FWSZ;
 1246         sc->sched_txfact_addr = IWN4965_SCHED_TXFACT;
 1247         sc->limits = &iwn4965_sensitivity_limits;
 1248         sc->fwname = "iwn4965fw";
 1249         /* Override chains masks, ROM is known to be broken. */
 1250         sc->txchainmask = IWN_ANT_AB;
 1251         sc->rxchainmask = IWN_ANT_ABC;
 1252         /* Enable normal btcoex */
 1253         sc->sc_flags |= IWN_FLAG_BTCOEX;
 1254 
 1255         DPRINTF(sc, IWN_DEBUG_TRACE, "%s: end\n",__func__);
 1256 
 1257         return 0;
 1258 }
 1259 
 1260 static int
 1261 iwn5000_attach(struct iwn_softc *sc, uint16_t pid)
 1262 {
 1263         struct iwn_ops *ops = &sc->ops;
 1264 
 1265         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 1266 
 1267         ops->load_firmware = iwn5000_load_firmware;
 1268         ops->read_eeprom = iwn5000_read_eeprom;
 1269         ops->post_alive = iwn5000_post_alive;
 1270         ops->nic_config = iwn5000_nic_config;
 1271         ops->update_sched = iwn5000_update_sched;
 1272         ops->get_temperature = iwn5000_get_temperature;
 1273         ops->get_rssi = iwn5000_get_rssi;
 1274         ops->set_txpower = iwn5000_set_txpower;
 1275         ops->init_gains = iwn5000_init_gains;
 1276         ops->set_gains = iwn5000_set_gains;
 1277         ops->add_node = iwn5000_add_node;
 1278         ops->tx_done = iwn5000_tx_done;
 1279         ops->ampdu_tx_start = iwn5000_ampdu_tx_start;
 1280         ops->ampdu_tx_stop = iwn5000_ampdu_tx_stop;
 1281         sc->ntxqs = IWN5000_NTXQUEUES;
 1282         sc->firstaggqueue = IWN5000_FIRSTAGGQUEUE;
 1283         sc->ndmachnls = IWN5000_NDMACHNLS;
 1284         sc->broadcast_id = IWN5000_ID_BROADCAST;
 1285         sc->rxonsz = IWN5000_RXONSZ;
 1286         sc->schedsz = IWN5000_SCHEDSZ;
 1287         sc->fw_text_maxsz = IWN5000_FW_TEXT_MAXSZ;
 1288         sc->fw_data_maxsz = IWN5000_FW_DATA_MAXSZ;
 1289         sc->fwsz = IWN5000_FWSZ;
 1290         sc->sched_txfact_addr = IWN5000_SCHED_TXFACT;
 1291         sc->reset_noise_gain = IWN5000_PHY_CALIB_RESET_NOISE_GAIN;
 1292         sc->noise_gain = IWN5000_PHY_CALIB_NOISE_GAIN;
 1293 
 1294         return 0;
 1295 }
 1296 
 1297 /*
 1298  * Attach the interface to 802.11 radiotap.
 1299  */
 1300 static void
 1301 iwn_radiotap_attach(struct iwn_softc *sc)
 1302 {
 1303 
 1304         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 1305         ieee80211_radiotap_attach(&sc->sc_ic,
 1306             &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap),
 1307                 IWN_TX_RADIOTAP_PRESENT,
 1308             &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
 1309                 IWN_RX_RADIOTAP_PRESENT);
 1310         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
 1311 }
 1312 
 1313 static void
 1314 iwn_sysctlattach(struct iwn_softc *sc)
 1315 {
 1316 #ifdef  IWN_DEBUG
 1317         struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
 1318         struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
 1319 
 1320         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
 1321             "debug", CTLFLAG_RW, &sc->sc_debug, sc->sc_debug,
 1322                 "control debugging printfs");
 1323 #endif
 1324 }
 1325 
 1326 static struct ieee80211vap *
 1327 iwn_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
 1328     enum ieee80211_opmode opmode, int flags,
 1329     const uint8_t bssid[IEEE80211_ADDR_LEN],
 1330     const uint8_t mac[IEEE80211_ADDR_LEN])
 1331 {
 1332         struct iwn_softc *sc = ic->ic_softc;
 1333         struct iwn_vap *ivp;
 1334         struct ieee80211vap *vap;
 1335 
 1336         if (!TAILQ_EMPTY(&ic->ic_vaps))         /* only one at a time */
 1337                 return NULL;
 1338 
 1339         ivp = malloc(sizeof(struct iwn_vap), M_80211_VAP, M_WAITOK | M_ZERO);
 1340         vap = &ivp->iv_vap;
 1341         ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid);
 1342         ivp->ctx = IWN_RXON_BSS_CTX;
 1343         vap->iv_bmissthreshold = 10;            /* override default */
 1344         /* Override with driver methods. */
 1345         ivp->iv_newstate = vap->iv_newstate;
 1346         vap->iv_newstate = iwn_newstate;
 1347         sc->ivap[IWN_RXON_BSS_CTX] = vap;
 1348 
 1349         ieee80211_ratectl_init(vap);
 1350         /* Complete setup. */
 1351         ieee80211_vap_attach(vap, iwn_media_change, ieee80211_media_status,
 1352             mac);
 1353         ic->ic_opmode = opmode;
 1354         return vap;
 1355 }
 1356 
 1357 static void
 1358 iwn_vap_delete(struct ieee80211vap *vap)
 1359 {
 1360         struct iwn_vap *ivp = IWN_VAP(vap);
 1361 
 1362         ieee80211_ratectl_deinit(vap);
 1363         ieee80211_vap_detach(vap);
 1364         free(ivp, M_80211_VAP);
 1365 }
 1366 
 1367 static void
 1368 iwn_xmit_queue_drain(struct iwn_softc *sc)
 1369 {
 1370         struct mbuf *m;
 1371         struct ieee80211_node *ni;
 1372 
 1373         IWN_LOCK_ASSERT(sc);
 1374         while ((m = mbufq_dequeue(&sc->sc_xmit_queue)) != NULL) {
 1375                 ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
 1376                 ieee80211_free_node(ni);
 1377                 m_freem(m);
 1378         }
 1379 }
 1380 
 1381 static int
 1382 iwn_xmit_queue_enqueue(struct iwn_softc *sc, struct mbuf *m)
 1383 {
 1384 
 1385         IWN_LOCK_ASSERT(sc);
 1386         return (mbufq_enqueue(&sc->sc_xmit_queue, m));
 1387 }
 1388 
 1389 static int
 1390 iwn_detach(device_t dev)
 1391 {
 1392         struct iwn_softc *sc = device_get_softc(dev);
 1393         int qid;
 1394 
 1395         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 1396 
 1397         if (sc->sc_ic.ic_softc != NULL) {
 1398                 /* Free the mbuf queue and node references */
 1399                 IWN_LOCK(sc);
 1400                 iwn_xmit_queue_drain(sc);
 1401                 IWN_UNLOCK(sc);
 1402 
 1403                 ieee80211_draintask(&sc->sc_ic, &sc->sc_radioon_task);
 1404                 ieee80211_draintask(&sc->sc_ic, &sc->sc_radiooff_task);
 1405                 iwn_stop(sc);
 1406 
 1407                 taskqueue_drain_all(sc->sc_tq);
 1408                 taskqueue_free(sc->sc_tq);
 1409 
 1410                 callout_drain(&sc->watchdog_to);
 1411                 callout_drain(&sc->scan_timeout);
 1412                 callout_drain(&sc->calib_to);
 1413                 ieee80211_ifdetach(&sc->sc_ic);
 1414         }
 1415 
 1416         /* Uninstall interrupt handler. */
 1417         if (sc->irq != NULL) {
 1418                 bus_teardown_intr(dev, sc->irq, sc->sc_ih);
 1419                 bus_release_resource(dev, SYS_RES_IRQ, rman_get_rid(sc->irq),
 1420                     sc->irq);
 1421                 pci_release_msi(dev);
 1422         }
 1423 
 1424         /* Free DMA resources. */
 1425         iwn_free_rx_ring(sc, &sc->rxq);
 1426         for (qid = 0; qid < sc->ntxqs; qid++)
 1427                 iwn_free_tx_ring(sc, &sc->txq[qid]);
 1428         iwn_free_sched(sc);
 1429         iwn_free_kw(sc);
 1430         if (sc->ict != NULL)
 1431                 iwn_free_ict(sc);
 1432         iwn_free_fwmem(sc);
 1433 
 1434         if (sc->mem != NULL)
 1435                 bus_release_resource(dev, SYS_RES_MEMORY,
 1436                     rman_get_rid(sc->mem), sc->mem);
 1437 
 1438         if (sc->sc_cdev) {
 1439                 destroy_dev(sc->sc_cdev);
 1440                 sc->sc_cdev = NULL;
 1441         }
 1442 
 1443         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n", __func__);
 1444         IWN_LOCK_DESTROY(sc);
 1445         return 0;
 1446 }
 1447 
 1448 static int
 1449 iwn_shutdown(device_t dev)
 1450 {
 1451         struct iwn_softc *sc = device_get_softc(dev);
 1452 
 1453         iwn_stop(sc);
 1454         return 0;
 1455 }
 1456 
 1457 static int
 1458 iwn_suspend(device_t dev)
 1459 {
 1460         struct iwn_softc *sc = device_get_softc(dev);
 1461 
 1462         ieee80211_suspend_all(&sc->sc_ic);
 1463         return 0;
 1464 }
 1465 
 1466 static int
 1467 iwn_resume(device_t dev)
 1468 {
 1469         struct iwn_softc *sc = device_get_softc(dev);
 1470 
 1471         /* Clear device-specific "PCI retry timeout" register (41h). */
 1472         pci_write_config(dev, 0x41, 0, 1);
 1473 
 1474         ieee80211_resume_all(&sc->sc_ic);
 1475         return 0;
 1476 }
 1477 
 1478 static int
 1479 iwn_nic_lock(struct iwn_softc *sc)
 1480 {
 1481         int ntries;
 1482 
 1483         /* Request exclusive access to NIC. */
 1484         IWN_SETBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_MAC_ACCESS_REQ);
 1485 
 1486         /* Spin until we actually get the lock. */
 1487         for (ntries = 0; ntries < 1000; ntries++) {
 1488                 if ((IWN_READ(sc, IWN_GP_CNTRL) &
 1489                      (IWN_GP_CNTRL_MAC_ACCESS_ENA | IWN_GP_CNTRL_SLEEP)) ==
 1490                     IWN_GP_CNTRL_MAC_ACCESS_ENA)
 1491                         return 0;
 1492                 DELAY(10);
 1493         }
 1494         return ETIMEDOUT;
 1495 }
 1496 
 1497 static __inline void
 1498 iwn_nic_unlock(struct iwn_softc *sc)
 1499 {
 1500         IWN_CLRBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_MAC_ACCESS_REQ);
 1501 }
 1502 
 1503 static __inline uint32_t
 1504 iwn_prph_read(struct iwn_softc *sc, uint32_t addr)
 1505 {
 1506         IWN_WRITE(sc, IWN_PRPH_RADDR, IWN_PRPH_DWORD | addr);
 1507         IWN_BARRIER_READ_WRITE(sc);
 1508         return IWN_READ(sc, IWN_PRPH_RDATA);
 1509 }
 1510 
 1511 static __inline void
 1512 iwn_prph_write(struct iwn_softc *sc, uint32_t addr, uint32_t data)
 1513 {
 1514         IWN_WRITE(sc, IWN_PRPH_WADDR, IWN_PRPH_DWORD | addr);
 1515         IWN_BARRIER_WRITE(sc);
 1516         IWN_WRITE(sc, IWN_PRPH_WDATA, data);
 1517 }
 1518 
 1519 static __inline void
 1520 iwn_prph_setbits(struct iwn_softc *sc, uint32_t addr, uint32_t mask)
 1521 {
 1522         iwn_prph_write(sc, addr, iwn_prph_read(sc, addr) | mask);
 1523 }
 1524 
 1525 static __inline void
 1526 iwn_prph_clrbits(struct iwn_softc *sc, uint32_t addr, uint32_t mask)
 1527 {
 1528         iwn_prph_write(sc, addr, iwn_prph_read(sc, addr) & ~mask);
 1529 }
 1530 
 1531 static __inline void
 1532 iwn_prph_write_region_4(struct iwn_softc *sc, uint32_t addr,
 1533     const uint32_t *data, int count)
 1534 {
 1535         for (; count > 0; count--, data++, addr += 4)
 1536                 iwn_prph_write(sc, addr, *data);
 1537 }
 1538 
 1539 static __inline uint32_t
 1540 iwn_mem_read(struct iwn_softc *sc, uint32_t addr)
 1541 {
 1542         IWN_WRITE(sc, IWN_MEM_RADDR, addr);
 1543         IWN_BARRIER_READ_WRITE(sc);
 1544         return IWN_READ(sc, IWN_MEM_RDATA);
 1545 }
 1546 
 1547 static __inline void
 1548 iwn_mem_write(struct iwn_softc *sc, uint32_t addr, uint32_t data)
 1549 {
 1550         IWN_WRITE(sc, IWN_MEM_WADDR, addr);
 1551         IWN_BARRIER_WRITE(sc);
 1552         IWN_WRITE(sc, IWN_MEM_WDATA, data);
 1553 }
 1554 
 1555 static __inline void
 1556 iwn_mem_write_2(struct iwn_softc *sc, uint32_t addr, uint16_t data)
 1557 {
 1558         uint32_t tmp;
 1559 
 1560         tmp = iwn_mem_read(sc, addr & ~3);
 1561         if (addr & 3)
 1562                 tmp = (tmp & 0x0000ffff) | data << 16;
 1563         else
 1564                 tmp = (tmp & 0xffff0000) | data;
 1565         iwn_mem_write(sc, addr & ~3, tmp);
 1566 }
 1567 
 1568 static __inline void
 1569 iwn_mem_read_region_4(struct iwn_softc *sc, uint32_t addr, uint32_t *data,
 1570     int count)
 1571 {
 1572         for (; count > 0; count--, addr += 4)
 1573                 *data++ = iwn_mem_read(sc, addr);
 1574 }
 1575 
 1576 static __inline void
 1577 iwn_mem_set_region_4(struct iwn_softc *sc, uint32_t addr, uint32_t val,
 1578     int count)
 1579 {
 1580         for (; count > 0; count--, addr += 4)
 1581                 iwn_mem_write(sc, addr, val);
 1582 }
 1583 
 1584 static int
 1585 iwn_eeprom_lock(struct iwn_softc *sc)
 1586 {
 1587         int i, ntries;
 1588 
 1589         for (i = 0; i < 100; i++) {
 1590                 /* Request exclusive access to EEPROM. */
 1591                 IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
 1592                     IWN_HW_IF_CONFIG_EEPROM_LOCKED);
 1593 
 1594                 /* Spin until we actually get the lock. */
 1595                 for (ntries = 0; ntries < 100; ntries++) {
 1596                         if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
 1597                             IWN_HW_IF_CONFIG_EEPROM_LOCKED)
 1598                                 return 0;
 1599                         DELAY(10);
 1600                 }
 1601         }
 1602         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end timeout\n", __func__);
 1603         return ETIMEDOUT;
 1604 }
 1605 
 1606 static __inline void
 1607 iwn_eeprom_unlock(struct iwn_softc *sc)
 1608 {
 1609         IWN_CLRBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_EEPROM_LOCKED);
 1610 }
 1611 
 1612 /*
 1613  * Initialize access by host to One Time Programmable ROM.
 1614  * NB: This kind of ROM can be found on 1000 or 6000 Series only.
 1615  */
 1616 static int
 1617 iwn_init_otprom(struct iwn_softc *sc)
 1618 {
 1619         uint16_t prev, base, next;
 1620         int count, error;
 1621 
 1622         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 1623 
 1624         /* Wait for clock stabilization before accessing prph. */
 1625         if ((error = iwn_clock_wait(sc)) != 0)
 1626                 return error;
 1627 
 1628         if ((error = iwn_nic_lock(sc)) != 0)
 1629                 return error;
 1630         iwn_prph_setbits(sc, IWN_APMG_PS, IWN_APMG_PS_RESET_REQ);
 1631         DELAY(5);
 1632         iwn_prph_clrbits(sc, IWN_APMG_PS, IWN_APMG_PS_RESET_REQ);
 1633         iwn_nic_unlock(sc);
 1634 
 1635         /* Set auto clock gate disable bit for HW with OTP shadow RAM. */
 1636         if (sc->base_params->shadow_ram_support) {
 1637                 IWN_SETBITS(sc, IWN_DBG_LINK_PWR_MGMT,
 1638                     IWN_RESET_LINK_PWR_MGMT_DIS);
 1639         }
 1640         IWN_CLRBITS(sc, IWN_EEPROM_GP, IWN_EEPROM_GP_IF_OWNER);
 1641         /* Clear ECC status. */
 1642         IWN_SETBITS(sc, IWN_OTP_GP,
 1643             IWN_OTP_GP_ECC_CORR_STTS | IWN_OTP_GP_ECC_UNCORR_STTS);
 1644 
 1645         /*
 1646          * Find the block before last block (contains the EEPROM image)
 1647          * for HW without OTP shadow RAM.
 1648          */
 1649         if (! sc->base_params->shadow_ram_support) {
 1650                 /* Switch to absolute addressing mode. */
 1651                 IWN_CLRBITS(sc, IWN_OTP_GP, IWN_OTP_GP_RELATIVE_ACCESS);
 1652                 base = prev = 0;
 1653                 for (count = 0; count < sc->base_params->max_ll_items;
 1654                     count++) {
 1655                         error = iwn_read_prom_data(sc, base, &next, 2);
 1656                         if (error != 0)
 1657                                 return error;
 1658                         if (next == 0)  /* End of linked-list. */
 1659                                 break;
 1660                         prev = base;
 1661                         base = le16toh(next);
 1662                 }
 1663                 if (count == 0 || count == sc->base_params->max_ll_items)
 1664                         return EIO;
 1665                 /* Skip "next" word. */
 1666                 sc->prom_base = prev + 1;
 1667         }
 1668 
 1669         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
 1670 
 1671         return 0;
 1672 }
 1673 
 1674 static int
 1675 iwn_read_prom_data(struct iwn_softc *sc, uint32_t addr, void *data, int count)
 1676 {
 1677         uint8_t *out = data;
 1678         uint32_t val, tmp;
 1679         int ntries;
 1680 
 1681         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 1682 
 1683         addr += sc->prom_base;
 1684         for (; count > 0; count -= 2, addr++) {
 1685                 IWN_WRITE(sc, IWN_EEPROM, addr << 2);
 1686                 for (ntries = 0; ntries < 10; ntries++) {
 1687                         val = IWN_READ(sc, IWN_EEPROM);
 1688                         if (val & IWN_EEPROM_READ_VALID)
 1689                                 break;
 1690                         DELAY(5);
 1691                 }
 1692                 if (ntries == 10) {
 1693                         device_printf(sc->sc_dev,
 1694                             "timeout reading ROM at 0x%x\n", addr);
 1695                         return ETIMEDOUT;
 1696                 }
 1697                 if (sc->sc_flags & IWN_FLAG_HAS_OTPROM) {
 1698                         /* OTPROM, check for ECC errors. */
 1699                         tmp = IWN_READ(sc, IWN_OTP_GP);
 1700                         if (tmp & IWN_OTP_GP_ECC_UNCORR_STTS) {
 1701                                 device_printf(sc->sc_dev,
 1702                                     "OTPROM ECC error at 0x%x\n", addr);
 1703                                 return EIO;
 1704                         }
 1705                         if (tmp & IWN_OTP_GP_ECC_CORR_STTS) {
 1706                                 /* Correctable ECC error, clear bit. */
 1707                                 IWN_SETBITS(sc, IWN_OTP_GP,
 1708                                     IWN_OTP_GP_ECC_CORR_STTS);
 1709                         }
 1710                 }
 1711                 *out++ = val >> 16;
 1712                 if (count > 1)
 1713                         *out++ = val >> 24;
 1714         }
 1715 
 1716         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
 1717 
 1718         return 0;
 1719 }
 1720 
 1721 static void
 1722 iwn_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
 1723 {
 1724         if (error != 0)
 1725                 return;
 1726         KASSERT(nsegs == 1, ("too many DMA segments, %d should be 1", nsegs));
 1727         *(bus_addr_t *)arg = segs[0].ds_addr;
 1728 }
 1729 
 1730 static int
 1731 iwn_dma_contig_alloc(struct iwn_softc *sc, struct iwn_dma_info *dma,
 1732     void **kvap, bus_size_t size, bus_size_t alignment)
 1733 {
 1734         int error;
 1735 
 1736         dma->tag = NULL;
 1737         dma->size = size;
 1738 
 1739         error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), alignment,
 1740             0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, size,
 1741             1, size, 0, NULL, NULL, &dma->tag);
 1742         if (error != 0)
 1743                 goto fail;
 1744 
 1745         error = bus_dmamem_alloc(dma->tag, (void **)&dma->vaddr,
 1746             BUS_DMA_NOWAIT | BUS_DMA_ZERO | BUS_DMA_COHERENT, &dma->map);
 1747         if (error != 0)
 1748                 goto fail;
 1749 
 1750         error = bus_dmamap_load(dma->tag, dma->map, dma->vaddr, size,
 1751             iwn_dma_map_addr, &dma->paddr, BUS_DMA_NOWAIT);
 1752         if (error != 0)
 1753                 goto fail;
 1754 
 1755         bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
 1756 
 1757         if (kvap != NULL)
 1758                 *kvap = dma->vaddr;
 1759 
 1760         return 0;
 1761 
 1762 fail:   iwn_dma_contig_free(dma);
 1763         return error;
 1764 }
 1765 
 1766 static void
 1767 iwn_dma_contig_free(struct iwn_dma_info *dma)
 1768 {
 1769         if (dma->vaddr != NULL) {
 1770                 bus_dmamap_sync(dma->tag, dma->map,
 1771                     BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
 1772                 bus_dmamap_unload(dma->tag, dma->map);
 1773                 bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
 1774                 dma->vaddr = NULL;
 1775         }
 1776         if (dma->tag != NULL) {
 1777                 bus_dma_tag_destroy(dma->tag);
 1778                 dma->tag = NULL;
 1779         }
 1780 }
 1781 
 1782 static int
 1783 iwn_alloc_sched(struct iwn_softc *sc)
 1784 {
 1785         /* TX scheduler rings must be aligned on a 1KB boundary. */
 1786         return iwn_dma_contig_alloc(sc, &sc->sched_dma, (void **)&sc->sched,
 1787             sc->schedsz, 1024);
 1788 }
 1789 
 1790 static void
 1791 iwn_free_sched(struct iwn_softc *sc)
 1792 {
 1793         iwn_dma_contig_free(&sc->sched_dma);
 1794 }
 1795 
 1796 static int
 1797 iwn_alloc_kw(struct iwn_softc *sc)
 1798 {
 1799         /* "Keep Warm" page must be aligned on a 4KB boundary. */
 1800         return iwn_dma_contig_alloc(sc, &sc->kw_dma, NULL, 4096, 4096);
 1801 }
 1802 
 1803 static void
 1804 iwn_free_kw(struct iwn_softc *sc)
 1805 {
 1806         iwn_dma_contig_free(&sc->kw_dma);
 1807 }
 1808 
 1809 static int
 1810 iwn_alloc_ict(struct iwn_softc *sc)
 1811 {
 1812         /* ICT table must be aligned on a 4KB boundary. */
 1813         return iwn_dma_contig_alloc(sc, &sc->ict_dma, (void **)&sc->ict,
 1814             IWN_ICT_SIZE, 4096);
 1815 }
 1816 
 1817 static void
 1818 iwn_free_ict(struct iwn_softc *sc)
 1819 {
 1820         iwn_dma_contig_free(&sc->ict_dma);
 1821 }
 1822 
 1823 static int
 1824 iwn_alloc_fwmem(struct iwn_softc *sc)
 1825 {
 1826         /* Must be aligned on a 16-byte boundary. */
 1827         return iwn_dma_contig_alloc(sc, &sc->fw_dma, NULL, sc->fwsz, 16);
 1828 }
 1829 
 1830 static void
 1831 iwn_free_fwmem(struct iwn_softc *sc)
 1832 {
 1833         iwn_dma_contig_free(&sc->fw_dma);
 1834 }
 1835 
 1836 static int
 1837 iwn_alloc_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
 1838 {
 1839         bus_size_t size;
 1840         int i, error;
 1841 
 1842         ring->cur = 0;
 1843 
 1844         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 1845 
 1846         /* Allocate RX descriptors (256-byte aligned). */
 1847         size = IWN_RX_RING_COUNT * sizeof (uint32_t);
 1848         error = iwn_dma_contig_alloc(sc, &ring->desc_dma, (void **)&ring->desc,
 1849             size, 256);
 1850         if (error != 0) {
 1851                 device_printf(sc->sc_dev,
 1852                     "%s: could not allocate RX ring DMA memory, error %d\n",
 1853                     __func__, error);
 1854                 goto fail;
 1855         }
 1856 
 1857         /* Allocate RX status area (16-byte aligned). */
 1858         error = iwn_dma_contig_alloc(sc, &ring->stat_dma, (void **)&ring->stat,
 1859             sizeof (struct iwn_rx_status), 16);
 1860         if (error != 0) {
 1861                 device_printf(sc->sc_dev,
 1862                     "%s: could not allocate RX status DMA memory, error %d\n",
 1863                     __func__, error);
 1864                 goto fail;
 1865         }
 1866 
 1867         /* Create RX buffer DMA tag. */
 1868         error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
 1869             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
 1870             IWN_RBUF_SIZE, 1, IWN_RBUF_SIZE, 0, NULL, NULL, &ring->data_dmat);
 1871         if (error != 0) {
 1872                 device_printf(sc->sc_dev,
 1873                     "%s: could not create RX buf DMA tag, error %d\n",
 1874                     __func__, error);
 1875                 goto fail;
 1876         }
 1877 
 1878         /*
 1879          * Allocate and map RX buffers.
 1880          */
 1881         for (i = 0; i < IWN_RX_RING_COUNT; i++) {
 1882                 struct iwn_rx_data *data = &ring->data[i];
 1883                 bus_addr_t paddr;
 1884 
 1885                 error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
 1886                 if (error != 0) {
 1887                         device_printf(sc->sc_dev,
 1888                             "%s: could not create RX buf DMA map, error %d\n",
 1889                             __func__, error);
 1890                         goto fail;
 1891                 }
 1892 
 1893                 data->m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR,
 1894                     IWN_RBUF_SIZE);
 1895                 if (data->m == NULL) {
 1896                         device_printf(sc->sc_dev,
 1897                             "%s: could not allocate RX mbuf\n", __func__);
 1898                         error = ENOBUFS;
 1899                         goto fail;
 1900                 }
 1901 
 1902                 error = bus_dmamap_load(ring->data_dmat, data->map,
 1903                     mtod(data->m, void *), IWN_RBUF_SIZE, iwn_dma_map_addr,
 1904                     &paddr, BUS_DMA_NOWAIT);
 1905                 if (error != 0 && error != EFBIG) {
 1906                         device_printf(sc->sc_dev,
 1907                             "%s: can't map mbuf, error %d\n", __func__,
 1908                             error);
 1909                         goto fail;
 1910                 }
 1911 
 1912                 /* Set physical address of RX buffer (256-byte aligned). */
 1913                 ring->desc[i] = htole32(paddr >> 8);
 1914         }
 1915 
 1916         bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
 1917             BUS_DMASYNC_PREWRITE);
 1918 
 1919         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 1920 
 1921         return 0;
 1922 
 1923 fail:   iwn_free_rx_ring(sc, ring);
 1924 
 1925         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end in error\n",__func__);
 1926 
 1927         return error;
 1928 }
 1929 
 1930 static void
 1931 iwn_reset_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
 1932 {
 1933         int ntries;
 1934 
 1935         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 1936 
 1937         if (iwn_nic_lock(sc) == 0) {
 1938                 IWN_WRITE(sc, IWN_FH_RX_CONFIG, 0);
 1939                 for (ntries = 0; ntries < 1000; ntries++) {
 1940                         if (IWN_READ(sc, IWN_FH_RX_STATUS) &
 1941                             IWN_FH_RX_STATUS_IDLE)
 1942                                 break;
 1943                         DELAY(10);
 1944                 }
 1945                 iwn_nic_unlock(sc);
 1946         }
 1947         ring->cur = 0;
 1948         sc->last_rx_valid = 0;
 1949 }
 1950 
 1951 static void
 1952 iwn_free_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
 1953 {
 1954         int i;
 1955 
 1956         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s \n", __func__);
 1957 
 1958         iwn_dma_contig_free(&ring->desc_dma);
 1959         iwn_dma_contig_free(&ring->stat_dma);
 1960 
 1961         for (i = 0; i < IWN_RX_RING_COUNT; i++) {
 1962                 struct iwn_rx_data *data = &ring->data[i];
 1963 
 1964                 if (data->m != NULL) {
 1965                         bus_dmamap_sync(ring->data_dmat, data->map,
 1966                             BUS_DMASYNC_POSTREAD);
 1967                         bus_dmamap_unload(ring->data_dmat, data->map);
 1968                         m_freem(data->m);
 1969                         data->m = NULL;
 1970                 }
 1971                 if (data->map != NULL)
 1972                         bus_dmamap_destroy(ring->data_dmat, data->map);
 1973         }
 1974         if (ring->data_dmat != NULL) {
 1975                 bus_dma_tag_destroy(ring->data_dmat);
 1976                 ring->data_dmat = NULL;
 1977         }
 1978 }
 1979 
 1980 static int
 1981 iwn_alloc_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring, int qid)
 1982 {
 1983         bus_addr_t paddr;
 1984         bus_size_t size;
 1985         int i, error;
 1986 
 1987         ring->qid = qid;
 1988         ring->queued = 0;
 1989         ring->cur = 0;
 1990 
 1991         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 1992 
 1993         /* Allocate TX descriptors (256-byte aligned). */
 1994         size = IWN_TX_RING_COUNT * sizeof (struct iwn_tx_desc);
 1995         error = iwn_dma_contig_alloc(sc, &ring->desc_dma, (void **)&ring->desc,
 1996             size, 256);
 1997         if (error != 0) {
 1998                 device_printf(sc->sc_dev,
 1999                     "%s: could not allocate TX ring DMA memory, error %d\n",
 2000                     __func__, error);
 2001                 goto fail;
 2002         }
 2003 
 2004         size = IWN_TX_RING_COUNT * sizeof (struct iwn_tx_cmd);
 2005         error = iwn_dma_contig_alloc(sc, &ring->cmd_dma, (void **)&ring->cmd,
 2006             size, 4);
 2007         if (error != 0) {
 2008                 device_printf(sc->sc_dev,
 2009                     "%s: could not allocate TX cmd DMA memory, error %d\n",
 2010                     __func__, error);
 2011                 goto fail;
 2012         }
 2013 
 2014         error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
 2015             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
 2016             IWN_MAX_SCATTER - 1, MCLBYTES, 0, NULL, NULL, &ring->data_dmat);
 2017         if (error != 0) {
 2018                 device_printf(sc->sc_dev,
 2019                     "%s: could not create TX buf DMA tag, error %d\n",
 2020                     __func__, error);
 2021                 goto fail;
 2022         }
 2023 
 2024         paddr = ring->cmd_dma.paddr;
 2025         for (i = 0; i < IWN_TX_RING_COUNT; i++) {
 2026                 struct iwn_tx_data *data = &ring->data[i];
 2027 
 2028                 data->cmd_paddr = paddr;
 2029                 data->scratch_paddr = paddr + 12;
 2030                 paddr += sizeof (struct iwn_tx_cmd);
 2031 
 2032                 error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
 2033                 if (error != 0) {
 2034                         device_printf(sc->sc_dev,
 2035                             "%s: could not create TX buf DMA map, error %d\n",
 2036                             __func__, error);
 2037                         goto fail;
 2038                 }
 2039         }
 2040 
 2041         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
 2042 
 2043         return 0;
 2044 
 2045 fail:   iwn_free_tx_ring(sc, ring);
 2046         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end in error\n", __func__);
 2047         return error;
 2048 }
 2049 
 2050 static void
 2051 iwn_reset_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
 2052 {
 2053         int i;
 2054 
 2055         DPRINTF(sc, IWN_DEBUG_TRACE, "->doing %s \n", __func__);
 2056 
 2057         for (i = 0; i < IWN_TX_RING_COUNT; i++) {
 2058                 struct iwn_tx_data *data = &ring->data[i];
 2059 
 2060                 if (data->m != NULL) {
 2061                         bus_dmamap_sync(ring->data_dmat, data->map,
 2062                             BUS_DMASYNC_POSTWRITE);
 2063                         bus_dmamap_unload(ring->data_dmat, data->map);
 2064                         m_freem(data->m);
 2065                         data->m = NULL;
 2066                 }
 2067                 if (data->ni != NULL) {
 2068                         ieee80211_free_node(data->ni);
 2069                         data->ni = NULL;
 2070                 }
 2071         }
 2072         /* Clear TX descriptors. */
 2073         memset(ring->desc, 0, ring->desc_dma.size);
 2074         bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
 2075             BUS_DMASYNC_PREWRITE);
 2076         sc->qfullmsk &= ~(1 << ring->qid);
 2077         ring->queued = 0;
 2078         ring->cur = 0;
 2079 }
 2080 
 2081 static void
 2082 iwn_free_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
 2083 {
 2084         int i;
 2085 
 2086         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s \n", __func__);
 2087 
 2088         iwn_dma_contig_free(&ring->desc_dma);
 2089         iwn_dma_contig_free(&ring->cmd_dma);
 2090 
 2091         for (i = 0; i < IWN_TX_RING_COUNT; i++) {
 2092                 struct iwn_tx_data *data = &ring->data[i];
 2093 
 2094                 if (data->m != NULL) {
 2095                         bus_dmamap_sync(ring->data_dmat, data->map,
 2096                             BUS_DMASYNC_POSTWRITE);
 2097                         bus_dmamap_unload(ring->data_dmat, data->map);
 2098                         m_freem(data->m);
 2099                 }
 2100                 if (data->map != NULL)
 2101                         bus_dmamap_destroy(ring->data_dmat, data->map);
 2102         }
 2103         if (ring->data_dmat != NULL) {
 2104                 bus_dma_tag_destroy(ring->data_dmat);
 2105                 ring->data_dmat = NULL;
 2106         }
 2107 }
 2108 
 2109 static void
 2110 iwn5000_ict_reset(struct iwn_softc *sc)
 2111 {
 2112         /* Disable interrupts. */
 2113         IWN_WRITE(sc, IWN_INT_MASK, 0);
 2114 
 2115         /* Reset ICT table. */
 2116         memset(sc->ict, 0, IWN_ICT_SIZE);
 2117         sc->ict_cur = 0;
 2118 
 2119         /* Set physical address of ICT table (4KB aligned). */
 2120         DPRINTF(sc, IWN_DEBUG_RESET, "%s: enabling ICT\n", __func__);
 2121         IWN_WRITE(sc, IWN_DRAM_INT_TBL, IWN_DRAM_INT_TBL_ENABLE |
 2122             IWN_DRAM_INT_TBL_WRAP_CHECK | sc->ict_dma.paddr >> 12);
 2123 
 2124         /* Enable periodic RX interrupt. */
 2125         sc->int_mask |= IWN_INT_RX_PERIODIC;
 2126         /* Switch to ICT interrupt mode in driver. */
 2127         sc->sc_flags |= IWN_FLAG_USE_ICT;
 2128 
 2129         /* Re-enable interrupts. */
 2130         IWN_WRITE(sc, IWN_INT, 0xffffffff);
 2131         IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
 2132 }
 2133 
 2134 static int
 2135 iwn_read_eeprom(struct iwn_softc *sc, uint8_t macaddr[IEEE80211_ADDR_LEN])
 2136 {
 2137         struct iwn_ops *ops = &sc->ops;
 2138         uint16_t val;
 2139         int error;
 2140 
 2141         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 2142 
 2143         /* Check whether adapter has an EEPROM or an OTPROM. */
 2144         if (sc->hw_type >= IWN_HW_REV_TYPE_1000 &&
 2145             (IWN_READ(sc, IWN_OTP_GP) & IWN_OTP_GP_DEV_SEL_OTP))
 2146                 sc->sc_flags |= IWN_FLAG_HAS_OTPROM;
 2147         DPRINTF(sc, IWN_DEBUG_RESET, "%s found\n",
 2148             (sc->sc_flags & IWN_FLAG_HAS_OTPROM) ? "OTPROM" : "EEPROM");
 2149 
 2150         /* Adapter has to be powered on for EEPROM access to work. */
 2151         if ((error = iwn_apm_init(sc)) != 0) {
 2152                 device_printf(sc->sc_dev,
 2153                     "%s: could not power ON adapter, error %d\n", __func__,
 2154                     error);
 2155                 return error;
 2156         }
 2157 
 2158         if ((IWN_READ(sc, IWN_EEPROM_GP) & 0x7) == 0) {
 2159                 device_printf(sc->sc_dev, "%s: bad ROM signature\n", __func__);
 2160                 return EIO;
 2161         }
 2162         if ((error = iwn_eeprom_lock(sc)) != 0) {
 2163                 device_printf(sc->sc_dev, "%s: could not lock ROM, error %d\n",
 2164                     __func__, error);
 2165                 return error;
 2166         }
 2167         if (sc->sc_flags & IWN_FLAG_HAS_OTPROM) {
 2168                 if ((error = iwn_init_otprom(sc)) != 0) {
 2169                         device_printf(sc->sc_dev,
 2170                             "%s: could not initialize OTPROM, error %d\n",
 2171                             __func__, error);
 2172                         return error;
 2173                 }
 2174         }
 2175 
 2176         iwn_read_prom_data(sc, IWN_EEPROM_SKU_CAP, &val, 2);
 2177         DPRINTF(sc, IWN_DEBUG_RESET, "SKU capabilities=0x%04x\n", le16toh(val));
 2178         /* Check if HT support is bonded out. */
 2179         if (val & htole16(IWN_EEPROM_SKU_CAP_11N))
 2180                 sc->sc_flags |= IWN_FLAG_HAS_11N;
 2181 
 2182         iwn_read_prom_data(sc, IWN_EEPROM_RFCFG, &val, 2);
 2183         sc->rfcfg = le16toh(val);
 2184         DPRINTF(sc, IWN_DEBUG_RESET, "radio config=0x%04x\n", sc->rfcfg);
 2185         /* Read Tx/Rx chains from ROM unless it's known to be broken. */
 2186         if (sc->txchainmask == 0)
 2187                 sc->txchainmask = IWN_RFCFG_TXANTMSK(sc->rfcfg);
 2188         if (sc->rxchainmask == 0)
 2189                 sc->rxchainmask = IWN_RFCFG_RXANTMSK(sc->rfcfg);
 2190 
 2191         /* Read MAC address. */
 2192         iwn_read_prom_data(sc, IWN_EEPROM_MAC, macaddr, 6);
 2193 
 2194         /* Read adapter-specific information from EEPROM. */
 2195         ops->read_eeprom(sc);
 2196 
 2197         iwn_apm_stop(sc);       /* Power OFF adapter. */
 2198 
 2199         iwn_eeprom_unlock(sc);
 2200 
 2201         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
 2202 
 2203         return 0;
 2204 }
 2205 
 2206 static void
 2207 iwn4965_read_eeprom(struct iwn_softc *sc)
 2208 {
 2209         uint32_t addr;
 2210         uint16_t val;
 2211         int i;
 2212 
 2213         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 2214 
 2215         /* Read regulatory domain (4 ASCII characters). */
 2216         iwn_read_prom_data(sc, IWN4965_EEPROM_DOMAIN, sc->eeprom_domain, 4);
 2217 
 2218         /* Read the list of authorized channels (20MHz & 40MHz). */
 2219         for (i = 0; i < IWN_NBANDS - 1; i++) {
 2220                 addr = iwn4965_regulatory_bands[i];
 2221                 iwn_read_eeprom_channels(sc, i, addr);
 2222         }
 2223 
 2224         /* Read maximum allowed TX power for 2GHz and 5GHz bands. */
 2225         iwn_read_prom_data(sc, IWN4965_EEPROM_MAXPOW, &val, 2);
 2226         sc->maxpwr2GHz = val & 0xff;
 2227         sc->maxpwr5GHz = val >> 8;
 2228         /* Check that EEPROM values are within valid range. */
 2229         if (sc->maxpwr5GHz < 20 || sc->maxpwr5GHz > 50)
 2230                 sc->maxpwr5GHz = 38;
 2231         if (sc->maxpwr2GHz < 20 || sc->maxpwr2GHz > 50)
 2232                 sc->maxpwr2GHz = 38;
 2233         DPRINTF(sc, IWN_DEBUG_RESET, "maxpwr 2GHz=%d 5GHz=%d\n",
 2234             sc->maxpwr2GHz, sc->maxpwr5GHz);
 2235 
 2236         /* Read samples for each TX power group. */
 2237         iwn_read_prom_data(sc, IWN4965_EEPROM_BANDS, sc->bands,
 2238             sizeof sc->bands);
 2239 
 2240         /* Read voltage at which samples were taken. */
 2241         iwn_read_prom_data(sc, IWN4965_EEPROM_VOLTAGE, &val, 2);
 2242         sc->eeprom_voltage = (int16_t)le16toh(val);
 2243         DPRINTF(sc, IWN_DEBUG_RESET, "voltage=%d (in 0.3V)\n",
 2244             sc->eeprom_voltage);
 2245 
 2246 #ifdef IWN_DEBUG
 2247         /* Print samples. */
 2248         if (sc->sc_debug & IWN_DEBUG_ANY) {
 2249                 for (i = 0; i < IWN_NBANDS - 1; i++)
 2250                         iwn4965_print_power_group(sc, i);
 2251         }
 2252 #endif
 2253 
 2254         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
 2255 }
 2256 
 2257 #ifdef IWN_DEBUG
 2258 static void
 2259 iwn4965_print_power_group(struct iwn_softc *sc, int i)
 2260 {
 2261         struct iwn4965_eeprom_band *band = &sc->bands[i];
 2262         struct iwn4965_eeprom_chan_samples *chans = band->chans;
 2263         int j, c;
 2264 
 2265         printf("===band %d===\n", i);
 2266         printf("chan lo=%d, chan hi=%d\n", band->lo, band->hi);
 2267         printf("chan1 num=%d\n", chans[0].num);
 2268         for (c = 0; c < 2; c++) {
 2269                 for (j = 0; j < IWN_NSAMPLES; j++) {
 2270                         printf("chain %d, sample %d: temp=%d gain=%d "
 2271                             "power=%d pa_det=%d\n", c, j,
 2272                             chans[0].samples[c][j].temp,
 2273                             chans[0].samples[c][j].gain,
 2274                             chans[0].samples[c][j].power,
 2275                             chans[0].samples[c][j].pa_det);
 2276                 }
 2277         }
 2278         printf("chan2 num=%d\n", chans[1].num);
 2279         for (c = 0; c < 2; c++) {
 2280                 for (j = 0; j < IWN_NSAMPLES; j++) {
 2281                         printf("chain %d, sample %d: temp=%d gain=%d "
 2282                             "power=%d pa_det=%d\n", c, j,
 2283                             chans[1].samples[c][j].temp,
 2284                             chans[1].samples[c][j].gain,
 2285                             chans[1].samples[c][j].power,
 2286                             chans[1].samples[c][j].pa_det);
 2287                 }
 2288         }
 2289 }
 2290 #endif
 2291 
 2292 static void
 2293 iwn5000_read_eeprom(struct iwn_softc *sc)
 2294 {
 2295         struct iwn5000_eeprom_calib_hdr hdr;
 2296         int32_t volt;
 2297         uint32_t base, addr;
 2298         uint16_t val;
 2299         int i;
 2300 
 2301         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 2302 
 2303         /* Read regulatory domain (4 ASCII characters). */
 2304         iwn_read_prom_data(sc, IWN5000_EEPROM_REG, &val, 2);
 2305         base = le16toh(val);
 2306         iwn_read_prom_data(sc, base + IWN5000_EEPROM_DOMAIN,
 2307             sc->eeprom_domain, 4);
 2308 
 2309         /* Read the list of authorized channels (20MHz & 40MHz). */
 2310         for (i = 0; i < IWN_NBANDS - 1; i++) {
 2311                 addr =  base + sc->base_params->regulatory_bands[i];
 2312                 iwn_read_eeprom_channels(sc, i, addr);
 2313         }
 2314 
 2315         /* Read enhanced TX power information for 6000 Series. */
 2316         if (sc->base_params->enhanced_TX_power)
 2317                 iwn_read_eeprom_enhinfo(sc);
 2318 
 2319         iwn_read_prom_data(sc, IWN5000_EEPROM_CAL, &val, 2);
 2320         base = le16toh(val);
 2321         iwn_read_prom_data(sc, base, &hdr, sizeof hdr);
 2322         DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 2323             "%s: calib version=%u pa type=%u voltage=%u\n", __func__,
 2324             hdr.version, hdr.pa_type, le16toh(hdr.volt));
 2325         sc->calib_ver = hdr.version;
 2326 
 2327         if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSETv2) {
 2328                 sc->eeprom_voltage = le16toh(hdr.volt);
 2329                 iwn_read_prom_data(sc, base + IWN5000_EEPROM_TEMP, &val, 2);
 2330                 sc->eeprom_temp_high=le16toh(val);
 2331                 iwn_read_prom_data(sc, base + IWN5000_EEPROM_VOLT, &val, 2);
 2332                 sc->eeprom_temp = le16toh(val);
 2333         }
 2334 
 2335         if (sc->hw_type == IWN_HW_REV_TYPE_5150) {
 2336                 /* Compute temperature offset. */
 2337                 iwn_read_prom_data(sc, base + IWN5000_EEPROM_TEMP, &val, 2);
 2338                 sc->eeprom_temp = le16toh(val);
 2339                 iwn_read_prom_data(sc, base + IWN5000_EEPROM_VOLT, &val, 2);
 2340                 volt = le16toh(val);
 2341                 sc->temp_off = sc->eeprom_temp - (volt / -5);
 2342                 DPRINTF(sc, IWN_DEBUG_CALIBRATE, "temp=%d volt=%d offset=%dK\n",
 2343                     sc->eeprom_temp, volt, sc->temp_off);
 2344         } else {
 2345                 /* Read crystal calibration. */
 2346                 iwn_read_prom_data(sc, base + IWN5000_EEPROM_CRYSTAL,
 2347                     &sc->eeprom_crystal, sizeof (uint32_t));
 2348                 DPRINTF(sc, IWN_DEBUG_CALIBRATE, "crystal calibration 0x%08x\n",
 2349                     le32toh(sc->eeprom_crystal));
 2350         }
 2351 
 2352         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
 2353 
 2354 }
 2355 
 2356 /*
 2357  * Translate EEPROM flags to net80211.
 2358  */
 2359 static uint32_t
 2360 iwn_eeprom_channel_flags(struct iwn_eeprom_chan *channel)
 2361 {
 2362         uint32_t nflags;
 2363 
 2364         nflags = 0;
 2365         if ((channel->flags & IWN_EEPROM_CHAN_ACTIVE) == 0)
 2366                 nflags |= IEEE80211_CHAN_PASSIVE;
 2367         if ((channel->flags & IWN_EEPROM_CHAN_IBSS) == 0)
 2368                 nflags |= IEEE80211_CHAN_NOADHOC;
 2369         if (channel->flags & IWN_EEPROM_CHAN_RADAR) {
 2370                 nflags |= IEEE80211_CHAN_DFS;
 2371                 /* XXX apparently IBSS may still be marked */
 2372                 nflags |= IEEE80211_CHAN_NOADHOC;
 2373         }
 2374 
 2375         return nflags;
 2376 }
 2377 
 2378 static void
 2379 iwn_read_eeprom_band(struct iwn_softc *sc, int n, int maxchans, int *nchans,
 2380     struct ieee80211_channel chans[])
 2381 {
 2382         struct iwn_eeprom_chan *channels = sc->eeprom_channels[n];
 2383         const struct iwn_chan_band *band = &iwn_bands[n];
 2384         uint8_t bands[IEEE80211_MODE_BYTES];
 2385         uint8_t chan;
 2386         int i, error, nflags;
 2387 
 2388         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 2389 
 2390         memset(bands, 0, sizeof(bands));
 2391         if (n == 0) {
 2392                 setbit(bands, IEEE80211_MODE_11B);
 2393                 setbit(bands, IEEE80211_MODE_11G);
 2394                 if (sc->sc_flags & IWN_FLAG_HAS_11N)
 2395                         setbit(bands, IEEE80211_MODE_11NG);
 2396         } else {
 2397                 setbit(bands, IEEE80211_MODE_11A);
 2398                 if (sc->sc_flags & IWN_FLAG_HAS_11N)
 2399                         setbit(bands, IEEE80211_MODE_11NA);
 2400         }
 2401 
 2402         for (i = 0; i < band->nchan; i++) {
 2403                 if (!(channels[i].flags & IWN_EEPROM_CHAN_VALID)) {
 2404                         DPRINTF(sc, IWN_DEBUG_RESET,
 2405                             "skip chan %d flags 0x%x maxpwr %d\n",
 2406                             band->chan[i], channels[i].flags,
 2407                             channels[i].maxpwr);
 2408                         continue;
 2409                 }
 2410 
 2411                 chan = band->chan[i];
 2412                 nflags = iwn_eeprom_channel_flags(&channels[i]);
 2413                 error = ieee80211_add_channel(chans, maxchans, nchans,
 2414                     chan, 0, channels[i].maxpwr, nflags, bands);
 2415                 if (error != 0)
 2416                         break;
 2417 
 2418                 /* Save maximum allowed TX power for this channel. */
 2419                 /* XXX wrong */
 2420                 sc->maxpwr[chan] = channels[i].maxpwr;
 2421 
 2422                 DPRINTF(sc, IWN_DEBUG_RESET,
 2423                     "add chan %d flags 0x%x maxpwr %d\n", chan,
 2424                     channels[i].flags, channels[i].maxpwr);
 2425         }
 2426 
 2427         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
 2428 
 2429 }
 2430 
 2431 static void
 2432 iwn_read_eeprom_ht40(struct iwn_softc *sc, int n, int maxchans, int *nchans,
 2433     struct ieee80211_channel chans[])
 2434 {
 2435         struct iwn_eeprom_chan *channels = sc->eeprom_channels[n];
 2436         const struct iwn_chan_band *band = &iwn_bands[n];
 2437         uint8_t chan;
 2438         int i, error, nflags;
 2439 
 2440         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s start\n", __func__);
 2441 
 2442         if (!(sc->sc_flags & IWN_FLAG_HAS_11N)) {
 2443                 DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end no 11n\n", __func__);
 2444                 return;
 2445         }
 2446 
 2447         for (i = 0; i < band->nchan; i++) {
 2448                 if (!(channels[i].flags & IWN_EEPROM_CHAN_VALID)) {
 2449                         DPRINTF(sc, IWN_DEBUG_RESET,
 2450                             "skip chan %d flags 0x%x maxpwr %d\n",
 2451                             band->chan[i], channels[i].flags,
 2452                             channels[i].maxpwr);
 2453                         continue;
 2454                 }
 2455 
 2456                 chan = band->chan[i];
 2457                 nflags = iwn_eeprom_channel_flags(&channels[i]);
 2458                 nflags |= (n == 5 ? IEEE80211_CHAN_G : IEEE80211_CHAN_A);
 2459                 error = ieee80211_add_channel_ht40(chans, maxchans, nchans,
 2460                     chan, channels[i].maxpwr, nflags);
 2461                 switch (error) {
 2462                 case EINVAL:
 2463                         device_printf(sc->sc_dev,
 2464                             "%s: no entry for channel %d\n", __func__, chan);
 2465                         continue;
 2466                 case ENOENT:
 2467                         DPRINTF(sc, IWN_DEBUG_RESET,
 2468                             "%s: skip chan %d, extension channel not found\n",
 2469                             __func__, chan);
 2470                         continue;
 2471                 case ENOBUFS:
 2472                         device_printf(sc->sc_dev,
 2473                             "%s: channel table is full!\n", __func__);
 2474                         break;
 2475                 case 0:
 2476                         DPRINTF(sc, IWN_DEBUG_RESET,
 2477                             "add ht40 chan %d flags 0x%x maxpwr %d\n",
 2478                             chan, channels[i].flags, channels[i].maxpwr);
 2479                         /* FALLTHROUGH */
 2480                 default:
 2481                         break;
 2482                 }
 2483         }
 2484 
 2485         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
 2486 
 2487 }
 2488 
 2489 static void
 2490 iwn_read_eeprom_channels(struct iwn_softc *sc, int n, uint32_t addr)
 2491 {
 2492         struct ieee80211com *ic = &sc->sc_ic;
 2493 
 2494         iwn_read_prom_data(sc, addr, &sc->eeprom_channels[n],
 2495             iwn_bands[n].nchan * sizeof (struct iwn_eeprom_chan));
 2496 
 2497         if (n < 5) {
 2498                 iwn_read_eeprom_band(sc, n, IEEE80211_CHAN_MAX, &ic->ic_nchans,
 2499                     ic->ic_channels);
 2500         } else {
 2501                 iwn_read_eeprom_ht40(sc, n, IEEE80211_CHAN_MAX, &ic->ic_nchans,
 2502                     ic->ic_channels);
 2503         }
 2504         ieee80211_sort_channels(ic->ic_channels, ic->ic_nchans);
 2505 }
 2506 
 2507 static struct iwn_eeprom_chan *
 2508 iwn_find_eeprom_channel(struct iwn_softc *sc, struct ieee80211_channel *c)
 2509 {
 2510         int band, chan, i, j;
 2511 
 2512         if (IEEE80211_IS_CHAN_HT40(c)) {
 2513                 band = IEEE80211_IS_CHAN_5GHZ(c) ? 6 : 5;
 2514                 if (IEEE80211_IS_CHAN_HT40D(c))
 2515                         chan = c->ic_extieee;
 2516                 else
 2517                         chan = c->ic_ieee;
 2518                 for (i = 0; i < iwn_bands[band].nchan; i++) {
 2519                         if (iwn_bands[band].chan[i] == chan)
 2520                                 return &sc->eeprom_channels[band][i];
 2521                 }
 2522         } else {
 2523                 for (j = 0; j < 5; j++) {
 2524                         for (i = 0; i < iwn_bands[j].nchan; i++) {
 2525                                 if (iwn_bands[j].chan[i] == c->ic_ieee &&
 2526                                     ((j == 0) ^ IEEE80211_IS_CHAN_A(c)) == 1)
 2527                                         return &sc->eeprom_channels[j][i];
 2528                         }
 2529                 }
 2530         }
 2531         return NULL;
 2532 }
 2533 
 2534 static void
 2535 iwn_getradiocaps(struct ieee80211com *ic,
 2536     int maxchans, int *nchans, struct ieee80211_channel chans[])
 2537 {
 2538         struct iwn_softc *sc = ic->ic_softc;
 2539         int i;
 2540 
 2541         /* Parse the list of authorized channels. */
 2542         for (i = 0; i < 5 && *nchans < maxchans; i++)
 2543                 iwn_read_eeprom_band(sc, i, maxchans, nchans, chans);
 2544         for (i = 5; i < IWN_NBANDS - 1 && *nchans < maxchans; i++)
 2545                 iwn_read_eeprom_ht40(sc, i, maxchans, nchans, chans);
 2546 }
 2547 
 2548 /*
 2549  * Enforce flags read from EEPROM.
 2550  */
 2551 static int
 2552 iwn_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *rd,
 2553     int nchan, struct ieee80211_channel chans[])
 2554 {
 2555         struct iwn_softc *sc = ic->ic_softc;
 2556         int i;
 2557 
 2558         for (i = 0; i < nchan; i++) {
 2559                 struct ieee80211_channel *c = &chans[i];
 2560                 struct iwn_eeprom_chan *channel;
 2561 
 2562                 channel = iwn_find_eeprom_channel(sc, c);
 2563                 if (channel == NULL) {
 2564                         ic_printf(ic, "%s: invalid channel %u freq %u/0x%x\n",
 2565                             __func__, c->ic_ieee, c->ic_freq, c->ic_flags);
 2566                         return EINVAL;
 2567                 }
 2568                 c->ic_flags |= iwn_eeprom_channel_flags(channel);
 2569         }
 2570 
 2571         return 0;
 2572 }
 2573 
 2574 static void
 2575 iwn_read_eeprom_enhinfo(struct iwn_softc *sc)
 2576 {
 2577         struct iwn_eeprom_enhinfo enhinfo[35];
 2578         struct ieee80211com *ic = &sc->sc_ic;
 2579         struct ieee80211_channel *c;
 2580         uint16_t val, base;
 2581         int8_t maxpwr;
 2582         uint8_t flags;
 2583         int i, j;
 2584 
 2585         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 2586 
 2587         iwn_read_prom_data(sc, IWN5000_EEPROM_REG, &val, 2);
 2588         base = le16toh(val);
 2589         iwn_read_prom_data(sc, base + IWN6000_EEPROM_ENHINFO,
 2590             enhinfo, sizeof enhinfo);
 2591 
 2592         for (i = 0; i < nitems(enhinfo); i++) {
 2593                 flags = enhinfo[i].flags;
 2594                 if (!(flags & IWN_ENHINFO_VALID))
 2595                         continue;       /* Skip invalid entries. */
 2596 
 2597                 maxpwr = 0;
 2598                 if (sc->txchainmask & IWN_ANT_A)
 2599                         maxpwr = MAX(maxpwr, enhinfo[i].chain[0]);
 2600                 if (sc->txchainmask & IWN_ANT_B)
 2601                         maxpwr = MAX(maxpwr, enhinfo[i].chain[1]);
 2602                 if (sc->txchainmask & IWN_ANT_C)
 2603                         maxpwr = MAX(maxpwr, enhinfo[i].chain[2]);
 2604                 if (sc->ntxchains == 2)
 2605                         maxpwr = MAX(maxpwr, enhinfo[i].mimo2);
 2606                 else if (sc->ntxchains == 3)
 2607                         maxpwr = MAX(maxpwr, enhinfo[i].mimo3);
 2608 
 2609                 for (j = 0; j < ic->ic_nchans; j++) {
 2610                         c = &ic->ic_channels[j];
 2611                         if ((flags & IWN_ENHINFO_5GHZ)) {
 2612                                 if (!IEEE80211_IS_CHAN_A(c))
 2613                                         continue;
 2614                         } else if ((flags & IWN_ENHINFO_OFDM)) {
 2615                                 if (!IEEE80211_IS_CHAN_G(c))
 2616                                         continue;
 2617                         } else if (!IEEE80211_IS_CHAN_B(c))
 2618                                 continue;
 2619                         if ((flags & IWN_ENHINFO_HT40)) {
 2620                                 if (!IEEE80211_IS_CHAN_HT40(c))
 2621                                         continue;
 2622                         } else {
 2623                                 if (IEEE80211_IS_CHAN_HT40(c))
 2624                                         continue;
 2625                         }
 2626                         if (enhinfo[i].chan != 0 &&
 2627                             enhinfo[i].chan != c->ic_ieee)
 2628                                 continue;
 2629 
 2630                         DPRINTF(sc, IWN_DEBUG_RESET,
 2631                             "channel %d(%x), maxpwr %d\n", c->ic_ieee,
 2632                             c->ic_flags, maxpwr / 2);
 2633                         c->ic_maxregpower = maxpwr / 2;
 2634                         c->ic_maxpower = maxpwr;
 2635                 }
 2636         }
 2637 
 2638         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
 2639 
 2640 }
 2641 
 2642 static struct ieee80211_node *
 2643 iwn_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
 2644 {
 2645         return malloc(sizeof (struct iwn_node), M_80211_NODE,M_NOWAIT | M_ZERO);
 2646 }
 2647 
 2648 static __inline int
 2649 rate2plcp(int rate)
 2650 {
 2651         switch (rate & 0xff) {
 2652         case 12:        return 0xd;
 2653         case 18:        return 0xf;
 2654         case 24:        return 0x5;
 2655         case 36:        return 0x7;
 2656         case 48:        return 0x9;
 2657         case 72:        return 0xb;
 2658         case 96:        return 0x1;
 2659         case 108:       return 0x3;
 2660         case 2:         return 10;
 2661         case 4:         return 20;
 2662         case 11:        return 55;
 2663         case 22:        return 110;
 2664         }
 2665         return 0;
 2666 }
 2667 
 2668 static int
 2669 iwn_get_1stream_tx_antmask(struct iwn_softc *sc)
 2670 {
 2671 
 2672         return IWN_LSB(sc->txchainmask);
 2673 }
 2674 
 2675 static int
 2676 iwn_get_2stream_tx_antmask(struct iwn_softc *sc)
 2677 {
 2678         int tx;
 2679 
 2680         /*
 2681          * The '2 stream' setup is a bit .. odd.
 2682          *
 2683          * For NICs that support only 1 antenna, default to IWN_ANT_AB or
 2684          * the firmware panics (eg Intel 5100.)
 2685          *
 2686          * For NICs that support two antennas, we use ANT_AB.
 2687          *
 2688          * For NICs that support three antennas, we use the two that
 2689          * wasn't the default one.
 2690          *
 2691          * XXX TODO: if bluetooth (full concurrent) is enabled, restrict
 2692          * this to only one antenna.
 2693          */
 2694 
 2695         /* Default - transmit on the other antennas */
 2696         tx = (sc->txchainmask & ~IWN_LSB(sc->txchainmask));
 2697 
 2698         /* Now, if it's zero, set it to IWN_ANT_AB, so to not panic firmware */
 2699         if (tx == 0)
 2700                 tx = IWN_ANT_AB;
 2701 
 2702         /*
 2703          * If the NIC is a two-stream TX NIC, configure the TX mask to
 2704          * the default chainmask
 2705          */
 2706         else if (sc->ntxchains == 2)
 2707                 tx = sc->txchainmask;
 2708 
 2709         return (tx);
 2710 }
 2711 
 2712 
 2713 
 2714 /*
 2715  * Calculate the required PLCP value from the given rate,
 2716  * to the given node.
 2717  *
 2718  * This will take the node configuration (eg 11n, rate table
 2719  * setup, etc) into consideration.
 2720  */
 2721 static uint32_t
 2722 iwn_rate_to_plcp(struct iwn_softc *sc, struct ieee80211_node *ni,
 2723     uint8_t rate)
 2724 {
 2725         struct ieee80211com *ic = ni->ni_ic;
 2726         uint32_t plcp = 0;
 2727         int ridx;
 2728 
 2729         /*
 2730          * If it's an MCS rate, let's set the plcp correctly
 2731          * and set the relevant flags based on the node config.
 2732          */
 2733         if (rate & IEEE80211_RATE_MCS) {
 2734                 /*
 2735                  * Set the initial PLCP value to be between 0->31 for
 2736                  * MCS 0 -> MCS 31, then set the "I'm an MCS rate!"
 2737                  * flag.
 2738                  */
 2739                 plcp = IEEE80211_RV(rate) | IWN_RFLAG_MCS;
 2740 
 2741                 /*
 2742                  * XXX the following should only occur if both
 2743                  * the local configuration _and_ the remote node
 2744                  * advertise these capabilities.  Thus this code
 2745                  * may need fixing!
 2746                  */
 2747 
 2748                 /*
 2749                  * Set the channel width and guard interval.
 2750                  */
 2751                 if (IEEE80211_IS_CHAN_HT40(ni->ni_chan)) {
 2752                         plcp |= IWN_RFLAG_HT40;
 2753                         if (ni->ni_htcap & IEEE80211_HTCAP_SHORTGI40)
 2754                                 plcp |= IWN_RFLAG_SGI;
 2755                 } else if (ni->ni_htcap & IEEE80211_HTCAP_SHORTGI20) {
 2756                         plcp |= IWN_RFLAG_SGI;
 2757                 }
 2758 
 2759                 /*
 2760                  * Ensure the selected rate matches the link quality
 2761                  * table entries being used.
 2762                  */
 2763                 if (rate > 0x8f)
 2764                         plcp |= IWN_RFLAG_ANT(sc->txchainmask);
 2765                 else if (rate > 0x87)
 2766                         plcp |= IWN_RFLAG_ANT(iwn_get_2stream_tx_antmask(sc));
 2767                 else
 2768                         plcp |= IWN_RFLAG_ANT(iwn_get_1stream_tx_antmask(sc));
 2769         } else {
 2770                 /*
 2771                  * Set the initial PLCP - fine for both
 2772                  * OFDM and CCK rates.
 2773                  */
 2774                 plcp = rate2plcp(rate);
 2775 
 2776                 /* Set CCK flag if it's CCK */
 2777 
 2778                 /* XXX It would be nice to have a method
 2779                  * to map the ridx -> phy table entry
 2780                  * so we could just query that, rather than
 2781                  * this hack to check against IWN_RIDX_OFDM6.
 2782                  */
 2783                 ridx = ieee80211_legacy_rate_lookup(ic->ic_rt,
 2784                     rate & IEEE80211_RATE_VAL);
 2785                 if (ridx < IWN_RIDX_OFDM6 &&
 2786                     IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
 2787                         plcp |= IWN_RFLAG_CCK;
 2788 
 2789                 /* Set antenna configuration */
 2790                 /* XXX TODO: is this the right antenna to use for legacy? */
 2791                 plcp |= IWN_RFLAG_ANT(iwn_get_1stream_tx_antmask(sc));
 2792         }
 2793 
 2794         DPRINTF(sc, IWN_DEBUG_TXRATE, "%s: rate=0x%02x, plcp=0x%08x\n",
 2795             __func__,
 2796             rate,
 2797             plcp);
 2798 
 2799         return (htole32(plcp));
 2800 }
 2801 
 2802 static void
 2803 iwn_newassoc(struct ieee80211_node *ni, int isnew)
 2804 {
 2805         /* Doesn't do anything at the moment */
 2806 }
 2807 
 2808 static int
 2809 iwn_media_change(struct ifnet *ifp)
 2810 {
 2811         int error;
 2812 
 2813         error = ieee80211_media_change(ifp);
 2814         /* NB: only the fixed rate can change and that doesn't need a reset */
 2815         return (error == ENETRESET ? 0 : error);
 2816 }
 2817 
 2818 static int
 2819 iwn_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 2820 {
 2821         struct iwn_vap *ivp = IWN_VAP(vap);
 2822         struct ieee80211com *ic = vap->iv_ic;
 2823         struct iwn_softc *sc = ic->ic_softc;
 2824         int error = 0;
 2825 
 2826         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 2827 
 2828         DPRINTF(sc, IWN_DEBUG_STATE, "%s: %s -> %s\n", __func__,
 2829             ieee80211_state_name[vap->iv_state], ieee80211_state_name[nstate]);
 2830 
 2831         IEEE80211_UNLOCK(ic);
 2832         IWN_LOCK(sc);
 2833         callout_stop(&sc->calib_to);
 2834 
 2835         sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
 2836 
 2837         switch (nstate) {
 2838         case IEEE80211_S_ASSOC:
 2839                 if (vap->iv_state != IEEE80211_S_RUN)
 2840                         break;
 2841                 /* FALLTHROUGH */
 2842         case IEEE80211_S_AUTH:
 2843                 if (vap->iv_state == IEEE80211_S_AUTH)
 2844                         break;
 2845 
 2846                 /*
 2847                  * !AUTH -> AUTH transition requires state reset to handle
 2848                  * reassociations correctly.
 2849                  */
 2850                 sc->rxon->associd = 0;
 2851                 sc->rxon->filter &= ~htole32(IWN_FILTER_BSS);
 2852                 sc->calib.state = IWN_CALIB_STATE_INIT;
 2853 
 2854                 /* Wait until we hear a beacon before we transmit */
 2855                 if (IEEE80211_IS_CHAN_PASSIVE(ic->ic_curchan))
 2856                         sc->sc_beacon_wait = 1;
 2857 
 2858                 if ((error = iwn_auth(sc, vap)) != 0) {
 2859                         device_printf(sc->sc_dev,
 2860                             "%s: could not move to auth state\n", __func__);
 2861                 }
 2862                 break;
 2863 
 2864         case IEEE80211_S_RUN:
 2865                 /*
 2866                  * RUN -> RUN transition; Just restart the timers.
 2867                  */
 2868                 if (vap->iv_state == IEEE80211_S_RUN) {
 2869                         sc->calib_cnt = 0;
 2870                         break;
 2871                 }
 2872 
 2873                 /* Wait until we hear a beacon before we transmit */
 2874                 if (IEEE80211_IS_CHAN_PASSIVE(ic->ic_curchan))
 2875                         sc->sc_beacon_wait = 1;
 2876 
 2877                 /*
 2878                  * !RUN -> RUN requires setting the association id
 2879                  * which is done with a firmware cmd.  We also defer
 2880                  * starting the timers until that work is done.
 2881                  */
 2882                 if ((error = iwn_run(sc, vap)) != 0) {
 2883                         device_printf(sc->sc_dev,
 2884                             "%s: could not move to run state\n", __func__);
 2885                 }
 2886                 break;
 2887 
 2888         case IEEE80211_S_INIT:
 2889                 sc->calib.state = IWN_CALIB_STATE_INIT;
 2890                 /*
 2891                  * Purge the xmit queue so we don't have old frames
 2892                  * during a new association attempt.
 2893                  */
 2894                 sc->sc_beacon_wait = 0;
 2895                 iwn_xmit_queue_drain(sc);
 2896                 break;
 2897 
 2898         default:
 2899                 break;
 2900         }
 2901         IWN_UNLOCK(sc);
 2902         IEEE80211_LOCK(ic);
 2903         if (error != 0){
 2904                 DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end in error\n", __func__);
 2905                 return error;
 2906         }
 2907 
 2908         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 2909 
 2910         return ivp->iv_newstate(vap, nstate, arg);
 2911 }
 2912 
 2913 static void
 2914 iwn_calib_timeout(void *arg)
 2915 {
 2916         struct iwn_softc *sc = arg;
 2917 
 2918         IWN_LOCK_ASSERT(sc);
 2919 
 2920         /* Force automatic TX power calibration every 60 secs. */
 2921         if (++sc->calib_cnt >= 120) {
 2922                 uint32_t flags = 0;
 2923 
 2924                 DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s\n",
 2925                     "sending request for statistics");
 2926                 (void)iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags,
 2927                     sizeof flags, 1);
 2928                 sc->calib_cnt = 0;
 2929         }
 2930         callout_reset(&sc->calib_to, msecs_to_ticks(500), iwn_calib_timeout,
 2931             sc);
 2932 }
 2933 
 2934 /*
 2935  * Process an RX_PHY firmware notification.  This is usually immediately
 2936  * followed by an MPDU_RX_DONE notification.
 2937  */
 2938 static void
 2939 iwn_rx_phy(struct iwn_softc *sc, struct iwn_rx_desc *desc,
 2940     struct iwn_rx_data *data)
 2941 {
 2942         struct iwn_rx_stat *stat = (struct iwn_rx_stat *)(desc + 1);
 2943 
 2944         DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: received PHY stats\n", __func__);
 2945         bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
 2946 
 2947         /* Save RX statistics, they will be used on MPDU_RX_DONE. */
 2948         memcpy(&sc->last_rx_stat, stat, sizeof (*stat));
 2949         sc->last_rx_valid = 1;
 2950 }
 2951 
 2952 /*
 2953  * Process an RX_DONE (4965AGN only) or MPDU_RX_DONE firmware notification.
 2954  * Each MPDU_RX_DONE notification must be preceded by an RX_PHY one.
 2955  */
 2956 static void
 2957 iwn_rx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
 2958     struct iwn_rx_data *data)
 2959 {
 2960         struct iwn_ops *ops = &sc->ops;
 2961         struct ieee80211com *ic = &sc->sc_ic;
 2962         struct iwn_rx_ring *ring = &sc->rxq;
 2963         struct ieee80211_frame *wh;
 2964         struct ieee80211_node *ni;
 2965         struct mbuf *m, *m1;
 2966         struct iwn_rx_stat *stat;
 2967         caddr_t head;
 2968         bus_addr_t paddr;
 2969         uint32_t flags;
 2970         int error, len, rssi, nf;
 2971 
 2972         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 2973 
 2974         if (desc->type == IWN_MPDU_RX_DONE) {
 2975                 /* Check for prior RX_PHY notification. */
 2976                 if (!sc->last_rx_valid) {
 2977                         DPRINTF(sc, IWN_DEBUG_ANY,
 2978                             "%s: missing RX_PHY\n", __func__);
 2979                         return;
 2980                 }
 2981                 stat = &sc->last_rx_stat;
 2982         } else
 2983                 stat = (struct iwn_rx_stat *)(desc + 1);
 2984 
 2985         bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD);
 2986 
 2987         if (stat->cfg_phy_len > IWN_STAT_MAXLEN) {
 2988                 device_printf(sc->sc_dev,
 2989                     "%s: invalid RX statistic header, len %d\n", __func__,
 2990                     stat->cfg_phy_len);
 2991                 return;
 2992         }
 2993         if (desc->type == IWN_MPDU_RX_DONE) {
 2994                 struct iwn_rx_mpdu *mpdu = (struct iwn_rx_mpdu *)(desc + 1);
 2995                 head = (caddr_t)(mpdu + 1);
 2996                 len = le16toh(mpdu->len);
 2997         } else {
 2998                 head = (caddr_t)(stat + 1) + stat->cfg_phy_len;
 2999                 len = le16toh(stat->len);
 3000         }
 3001 
 3002         flags = le32toh(*(uint32_t *)(head + len));
 3003 
 3004         /* Discard frames with a bad FCS early. */
 3005         if ((flags & IWN_RX_NOERROR) != IWN_RX_NOERROR) {
 3006                 DPRINTF(sc, IWN_DEBUG_RECV, "%s: RX flags error %x\n",
 3007                     __func__, flags);
 3008                 counter_u64_add(ic->ic_ierrors, 1);
 3009                 return;
 3010         }
 3011         /* Discard frames that are too short. */
 3012         if (len < sizeof (struct ieee80211_frame_ack)) {
 3013                 DPRINTF(sc, IWN_DEBUG_RECV, "%s: frame too short: %d\n",
 3014                     __func__, len);
 3015                 counter_u64_add(ic->ic_ierrors, 1);
 3016                 return;
 3017         }
 3018 
 3019         m1 = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, IWN_RBUF_SIZE);
 3020         if (m1 == NULL) {
 3021                 DPRINTF(sc, IWN_DEBUG_ANY, "%s: no mbuf to restock ring\n",
 3022                     __func__);
 3023                 counter_u64_add(ic->ic_ierrors, 1);
 3024                 return;
 3025         }
 3026         bus_dmamap_unload(ring->data_dmat, data->map);
 3027 
 3028         error = bus_dmamap_load(ring->data_dmat, data->map, mtod(m1, void *),
 3029             IWN_RBUF_SIZE, iwn_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
 3030         if (error != 0 && error != EFBIG) {
 3031                 device_printf(sc->sc_dev,
 3032                     "%s: bus_dmamap_load failed, error %d\n", __func__, error);
 3033                 m_freem(m1);
 3034 
 3035                 /* Try to reload the old mbuf. */
 3036                 error = bus_dmamap_load(ring->data_dmat, data->map,
 3037                     mtod(data->m, void *), IWN_RBUF_SIZE, iwn_dma_map_addr,
 3038                     &paddr, BUS_DMA_NOWAIT);
 3039                 if (error != 0 && error != EFBIG) {
 3040                         panic("%s: could not load old RX mbuf", __func__);
 3041                 }
 3042                 /* Physical address may have changed. */
 3043                 ring->desc[ring->cur] = htole32(paddr >> 8);
 3044                 bus_dmamap_sync(ring->data_dmat, ring->desc_dma.map,
 3045                     BUS_DMASYNC_PREWRITE);
 3046                 counter_u64_add(ic->ic_ierrors, 1);
 3047                 return;
 3048         }
 3049 
 3050         m = data->m;
 3051         data->m = m1;
 3052         /* Update RX descriptor. */
 3053         ring->desc[ring->cur] = htole32(paddr >> 8);
 3054         bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
 3055             BUS_DMASYNC_PREWRITE);
 3056 
 3057         /* Finalize mbuf. */
 3058         m->m_data = head;
 3059         m->m_pkthdr.len = m->m_len = len;
 3060 
 3061         /* Grab a reference to the source node. */
 3062         wh = mtod(m, struct ieee80211_frame *);
 3063         if (len >= sizeof(struct ieee80211_frame_min))
 3064                 ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
 3065         else
 3066                 ni = NULL;
 3067         nf = (ni != NULL && ni->ni_vap->iv_state == IEEE80211_S_RUN &&
 3068             (ic->ic_flags & IEEE80211_F_SCAN) == 0) ? sc->noise : -95;
 3069 
 3070         rssi = ops->get_rssi(sc, stat);
 3071 
 3072         if (ieee80211_radiotap_active(ic)) {
 3073                 struct iwn_rx_radiotap_header *tap = &sc->sc_rxtap;
 3074 
 3075                 tap->wr_flags = 0;
 3076                 if (stat->flags & htole16(IWN_STAT_FLAG_SHPREAMBLE))
 3077                         tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
 3078                 tap->wr_dbm_antsignal = (int8_t)rssi;
 3079                 tap->wr_dbm_antnoise = (int8_t)nf;
 3080                 tap->wr_tsft = stat->tstamp;
 3081                 switch (stat->rate) {
 3082                 /* CCK rates. */
 3083                 case  10: tap->wr_rate =   2; break;
 3084                 case  20: tap->wr_rate =   4; break;
 3085                 case  55: tap->wr_rate =  11; break;
 3086                 case 110: tap->wr_rate =  22; break;
 3087                 /* OFDM rates. */
 3088                 case 0xd: tap->wr_rate =  12; break;
 3089                 case 0xf: tap->wr_rate =  18; break;
 3090                 case 0x5: tap->wr_rate =  24; break;
 3091                 case 0x7: tap->wr_rate =  36; break;
 3092                 case 0x9: tap->wr_rate =  48; break;
 3093                 case 0xb: tap->wr_rate =  72; break;
 3094                 case 0x1: tap->wr_rate =  96; break;
 3095                 case 0x3: tap->wr_rate = 108; break;
 3096                 /* Unknown rate: should not happen. */
 3097                 default:  tap->wr_rate =   0;
 3098                 }
 3099         }
 3100 
 3101         /*
 3102          * If it's a beacon and we're waiting, then do the
 3103          * wakeup.  This should unblock raw_xmit/start.
 3104          */
 3105         if (sc->sc_beacon_wait) {
 3106                 uint8_t type, subtype;
 3107                 /* NB: Re-assign wh */
 3108                 wh = mtod(m, struct ieee80211_frame *);
 3109                 type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
 3110                 subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
 3111                 /*
 3112                  * This assumes at this point we've received our own
 3113                  * beacon.
 3114                  */
 3115                 DPRINTF(sc, IWN_DEBUG_TRACE,
 3116                     "%s: beacon_wait, type=%d, subtype=%d\n",
 3117                     __func__, type, subtype);
 3118                 if (type == IEEE80211_FC0_TYPE_MGT &&
 3119                     subtype == IEEE80211_FC0_SUBTYPE_BEACON) {
 3120                         DPRINTF(sc, IWN_DEBUG_TRACE | IWN_DEBUG_XMIT,
 3121                             "%s: waking things up\n", __func__);
 3122                         /* queue taskqueue to transmit! */
 3123                         taskqueue_enqueue(sc->sc_tq, &sc->sc_xmit_task);
 3124                 }
 3125         }
 3126 
 3127         IWN_UNLOCK(sc);
 3128 
 3129         /* Send the frame to the 802.11 layer. */
 3130         if (ni != NULL) {
 3131                 if (ni->ni_flags & IEEE80211_NODE_HT)
 3132                         m->m_flags |= M_AMPDU;
 3133                 (void)ieee80211_input(ni, m, rssi - nf, nf);
 3134                 /* Node is no longer needed. */
 3135                 ieee80211_free_node(ni);
 3136         } else
 3137                 (void)ieee80211_input_all(ic, m, rssi - nf, nf);
 3138 
 3139         IWN_LOCK(sc);
 3140 
 3141         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 3142 
 3143 }
 3144 
 3145 /* Process an incoming Compressed BlockAck. */
 3146 static void
 3147 iwn_rx_compressed_ba(struct iwn_softc *sc, struct iwn_rx_desc *desc,
 3148     struct iwn_rx_data *data)
 3149 {
 3150         struct iwn_ops *ops = &sc->ops;
 3151         struct iwn_node *wn;
 3152         struct ieee80211_node *ni;
 3153         struct iwn_compressed_ba *ba = (struct iwn_compressed_ba *)(desc + 1);
 3154         struct iwn_tx_ring *txq;
 3155         struct iwn_tx_data *txdata;
 3156         struct ieee80211_tx_ampdu *tap;
 3157         struct mbuf *m;
 3158         uint64_t bitmap;
 3159         uint16_t ssn;
 3160         uint8_t tid;
 3161         int ackfailcnt = 0, i, lastidx, qid, *res, shift;
 3162         int tx_ok = 0, tx_err = 0;
 3163 
 3164         DPRINTF(sc, IWN_DEBUG_TRACE | IWN_DEBUG_XMIT, "->%s begin\n", __func__);
 3165 
 3166         bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
 3167 
 3168         qid = le16toh(ba->qid);
 3169         txq = &sc->txq[ba->qid];
 3170         tap = sc->qid2tap[ba->qid];
 3171         tid = tap->txa_tid;
 3172         wn = (void *)tap->txa_ni;
 3173 
 3174         res = NULL;
 3175         ssn = 0;
 3176         if (!IEEE80211_AMPDU_RUNNING(tap)) {
 3177                 res = tap->txa_private;
 3178                 ssn = tap->txa_start & 0xfff;
 3179         }
 3180 
 3181         for (lastidx = le16toh(ba->ssn) & 0xff; txq->read != lastidx;) {
 3182                 txdata = &txq->data[txq->read];
 3183 
 3184                 /* Unmap and free mbuf. */
 3185                 bus_dmamap_sync(txq->data_dmat, txdata->map,
 3186                     BUS_DMASYNC_POSTWRITE);
 3187                 bus_dmamap_unload(txq->data_dmat, txdata->map);
 3188                 m = txdata->m, txdata->m = NULL;
 3189                 ni = txdata->ni, txdata->ni = NULL;
 3190 
 3191                 KASSERT(ni != NULL, ("no node"));
 3192                 KASSERT(m != NULL, ("no mbuf"));
 3193 
 3194                 DPRINTF(sc, IWN_DEBUG_XMIT, "%s: freeing m=%p\n", __func__, m);
 3195                 ieee80211_tx_complete(ni, m, 1);
 3196 
 3197                 txq->queued--;
 3198                 txq->read = (txq->read + 1) % IWN_TX_RING_COUNT;
 3199         }
 3200 
 3201         if (txq->queued == 0 && res != NULL) {
 3202                 iwn_nic_lock(sc);
 3203                 ops->ampdu_tx_stop(sc, qid, tid, ssn);
 3204                 iwn_nic_unlock(sc);
 3205                 sc->qid2tap[qid] = NULL;
 3206                 free(res, M_DEVBUF);
 3207                 return;
 3208         }
 3209 
 3210         if (wn->agg[tid].bitmap == 0)
 3211                 return;
 3212 
 3213         shift = wn->agg[tid].startidx - ((le16toh(ba->seq) >> 4) & 0xff);
 3214         if (shift < 0)
 3215                 shift += 0x100;
 3216 
 3217         if (wn->agg[tid].nframes > (64 - shift))
 3218                 return;
 3219 
 3220         /*
 3221          * Walk the bitmap and calculate how many successful and failed
 3222          * attempts are made.
 3223          *
 3224          * Yes, the rate control code doesn't know these are A-MPDU
 3225          * subframes and that it's okay to fail some of these.
 3226          */
 3227         ni = tap->txa_ni;
 3228         bitmap = (le64toh(ba->bitmap) >> shift) & wn->agg[tid].bitmap;
 3229         for (i = 0; bitmap; i++) {
 3230                 if ((bitmap & 1) == 0) {
 3231                         tx_err ++;
 3232                         ieee80211_ratectl_tx_complete(ni->ni_vap, ni,
 3233                             IEEE80211_RATECTL_TX_FAILURE, &ackfailcnt, NULL);
 3234                 } else {
 3235                         tx_ok ++;
 3236                         ieee80211_ratectl_tx_complete(ni->ni_vap, ni,
 3237                             IEEE80211_RATECTL_TX_SUCCESS, &ackfailcnt, NULL);
 3238                 }
 3239                 bitmap >>= 1;
 3240         }
 3241 
 3242         DPRINTF(sc, IWN_DEBUG_TRACE | IWN_DEBUG_XMIT,
 3243             "->%s: end; %d ok; %d err\n",__func__, tx_ok, tx_err);
 3244 
 3245 }
 3246 
 3247 /*
 3248  * Process a CALIBRATION_RESULT notification sent by the initialization
 3249  * firmware on response to a CMD_CALIB_CONFIG command (5000 only).
 3250  */
 3251 static void
 3252 iwn5000_rx_calib_results(struct iwn_softc *sc, struct iwn_rx_desc *desc,
 3253     struct iwn_rx_data *data)
 3254 {
 3255         struct iwn_phy_calib *calib = (struct iwn_phy_calib *)(desc + 1);
 3256         int len, idx = -1;
 3257 
 3258         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 3259 
 3260         /* Runtime firmware should not send such a notification. */
 3261         if (sc->sc_flags & IWN_FLAG_CALIB_DONE){
 3262                 DPRINTF(sc, IWN_DEBUG_TRACE, "->%s received after clib done\n",
 3263             __func__);
 3264                 return;
 3265         }
 3266         len = (le32toh(desc->len) & 0x3fff) - 4;
 3267         bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
 3268 
 3269         switch (calib->code) {
 3270         case IWN5000_PHY_CALIB_DC:
 3271                 if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_DC)
 3272                         idx = 0;
 3273                 break;
 3274         case IWN5000_PHY_CALIB_LO:
 3275                 if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_LO)
 3276                         idx = 1;
 3277                 break;
 3278         case IWN5000_PHY_CALIB_TX_IQ:
 3279                 if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TX_IQ)
 3280                         idx = 2;
 3281                 break;
 3282         case IWN5000_PHY_CALIB_TX_IQ_PERIODIC:
 3283                 if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TX_IQ_PERIODIC)
 3284                         idx = 3;
 3285                 break;
 3286         case IWN5000_PHY_CALIB_BASE_BAND:
 3287                 if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_BASE_BAND)
 3288                         idx = 4;
 3289                 break;
 3290         }
 3291         if (idx == -1)  /* Ignore other results. */
 3292                 return;
 3293 
 3294         /* Save calibration result. */
 3295         if (sc->calibcmd[idx].buf != NULL)
 3296                 free(sc->calibcmd[idx].buf, M_DEVBUF);
 3297         sc->calibcmd[idx].buf = malloc(len, M_DEVBUF, M_NOWAIT);
 3298         if (sc->calibcmd[idx].buf == NULL) {
 3299                 DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 3300                     "not enough memory for calibration result %d\n",
 3301                     calib->code);
 3302                 return;
 3303         }
 3304         DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 3305             "saving calibration result idx=%d, code=%d len=%d\n", idx, calib->code, len);
 3306         sc->calibcmd[idx].len = len;
 3307         memcpy(sc->calibcmd[idx].buf, calib, len);
 3308 }
 3309 
 3310 static void
 3311 iwn_stats_update(struct iwn_softc *sc, struct iwn_calib_state *calib,
 3312     struct iwn_stats *stats, int len)
 3313 {
 3314         struct iwn_stats_bt *stats_bt;
 3315         struct iwn_stats *lstats;
 3316 
 3317         /*
 3318          * First - check whether the length is the bluetooth or normal.
 3319          *
 3320          * If it's normal - just copy it and bump out.
 3321          * Otherwise we have to convert things.
 3322          */
 3323 
 3324         if (len == sizeof(struct iwn_stats) + 4) {
 3325                 memcpy(&sc->last_stat, stats, sizeof(struct iwn_stats));
 3326                 sc->last_stat_valid = 1;
 3327                 return;
 3328         }
 3329 
 3330         /*
 3331          * If it's not the bluetooth size - log, then just copy.
 3332          */
 3333         if (len != sizeof(struct iwn_stats_bt) + 4) {
 3334                 DPRINTF(sc, IWN_DEBUG_STATS,
 3335                     "%s: size of rx statistics (%d) not an expected size!\n",
 3336                     __func__,
 3337                     len);
 3338                 memcpy(&sc->last_stat, stats, sizeof(struct iwn_stats));
 3339                 sc->last_stat_valid = 1;
 3340                 return;
 3341         }
 3342 
 3343         /*
 3344          * Ok. Time to copy.
 3345          */
 3346         stats_bt = (struct iwn_stats_bt *) stats;
 3347         lstats = &sc->last_stat;
 3348 
 3349         /* flags */
 3350         lstats->flags = stats_bt->flags;
 3351         /* rx_bt */
 3352         memcpy(&lstats->rx.ofdm, &stats_bt->rx_bt.ofdm,
 3353             sizeof(struct iwn_rx_phy_stats));
 3354         memcpy(&lstats->rx.cck, &stats_bt->rx_bt.cck,
 3355             sizeof(struct iwn_rx_phy_stats));
 3356         memcpy(&lstats->rx.general, &stats_bt->rx_bt.general_bt.common,
 3357             sizeof(struct iwn_rx_general_stats));
 3358         memcpy(&lstats->rx.ht, &stats_bt->rx_bt.ht,
 3359             sizeof(struct iwn_rx_ht_phy_stats));
 3360         /* tx */
 3361         memcpy(&lstats->tx, &stats_bt->tx,
 3362             sizeof(struct iwn_tx_stats));
 3363         /* general */
 3364         memcpy(&lstats->general, &stats_bt->general,
 3365             sizeof(struct iwn_general_stats));
 3366 
 3367         /* XXX TODO: Squirrel away the extra bluetooth stats somewhere */
 3368         sc->last_stat_valid = 1;
 3369 }
 3370 
 3371 /*
 3372  * Process an RX_STATISTICS or BEACON_STATISTICS firmware notification.
 3373  * The latter is sent by the firmware after each received beacon.
 3374  */
 3375 static void
 3376 iwn_rx_statistics(struct iwn_softc *sc, struct iwn_rx_desc *desc,
 3377     struct iwn_rx_data *data)
 3378 {
 3379         struct iwn_ops *ops = &sc->ops;
 3380         struct ieee80211com *ic = &sc->sc_ic;
 3381         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
 3382         struct iwn_calib_state *calib = &sc->calib;
 3383         struct iwn_stats *stats = (struct iwn_stats *)(desc + 1);
 3384         struct iwn_stats *lstats;
 3385         int temp;
 3386 
 3387         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 3388 
 3389         /* Ignore statistics received during a scan. */
 3390         if (vap->iv_state != IEEE80211_S_RUN ||
 3391             (ic->ic_flags & IEEE80211_F_SCAN)){
 3392                 DPRINTF(sc, IWN_DEBUG_TRACE, "->%s received during calib\n",
 3393             __func__);
 3394                 return;
 3395         }
 3396 
 3397         bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
 3398 
 3399         DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_STATS,
 3400             "%s: received statistics, cmd %d, len %d\n",
 3401             __func__, desc->type, le16toh(desc->len));
 3402         sc->calib_cnt = 0;      /* Reset TX power calibration timeout. */
 3403 
 3404         /*
 3405          * Collect/track general statistics for reporting.
 3406          *
 3407          * This takes care of ensuring that the bluetooth sized message
 3408          * will be correctly converted to the legacy sized message.
 3409          */
 3410         iwn_stats_update(sc, calib, stats, le16toh(desc->len));
 3411 
 3412         /*
 3413          * And now, let's take a reference of it to use!
 3414          */
 3415         lstats = &sc->last_stat;
 3416 
 3417         /* Test if temperature has changed. */
 3418         if (lstats->general.temp != sc->rawtemp) {
 3419                 /* Convert "raw" temperature to degC. */
 3420                 sc->rawtemp = stats->general.temp;
 3421                 temp = ops->get_temperature(sc);
 3422                 DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: temperature %d\n",
 3423                     __func__, temp);
 3424 
 3425                 /* Update TX power if need be (4965AGN only). */
 3426                 if (sc->hw_type == IWN_HW_REV_TYPE_4965)
 3427                         iwn4965_power_calibration(sc, temp);
 3428         }
 3429 
 3430         if (desc->type != IWN_BEACON_STATISTICS)
 3431                 return; /* Reply to a statistics request. */
 3432 
 3433         sc->noise = iwn_get_noise(&lstats->rx.general);
 3434         DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: noise %d\n", __func__, sc->noise);
 3435 
 3436         /* Test that RSSI and noise are present in stats report. */
 3437         if (le32toh(lstats->rx.general.flags) != 1) {
 3438                 DPRINTF(sc, IWN_DEBUG_ANY, "%s\n",
 3439                     "received statistics without RSSI");
 3440                 return;
 3441         }
 3442 
 3443         if (calib->state == IWN_CALIB_STATE_ASSOC)
 3444                 iwn_collect_noise(sc, &lstats->rx.general);
 3445         else if (calib->state == IWN_CALIB_STATE_RUN) {
 3446                 iwn_tune_sensitivity(sc, &lstats->rx);
 3447                 /*
 3448                  * XXX TODO: Only run the RX recovery if we're associated!
 3449                  */
 3450                 iwn_check_rx_recovery(sc, lstats);
 3451                 iwn_save_stats_counters(sc, lstats);
 3452         }
 3453 
 3454         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 3455 }
 3456 
 3457 /*
 3458  * Save the relevant statistic counters for the next calibration
 3459  * pass.
 3460  */
 3461 static void
 3462 iwn_save_stats_counters(struct iwn_softc *sc, const struct iwn_stats *rs)
 3463 {
 3464         struct iwn_calib_state *calib = &sc->calib;
 3465 
 3466         /* Save counters values for next call. */
 3467         calib->bad_plcp_cck = le32toh(rs->rx.cck.bad_plcp);
 3468         calib->fa_cck = le32toh(rs->rx.cck.fa);
 3469         calib->bad_plcp_ht = le32toh(rs->rx.ht.bad_plcp);
 3470         calib->bad_plcp_ofdm = le32toh(rs->rx.ofdm.bad_plcp);
 3471         calib->fa_ofdm = le32toh(rs->rx.ofdm.fa);
 3472 
 3473         /* Last time we received these tick values */
 3474         sc->last_calib_ticks = ticks;
 3475 }
 3476 
 3477 /*
 3478  * Process a TX_DONE firmware notification.  Unfortunately, the 4965AGN
 3479  * and 5000 adapters have different incompatible TX status formats.
 3480  */
 3481 static void
 3482 iwn4965_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
 3483     struct iwn_rx_data *data)
 3484 {
 3485         struct iwn4965_tx_stat *stat = (struct iwn4965_tx_stat *)(desc + 1);
 3486         struct iwn_tx_ring *ring;
 3487         int qid;
 3488 
 3489         qid = desc->qid & 0xf;
 3490         ring = &sc->txq[qid];
 3491 
 3492         DPRINTF(sc, IWN_DEBUG_XMIT, "%s: "
 3493             "qid %d idx %d RTS retries %d ACK retries %d nkill %d rate %x duration %d status %x\n",
 3494             __func__, desc->qid, desc->idx,
 3495             stat->rtsfailcnt,
 3496             stat->ackfailcnt,
 3497             stat->btkillcnt,
 3498             stat->rate, le16toh(stat->duration),
 3499             le32toh(stat->status));
 3500 
 3501         bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD);
 3502         if (qid >= sc->firstaggqueue) {
 3503                 iwn_ampdu_tx_done(sc, qid, desc->idx, stat->nframes,
 3504                     stat->ackfailcnt, &stat->status);
 3505         } else {
 3506                 iwn_tx_done(sc, desc, stat->ackfailcnt,
 3507                     le32toh(stat->status) & 0xff);
 3508         }
 3509 }
 3510 
 3511 static void
 3512 iwn5000_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
 3513     struct iwn_rx_data *data)
 3514 {
 3515         struct iwn5000_tx_stat *stat = (struct iwn5000_tx_stat *)(desc + 1);
 3516         struct iwn_tx_ring *ring;
 3517         int qid;
 3518 
 3519         qid = desc->qid & 0xf;
 3520         ring = &sc->txq[qid];
 3521 
 3522         DPRINTF(sc, IWN_DEBUG_XMIT, "%s: "
 3523             "qid %d idx %d RTS retries %d ACK retries %d nkill %d rate %x duration %d status %x\n",
 3524             __func__, desc->qid, desc->idx,
 3525             stat->rtsfailcnt,
 3526             stat->ackfailcnt,
 3527             stat->btkillcnt,
 3528             stat->rate, le16toh(stat->duration),
 3529             le32toh(stat->status));
 3530 
 3531 #ifdef notyet
 3532         /* Reset TX scheduler slot. */
 3533         iwn5000_reset_sched(sc, desc->qid & 0xf, desc->idx);
 3534 #endif
 3535 
 3536         bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD);
 3537         if (qid >= sc->firstaggqueue) {
 3538                 iwn_ampdu_tx_done(sc, qid, desc->idx, stat->nframes,
 3539                     stat->ackfailcnt, &stat->status);
 3540         } else {
 3541                 iwn_tx_done(sc, desc, stat->ackfailcnt,
 3542                     le16toh(stat->status) & 0xff);
 3543         }
 3544 }
 3545 
 3546 /*
 3547  * Adapter-independent backend for TX_DONE firmware notifications.
 3548  */
 3549 static void
 3550 iwn_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc, int ackfailcnt,
 3551     uint8_t status)
 3552 {
 3553         struct iwn_tx_ring *ring = &sc->txq[desc->qid & 0xf];
 3554         struct iwn_tx_data *data = &ring->data[desc->idx];
 3555         struct mbuf *m;
 3556         struct ieee80211_node *ni;
 3557         struct ieee80211vap *vap;
 3558 
 3559         KASSERT(data->ni != NULL, ("no node"));
 3560 
 3561         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 3562 
 3563         /* Unmap and free mbuf. */
 3564         bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTWRITE);
 3565         bus_dmamap_unload(ring->data_dmat, data->map);
 3566         m = data->m, data->m = NULL;
 3567         ni = data->ni, data->ni = NULL;
 3568         vap = ni->ni_vap;
 3569 
 3570         /*
 3571          * Update rate control statistics for the node.
 3572          */
 3573         if (status & IWN_TX_FAIL)
 3574                 ieee80211_ratectl_tx_complete(vap, ni,
 3575                     IEEE80211_RATECTL_TX_FAILURE, &ackfailcnt, NULL);
 3576         else
 3577                 ieee80211_ratectl_tx_complete(vap, ni,
 3578                     IEEE80211_RATECTL_TX_SUCCESS, &ackfailcnt, NULL);
 3579 
 3580         /*
 3581          * Channels marked for "radar" require traffic to be received
 3582          * to unlock before we can transmit.  Until traffic is seen
 3583          * any attempt to transmit is returned immediately with status
 3584          * set to IWN_TX_FAIL_TX_LOCKED.  Unfortunately this can easily
 3585          * happen on first authenticate after scanning.  To workaround
 3586          * this we ignore a failure of this sort in AUTH state so the
 3587          * 802.11 layer will fall back to using a timeout to wait for
 3588          * the AUTH reply.  This allows the firmware time to see
 3589          * traffic so a subsequent retry of AUTH succeeds.  It's
 3590          * unclear why the firmware does not maintain state for
 3591          * channels recently visited as this would allow immediate
 3592          * use of the channel after a scan (where we see traffic).
 3593          */
 3594         if (status == IWN_TX_FAIL_TX_LOCKED &&
 3595             ni->ni_vap->iv_state == IEEE80211_S_AUTH)
 3596                 ieee80211_tx_complete(ni, m, 0);
 3597         else
 3598                 ieee80211_tx_complete(ni, m,
 3599                     (status & IWN_TX_FAIL) != 0);
 3600 
 3601         sc->sc_tx_timer = 0;
 3602         if (--ring->queued < IWN_TX_RING_LOMARK)
 3603                 sc->qfullmsk &= ~(1 << ring->qid);
 3604 
 3605         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 3606 }
 3607 
 3608 /*
 3609  * Process a "command done" firmware notification.  This is where we wakeup
 3610  * processes waiting for a synchronous command completion.
 3611  */
 3612 static void
 3613 iwn_cmd_done(struct iwn_softc *sc, struct iwn_rx_desc *desc)
 3614 {
 3615         struct iwn_tx_ring *ring;
 3616         struct iwn_tx_data *data;
 3617         int cmd_queue_num;
 3618 
 3619         if (sc->sc_flags & IWN_FLAG_PAN_SUPPORT)
 3620                 cmd_queue_num = IWN_PAN_CMD_QUEUE;
 3621         else
 3622                 cmd_queue_num = IWN_CMD_QUEUE_NUM;
 3623 
 3624         if ((desc->qid & IWN_RX_DESC_QID_MSK) != cmd_queue_num)
 3625                 return; /* Not a command ack. */
 3626 
 3627         ring = &sc->txq[cmd_queue_num];
 3628         data = &ring->data[desc->idx];
 3629 
 3630         /* If the command was mapped in an mbuf, free it. */
 3631         if (data->m != NULL) {
 3632                 bus_dmamap_sync(ring->data_dmat, data->map,
 3633                     BUS_DMASYNC_POSTWRITE);
 3634                 bus_dmamap_unload(ring->data_dmat, data->map);
 3635                 m_freem(data->m);
 3636                 data->m = NULL;
 3637         }
 3638         wakeup(&ring->desc[desc->idx]);
 3639 }
 3640 
 3641 static void
 3642 iwn_ampdu_tx_done(struct iwn_softc *sc, int qid, int idx, int nframes,
 3643     int ackfailcnt, void *stat)
 3644 {
 3645         struct iwn_ops *ops = &sc->ops;
 3646         struct iwn_tx_ring *ring = &sc->txq[qid];
 3647         struct iwn_tx_data *data;
 3648         struct mbuf *m;
 3649         struct iwn_node *wn;
 3650         struct ieee80211_node *ni;
 3651         struct ieee80211_tx_ampdu *tap;
 3652         uint64_t bitmap;
 3653         uint32_t *status = stat;
 3654         uint16_t *aggstatus = stat;
 3655         uint16_t ssn;
 3656         uint8_t tid;
 3657         int bit, i, lastidx, *res, seqno, shift, start;
 3658 
 3659         /* XXX TODO: status is le16 field! Grr */
 3660 
 3661         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 3662         DPRINTF(sc, IWN_DEBUG_XMIT, "%s: nframes=%d, status=0x%08x\n",
 3663             __func__,
 3664             nframes,
 3665             *status);
 3666 
 3667         tap = sc->qid2tap[qid];
 3668         tid = tap->txa_tid;
 3669         wn = (void *)tap->txa_ni;
 3670         ni = tap->txa_ni;
 3671 
 3672         /*
 3673          * XXX TODO: ACK and RTS failures would be nice here!
 3674          */
 3675 
 3676         /*
 3677          * A-MPDU single frame status - if we failed to transmit it
 3678          * in A-MPDU, then it may be a permanent failure.
 3679          *
 3680          * XXX TODO: check what the Linux iwlwifi driver does here;
 3681          * there's some permanent and temporary failures that may be
 3682          * handled differently.
 3683          */
 3684         if (nframes == 1) {
 3685                 if ((*status & 0xff) != 1 && (*status & 0xff) != 2) {
 3686 #ifdef  NOT_YET
 3687                         printf("ieee80211_send_bar()\n");
 3688 #endif
 3689                         /*
 3690                          * If we completely fail a transmit, make sure a
 3691                          * notification is pushed up to the rate control
 3692                          * layer.
 3693                          */
 3694                         ieee80211_ratectl_tx_complete(ni->ni_vap,
 3695                             ni,
 3696                             IEEE80211_RATECTL_TX_FAILURE,
 3697                             &ackfailcnt,
 3698                             NULL);
 3699                 } else {
 3700                         /*
 3701                          * If nframes=1, then we won't be getting a BA for
 3702                          * this frame.  Ensure that we correctly update the
 3703                          * rate control code with how many retries were
 3704                          * needed to send it.
 3705                          */
 3706                         ieee80211_ratectl_tx_complete(ni->ni_vap,
 3707                             ni,
 3708                             IEEE80211_RATECTL_TX_SUCCESS,
 3709                             &ackfailcnt,
 3710                             NULL);
 3711                 }
 3712         }
 3713 
 3714         bitmap = 0;
 3715         start = idx;
 3716         for (i = 0; i < nframes; i++) {
 3717                 if (le16toh(aggstatus[i * 2]) & 0xc)
 3718                         continue;
 3719 
 3720                 idx = le16toh(aggstatus[2*i + 1]) & 0xff;
 3721                 bit = idx - start;
 3722                 shift = 0;
 3723                 if (bit >= 64) {
 3724                         shift = 0x100 - idx + start;
 3725                         bit = 0;
 3726                         start = idx;
 3727                 } else if (bit <= -64)
 3728                         bit = 0x100 - start + idx;
 3729                 else if (bit < 0) {
 3730                         shift = start - idx;
 3731                         start = idx;
 3732                         bit = 0;
 3733                 }
 3734                 bitmap = bitmap << shift;
 3735                 bitmap |= 1ULL << bit;
 3736         }
 3737         tap = sc->qid2tap[qid];
 3738         tid = tap->txa_tid;
 3739         wn = (void *)tap->txa_ni;
 3740         wn->agg[tid].bitmap = bitmap;
 3741         wn->agg[tid].startidx = start;
 3742         wn->agg[tid].nframes = nframes;
 3743 
 3744         res = NULL;
 3745         ssn = 0;
 3746         if (!IEEE80211_AMPDU_RUNNING(tap)) {
 3747                 res = tap->txa_private;
 3748                 ssn = tap->txa_start & 0xfff;
 3749         }
 3750 
 3751         /* This is going nframes DWORDS into the descriptor? */
 3752         seqno = le32toh(*(status + nframes)) & 0xfff;
 3753         for (lastidx = (seqno & 0xff); ring->read != lastidx;) {
 3754                 data = &ring->data[ring->read];
 3755 
 3756                 /* Unmap and free mbuf. */
 3757                 bus_dmamap_sync(ring->data_dmat, data->map,
 3758                     BUS_DMASYNC_POSTWRITE);
 3759                 bus_dmamap_unload(ring->data_dmat, data->map);
 3760                 m = data->m, data->m = NULL;
 3761                 ni = data->ni, data->ni = NULL;
 3762 
 3763                 KASSERT(ni != NULL, ("no node"));
 3764                 KASSERT(m != NULL, ("no mbuf"));
 3765                 DPRINTF(sc, IWN_DEBUG_XMIT, "%s: freeing m=%p\n", __func__, m);
 3766                 ieee80211_tx_complete(ni, m, 1);
 3767 
 3768                 ring->queued--;
 3769                 ring->read = (ring->read + 1) % IWN_TX_RING_COUNT;
 3770         }
 3771 
 3772         if (ring->queued == 0 && res != NULL) {
 3773                 iwn_nic_lock(sc);
 3774                 ops->ampdu_tx_stop(sc, qid, tid, ssn);
 3775                 iwn_nic_unlock(sc);
 3776                 sc->qid2tap[qid] = NULL;
 3777                 free(res, M_DEVBUF);
 3778                 return;
 3779         }
 3780 
 3781         sc->sc_tx_timer = 0;
 3782         if (ring->queued < IWN_TX_RING_LOMARK)
 3783                 sc->qfullmsk &= ~(1 << ring->qid);
 3784 
 3785         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 3786 }
 3787 
 3788 /*
 3789  * Process an INT_FH_RX or INT_SW_RX interrupt.
 3790  */
 3791 static void
 3792 iwn_notif_intr(struct iwn_softc *sc)
 3793 {
 3794         struct iwn_ops *ops = &sc->ops;
 3795         struct ieee80211com *ic = &sc->sc_ic;
 3796         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
 3797         uint16_t hw;
 3798 
 3799         bus_dmamap_sync(sc->rxq.stat_dma.tag, sc->rxq.stat_dma.map,
 3800             BUS_DMASYNC_POSTREAD);
 3801 
 3802         hw = le16toh(sc->rxq.stat->closed_count) & 0xfff;
 3803         while (sc->rxq.cur != hw) {
 3804                 struct iwn_rx_data *data = &sc->rxq.data[sc->rxq.cur];
 3805                 struct iwn_rx_desc *desc;
 3806 
 3807                 bus_dmamap_sync(sc->rxq.data_dmat, data->map,
 3808                     BUS_DMASYNC_POSTREAD);
 3809                 desc = mtod(data->m, struct iwn_rx_desc *);
 3810 
 3811                 DPRINTF(sc, IWN_DEBUG_RECV,
 3812                     "%s: cur=%d; qid %x idx %d flags %x type %d(%s) len %d\n",
 3813                     __func__, sc->rxq.cur, desc->qid & 0xf, desc->idx, desc->flags,
 3814                     desc->type, iwn_intr_str(desc->type),
 3815                     le16toh(desc->len));
 3816 
 3817                 if (!(desc->qid & IWN_UNSOLICITED_RX_NOTIF))    /* Reply to a command. */
 3818                         iwn_cmd_done(sc, desc);
 3819 
 3820                 switch (desc->type) {
 3821                 case IWN_RX_PHY:
 3822                         iwn_rx_phy(sc, desc, data);
 3823                         break;
 3824 
 3825                 case IWN_RX_DONE:               /* 4965AGN only. */
 3826                 case IWN_MPDU_RX_DONE:
 3827                         /* An 802.11 frame has been received. */
 3828                         iwn_rx_done(sc, desc, data);
 3829                         break;
 3830 
 3831                 case IWN_RX_COMPRESSED_BA:
 3832                         /* A Compressed BlockAck has been received. */
 3833                         iwn_rx_compressed_ba(sc, desc, data);
 3834                         break;
 3835 
 3836                 case IWN_TX_DONE:
 3837                         /* An 802.11 frame has been transmitted. */
 3838                         ops->tx_done(sc, desc, data);
 3839                         break;
 3840 
 3841                 case IWN_RX_STATISTICS:
 3842                 case IWN_BEACON_STATISTICS:
 3843                         iwn_rx_statistics(sc, desc, data);
 3844                         break;
 3845 
 3846                 case IWN_BEACON_MISSED:
 3847                 {
 3848                         struct iwn_beacon_missed *miss =
 3849                             (struct iwn_beacon_missed *)(desc + 1);
 3850                         int misses;
 3851 
 3852                         bus_dmamap_sync(sc->rxq.data_dmat, data->map,
 3853                             BUS_DMASYNC_POSTREAD);
 3854                         misses = le32toh(miss->consecutive);
 3855 
 3856                         DPRINTF(sc, IWN_DEBUG_STATE,
 3857                             "%s: beacons missed %d/%d\n", __func__,
 3858                             misses, le32toh(miss->total));
 3859                         /*
 3860                          * If more than 5 consecutive beacons are missed,
 3861                          * reinitialize the sensitivity state machine.
 3862                          */
 3863                         if (vap->iv_state == IEEE80211_S_RUN &&
 3864                             (ic->ic_flags & IEEE80211_F_SCAN) == 0) {
 3865                                 if (misses > 5)
 3866                                         (void)iwn_init_sensitivity(sc);
 3867                                 if (misses >= vap->iv_bmissthreshold) {
 3868                                         IWN_UNLOCK(sc);
 3869                                         ieee80211_beacon_miss(ic);
 3870                                         IWN_LOCK(sc);
 3871                                 }
 3872                         }
 3873                         break;
 3874                 }
 3875                 case IWN_UC_READY:
 3876                 {
 3877                         struct iwn_ucode_info *uc =
 3878                             (struct iwn_ucode_info *)(desc + 1);
 3879 
 3880                         /* The microcontroller is ready. */
 3881                         bus_dmamap_sync(sc->rxq.data_dmat, data->map,
 3882                             BUS_DMASYNC_POSTREAD);
 3883                         DPRINTF(sc, IWN_DEBUG_RESET,
 3884                             "microcode alive notification version=%d.%d "
 3885                             "subtype=%x alive=%x\n", uc->major, uc->minor,
 3886                             uc->subtype, le32toh(uc->valid));
 3887 
 3888                         if (le32toh(uc->valid) != 1) {
 3889                                 device_printf(sc->sc_dev,
 3890                                     "microcontroller initialization failed");
 3891                                 break;
 3892                         }
 3893                         if (uc->subtype == IWN_UCODE_INIT) {
 3894                                 /* Save microcontroller report. */
 3895                                 memcpy(&sc->ucode_info, uc, sizeof (*uc));
 3896                         }
 3897                         /* Save the address of the error log in SRAM. */
 3898                         sc->errptr = le32toh(uc->errptr);
 3899                         break;
 3900                 }
 3901                 case IWN_STATE_CHANGED:
 3902                 {
 3903                         /*
 3904                          * State change allows hardware switch change to be
 3905                          * noted. However, we handle this in iwn_intr as we
 3906                          * get both the enable/disble intr.
 3907                          */
 3908                         bus_dmamap_sync(sc->rxq.data_dmat, data->map,
 3909                             BUS_DMASYNC_POSTREAD);
 3910 #ifdef  IWN_DEBUG
 3911                         uint32_t *status = (uint32_t *)(desc + 1);
 3912                         DPRINTF(sc, IWN_DEBUG_INTR | IWN_DEBUG_STATE,
 3913                             "state changed to %x\n",
 3914                             le32toh(*status));
 3915 #endif
 3916                         break;
 3917                 }
 3918                 case IWN_START_SCAN:
 3919                 {
 3920                         bus_dmamap_sync(sc->rxq.data_dmat, data->map,
 3921                             BUS_DMASYNC_POSTREAD);
 3922 #ifdef  IWN_DEBUG
 3923                         struct iwn_start_scan *scan =
 3924                             (struct iwn_start_scan *)(desc + 1);
 3925                         DPRINTF(sc, IWN_DEBUG_ANY,
 3926                             "%s: scanning channel %d status %x\n",
 3927                             __func__, scan->chan, le32toh(scan->status));
 3928 #endif
 3929                         break;
 3930                 }
 3931                 case IWN_STOP_SCAN:
 3932                 {
 3933                         bus_dmamap_sync(sc->rxq.data_dmat, data->map,
 3934                             BUS_DMASYNC_POSTREAD);
 3935 #ifdef  IWN_DEBUG
 3936                         struct iwn_stop_scan *scan =
 3937                             (struct iwn_stop_scan *)(desc + 1);
 3938                         DPRINTF(sc, IWN_DEBUG_STATE | IWN_DEBUG_SCAN,
 3939                             "scan finished nchan=%d status=%d chan=%d\n",
 3940                             scan->nchan, scan->status, scan->chan);
 3941 #endif
 3942                         sc->sc_is_scanning = 0;
 3943                         callout_stop(&sc->scan_timeout);
 3944                         IWN_UNLOCK(sc);
 3945                         ieee80211_scan_next(vap);
 3946                         IWN_LOCK(sc);
 3947                         break;
 3948                 }
 3949                 case IWN5000_CALIBRATION_RESULT:
 3950                         iwn5000_rx_calib_results(sc, desc, data);
 3951                         break;
 3952 
 3953                 case IWN5000_CALIBRATION_DONE:
 3954                         sc->sc_flags |= IWN_FLAG_CALIB_DONE;
 3955                         wakeup(sc);
 3956                         break;
 3957                 }
 3958 
 3959                 sc->rxq.cur = (sc->rxq.cur + 1) % IWN_RX_RING_COUNT;
 3960         }
 3961 
 3962         /* Tell the firmware what we have processed. */
 3963         hw = (hw == 0) ? IWN_RX_RING_COUNT - 1 : hw - 1;
 3964         IWN_WRITE(sc, IWN_FH_RX_WPTR, hw & ~7);
 3965 }
 3966 
 3967 /*
 3968  * Process an INT_WAKEUP interrupt raised when the microcontroller wakes up
 3969  * from power-down sleep mode.
 3970  */
 3971 static void
 3972 iwn_wakeup_intr(struct iwn_softc *sc)
 3973 {
 3974         int qid;
 3975 
 3976         DPRINTF(sc, IWN_DEBUG_RESET, "%s: ucode wakeup from power-down sleep\n",
 3977             __func__);
 3978 
 3979         /* Wakeup RX and TX rings. */
 3980         IWN_WRITE(sc, IWN_FH_RX_WPTR, sc->rxq.cur & ~7);
 3981         for (qid = 0; qid < sc->ntxqs; qid++) {
 3982                 struct iwn_tx_ring *ring = &sc->txq[qid];
 3983                 IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | ring->cur);
 3984         }
 3985 }
 3986 
 3987 static void
 3988 iwn_rftoggle_intr(struct iwn_softc *sc)
 3989 {
 3990         struct ieee80211com *ic = &sc->sc_ic;
 3991         uint32_t tmp = IWN_READ(sc, IWN_GP_CNTRL);
 3992 
 3993         IWN_LOCK_ASSERT(sc);
 3994 
 3995         device_printf(sc->sc_dev, "RF switch: radio %s\n",
 3996             (tmp & IWN_GP_CNTRL_RFKILL) ? "enabled" : "disabled");
 3997         if (tmp & IWN_GP_CNTRL_RFKILL)
 3998                 ieee80211_runtask(ic, &sc->sc_radioon_task);
 3999         else
 4000                 ieee80211_runtask(ic, &sc->sc_radiooff_task);
 4001 }
 4002 
 4003 /*
 4004  * Dump the error log of the firmware when a firmware panic occurs.  Although
 4005  * we can't debug the firmware because it is neither open source nor free, it
 4006  * can help us to identify certain classes of problems.
 4007  */
 4008 static void
 4009 iwn_fatal_intr(struct iwn_softc *sc)
 4010 {
 4011         struct iwn_fw_dump dump;
 4012         int i;
 4013 
 4014         IWN_LOCK_ASSERT(sc);
 4015 
 4016         /* Force a complete recalibration on next init. */
 4017         sc->sc_flags &= ~IWN_FLAG_CALIB_DONE;
 4018 
 4019         /* Check that the error log address is valid. */
 4020         if (sc->errptr < IWN_FW_DATA_BASE ||
 4021             sc->errptr + sizeof (dump) >
 4022             IWN_FW_DATA_BASE + sc->fw_data_maxsz) {
 4023                 printf("%s: bad firmware error log address 0x%08x\n", __func__,
 4024                     sc->errptr);
 4025                 return;
 4026         }
 4027         if (iwn_nic_lock(sc) != 0) {
 4028                 printf("%s: could not read firmware error log\n", __func__);
 4029                 return;
 4030         }
 4031         /* Read firmware error log from SRAM. */
 4032         iwn_mem_read_region_4(sc, sc->errptr, (uint32_t *)&dump,
 4033             sizeof (dump) / sizeof (uint32_t));
 4034         iwn_nic_unlock(sc);
 4035 
 4036         if (dump.valid == 0) {
 4037                 printf("%s: firmware error log is empty\n", __func__);
 4038                 return;
 4039         }
 4040         printf("firmware error log:\n");
 4041         printf("  error type      = \"%s\" (0x%08X)\n",
 4042             (dump.id < nitems(iwn_fw_errmsg)) ?
 4043                 iwn_fw_errmsg[dump.id] : "UNKNOWN",
 4044             dump.id);
 4045         printf("  program counter = 0x%08X\n", dump.pc);
 4046         printf("  source line     = 0x%08X\n", dump.src_line);
 4047         printf("  error data      = 0x%08X%08X\n",
 4048             dump.error_data[0], dump.error_data[1]);
 4049         printf("  branch link     = 0x%08X%08X\n",
 4050             dump.branch_link[0], dump.branch_link[1]);
 4051         printf("  interrupt link  = 0x%08X%08X\n",
 4052             dump.interrupt_link[0], dump.interrupt_link[1]);
 4053         printf("  time            = %u\n", dump.time[0]);
 4054 
 4055         /* Dump driver status (TX and RX rings) while we're here. */
 4056         printf("driver status:\n");
 4057         for (i = 0; i < sc->ntxqs; i++) {
 4058                 struct iwn_tx_ring *ring = &sc->txq[i];
 4059                 printf("  tx ring %2d: qid=%-2d cur=%-3d queued=%-3d\n",
 4060                     i, ring->qid, ring->cur, ring->queued);
 4061         }
 4062         printf("  rx ring: cur=%d\n", sc->rxq.cur);
 4063 }
 4064 
 4065 static void
 4066 iwn_intr(void *arg)
 4067 {
 4068         struct iwn_softc *sc = arg;
 4069         uint32_t r1, r2, tmp;
 4070 
 4071         IWN_LOCK(sc);
 4072 
 4073         /* Disable interrupts. */
 4074         IWN_WRITE(sc, IWN_INT_MASK, 0);
 4075 
 4076         /* Read interrupts from ICT (fast) or from registers (slow). */
 4077         if (sc->sc_flags & IWN_FLAG_USE_ICT) {
 4078                 tmp = 0;
 4079                 while (sc->ict[sc->ict_cur] != 0) {
 4080                         tmp |= sc->ict[sc->ict_cur];
 4081                         sc->ict[sc->ict_cur] = 0;       /* Acknowledge. */
 4082                         sc->ict_cur = (sc->ict_cur + 1) % IWN_ICT_COUNT;
 4083                 }
 4084                 tmp = le32toh(tmp);
 4085                 if (tmp == 0xffffffff)  /* Shouldn't happen. */
 4086                         tmp = 0;
 4087                 else if (tmp & 0xc0000) /* Workaround a HW bug. */
 4088                         tmp |= 0x8000;
 4089                 r1 = (tmp & 0xff00) << 16 | (tmp & 0xff);
 4090                 r2 = 0; /* Unused. */
 4091         } else {
 4092                 r1 = IWN_READ(sc, IWN_INT);
 4093                 if (r1 == 0xffffffff || (r1 & 0xfffffff0) == 0xa5a5a5a0) {
 4094                         IWN_UNLOCK(sc);
 4095                         return; /* Hardware gone! */
 4096                 }
 4097                 r2 = IWN_READ(sc, IWN_FH_INT);
 4098         }
 4099 
 4100         DPRINTF(sc, IWN_DEBUG_INTR, "interrupt reg1=0x%08x reg2=0x%08x\n"
 4101     , r1, r2);
 4102 
 4103         if (r1 == 0 && r2 == 0)
 4104                 goto done;      /* Interrupt not for us. */
 4105 
 4106         /* Acknowledge interrupts. */
 4107         IWN_WRITE(sc, IWN_INT, r1);
 4108         if (!(sc->sc_flags & IWN_FLAG_USE_ICT))
 4109                 IWN_WRITE(sc, IWN_FH_INT, r2);
 4110 
 4111         if (r1 & IWN_INT_RF_TOGGLED) {
 4112                 iwn_rftoggle_intr(sc);
 4113                 goto done;
 4114         }
 4115         if (r1 & IWN_INT_CT_REACHED) {
 4116                 device_printf(sc->sc_dev, "%s: critical temperature reached!\n",
 4117                     __func__);
 4118         }
 4119         if (r1 & (IWN_INT_SW_ERR | IWN_INT_HW_ERR)) {
 4120                 device_printf(sc->sc_dev, "%s: fatal firmware error\n",
 4121                     __func__);
 4122 #ifdef  IWN_DEBUG
 4123                 iwn_debug_register(sc);
 4124 #endif
 4125                 /* Dump firmware error log and stop. */
 4126                 iwn_fatal_intr(sc);
 4127 
 4128                 taskqueue_enqueue(sc->sc_tq, &sc->sc_panic_task);
 4129                 goto done;
 4130         }
 4131         if ((r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX | IWN_INT_RX_PERIODIC)) ||
 4132             (r2 & IWN_FH_INT_RX)) {
 4133                 if (sc->sc_flags & IWN_FLAG_USE_ICT) {
 4134                         if (r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX))
 4135                                 IWN_WRITE(sc, IWN_FH_INT, IWN_FH_INT_RX);
 4136                         IWN_WRITE_1(sc, IWN_INT_PERIODIC,
 4137                             IWN_INT_PERIODIC_DIS);
 4138                         iwn_notif_intr(sc);
 4139                         if (r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX)) {
 4140                                 IWN_WRITE_1(sc, IWN_INT_PERIODIC,
 4141                                     IWN_INT_PERIODIC_ENA);
 4142                         }
 4143                 } else
 4144                         iwn_notif_intr(sc);
 4145         }
 4146 
 4147         if ((r1 & IWN_INT_FH_TX) || (r2 & IWN_FH_INT_TX)) {
 4148                 if (sc->sc_flags & IWN_FLAG_USE_ICT)
 4149                         IWN_WRITE(sc, IWN_FH_INT, IWN_FH_INT_TX);
 4150                 wakeup(sc);     /* FH DMA transfer completed. */
 4151         }
 4152 
 4153         if (r1 & IWN_INT_ALIVE)
 4154                 wakeup(sc);     /* Firmware is alive. */
 4155 
 4156         if (r1 & IWN_INT_WAKEUP)
 4157                 iwn_wakeup_intr(sc);
 4158 
 4159 done:
 4160         /* Re-enable interrupts. */
 4161         if (sc->sc_flags & IWN_FLAG_RUNNING)
 4162                 IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
 4163 
 4164         IWN_UNLOCK(sc);
 4165 }
 4166 
 4167 /*
 4168  * Update TX scheduler ring when transmitting an 802.11 frame (4965AGN and
 4169  * 5000 adapters use a slightly different format).
 4170  */
 4171 static void
 4172 iwn4965_update_sched(struct iwn_softc *sc, int qid, int idx, uint8_t id,
 4173     uint16_t len)
 4174 {
 4175         uint16_t *w = &sc->sched[qid * IWN4965_SCHED_COUNT + idx];
 4176 
 4177         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 4178 
 4179         *w = htole16(len + 8);
 4180         bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
 4181             BUS_DMASYNC_PREWRITE);
 4182         if (idx < IWN_SCHED_WINSZ) {
 4183                 *(w + IWN_TX_RING_COUNT) = *w;
 4184                 bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
 4185                     BUS_DMASYNC_PREWRITE);
 4186         }
 4187 }
 4188 
 4189 static void
 4190 iwn5000_update_sched(struct iwn_softc *sc, int qid, int idx, uint8_t id,
 4191     uint16_t len)
 4192 {
 4193         uint16_t *w = &sc->sched[qid * IWN5000_SCHED_COUNT + idx];
 4194 
 4195         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 4196 
 4197         *w = htole16(id << 12 | (len + 8));
 4198         bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
 4199             BUS_DMASYNC_PREWRITE);
 4200         if (idx < IWN_SCHED_WINSZ) {
 4201                 *(w + IWN_TX_RING_COUNT) = *w;
 4202                 bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
 4203                     BUS_DMASYNC_PREWRITE);
 4204         }
 4205 }
 4206 
 4207 #ifdef notyet
 4208 static void
 4209 iwn5000_reset_sched(struct iwn_softc *sc, int qid, int idx)
 4210 {
 4211         uint16_t *w = &sc->sched[qid * IWN5000_SCHED_COUNT + idx];
 4212 
 4213         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 4214 
 4215         *w = (*w & htole16(0xf000)) | htole16(1);
 4216         bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
 4217             BUS_DMASYNC_PREWRITE);
 4218         if (idx < IWN_SCHED_WINSZ) {
 4219                 *(w + IWN_TX_RING_COUNT) = *w;
 4220                 bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
 4221                     BUS_DMASYNC_PREWRITE);
 4222         }
 4223 }
 4224 #endif
 4225 
 4226 /*
 4227  * Check whether OFDM 11g protection will be enabled for the given rate.
 4228  *
 4229  * The original driver code only enabled protection for OFDM rates.
 4230  * It didn't check to see whether it was operating in 11a or 11bg mode.
 4231  */
 4232 static int
 4233 iwn_check_rate_needs_protection(struct iwn_softc *sc,
 4234     struct ieee80211vap *vap, uint8_t rate)
 4235 {
 4236         struct ieee80211com *ic = vap->iv_ic;
 4237 
 4238         /*
 4239          * Not in 2GHz mode? Then there's no need to enable OFDM
 4240          * 11bg protection.
 4241          */
 4242         if (! IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan)) {
 4243                 return (0);
 4244         }
 4245 
 4246         /*
 4247          * 11bg protection not enabled? Then don't use it.
 4248          */
 4249         if ((ic->ic_flags & IEEE80211_F_USEPROT) == 0)
 4250                 return (0);
 4251 
 4252         /*
 4253          * If it's an 11n rate - no protection.
 4254          * We'll do it via a specific 11n check.
 4255          */
 4256         if (rate & IEEE80211_RATE_MCS) {
 4257                 return (0);
 4258         }
 4259 
 4260         /*
 4261          * Do a rate table lookup.  If the PHY is CCK,
 4262          * don't do protection.
 4263          */
 4264         if (ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_CCK)
 4265                 return (0);
 4266 
 4267         /*
 4268          * Yup, enable protection.
 4269          */
 4270         return (1);
 4271 }
 4272 
 4273 /*
 4274  * return a value between 0 and IWN_MAX_TX_RETRIES-1 as an index into
 4275  * the link quality table that reflects this particular entry.
 4276  */
 4277 static int
 4278 iwn_tx_rate_to_linkq_offset(struct iwn_softc *sc, struct ieee80211_node *ni,
 4279     uint8_t rate)
 4280 {
 4281         struct ieee80211_rateset *rs;
 4282         int is_11n;
 4283         int nr;
 4284         int i;
 4285         uint8_t cmp_rate;
 4286 
 4287         /*
 4288          * Figure out if we're using 11n or not here.
 4289          */
 4290         if (IEEE80211_IS_CHAN_HT(ni->ni_chan) && ni->ni_htrates.rs_nrates > 0)
 4291                 is_11n = 1;
 4292         else
 4293                 is_11n = 0;
 4294 
 4295         /*
 4296          * Use the correct rate table.
 4297          */
 4298         if (is_11n) {
 4299                 rs = (struct ieee80211_rateset *) &ni->ni_htrates;
 4300                 nr = ni->ni_htrates.rs_nrates;
 4301         } else {
 4302                 rs = &ni->ni_rates;
 4303                 nr = rs->rs_nrates;
 4304         }
 4305 
 4306         /*
 4307          * Find the relevant link quality entry in the table.
 4308          */
 4309         for (i = 0; i < nr && i < IWN_MAX_TX_RETRIES - 1 ; i++) {
 4310                 /*
 4311                  * The link quality table index starts at 0 == highest
 4312                  * rate, so we walk the rate table backwards.
 4313                  */
 4314                 cmp_rate = rs->rs_rates[(nr - 1) - i];
 4315                 if (rate & IEEE80211_RATE_MCS)
 4316                         cmp_rate |= IEEE80211_RATE_MCS;
 4317 
 4318 #if 0
 4319                 DPRINTF(sc, IWN_DEBUG_XMIT, "%s: idx %d: nr=%d, rate=0x%02x, rateentry=0x%02x\n",
 4320                     __func__,
 4321                     i,
 4322                     nr,
 4323                     rate,
 4324                     cmp_rate);
 4325 #endif
 4326 
 4327                 if (cmp_rate == rate)
 4328                         return (i);
 4329         }
 4330 
 4331         /* Failed? Start at the end */
 4332         return (IWN_MAX_TX_RETRIES - 1);
 4333 }
 4334 
 4335 static int
 4336 iwn_tx_data(struct iwn_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
 4337 {
 4338         struct iwn_ops *ops = &sc->ops;
 4339         const struct ieee80211_txparam *tp;
 4340         struct ieee80211vap *vap = ni->ni_vap;
 4341         struct ieee80211com *ic = ni->ni_ic;
 4342         struct iwn_node *wn = (void *)ni;
 4343         struct iwn_tx_ring *ring;
 4344         struct iwn_tx_desc *desc;
 4345         struct iwn_tx_data *data;
 4346         struct iwn_tx_cmd *cmd;
 4347         struct iwn_cmd_data *tx;
 4348         struct ieee80211_frame *wh;
 4349         struct ieee80211_key *k = NULL;
 4350         struct mbuf *m1;
 4351         uint32_t flags;
 4352         uint16_t qos;
 4353         u_int hdrlen;
 4354         bus_dma_segment_t *seg, segs[IWN_MAX_SCATTER];
 4355         uint8_t tid, type;
 4356         int ac, i, totlen, error, pad, nsegs = 0, rate;
 4357 
 4358         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 4359 
 4360         IWN_LOCK_ASSERT(sc);
 4361 
 4362         wh = mtod(m, struct ieee80211_frame *);
 4363         hdrlen = ieee80211_anyhdrsize(wh);
 4364         type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
 4365 
 4366         /* Select EDCA Access Category and TX ring for this frame. */
 4367         if (IEEE80211_QOS_HAS_SEQ(wh)) {
 4368                 qos = ((const struct ieee80211_qosframe *)wh)->i_qos[0];
 4369                 tid = qos & IEEE80211_QOS_TID;
 4370         } else {
 4371                 qos = 0;
 4372                 tid = 0;
 4373         }
 4374         ac = M_WME_GETAC(m);
 4375         if (m->m_flags & M_AMPDU_MPDU) {
 4376                 uint16_t seqno;
 4377                 struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[ac];
 4378 
 4379                 if (!IEEE80211_AMPDU_RUNNING(tap)) {
 4380                         return EINVAL;
 4381                 }
 4382 
 4383                 /*
 4384                  * Queue this frame to the hardware ring that we've
 4385                  * negotiated AMPDU TX on.
 4386                  *
 4387                  * Note that the sequence number must match the TX slot
 4388                  * being used!
 4389                  */
 4390                 ac = *(int *)tap->txa_private;
 4391                 seqno = ni->ni_txseqs[tid];
 4392                 *(uint16_t *)wh->i_seq =
 4393                     htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT);
 4394                 ring = &sc->txq[ac];
 4395                 if ((seqno % 256) != ring->cur) {
 4396                         device_printf(sc->sc_dev,
 4397                             "%s: m=%p: seqno (%d) (%d) != ring index (%d) !\n",
 4398                             __func__,
 4399                             m,
 4400                             seqno,
 4401                             seqno % 256,
 4402                             ring->cur);
 4403                 }
 4404                 ni->ni_txseqs[tid]++;
 4405         }
 4406         ring = &sc->txq[ac];
 4407         desc = &ring->desc[ring->cur];
 4408         data = &ring->data[ring->cur];
 4409 
 4410         /* Choose a TX rate index. */
 4411         tp = &vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)];
 4412         if (type == IEEE80211_FC0_TYPE_MGT)
 4413                 rate = tp->mgmtrate;
 4414         else if (IEEE80211_IS_MULTICAST(wh->i_addr1))
 4415                 rate = tp->mcastrate;
 4416         else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
 4417                 rate = tp->ucastrate;
 4418         else if (m->m_flags & M_EAPOL)
 4419                 rate = tp->mgmtrate;
 4420         else {
 4421                 /* XXX pass pktlen */
 4422                 (void) ieee80211_ratectl_rate(ni, NULL, 0);
 4423                 rate = ni->ni_txrate;
 4424         }
 4425 
 4426         /* Encrypt the frame if need be. */
 4427         if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
 4428                 /* Retrieve key for TX. */
 4429                 k = ieee80211_crypto_encap(ni, m);
 4430                 if (k == NULL) {
 4431                         return ENOBUFS;
 4432                 }
 4433                 /* 802.11 header may have moved. */
 4434                 wh = mtod(m, struct ieee80211_frame *);
 4435         }
 4436         totlen = m->m_pkthdr.len;
 4437 
 4438         if (ieee80211_radiotap_active_vap(vap)) {
 4439                 struct iwn_tx_radiotap_header *tap = &sc->sc_txtap;
 4440 
 4441                 tap->wt_flags = 0;
 4442                 tap->wt_rate = rate;
 4443                 if (k != NULL)
 4444                         tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
 4445 
 4446                 ieee80211_radiotap_tx(vap, m);
 4447         }
 4448 
 4449         /* Prepare TX firmware command. */
 4450         cmd = &ring->cmd[ring->cur];
 4451         cmd->code = IWN_CMD_TX_DATA;
 4452         cmd->flags = 0;
 4453         cmd->qid = ring->qid;
 4454         cmd->idx = ring->cur;
 4455 
 4456         tx = (struct iwn_cmd_data *)cmd->data;
 4457         /* NB: No need to clear tx, all fields are reinitialized here. */
 4458         tx->scratch = 0;        /* clear "scratch" area */
 4459 
 4460         flags = 0;
 4461         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
 4462                 /* Unicast frame, check if an ACK is expected. */
 4463                 if (!qos || (qos & IEEE80211_QOS_ACKPOLICY) !=
 4464                     IEEE80211_QOS_ACKPOLICY_NOACK)
 4465                         flags |= IWN_TX_NEED_ACK;
 4466         }
 4467         if ((wh->i_fc[0] &
 4468             (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
 4469             (IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_BAR))
 4470                 flags |= IWN_TX_IMM_BA;         /* Cannot happen yet. */
 4471 
 4472         if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG)
 4473                 flags |= IWN_TX_MORE_FRAG;      /* Cannot happen yet. */
 4474 
 4475         /* Check if frame must be protected using RTS/CTS or CTS-to-self. */
 4476         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
 4477                 /* NB: Group frames are sent using CCK in 802.11b/g. */
 4478                 if (totlen + IEEE80211_CRC_LEN > vap->iv_rtsthreshold) {
 4479                         flags |= IWN_TX_NEED_RTS;
 4480                 } else if (iwn_check_rate_needs_protection(sc, vap, rate)) {
 4481                         if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
 4482                                 flags |= IWN_TX_NEED_CTS;
 4483                         else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
 4484                                 flags |= IWN_TX_NEED_RTS;
 4485                 } else if ((rate & IEEE80211_RATE_MCS) &&
 4486                         (ic->ic_htprotmode == IEEE80211_PROT_RTSCTS)) {
 4487                         flags |= IWN_TX_NEED_RTS;
 4488                 }
 4489 
 4490                 /* XXX HT protection? */
 4491 
 4492                 if (flags & (IWN_TX_NEED_RTS | IWN_TX_NEED_CTS)) {
 4493                         if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
 4494                                 /* 5000 autoselects RTS/CTS or CTS-to-self. */
 4495                                 flags &= ~(IWN_TX_NEED_RTS | IWN_TX_NEED_CTS);
 4496                                 flags |= IWN_TX_NEED_PROTECTION;
 4497                         } else
 4498                                 flags |= IWN_TX_FULL_TXOP;
 4499                 }
 4500         }
 4501 
 4502         if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
 4503             type != IEEE80211_FC0_TYPE_DATA)
 4504                 tx->id = sc->broadcast_id;
 4505         else
 4506                 tx->id = wn->id;
 4507 
 4508         if (type == IEEE80211_FC0_TYPE_MGT) {
 4509                 uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
 4510 
 4511                 /* Tell HW to set timestamp in probe responses. */
 4512                 if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
 4513                         flags |= IWN_TX_INSERT_TSTAMP;
 4514                 if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
 4515                     subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
 4516                         tx->timeout = htole16(3);
 4517                 else
 4518                         tx->timeout = htole16(2);
 4519         } else
 4520                 tx->timeout = htole16(0);
 4521 
 4522         if (hdrlen & 3) {
 4523                 /* First segment length must be a multiple of 4. */
 4524                 flags |= IWN_TX_NEED_PADDING;
 4525                 pad = 4 - (hdrlen & 3);
 4526         } else
 4527                 pad = 0;
 4528 
 4529         tx->len = htole16(totlen);
 4530         tx->tid = tid;
 4531         tx->rts_ntries = 60;
 4532         tx->data_ntries = 15;
 4533         tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
 4534         tx->rate = iwn_rate_to_plcp(sc, ni, rate);
 4535         if (tx->id == sc->broadcast_id) {
 4536                 /* Group or management frame. */
 4537                 tx->linkq = 0;
 4538         } else {
 4539                 tx->linkq = iwn_tx_rate_to_linkq_offset(sc, ni, rate);
 4540                 flags |= IWN_TX_LINKQ;  /* enable MRR */
 4541         }
 4542 
 4543         /* Set physical address of "scratch area". */
 4544         tx->loaddr = htole32(IWN_LOADDR(data->scratch_paddr));
 4545         tx->hiaddr = IWN_HIADDR(data->scratch_paddr);
 4546 
 4547         /* Copy 802.11 header in TX command. */
 4548         memcpy((uint8_t *)(tx + 1), wh, hdrlen);
 4549 
 4550         /* Trim 802.11 header. */
 4551         m_adj(m, hdrlen);
 4552         tx->security = 0;
 4553         tx->flags = htole32(flags);
 4554 
 4555         error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m, segs,
 4556             &nsegs, BUS_DMA_NOWAIT);
 4557         if (error != 0) {
 4558                 if (error != EFBIG) {
 4559                         device_printf(sc->sc_dev,
 4560                             "%s: can't map mbuf (error %d)\n", __func__, error);
 4561                         return error;
 4562                 }
 4563                 /* Too many DMA segments, linearize mbuf. */
 4564                 m1 = m_collapse(m, M_NOWAIT, IWN_MAX_SCATTER - 1);
 4565                 if (m1 == NULL) {
 4566                         device_printf(sc->sc_dev,
 4567                             "%s: could not defrag mbuf\n", __func__);
 4568                         return ENOBUFS;
 4569                 }
 4570                 m = m1;
 4571 
 4572                 error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m,
 4573                     segs, &nsegs, BUS_DMA_NOWAIT);
 4574                 if (error != 0) {
 4575                         device_printf(sc->sc_dev,
 4576                             "%s: can't map mbuf (error %d)\n", __func__, error);
 4577                         return error;
 4578                 }
 4579         }
 4580 
 4581         data->m = m;
 4582         data->ni = ni;
 4583 
 4584         DPRINTF(sc, IWN_DEBUG_XMIT,
 4585             "%s: qid %d idx %d len %d nsegs %d flags 0x%08x rate 0x%04x plcp 0x%08x\n",
 4586             __func__,
 4587             ring->qid,
 4588             ring->cur,
 4589             m->m_pkthdr.len,
 4590             nsegs,
 4591             flags,
 4592             rate,
 4593             tx->rate);
 4594 
 4595         /* Fill TX descriptor. */
 4596         desc->nsegs = 1;
 4597         if (m->m_len != 0)
 4598                 desc->nsegs += nsegs;
 4599         /* First DMA segment is used by the TX command. */
 4600         desc->segs[0].addr = htole32(IWN_LOADDR(data->cmd_paddr));
 4601         desc->segs[0].len  = htole16(IWN_HIADDR(data->cmd_paddr) |
 4602             (4 + sizeof (*tx) + hdrlen + pad) << 4);
 4603         /* Other DMA segments are for data payload. */
 4604         seg = &segs[0];
 4605         for (i = 1; i <= nsegs; i++) {
 4606                 desc->segs[i].addr = htole32(IWN_LOADDR(seg->ds_addr));
 4607                 desc->segs[i].len  = htole16(IWN_HIADDR(seg->ds_addr) |
 4608                     seg->ds_len << 4);
 4609                 seg++;
 4610         }
 4611 
 4612         bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
 4613         bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
 4614             BUS_DMASYNC_PREWRITE);
 4615         bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
 4616             BUS_DMASYNC_PREWRITE);
 4617 
 4618         /* Update TX scheduler. */
 4619         if (ring->qid >= sc->firstaggqueue)
 4620                 ops->update_sched(sc, ring->qid, ring->cur, tx->id, totlen);
 4621 
 4622         /* Kick TX ring. */
 4623         ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
 4624         IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
 4625 
 4626         /* Mark TX ring as full if we reach a certain threshold. */
 4627         if (++ring->queued > IWN_TX_RING_HIMARK)
 4628                 sc->qfullmsk |= 1 << ring->qid;
 4629 
 4630         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 4631 
 4632         return 0;
 4633 }
 4634 
 4635 static int
 4636 iwn_tx_data_raw(struct iwn_softc *sc, struct mbuf *m,
 4637     struct ieee80211_node *ni, const struct ieee80211_bpf_params *params)
 4638 {
 4639         struct iwn_ops *ops = &sc->ops;
 4640         struct ieee80211vap *vap = ni->ni_vap;
 4641         struct iwn_tx_cmd *cmd;
 4642         struct iwn_cmd_data *tx;
 4643         struct ieee80211_frame *wh;
 4644         struct iwn_tx_ring *ring;
 4645         struct iwn_tx_desc *desc;
 4646         struct iwn_tx_data *data;
 4647         struct mbuf *m1;
 4648         bus_dma_segment_t *seg, segs[IWN_MAX_SCATTER];
 4649         uint32_t flags;
 4650         u_int hdrlen;
 4651         int ac, totlen, error, pad, nsegs = 0, i, rate;
 4652         uint8_t type;
 4653 
 4654         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 4655 
 4656         IWN_LOCK_ASSERT(sc);
 4657 
 4658         wh = mtod(m, struct ieee80211_frame *);
 4659         hdrlen = ieee80211_anyhdrsize(wh);
 4660         type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
 4661 
 4662         ac = params->ibp_pri & 3;
 4663 
 4664         ring = &sc->txq[ac];
 4665         desc = &ring->desc[ring->cur];
 4666         data = &ring->data[ring->cur];
 4667 
 4668         /* Choose a TX rate. */
 4669         rate = params->ibp_rate0;
 4670         totlen = m->m_pkthdr.len;
 4671 
 4672         /* Prepare TX firmware command. */
 4673         cmd = &ring->cmd[ring->cur];
 4674         cmd->code = IWN_CMD_TX_DATA;
 4675         cmd->flags = 0;
 4676         cmd->qid = ring->qid;
 4677         cmd->idx = ring->cur;
 4678 
 4679         tx = (struct iwn_cmd_data *)cmd->data;
 4680         /* NB: No need to clear tx, all fields are reinitialized here. */
 4681         tx->scratch = 0;        /* clear "scratch" area */
 4682 
 4683         flags = 0;
 4684         if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0)
 4685                 flags |= IWN_TX_NEED_ACK;
 4686         if (params->ibp_flags & IEEE80211_BPF_RTS) {
 4687                 if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
 4688                         /* 5000 autoselects RTS/CTS or CTS-to-self. */
 4689                         flags &= ~IWN_TX_NEED_RTS;
 4690                         flags |= IWN_TX_NEED_PROTECTION;
 4691                 } else
 4692                         flags |= IWN_TX_NEED_RTS | IWN_TX_FULL_TXOP;
 4693         }
 4694         if (params->ibp_flags & IEEE80211_BPF_CTS) {
 4695                 if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
 4696                         /* 5000 autoselects RTS/CTS or CTS-to-self. */
 4697                         flags &= ~IWN_TX_NEED_CTS;
 4698                         flags |= IWN_TX_NEED_PROTECTION;
 4699                 } else
 4700                         flags |= IWN_TX_NEED_CTS | IWN_TX_FULL_TXOP;
 4701         }
 4702         if (type == IEEE80211_FC0_TYPE_MGT) {
 4703                 uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
 4704 
 4705                 /* Tell HW to set timestamp in probe responses. */
 4706                 if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
 4707                         flags |= IWN_TX_INSERT_TSTAMP;
 4708 
 4709                 if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
 4710                     subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
 4711                         tx->timeout = htole16(3);
 4712                 else
 4713                         tx->timeout = htole16(2);
 4714         } else
 4715                 tx->timeout = htole16(0);
 4716 
 4717         if (hdrlen & 3) {
 4718                 /* First segment length must be a multiple of 4. */
 4719                 flags |= IWN_TX_NEED_PADDING;
 4720                 pad = 4 - (hdrlen & 3);
 4721         } else
 4722                 pad = 0;
 4723 
 4724         if (ieee80211_radiotap_active_vap(vap)) {
 4725                 struct iwn_tx_radiotap_header *tap = &sc->sc_txtap;
 4726 
 4727                 tap->wt_flags = 0;
 4728                 tap->wt_rate = rate;
 4729 
 4730                 ieee80211_radiotap_tx(vap, m);
 4731         }
 4732 
 4733         tx->len = htole16(totlen);
 4734         tx->tid = 0;
 4735         tx->id = sc->broadcast_id;
 4736         tx->rts_ntries = params->ibp_try1;
 4737         tx->data_ntries = params->ibp_try0;
 4738         tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
 4739         tx->rate = iwn_rate_to_plcp(sc, ni, rate);
 4740 
 4741         /* Group or management frame. */
 4742         tx->linkq = 0;
 4743 
 4744         /* Set physical address of "scratch area". */
 4745         tx->loaddr = htole32(IWN_LOADDR(data->scratch_paddr));
 4746         tx->hiaddr = IWN_HIADDR(data->scratch_paddr);
 4747 
 4748         /* Copy 802.11 header in TX command. */
 4749         memcpy((uint8_t *)(tx + 1), wh, hdrlen);
 4750 
 4751         /* Trim 802.11 header. */
 4752         m_adj(m, hdrlen);
 4753         tx->security = 0;
 4754         tx->flags = htole32(flags);
 4755 
 4756         error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m, segs,
 4757             &nsegs, BUS_DMA_NOWAIT);
 4758         if (error != 0) {
 4759                 if (error != EFBIG) {
 4760                         device_printf(sc->sc_dev,
 4761                             "%s: can't map mbuf (error %d)\n", __func__, error);
 4762                         return error;
 4763                 }
 4764                 /* Too many DMA segments, linearize mbuf. */
 4765                 m1 = m_collapse(m, M_NOWAIT, IWN_MAX_SCATTER - 1);
 4766                 if (m1 == NULL) {
 4767                         device_printf(sc->sc_dev,
 4768                             "%s: could not defrag mbuf\n", __func__);
 4769                         return ENOBUFS;
 4770                 }
 4771                 m = m1;
 4772 
 4773                 error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m,
 4774                     segs, &nsegs, BUS_DMA_NOWAIT);
 4775                 if (error != 0) {
 4776                         device_printf(sc->sc_dev,
 4777                             "%s: can't map mbuf (error %d)\n", __func__, error);
 4778                         return error;
 4779                 }
 4780         }
 4781 
 4782         data->m = m;
 4783         data->ni = ni;
 4784 
 4785         DPRINTF(sc, IWN_DEBUG_XMIT, "%s: qid %d idx %d len %d nsegs %d\n",
 4786             __func__, ring->qid, ring->cur, m->m_pkthdr.len, nsegs);
 4787 
 4788         /* Fill TX descriptor. */
 4789         desc->nsegs = 1;
 4790         if (m->m_len != 0)
 4791                 desc->nsegs += nsegs;
 4792         /* First DMA segment is used by the TX command. */
 4793         desc->segs[0].addr = htole32(IWN_LOADDR(data->cmd_paddr));
 4794         desc->segs[0].len  = htole16(IWN_HIADDR(data->cmd_paddr) |
 4795             (4 + sizeof (*tx) + hdrlen + pad) << 4);
 4796         /* Other DMA segments are for data payload. */
 4797         seg = &segs[0];
 4798         for (i = 1; i <= nsegs; i++) {
 4799                 desc->segs[i].addr = htole32(IWN_LOADDR(seg->ds_addr));
 4800                 desc->segs[i].len  = htole16(IWN_HIADDR(seg->ds_addr) |
 4801                     seg->ds_len << 4);
 4802                 seg++;
 4803         }
 4804 
 4805         bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
 4806         bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
 4807             BUS_DMASYNC_PREWRITE);
 4808         bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
 4809             BUS_DMASYNC_PREWRITE);
 4810 
 4811         /* Update TX scheduler. */
 4812         if (ring->qid >= sc->firstaggqueue)
 4813                 ops->update_sched(sc, ring->qid, ring->cur, tx->id, totlen);
 4814 
 4815         /* Kick TX ring. */
 4816         ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
 4817         IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
 4818 
 4819         /* Mark TX ring as full if we reach a certain threshold. */
 4820         if (++ring->queued > IWN_TX_RING_HIMARK)
 4821                 sc->qfullmsk |= 1 << ring->qid;
 4822 
 4823         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 4824 
 4825         return 0;
 4826 }
 4827 
 4828 static void
 4829 iwn_xmit_task(void *arg0, int pending)
 4830 {
 4831         struct iwn_softc *sc = arg0;
 4832         struct ieee80211_node *ni;
 4833         struct mbuf *m;
 4834         int error;
 4835         struct ieee80211_bpf_params p;
 4836         int have_p;
 4837 
 4838         DPRINTF(sc, IWN_DEBUG_XMIT, "%s: called\n", __func__);
 4839 
 4840         IWN_LOCK(sc);
 4841         /*
 4842          * Dequeue frames, attempt to transmit,
 4843          * then disable beaconwait when we're done.
 4844          */
 4845         while ((m = mbufq_dequeue(&sc->sc_xmit_queue)) != NULL) {
 4846                 have_p = 0;
 4847                 ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
 4848 
 4849                 /* Get xmit params if appropriate */
 4850                 if (ieee80211_get_xmit_params(m, &p) == 0)
 4851                         have_p = 1;
 4852 
 4853                 DPRINTF(sc, IWN_DEBUG_XMIT, "%s: m=%p, have_p=%d\n",
 4854                     __func__, m, have_p);
 4855 
 4856                 /* If we have xmit params, use them */
 4857                 if (have_p)
 4858                         error = iwn_tx_data_raw(sc, m, ni, &p);
 4859                 else
 4860                         error = iwn_tx_data(sc, m, ni);
 4861 
 4862                 if (error != 0) {
 4863                         if_inc_counter(ni->ni_vap->iv_ifp,
 4864                             IFCOUNTER_OERRORS, 1);
 4865                         ieee80211_free_node(ni);
 4866                         m_freem(m);
 4867                 }
 4868         }
 4869 
 4870         sc->sc_beacon_wait = 0;
 4871         IWN_UNLOCK(sc);
 4872 }
 4873 
 4874 /*
 4875  * raw frame xmit - free node/reference if failed.
 4876  */
 4877 static int
 4878 iwn_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
 4879     const struct ieee80211_bpf_params *params)
 4880 {
 4881         struct ieee80211com *ic = ni->ni_ic;
 4882         struct iwn_softc *sc = ic->ic_softc;
 4883         int error = 0;
 4884 
 4885         DPRINTF(sc, IWN_DEBUG_XMIT | IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 4886 
 4887         IWN_LOCK(sc);
 4888         if ((sc->sc_flags & IWN_FLAG_RUNNING) == 0) {
 4889                 m_freem(m);
 4890                 IWN_UNLOCK(sc);
 4891                 return (ENETDOWN);
 4892         }
 4893 
 4894         /* queue frame if we have to */
 4895         if (sc->sc_beacon_wait) {
 4896                 if (iwn_xmit_queue_enqueue(sc, m) != 0) {
 4897                         m_freem(m);
 4898                         IWN_UNLOCK(sc);
 4899                         return (ENOBUFS);
 4900                 }
 4901                 /* Queued, so just return OK */
 4902                 IWN_UNLOCK(sc);
 4903                 return (0);
 4904         }
 4905 
 4906         if (params == NULL) {
 4907                 /*
 4908                  * Legacy path; interpret frame contents to decide
 4909                  * precisely how to send the frame.
 4910                  */
 4911                 error = iwn_tx_data(sc, m, ni);
 4912         } else {
 4913                 /*
 4914                  * Caller supplied explicit parameters to use in
 4915                  * sending the frame.
 4916                  */
 4917                 error = iwn_tx_data_raw(sc, m, ni, params);
 4918         }
 4919         if (error == 0)
 4920                 sc->sc_tx_timer = 5;
 4921         else
 4922                 m_freem(m);
 4923 
 4924         IWN_UNLOCK(sc);
 4925 
 4926         DPRINTF(sc, IWN_DEBUG_TRACE | IWN_DEBUG_XMIT, "->%s: end\n",__func__);
 4927 
 4928         return (error);
 4929 }
 4930 
 4931 /*
 4932  * transmit - don't free mbuf if failed; don't free node ref if failed.
 4933  */
 4934 static int
 4935 iwn_transmit(struct ieee80211com *ic, struct mbuf *m)
 4936 {
 4937         struct iwn_softc *sc = ic->ic_softc;
 4938         struct ieee80211_node *ni;
 4939         int error;
 4940 
 4941         ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
 4942 
 4943         IWN_LOCK(sc);
 4944         if ((sc->sc_flags & IWN_FLAG_RUNNING) == 0 || sc->sc_beacon_wait) {
 4945                 IWN_UNLOCK(sc);
 4946                 return (ENXIO);
 4947         }
 4948 
 4949         if (sc->qfullmsk) {
 4950                 IWN_UNLOCK(sc);
 4951                 return (ENOBUFS);
 4952         }
 4953 
 4954         error = iwn_tx_data(sc, m, ni);
 4955         if (!error)
 4956                 sc->sc_tx_timer = 5;
 4957         IWN_UNLOCK(sc);
 4958         return (error);
 4959 }
 4960 
 4961 static void
 4962 iwn_scan_timeout(void *arg)
 4963 {
 4964         struct iwn_softc *sc = arg;
 4965         struct ieee80211com *ic = &sc->sc_ic;
 4966 
 4967         ic_printf(ic, "scan timeout\n");
 4968         ieee80211_restart_all(ic);
 4969 }
 4970 
 4971 static void
 4972 iwn_watchdog(void *arg)
 4973 {
 4974         struct iwn_softc *sc = arg;
 4975         struct ieee80211com *ic = &sc->sc_ic;
 4976 
 4977         IWN_LOCK_ASSERT(sc);
 4978 
 4979         KASSERT(sc->sc_flags & IWN_FLAG_RUNNING, ("not running"));
 4980 
 4981         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 4982 
 4983         if (sc->sc_tx_timer > 0) {
 4984                 if (--sc->sc_tx_timer == 0) {
 4985                         ic_printf(ic, "device timeout\n");
 4986                         ieee80211_restart_all(ic);
 4987                         return;
 4988                 }
 4989         }
 4990         callout_reset(&sc->watchdog_to, hz, iwn_watchdog, sc);
 4991 }
 4992 
 4993 static int
 4994 iwn_cdev_open(struct cdev *dev, int flags, int type, struct thread *td)
 4995 {
 4996 
 4997         return (0);
 4998 }
 4999 
 5000 static int
 5001 iwn_cdev_close(struct cdev *dev, int flags, int type, struct thread *td)
 5002 {
 5003 
 5004         return (0);
 5005 }
 5006 
 5007 static int
 5008 iwn_cdev_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
 5009     struct thread *td)
 5010 {
 5011         int rc;
 5012         struct iwn_softc *sc = dev->si_drv1;
 5013         struct iwn_ioctl_data *d;
 5014 
 5015         rc = priv_check(td, PRIV_DRIVER);
 5016         if (rc != 0)
 5017                 return (0);
 5018 
 5019         switch (cmd) {
 5020         case SIOCGIWNSTATS:
 5021                 d = (struct iwn_ioctl_data *) data;
 5022                 IWN_LOCK(sc);
 5023                 /* XXX validate permissions/memory/etc? */
 5024                 rc = copyout(&sc->last_stat, d->dst_addr, sizeof(struct iwn_stats));
 5025                 IWN_UNLOCK(sc);
 5026                 break;
 5027         case SIOCZIWNSTATS:
 5028                 IWN_LOCK(sc);
 5029                 memset(&sc->last_stat, 0, sizeof(struct iwn_stats));
 5030                 IWN_UNLOCK(sc);
 5031                 break;
 5032         default:
 5033                 rc = EINVAL;
 5034                 break;
 5035         }
 5036         return (rc);
 5037 }
 5038 
 5039 static int
 5040 iwn_ioctl(struct ieee80211com *ic, u_long cmd, void *data)
 5041 {
 5042 
 5043         return (ENOTTY);
 5044 }
 5045 
 5046 static void
 5047 iwn_parent(struct ieee80211com *ic)
 5048 {
 5049         struct iwn_softc *sc = ic->ic_softc;
 5050         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
 5051         int startall = 0, stop = 0;
 5052  
 5053         IWN_LOCK(sc);
 5054         if (ic->ic_nrunning > 0) {
 5055                 if (!(sc->sc_flags & IWN_FLAG_RUNNING)) {
 5056                         iwn_init_locked(sc);
 5057                         if (IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_RFKILL)
 5058                                 startall = 1;
 5059                         else
 5060                                 stop = 1;
 5061                 }
 5062         } else if (sc->sc_flags & IWN_FLAG_RUNNING)
 5063                 iwn_stop_locked(sc);
 5064         IWN_UNLOCK(sc);
 5065         if (startall)
 5066                 ieee80211_start_all(ic);
 5067         else if (vap != NULL && stop)
 5068                 ieee80211_stop(vap);
 5069 }
 5070 
 5071 /*
 5072  * Send a command to the firmware.
 5073  */
 5074 static int
 5075 iwn_cmd(struct iwn_softc *sc, int code, const void *buf, int size, int async)
 5076 {
 5077         struct iwn_tx_ring *ring;
 5078         struct iwn_tx_desc *desc;
 5079         struct iwn_tx_data *data;
 5080         struct iwn_tx_cmd *cmd;
 5081         struct mbuf *m;
 5082         bus_addr_t paddr;
 5083         int totlen, error;
 5084         int cmd_queue_num;
 5085 
 5086         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 5087 
 5088         if (async == 0)
 5089                 IWN_LOCK_ASSERT(sc);
 5090 
 5091         if (sc->sc_flags & IWN_FLAG_PAN_SUPPORT)
 5092                 cmd_queue_num = IWN_PAN_CMD_QUEUE;
 5093         else
 5094                 cmd_queue_num = IWN_CMD_QUEUE_NUM;
 5095 
 5096         ring = &sc->txq[cmd_queue_num];
 5097         desc = &ring->desc[ring->cur];
 5098         data = &ring->data[ring->cur];
 5099         totlen = 4 + size;
 5100 
 5101         if (size > sizeof cmd->data) {
 5102                 /* Command is too large to fit in a descriptor. */
 5103                 if (totlen > MCLBYTES)
 5104                         return EINVAL;
 5105                 m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE);
 5106                 if (m == NULL)
 5107                         return ENOMEM;
 5108                 cmd = mtod(m, struct iwn_tx_cmd *);
 5109                 error = bus_dmamap_load(ring->data_dmat, data->map, cmd,
 5110                     totlen, iwn_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
 5111                 if (error != 0) {
 5112                         m_freem(m);
 5113                         return error;
 5114                 }
 5115                 data->m = m;
 5116         } else {
 5117                 cmd = &ring->cmd[ring->cur];
 5118                 paddr = data->cmd_paddr;
 5119         }
 5120 
 5121         cmd->code = code;
 5122         cmd->flags = 0;
 5123         cmd->qid = ring->qid;
 5124         cmd->idx = ring->cur;
 5125         memcpy(cmd->data, buf, size);
 5126 
 5127         desc->nsegs = 1;
 5128         desc->segs[0].addr = htole32(IWN_LOADDR(paddr));
 5129         desc->segs[0].len  = htole16(IWN_HIADDR(paddr) | totlen << 4);
 5130 
 5131         DPRINTF(sc, IWN_DEBUG_CMD, "%s: %s (0x%x) flags %d qid %d idx %d\n",
 5132             __func__, iwn_intr_str(cmd->code), cmd->code,
 5133             cmd->flags, cmd->qid, cmd->idx);
 5134 
 5135         if (size > sizeof cmd->data) {
 5136                 bus_dmamap_sync(ring->data_dmat, data->map,
 5137                     BUS_DMASYNC_PREWRITE);
 5138         } else {
 5139                 bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
 5140                     BUS_DMASYNC_PREWRITE);
 5141         }
 5142         bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
 5143             BUS_DMASYNC_PREWRITE);
 5144 
 5145         /* Kick command ring. */
 5146         ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
 5147         IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
 5148 
 5149         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 5150 
 5151         return async ? 0 : msleep(desc, &sc->sc_mtx, PCATCH, "iwncmd", hz);
 5152 }
 5153 
 5154 static int
 5155 iwn4965_add_node(struct iwn_softc *sc, struct iwn_node_info *node, int async)
 5156 {
 5157         struct iwn4965_node_info hnode;
 5158         caddr_t src, dst;
 5159 
 5160         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5161 
 5162         /*
 5163          * We use the node structure for 5000 Series internally (it is
 5164          * a superset of the one for 4965AGN). We thus copy the common
 5165          * fields before sending the command.
 5166          */
 5167         src = (caddr_t)node;
 5168         dst = (caddr_t)&hnode;
 5169         memcpy(dst, src, 48);
 5170         /* Skip TSC, RX MIC and TX MIC fields from ``src''. */
 5171         memcpy(dst + 48, src + 72, 20);
 5172         return iwn_cmd(sc, IWN_CMD_ADD_NODE, &hnode, sizeof hnode, async);
 5173 }
 5174 
 5175 static int
 5176 iwn5000_add_node(struct iwn_softc *sc, struct iwn_node_info *node, int async)
 5177 {
 5178 
 5179         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5180 
 5181         /* Direct mapping. */
 5182         return iwn_cmd(sc, IWN_CMD_ADD_NODE, node, sizeof (*node), async);
 5183 }
 5184 
 5185 static int
 5186 iwn_set_link_quality(struct iwn_softc *sc, struct ieee80211_node *ni)
 5187 {
 5188         struct iwn_node *wn = (void *)ni;
 5189         struct ieee80211_rateset *rs;
 5190         struct iwn_cmd_link_quality linkq;
 5191         int i, rate, txrate;
 5192         int is_11n;
 5193 
 5194         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 5195 
 5196         memset(&linkq, 0, sizeof linkq);
 5197         linkq.id = wn->id;
 5198         linkq.antmsk_1stream = iwn_get_1stream_tx_antmask(sc);
 5199         linkq.antmsk_2stream = iwn_get_2stream_tx_antmask(sc);
 5200 
 5201         linkq.ampdu_max = 32;           /* XXX negotiated? */
 5202         linkq.ampdu_threshold = 3;
 5203         linkq.ampdu_limit = htole16(4000);      /* 4ms */
 5204 
 5205         DPRINTF(sc, IWN_DEBUG_XMIT,
 5206             "%s: 1stream antenna=0x%02x, 2stream antenna=0x%02x, ntxstreams=%d\n",
 5207             __func__,
 5208             linkq.antmsk_1stream,
 5209             linkq.antmsk_2stream,
 5210             sc->ntxchains);
 5211 
 5212         /*
 5213          * Are we using 11n rates? Ensure the channel is
 5214          * 11n _and_ we have some 11n rates, or don't
 5215          * try.
 5216          */
 5217         if (IEEE80211_IS_CHAN_HT(ni->ni_chan) && ni->ni_htrates.rs_nrates > 0) {
 5218                 rs = (struct ieee80211_rateset *) &ni->ni_htrates;
 5219                 is_11n = 1;
 5220         } else {
 5221                 rs = &ni->ni_rates;
 5222                 is_11n = 0;
 5223         }
 5224 
 5225         /* Start at highest available bit-rate. */
 5226         /*
 5227          * XXX this is all very dirty!
 5228          */
 5229         if (is_11n)
 5230                 txrate = ni->ni_htrates.rs_nrates - 1;
 5231         else
 5232                 txrate = rs->rs_nrates - 1;
 5233         for (i = 0; i < IWN_MAX_TX_RETRIES; i++) {
 5234                 uint32_t plcp;
 5235 
 5236                 /*
 5237                  * XXX TODO: ensure the last two slots are the two lowest
 5238                  * rate entries, just for now.
 5239                  */
 5240                 if (i == 14 || i == 15)
 5241                         txrate = 0;
 5242 
 5243                 if (is_11n)
 5244                         rate = IEEE80211_RATE_MCS | rs->rs_rates[txrate];
 5245                 else
 5246                         rate = IEEE80211_RV(rs->rs_rates[txrate]);
 5247 
 5248                 /* Do rate -> PLCP config mapping */
 5249                 plcp = iwn_rate_to_plcp(sc, ni, rate);
 5250                 linkq.retry[i] = plcp;
 5251                 DPRINTF(sc, IWN_DEBUG_XMIT,
 5252                     "%s: i=%d, txrate=%d, rate=0x%02x, plcp=0x%08x\n",
 5253                     __func__,
 5254                     i,
 5255                     txrate,
 5256                     rate,
 5257                     le32toh(plcp));
 5258 
 5259                 /*
 5260                  * The mimo field is an index into the table which
 5261                  * indicates the first index where it and subsequent entries
 5262                  * will not be using MIMO.
 5263                  *
 5264                  * Since we're filling linkq from 0..15 and we're filling
 5265                  * from the highest MCS rates to the lowest rates, if we
 5266                  * _are_ doing a dual-stream rate, set mimo to idx+1 (ie,
 5267                  * the next entry.)  That way if the next entry is a non-MIMO
 5268                  * entry, we're already pointing at it.
 5269                  */
 5270                 if ((le32toh(plcp) & IWN_RFLAG_MCS) &&
 5271                     IEEE80211_RV(le32toh(plcp)) > 7)
 5272                         linkq.mimo = i + 1;
 5273 
 5274                 /* Next retry at immediate lower bit-rate. */
 5275                 if (txrate > 0)
 5276                         txrate--;
 5277         }
 5278         /*
 5279          * If we reached the end of the list and indeed we hit
 5280          * all MIMO rates (eg 5300 doing MCS23-15) then yes,
 5281          * set mimo to 15.  Setting it to 16 panics the firmware.
 5282          */
 5283         if (linkq.mimo > 15)
 5284                 linkq.mimo = 15;
 5285 
 5286         DPRINTF(sc, IWN_DEBUG_XMIT, "%s: mimo = %d\n", __func__, linkq.mimo);
 5287 
 5288         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 5289 
 5290         return iwn_cmd(sc, IWN_CMD_LINK_QUALITY, &linkq, sizeof linkq, 1);
 5291 }
 5292 
 5293 /*
 5294  * Broadcast node is used to send group-addressed and management frames.
 5295  */
 5296 static int
 5297 iwn_add_broadcast_node(struct iwn_softc *sc, int async)
 5298 {
 5299         struct iwn_ops *ops = &sc->ops;
 5300         struct ieee80211com *ic = &sc->sc_ic;
 5301         struct iwn_node_info node;
 5302         struct iwn_cmd_link_quality linkq;
 5303         uint8_t txant;
 5304         int i, error;
 5305 
 5306         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 5307 
 5308         sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
 5309 
 5310         memset(&node, 0, sizeof node);
 5311         IEEE80211_ADDR_COPY(node.macaddr, ieee80211broadcastaddr);
 5312         node.id = sc->broadcast_id;
 5313         DPRINTF(sc, IWN_DEBUG_RESET, "%s: adding broadcast node\n", __func__);
 5314         if ((error = ops->add_node(sc, &node, async)) != 0)
 5315                 return error;
 5316 
 5317         /* Use the first valid TX antenna. */
 5318         txant = IWN_LSB(sc->txchainmask);
 5319 
 5320         memset(&linkq, 0, sizeof linkq);
 5321         linkq.id = sc->broadcast_id;
 5322         linkq.antmsk_1stream = iwn_get_1stream_tx_antmask(sc);
 5323         linkq.antmsk_2stream = iwn_get_2stream_tx_antmask(sc);
 5324         linkq.ampdu_max = 64;
 5325         linkq.ampdu_threshold = 3;
 5326         linkq.ampdu_limit = htole16(4000);      /* 4ms */
 5327 
 5328         /* Use lowest mandatory bit-rate. */
 5329         /* XXX rate table lookup? */
 5330         if (IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan))
 5331                 linkq.retry[0] = htole32(0xd);
 5332         else
 5333                 linkq.retry[0] = htole32(10 | IWN_RFLAG_CCK);
 5334         linkq.retry[0] |= htole32(IWN_RFLAG_ANT(txant));
 5335         /* Use same bit-rate for all TX retries. */
 5336         for (i = 1; i < IWN_MAX_TX_RETRIES; i++) {
 5337                 linkq.retry[i] = linkq.retry[0];
 5338         }
 5339 
 5340         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 5341 
 5342         return iwn_cmd(sc, IWN_CMD_LINK_QUALITY, &linkq, sizeof linkq, async);
 5343 }
 5344 
 5345 static int
 5346 iwn_updateedca(struct ieee80211com *ic)
 5347 {
 5348 #define IWN_EXP2(x)     ((1 << (x)) - 1)        /* CWmin = 2^ECWmin - 1 */
 5349         struct iwn_softc *sc = ic->ic_softc;
 5350         struct iwn_edca_params cmd;
 5351         int aci;
 5352 
 5353         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 5354 
 5355         memset(&cmd, 0, sizeof cmd);
 5356         cmd.flags = htole32(IWN_EDCA_UPDATE);
 5357 
 5358         IEEE80211_LOCK(ic);
 5359         for (aci = 0; aci < WME_NUM_AC; aci++) {
 5360                 const struct wmeParams *ac =
 5361                     &ic->ic_wme.wme_chanParams.cap_wmeParams[aci];
 5362                 cmd.ac[aci].aifsn = ac->wmep_aifsn;
 5363                 cmd.ac[aci].cwmin = htole16(IWN_EXP2(ac->wmep_logcwmin));
 5364                 cmd.ac[aci].cwmax = htole16(IWN_EXP2(ac->wmep_logcwmax));
 5365                 cmd.ac[aci].txoplimit =
 5366                     htole16(IEEE80211_TXOP_TO_US(ac->wmep_txopLimit));
 5367         }
 5368         IEEE80211_UNLOCK(ic);
 5369 
 5370         IWN_LOCK(sc);
 5371         (void)iwn_cmd(sc, IWN_CMD_EDCA_PARAMS, &cmd, sizeof cmd, 1);
 5372         IWN_UNLOCK(sc);
 5373 
 5374         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 5375 
 5376         return 0;
 5377 #undef IWN_EXP2
 5378 }
 5379 
 5380 static void
 5381 iwn_update_mcast(struct ieee80211com *ic)
 5382 {
 5383         /* Ignore */
 5384 }
 5385 
 5386 static void
 5387 iwn_set_led(struct iwn_softc *sc, uint8_t which, uint8_t off, uint8_t on)
 5388 {
 5389         struct iwn_cmd_led led;
 5390 
 5391         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5392 
 5393 #if 0
 5394         /* XXX don't set LEDs during scan? */
 5395         if (sc->sc_is_scanning)
 5396                 return;
 5397 #endif
 5398 
 5399         /* Clear microcode LED ownership. */
 5400         IWN_CLRBITS(sc, IWN_LED, IWN_LED_BSM_CTRL);
 5401 
 5402         led.which = which;
 5403         led.unit = htole32(10000);      /* on/off in unit of 100ms */
 5404         led.off = off;
 5405         led.on = on;
 5406         (void)iwn_cmd(sc, IWN_CMD_SET_LED, &led, sizeof led, 1);
 5407 }
 5408 
 5409 /*
 5410  * Set the critical temperature at which the firmware will stop the radio
 5411  * and notify us.
 5412  */
 5413 static int
 5414 iwn_set_critical_temp(struct iwn_softc *sc)
 5415 {
 5416         struct iwn_critical_temp crit;
 5417         int32_t temp;
 5418 
 5419         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5420 
 5421         IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CTEMP_STOP_RF);
 5422 
 5423         if (sc->hw_type == IWN_HW_REV_TYPE_5150)
 5424                 temp = (IWN_CTOK(110) - sc->temp_off) * -5;
 5425         else if (sc->hw_type == IWN_HW_REV_TYPE_4965)
 5426                 temp = IWN_CTOK(110);
 5427         else
 5428                 temp = 110;
 5429         memset(&crit, 0, sizeof crit);
 5430         crit.tempR = htole32(temp);
 5431         DPRINTF(sc, IWN_DEBUG_RESET, "setting critical temp to %d\n", temp);
 5432         return iwn_cmd(sc, IWN_CMD_SET_CRITICAL_TEMP, &crit, sizeof crit, 0);
 5433 }
 5434 
 5435 static int
 5436 iwn_set_timing(struct iwn_softc *sc, struct ieee80211_node *ni)
 5437 {
 5438         struct iwn_cmd_timing cmd;
 5439         uint64_t val, mod;
 5440 
 5441         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5442 
 5443         memset(&cmd, 0, sizeof cmd);
 5444         memcpy(&cmd.tstamp, ni->ni_tstamp.data, sizeof (uint64_t));
 5445         cmd.bintval = htole16(ni->ni_intval);
 5446         cmd.lintval = htole16(10);
 5447 
 5448         /* Compute remaining time until next beacon. */
 5449         val = (uint64_t)ni->ni_intval * IEEE80211_DUR_TU;
 5450         mod = le64toh(cmd.tstamp) % val;
 5451         cmd.binitval = htole32((uint32_t)(val - mod));
 5452 
 5453         DPRINTF(sc, IWN_DEBUG_RESET, "timing bintval=%u tstamp=%ju, init=%u\n",
 5454             ni->ni_intval, le64toh(cmd.tstamp), (uint32_t)(val - mod));
 5455 
 5456         return iwn_cmd(sc, IWN_CMD_TIMING, &cmd, sizeof cmd, 1);
 5457 }
 5458 
 5459 static void
 5460 iwn4965_power_calibration(struct iwn_softc *sc, int temp)
 5461 {
 5462         struct ieee80211com *ic = &sc->sc_ic;
 5463 
 5464         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5465 
 5466         /* Adjust TX power if need be (delta >= 3 degC). */
 5467         DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: temperature %d->%d\n",
 5468             __func__, sc->temp, temp);
 5469         if (abs(temp - sc->temp) >= 3) {
 5470                 /* Record temperature of last calibration. */
 5471                 sc->temp = temp;
 5472                 (void)iwn4965_set_txpower(sc, ic->ic_bsschan, 1);
 5473         }
 5474 }
 5475 
 5476 /*
 5477  * Set TX power for current channel (each rate has its own power settings).
 5478  * This function takes into account the regulatory information from EEPROM,
 5479  * the current temperature and the current voltage.
 5480  */
 5481 static int
 5482 iwn4965_set_txpower(struct iwn_softc *sc, struct ieee80211_channel *ch,
 5483     int async)
 5484 {
 5485 /* Fixed-point arithmetic division using a n-bit fractional part. */
 5486 #define fdivround(a, b, n)      \
 5487         ((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
 5488 /* Linear interpolation. */
 5489 #define interpolate(x, x1, y1, x2, y2, n)       \
 5490         ((y1) + fdivround(((int)(x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
 5491 
 5492         static const int tdiv[IWN_NATTEN_GROUPS] = { 9, 8, 8, 8, 6 };
 5493         struct iwn_ucode_info *uc = &sc->ucode_info;
 5494         struct iwn4965_cmd_txpower cmd;
 5495         struct iwn4965_eeprom_chan_samples *chans;
 5496         const uint8_t *rf_gain, *dsp_gain;
 5497         int32_t vdiff, tdiff;
 5498         int i, c, grp, maxpwr;
 5499         uint8_t chan;
 5500 
 5501         sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
 5502         /* Retrieve current channel from last RXON. */
 5503         chan = sc->rxon->chan;
 5504         DPRINTF(sc, IWN_DEBUG_RESET, "setting TX power for channel %d\n",
 5505             chan);
 5506 
 5507         memset(&cmd, 0, sizeof cmd);
 5508         cmd.band = IEEE80211_IS_CHAN_5GHZ(ch) ? 0 : 1;
 5509         cmd.chan = chan;
 5510 
 5511         if (IEEE80211_IS_CHAN_5GHZ(ch)) {
 5512                 maxpwr   = sc->maxpwr5GHz;
 5513                 rf_gain  = iwn4965_rf_gain_5ghz;
 5514                 dsp_gain = iwn4965_dsp_gain_5ghz;
 5515         } else {
 5516                 maxpwr   = sc->maxpwr2GHz;
 5517                 rf_gain  = iwn4965_rf_gain_2ghz;
 5518                 dsp_gain = iwn4965_dsp_gain_2ghz;
 5519         }
 5520 
 5521         /* Compute voltage compensation. */
 5522         vdiff = ((int32_t)le32toh(uc->volt) - sc->eeprom_voltage) / 7;
 5523         if (vdiff > 0)
 5524                 vdiff *= 2;
 5525         if (abs(vdiff) > 2)
 5526                 vdiff = 0;
 5527         DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
 5528             "%s: voltage compensation=%d (UCODE=%d, EEPROM=%d)\n",
 5529             __func__, vdiff, le32toh(uc->volt), sc->eeprom_voltage);
 5530 
 5531         /* Get channel attenuation group. */
 5532         if (chan <= 20)         /* 1-20 */
 5533                 grp = 4;
 5534         else if (chan <= 43)    /* 34-43 */
 5535                 grp = 0;
 5536         else if (chan <= 70)    /* 44-70 */
 5537                 grp = 1;
 5538         else if (chan <= 124)   /* 71-124 */
 5539                 grp = 2;
 5540         else                    /* 125-200 */
 5541                 grp = 3;
 5542         DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
 5543             "%s: chan %d, attenuation group=%d\n", __func__, chan, grp);
 5544 
 5545         /* Get channel sub-band. */
 5546         for (i = 0; i < IWN_NBANDS; i++)
 5547                 if (sc->bands[i].lo != 0 &&
 5548                     sc->bands[i].lo <= chan && chan <= sc->bands[i].hi)
 5549                         break;
 5550         if (i == IWN_NBANDS)    /* Can't happen in real-life. */
 5551                 return EINVAL;
 5552         chans = sc->bands[i].chans;
 5553         DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
 5554             "%s: chan %d sub-band=%d\n", __func__, chan, i);
 5555 
 5556         for (c = 0; c < 2; c++) {
 5557                 uint8_t power, gain, temp;
 5558                 int maxchpwr, pwr, ridx, idx;
 5559 
 5560                 power = interpolate(chan,
 5561                     chans[0].num, chans[0].samples[c][1].power,
 5562                     chans[1].num, chans[1].samples[c][1].power, 1);
 5563                 gain  = interpolate(chan,
 5564                     chans[0].num, chans[0].samples[c][1].gain,
 5565                     chans[1].num, chans[1].samples[c][1].gain, 1);
 5566                 temp  = interpolate(chan,
 5567                     chans[0].num, chans[0].samples[c][1].temp,
 5568                     chans[1].num, chans[1].samples[c][1].temp, 1);
 5569                 DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
 5570                     "%s: Tx chain %d: power=%d gain=%d temp=%d\n",
 5571                     __func__, c, power, gain, temp);
 5572 
 5573                 /* Compute temperature compensation. */
 5574                 tdiff = ((sc->temp - temp) * 2) / tdiv[grp];
 5575                 DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
 5576                     "%s: temperature compensation=%d (current=%d, EEPROM=%d)\n",
 5577                     __func__, tdiff, sc->temp, temp);
 5578 
 5579                 for (ridx = 0; ridx <= IWN_RIDX_MAX; ridx++) {
 5580                         /* Convert dBm to half-dBm. */
 5581                         maxchpwr = sc->maxpwr[chan] * 2;
 5582                         if ((ridx / 8) & 1)
 5583                                 maxchpwr -= 6;  /* MIMO 2T: -3dB */
 5584 
 5585                         pwr = maxpwr;
 5586 
 5587                         /* Adjust TX power based on rate. */
 5588                         if ((ridx % 8) == 5)
 5589                                 pwr -= 15;      /* OFDM48: -7.5dB */
 5590                         else if ((ridx % 8) == 6)
 5591                                 pwr -= 17;      /* OFDM54: -8.5dB */
 5592                         else if ((ridx % 8) == 7)
 5593                                 pwr -= 20;      /* OFDM60: -10dB */
 5594                         else
 5595                                 pwr -= 10;      /* Others: -5dB */
 5596 
 5597                         /* Do not exceed channel max TX power. */
 5598                         if (pwr > maxchpwr)
 5599                                 pwr = maxchpwr;
 5600 
 5601                         idx = gain - (pwr - power) - tdiff - vdiff;
 5602                         if ((ridx / 8) & 1)     /* MIMO */
 5603                                 idx += (int32_t)le32toh(uc->atten[grp][c]);
 5604 
 5605                         if (cmd.band == 0)
 5606                                 idx += 9;       /* 5GHz */
 5607                         if (ridx == IWN_RIDX_MAX)
 5608                                 idx += 5;       /* CCK */
 5609 
 5610                         /* Make sure idx stays in a valid range. */
 5611                         if (idx < 0)
 5612                                 idx = 0;
 5613                         else if (idx > IWN4965_MAX_PWR_INDEX)
 5614                                 idx = IWN4965_MAX_PWR_INDEX;
 5615 
 5616                         DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
 5617                             "%s: Tx chain %d, rate idx %d: power=%d\n",
 5618                             __func__, c, ridx, idx);
 5619                         cmd.power[ridx].rf_gain[c] = rf_gain[idx];
 5620                         cmd.power[ridx].dsp_gain[c] = dsp_gain[idx];
 5621                 }
 5622         }
 5623 
 5624         DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
 5625             "%s: set tx power for chan %d\n", __func__, chan);
 5626         return iwn_cmd(sc, IWN_CMD_TXPOWER, &cmd, sizeof cmd, async);
 5627 
 5628 #undef interpolate
 5629 #undef fdivround
 5630 }
 5631 
 5632 static int
 5633 iwn5000_set_txpower(struct iwn_softc *sc, struct ieee80211_channel *ch,
 5634     int async)
 5635 {
 5636         struct iwn5000_cmd_txpower cmd;
 5637         int cmdid;
 5638 
 5639         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5640 
 5641         /*
 5642          * TX power calibration is handled automatically by the firmware
 5643          * for 5000 Series.
 5644          */
 5645         memset(&cmd, 0, sizeof cmd);
 5646         cmd.global_limit = 2 * IWN5000_TXPOWER_MAX_DBM; /* 16 dBm */
 5647         cmd.flags = IWN5000_TXPOWER_NO_CLOSED;
 5648         cmd.srv_limit = IWN5000_TXPOWER_AUTO;
 5649         DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_XMIT,
 5650             "%s: setting TX power; rev=%d\n",
 5651             __func__,
 5652             IWN_UCODE_API(sc->ucode_rev));
 5653         if (IWN_UCODE_API(sc->ucode_rev) == 1)
 5654                 cmdid = IWN_CMD_TXPOWER_DBM_V1;
 5655         else
 5656                 cmdid = IWN_CMD_TXPOWER_DBM;
 5657         return iwn_cmd(sc, cmdid, &cmd, sizeof cmd, async);
 5658 }
 5659 
 5660 /*
 5661  * Retrieve the maximum RSSI (in dBm) among receivers.
 5662  */
 5663 static int
 5664 iwn4965_get_rssi(struct iwn_softc *sc, struct iwn_rx_stat *stat)
 5665 {
 5666         struct iwn4965_rx_phystat *phy = (void *)stat->phybuf;
 5667         uint8_t mask, agc;
 5668         int rssi;
 5669 
 5670         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5671 
 5672         mask = (le16toh(phy->antenna) >> 4) & IWN_ANT_ABC;
 5673         agc  = (le16toh(phy->agc) >> 7) & 0x7f;
 5674 
 5675         rssi = 0;
 5676         if (mask & IWN_ANT_A)
 5677                 rssi = MAX(rssi, phy->rssi[0]);
 5678         if (mask & IWN_ANT_B)
 5679                 rssi = MAX(rssi, phy->rssi[2]);
 5680         if (mask & IWN_ANT_C)
 5681                 rssi = MAX(rssi, phy->rssi[4]);
 5682 
 5683         DPRINTF(sc, IWN_DEBUG_RECV,
 5684             "%s: agc %d mask 0x%x rssi %d %d %d result %d\n", __func__, agc,
 5685             mask, phy->rssi[0], phy->rssi[2], phy->rssi[4],
 5686             rssi - agc - IWN_RSSI_TO_DBM);
 5687         return rssi - agc - IWN_RSSI_TO_DBM;
 5688 }
 5689 
 5690 static int
 5691 iwn5000_get_rssi(struct iwn_softc *sc, struct iwn_rx_stat *stat)
 5692 {
 5693         struct iwn5000_rx_phystat *phy = (void *)stat->phybuf;
 5694         uint8_t agc;
 5695         int rssi;
 5696 
 5697         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5698 
 5699         agc = (le32toh(phy->agc) >> 9) & 0x7f;
 5700 
 5701         rssi = MAX(le16toh(phy->rssi[0]) & 0xff,
 5702                    le16toh(phy->rssi[1]) & 0xff);
 5703         rssi = MAX(le16toh(phy->rssi[2]) & 0xff, rssi);
 5704 
 5705         DPRINTF(sc, IWN_DEBUG_RECV,
 5706             "%s: agc %d rssi %d %d %d result %d\n", __func__, agc,
 5707             phy->rssi[0], phy->rssi[1], phy->rssi[2],
 5708             rssi - agc - IWN_RSSI_TO_DBM);
 5709         return rssi - agc - IWN_RSSI_TO_DBM;
 5710 }
 5711 
 5712 /*
 5713  * Retrieve the average noise (in dBm) among receivers.
 5714  */
 5715 static int
 5716 iwn_get_noise(const struct iwn_rx_general_stats *stats)
 5717 {
 5718         int i, total, nbant, noise;
 5719 
 5720         total = nbant = 0;
 5721         for (i = 0; i < 3; i++) {
 5722                 if ((noise = le32toh(stats->noise[i]) & 0xff) == 0)
 5723                         continue;
 5724                 total += noise;
 5725                 nbant++;
 5726         }
 5727         /* There should be at least one antenna but check anyway. */
 5728         return (nbant == 0) ? -127 : (total / nbant) - 107;
 5729 }
 5730 
 5731 /*
 5732  * Compute temperature (in degC) from last received statistics.
 5733  */
 5734 static int
 5735 iwn4965_get_temperature(struct iwn_softc *sc)
 5736 {
 5737         struct iwn_ucode_info *uc = &sc->ucode_info;
 5738         int32_t r1, r2, r3, r4, temp;
 5739 
 5740         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5741 
 5742         r1 = le32toh(uc->temp[0].chan20MHz);
 5743         r2 = le32toh(uc->temp[1].chan20MHz);
 5744         r3 = le32toh(uc->temp[2].chan20MHz);
 5745         r4 = le32toh(sc->rawtemp);
 5746 
 5747         if (r1 == r3)   /* Prevents division by 0 (should not happen). */
 5748                 return 0;
 5749 
 5750         /* Sign-extend 23-bit R4 value to 32-bit. */
 5751         r4 = ((r4 & 0xffffff) ^ 0x800000) - 0x800000;
 5752         /* Compute temperature in Kelvin. */
 5753         temp = (259 * (r4 - r2)) / (r3 - r1);
 5754         temp = (temp * 97) / 100 + 8;
 5755 
 5756         DPRINTF(sc, IWN_DEBUG_ANY, "temperature %dK/%dC\n", temp,
 5757             IWN_KTOC(temp));
 5758         return IWN_KTOC(temp);
 5759 }
 5760 
 5761 static int
 5762 iwn5000_get_temperature(struct iwn_softc *sc)
 5763 {
 5764         int32_t temp;
 5765 
 5766         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5767 
 5768         /*
 5769          * Temperature is not used by the driver for 5000 Series because
 5770          * TX power calibration is handled by firmware.
 5771          */
 5772         temp = le32toh(sc->rawtemp);
 5773         if (sc->hw_type == IWN_HW_REV_TYPE_5150) {
 5774                 temp = (temp / -5) + sc->temp_off;
 5775                 temp = IWN_KTOC(temp);
 5776         }
 5777         return temp;
 5778 }
 5779 
 5780 /*
 5781  * Initialize sensitivity calibration state machine.
 5782  */
 5783 static int
 5784 iwn_init_sensitivity(struct iwn_softc *sc)
 5785 {
 5786         struct iwn_ops *ops = &sc->ops;
 5787         struct iwn_calib_state *calib = &sc->calib;
 5788         uint32_t flags;
 5789         int error;
 5790 
 5791         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5792 
 5793         /* Reset calibration state machine. */
 5794         memset(calib, 0, sizeof (*calib));
 5795         calib->state = IWN_CALIB_STATE_INIT;
 5796         calib->cck_state = IWN_CCK_STATE_HIFA;
 5797         /* Set initial correlation values. */
 5798         calib->ofdm_x1     = sc->limits->min_ofdm_x1;
 5799         calib->ofdm_mrc_x1 = sc->limits->min_ofdm_mrc_x1;
 5800         calib->ofdm_x4     = sc->limits->min_ofdm_x4;
 5801         calib->ofdm_mrc_x4 = sc->limits->min_ofdm_mrc_x4;
 5802         calib->cck_x4      = 125;
 5803         calib->cck_mrc_x4  = sc->limits->min_cck_mrc_x4;
 5804         calib->energy_cck  = sc->limits->energy_cck;
 5805 
 5806         /* Write initial sensitivity. */
 5807         if ((error = iwn_send_sensitivity(sc)) != 0)
 5808                 return error;
 5809 
 5810         /* Write initial gains. */
 5811         if ((error = ops->init_gains(sc)) != 0)
 5812                 return error;
 5813 
 5814         /* Request statistics at each beacon interval. */
 5815         flags = 0;
 5816         DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: sending request for statistics\n",
 5817             __func__);
 5818         return iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags, sizeof flags, 1);
 5819 }
 5820 
 5821 /*
 5822  * Collect noise and RSSI statistics for the first 20 beacons received
 5823  * after association and use them to determine connected antennas and
 5824  * to set differential gains.
 5825  */
 5826 static void
 5827 iwn_collect_noise(struct iwn_softc *sc,
 5828     const struct iwn_rx_general_stats *stats)
 5829 {
 5830         struct iwn_ops *ops = &sc->ops;
 5831         struct iwn_calib_state *calib = &sc->calib;
 5832         struct ieee80211com *ic = &sc->sc_ic;
 5833         uint32_t val;
 5834         int i;
 5835 
 5836         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 5837 
 5838         /* Accumulate RSSI and noise for all 3 antennas. */
 5839         for (i = 0; i < 3; i++) {
 5840                 calib->rssi[i] += le32toh(stats->rssi[i]) & 0xff;
 5841                 calib->noise[i] += le32toh(stats->noise[i]) & 0xff;
 5842         }
 5843         /* NB: We update differential gains only once after 20 beacons. */
 5844         if (++calib->nbeacons < 20)
 5845                 return;
 5846 
 5847         /* Determine highest average RSSI. */
 5848         val = MAX(calib->rssi[0], calib->rssi[1]);
 5849         val = MAX(calib->rssi[2], val);
 5850 
 5851         /* Determine which antennas are connected. */
 5852         sc->chainmask = sc->rxchainmask;
 5853         for (i = 0; i < 3; i++)
 5854                 if (val - calib->rssi[i] > 15 * 20)
 5855                         sc->chainmask &= ~(1 << i);
 5856         DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_XMIT,
 5857             "%s: RX chains mask: theoretical=0x%x, actual=0x%x\n",
 5858             __func__, sc->rxchainmask, sc->chainmask);
 5859 
 5860         /* If none of the TX antennas are connected, keep at least one. */
 5861         if ((sc->chainmask & sc->txchainmask) == 0)
 5862                 sc->chainmask |= IWN_LSB(sc->txchainmask);
 5863 
 5864         (void)ops->set_gains(sc);
 5865         calib->state = IWN_CALIB_STATE_RUN;
 5866 
 5867 #ifdef notyet
 5868         /* XXX Disable RX chains with no antennas connected. */
 5869         sc->rxon->rxchain = htole16(IWN_RXCHAIN_SEL(sc->chainmask));
 5870         if (sc->sc_is_scanning)
 5871                 device_printf(sc->sc_dev,
 5872                     "%s: is_scanning set, before RXON\n",
 5873                     __func__);
 5874         (void)iwn_cmd(sc, IWN_CMD_RXON, sc->rxon, sc->rxonsz, 1);
 5875 #endif
 5876 
 5877         /* Enable power-saving mode if requested by user. */
 5878         if (ic->ic_flags & IEEE80211_F_PMGTON)
 5879                 (void)iwn_set_pslevel(sc, 0, 3, 1);
 5880 
 5881         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 5882 
 5883 }
 5884 
 5885 static int
 5886 iwn4965_init_gains(struct iwn_softc *sc)
 5887 {
 5888         struct iwn_phy_calib_gain cmd;
 5889 
 5890         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5891 
 5892         memset(&cmd, 0, sizeof cmd);
 5893         cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN;
 5894         /* Differential gains initially set to 0 for all 3 antennas. */
 5895         DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 5896             "%s: setting initial differential gains\n", __func__);
 5897         return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
 5898 }
 5899 
 5900 static int
 5901 iwn5000_init_gains(struct iwn_softc *sc)
 5902 {
 5903         struct iwn_phy_calib cmd;
 5904 
 5905         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5906 
 5907         memset(&cmd, 0, sizeof cmd);
 5908         cmd.code = sc->reset_noise_gain;
 5909         cmd.ngroups = 1;
 5910         cmd.isvalid = 1;
 5911         DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 5912             "%s: setting initial differential gains\n", __func__);
 5913         return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
 5914 }
 5915 
 5916 static int
 5917 iwn4965_set_gains(struct iwn_softc *sc)
 5918 {
 5919         struct iwn_calib_state *calib = &sc->calib;
 5920         struct iwn_phy_calib_gain cmd;
 5921         int i, delta, noise;
 5922 
 5923         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5924 
 5925         /* Get minimal noise among connected antennas. */
 5926         noise = INT_MAX;        /* NB: There's at least one antenna. */
 5927         for (i = 0; i < 3; i++)
 5928                 if (sc->chainmask & (1 << i))
 5929                         noise = MIN(calib->noise[i], noise);
 5930 
 5931         memset(&cmd, 0, sizeof cmd);
 5932         cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN;
 5933         /* Set differential gains for connected antennas. */
 5934         for (i = 0; i < 3; i++) {
 5935                 if (sc->chainmask & (1 << i)) {
 5936                         /* Compute attenuation (in unit of 1.5dB). */
 5937                         delta = (noise - (int32_t)calib->noise[i]) / 30;
 5938                         /* NB: delta <= 0 */
 5939                         /* Limit to [-4.5dB,0]. */
 5940                         cmd.gain[i] = MIN(abs(delta), 3);
 5941                         if (delta < 0)
 5942                                 cmd.gain[i] |= 1 << 2;  /* sign bit */
 5943                 }
 5944         }
 5945         DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 5946             "setting differential gains Ant A/B/C: %x/%x/%x (%x)\n",
 5947             cmd.gain[0], cmd.gain[1], cmd.gain[2], sc->chainmask);
 5948         return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
 5949 }
 5950 
 5951 static int
 5952 iwn5000_set_gains(struct iwn_softc *sc)
 5953 {
 5954         struct iwn_calib_state *calib = &sc->calib;
 5955         struct iwn_phy_calib_gain cmd;
 5956         int i, ant, div, delta;
 5957 
 5958         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5959 
 5960         /* We collected 20 beacons and !=6050 need a 1.5 factor. */
 5961         div = (sc->hw_type == IWN_HW_REV_TYPE_6050) ? 20 : 30;
 5962 
 5963         memset(&cmd, 0, sizeof cmd);
 5964         cmd.code = sc->noise_gain;
 5965         cmd.ngroups = 1;
 5966         cmd.isvalid = 1;
 5967         /* Get first available RX antenna as referential. */
 5968         ant = IWN_LSB(sc->rxchainmask);
 5969         /* Set differential gains for other antennas. */
 5970         for (i = ant + 1; i < 3; i++) {
 5971                 if (sc->chainmask & (1 << i)) {
 5972                         /* The delta is relative to antenna "ant". */
 5973                         delta = ((int32_t)calib->noise[ant] -
 5974                             (int32_t)calib->noise[i]) / div;
 5975                         /* Limit to [-4.5dB,+4.5dB]. */
 5976                         cmd.gain[i - 1] = MIN(abs(delta), 3);
 5977                         if (delta < 0)
 5978                                 cmd.gain[i - 1] |= 1 << 2;      /* sign bit */
 5979                 }
 5980         }
 5981         DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_XMIT,
 5982             "setting differential gains Ant B/C: %x/%x (%x)\n",
 5983             cmd.gain[0], cmd.gain[1], sc->chainmask);
 5984         return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
 5985 }
 5986 
 5987 /*
 5988  * Tune RF RX sensitivity based on the number of false alarms detected
 5989  * during the last beacon period.
 5990  */
 5991 static void
 5992 iwn_tune_sensitivity(struct iwn_softc *sc, const struct iwn_rx_stats *stats)
 5993 {
 5994 #define inc(val, inc, max)                      \
 5995         if ((val) < (max)) {                    \
 5996                 if ((val) < (max) - (inc))      \
 5997                         (val) += (inc);         \
 5998                 else                            \
 5999                         (val) = (max);          \
 6000                 needs_update = 1;               \
 6001         }
 6002 #define dec(val, dec, min)                      \
 6003         if ((val) > (min)) {                    \
 6004                 if ((val) > (min) + (dec))      \
 6005                         (val) -= (dec);         \
 6006                 else                            \
 6007                         (val) = (min);          \
 6008                 needs_update = 1;               \
 6009         }
 6010 
 6011         const struct iwn_sensitivity_limits *limits = sc->limits;
 6012         struct iwn_calib_state *calib = &sc->calib;
 6013         uint32_t val, rxena, fa;
 6014         uint32_t energy[3], energy_min;
 6015         uint8_t noise[3], noise_ref;
 6016         int i, needs_update = 0;
 6017 
 6018         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 6019 
 6020         /* Check that we've been enabled long enough. */
 6021         if ((rxena = le32toh(stats->general.load)) == 0){
 6022                 DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end not so long\n", __func__);
 6023                 return;
 6024         }
 6025 
 6026         /* Compute number of false alarms since last call for OFDM. */
 6027         fa  = le32toh(stats->ofdm.bad_plcp) - calib->bad_plcp_ofdm;
 6028         fa += le32toh(stats->ofdm.fa) - calib->fa_ofdm;
 6029         fa *= 200 * IEEE80211_DUR_TU;   /* 200TU */
 6030 
 6031         if (fa > 50 * rxena) {
 6032                 /* High false alarm count, decrease sensitivity. */
 6033                 DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 6034                     "%s: OFDM high false alarm count: %u\n", __func__, fa);
 6035                 inc(calib->ofdm_x1,     1, limits->max_ofdm_x1);
 6036                 inc(calib->ofdm_mrc_x1, 1, limits->max_ofdm_mrc_x1);
 6037                 inc(calib->ofdm_x4,     1, limits->max_ofdm_x4);
 6038                 inc(calib->ofdm_mrc_x4, 1, limits->max_ofdm_mrc_x4);
 6039 
 6040         } else if (fa < 5 * rxena) {
 6041                 /* Low false alarm count, increase sensitivity. */
 6042                 DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 6043                     "%s: OFDM low false alarm count: %u\n", __func__, fa);
 6044                 dec(calib->ofdm_x1,     1, limits->min_ofdm_x1);
 6045                 dec(calib->ofdm_mrc_x1, 1, limits->min_ofdm_mrc_x1);
 6046                 dec(calib->ofdm_x4,     1, limits->min_ofdm_x4);
 6047                 dec(calib->ofdm_mrc_x4, 1, limits->min_ofdm_mrc_x4);
 6048         }
 6049 
 6050         /* Compute maximum noise among 3 receivers. */
 6051         for (i = 0; i < 3; i++)
 6052                 noise[i] = (le32toh(stats->general.noise[i]) >> 8) & 0xff;
 6053         val = MAX(noise[0], noise[1]);
 6054         val = MAX(noise[2], val);
 6055         /* Insert it into our samples table. */
 6056         calib->noise_samples[calib->cur_noise_sample] = val;
 6057         calib->cur_noise_sample = (calib->cur_noise_sample + 1) % 20;
 6058 
 6059         /* Compute maximum noise among last 20 samples. */
 6060         noise_ref = calib->noise_samples[0];
 6061         for (i = 1; i < 20; i++)
 6062                 noise_ref = MAX(noise_ref, calib->noise_samples[i]);
 6063 
 6064         /* Compute maximum energy among 3 receivers. */
 6065         for (i = 0; i < 3; i++)
 6066                 energy[i] = le32toh(stats->general.energy[i]);
 6067         val = MIN(energy[0], energy[1]);
 6068         val = MIN(energy[2], val);
 6069         /* Insert it into our samples table. */
 6070         calib->energy_samples[calib->cur_energy_sample] = val;
 6071         calib->cur_energy_sample = (calib->cur_energy_sample + 1) % 10;
 6072 
 6073         /* Compute minimum energy among last 10 samples. */
 6074         energy_min = calib->energy_samples[0];
 6075         for (i = 1; i < 10; i++)
 6076                 energy_min = MAX(energy_min, calib->energy_samples[i]);
 6077         energy_min += 6;
 6078 
 6079         /* Compute number of false alarms since last call for CCK. */
 6080         fa  = le32toh(stats->cck.bad_plcp) - calib->bad_plcp_cck;
 6081         fa += le32toh(stats->cck.fa) - calib->fa_cck;
 6082         fa *= 200 * IEEE80211_DUR_TU;   /* 200TU */
 6083 
 6084         if (fa > 50 * rxena) {
 6085                 /* High false alarm count, decrease sensitivity. */
 6086                 DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 6087                     "%s: CCK high false alarm count: %u\n", __func__, fa);
 6088                 calib->cck_state = IWN_CCK_STATE_HIFA;
 6089                 calib->low_fa = 0;
 6090 
 6091                 if (calib->cck_x4 > 160) {
 6092                         calib->noise_ref = noise_ref;
 6093                         if (calib->energy_cck > 2)
 6094                                 dec(calib->energy_cck, 2, energy_min);
 6095                 }
 6096                 if (calib->cck_x4 < 160) {
 6097                         calib->cck_x4 = 161;
 6098                         needs_update = 1;
 6099                 } else
 6100                         inc(calib->cck_x4, 3, limits->max_cck_x4);
 6101 
 6102                 inc(calib->cck_mrc_x4, 3, limits->max_cck_mrc_x4);
 6103 
 6104         } else if (fa < 5 * rxena) {
 6105                 /* Low false alarm count, increase sensitivity. */
 6106                 DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 6107                     "%s: CCK low false alarm count: %u\n", __func__, fa);
 6108                 calib->cck_state = IWN_CCK_STATE_LOFA;
 6109                 calib->low_fa++;
 6110 
 6111                 if (calib->cck_state != IWN_CCK_STATE_INIT &&
 6112                     (((int32_t)calib->noise_ref - (int32_t)noise_ref) > 2 ||
 6113                      calib->low_fa > 100)) {
 6114                         inc(calib->energy_cck, 2, limits->min_energy_cck);
 6115                         dec(calib->cck_x4,     3, limits->min_cck_x4);
 6116                         dec(calib->cck_mrc_x4, 3, limits->min_cck_mrc_x4);
 6117                 }
 6118         } else {
 6119                 /* Not worth to increase or decrease sensitivity. */
 6120                 DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 6121                     "%s: CCK normal false alarm count: %u\n", __func__, fa);
 6122                 calib->low_fa = 0;
 6123                 calib->noise_ref = noise_ref;
 6124 
 6125                 if (calib->cck_state == IWN_CCK_STATE_HIFA) {
 6126                         /* Previous interval had many false alarms. */
 6127                         dec(calib->energy_cck, 8, energy_min);
 6128                 }
 6129                 calib->cck_state = IWN_CCK_STATE_INIT;
 6130         }
 6131 
 6132         if (needs_update)
 6133                 (void)iwn_send_sensitivity(sc);
 6134 
 6135         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 6136 
 6137 #undef dec
 6138 #undef inc
 6139 }
 6140 
 6141 static int
 6142 iwn_send_sensitivity(struct iwn_softc *sc)
 6143 {
 6144         struct iwn_calib_state *calib = &sc->calib;
 6145         struct iwn_enhanced_sensitivity_cmd cmd;
 6146         int len;
 6147 
 6148         memset(&cmd, 0, sizeof cmd);
 6149         len = sizeof (struct iwn_sensitivity_cmd);
 6150         cmd.which = IWN_SENSITIVITY_WORKTBL;
 6151         /* OFDM modulation. */
 6152         cmd.corr_ofdm_x1       = htole16(calib->ofdm_x1);
 6153         cmd.corr_ofdm_mrc_x1   = htole16(calib->ofdm_mrc_x1);
 6154         cmd.corr_ofdm_x4       = htole16(calib->ofdm_x4);
 6155         cmd.corr_ofdm_mrc_x4   = htole16(calib->ofdm_mrc_x4);
 6156         cmd.energy_ofdm        = htole16(sc->limits->energy_ofdm);
 6157         cmd.energy_ofdm_th     = htole16(62);
 6158         /* CCK modulation. */
 6159         cmd.corr_cck_x4        = htole16(calib->cck_x4);
 6160         cmd.corr_cck_mrc_x4    = htole16(calib->cck_mrc_x4);
 6161         cmd.energy_cck         = htole16(calib->energy_cck);
 6162         /* Barker modulation: use default values. */
 6163         cmd.corr_barker        = htole16(190);
 6164         cmd.corr_barker_mrc    = htole16(sc->limits->barker_mrc);
 6165 
 6166         DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 6167             "%s: set sensitivity %d/%d/%d/%d/%d/%d/%d\n", __func__,
 6168             calib->ofdm_x1, calib->ofdm_mrc_x1, calib->ofdm_x4,
 6169             calib->ofdm_mrc_x4, calib->cck_x4,
 6170             calib->cck_mrc_x4, calib->energy_cck);
 6171 
 6172         if (!(sc->sc_flags & IWN_FLAG_ENH_SENS))
 6173                 goto send;
 6174         /* Enhanced sensitivity settings. */
 6175         len = sizeof (struct iwn_enhanced_sensitivity_cmd);
 6176         cmd.ofdm_det_slope_mrc = htole16(668);
 6177         cmd.ofdm_det_icept_mrc = htole16(4);
 6178         cmd.ofdm_det_slope     = htole16(486);
 6179         cmd.ofdm_det_icept     = htole16(37);
 6180         cmd.cck_det_slope_mrc  = htole16(853);
 6181         cmd.cck_det_icept_mrc  = htole16(4);
 6182         cmd.cck_det_slope      = htole16(476);
 6183         cmd.cck_det_icept      = htole16(99);
 6184 send:
 6185         return iwn_cmd(sc, IWN_CMD_SET_SENSITIVITY, &cmd, len, 1);
 6186 }
 6187 
 6188 /*
 6189  * Look at the increase of PLCP errors over time; if it exceeds
 6190  * a programmed threshold then trigger an RF retune.
 6191  */
 6192 static void
 6193 iwn_check_rx_recovery(struct iwn_softc *sc, struct iwn_stats *rs)
 6194 {
 6195         int32_t delta_ofdm, delta_ht, delta_cck;
 6196         struct iwn_calib_state *calib = &sc->calib;
 6197         int delta_ticks, cur_ticks;
 6198         int delta_msec;
 6199         int thresh;
 6200 
 6201         /*
 6202          * Calculate the difference between the current and
 6203          * previous statistics.
 6204          */
 6205         delta_cck = le32toh(rs->rx.cck.bad_plcp) - calib->bad_plcp_cck;
 6206         delta_ofdm = le32toh(rs->rx.ofdm.bad_plcp) - calib->bad_plcp_ofdm;
 6207         delta_ht = le32toh(rs->rx.ht.bad_plcp) - calib->bad_plcp_ht;
 6208 
 6209         /*
 6210          * Calculate the delta in time between successive statistics
 6211          * messages.  Yes, it can roll over; so we make sure that
 6212          * this doesn't happen.
 6213          *
 6214          * XXX go figure out what to do about rollover
 6215          * XXX go figure out what to do if ticks rolls over to -ve instead!
 6216          * XXX go stab signed integer overflow undefined-ness in the face.
 6217          */
 6218         cur_ticks = ticks;
 6219         delta_ticks = cur_ticks - sc->last_calib_ticks;
 6220 
 6221         /*
 6222          * If any are negative, then the firmware likely reset; so just
 6223          * bail.  We'll pick this up next time.
 6224          */
 6225         if (delta_cck < 0 || delta_ofdm < 0 || delta_ht < 0 || delta_ticks < 0)
 6226                 return;
 6227 
 6228         /*
 6229          * delta_ticks is in ticks; we need to convert it up to milliseconds
 6230          * so we can do some useful math with it.
 6231          */
 6232         delta_msec = ticks_to_msecs(delta_ticks);
 6233 
 6234         /*
 6235          * Calculate what our threshold is given the current delta_msec.
 6236          */
 6237         thresh = sc->base_params->plcp_err_threshold * delta_msec;
 6238 
 6239         DPRINTF(sc, IWN_DEBUG_STATE,
 6240             "%s: time delta: %d; cck=%d, ofdm=%d, ht=%d, total=%d, thresh=%d\n",
 6241             __func__,
 6242             delta_msec,
 6243             delta_cck,
 6244             delta_ofdm,
 6245             delta_ht,
 6246             (delta_msec + delta_cck + delta_ofdm + delta_ht),
 6247             thresh);
 6248 
 6249         /*
 6250          * If we need a retune, then schedule a single channel scan
 6251          * to a channel that isn't the currently active one!
 6252          *
 6253          * The math from linux iwlwifi:
 6254          *
 6255          * if ((delta * 100 / msecs) > threshold)
 6256          */
 6257         if (thresh > 0 && (delta_cck + delta_ofdm + delta_ht) * 100 > thresh) {
 6258                 DPRINTF(sc, IWN_DEBUG_ANY,
 6259                     "%s: PLCP error threshold raw (%d) comparison (%d) "
 6260                     "over limit (%d); retune!\n",
 6261                     __func__,
 6262                     (delta_cck + delta_ofdm + delta_ht),
 6263                     (delta_cck + delta_ofdm + delta_ht) * 100,
 6264                     thresh);
 6265         }
 6266 }
 6267 
 6268 /*
 6269  * Set STA mode power saving level (between 0 and 5).
 6270  * Level 0 is CAM (Continuously Aware Mode), 5 is for maximum power saving.
 6271  */
 6272 static int
 6273 iwn_set_pslevel(struct iwn_softc *sc, int dtim, int level, int async)
 6274 {
 6275         struct iwn_pmgt_cmd cmd;
 6276         const struct iwn_pmgt *pmgt;
 6277         uint32_t max, skip_dtim;
 6278         uint32_t reg;
 6279         int i;
 6280 
 6281         DPRINTF(sc, IWN_DEBUG_PWRSAVE,
 6282             "%s: dtim=%d, level=%d, async=%d\n",
 6283             __func__,
 6284             dtim,
 6285             level,
 6286             async);
 6287 
 6288         /* Select which PS parameters to use. */
 6289         if (dtim <= 2)
 6290                 pmgt = &iwn_pmgt[0][level];
 6291         else if (dtim <= 10)
 6292                 pmgt = &iwn_pmgt[1][level];
 6293         else
 6294                 pmgt = &iwn_pmgt[2][level];
 6295 
 6296         memset(&cmd, 0, sizeof cmd);
 6297         if (level != 0) /* not CAM */
 6298                 cmd.flags |= htole16(IWN_PS_ALLOW_SLEEP);
 6299         if (level == 5)
 6300                 cmd.flags |= htole16(IWN_PS_FAST_PD);
 6301         /* Retrieve PCIe Active State Power Management (ASPM). */
 6302         reg = pci_read_config(sc->sc_dev, sc->sc_cap_off + PCIER_LINK_CTL, 4);
 6303         if (!(reg & PCIEM_LINK_CTL_ASPMC_L0S))  /* L0s Entry disabled. */
 6304                 cmd.flags |= htole16(IWN_PS_PCI_PMGT);
 6305         cmd.rxtimeout = htole32(pmgt->rxtimeout * 1024);
 6306         cmd.txtimeout = htole32(pmgt->txtimeout * 1024);
 6307 
 6308         if (dtim == 0) {
 6309                 dtim = 1;
 6310                 skip_dtim = 0;
 6311         } else
 6312                 skip_dtim = pmgt->skip_dtim;
 6313         if (skip_dtim != 0) {
 6314                 cmd.flags |= htole16(IWN_PS_SLEEP_OVER_DTIM);
 6315                 max = pmgt->intval[4];
 6316                 if (max == (uint32_t)-1)
 6317                         max = dtim * (skip_dtim + 1);
 6318                 else if (max > dtim)
 6319                         max = rounddown(max, dtim);
 6320         } else
 6321                 max = dtim;
 6322         for (i = 0; i < 5; i++)
 6323                 cmd.intval[i] = htole32(MIN(max, pmgt->intval[i]));
 6324 
 6325         DPRINTF(sc, IWN_DEBUG_RESET, "setting power saving level to %d\n",
 6326             level);
 6327         return iwn_cmd(sc, IWN_CMD_SET_POWER_MODE, &cmd, sizeof cmd, async);
 6328 }
 6329 
 6330 static int
 6331 iwn_send_btcoex(struct iwn_softc *sc)
 6332 {
 6333         struct iwn_bluetooth cmd;
 6334 
 6335         memset(&cmd, 0, sizeof cmd);
 6336         cmd.flags = IWN_BT_COEX_CHAN_ANN | IWN_BT_COEX_BT_PRIO;
 6337         cmd.lead_time = IWN_BT_LEAD_TIME_DEF;
 6338         cmd.max_kill = IWN_BT_MAX_KILL_DEF;
 6339         DPRINTF(sc, IWN_DEBUG_RESET, "%s: configuring bluetooth coexistence\n",
 6340             __func__);
 6341         return iwn_cmd(sc, IWN_CMD_BT_COEX, &cmd, sizeof(cmd), 0);
 6342 }
 6343 
 6344 static int
 6345 iwn_send_advanced_btcoex(struct iwn_softc *sc)
 6346 {
 6347         static const uint32_t btcoex_3wire[12] = {
 6348                 0xaaaaaaaa, 0xaaaaaaaa, 0xaeaaaaaa, 0xaaaaaaaa,
 6349                 0xcc00ff28, 0x0000aaaa, 0xcc00aaaa, 0x0000aaaa,
 6350                 0xc0004000, 0x00004000, 0xf0005000, 0xf0005000,
 6351         };
 6352         struct iwn6000_btcoex_config btconfig;
 6353         struct iwn2000_btcoex_config btconfig2k;
 6354         struct iwn_btcoex_priotable btprio;
 6355         struct iwn_btcoex_prot btprot;
 6356         int error, i;
 6357         uint8_t flags;
 6358 
 6359         memset(&btconfig, 0, sizeof btconfig);
 6360         memset(&btconfig2k, 0, sizeof btconfig2k);
 6361 
 6362         flags = IWN_BT_FLAG_COEX6000_MODE_3W <<
 6363             IWN_BT_FLAG_COEX6000_MODE_SHIFT; // Done as is in linux kernel 3.2
 6364 
 6365         if (sc->base_params->bt_sco_disable)
 6366                 flags &= ~IWN_BT_FLAG_SYNC_2_BT_DISABLE;
 6367         else
 6368                 flags |= IWN_BT_FLAG_SYNC_2_BT_DISABLE;
 6369 
 6370         flags |= IWN_BT_FLAG_COEX6000_CHAN_INHIBITION;
 6371 
 6372         /* Default flags result is 145 as old value */
 6373 
 6374         /*
 6375          * Flags value has to be review. Values must change if we
 6376          * which to disable it
 6377          */
 6378         if (sc->base_params->bt_session_2) {
 6379                 btconfig2k.flags = flags;
 6380                 btconfig2k.max_kill = 5;
 6381                 btconfig2k.bt3_t7_timer = 1;
 6382                 btconfig2k.kill_ack = htole32(0xffff0000);
 6383                 btconfig2k.kill_cts = htole32(0xffff0000);
 6384                 btconfig2k.sample_time = 2;
 6385                 btconfig2k.bt3_t2_timer = 0xc;
 6386 
 6387                 for (i = 0; i < 12; i++)
 6388                         btconfig2k.lookup_table[i] = htole32(btcoex_3wire[i]);
 6389                 btconfig2k.valid = htole16(0xff);
 6390                 btconfig2k.prio_boost = htole32(0xf0);
 6391                 DPRINTF(sc, IWN_DEBUG_RESET,
 6392                     "%s: configuring advanced bluetooth coexistence"
 6393                     " session 2, flags : 0x%x\n",
 6394                     __func__,
 6395                     flags);
 6396                 error = iwn_cmd(sc, IWN_CMD_BT_COEX, &btconfig2k,
 6397                     sizeof(btconfig2k), 1);
 6398         } else {
 6399                 btconfig.flags = flags;
 6400                 btconfig.max_kill = 5;
 6401                 btconfig.bt3_t7_timer = 1;
 6402                 btconfig.kill_ack = htole32(0xffff0000);
 6403                 btconfig.kill_cts = htole32(0xffff0000);
 6404                 btconfig.sample_time = 2;
 6405                 btconfig.bt3_t2_timer = 0xc;
 6406 
 6407                 for (i = 0; i < 12; i++)
 6408                         btconfig.lookup_table[i] = htole32(btcoex_3wire[i]);
 6409                 btconfig.valid = htole16(0xff);
 6410                 btconfig.prio_boost = 0xf0;
 6411                 DPRINTF(sc, IWN_DEBUG_RESET,
 6412                     "%s: configuring advanced bluetooth coexistence,"
 6413                     " flags : 0x%x\n",
 6414                     __func__,
 6415                     flags);
 6416                 error = iwn_cmd(sc, IWN_CMD_BT_COEX, &btconfig,
 6417                     sizeof(btconfig), 1);
 6418         }
 6419 
 6420         if (error != 0)
 6421                 return error;
 6422 
 6423         memset(&btprio, 0, sizeof btprio);
 6424         btprio.calib_init1 = 0x6;
 6425         btprio.calib_init2 = 0x7;
 6426         btprio.calib_periodic_low1 = 0x2;
 6427         btprio.calib_periodic_low2 = 0x3;
 6428         btprio.calib_periodic_high1 = 0x4;
 6429         btprio.calib_periodic_high2 = 0x5;
 6430         btprio.dtim = 0x6;
 6431         btprio.scan52 = 0x8;
 6432         btprio.scan24 = 0xa;
 6433         error = iwn_cmd(sc, IWN_CMD_BT_COEX_PRIOTABLE, &btprio, sizeof(btprio),
 6434             1);
 6435         if (error != 0)
 6436                 return error;
 6437 
 6438         /* Force BT state machine change. */
 6439         memset(&btprot, 0, sizeof btprot);
 6440         btprot.open = 1;
 6441         btprot.type = 1;
 6442         error = iwn_cmd(sc, IWN_CMD_BT_COEX_PROT, &btprot, sizeof(btprot), 1);
 6443         if (error != 0)
 6444                 return error;
 6445         btprot.open = 0;
 6446         return iwn_cmd(sc, IWN_CMD_BT_COEX_PROT, &btprot, sizeof(btprot), 1);
 6447 }
 6448 
 6449 static int
 6450 iwn5000_runtime_calib(struct iwn_softc *sc)
 6451 {
 6452         struct iwn5000_calib_config cmd;
 6453 
 6454         memset(&cmd, 0, sizeof cmd);
 6455         cmd.ucode.once.enable = 0xffffffff;
 6456         cmd.ucode.once.start = IWN5000_CALIB_DC;
 6457         DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 6458             "%s: configuring runtime calibration\n", __func__);
 6459         return iwn_cmd(sc, IWN5000_CMD_CALIB_CONFIG, &cmd, sizeof(cmd), 0);
 6460 }
 6461 
 6462 static uint32_t
 6463 iwn_get_rxon_ht_flags(struct iwn_softc *sc, struct ieee80211_channel *c)
 6464 {
 6465         struct ieee80211com *ic = &sc->sc_ic;
 6466         uint32_t htflags = 0;
 6467 
 6468         if (! IEEE80211_IS_CHAN_HT(c))
 6469                 return (0);
 6470 
 6471         htflags |= IWN_RXON_HT_PROTMODE(ic->ic_curhtprotmode);
 6472 
 6473         if (IEEE80211_IS_CHAN_HT40(c)) {
 6474                 switch (ic->ic_curhtprotmode) {
 6475                 case IEEE80211_HTINFO_OPMODE_HT20PR:
 6476                         htflags |= IWN_RXON_HT_MODEPURE40;
 6477                         break;
 6478                 default:
 6479                         htflags |= IWN_RXON_HT_MODEMIXED;
 6480                         break;
 6481                 }
 6482         }
 6483         if (IEEE80211_IS_CHAN_HT40D(c))
 6484                 htflags |= IWN_RXON_HT_HT40MINUS;
 6485 
 6486         return (htflags);
 6487 }
 6488 
 6489 static int
 6490 iwn_config(struct iwn_softc *sc)
 6491 {
 6492         struct iwn_ops *ops = &sc->ops;
 6493         struct ieee80211com *ic = &sc->sc_ic;
 6494         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
 6495         const uint8_t *macaddr;
 6496         uint32_t txmask;
 6497         uint16_t rxchain;
 6498         int error;
 6499 
 6500         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 6501 
 6502         if ((sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSET)
 6503             && (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSETv2)) {
 6504                 device_printf(sc->sc_dev,"%s: temp_offset and temp_offsetv2 are"
 6505                     " exclusive each together. Review NIC config file. Conf"
 6506                     " :  0x%08x Flags :  0x%08x  \n", __func__,
 6507                     sc->base_params->calib_need,
 6508                     (IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSET |
 6509                     IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSETv2));
 6510                 return (EINVAL);
 6511         }
 6512 
 6513         /* Compute temperature calib if needed. Will be send by send calib */
 6514         if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSET) {
 6515                 error = iwn5000_temp_offset_calib(sc);
 6516                 if (error != 0) {
 6517                         device_printf(sc->sc_dev,
 6518                             "%s: could not set temperature offset\n", __func__);
 6519                         return (error);
 6520                 }
 6521         } else if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSETv2) {
 6522                 error = iwn5000_temp_offset_calibv2(sc);
 6523                 if (error != 0) {
 6524                         device_printf(sc->sc_dev,
 6525                             "%s: could not compute temperature offset v2\n",
 6526                             __func__);
 6527                         return (error);
 6528                 }
 6529         }
 6530 
 6531         if (sc->hw_type == IWN_HW_REV_TYPE_6050) {
 6532                 /* Configure runtime DC calibration. */
 6533                 error = iwn5000_runtime_calib(sc);
 6534                 if (error != 0) {
 6535                         device_printf(sc->sc_dev,
 6536                             "%s: could not configure runtime calibration\n",
 6537                             __func__);
 6538                         return error;
 6539                 }
 6540         }
 6541 
 6542         /* Configure valid TX chains for >=5000 Series. */
 6543         if (sc->hw_type != IWN_HW_REV_TYPE_4965 &&
 6544             IWN_UCODE_API(sc->ucode_rev) > 1) {
 6545                 txmask = htole32(sc->txchainmask);
 6546                 DPRINTF(sc, IWN_DEBUG_RESET | IWN_DEBUG_XMIT,
 6547                     "%s: configuring valid TX chains 0x%x\n", __func__, txmask);
 6548                 error = iwn_cmd(sc, IWN5000_CMD_TX_ANT_CONFIG, &txmask,
 6549                     sizeof txmask, 0);
 6550                 if (error != 0) {
 6551                         device_printf(sc->sc_dev,
 6552                             "%s: could not configure valid TX chains, "
 6553                             "error %d\n", __func__, error);
 6554                         return error;
 6555                 }
 6556         }
 6557 
 6558         /* Configure bluetooth coexistence. */
 6559         error = 0;
 6560 
 6561         /* Configure bluetooth coexistence if needed. */
 6562         if (sc->base_params->bt_mode == IWN_BT_ADVANCED)
 6563                 error = iwn_send_advanced_btcoex(sc);
 6564         if (sc->base_params->bt_mode == IWN_BT_SIMPLE)
 6565                 error = iwn_send_btcoex(sc);
 6566 
 6567         if (error != 0) {
 6568                 device_printf(sc->sc_dev,
 6569                     "%s: could not configure bluetooth coexistence, error %d\n",
 6570                     __func__, error);
 6571                 return error;
 6572         }
 6573 
 6574         /* Set mode, channel, RX filter and enable RX. */
 6575         sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
 6576         memset(sc->rxon, 0, sizeof (struct iwn_rxon));
 6577         macaddr = vap ? vap->iv_myaddr : ic->ic_macaddr;
 6578         IEEE80211_ADDR_COPY(sc->rxon->myaddr, macaddr);
 6579         IEEE80211_ADDR_COPY(sc->rxon->wlap, macaddr);
 6580         sc->rxon->chan = ieee80211_chan2ieee(ic, ic->ic_curchan);
 6581         sc->rxon->flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
 6582         if (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
 6583                 sc->rxon->flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
 6584         switch (ic->ic_opmode) {
 6585         case IEEE80211_M_STA:
 6586                 sc->rxon->mode = IWN_MODE_STA;
 6587                 sc->rxon->filter = htole32(IWN_FILTER_MULTICAST);
 6588                 break;
 6589         case IEEE80211_M_MONITOR:
 6590                 sc->rxon->mode = IWN_MODE_MONITOR;
 6591                 sc->rxon->filter = htole32(IWN_FILTER_MULTICAST |
 6592                     IWN_FILTER_CTL | IWN_FILTER_PROMISC);
 6593                 break;
 6594         default:
 6595                 /* Should not get there. */
 6596                 break;
 6597         }
 6598         sc->rxon->cck_mask  = 0x0f;     /* not yet negotiated */
 6599         sc->rxon->ofdm_mask = 0xff;     /* not yet negotiated */
 6600         sc->rxon->ht_single_mask = 0xff;
 6601         sc->rxon->ht_dual_mask = 0xff;
 6602         sc->rxon->ht_triple_mask = 0xff;
 6603         /*
 6604          * In active association mode, ensure that
 6605          * all the receive chains are enabled.
 6606          *
 6607          * Since we're not yet doing SMPS, don't allow the
 6608          * number of idle RX chains to be less than the active
 6609          * number.
 6610          */
 6611         rxchain =
 6612             IWN_RXCHAIN_VALID(sc->rxchainmask) |
 6613             IWN_RXCHAIN_MIMO_COUNT(sc->nrxchains) |
 6614             IWN_RXCHAIN_IDLE_COUNT(sc->nrxchains);
 6615         sc->rxon->rxchain = htole16(rxchain);
 6616         DPRINTF(sc, IWN_DEBUG_RESET | IWN_DEBUG_XMIT,
 6617             "%s: rxchainmask=0x%x, nrxchains=%d\n",
 6618             __func__,
 6619             sc->rxchainmask,
 6620             sc->nrxchains);
 6621 
 6622         sc->rxon->flags |= htole32(iwn_get_rxon_ht_flags(sc, ic->ic_curchan));
 6623 
 6624         DPRINTF(sc, IWN_DEBUG_RESET,
 6625             "%s: setting configuration; flags=0x%08x\n",
 6626             __func__, le32toh(sc->rxon->flags));
 6627         if (sc->sc_is_scanning)
 6628                 device_printf(sc->sc_dev,
 6629                     "%s: is_scanning set, before RXON\n",
 6630                     __func__);
 6631         error = iwn_cmd(sc, IWN_CMD_RXON, sc->rxon, sc->rxonsz, 0);
 6632         if (error != 0) {
 6633                 device_printf(sc->sc_dev, "%s: RXON command failed\n",
 6634                     __func__);
 6635                 return error;
 6636         }
 6637 
 6638         if ((error = iwn_add_broadcast_node(sc, 0)) != 0) {
 6639                 device_printf(sc->sc_dev, "%s: could not add broadcast node\n",
 6640                     __func__);
 6641                 return error;
 6642         }
 6643 
 6644         /* Configuration has changed, set TX power accordingly. */
 6645         if ((error = ops->set_txpower(sc, ic->ic_curchan, 0)) != 0) {
 6646                 device_printf(sc->sc_dev, "%s: could not set TX power\n",
 6647                     __func__);
 6648                 return error;
 6649         }
 6650 
 6651         if ((error = iwn_set_critical_temp(sc)) != 0) {
 6652                 device_printf(sc->sc_dev,
 6653                     "%s: could not set critical temperature\n", __func__);
 6654                 return error;
 6655         }
 6656 
 6657         /* Set power saving level to CAM during initialization. */
 6658         if ((error = iwn_set_pslevel(sc, 0, 0, 0)) != 0) {
 6659                 device_printf(sc->sc_dev,
 6660                     "%s: could not set power saving level\n", __func__);
 6661                 return error;
 6662         }
 6663 
 6664         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 6665 
 6666         return 0;
 6667 }
 6668 
 6669 static uint16_t
 6670 iwn_get_active_dwell_time(struct iwn_softc *sc,
 6671     struct ieee80211_channel *c, uint8_t n_probes)
 6672 {
 6673         /* No channel? Default to 2GHz settings */
 6674         if (c == NULL || IEEE80211_IS_CHAN_2GHZ(c)) {
 6675                 return (IWN_ACTIVE_DWELL_TIME_2GHZ +
 6676                 IWN_ACTIVE_DWELL_FACTOR_2GHZ * (n_probes + 1));
 6677         }
 6678 
 6679         /* 5GHz dwell time */
 6680         return (IWN_ACTIVE_DWELL_TIME_5GHZ +
 6681             IWN_ACTIVE_DWELL_FACTOR_5GHZ * (n_probes + 1));
 6682 }
 6683 
 6684 /*
 6685  * Limit the total dwell time to 85% of the beacon interval.
 6686  *
 6687  * Returns the dwell time in milliseconds.
 6688  */
 6689 static uint16_t
 6690 iwn_limit_dwell(struct iwn_softc *sc, uint16_t dwell_time)
 6691 {
 6692         struct ieee80211com *ic = &sc->sc_ic;
 6693         struct ieee80211vap *vap = NULL;
 6694         int bintval = 0;
 6695 
 6696         /* bintval is in TU (1.024mS) */
 6697         if (! TAILQ_EMPTY(&ic->ic_vaps)) {
 6698                 vap = TAILQ_FIRST(&ic->ic_vaps);
 6699                 bintval = vap->iv_bss->ni_intval;
 6700         }
 6701 
 6702         /*
 6703          * If it's non-zero, we should calculate the minimum of
 6704          * it and the DWELL_BASE.
 6705          *
 6706          * XXX Yes, the math should take into account that bintval
 6707          * is 1.024mS, not 1mS..
 6708          */
 6709         if (bintval > 0) {
 6710                 DPRINTF(sc, IWN_DEBUG_SCAN,
 6711                     "%s: bintval=%d\n",
 6712                     __func__,
 6713                     bintval);
 6714                 return (MIN(IWN_PASSIVE_DWELL_BASE, ((bintval * 85) / 100)));
 6715         }
 6716 
 6717         /* No association context? Default */
 6718         return (IWN_PASSIVE_DWELL_BASE);
 6719 }
 6720 
 6721 static uint16_t
 6722 iwn_get_passive_dwell_time(struct iwn_softc *sc, struct ieee80211_channel *c)
 6723 {
 6724         uint16_t passive;
 6725 
 6726         if (c == NULL || IEEE80211_IS_CHAN_2GHZ(c)) {
 6727                 passive = IWN_PASSIVE_DWELL_BASE + IWN_PASSIVE_DWELL_TIME_2GHZ;
 6728         } else {
 6729                 passive = IWN_PASSIVE_DWELL_BASE + IWN_PASSIVE_DWELL_TIME_5GHZ;
 6730         }
 6731 
 6732         /* Clamp to the beacon interval if we're associated */
 6733         return (iwn_limit_dwell(sc, passive));
 6734 }
 6735 
 6736 static int
 6737 iwn_scan(struct iwn_softc *sc, struct ieee80211vap *vap,
 6738     struct ieee80211_scan_state *ss, struct ieee80211_channel *c)
 6739 {
 6740         struct ieee80211com *ic = &sc->sc_ic;
 6741         struct ieee80211_node *ni = vap->iv_bss;
 6742         struct iwn_scan_hdr *hdr;
 6743         struct iwn_cmd_data *tx;
 6744         struct iwn_scan_essid *essid;
 6745         struct iwn_scan_chan *chan;
 6746         struct ieee80211_frame *wh;
 6747         struct ieee80211_rateset *rs;
 6748         uint8_t *buf, *frm;
 6749         uint16_t rxchain;
 6750         uint8_t txant;
 6751         int buflen, error;
 6752         int is_active;
 6753         uint16_t dwell_active, dwell_passive;
 6754         uint32_t extra, scan_service_time;
 6755 
 6756         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 6757 
 6758         /*
 6759          * We are absolutely not allowed to send a scan command when another
 6760          * scan command is pending.
 6761          */
 6762         if (sc->sc_is_scanning) {
 6763                 device_printf(sc->sc_dev, "%s: called whilst scanning!\n",
 6764                     __func__);
 6765                 return (EAGAIN);
 6766         }
 6767 
 6768         /* Assign the scan channel */
 6769         c = ic->ic_curchan;
 6770 
 6771         sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
 6772         buf = malloc(IWN_SCAN_MAXSZ, M_DEVBUF, M_NOWAIT | M_ZERO);
 6773         if (buf == NULL) {
 6774                 device_printf(sc->sc_dev,
 6775                     "%s: could not allocate buffer for scan command\n",
 6776                     __func__);
 6777                 return ENOMEM;
 6778         }
 6779         hdr = (struct iwn_scan_hdr *)buf;
 6780         /*
 6781          * Move to the next channel if no frames are received within 10ms
 6782          * after sending the probe request.
 6783          */
 6784         hdr->quiet_time = htole16(10);          /* timeout in milliseconds */
 6785         hdr->quiet_threshold = htole16(1);      /* min # of packets */
 6786         /*
 6787          * Max needs to be greater than active and passive and quiet!
 6788          * It's also in microseconds!
 6789          */
 6790         hdr->max_svc = htole32(250 * 1024);
 6791 
 6792         /*
 6793          * Reset scan: interval=100
 6794          * Normal scan: interval=becaon interval
 6795          * suspend_time: 100 (TU)
 6796          *
 6797          */
 6798         extra = (100 /* suspend_time */ / 100 /* beacon interval */) << 22;
 6799         //scan_service_time = extra | ((100 /* susp */ % 100 /* int */) * 1024);
 6800         scan_service_time = (4 << 22) | (100 * 1024);   /* Hardcode for now! */
 6801         hdr->pause_svc = htole32(scan_service_time);
 6802 
 6803         /* Select antennas for scanning. */
 6804         rxchain =
 6805             IWN_RXCHAIN_VALID(sc->rxchainmask) |
 6806             IWN_RXCHAIN_FORCE_MIMO_SEL(sc->rxchainmask) |
 6807             IWN_RXCHAIN_DRIVER_FORCE;
 6808         if (IEEE80211_IS_CHAN_A(c) &&
 6809             sc->hw_type == IWN_HW_REV_TYPE_4965) {
 6810                 /* Ant A must be avoided in 5GHz because of an HW bug. */
 6811                 rxchain |= IWN_RXCHAIN_FORCE_SEL(IWN_ANT_B);
 6812         } else  /* Use all available RX antennas. */
 6813                 rxchain |= IWN_RXCHAIN_FORCE_SEL(sc->rxchainmask);
 6814         hdr->rxchain = htole16(rxchain);
 6815         hdr->filter = htole32(IWN_FILTER_MULTICAST | IWN_FILTER_BEACON);
 6816 
 6817         tx = (struct iwn_cmd_data *)(hdr + 1);
 6818         tx->flags = htole32(IWN_TX_AUTO_SEQ);
 6819         tx->id = sc->broadcast_id;
 6820         tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
 6821 
 6822         if (IEEE80211_IS_CHAN_5GHZ(c)) {
 6823                 /* Send probe requests at 6Mbps. */
 6824                 tx->rate = htole32(0xd);
 6825                 rs = &ic->ic_sup_rates[IEEE80211_MODE_11A];
 6826         } else {
 6827                 hdr->flags = htole32(IWN_RXON_24GHZ | IWN_RXON_AUTO);
 6828                 if (sc->hw_type == IWN_HW_REV_TYPE_4965 &&
 6829                     sc->rxon->associd && sc->rxon->chan > 14)
 6830                         tx->rate = htole32(0xd);
 6831                 else {
 6832                         /* Send probe requests at 1Mbps. */
 6833                         tx->rate = htole32(10 | IWN_RFLAG_CCK);
 6834                 }
 6835                 rs = &ic->ic_sup_rates[IEEE80211_MODE_11G];
 6836         }
 6837         /* Use the first valid TX antenna. */
 6838         txant = IWN_LSB(sc->txchainmask);
 6839         tx->rate |= htole32(IWN_RFLAG_ANT(txant));
 6840 
 6841         /*
 6842          * Only do active scanning if we're announcing a probe request
 6843          * for a given SSID (or more, if we ever add it to the driver.)
 6844          */
 6845         is_active = 0;
 6846 
 6847         /*
 6848          * If we're scanning for a specific SSID, add it to the command.
 6849          *
 6850          * XXX maybe look at adding support for scanning multiple SSIDs?
 6851          */
 6852         essid = (struct iwn_scan_essid *)(tx + 1);
 6853         if (ss != NULL) {
 6854                 if (ss->ss_ssid[0].len != 0) {
 6855                         essid[0].id = IEEE80211_ELEMID_SSID;
 6856                         essid[0].len = ss->ss_ssid[0].len;
 6857                         memcpy(essid[0].data, ss->ss_ssid[0].ssid, ss->ss_ssid[0].len);
 6858                 }
 6859 
 6860                 DPRINTF(sc, IWN_DEBUG_SCAN, "%s: ssid_len=%d, ssid=%*s\n",
 6861                     __func__,
 6862                     ss->ss_ssid[0].len,
 6863                     ss->ss_ssid[0].len,
 6864                     ss->ss_ssid[0].ssid);
 6865 
 6866                 if (ss->ss_nssid > 0)
 6867                         is_active = 1;
 6868         }
 6869 
 6870         /*
 6871          * Build a probe request frame.  Most of the following code is a
 6872          * copy & paste of what is done in net80211.
 6873          */
 6874         wh = (struct ieee80211_frame *)(essid + 20);
 6875         wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
 6876             IEEE80211_FC0_SUBTYPE_PROBE_REQ;
 6877         wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
 6878         IEEE80211_ADDR_COPY(wh->i_addr1, vap->iv_ifp->if_broadcastaddr);
 6879         IEEE80211_ADDR_COPY(wh->i_addr2, IF_LLADDR(vap->iv_ifp));
 6880         IEEE80211_ADDR_COPY(wh->i_addr3, vap->iv_ifp->if_broadcastaddr);
 6881         *(uint16_t *)&wh->i_dur[0] = 0; /* filled by HW */
 6882         *(uint16_t *)&wh->i_seq[0] = 0; /* filled by HW */
 6883 
 6884         frm = (uint8_t *)(wh + 1);
 6885         frm = ieee80211_add_ssid(frm, NULL, 0);
 6886         frm = ieee80211_add_rates(frm, rs);
 6887         if (rs->rs_nrates > IEEE80211_RATE_SIZE)
 6888                 frm = ieee80211_add_xrates(frm, rs);
 6889         if (ic->ic_htcaps & IEEE80211_HTC_HT)
 6890                 frm = ieee80211_add_htcap(frm, ni);
 6891 
 6892         /* Set length of probe request. */
 6893         tx->len = htole16(frm - (uint8_t *)wh);
 6894 
 6895         /*
 6896          * If active scanning is requested but a certain channel is
 6897          * marked passive, we can do active scanning if we detect
 6898          * transmissions.
 6899          *
 6900          * There is an issue with some firmware versions that triggers
 6901          * a sysassert on a "good CRC threshold" of zero (== disabled),
 6902          * on a radar channel even though this means that we should NOT
 6903          * send probes.
 6904          *
 6905          * The "good CRC threshold" is the number of frames that we
 6906          * need to receive during our dwell time on a channel before
 6907          * sending out probes -- setting this to a huge value will
 6908          * mean we never reach it, but at the same time work around
 6909          * the aforementioned issue. Thus use IWL_GOOD_CRC_TH_NEVER
 6910          * here instead of IWL_GOOD_CRC_TH_DISABLED.
 6911          *
 6912          * This was fixed in later versions along with some other
 6913          * scan changes, and the threshold behaves as a flag in those
 6914          * versions.
 6915          */
 6916 
 6917         /*
 6918          * If we're doing active scanning, set the crc_threshold
 6919          * to a suitable value.  This is different to active veruss
 6920          * passive scanning depending upon the channel flags; the
 6921          * firmware will obey that particular check for us.
 6922          */
 6923         if (sc->tlv_feature_flags & IWN_UCODE_TLV_FLAGS_NEWSCAN)
 6924                 hdr->crc_threshold = is_active ?
 6925                     IWN_GOOD_CRC_TH_DEFAULT : IWN_GOOD_CRC_TH_DISABLED;
 6926         else
 6927                 hdr->crc_threshold = is_active ?
 6928                     IWN_GOOD_CRC_TH_DEFAULT : IWN_GOOD_CRC_TH_NEVER;
 6929 
 6930         chan = (struct iwn_scan_chan *)frm;
 6931         chan->chan = htole16(ieee80211_chan2ieee(ic, c));
 6932         chan->flags = 0;
 6933         if (ss->ss_nssid > 0)
 6934                 chan->flags |= htole32(IWN_CHAN_NPBREQS(1));
 6935         chan->dsp_gain = 0x6e;
 6936 
 6937         /*
 6938          * Set the passive/active flag depending upon the channel mode.
 6939          * XXX TODO: take the is_active flag into account as well?
 6940          */
 6941         if (c->ic_flags & IEEE80211_CHAN_PASSIVE)
 6942                 chan->flags |= htole32(IWN_CHAN_PASSIVE);
 6943         else
 6944                 chan->flags |= htole32(IWN_CHAN_ACTIVE);
 6945 
 6946         /*
 6947          * Calculate the active/passive dwell times.
 6948          */
 6949 
 6950         dwell_active = iwn_get_active_dwell_time(sc, c, ss->ss_nssid);
 6951         dwell_passive = iwn_get_passive_dwell_time(sc, c);
 6952 
 6953         /* Make sure they're valid */
 6954         if (dwell_passive <= dwell_active)
 6955                 dwell_passive = dwell_active + 1;
 6956 
 6957         chan->active = htole16(dwell_active);
 6958         chan->passive = htole16(dwell_passive);
 6959 
 6960         if (IEEE80211_IS_CHAN_5GHZ(c))
 6961                 chan->rf_gain = 0x3b;
 6962         else
 6963                 chan->rf_gain = 0x28;
 6964 
 6965         DPRINTF(sc, IWN_DEBUG_STATE,
 6966             "%s: chan %u flags 0x%x rf_gain 0x%x "
 6967             "dsp_gain 0x%x active %d passive %d scan_svc_time %d crc 0x%x "
 6968             "isactive=%d numssid=%d\n", __func__,
 6969             chan->chan, chan->flags, chan->rf_gain, chan->dsp_gain,
 6970             dwell_active, dwell_passive, scan_service_time,
 6971             hdr->crc_threshold, is_active, ss->ss_nssid);
 6972 
 6973         hdr->nchan++;
 6974         chan++;
 6975         buflen = (uint8_t *)chan - buf;
 6976         hdr->len = htole16(buflen);
 6977 
 6978         if (sc->sc_is_scanning) {
 6979                 device_printf(sc->sc_dev,
 6980                     "%s: called with is_scanning set!\n",
 6981                     __func__);
 6982         }
 6983         sc->sc_is_scanning = 1;
 6984 
 6985         DPRINTF(sc, IWN_DEBUG_STATE, "sending scan command nchan=%d\n",
 6986             hdr->nchan);
 6987         error = iwn_cmd(sc, IWN_CMD_SCAN, buf, buflen, 1);
 6988         free(buf, M_DEVBUF);
 6989         if (error == 0)
 6990                 callout_reset(&sc->scan_timeout, 5*hz, iwn_scan_timeout, sc);
 6991 
 6992         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 6993 
 6994         return error;
 6995 }
 6996 
 6997 static int
 6998 iwn_auth(struct iwn_softc *sc, struct ieee80211vap *vap)
 6999 {
 7000         struct iwn_ops *ops = &sc->ops;
 7001         struct ieee80211com *ic = &sc->sc_ic;
 7002         struct ieee80211_node *ni = vap->iv_bss;
 7003         int error;
 7004 
 7005         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 7006 
 7007         sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
 7008         /* Update adapter configuration. */
 7009         IEEE80211_ADDR_COPY(sc->rxon->bssid, ni->ni_bssid);
 7010         sc->rxon->chan = ieee80211_chan2ieee(ic, ni->ni_chan);
 7011         sc->rxon->flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
 7012         if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
 7013                 sc->rxon->flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
 7014         if (ic->ic_flags & IEEE80211_F_SHSLOT)
 7015                 sc->rxon->flags |= htole32(IWN_RXON_SHSLOT);
 7016         if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
 7017                 sc->rxon->flags |= htole32(IWN_RXON_SHPREAMBLE);
 7018         if (IEEE80211_IS_CHAN_A(ni->ni_chan)) {
 7019                 sc->rxon->cck_mask  = 0;
 7020                 sc->rxon->ofdm_mask = 0x15;
 7021         } else if (IEEE80211_IS_CHAN_B(ni->ni_chan)) {
 7022                 sc->rxon->cck_mask  = 0x03;
 7023                 sc->rxon->ofdm_mask = 0;
 7024         } else {
 7025                 /* Assume 802.11b/g. */
 7026                 sc->rxon->cck_mask  = 0x03;
 7027                 sc->rxon->ofdm_mask = 0x15;
 7028         }
 7029 
 7030         /* try HT */
 7031         sc->rxon->flags |= htole32(iwn_get_rxon_ht_flags(sc, ic->ic_curchan));
 7032 
 7033         DPRINTF(sc, IWN_DEBUG_STATE, "rxon chan %d flags %x cck %x ofdm %x\n",
 7034             sc->rxon->chan, sc->rxon->flags, sc->rxon->cck_mask,
 7035             sc->rxon->ofdm_mask);
 7036         if (sc->sc_is_scanning)
 7037                 device_printf(sc->sc_dev,
 7038                     "%s: is_scanning set, before RXON\n",
 7039                     __func__);
 7040         error = iwn_cmd(sc, IWN_CMD_RXON, sc->rxon, sc->rxonsz, 1);
 7041         if (error != 0) {
 7042                 device_printf(sc->sc_dev, "%s: RXON command failed, error %d\n",
 7043                     __func__, error);
 7044                 return error;
 7045         }
 7046 
 7047         /* Configuration has changed, set TX power accordingly. */
 7048         if ((error = ops->set_txpower(sc, ni->ni_chan, 1)) != 0) {
 7049                 device_printf(sc->sc_dev,
 7050                     "%s: could not set TX power, error %d\n", __func__, error);
 7051                 return error;
 7052         }
 7053         /*
 7054          * Reconfiguring RXON clears the firmware nodes table so we must
 7055          * add the broadcast node again.
 7056          */
 7057         if ((error = iwn_add_broadcast_node(sc, 1)) != 0) {
 7058                 device_printf(sc->sc_dev,
 7059                     "%s: could not add broadcast node, error %d\n", __func__,
 7060                     error);
 7061                 return error;
 7062         }
 7063 
 7064         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 7065 
 7066         return 0;
 7067 }
 7068 
 7069 static int
 7070 iwn_run(struct iwn_softc *sc, struct ieee80211vap *vap)
 7071 {
 7072         struct iwn_ops *ops = &sc->ops;
 7073         struct ieee80211com *ic = &sc->sc_ic;
 7074         struct ieee80211_node *ni = vap->iv_bss;
 7075         struct iwn_node_info node;
 7076         int error;
 7077 
 7078         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 7079 
 7080         sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
 7081         if (ic->ic_opmode == IEEE80211_M_MONITOR) {
 7082                 /* Link LED blinks while monitoring. */
 7083                 iwn_set_led(sc, IWN_LED_LINK, 5, 5);
 7084                 return 0;
 7085         }
 7086         if ((error = iwn_set_timing(sc, ni)) != 0) {
 7087                 device_printf(sc->sc_dev,
 7088                     "%s: could not set timing, error %d\n", __func__, error);
 7089                 return error;
 7090         }
 7091 
 7092         /* Update adapter configuration. */
 7093         IEEE80211_ADDR_COPY(sc->rxon->bssid, ni->ni_bssid);
 7094         sc->rxon->associd = htole16(IEEE80211_AID(ni->ni_associd));
 7095         sc->rxon->chan = ieee80211_chan2ieee(ic, ni->ni_chan);
 7096         sc->rxon->flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
 7097         if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
 7098                 sc->rxon->flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
 7099         if (ic->ic_flags & IEEE80211_F_SHSLOT)
 7100                 sc->rxon->flags |= htole32(IWN_RXON_SHSLOT);
 7101         if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
 7102                 sc->rxon->flags |= htole32(IWN_RXON_SHPREAMBLE);
 7103         if (IEEE80211_IS_CHAN_A(ni->ni_chan)) {
 7104                 sc->rxon->cck_mask  = 0;
 7105                 sc->rxon->ofdm_mask = 0x15;
 7106         } else if (IEEE80211_IS_CHAN_B(ni->ni_chan)) {
 7107                 sc->rxon->cck_mask  = 0x03;
 7108                 sc->rxon->ofdm_mask = 0;
 7109         } else {
 7110                 /* Assume 802.11b/g. */
 7111                 sc->rxon->cck_mask  = 0x0f;
 7112                 sc->rxon->ofdm_mask = 0x15;
 7113         }
 7114         /* try HT */
 7115         sc->rxon->flags |= htole32(iwn_get_rxon_ht_flags(sc, ni->ni_chan));
 7116         sc->rxon->filter |= htole32(IWN_FILTER_BSS);
 7117         DPRINTF(sc, IWN_DEBUG_STATE, "rxon chan %d flags %x, curhtprotmode=%d\n",
 7118             sc->rxon->chan, le32toh(sc->rxon->flags), ic->ic_curhtprotmode);
 7119         if (sc->sc_is_scanning)
 7120                 device_printf(sc->sc_dev,
 7121                     "%s: is_scanning set, before RXON\n",
 7122                     __func__);
 7123         error = iwn_cmd(sc, IWN_CMD_RXON, sc->rxon, sc->rxonsz, 1);
 7124         if (error != 0) {
 7125                 device_printf(sc->sc_dev,
 7126                     "%s: could not update configuration, error %d\n", __func__,
 7127                     error);
 7128                 return error;
 7129         }
 7130 
 7131         /* Configuration has changed, set TX power accordingly. */
 7132         if ((error = ops->set_txpower(sc, ni->ni_chan, 1)) != 0) {
 7133                 device_printf(sc->sc_dev,
 7134                     "%s: could not set TX power, error %d\n", __func__, error);
 7135                 return error;
 7136         }
 7137 
 7138         /* Fake a join to initialize the TX rate. */
 7139         ((struct iwn_node *)ni)->id = IWN_ID_BSS;
 7140         iwn_newassoc(ni, 1);
 7141 
 7142         /* Add BSS node. */
 7143         memset(&node, 0, sizeof node);
 7144         IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr);
 7145         node.id = IWN_ID_BSS;
 7146         if (IEEE80211_IS_CHAN_HT(ni->ni_chan)) {
 7147                 switch (ni->ni_htcap & IEEE80211_HTCAP_SMPS) {
 7148                 case IEEE80211_HTCAP_SMPS_ENA:
 7149                         node.htflags |= htole32(IWN_SMPS_MIMO_DIS);
 7150                         break;
 7151                 case IEEE80211_HTCAP_SMPS_DYNAMIC:
 7152                         node.htflags |= htole32(IWN_SMPS_MIMO_PROT);
 7153                         break;
 7154                 }
 7155                 node.htflags |= htole32(IWN_AMDPU_SIZE_FACTOR(3) |
 7156                     IWN_AMDPU_DENSITY(5));      /* 4us */
 7157                 if (IEEE80211_IS_CHAN_HT40(ni->ni_chan))
 7158                         node.htflags |= htole32(IWN_NODE_HT40);
 7159         }
 7160         DPRINTF(sc, IWN_DEBUG_STATE, "%s: adding BSS node\n", __func__);
 7161         error = ops->add_node(sc, &node, 1);
 7162         if (error != 0) {
 7163                 device_printf(sc->sc_dev,
 7164                     "%s: could not add BSS node, error %d\n", __func__, error);
 7165                 return error;
 7166         }
 7167         DPRINTF(sc, IWN_DEBUG_STATE, "%s: setting link quality for node %d\n",
 7168             __func__, node.id);
 7169         if ((error = iwn_set_link_quality(sc, ni)) != 0) {
 7170                 device_printf(sc->sc_dev,
 7171                     "%s: could not setup link quality for node %d, error %d\n",
 7172                     __func__, node.id, error);
 7173                 return error;
 7174         }
 7175 
 7176         if ((error = iwn_init_sensitivity(sc)) != 0) {
 7177                 device_printf(sc->sc_dev,
 7178                     "%s: could not set sensitivity, error %d\n", __func__,
 7179                     error);
 7180                 return error;
 7181         }
 7182         /* Start periodic calibration timer. */
 7183         sc->calib.state = IWN_CALIB_STATE_ASSOC;
 7184         sc->calib_cnt = 0;
 7185         callout_reset(&sc->calib_to, msecs_to_ticks(500), iwn_calib_timeout,
 7186             sc);
 7187 
 7188         /* Link LED always on while associated. */
 7189         iwn_set_led(sc, IWN_LED_LINK, 0, 1);
 7190 
 7191         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 7192 
 7193         return 0;
 7194 }
 7195 
 7196 /*
 7197  * This function is called by upper layer when an ADDBA request is received
 7198  * from another STA and before the ADDBA response is sent.
 7199  */
 7200 static int
 7201 iwn_ampdu_rx_start(struct ieee80211_node *ni, struct ieee80211_rx_ampdu *rap,
 7202     int baparamset, int batimeout, int baseqctl)
 7203 {
 7204 #define MS(_v, _f)      (((_v) & _f) >> _f##_S)
 7205         struct iwn_softc *sc = ni->ni_ic->ic_softc;
 7206         struct iwn_ops *ops = &sc->ops;
 7207         struct iwn_node *wn = (void *)ni;
 7208         struct iwn_node_info node;
 7209         uint16_t ssn;
 7210         uint8_t tid;
 7211         int error;
 7212 
 7213         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 7214 
 7215         tid = MS(le16toh(baparamset), IEEE80211_BAPS_TID);
 7216         ssn = MS(le16toh(baseqctl), IEEE80211_BASEQ_START);
 7217 
 7218         memset(&node, 0, sizeof node);
 7219         node.id = wn->id;
 7220         node.control = IWN_NODE_UPDATE;
 7221         node.flags = IWN_FLAG_SET_ADDBA;
 7222         node.addba_tid = tid;
 7223         node.addba_ssn = htole16(ssn);
 7224         DPRINTF(sc, IWN_DEBUG_RECV, "ADDBA RA=%d TID=%d SSN=%d\n",
 7225             wn->id, tid, ssn);
 7226         error = ops->add_node(sc, &node, 1);
 7227         if (error != 0)
 7228                 return error;
 7229         return sc->sc_ampdu_rx_start(ni, rap, baparamset, batimeout, baseqctl);
 7230 #undef MS
 7231 }
 7232 
 7233 /*
 7234  * This function is called by upper layer on teardown of an HT-immediate
 7235  * Block Ack agreement (eg. uppon receipt of a DELBA frame).
 7236  */
 7237 static void
 7238 iwn_ampdu_rx_stop(struct ieee80211_node *ni, struct ieee80211_rx_ampdu *rap)
 7239 {
 7240         struct ieee80211com *ic = ni->ni_ic;
 7241         struct iwn_softc *sc = ic->ic_softc;
 7242         struct iwn_ops *ops = &sc->ops;
 7243         struct iwn_node *wn = (void *)ni;
 7244         struct iwn_node_info node;
 7245         uint8_t tid;
 7246 
 7247         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 7248 
 7249         /* XXX: tid as an argument */
 7250         for (tid = 0; tid < WME_NUM_TID; tid++) {
 7251                 if (&ni->ni_rx_ampdu[tid] == rap)
 7252                         break;
 7253         }
 7254 
 7255         memset(&node, 0, sizeof node);
 7256         node.id = wn->id;
 7257         node.control = IWN_NODE_UPDATE;
 7258         node.flags = IWN_FLAG_SET_DELBA;
 7259         node.delba_tid = tid;
 7260         DPRINTF(sc, IWN_DEBUG_RECV, "DELBA RA=%d TID=%d\n", wn->id, tid);
 7261         (void)ops->add_node(sc, &node, 1);
 7262         sc->sc_ampdu_rx_stop(ni, rap);
 7263 }
 7264 
 7265 static int
 7266 iwn_addba_request(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
 7267     int dialogtoken, int baparamset, int batimeout)
 7268 {
 7269         struct iwn_softc *sc = ni->ni_ic->ic_softc;
 7270         int qid;
 7271 
 7272         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 7273 
 7274         for (qid = sc->firstaggqueue; qid < sc->ntxqs; qid++) {
 7275                 if (sc->qid2tap[qid] == NULL)
 7276                         break;
 7277         }
 7278         if (qid == sc->ntxqs) {
 7279                 DPRINTF(sc, IWN_DEBUG_XMIT, "%s: not free aggregation queue\n",
 7280                     __func__);
 7281                 return 0;
 7282         }
 7283         tap->txa_private = malloc(sizeof(int), M_DEVBUF, M_NOWAIT);
 7284         if (tap->txa_private == NULL) {
 7285                 device_printf(sc->sc_dev,
 7286                     "%s: failed to alloc TX aggregation structure\n", __func__);
 7287                 return 0;
 7288         }
 7289         sc->qid2tap[qid] = tap;
 7290         *(int *)tap->txa_private = qid;
 7291         return sc->sc_addba_request(ni, tap, dialogtoken, baparamset,
 7292             batimeout);
 7293 }
 7294 
 7295 static int
 7296 iwn_addba_response(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
 7297     int code, int baparamset, int batimeout)
 7298 {
 7299         struct iwn_softc *sc = ni->ni_ic->ic_softc;
 7300         int qid = *(int *)tap->txa_private;
 7301         uint8_t tid = tap->txa_tid;
 7302         int ret;
 7303 
 7304         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 7305 
 7306         if (code == IEEE80211_STATUS_SUCCESS) {
 7307                 ni->ni_txseqs[tid] = tap->txa_start & 0xfff;
 7308                 ret = iwn_ampdu_tx_start(ni->ni_ic, ni, tid);
 7309                 if (ret != 1)
 7310                         return ret;
 7311         } else {
 7312                 sc->qid2tap[qid] = NULL;
 7313                 free(tap->txa_private, M_DEVBUF);
 7314                 tap->txa_private = NULL;
 7315         }
 7316         return sc->sc_addba_response(ni, tap, code, baparamset, batimeout);
 7317 }
 7318 
 7319 /*
 7320  * This function is called by upper layer when an ADDBA response is received
 7321  * from another STA.
 7322  */
 7323 static int
 7324 iwn_ampdu_tx_start(struct ieee80211com *ic, struct ieee80211_node *ni,
 7325     uint8_t tid)
 7326 {
 7327         struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[tid];
 7328         struct iwn_softc *sc = ni->ni_ic->ic_softc;
 7329         struct iwn_ops *ops = &sc->ops;
 7330         struct iwn_node *wn = (void *)ni;
 7331         struct iwn_node_info node;
 7332         int error, qid;
 7333 
 7334         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 7335 
 7336         /* Enable TX for the specified RA/TID. */
 7337         wn->disable_tid &= ~(1 << tid);
 7338         memset(&node, 0, sizeof node);
 7339         node.id = wn->id;
 7340         node.control = IWN_NODE_UPDATE;
 7341         node.flags = IWN_FLAG_SET_DISABLE_TID;
 7342         node.disable_tid = htole16(wn->disable_tid);
 7343         error = ops->add_node(sc, &node, 1);
 7344         if (error != 0)
 7345                 return 0;
 7346 
 7347         if ((error = iwn_nic_lock(sc)) != 0)
 7348                 return 0;
 7349         qid = *(int *)tap->txa_private;
 7350         DPRINTF(sc, IWN_DEBUG_XMIT, "%s: ra=%d tid=%d ssn=%d qid=%d\n",
 7351             __func__, wn->id, tid, tap->txa_start, qid);
 7352         ops->ampdu_tx_start(sc, ni, qid, tid, tap->txa_start & 0xfff);
 7353         iwn_nic_unlock(sc);
 7354 
 7355         iwn_set_link_quality(sc, ni);
 7356         return 1;
 7357 }
 7358 
 7359 static void
 7360 iwn_ampdu_tx_stop(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap)
 7361 {
 7362         struct iwn_softc *sc = ni->ni_ic->ic_softc;
 7363         struct iwn_ops *ops = &sc->ops;
 7364         uint8_t tid = tap->txa_tid;
 7365         int qid;
 7366 
 7367         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 7368 
 7369         sc->sc_addba_stop(ni, tap);
 7370 
 7371         if (tap->txa_private == NULL)
 7372                 return;
 7373 
 7374         qid = *(int *)tap->txa_private;
 7375         if (sc->txq[qid].queued != 0)
 7376                 return;
 7377         if (iwn_nic_lock(sc) != 0)
 7378                 return;
 7379         ops->ampdu_tx_stop(sc, qid, tid, tap->txa_start & 0xfff);
 7380         iwn_nic_unlock(sc);
 7381         sc->qid2tap[qid] = NULL;
 7382         free(tap->txa_private, M_DEVBUF);
 7383         tap->txa_private = NULL;
 7384 }
 7385 
 7386 static void
 7387 iwn4965_ampdu_tx_start(struct iwn_softc *sc, struct ieee80211_node *ni,
 7388     int qid, uint8_t tid, uint16_t ssn)
 7389 {
 7390         struct iwn_node *wn = (void *)ni;
 7391 
 7392         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 7393 
 7394         /* Stop TX scheduler while we're changing its configuration. */
 7395         iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
 7396             IWN4965_TXQ_STATUS_CHGACT);
 7397 
 7398         /* Assign RA/TID translation to the queue. */
 7399         iwn_mem_write_2(sc, sc->sched_base + IWN4965_SCHED_TRANS_TBL(qid),
 7400             wn->id << 4 | tid);
 7401 
 7402         /* Enable chain-building mode for the queue. */
 7403         iwn_prph_setbits(sc, IWN4965_SCHED_QCHAIN_SEL, 1 << qid);
 7404 
 7405         /* Set starting sequence number from the ADDBA request. */
 7406         sc->txq[qid].cur = sc->txq[qid].read = (ssn & 0xff);
 7407         IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
 7408         iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), ssn);
 7409 
 7410         /* Set scheduler window size. */
 7411         iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid),
 7412             IWN_SCHED_WINSZ);
 7413         /* Set scheduler frame limit. */
 7414         iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid) + 4,
 7415             IWN_SCHED_LIMIT << 16);
 7416 
 7417         /* Enable interrupts for the queue. */
 7418         iwn_prph_setbits(sc, IWN4965_SCHED_INTR_MASK, 1 << qid);
 7419 
 7420         /* Mark the queue as active. */
 7421         iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
 7422             IWN4965_TXQ_STATUS_ACTIVE | IWN4965_TXQ_STATUS_AGGR_ENA |
 7423             iwn_tid2fifo[tid] << 1);
 7424 }
 7425 
 7426 static void
 7427 iwn4965_ampdu_tx_stop(struct iwn_softc *sc, int qid, uint8_t tid, uint16_t ssn)
 7428 {
 7429         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 7430 
 7431         /* Stop TX scheduler while we're changing its configuration. */
 7432         iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
 7433             IWN4965_TXQ_STATUS_CHGACT);
 7434 
 7435         /* Set starting sequence number from the ADDBA request. */
 7436         IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
 7437         iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), ssn);
 7438 
 7439         /* Disable interrupts for the queue. */
 7440         iwn_prph_clrbits(sc, IWN4965_SCHED_INTR_MASK, 1 << qid);
 7441 
 7442         /* Mark the queue as inactive. */
 7443         iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
 7444             IWN4965_TXQ_STATUS_INACTIVE | iwn_tid2fifo[tid] << 1);
 7445 }
 7446 
 7447 static void
 7448 iwn5000_ampdu_tx_start(struct iwn_softc *sc, struct ieee80211_node *ni,
 7449     int qid, uint8_t tid, uint16_t ssn)
 7450 {
 7451         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 7452 
 7453         struct iwn_node *wn = (void *)ni;
 7454 
 7455         /* Stop TX scheduler while we're changing its configuration. */
 7456         iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
 7457             IWN5000_TXQ_STATUS_CHGACT);
 7458 
 7459         /* Assign RA/TID translation to the queue. */
 7460         iwn_mem_write_2(sc, sc->sched_base + IWN5000_SCHED_TRANS_TBL(qid),
 7461             wn->id << 4 | tid);
 7462 
 7463         /* Enable chain-building mode for the queue. */
 7464         iwn_prph_setbits(sc, IWN5000_SCHED_QCHAIN_SEL, 1 << qid);
 7465 
 7466         /* Enable aggregation for the queue. */
 7467         iwn_prph_setbits(sc, IWN5000_SCHED_AGGR_SEL, 1 << qid);
 7468 
 7469         /* Set starting sequence number from the ADDBA request. */
 7470         sc->txq[qid].cur = sc->txq[qid].read = (ssn & 0xff);
 7471         IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
 7472         iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), ssn);
 7473 
 7474         /* Set scheduler window size and frame limit. */
 7475         iwn_mem_write(sc, sc->sched_base + IWN5000_SCHED_QUEUE_OFFSET(qid) + 4,
 7476             IWN_SCHED_LIMIT << 16 | IWN_SCHED_WINSZ);
 7477 
 7478         /* Enable interrupts for the queue. */
 7479         iwn_prph_setbits(sc, IWN5000_SCHED_INTR_MASK, 1 << qid);
 7480 
 7481         /* Mark the queue as active. */
 7482         iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
 7483             IWN5000_TXQ_STATUS_ACTIVE | iwn_tid2fifo[tid]);
 7484 }
 7485 
 7486 static void
 7487 iwn5000_ampdu_tx_stop(struct iwn_softc *sc, int qid, uint8_t tid, uint16_t ssn)
 7488 {
 7489         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 7490 
 7491         /* Stop TX scheduler while we're changing its configuration. */
 7492         iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
 7493             IWN5000_TXQ_STATUS_CHGACT);
 7494 
 7495         /* Disable aggregation for the queue. */
 7496         iwn_prph_clrbits(sc, IWN5000_SCHED_AGGR_SEL, 1 << qid);
 7497 
 7498         /* Set starting sequence number from the ADDBA request. */
 7499         IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
 7500         iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), ssn);
 7501 
 7502         /* Disable interrupts for the queue. */
 7503         iwn_prph_clrbits(sc, IWN5000_SCHED_INTR_MASK, 1 << qid);
 7504 
 7505         /* Mark the queue as inactive. */
 7506         iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
 7507             IWN5000_TXQ_STATUS_INACTIVE | iwn_tid2fifo[tid]);
 7508 }
 7509 
 7510 /*
 7511  * Query calibration tables from the initialization firmware.  We do this
 7512  * only once at first boot.  Called from a process context.
 7513  */
 7514 static int
 7515 iwn5000_query_calibration(struct iwn_softc *sc)
 7516 {
 7517         struct iwn5000_calib_config cmd;
 7518         int error;
 7519 
 7520         memset(&cmd, 0, sizeof cmd);
 7521         cmd.ucode.once.enable = htole32(0xffffffff);
 7522         cmd.ucode.once.start  = htole32(0xffffffff);
 7523         cmd.ucode.once.send   = htole32(0xffffffff);
 7524         cmd.ucode.flags       = htole32(0xffffffff);
 7525         DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: sending calibration query\n",
 7526             __func__);
 7527         error = iwn_cmd(sc, IWN5000_CMD_CALIB_CONFIG, &cmd, sizeof cmd, 0);
 7528         if (error != 0)
 7529                 return error;
 7530 
 7531         /* Wait at most two seconds for calibration to complete. */
 7532         if (!(sc->sc_flags & IWN_FLAG_CALIB_DONE))
 7533                 error = msleep(sc, &sc->sc_mtx, PCATCH, "iwncal", 2 * hz);
 7534         return error;
 7535 }
 7536 
 7537 /*
 7538  * Send calibration results to the runtime firmware.  These results were
 7539  * obtained on first boot from the initialization firmware.
 7540  */
 7541 static int
 7542 iwn5000_send_calibration(struct iwn_softc *sc)
 7543 {
 7544         int idx, error;
 7545 
 7546         for (idx = 0; idx < IWN5000_PHY_CALIB_MAX_RESULT; idx++) {
 7547                 if (!(sc->base_params->calib_need & (1<<idx))) {
 7548                         DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 7549                             "No need of calib %d\n",
 7550                             idx);
 7551                         continue; /* no need for this calib */
 7552                 }
 7553                 if (sc->calibcmd[idx].buf == NULL) {
 7554                         DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 7555                             "Need calib idx : %d but no available data\n",
 7556                             idx);
 7557                         continue;
 7558                 }
 7559 
 7560                 DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 7561                     "send calibration result idx=%d len=%d\n", idx,
 7562                     sc->calibcmd[idx].len);
 7563                 error = iwn_cmd(sc, IWN_CMD_PHY_CALIB, sc->calibcmd[idx].buf,
 7564                     sc->calibcmd[idx].len, 0);
 7565                 if (error != 0) {
 7566                         device_printf(sc->sc_dev,
 7567                             "%s: could not send calibration result, error %d\n",
 7568                             __func__, error);
 7569                         return error;
 7570                 }
 7571         }
 7572         return 0;
 7573 }
 7574 
 7575 static int
 7576 iwn5000_send_wimax_coex(struct iwn_softc *sc)
 7577 {
 7578         struct iwn5000_wimax_coex wimax;
 7579 
 7580 #if 0
 7581         if (sc->hw_type == IWN_HW_REV_TYPE_6050) {
 7582                 /* Enable WiMAX coexistence for combo adapters. */
 7583                 wimax.flags =
 7584                     IWN_WIMAX_COEX_ASSOC_WA_UNMASK |
 7585                     IWN_WIMAX_COEX_UNASSOC_WA_UNMASK |
 7586                     IWN_WIMAX_COEX_STA_TABLE_VALID |
 7587                     IWN_WIMAX_COEX_ENABLE;
 7588                 memcpy(wimax.events, iwn6050_wimax_events,
 7589                     sizeof iwn6050_wimax_events);
 7590         } else
 7591 #endif
 7592         {
 7593                 /* Disable WiMAX coexistence. */
 7594                 wimax.flags = 0;
 7595                 memset(wimax.events, 0, sizeof wimax.events);
 7596         }
 7597         DPRINTF(sc, IWN_DEBUG_RESET, "%s: Configuring WiMAX coexistence\n",
 7598             __func__);
 7599         return iwn_cmd(sc, IWN5000_CMD_WIMAX_COEX, &wimax, sizeof wimax, 0);
 7600 }
 7601 
 7602 static int
 7603 iwn5000_crystal_calib(struct iwn_softc *sc)
 7604 {
 7605         struct iwn5000_phy_calib_crystal cmd;
 7606 
 7607         memset(&cmd, 0, sizeof cmd);
 7608         cmd.code = IWN5000_PHY_CALIB_CRYSTAL;
 7609         cmd.ngroups = 1;
 7610         cmd.isvalid = 1;
 7611         cmd.cap_pin[0] = le32toh(sc->eeprom_crystal) & 0xff;
 7612         cmd.cap_pin[1] = (le32toh(sc->eeprom_crystal) >> 16) & 0xff;
 7613         DPRINTF(sc, IWN_DEBUG_CALIBRATE, "sending crystal calibration %d, %d\n",
 7614             cmd.cap_pin[0], cmd.cap_pin[1]);
 7615         return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
 7616 }
 7617 
 7618 static int
 7619 iwn5000_temp_offset_calib(struct iwn_softc *sc)
 7620 {
 7621         struct iwn5000_phy_calib_temp_offset cmd;
 7622 
 7623         memset(&cmd, 0, sizeof cmd);
 7624         cmd.code = IWN5000_PHY_CALIB_TEMP_OFFSET;
 7625         cmd.ngroups = 1;
 7626         cmd.isvalid = 1;
 7627         if (sc->eeprom_temp != 0)
 7628                 cmd.offset = htole16(sc->eeprom_temp);
 7629         else
 7630                 cmd.offset = htole16(IWN_DEFAULT_TEMP_OFFSET);
 7631         DPRINTF(sc, IWN_DEBUG_CALIBRATE, "setting radio sensor offset to %d\n",
 7632             le16toh(cmd.offset));
 7633         return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
 7634 }
 7635 
 7636 static int
 7637 iwn5000_temp_offset_calibv2(struct iwn_softc *sc)
 7638 {
 7639         struct iwn5000_phy_calib_temp_offsetv2 cmd;
 7640 
 7641         memset(&cmd, 0, sizeof cmd);
 7642         cmd.code = IWN5000_PHY_CALIB_TEMP_OFFSET;
 7643         cmd.ngroups = 1;
 7644         cmd.isvalid = 1;
 7645         if (sc->eeprom_temp != 0) {
 7646                 cmd.offset_low = htole16(sc->eeprom_temp);
 7647                 cmd.offset_high = htole16(sc->eeprom_temp_high);
 7648         } else {
 7649                 cmd.offset_low = htole16(IWN_DEFAULT_TEMP_OFFSET);
 7650                 cmd.offset_high = htole16(IWN_DEFAULT_TEMP_OFFSET);
 7651         }
 7652         cmd.burnt_voltage_ref = htole16(sc->eeprom_voltage);
 7653 
 7654         DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 7655             "setting radio sensor low offset to %d, high offset to %d, voltage to %d\n",
 7656             le16toh(cmd.offset_low),
 7657             le16toh(cmd.offset_high),
 7658             le16toh(cmd.burnt_voltage_ref));
 7659 
 7660         return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
 7661 }
 7662 
 7663 /*
 7664  * This function is called after the runtime firmware notifies us of its
 7665  * readiness (called in a process context).
 7666  */
 7667 static int
 7668 iwn4965_post_alive(struct iwn_softc *sc)
 7669 {
 7670         int error, qid;
 7671 
 7672         if ((error = iwn_nic_lock(sc)) != 0)
 7673                 return error;
 7674 
 7675         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 7676 
 7677         /* Clear TX scheduler state in SRAM. */
 7678         sc->sched_base = iwn_prph_read(sc, IWN_SCHED_SRAM_ADDR);
 7679         iwn_mem_set_region_4(sc, sc->sched_base + IWN4965_SCHED_CTX_OFF, 0,
 7680             IWN4965_SCHED_CTX_LEN / sizeof (uint32_t));
 7681 
 7682         /* Set physical address of TX scheduler rings (1KB aligned). */
 7683         iwn_prph_write(sc, IWN4965_SCHED_DRAM_ADDR, sc->sched_dma.paddr >> 10);
 7684 
 7685         IWN_SETBITS(sc, IWN_FH_TX_CHICKEN, IWN_FH_TX_CHICKEN_SCHED_RETRY);
 7686 
 7687         /* Disable chain mode for all our 16 queues. */
 7688         iwn_prph_write(sc, IWN4965_SCHED_QCHAIN_SEL, 0);
 7689 
 7690         for (qid = 0; qid < IWN4965_NTXQUEUES; qid++) {
 7691                 iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), 0);
 7692                 IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | 0);
 7693 
 7694                 /* Set scheduler window size. */
 7695                 iwn_mem_write(sc, sc->sched_base +
 7696                     IWN4965_SCHED_QUEUE_OFFSET(qid), IWN_SCHED_WINSZ);
 7697                 /* Set scheduler frame limit. */
 7698                 iwn_mem_write(sc, sc->sched_base +
 7699                     IWN4965_SCHED_QUEUE_OFFSET(qid) + 4,
 7700                     IWN_SCHED_LIMIT << 16);
 7701         }
 7702 
 7703         /* Enable interrupts for all our 16 queues. */
 7704         iwn_prph_write(sc, IWN4965_SCHED_INTR_MASK, 0xffff);
 7705         /* Identify TX FIFO rings (0-7). */
 7706         iwn_prph_write(sc, IWN4965_SCHED_TXFACT, 0xff);
 7707 
 7708         /* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
 7709         for (qid = 0; qid < 7; qid++) {
 7710                 static uint8_t qid2fifo[] = { 3, 2, 1, 0, 4, 5, 6 };
 7711                 iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
 7712                     IWN4965_TXQ_STATUS_ACTIVE | qid2fifo[qid] << 1);
 7713         }
 7714         iwn_nic_unlock(sc);
 7715         return 0;
 7716 }
 7717 
 7718 /*
 7719  * This function is called after the initialization or runtime firmware
 7720  * notifies us of its readiness (called in a process context).
 7721  */
 7722 static int
 7723 iwn5000_post_alive(struct iwn_softc *sc)
 7724 {
 7725         int error, qid;
 7726 
 7727         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 7728 
 7729         /* Switch to using ICT interrupt mode. */
 7730         iwn5000_ict_reset(sc);
 7731 
 7732         if ((error = iwn_nic_lock(sc)) != 0){
 7733                 DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end in error\n", __func__);
 7734                 return error;
 7735         }
 7736 
 7737         /* Clear TX scheduler state in SRAM. */
 7738         sc->sched_base = iwn_prph_read(sc, IWN_SCHED_SRAM_ADDR);
 7739         iwn_mem_set_region_4(sc, sc->sched_base + IWN5000_SCHED_CTX_OFF, 0,
 7740             IWN5000_SCHED_CTX_LEN / sizeof (uint32_t));
 7741 
 7742         /* Set physical address of TX scheduler rings (1KB aligned). */
 7743         iwn_prph_write(sc, IWN5000_SCHED_DRAM_ADDR, sc->sched_dma.paddr >> 10);
 7744 
 7745         IWN_SETBITS(sc, IWN_FH_TX_CHICKEN, IWN_FH_TX_CHICKEN_SCHED_RETRY);
 7746 
 7747         /* Enable chain mode for all queues, except command queue. */
 7748         if (sc->sc_flags & IWN_FLAG_PAN_SUPPORT)
 7749                 iwn_prph_write(sc, IWN5000_SCHED_QCHAIN_SEL, 0xfffdf);
 7750         else
 7751                 iwn_prph_write(sc, IWN5000_SCHED_QCHAIN_SEL, 0xfffef);
 7752         iwn_prph_write(sc, IWN5000_SCHED_AGGR_SEL, 0);
 7753 
 7754         for (qid = 0; qid < IWN5000_NTXQUEUES; qid++) {
 7755                 iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), 0);
 7756                 IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | 0);
 7757 
 7758                 iwn_mem_write(sc, sc->sched_base +
 7759                     IWN5000_SCHED_QUEUE_OFFSET(qid), 0);
 7760                 /* Set scheduler window size and frame limit. */
 7761                 iwn_mem_write(sc, sc->sched_base +
 7762                     IWN5000_SCHED_QUEUE_OFFSET(qid) + 4,
 7763                     IWN_SCHED_LIMIT << 16 | IWN_SCHED_WINSZ);
 7764         }
 7765 
 7766         /* Enable interrupts for all our 20 queues. */
 7767         iwn_prph_write(sc, IWN5000_SCHED_INTR_MASK, 0xfffff);
 7768         /* Identify TX FIFO rings (0-7). */
 7769         iwn_prph_write(sc, IWN5000_SCHED_TXFACT, 0xff);
 7770 
 7771         /* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
 7772         if (sc->sc_flags & IWN_FLAG_PAN_SUPPORT) {
 7773                 /* Mark TX rings as active. */
 7774                 for (qid = 0; qid < 11; qid++) {
 7775                         static uint8_t qid2fifo[] = { 3, 2, 1, 0, 0, 4, 2, 5, 4, 7, 5 };
 7776                         iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
 7777                             IWN5000_TXQ_STATUS_ACTIVE | qid2fifo[qid]);
 7778                 }
 7779         } else {
 7780                 /* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
 7781                 for (qid = 0; qid < 7; qid++) {
 7782                         static uint8_t qid2fifo[] = { 3, 2, 1, 0, 7, 5, 6 };
 7783                         iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
 7784                             IWN5000_TXQ_STATUS_ACTIVE | qid2fifo[qid]);
 7785                 }
 7786         }
 7787         iwn_nic_unlock(sc);
 7788 
 7789         /* Configure WiMAX coexistence for combo adapters. */
 7790         error = iwn5000_send_wimax_coex(sc);
 7791         if (error != 0) {
 7792                 device_printf(sc->sc_dev,
 7793                     "%s: could not configure WiMAX coexistence, error %d\n",
 7794                     __func__, error);
 7795                 return error;
 7796         }
 7797         if (sc->hw_type != IWN_HW_REV_TYPE_5150) {
 7798                 /* Perform crystal calibration. */
 7799                 error = iwn5000_crystal_calib(sc);
 7800                 if (error != 0) {
 7801                         device_printf(sc->sc_dev,
 7802                             "%s: crystal calibration failed, error %d\n",
 7803                             __func__, error);
 7804                         return error;
 7805                 }
 7806         }
 7807         if (!(sc->sc_flags & IWN_FLAG_CALIB_DONE)) {
 7808                 /* Query calibration from the initialization firmware. */
 7809                 if ((error = iwn5000_query_calibration(sc)) != 0) {
 7810                         device_printf(sc->sc_dev,
 7811                             "%s: could not query calibration, error %d\n",
 7812                             __func__, error);
 7813                         return error;
 7814                 }
 7815                 /*
 7816                  * We have the calibration results now, reboot with the
 7817                  * runtime firmware (call ourselves recursively!)
 7818                  */
 7819                 iwn_hw_stop(sc);
 7820                 error = iwn_hw_init(sc);
 7821         } else {
 7822                 /* Send calibration results to runtime firmware. */
 7823                 error = iwn5000_send_calibration(sc);
 7824         }
 7825 
 7826         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 7827 
 7828         return error;
 7829 }
 7830 
 7831 /*
 7832  * The firmware boot code is small and is intended to be copied directly into
 7833  * the NIC internal memory (no DMA transfer).
 7834  */
 7835 static int
 7836 iwn4965_load_bootcode(struct iwn_softc *sc, const uint8_t *ucode, int size)
 7837 {
 7838         int error, ntries;
 7839 
 7840         size /= sizeof (uint32_t);
 7841 
 7842         if ((error = iwn_nic_lock(sc)) != 0)
 7843                 return error;
 7844 
 7845         /* Copy microcode image into NIC memory. */
 7846         iwn_prph_write_region_4(sc, IWN_BSM_SRAM_BASE,
 7847             (const uint32_t *)ucode, size);
 7848 
 7849         iwn_prph_write(sc, IWN_BSM_WR_MEM_SRC, 0);
 7850         iwn_prph_write(sc, IWN_BSM_WR_MEM_DST, IWN_FW_TEXT_BASE);
 7851         iwn_prph_write(sc, IWN_BSM_WR_DWCOUNT, size);
 7852 
 7853         /* Start boot load now. */
 7854         iwn_prph_write(sc, IWN_BSM_WR_CTRL, IWN_BSM_WR_CTRL_START);
 7855 
 7856         /* Wait for transfer to complete. */
 7857         for (ntries = 0; ntries < 1000; ntries++) {
 7858                 if (!(iwn_prph_read(sc, IWN_BSM_WR_CTRL) &
 7859                     IWN_BSM_WR_CTRL_START))
 7860                         break;
 7861                 DELAY(10);
 7862         }
 7863         if (ntries == 1000) {
 7864                 device_printf(sc->sc_dev, "%s: could not load boot firmware\n",
 7865                     __func__);
 7866                 iwn_nic_unlock(sc);
 7867                 return ETIMEDOUT;
 7868         }
 7869 
 7870         /* Enable boot after power up. */
 7871         iwn_prph_write(sc, IWN_BSM_WR_CTRL, IWN_BSM_WR_CTRL_START_EN);
 7872 
 7873         iwn_nic_unlock(sc);
 7874         return 0;
 7875 }
 7876 
 7877 static int
 7878 iwn4965_load_firmware(struct iwn_softc *sc)
 7879 {
 7880         struct iwn_fw_info *fw = &sc->fw;
 7881         struct iwn_dma_info *dma = &sc->fw_dma;
 7882         int error;
 7883 
 7884         /* Copy initialization sections into pre-allocated DMA-safe memory. */
 7885         memcpy(dma->vaddr, fw->init.data, fw->init.datasz);
 7886         bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
 7887         memcpy(dma->vaddr + IWN4965_FW_DATA_MAXSZ,
 7888             fw->init.text, fw->init.textsz);
 7889         bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
 7890 
 7891         /* Tell adapter where to find initialization sections. */
 7892         if ((error = iwn_nic_lock(sc)) != 0)
 7893                 return error;
 7894         iwn_prph_write(sc, IWN_BSM_DRAM_DATA_ADDR, dma->paddr >> 4);
 7895         iwn_prph_write(sc, IWN_BSM_DRAM_DATA_SIZE, fw->init.datasz);
 7896         iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_ADDR,
 7897             (dma->paddr + IWN4965_FW_DATA_MAXSZ) >> 4);
 7898         iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_SIZE, fw->init.textsz);
 7899         iwn_nic_unlock(sc);
 7900 
 7901         /* Load firmware boot code. */
 7902         error = iwn4965_load_bootcode(sc, fw->boot.text, fw->boot.textsz);
 7903         if (error != 0) {
 7904                 device_printf(sc->sc_dev, "%s: could not load boot firmware\n",
 7905                     __func__);
 7906                 return error;
 7907         }
 7908         /* Now press "execute". */
 7909         IWN_WRITE(sc, IWN_RESET, 0);
 7910 
 7911         /* Wait at most one second for first alive notification. */
 7912         if ((error = msleep(sc, &sc->sc_mtx, PCATCH, "iwninit", hz)) != 0) {
 7913                 device_printf(sc->sc_dev,
 7914                     "%s: timeout waiting for adapter to initialize, error %d\n",
 7915                     __func__, error);
 7916                 return error;
 7917         }
 7918 
 7919         /* Retrieve current temperature for initial TX power calibration. */
 7920         sc->rawtemp = sc->ucode_info.temp[3].chan20MHz;
 7921         sc->temp = iwn4965_get_temperature(sc);
 7922 
 7923         /* Copy runtime sections into pre-allocated DMA-safe memory. */
 7924         memcpy(dma->vaddr, fw->main.data, fw->main.datasz);
 7925         bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
 7926         memcpy(dma->vaddr + IWN4965_FW_DATA_MAXSZ,
 7927             fw->main.text, fw->main.textsz);
 7928         bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
 7929 
 7930         /* Tell adapter where to find runtime sections. */
 7931         if ((error = iwn_nic_lock(sc)) != 0)
 7932                 return error;
 7933         iwn_prph_write(sc, IWN_BSM_DRAM_DATA_ADDR, dma->paddr >> 4);
 7934         iwn_prph_write(sc, IWN_BSM_DRAM_DATA_SIZE, fw->main.datasz);
 7935         iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_ADDR,
 7936             (dma->paddr + IWN4965_FW_DATA_MAXSZ) >> 4);
 7937         iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_SIZE,
 7938             IWN_FW_UPDATED | fw->main.textsz);
 7939         iwn_nic_unlock(sc);
 7940 
 7941         return 0;
 7942 }
 7943 
 7944 static int
 7945 iwn5000_load_firmware_section(struct iwn_softc *sc, uint32_t dst,
 7946     const uint8_t *section, int size)
 7947 {
 7948         struct iwn_dma_info *dma = &sc->fw_dma;
 7949         int error;
 7950 
 7951         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 7952 
 7953         /* Copy firmware section into pre-allocated DMA-safe memory. */
 7954         memcpy(dma->vaddr, section, size);
 7955         bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
 7956 
 7957         if ((error = iwn_nic_lock(sc)) != 0)
 7958                 return error;
 7959 
 7960         IWN_WRITE(sc, IWN_FH_TX_CONFIG(IWN_SRVC_DMACHNL),
 7961             IWN_FH_TX_CONFIG_DMA_PAUSE);
 7962 
 7963         IWN_WRITE(sc, IWN_FH_SRAM_ADDR(IWN_SRVC_DMACHNL), dst);
 7964         IWN_WRITE(sc, IWN_FH_TFBD_CTRL0(IWN_SRVC_DMACHNL),
 7965             IWN_LOADDR(dma->paddr));
 7966         IWN_WRITE(sc, IWN_FH_TFBD_CTRL1(IWN_SRVC_DMACHNL),
 7967             IWN_HIADDR(dma->paddr) << 28 | size);
 7968         IWN_WRITE(sc, IWN_FH_TXBUF_STATUS(IWN_SRVC_DMACHNL),
 7969             IWN_FH_TXBUF_STATUS_TBNUM(1) |
 7970             IWN_FH_TXBUF_STATUS_TBIDX(1) |
 7971             IWN_FH_TXBUF_STATUS_TFBD_VALID);
 7972 
 7973         /* Kick Flow Handler to start DMA transfer. */
 7974         IWN_WRITE(sc, IWN_FH_TX_CONFIG(IWN_SRVC_DMACHNL),
 7975             IWN_FH_TX_CONFIG_DMA_ENA | IWN_FH_TX_CONFIG_CIRQ_HOST_ENDTFD);
 7976 
 7977         iwn_nic_unlock(sc);
 7978 
 7979         /* Wait at most five seconds for FH DMA transfer to complete. */
 7980         return msleep(sc, &sc->sc_mtx, PCATCH, "iwninit", 5 * hz);
 7981 }
 7982 
 7983 static int
 7984 iwn5000_load_firmware(struct iwn_softc *sc)
 7985 {
 7986         struct iwn_fw_part *fw;
 7987         int error;
 7988 
 7989         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 7990 
 7991         /* Load the initialization firmware on first boot only. */
 7992         fw = (sc->sc_flags & IWN_FLAG_CALIB_DONE) ?
 7993             &sc->fw.main : &sc->fw.init;
 7994 
 7995         error = iwn5000_load_firmware_section(sc, IWN_FW_TEXT_BASE,
 7996             fw->text, fw->textsz);
 7997         if (error != 0) {
 7998                 device_printf(sc->sc_dev,
 7999                     "%s: could not load firmware %s section, error %d\n",
 8000                     __func__, ".text", error);
 8001                 return error;
 8002         }
 8003         error = iwn5000_load_firmware_section(sc, IWN_FW_DATA_BASE,
 8004             fw->data, fw->datasz);
 8005         if (error != 0) {
 8006                 device_printf(sc->sc_dev,
 8007                     "%s: could not load firmware %s section, error %d\n",
 8008                     __func__, ".data", error);
 8009                 return error;
 8010         }
 8011 
 8012         /* Now press "execute". */
 8013         IWN_WRITE(sc, IWN_RESET, 0);
 8014         return 0;
 8015 }
 8016 
 8017 /*
 8018  * Extract text and data sections from a legacy firmware image.
 8019  */
 8020 static int
 8021 iwn_read_firmware_leg(struct iwn_softc *sc, struct iwn_fw_info *fw)
 8022 {
 8023         const uint32_t *ptr;
 8024         size_t hdrlen = 24;
 8025         uint32_t rev;
 8026 
 8027         ptr = (const uint32_t *)fw->data;
 8028         rev = le32toh(*ptr++);
 8029 
 8030         sc->ucode_rev = rev;
 8031 
 8032         /* Check firmware API version. */
 8033         if (IWN_FW_API(rev) <= 1) {
 8034                 device_printf(sc->sc_dev,
 8035                     "%s: bad firmware, need API version >=2\n", __func__);
 8036                 return EINVAL;
 8037         }
 8038         if (IWN_FW_API(rev) >= 3) {
 8039                 /* Skip build number (version 2 header). */
 8040                 hdrlen += 4;
 8041                 ptr++;
 8042         }
 8043         if (fw->size < hdrlen) {
 8044                 device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
 8045                     __func__, fw->size);
 8046                 return EINVAL;
 8047         }
 8048         fw->main.textsz = le32toh(*ptr++);
 8049         fw->main.datasz = le32toh(*ptr++);
 8050         fw->init.textsz = le32toh(*ptr++);
 8051         fw->init.datasz = le32toh(*ptr++);
 8052         fw->boot.textsz = le32toh(*ptr++);
 8053 
 8054         /* Check that all firmware sections fit. */
 8055         if (fw->size < hdrlen + fw->main.textsz + fw->main.datasz +
 8056             fw->init.textsz + fw->init.datasz + fw->boot.textsz) {
 8057                 device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
 8058                     __func__, fw->size);
 8059                 return EINVAL;
 8060         }
 8061 
 8062         /* Get pointers to firmware sections. */
 8063         fw->main.text = (const uint8_t *)ptr;
 8064         fw->main.data = fw->main.text + fw->main.textsz;
 8065         fw->init.text = fw->main.data + fw->main.datasz;
 8066         fw->init.data = fw->init.text + fw->init.textsz;
 8067         fw->boot.text = fw->init.data + fw->init.datasz;
 8068         return 0;
 8069 }
 8070 
 8071 /*
 8072  * Extract text and data sections from a TLV firmware image.
 8073  */
 8074 static int
 8075 iwn_read_firmware_tlv(struct iwn_softc *sc, struct iwn_fw_info *fw,
 8076     uint16_t alt)
 8077 {
 8078         const struct iwn_fw_tlv_hdr *hdr;
 8079         const struct iwn_fw_tlv *tlv;
 8080         const uint8_t *ptr, *end;
 8081         uint64_t altmask;
 8082         uint32_t len, tmp;
 8083 
 8084         if (fw->size < sizeof (*hdr)) {
 8085                 device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
 8086                     __func__, fw->size);
 8087                 return EINVAL;
 8088         }
 8089         hdr = (const struct iwn_fw_tlv_hdr *)fw->data;
 8090         if (hdr->signature != htole32(IWN_FW_SIGNATURE)) {
 8091                 device_printf(sc->sc_dev, "%s: bad firmware signature 0x%08x\n",
 8092                     __func__, le32toh(hdr->signature));
 8093                 return EINVAL;
 8094         }
 8095         DPRINTF(sc, IWN_DEBUG_RESET, "FW: \"%.64s\", build 0x%x\n", hdr->descr,
 8096             le32toh(hdr->build));
 8097         sc->ucode_rev = le32toh(hdr->rev);
 8098 
 8099         /*
 8100          * Select the closest supported alternative that is less than
 8101          * or equal to the specified one.
 8102          */
 8103         altmask = le64toh(hdr->altmask);
 8104         while (alt > 0 && !(altmask & (1ULL << alt)))
 8105                 alt--;  /* Downgrade. */
 8106         DPRINTF(sc, IWN_DEBUG_RESET, "using alternative %d\n", alt);
 8107 
 8108         ptr = (const uint8_t *)(hdr + 1);
 8109         end = (const uint8_t *)(fw->data + fw->size);
 8110 
 8111         /* Parse type-length-value fields. */
 8112         while (ptr + sizeof (*tlv) <= end) {
 8113                 tlv = (const struct iwn_fw_tlv *)ptr;
 8114                 len = le32toh(tlv->len);
 8115 
 8116                 ptr += sizeof (*tlv);
 8117                 if (ptr + len > end) {
 8118                         device_printf(sc->sc_dev,
 8119                             "%s: firmware too short: %zu bytes\n", __func__,
 8120                             fw->size);
 8121                         return EINVAL;
 8122                 }
 8123                 /* Skip other alternatives. */
 8124                 if (tlv->alt != 0 && tlv->alt != htole16(alt))
 8125                         goto next;
 8126 
 8127                 switch (le16toh(tlv->type)) {
 8128                 case IWN_FW_TLV_MAIN_TEXT:
 8129                         fw->main.text = ptr;
 8130                         fw->main.textsz = len;
 8131                         break;
 8132                 case IWN_FW_TLV_MAIN_DATA:
 8133                         fw->main.data = ptr;
 8134                         fw->main.datasz = len;
 8135                         break;
 8136                 case IWN_FW_TLV_INIT_TEXT:
 8137                         fw->init.text = ptr;
 8138                         fw->init.textsz = len;
 8139                         break;
 8140                 case IWN_FW_TLV_INIT_DATA:
 8141                         fw->init.data = ptr;
 8142                         fw->init.datasz = len;
 8143                         break;
 8144                 case IWN_FW_TLV_BOOT_TEXT:
 8145                         fw->boot.text = ptr;
 8146                         fw->boot.textsz = len;
 8147                         break;
 8148                 case IWN_FW_TLV_ENH_SENS:
 8149                         if (!len)
 8150                                 sc->sc_flags |= IWN_FLAG_ENH_SENS;
 8151                         break;
 8152                 case IWN_FW_TLV_PHY_CALIB:
 8153                         tmp = le32toh(*ptr);
 8154                         if (tmp < 253) {
 8155                                 sc->reset_noise_gain = tmp;
 8156                                 sc->noise_gain = tmp + 1;
 8157                         }
 8158                         break;
 8159                 case IWN_FW_TLV_PAN:
 8160                         sc->sc_flags |= IWN_FLAG_PAN_SUPPORT;
 8161                         DPRINTF(sc, IWN_DEBUG_RESET,
 8162                             "PAN Support found: %d\n", 1);
 8163                         break;
 8164                 case IWN_FW_TLV_FLAGS:
 8165                         if (len < sizeof(uint32_t))
 8166                                 break;
 8167                         if (len % sizeof(uint32_t))
 8168                                 break;
 8169                         sc->tlv_feature_flags = le32toh(*ptr);
 8170                         DPRINTF(sc, IWN_DEBUG_RESET,
 8171                             "%s: feature: 0x%08x\n",
 8172                             __func__,
 8173                             sc->tlv_feature_flags);
 8174                         break;
 8175                 case IWN_FW_TLV_PBREQ_MAXLEN:
 8176                 case IWN_FW_TLV_RUNT_EVTLOG_PTR:
 8177                 case IWN_FW_TLV_RUNT_EVTLOG_SIZE:
 8178                 case IWN_FW_TLV_RUNT_ERRLOG_PTR:
 8179                 case IWN_FW_TLV_INIT_EVTLOG_PTR:
 8180                 case IWN_FW_TLV_INIT_EVTLOG_SIZE:
 8181                 case IWN_FW_TLV_INIT_ERRLOG_PTR:
 8182                 case IWN_FW_TLV_WOWLAN_INST:
 8183                 case IWN_FW_TLV_WOWLAN_DATA:
 8184                         DPRINTF(sc, IWN_DEBUG_RESET,
 8185                             "TLV type %d recognized but not handled\n",
 8186                             le16toh(tlv->type));
 8187                         break;
 8188                 default:
 8189                         DPRINTF(sc, IWN_DEBUG_RESET,
 8190                             "TLV type %d not handled\n", le16toh(tlv->type));
 8191                         break;
 8192                 }
 8193  next:          /* TLV fields are 32-bit aligned. */
 8194                 ptr += (len + 3) & ~3;
 8195         }
 8196         return 0;
 8197 }
 8198 
 8199 static int
 8200 iwn_read_firmware(struct iwn_softc *sc)
 8201 {
 8202         struct iwn_fw_info *fw = &sc->fw;
 8203         int error;
 8204 
 8205         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 8206 
 8207         IWN_UNLOCK(sc);
 8208 
 8209         memset(fw, 0, sizeof (*fw));
 8210 
 8211         /* Read firmware image from filesystem. */
 8212         sc->fw_fp = firmware_get(sc->fwname);
 8213         if (sc->fw_fp == NULL) {
 8214                 device_printf(sc->sc_dev, "%s: could not read firmware %s\n",
 8215                     __func__, sc->fwname);
 8216                 IWN_LOCK(sc);
 8217                 return EINVAL;
 8218         }
 8219         IWN_LOCK(sc);
 8220 
 8221         fw->size = sc->fw_fp->datasize;
 8222         fw->data = (const uint8_t *)sc->fw_fp->data;
 8223         if (fw->size < sizeof (uint32_t)) {
 8224                 device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
 8225                     __func__, fw->size);
 8226                 error = EINVAL;
 8227                 goto fail;
 8228         }
 8229 
 8230         /* Retrieve text and data sections. */
 8231         if (*(const uint32_t *)fw->data != 0)   /* Legacy image. */
 8232                 error = iwn_read_firmware_leg(sc, fw);
 8233         else
 8234                 error = iwn_read_firmware_tlv(sc, fw, 1);
 8235         if (error != 0) {
 8236                 device_printf(sc->sc_dev,
 8237                     "%s: could not read firmware sections, error %d\n",
 8238                     __func__, error);
 8239                 goto fail;
 8240         }
 8241 
 8242         device_printf(sc->sc_dev, "%s: ucode rev=0x%08x\n", __func__, sc->ucode_rev);
 8243 
 8244         /* Make sure text and data sections fit in hardware memory. */
 8245         if (fw->main.textsz > sc->fw_text_maxsz ||
 8246             fw->main.datasz > sc->fw_data_maxsz ||
 8247             fw->init.textsz > sc->fw_text_maxsz ||
 8248             fw->init.datasz > sc->fw_data_maxsz ||
 8249             fw->boot.textsz > IWN_FW_BOOT_TEXT_MAXSZ ||
 8250             (fw->boot.textsz & 3) != 0) {
 8251                 device_printf(sc->sc_dev, "%s: firmware sections too large\n",
 8252                     __func__);
 8253                 error = EINVAL;
 8254                 goto fail;
 8255         }
 8256 
 8257         /* We can proceed with loading the firmware. */
 8258         return 0;
 8259 
 8260 fail:   iwn_unload_firmware(sc);
 8261         return error;
 8262 }
 8263 
 8264 static void
 8265 iwn_unload_firmware(struct iwn_softc *sc)
 8266 {
 8267         firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
 8268         sc->fw_fp = NULL;
 8269 }
 8270 
 8271 static int
 8272 iwn_clock_wait(struct iwn_softc *sc)
 8273 {
 8274         int ntries;
 8275 
 8276         /* Set "initialization complete" bit. */
 8277         IWN_SETBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_INIT_DONE);
 8278 
 8279         /* Wait for clock stabilization. */
 8280         for (ntries = 0; ntries < 2500; ntries++) {
 8281                 if (IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_MAC_CLOCK_READY)
 8282                         return 0;
 8283                 DELAY(10);
 8284         }
 8285         device_printf(sc->sc_dev,
 8286             "%s: timeout waiting for clock stabilization\n", __func__);
 8287         return ETIMEDOUT;
 8288 }
 8289 
 8290 static int
 8291 iwn_apm_init(struct iwn_softc *sc)
 8292 {
 8293         uint32_t reg;
 8294         int error;
 8295 
 8296         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 8297 
 8298         /* Disable L0s exit timer (NMI bug workaround). */
 8299         IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_DIS_L0S_TIMER);
 8300         /* Don't wait for ICH L0s (ICH bug workaround). */
 8301         IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_L1A_NO_L0S_RX);
 8302 
 8303         /* Set FH wait threshold to max (HW bug under stress workaround). */
 8304         IWN_SETBITS(sc, IWN_DBG_HPET_MEM, 0xffff0000);
 8305 
 8306         /* Enable HAP INTA to move adapter from L1a to L0s. */
 8307         IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_HAP_WAKE_L1A);
 8308 
 8309         /* Retrieve PCIe Active State Power Management (ASPM). */
 8310         reg = pci_read_config(sc->sc_dev, sc->sc_cap_off + PCIER_LINK_CTL, 4);
 8311         /* Workaround for HW instability in PCIe L0->L0s->L1 transition. */
 8312         if (reg & PCIEM_LINK_CTL_ASPMC_L1)      /* L1 Entry enabled. */
 8313                 IWN_SETBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA);
 8314         else
 8315                 IWN_CLRBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA);
 8316 
 8317         if (sc->base_params->pll_cfg_val)
 8318                 IWN_SETBITS(sc, IWN_ANA_PLL, sc->base_params->pll_cfg_val);
 8319 
 8320         /* Wait for clock stabilization before accessing prph. */
 8321         if ((error = iwn_clock_wait(sc)) != 0)
 8322                 return error;
 8323 
 8324         if ((error = iwn_nic_lock(sc)) != 0)
 8325                 return error;
 8326         if (sc->hw_type == IWN_HW_REV_TYPE_4965) {
 8327                 /* Enable DMA and BSM (Bootstrap State Machine). */
 8328                 iwn_prph_write(sc, IWN_APMG_CLK_EN,
 8329                     IWN_APMG_CLK_CTRL_DMA_CLK_RQT |
 8330                     IWN_APMG_CLK_CTRL_BSM_CLK_RQT);
 8331         } else {
 8332                 /* Enable DMA. */
 8333                 iwn_prph_write(sc, IWN_APMG_CLK_EN,
 8334                     IWN_APMG_CLK_CTRL_DMA_CLK_RQT);
 8335         }
 8336         DELAY(20);
 8337         /* Disable L1-Active. */
 8338         iwn_prph_setbits(sc, IWN_APMG_PCI_STT, IWN_APMG_PCI_STT_L1A_DIS);
 8339         iwn_nic_unlock(sc);
 8340 
 8341         return 0;
 8342 }
 8343 
 8344 static void
 8345 iwn_apm_stop_master(struct iwn_softc *sc)
 8346 {
 8347         int ntries;
 8348 
 8349         /* Stop busmaster DMA activity. */
 8350         IWN_SETBITS(sc, IWN_RESET, IWN_RESET_STOP_MASTER);
 8351         for (ntries = 0; ntries < 100; ntries++) {
 8352                 if (IWN_READ(sc, IWN_RESET) & IWN_RESET_MASTER_DISABLED)
 8353                         return;
 8354                 DELAY(10);
 8355         }
 8356         device_printf(sc->sc_dev, "%s: timeout waiting for master\n", __func__);
 8357 }
 8358 
 8359 static void
 8360 iwn_apm_stop(struct iwn_softc *sc)
 8361 {
 8362         iwn_apm_stop_master(sc);
 8363 
 8364         /* Reset the entire device. */
 8365         IWN_SETBITS(sc, IWN_RESET, IWN_RESET_SW);
 8366         DELAY(10);
 8367         /* Clear "initialization complete" bit. */
 8368         IWN_CLRBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_INIT_DONE);
 8369 }
 8370 
 8371 static int
 8372 iwn4965_nic_config(struct iwn_softc *sc)
 8373 {
 8374         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 8375 
 8376         if (IWN_RFCFG_TYPE(sc->rfcfg) == 1) {
 8377                 /*
 8378                  * I don't believe this to be correct but this is what the
 8379                  * vendor driver is doing. Probably the bits should not be
 8380                  * shifted in IWN_RFCFG_*.
 8381                  */
 8382                 IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
 8383                     IWN_RFCFG_TYPE(sc->rfcfg) |
 8384                     IWN_RFCFG_STEP(sc->rfcfg) |
 8385                     IWN_RFCFG_DASH(sc->rfcfg));
 8386         }
 8387         IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
 8388             IWN_HW_IF_CONFIG_RADIO_SI | IWN_HW_IF_CONFIG_MAC_SI);
 8389         return 0;
 8390 }
 8391 
 8392 static int
 8393 iwn5000_nic_config(struct iwn_softc *sc)
 8394 {
 8395         uint32_t tmp;
 8396         int error;
 8397 
 8398         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 8399 
 8400         if (IWN_RFCFG_TYPE(sc->rfcfg) < 3) {
 8401                 IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
 8402                     IWN_RFCFG_TYPE(sc->rfcfg) |
 8403                     IWN_RFCFG_STEP(sc->rfcfg) |
 8404                     IWN_RFCFG_DASH(sc->rfcfg));
 8405         }
 8406         IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
 8407             IWN_HW_IF_CONFIG_RADIO_SI | IWN_HW_IF_CONFIG_MAC_SI);
 8408 
 8409         if ((error = iwn_nic_lock(sc)) != 0)
 8410                 return error;
 8411         iwn_prph_setbits(sc, IWN_APMG_PS, IWN_APMG_PS_EARLY_PWROFF_DIS);
 8412 
 8413         if (sc->hw_type == IWN_HW_REV_TYPE_1000) {
 8414                 /*
 8415                  * Select first Switching Voltage Regulator (1.32V) to
 8416                  * solve a stability issue related to noisy DC2DC line
 8417                  * in the silicon of 1000 Series.
 8418                  */
 8419                 tmp = iwn_prph_read(sc, IWN_APMG_DIGITAL_SVR);
 8420                 tmp &= ~IWN_APMG_DIGITAL_SVR_VOLTAGE_MASK;
 8421                 tmp |= IWN_APMG_DIGITAL_SVR_VOLTAGE_1_32;
 8422                 iwn_prph_write(sc, IWN_APMG_DIGITAL_SVR, tmp);
 8423         }
 8424         iwn_nic_unlock(sc);
 8425 
 8426         if (sc->sc_flags & IWN_FLAG_INTERNAL_PA) {
 8427                 /* Use internal power amplifier only. */
 8428                 IWN_WRITE(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_RADIO_2X2_IPA);
 8429         }
 8430         if (sc->base_params->additional_nic_config && sc->calib_ver >= 6) {
 8431                 /* Indicate that ROM calibration version is >=6. */
 8432                 IWN_SETBITS(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_CALIB_VER6);
 8433         }
 8434         if (sc->base_params->additional_gp_drv_bit)
 8435                 IWN_SETBITS(sc, IWN_GP_DRIVER,
 8436                     sc->base_params->additional_gp_drv_bit);
 8437         return 0;
 8438 }
 8439 
 8440 /*
 8441  * Take NIC ownership over Intel Active Management Technology (AMT).
 8442  */
 8443 static int
 8444 iwn_hw_prepare(struct iwn_softc *sc)
 8445 {
 8446         int ntries;
 8447 
 8448         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 8449 
 8450         /* Check if hardware is ready. */
 8451         IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_NIC_READY);
 8452         for (ntries = 0; ntries < 5; ntries++) {
 8453                 if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
 8454                     IWN_HW_IF_CONFIG_NIC_READY)
 8455                         return 0;
 8456                 DELAY(10);
 8457         }
 8458 
 8459         /* Hardware not ready, force into ready state. */
 8460         IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_PREPARE);
 8461         for (ntries = 0; ntries < 15000; ntries++) {
 8462                 if (!(IWN_READ(sc, IWN_HW_IF_CONFIG) &
 8463                     IWN_HW_IF_CONFIG_PREPARE_DONE))
 8464                         break;
 8465                 DELAY(10);
 8466         }
 8467         if (ntries == 15000)
 8468                 return ETIMEDOUT;
 8469 
 8470         /* Hardware should be ready now. */
 8471         IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_NIC_READY);
 8472         for (ntries = 0; ntries < 5; ntries++) {
 8473                 if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
 8474                     IWN_HW_IF_CONFIG_NIC_READY)
 8475                         return 0;
 8476                 DELAY(10);
 8477         }
 8478         return ETIMEDOUT;
 8479 }
 8480 
 8481 static int
 8482 iwn_hw_init(struct iwn_softc *sc)
 8483 {
 8484         struct iwn_ops *ops = &sc->ops;
 8485         int error, chnl, qid;
 8486 
 8487         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 8488 
 8489         /* Clear pending interrupts. */
 8490         IWN_WRITE(sc, IWN_INT, 0xffffffff);
 8491 
 8492         if ((error = iwn_apm_init(sc)) != 0) {
 8493                 device_printf(sc->sc_dev,
 8494                     "%s: could not power ON adapter, error %d\n", __func__,
 8495                     error);
 8496                 return error;
 8497         }
 8498 
 8499         /* Select VMAIN power source. */
 8500         if ((error = iwn_nic_lock(sc)) != 0)
 8501                 return error;
 8502         iwn_prph_clrbits(sc, IWN_APMG_PS, IWN_APMG_PS_PWR_SRC_MASK);
 8503         iwn_nic_unlock(sc);
 8504 
 8505         /* Perform adapter-specific initialization. */
 8506         if ((error = ops->nic_config(sc)) != 0)
 8507                 return error;
 8508 
 8509         /* Initialize RX ring. */
 8510         if ((error = iwn_nic_lock(sc)) != 0)
 8511                 return error;
 8512         IWN_WRITE(sc, IWN_FH_RX_CONFIG, 0);
 8513         IWN_WRITE(sc, IWN_FH_RX_WPTR, 0);
 8514         /* Set physical address of RX ring (256-byte aligned). */
 8515         IWN_WRITE(sc, IWN_FH_RX_BASE, sc->rxq.desc_dma.paddr >> 8);
 8516         /* Set physical address of RX status (16-byte aligned). */
 8517         IWN_WRITE(sc, IWN_FH_STATUS_WPTR, sc->rxq.stat_dma.paddr >> 4);
 8518         /* Enable RX. */
 8519         IWN_WRITE(sc, IWN_FH_RX_CONFIG,
 8520             IWN_FH_RX_CONFIG_ENA           |
 8521             IWN_FH_RX_CONFIG_IGN_RXF_EMPTY |    /* HW bug workaround */
 8522             IWN_FH_RX_CONFIG_IRQ_DST_HOST  |
 8523             IWN_FH_RX_CONFIG_SINGLE_FRAME  |
 8524             IWN_FH_RX_CONFIG_RB_TIMEOUT(0) |
 8525             IWN_FH_RX_CONFIG_NRBD(IWN_RX_RING_COUNT_LOG));
 8526         iwn_nic_unlock(sc);
 8527         IWN_WRITE(sc, IWN_FH_RX_WPTR, (IWN_RX_RING_COUNT - 1) & ~7);
 8528 
 8529         if ((error = iwn_nic_lock(sc)) != 0)
 8530                 return error;
 8531 
 8532         /* Initialize TX scheduler. */
 8533         iwn_prph_write(sc, sc->sched_txfact_addr, 0);
 8534 
 8535         /* Set physical address of "keep warm" page (16-byte aligned). */
 8536         IWN_WRITE(sc, IWN_FH_KW_ADDR, sc->kw_dma.paddr >> 4);
 8537 
 8538         /* Initialize TX rings. */
 8539         for (qid = 0; qid < sc->ntxqs; qid++) {
 8540                 struct iwn_tx_ring *txq = &sc->txq[qid];
 8541 
 8542                 /* Set physical address of TX ring (256-byte aligned). */
 8543                 IWN_WRITE(sc, IWN_FH_CBBC_QUEUE(qid),
 8544                     txq->desc_dma.paddr >> 8);
 8545         }
 8546         iwn_nic_unlock(sc);
 8547 
 8548         /* Enable DMA channels. */
 8549         for (chnl = 0; chnl < sc->ndmachnls; chnl++) {
 8550                 IWN_WRITE(sc, IWN_FH_TX_CONFIG(chnl),
 8551                     IWN_FH_TX_CONFIG_DMA_ENA |
 8552                     IWN_FH_TX_CONFIG_DMA_CREDIT_ENA);
 8553         }
 8554 
 8555         /* Clear "radio off" and "commands blocked" bits. */
 8556         IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
 8557         IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CMD_BLOCKED);
 8558 
 8559         /* Clear pending interrupts. */
 8560         IWN_WRITE(sc, IWN_INT, 0xffffffff);
 8561         /* Enable interrupt coalescing. */
 8562         IWN_WRITE(sc, IWN_INT_COALESCING, 512 / 8);
 8563         /* Enable interrupts. */
 8564         IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
 8565 
 8566         /* _Really_ make sure "radio off" bit is cleared! */
 8567         IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
 8568         IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
 8569 
 8570         /* Enable shadow registers. */
 8571         if (sc->base_params->shadow_reg_enable)
 8572                 IWN_SETBITS(sc, IWN_SHADOW_REG_CTRL, 0x800fffff);
 8573 
 8574         if ((error = ops->load_firmware(sc)) != 0) {
 8575                 device_printf(sc->sc_dev,
 8576                     "%s: could not load firmware, error %d\n", __func__,
 8577                     error);
 8578                 return error;
 8579         }
 8580         /* Wait at most one second for firmware alive notification. */
 8581         if ((error = msleep(sc, &sc->sc_mtx, PCATCH, "iwninit", hz)) != 0) {
 8582                 device_printf(sc->sc_dev,
 8583                     "%s: timeout waiting for adapter to initialize, error %d\n",
 8584                     __func__, error);
 8585                 return error;
 8586         }
 8587         /* Do post-firmware initialization. */
 8588 
 8589         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 8590 
 8591         return ops->post_alive(sc);
 8592 }
 8593 
 8594 static void
 8595 iwn_hw_stop(struct iwn_softc *sc)
 8596 {
 8597         int chnl, qid, ntries;
 8598 
 8599         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 8600 
 8601         IWN_WRITE(sc, IWN_RESET, IWN_RESET_NEVO);
 8602 
 8603         /* Disable interrupts. */
 8604         IWN_WRITE(sc, IWN_INT_MASK, 0);
 8605         IWN_WRITE(sc, IWN_INT, 0xffffffff);
 8606         IWN_WRITE(sc, IWN_FH_INT, 0xffffffff);
 8607         sc->sc_flags &= ~IWN_FLAG_USE_ICT;
 8608 
 8609         /* Make sure we no longer hold the NIC lock. */
 8610         iwn_nic_unlock(sc);
 8611 
 8612         /* Stop TX scheduler. */
 8613         iwn_prph_write(sc, sc->sched_txfact_addr, 0);
 8614 
 8615         /* Stop all DMA channels. */
 8616         if (iwn_nic_lock(sc) == 0) {
 8617                 for (chnl = 0; chnl < sc->ndmachnls; chnl++) {
 8618                         IWN_WRITE(sc, IWN_FH_TX_CONFIG(chnl), 0);
 8619                         for (ntries = 0; ntries < 200; ntries++) {
 8620                                 if (IWN_READ(sc, IWN_FH_TX_STATUS) &
 8621                                     IWN_FH_TX_STATUS_IDLE(chnl))
 8622                                         break;
 8623                                 DELAY(10);
 8624                         }
 8625                 }
 8626                 iwn_nic_unlock(sc);
 8627         }
 8628 
 8629         /* Stop RX ring. */
 8630         iwn_reset_rx_ring(sc, &sc->rxq);
 8631 
 8632         /* Reset all TX rings. */
 8633         for (qid = 0; qid < sc->ntxqs; qid++)
 8634                 iwn_reset_tx_ring(sc, &sc->txq[qid]);
 8635 
 8636         if (iwn_nic_lock(sc) == 0) {
 8637                 iwn_prph_write(sc, IWN_APMG_CLK_DIS,
 8638                     IWN_APMG_CLK_CTRL_DMA_CLK_RQT);
 8639                 iwn_nic_unlock(sc);
 8640         }
 8641         DELAY(5);
 8642         /* Power OFF adapter. */
 8643         iwn_apm_stop(sc);
 8644 }
 8645 
 8646 static void
 8647 iwn_radio_on(void *arg0, int pending)
 8648 {
 8649         struct iwn_softc *sc = arg0;
 8650         struct ieee80211com *ic = &sc->sc_ic;
 8651         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
 8652 
 8653         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 8654 
 8655         if (vap != NULL) {
 8656                 iwn_init(sc);
 8657                 ieee80211_init(vap);
 8658         }
 8659 }
 8660 
 8661 static void
 8662 iwn_radio_off(void *arg0, int pending)
 8663 {
 8664         struct iwn_softc *sc = arg0;
 8665         struct ieee80211com *ic = &sc->sc_ic;
 8666         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
 8667 
 8668         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 8669 
 8670         iwn_stop(sc);
 8671         if (vap != NULL)
 8672                 ieee80211_stop(vap);
 8673 
 8674         /* Enable interrupts to get RF toggle notification. */
 8675         IWN_LOCK(sc);
 8676         IWN_WRITE(sc, IWN_INT, 0xffffffff);
 8677         IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
 8678         IWN_UNLOCK(sc);
 8679 }
 8680 
 8681 static void
 8682 iwn_panicked(void *arg0, int pending)
 8683 {
 8684         struct iwn_softc *sc = arg0;
 8685         struct ieee80211com *ic = &sc->sc_ic;
 8686         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
 8687 #if 0
 8688         int error;
 8689 #endif
 8690 
 8691         if (vap == NULL) {
 8692                 printf("%s: null vap\n", __func__);
 8693                 return;
 8694         }
 8695 
 8696         device_printf(sc->sc_dev, "%s: controller panicked, iv_state = %d; "
 8697             "restarting\n", __func__, vap->iv_state);
 8698 
 8699         /*
 8700          * This is not enough work. We need to also reinitialise
 8701          * the correct transmit state for aggregation enabled queues,
 8702          * which has a very specific requirement of
 8703          * ring index = 802.11 seqno % 256.  If we don't do this (which
 8704          * we definitely don't!) then the firmware will just panic again.
 8705          */
 8706 #if 1
 8707         ieee80211_restart_all(ic);
 8708 #else
 8709         IWN_LOCK(sc);
 8710 
 8711         iwn_stop_locked(sc);
 8712         iwn_init_locked(sc);
 8713         if (vap->iv_state >= IEEE80211_S_AUTH &&
 8714             (error = iwn_auth(sc, vap)) != 0) {
 8715                 device_printf(sc->sc_dev,
 8716                     "%s: could not move to auth state\n", __func__);
 8717         }
 8718         if (vap->iv_state >= IEEE80211_S_RUN &&
 8719             (error = iwn_run(sc, vap)) != 0) {
 8720                 device_printf(sc->sc_dev,
 8721                     "%s: could not move to run state\n", __func__);
 8722         }
 8723 
 8724         IWN_UNLOCK(sc);
 8725 #endif
 8726 }
 8727 
 8728 static void
 8729 iwn_init_locked(struct iwn_softc *sc)
 8730 {
 8731         int error;
 8732 
 8733         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 8734 
 8735         IWN_LOCK_ASSERT(sc);
 8736 
 8737         sc->sc_flags |= IWN_FLAG_RUNNING;
 8738 
 8739         if ((error = iwn_hw_prepare(sc)) != 0) {
 8740                 device_printf(sc->sc_dev, "%s: hardware not ready, error %d\n",
 8741                     __func__, error);
 8742                 goto fail;
 8743         }
 8744 
 8745         /* Initialize interrupt mask to default value. */
 8746         sc->int_mask = IWN_INT_MASK_DEF;
 8747         sc->sc_flags &= ~IWN_FLAG_USE_ICT;
 8748 
 8749         /* Check that the radio is not disabled by hardware switch. */
 8750         if (!(IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_RFKILL)) {
 8751                 device_printf(sc->sc_dev,
 8752                     "radio is disabled by hardware switch\n");
 8753                 /* Enable interrupts to get RF toggle notifications. */
 8754                 IWN_WRITE(sc, IWN_INT, 0xffffffff);
 8755                 IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
 8756                 return;
 8757         }
 8758 
 8759         /* Read firmware images from the filesystem. */
 8760         if ((error = iwn_read_firmware(sc)) != 0) {
 8761                 device_printf(sc->sc_dev,
 8762                     "%s: could not read firmware, error %d\n", __func__,
 8763                     error);
 8764                 goto fail;
 8765         }
 8766 
 8767         /* Initialize hardware and upload firmware. */
 8768         error = iwn_hw_init(sc);
 8769         iwn_unload_firmware(sc);
 8770         if (error != 0) {
 8771                 device_printf(sc->sc_dev,
 8772                     "%s: could not initialize hardware, error %d\n", __func__,
 8773                     error);
 8774                 goto fail;
 8775         }
 8776 
 8777         /* Configure adapter now that it is ready. */
 8778         if ((error = iwn_config(sc)) != 0) {
 8779                 device_printf(sc->sc_dev,
 8780                     "%s: could not configure device, error %d\n", __func__,
 8781                     error);
 8782                 goto fail;
 8783         }
 8784 
 8785         callout_reset(&sc->watchdog_to, hz, iwn_watchdog, sc);
 8786 
 8787         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 8788 
 8789         return;
 8790 
 8791 fail:
 8792         sc->sc_flags &= ~IWN_FLAG_RUNNING;
 8793         iwn_stop_locked(sc);
 8794         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end in error\n",__func__);
 8795 }
 8796 
 8797 static void
 8798 iwn_init(struct iwn_softc *sc)
 8799 {
 8800 
 8801         IWN_LOCK(sc);
 8802         iwn_init_locked(sc);
 8803         IWN_UNLOCK(sc);
 8804 
 8805         if (sc->sc_flags & IWN_FLAG_RUNNING)
 8806                 ieee80211_start_all(&sc->sc_ic);
 8807 }
 8808 
 8809 static void
 8810 iwn_stop_locked(struct iwn_softc *sc)
 8811 {
 8812 
 8813         IWN_LOCK_ASSERT(sc);
 8814 
 8815         sc->sc_is_scanning = 0;
 8816         sc->sc_tx_timer = 0;
 8817         callout_stop(&sc->watchdog_to);
 8818         callout_stop(&sc->calib_to);
 8819         sc->sc_flags &= ~IWN_FLAG_RUNNING;
 8820 
 8821         /* Power OFF hardware. */
 8822         iwn_hw_stop(sc);
 8823 }
 8824 
 8825 static void
 8826 iwn_stop(struct iwn_softc *sc)
 8827 {
 8828         IWN_LOCK(sc);
 8829         iwn_stop_locked(sc);
 8830         IWN_UNLOCK(sc);
 8831 }
 8832 
 8833 /*
 8834  * Callback from net80211 to start a scan.
 8835  */
 8836 static void
 8837 iwn_scan_start(struct ieee80211com *ic)
 8838 {
 8839         struct iwn_softc *sc = ic->ic_softc;
 8840 
 8841         IWN_LOCK(sc);
 8842         /* make the link LED blink while we're scanning */
 8843         iwn_set_led(sc, IWN_LED_LINK, 20, 2);
 8844         IWN_UNLOCK(sc);
 8845 }
 8846 
 8847 /*
 8848  * Callback from net80211 to terminate a scan.
 8849  */
 8850 static void
 8851 iwn_scan_end(struct ieee80211com *ic)
 8852 {
 8853         struct iwn_softc *sc = ic->ic_softc;
 8854         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
 8855 
 8856         IWN_LOCK(sc);
 8857         if (vap->iv_state == IEEE80211_S_RUN) {
 8858                 /* Set link LED to ON status if we are associated */
 8859                 iwn_set_led(sc, IWN_LED_LINK, 0, 1);
 8860         }
 8861         IWN_UNLOCK(sc);
 8862 }
 8863 
 8864 /*
 8865  * Callback from net80211 to force a channel change.
 8866  */
 8867 static void
 8868 iwn_set_channel(struct ieee80211com *ic)
 8869 {
 8870         const struct ieee80211_channel *c = ic->ic_curchan;
 8871         struct iwn_softc *sc = ic->ic_softc;
 8872         int error;
 8873 
 8874         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 8875 
 8876         IWN_LOCK(sc);
 8877         sc->sc_rxtap.wr_chan_freq = htole16(c->ic_freq);
 8878         sc->sc_rxtap.wr_chan_flags = htole16(c->ic_flags);
 8879         sc->sc_txtap.wt_chan_freq = htole16(c->ic_freq);
 8880         sc->sc_txtap.wt_chan_flags = htole16(c->ic_flags);
 8881 
 8882         /*
 8883          * Only need to set the channel in Monitor mode. AP scanning and auth
 8884          * are already taken care of by their respective firmware commands.
 8885          */
 8886         if (ic->ic_opmode == IEEE80211_M_MONITOR) {
 8887                 error = iwn_config(sc);
 8888                 if (error != 0)
 8889                 device_printf(sc->sc_dev,
 8890                     "%s: error %d settting channel\n", __func__, error);
 8891         }
 8892         IWN_UNLOCK(sc);
 8893 }
 8894 
 8895 /*
 8896  * Callback from net80211 to start scanning of the current channel.
 8897  */
 8898 static void
 8899 iwn_scan_curchan(struct ieee80211_scan_state *ss, unsigned long maxdwell)
 8900 {
 8901         struct ieee80211vap *vap = ss->ss_vap;
 8902         struct ieee80211com *ic = vap->iv_ic;
 8903         struct iwn_softc *sc = ic->ic_softc;
 8904         int error;
 8905 
 8906         IWN_LOCK(sc);
 8907         error = iwn_scan(sc, vap, ss, ic->ic_curchan);
 8908         IWN_UNLOCK(sc);
 8909         if (error != 0)
 8910                 ieee80211_cancel_scan(vap);
 8911 }
 8912 
 8913 /*
 8914  * Callback from net80211 to handle the minimum dwell time being met.
 8915  * The intent is to terminate the scan but we just let the firmware
 8916  * notify us when it's finished as we have no safe way to abort it.
 8917  */
 8918 static void
 8919 iwn_scan_mindwell(struct ieee80211_scan_state *ss)
 8920 {
 8921         /* NB: don't try to abort scan; wait for firmware to finish */
 8922 }
 8923 #ifdef  IWN_DEBUG
 8924 #define IWN_DESC(x) case x:     return #x
 8925 
 8926 /*
 8927  * Translate CSR code to string
 8928  */
 8929 static char *iwn_get_csr_string(int csr)
 8930 {
 8931         switch (csr) {
 8932                 IWN_DESC(IWN_HW_IF_CONFIG);
 8933                 IWN_DESC(IWN_INT_COALESCING);
 8934                 IWN_DESC(IWN_INT);
 8935                 IWN_DESC(IWN_INT_MASK);
 8936                 IWN_DESC(IWN_FH_INT);
 8937                 IWN_DESC(IWN_GPIO_IN);
 8938                 IWN_DESC(IWN_RESET);
 8939                 IWN_DESC(IWN_GP_CNTRL);
 8940                 IWN_DESC(IWN_HW_REV);
 8941                 IWN_DESC(IWN_EEPROM);
 8942                 IWN_DESC(IWN_EEPROM_GP);
 8943                 IWN_DESC(IWN_OTP_GP);
 8944                 IWN_DESC(IWN_GIO);
 8945                 IWN_DESC(IWN_GP_UCODE);
 8946                 IWN_DESC(IWN_GP_DRIVER);
 8947                 IWN_DESC(IWN_UCODE_GP1);
 8948                 IWN_DESC(IWN_UCODE_GP2);
 8949                 IWN_DESC(IWN_LED);
 8950                 IWN_DESC(IWN_DRAM_INT_TBL);
 8951                 IWN_DESC(IWN_GIO_CHICKEN);
 8952                 IWN_DESC(IWN_ANA_PLL);
 8953                 IWN_DESC(IWN_HW_REV_WA);
 8954                 IWN_DESC(IWN_DBG_HPET_MEM);
 8955         default:
 8956                 return "UNKNOWN CSR";
 8957         }
 8958 }
 8959 
 8960 /*
 8961  * This function print firmware register
 8962  */
 8963 static void
 8964 iwn_debug_register(struct iwn_softc *sc)
 8965 {
 8966         int i;
 8967         static const uint32_t csr_tbl[] = {
 8968                 IWN_HW_IF_CONFIG,
 8969                 IWN_INT_COALESCING,
 8970                 IWN_INT,
 8971                 IWN_INT_MASK,
 8972                 IWN_FH_INT,
 8973                 IWN_GPIO_IN,
 8974                 IWN_RESET,
 8975                 IWN_GP_CNTRL,
 8976                 IWN_HW_REV,
 8977                 IWN_EEPROM,
 8978                 IWN_EEPROM_GP,
 8979                 IWN_OTP_GP,
 8980                 IWN_GIO,
 8981                 IWN_GP_UCODE,
 8982                 IWN_GP_DRIVER,
 8983                 IWN_UCODE_GP1,
 8984                 IWN_UCODE_GP2,
 8985                 IWN_LED,
 8986                 IWN_DRAM_INT_TBL,
 8987                 IWN_GIO_CHICKEN,
 8988                 IWN_ANA_PLL,
 8989                 IWN_HW_REV_WA,
 8990                 IWN_DBG_HPET_MEM,
 8991         };
 8992         DPRINTF(sc, IWN_DEBUG_REGISTER,
 8993             "CSR values: (2nd byte of IWN_INT_COALESCING is IWN_INT_PERIODIC)%s",
 8994             "\n");
 8995         for (i = 0; i <  nitems(csr_tbl); i++){
 8996                 DPRINTF(sc, IWN_DEBUG_REGISTER,"  %10s: 0x%08x ",
 8997                         iwn_get_csr_string(csr_tbl[i]), IWN_READ(sc, csr_tbl[i]));
 8998                 if ((i+1) % 3 == 0)
 8999                         DPRINTF(sc, IWN_DEBUG_REGISTER,"%s","\n");
 9000         }
 9001         DPRINTF(sc, IWN_DEBUG_REGISTER,"%s","\n");
 9002 }
 9003 #endif
 9004 
 9005 

Cache object: a1d22e009cc9708e4fca69ed58238b33


[ 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.