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-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-2  -  FREEBSD-11-1  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-4  -  FREEBSD-10-3  -  FREEBSD-10-2  -  FREEBSD-10-1  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-3  -  FREEBSD-9-2  -  FREEBSD-9-1  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-4  -  FREEBSD-8-3  -  FREEBSD-8-2  -  FREEBSD-8-1  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-4  -  FREEBSD-7-3  -  FREEBSD-7-2  -  FREEBSD-7-1  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-4  -  FREEBSD-6-3  -  FREEBSD-6-2  -  FREEBSD-6-1  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-5  -  FREEBSD-5-4  -  FREEBSD-5-3  -  FREEBSD-5-2  -  FREEBSD-5-1  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  linux-2.6  -  linux-2.4.22  -  MK83  -  MK84  -  PLAN9  -  DFBSD  -  NETBSD  -  NETBSD5  -  NETBSD4  -  NETBSD3  -  NETBSD20  -  OPENBSD  -  xnu-517  -  xnu-792  -  xnu-792.6.70  -  xnu-1228  -  xnu-1456.1.26  -  xnu-1699.24.8  -  xnu-2050.18.24  -  OPENSOLARIS  -  minix-3-1-1 
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/12.0/sys/dev/iwn/if_iwn.c 338949 2018-09-26 17:12:30Z imp $");
   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 static void     iwn_rx_done(struct iwn_softc *, struct iwn_rx_desc *,
  201                     struct iwn_rx_data *);
  202 static void     iwn_rx_compressed_ba(struct iwn_softc *, struct iwn_rx_desc *);
  203 static void     iwn5000_rx_calib_results(struct iwn_softc *,
  204                     struct iwn_rx_desc *);
  205 static void     iwn_rx_statistics(struct iwn_softc *, struct iwn_rx_desc *);
  206 static void     iwn4965_tx_done(struct iwn_softc *, struct iwn_rx_desc *,
  207                     struct iwn_rx_data *);
  208 static void     iwn5000_tx_done(struct iwn_softc *, struct iwn_rx_desc *,
  209                     struct iwn_rx_data *);
  210 static void     iwn_tx_done(struct iwn_softc *, struct iwn_rx_desc *, int, int,
  211                     uint8_t);
  212 static void     iwn_ampdu_tx_done(struct iwn_softc *, int, int, int, int, int,
  213                     void *);
  214 static void     iwn_cmd_done(struct iwn_softc *, struct iwn_rx_desc *);
  215 static void     iwn_notif_intr(struct iwn_softc *);
  216 static void     iwn_wakeup_intr(struct iwn_softc *);
  217 static void     iwn_rftoggle_task(void *, int);
  218 static void     iwn_fatal_intr(struct iwn_softc *);
  219 static void     iwn_intr(void *);
  220 static void     iwn4965_update_sched(struct iwn_softc *, int, int, uint8_t,
  221                     uint16_t);
  222 static void     iwn5000_update_sched(struct iwn_softc *, int, int, uint8_t,
  223                     uint16_t);
  224 #ifdef notyet
  225 static void     iwn5000_reset_sched(struct iwn_softc *, int, int);
  226 #endif
  227 static int      iwn_tx_data(struct iwn_softc *, struct mbuf *,
  228                     struct ieee80211_node *);
  229 static int      iwn_tx_data_raw(struct iwn_softc *, struct mbuf *,
  230                     struct ieee80211_node *,
  231                     const struct ieee80211_bpf_params *params);
  232 static int      iwn_tx_cmd(struct iwn_softc *, struct mbuf *,
  233                     struct ieee80211_node *, struct iwn_tx_ring *);
  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_set_promisc(struct iwn_softc *);
  252 static void     iwn_update_promisc(struct ieee80211com *);
  253 static void     iwn_update_mcast(struct ieee80211com *);
  254 static void     iwn_set_led(struct iwn_softc *, uint8_t, uint8_t, uint8_t);
  255 static int      iwn_set_critical_temp(struct iwn_softc *);
  256 static int      iwn_set_timing(struct iwn_softc *, struct ieee80211_node *);
  257 static void     iwn4965_power_calibration(struct iwn_softc *, int);
  258 static int      iwn4965_set_txpower(struct iwn_softc *, int);
  259 static int      iwn5000_set_txpower(struct iwn_softc *, 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_check_bss_filter(struct iwn_softc *);
  283 static int      iwn4965_rxon_assoc(struct iwn_softc *, int);
  284 static int      iwn5000_rxon_assoc(struct iwn_softc *, int);
  285 static int      iwn_send_rxon(struct iwn_softc *, int, int);
  286 static int      iwn_config(struct iwn_softc *);
  287 static int      iwn_scan(struct iwn_softc *, struct ieee80211vap *,
  288                     struct ieee80211_scan_state *, struct ieee80211_channel *);
  289 static int      iwn_auth(struct iwn_softc *, struct ieee80211vap *vap);
  290 static int      iwn_run(struct iwn_softc *, struct ieee80211vap *vap);
  291 static int      iwn_ampdu_rx_start(struct ieee80211_node *,
  292                     struct ieee80211_rx_ampdu *, int, int, int);
  293 static void     iwn_ampdu_rx_stop(struct ieee80211_node *,
  294                     struct ieee80211_rx_ampdu *);
  295 static int      iwn_addba_request(struct ieee80211_node *,
  296                     struct ieee80211_tx_ampdu *, int, int, int);
  297 static int      iwn_addba_response(struct ieee80211_node *,
  298                     struct ieee80211_tx_ampdu *, int, int, int);
  299 static int      iwn_ampdu_tx_start(struct ieee80211com *,
  300                     struct ieee80211_node *, uint8_t);
  301 static void     iwn_ampdu_tx_stop(struct ieee80211_node *,
  302                     struct ieee80211_tx_ampdu *);
  303 static void     iwn4965_ampdu_tx_start(struct iwn_softc *,
  304                     struct ieee80211_node *, int, uint8_t, uint16_t);
  305 static void     iwn4965_ampdu_tx_stop(struct iwn_softc *, int,
  306                     uint8_t, uint16_t);
  307 static void     iwn5000_ampdu_tx_start(struct iwn_softc *,
  308                     struct ieee80211_node *, int, uint8_t, uint16_t);
  309 static void     iwn5000_ampdu_tx_stop(struct iwn_softc *, int,
  310                     uint8_t, uint16_t);
  311 static int      iwn5000_query_calibration(struct iwn_softc *);
  312 static int      iwn5000_send_calibration(struct iwn_softc *);
  313 static int      iwn5000_send_wimax_coex(struct iwn_softc *);
  314 static int      iwn5000_crystal_calib(struct iwn_softc *);
  315 static int      iwn5000_temp_offset_calib(struct iwn_softc *);
  316 static int      iwn5000_temp_offset_calibv2(struct iwn_softc *);
  317 static int      iwn4965_post_alive(struct iwn_softc *);
  318 static int      iwn5000_post_alive(struct iwn_softc *);
  319 static int      iwn4965_load_bootcode(struct iwn_softc *, const uint8_t *,
  320                     int);
  321 static int      iwn4965_load_firmware(struct iwn_softc *);
  322 static int      iwn5000_load_firmware_section(struct iwn_softc *, uint32_t,
  323                     const uint8_t *, int);
  324 static int      iwn5000_load_firmware(struct iwn_softc *);
  325 static int      iwn_read_firmware_leg(struct iwn_softc *,
  326                     struct iwn_fw_info *);
  327 static int      iwn_read_firmware_tlv(struct iwn_softc *,
  328                     struct iwn_fw_info *, uint16_t);
  329 static int      iwn_read_firmware(struct iwn_softc *);
  330 static void     iwn_unload_firmware(struct iwn_softc *);
  331 static int      iwn_clock_wait(struct iwn_softc *);
  332 static int      iwn_apm_init(struct iwn_softc *);
  333 static void     iwn_apm_stop_master(struct iwn_softc *);
  334 static void     iwn_apm_stop(struct iwn_softc *);
  335 static int      iwn4965_nic_config(struct iwn_softc *);
  336 static int      iwn5000_nic_config(struct iwn_softc *);
  337 static int      iwn_hw_prepare(struct iwn_softc *);
  338 static int      iwn_hw_init(struct iwn_softc *);
  339 static void     iwn_hw_stop(struct iwn_softc *);
  340 static void     iwn_panicked(void *, int);
  341 static int      iwn_init_locked(struct iwn_softc *);
  342 static int      iwn_init(struct iwn_softc *);
  343 static void     iwn_stop_locked(struct iwn_softc *);
  344 static void     iwn_stop(struct iwn_softc *);
  345 static void     iwn_scan_start(struct ieee80211com *);
  346 static void     iwn_scan_end(struct ieee80211com *);
  347 static void     iwn_set_channel(struct ieee80211com *);
  348 static void     iwn_scan_curchan(struct ieee80211_scan_state *, unsigned long);
  349 static void     iwn_scan_mindwell(struct ieee80211_scan_state *);
  350 #ifdef  IWN_DEBUG
  351 static char     *iwn_get_csr_string(int);
  352 static void     iwn_debug_register(struct iwn_softc *);
  353 #endif
  354 
  355 static device_method_t iwn_methods[] = {
  356         /* Device interface */
  357         DEVMETHOD(device_probe,         iwn_probe),
  358         DEVMETHOD(device_attach,        iwn_attach),
  359         DEVMETHOD(device_detach,        iwn_detach),
  360         DEVMETHOD(device_shutdown,      iwn_shutdown),
  361         DEVMETHOD(device_suspend,       iwn_suspend),
  362         DEVMETHOD(device_resume,        iwn_resume),
  363 
  364         DEVMETHOD_END
  365 };
  366 
  367 static driver_t iwn_driver = {
  368         "iwn",
  369         iwn_methods,
  370         sizeof(struct iwn_softc)
  371 };
  372 static devclass_t iwn_devclass;
  373 
  374 DRIVER_MODULE(iwn, pci, iwn_driver, iwn_devclass, NULL, NULL);
  375 MODULE_PNP_INFO("U16:vendor;U16:device;D:#", pci, iwn, iwn_ident_table,
  376     nitems(iwn_ident_table) - 1);
  377 MODULE_VERSION(iwn, 1);
  378 
  379 MODULE_DEPEND(iwn, firmware, 1, 1, 1);
  380 MODULE_DEPEND(iwn, pci, 1, 1, 1);
  381 MODULE_DEPEND(iwn, wlan, 1, 1, 1);
  382 
  383 static d_ioctl_t iwn_cdev_ioctl;
  384 static d_open_t iwn_cdev_open;
  385 static d_close_t iwn_cdev_close;
  386 
  387 static struct cdevsw iwn_cdevsw = {
  388         .d_version = D_VERSION,
  389         .d_flags = 0,
  390         .d_open = iwn_cdev_open,
  391         .d_close = iwn_cdev_close,
  392         .d_ioctl = iwn_cdev_ioctl,
  393         .d_name = "iwn",
  394 };
  395 
  396 static int
  397 iwn_probe(device_t dev)
  398 {
  399         const struct iwn_ident *ident;
  400 
  401         for (ident = iwn_ident_table; ident->name != NULL; ident++) {
  402                 if (pci_get_vendor(dev) == ident->vendor &&
  403                     pci_get_device(dev) == ident->device) {
  404                         device_set_desc(dev, ident->name);
  405                         return (BUS_PROBE_DEFAULT);
  406                 }
  407         }
  408         return ENXIO;
  409 }
  410 
  411 static int
  412 iwn_is_3stream_device(struct iwn_softc *sc)
  413 {
  414         /* XXX for now only 5300, until the 5350 can be tested */
  415         if (sc->hw_type == IWN_HW_REV_TYPE_5300)
  416                 return (1);
  417         return (0);
  418 }
  419 
  420 static int
  421 iwn_attach(device_t dev)
  422 {
  423         struct iwn_softc *sc = device_get_softc(dev);
  424         struct ieee80211com *ic;
  425         int i, error, rid;
  426 
  427         sc->sc_dev = dev;
  428 
  429 #ifdef  IWN_DEBUG
  430         error = resource_int_value(device_get_name(sc->sc_dev),
  431             device_get_unit(sc->sc_dev), "debug", &(sc->sc_debug));
  432         if (error != 0)
  433                 sc->sc_debug = 0;
  434 #else
  435         sc->sc_debug = 0;
  436 #endif
  437 
  438         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: begin\n",__func__);
  439 
  440         /*
  441          * Get the offset of the PCI Express Capability Structure in PCI
  442          * Configuration Space.
  443          */
  444         error = pci_find_cap(dev, PCIY_EXPRESS, &sc->sc_cap_off);
  445         if (error != 0) {
  446                 device_printf(dev, "PCIe capability structure not found!\n");
  447                 return error;
  448         }
  449 
  450         /* Clear device-specific "PCI retry timeout" register (41h). */
  451         pci_write_config(dev, 0x41, 0, 1);
  452 
  453         /* Enable bus-mastering. */
  454         pci_enable_busmaster(dev);
  455 
  456         rid = PCIR_BAR(0);
  457         sc->mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
  458             RF_ACTIVE);
  459         if (sc->mem == NULL) {
  460                 device_printf(dev, "can't map mem space\n");
  461                 error = ENOMEM;
  462                 return error;
  463         }
  464         sc->sc_st = rman_get_bustag(sc->mem);
  465         sc->sc_sh = rman_get_bushandle(sc->mem);
  466 
  467         i = 1;
  468         rid = 0;
  469         if (pci_alloc_msi(dev, &i) == 0)
  470                 rid = 1;
  471         /* Install interrupt handler. */
  472         sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE |
  473             (rid != 0 ? 0 : RF_SHAREABLE));
  474         if (sc->irq == NULL) {
  475                 device_printf(dev, "can't map interrupt\n");
  476                 error = ENOMEM;
  477                 goto fail;
  478         }
  479 
  480         IWN_LOCK_INIT(sc);
  481 
  482         /* Read hardware revision and attach. */
  483         sc->hw_type = (IWN_READ(sc, IWN_HW_REV) >> IWN_HW_REV_TYPE_SHIFT)
  484             & IWN_HW_REV_TYPE_MASK;
  485         sc->subdevice_id = pci_get_subdevice(dev);
  486 
  487         /*
  488          * 4965 versus 5000 and later have different methods.
  489          * Let's set those up first.
  490          */
  491         if (sc->hw_type == IWN_HW_REV_TYPE_4965)
  492                 error = iwn4965_attach(sc, pci_get_device(dev));
  493         else
  494                 error = iwn5000_attach(sc, pci_get_device(dev));
  495         if (error != 0) {
  496                 device_printf(dev, "could not attach device, error %d\n",
  497                     error);
  498                 goto fail;
  499         }
  500 
  501         /*
  502          * Next, let's setup the various parameters of each NIC.
  503          */
  504         error = iwn_config_specific(sc, pci_get_device(dev));
  505         if (error != 0) {
  506                 device_printf(dev, "could not attach device, error %d\n",
  507                     error);
  508                 goto fail;
  509         }
  510 
  511         if ((error = iwn_hw_prepare(sc)) != 0) {
  512                 device_printf(dev, "hardware not ready, error %d\n", error);
  513                 goto fail;
  514         }
  515 
  516         /* Allocate DMA memory for firmware transfers. */
  517         if ((error = iwn_alloc_fwmem(sc)) != 0) {
  518                 device_printf(dev,
  519                     "could not allocate memory for firmware, error %d\n",
  520                     error);
  521                 goto fail;
  522         }
  523 
  524         /* Allocate "Keep Warm" page. */
  525         if ((error = iwn_alloc_kw(sc)) != 0) {
  526                 device_printf(dev,
  527                     "could not allocate keep warm page, error %d\n", error);
  528                 goto fail;
  529         }
  530 
  531         /* Allocate ICT table for 5000 Series. */
  532         if (sc->hw_type != IWN_HW_REV_TYPE_4965 &&
  533             (error = iwn_alloc_ict(sc)) != 0) {
  534                 device_printf(dev, "could not allocate ICT table, error %d\n",
  535                     error);
  536                 goto fail;
  537         }
  538 
  539         /* Allocate TX scheduler "rings". */
  540         if ((error = iwn_alloc_sched(sc)) != 0) {
  541                 device_printf(dev,
  542                     "could not allocate TX scheduler rings, error %d\n", error);
  543                 goto fail;
  544         }
  545 
  546         /* Allocate TX rings (16 on 4965AGN, 20 on >=5000). */
  547         for (i = 0; i < sc->ntxqs; i++) {
  548                 if ((error = iwn_alloc_tx_ring(sc, &sc->txq[i], i)) != 0) {
  549                         device_printf(dev,
  550                             "could not allocate TX ring %d, error %d\n", i,
  551                             error);
  552                         goto fail;
  553                 }
  554         }
  555 
  556         /* Allocate RX ring. */
  557         if ((error = iwn_alloc_rx_ring(sc, &sc->rxq)) != 0) {
  558                 device_printf(dev, "could not allocate RX ring, error %d\n",
  559                     error);
  560                 goto fail;
  561         }
  562 
  563         /* Clear pending interrupts. */
  564         IWN_WRITE(sc, IWN_INT, 0xffffffff);
  565 
  566         ic = &sc->sc_ic;
  567         ic->ic_softc = sc;
  568         ic->ic_name = device_get_nameunit(dev);
  569         ic->ic_phytype = IEEE80211_T_OFDM;      /* not only, but not used */
  570         ic->ic_opmode = IEEE80211_M_STA;        /* default to BSS mode */
  571 
  572         /* Set device capabilities. */
  573         ic->ic_caps =
  574                   IEEE80211_C_STA               /* station mode supported */
  575                 | IEEE80211_C_MONITOR           /* monitor mode supported */
  576 #if 0
  577                 | IEEE80211_C_BGSCAN            /* background scanning */
  578 #endif
  579                 | IEEE80211_C_TXPMGT            /* tx power management */
  580                 | IEEE80211_C_SHSLOT            /* short slot time supported */
  581                 | IEEE80211_C_WPA
  582                 | IEEE80211_C_SHPREAMBLE        /* short preamble supported */
  583 #if 0
  584                 | IEEE80211_C_IBSS              /* ibss/adhoc mode */
  585 #endif
  586                 | IEEE80211_C_WME               /* WME */
  587                 | IEEE80211_C_PMGT              /* Station-side power mgmt */
  588                 ;
  589 
  590         /* Read MAC address, channels, etc from EEPROM. */
  591         if ((error = iwn_read_eeprom(sc, ic->ic_macaddr)) != 0) {
  592                 device_printf(dev, "could not read EEPROM, error %d\n",
  593                     error);
  594                 goto fail;
  595         }
  596 
  597         /* Count the number of available chains. */
  598         sc->ntxchains =
  599             ((sc->txchainmask >> 2) & 1) +
  600             ((sc->txchainmask >> 1) & 1) +
  601             ((sc->txchainmask >> 0) & 1);
  602         sc->nrxchains =
  603             ((sc->rxchainmask >> 2) & 1) +
  604             ((sc->rxchainmask >> 1) & 1) +
  605             ((sc->rxchainmask >> 0) & 1);
  606         if (bootverbose) {
  607                 device_printf(dev, "MIMO %dT%dR, %.4s, address %6D\n",
  608                     sc->ntxchains, sc->nrxchains, sc->eeprom_domain,
  609                     ic->ic_macaddr, ":");
  610         }
  611 
  612         if (sc->sc_flags & IWN_FLAG_HAS_11N) {
  613                 ic->ic_rxstream = sc->nrxchains;
  614                 ic->ic_txstream = sc->ntxchains;
  615 
  616                 /*
  617                  * Some of the 3 antenna devices (ie, the 4965) only supports
  618                  * 2x2 operation.  So correct the number of streams if
  619                  * it's not a 3-stream device.
  620                  */
  621                 if (! iwn_is_3stream_device(sc)) {
  622                         if (ic->ic_rxstream > 2)
  623                                 ic->ic_rxstream = 2;
  624                         if (ic->ic_txstream > 2)
  625                                 ic->ic_txstream = 2;
  626                 }
  627 
  628                 ic->ic_htcaps =
  629                           IEEE80211_HTCAP_SMPS_OFF      /* SMPS mode disabled */
  630                         | IEEE80211_HTCAP_SHORTGI20     /* short GI in 20MHz */
  631                         | IEEE80211_HTCAP_CHWIDTH40     /* 40MHz channel width*/
  632                         | IEEE80211_HTCAP_SHORTGI40     /* short GI in 40MHz */
  633 #ifdef notyet
  634                         | IEEE80211_HTCAP_GREENFIELD
  635 #if IWN_RBUF_SIZE == 8192
  636                         | IEEE80211_HTCAP_MAXAMSDU_7935 /* max A-MSDU length */
  637 #else
  638                         | IEEE80211_HTCAP_MAXAMSDU_3839 /* max A-MSDU length */
  639 #endif
  640 #endif
  641                         /* s/w capabilities */
  642                         | IEEE80211_HTC_HT              /* HT operation */
  643                         | IEEE80211_HTC_AMPDU           /* tx A-MPDU */
  644 #ifdef notyet
  645                         | IEEE80211_HTC_AMSDU           /* tx A-MSDU */
  646 #endif
  647                         ;
  648         }
  649 
  650         ieee80211_ifattach(ic);
  651         ic->ic_vap_create = iwn_vap_create;
  652         ic->ic_ioctl = iwn_ioctl;
  653         ic->ic_parent = iwn_parent;
  654         ic->ic_vap_delete = iwn_vap_delete;
  655         ic->ic_transmit = iwn_transmit;
  656         ic->ic_raw_xmit = iwn_raw_xmit;
  657         ic->ic_node_alloc = iwn_node_alloc;
  658         sc->sc_ampdu_rx_start = ic->ic_ampdu_rx_start;
  659         ic->ic_ampdu_rx_start = iwn_ampdu_rx_start;
  660         sc->sc_ampdu_rx_stop = ic->ic_ampdu_rx_stop;
  661         ic->ic_ampdu_rx_stop = iwn_ampdu_rx_stop;
  662         sc->sc_addba_request = ic->ic_addba_request;
  663         ic->ic_addba_request = iwn_addba_request;
  664         sc->sc_addba_response = ic->ic_addba_response;
  665         ic->ic_addba_response = iwn_addba_response;
  666         sc->sc_addba_stop = ic->ic_addba_stop;
  667         ic->ic_addba_stop = iwn_ampdu_tx_stop;
  668         ic->ic_newassoc = iwn_newassoc;
  669         ic->ic_wme.wme_update = iwn_updateedca;
  670         ic->ic_update_promisc = iwn_update_promisc;
  671         ic->ic_update_mcast = iwn_update_mcast;
  672         ic->ic_scan_start = iwn_scan_start;
  673         ic->ic_scan_end = iwn_scan_end;
  674         ic->ic_set_channel = iwn_set_channel;
  675         ic->ic_scan_curchan = iwn_scan_curchan;
  676         ic->ic_scan_mindwell = iwn_scan_mindwell;
  677         ic->ic_getradiocaps = iwn_getradiocaps;
  678         ic->ic_setregdomain = iwn_setregdomain;
  679 
  680         iwn_radiotap_attach(sc);
  681 
  682         callout_init_mtx(&sc->calib_to, &sc->sc_mtx, 0);
  683         callout_init_mtx(&sc->scan_timeout, &sc->sc_mtx, 0);
  684         callout_init_mtx(&sc->watchdog_to, &sc->sc_mtx, 0);
  685         TASK_INIT(&sc->sc_rftoggle_task, 0, iwn_rftoggle_task, sc);
  686         TASK_INIT(&sc->sc_panic_task, 0, iwn_panicked, sc);
  687         TASK_INIT(&sc->sc_xmit_task, 0, iwn_xmit_task, sc);
  688 
  689         mbufq_init(&sc->sc_xmit_queue, 1024);
  690 
  691         sc->sc_tq = taskqueue_create("iwn_taskq", M_WAITOK,
  692             taskqueue_thread_enqueue, &sc->sc_tq);
  693         error = taskqueue_start_threads(&sc->sc_tq, 1, 0, "iwn_taskq");
  694         if (error != 0) {
  695                 device_printf(dev, "can't start threads, error %d\n", error);
  696                 goto fail;
  697         }
  698 
  699         iwn_sysctlattach(sc);
  700 
  701         /*
  702          * Hook our interrupt after all initialization is complete.
  703          */
  704         error = bus_setup_intr(dev, sc->irq, INTR_TYPE_NET | INTR_MPSAFE,
  705             NULL, iwn_intr, sc, &sc->sc_ih);
  706         if (error != 0) {
  707                 device_printf(dev, "can't establish interrupt, error %d\n",
  708                     error);
  709                 goto fail;
  710         }
  711 
  712 #if 0
  713         device_printf(sc->sc_dev, "%s: rx_stats=%d, rx_stats_bt=%d\n",
  714             __func__,
  715             sizeof(struct iwn_stats),
  716             sizeof(struct iwn_stats_bt));
  717 #endif
  718 
  719         if (bootverbose)
  720                 ieee80211_announce(ic);
  721         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
  722 
  723         /* Add debug ioctl right at the end */
  724         sc->sc_cdev = make_dev(&iwn_cdevsw, device_get_unit(dev),
  725             UID_ROOT, GID_WHEEL, 0600, "%s", device_get_nameunit(dev));
  726         if (sc->sc_cdev == NULL) {
  727                 device_printf(dev, "failed to create debug character device\n");
  728         } else {
  729                 sc->sc_cdev->si_drv1 = sc;
  730         }
  731         return 0;
  732 fail:
  733         iwn_detach(dev);
  734         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end in error\n",__func__);
  735         return error;
  736 }
  737 
  738 /*
  739  * Define specific configuration based on device id and subdevice id
  740  * pid : PCI device id
  741  */
  742 static int
  743 iwn_config_specific(struct iwn_softc *sc, uint16_t pid)
  744 {
  745 
  746         switch (pid) {
  747 /* 4965 series */
  748         case IWN_DID_4965_1:
  749         case IWN_DID_4965_2:
  750         case IWN_DID_4965_3:
  751         case IWN_DID_4965_4:
  752                 sc->base_params = &iwn4965_base_params;
  753                 sc->limits = &iwn4965_sensitivity_limits;
  754                 sc->fwname = "iwn4965fw";
  755                 /* Override chains masks, ROM is known to be broken. */
  756                 sc->txchainmask = IWN_ANT_AB;
  757                 sc->rxchainmask = IWN_ANT_ABC;
  758                 /* Enable normal btcoex */
  759                 sc->sc_flags |= IWN_FLAG_BTCOEX;
  760                 break;
  761 /* 1000 Series */
  762         case IWN_DID_1000_1:
  763         case IWN_DID_1000_2:
  764                 switch(sc->subdevice_id) {
  765                         case    IWN_SDID_1000_1:
  766                         case    IWN_SDID_1000_2:
  767                         case    IWN_SDID_1000_3:
  768                         case    IWN_SDID_1000_4:
  769                         case    IWN_SDID_1000_5:
  770                         case    IWN_SDID_1000_6:
  771                         case    IWN_SDID_1000_7:
  772                         case    IWN_SDID_1000_8:
  773                         case    IWN_SDID_1000_9:
  774                         case    IWN_SDID_1000_10:
  775                         case    IWN_SDID_1000_11:
  776                         case    IWN_SDID_1000_12:
  777                                 sc->limits = &iwn1000_sensitivity_limits;
  778                                 sc->base_params = &iwn1000_base_params;
  779                                 sc->fwname = "iwn1000fw";
  780                                 break;
  781                         default:
  782                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
  783                                     "0x%04x rev %d not supported (subdevice)\n", pid,
  784                                     sc->subdevice_id,sc->hw_type);
  785                                 return ENOTSUP;
  786                 }
  787                 break;
  788 /* 6x00 Series */
  789         case IWN_DID_6x00_2:
  790         case IWN_DID_6x00_4:
  791         case IWN_DID_6x00_1:
  792         case IWN_DID_6x00_3:
  793                 sc->fwname = "iwn6000fw";
  794                 sc->limits = &iwn6000_sensitivity_limits;
  795                 switch(sc->subdevice_id) {
  796                         case IWN_SDID_6x00_1:
  797                         case IWN_SDID_6x00_2:
  798                         case IWN_SDID_6x00_8:
  799                                 //iwl6000_3agn_cfg
  800                                 sc->base_params = &iwn_6000_base_params;
  801                                 break;
  802                         case IWN_SDID_6x00_3:
  803                         case IWN_SDID_6x00_6:
  804                         case IWN_SDID_6x00_9:
  805                                 ////iwl6000i_2agn
  806                         case IWN_SDID_6x00_4:
  807                         case IWN_SDID_6x00_7:
  808                         case IWN_SDID_6x00_10:
  809                                 //iwl6000i_2abg_cfg
  810                         case IWN_SDID_6x00_5:
  811                                 //iwl6000i_2bg_cfg
  812                                 sc->base_params = &iwn_6000i_base_params;
  813                                 sc->sc_flags |= IWN_FLAG_INTERNAL_PA;
  814                                 sc->txchainmask = IWN_ANT_BC;
  815                                 sc->rxchainmask = IWN_ANT_BC;
  816                                 break;
  817                         default:
  818                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
  819                                     "0x%04x rev %d not supported (subdevice)\n", pid,
  820                                     sc->subdevice_id,sc->hw_type);
  821                                 return ENOTSUP;
  822                 }
  823                 break;
  824 /* 6x05 Series */
  825         case IWN_DID_6x05_1:
  826         case IWN_DID_6x05_2:
  827                 switch(sc->subdevice_id) {
  828                         case IWN_SDID_6x05_1:
  829                         case IWN_SDID_6x05_4:
  830                         case IWN_SDID_6x05_6:
  831                                 //iwl6005_2agn_cfg
  832                         case IWN_SDID_6x05_2:
  833                         case IWN_SDID_6x05_5:
  834                         case IWN_SDID_6x05_7:
  835                                 //iwl6005_2abg_cfg
  836                         case IWN_SDID_6x05_3:
  837                                 //iwl6005_2bg_cfg
  838                         case IWN_SDID_6x05_8:
  839                         case IWN_SDID_6x05_9:
  840                                 //iwl6005_2agn_sff_cfg
  841                         case IWN_SDID_6x05_10:
  842                                 //iwl6005_2agn_d_cfg
  843                         case IWN_SDID_6x05_11:
  844                                 //iwl6005_2agn_mow1_cfg
  845                         case IWN_SDID_6x05_12:
  846                                 //iwl6005_2agn_mow2_cfg
  847                                 sc->fwname = "iwn6000g2afw";
  848                                 sc->limits = &iwn6000_sensitivity_limits;
  849                                 sc->base_params = &iwn_6000g2_base_params;
  850                                 break;
  851                         default:
  852                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
  853                                     "0x%04x rev %d not supported (subdevice)\n", pid,
  854                                     sc->subdevice_id,sc->hw_type);
  855                                 return ENOTSUP;
  856                 }
  857                 break;
  858 /* 6x35 Series */
  859         case IWN_DID_6035_1:
  860         case IWN_DID_6035_2:
  861                 switch(sc->subdevice_id) {
  862                         case IWN_SDID_6035_1:
  863                         case IWN_SDID_6035_2:
  864                         case IWN_SDID_6035_3:
  865                         case IWN_SDID_6035_4:
  866                         case IWN_SDID_6035_5:
  867                                 sc->fwname = "iwn6000g2bfw";
  868                                 sc->limits = &iwn6235_sensitivity_limits;
  869                                 sc->base_params = &iwn_6235_base_params;
  870                                 break;
  871                         default:
  872                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
  873                                     "0x%04x rev %d not supported (subdevice)\n", pid,
  874                                     sc->subdevice_id,sc->hw_type);
  875                                 return ENOTSUP;
  876                 }
  877                 break;
  878 /* 6x50 WiFi/WiMax Series */
  879         case IWN_DID_6050_1:
  880         case IWN_DID_6050_2:
  881                 switch(sc->subdevice_id) {
  882                         case IWN_SDID_6050_1:
  883                         case IWN_SDID_6050_3:
  884                         case IWN_SDID_6050_5:
  885                                 //iwl6050_2agn_cfg
  886                         case IWN_SDID_6050_2:
  887                         case IWN_SDID_6050_4:
  888                         case IWN_SDID_6050_6:
  889                                 //iwl6050_2abg_cfg
  890                                 sc->fwname = "iwn6050fw";
  891                                 sc->txchainmask = IWN_ANT_AB;
  892                                 sc->rxchainmask = IWN_ANT_AB;
  893                                 sc->limits = &iwn6000_sensitivity_limits;
  894                                 sc->base_params = &iwn_6050_base_params;
  895                                 break;
  896                         default:
  897                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
  898                                     "0x%04x rev %d not supported (subdevice)\n", pid,
  899                                     sc->subdevice_id,sc->hw_type);
  900                                 return ENOTSUP;
  901                 }
  902                 break;
  903 /* 6150 WiFi/WiMax Series */
  904         case IWN_DID_6150_1:
  905         case IWN_DID_6150_2:
  906                 switch(sc->subdevice_id) {
  907                         case IWN_SDID_6150_1:
  908                         case IWN_SDID_6150_3:
  909                         case IWN_SDID_6150_5:
  910                                 // iwl6150_bgn_cfg
  911                         case IWN_SDID_6150_2:
  912                         case IWN_SDID_6150_4:
  913                         case IWN_SDID_6150_6:
  914                                 //iwl6150_bg_cfg
  915                                 sc->fwname = "iwn6050fw";
  916                                 sc->limits = &iwn6000_sensitivity_limits;
  917                                 sc->base_params = &iwn_6150_base_params;
  918                                 break;
  919                         default:
  920                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
  921                                     "0x%04x rev %d not supported (subdevice)\n", pid,
  922                                     sc->subdevice_id,sc->hw_type);
  923                                 return ENOTSUP;
  924                 }
  925                 break;
  926 /* 6030 Series and 1030 Series */
  927         case IWN_DID_x030_1:
  928         case IWN_DID_x030_2:
  929         case IWN_DID_x030_3:
  930         case IWN_DID_x030_4:
  931                 switch(sc->subdevice_id) {
  932                         case IWN_SDID_x030_1:
  933                         case IWN_SDID_x030_3:
  934                         case IWN_SDID_x030_5:
  935                         // iwl1030_bgn_cfg
  936                         case IWN_SDID_x030_2:
  937                         case IWN_SDID_x030_4:
  938                         case IWN_SDID_x030_6:
  939                         //iwl1030_bg_cfg
  940                         case IWN_SDID_x030_7:
  941                         case IWN_SDID_x030_10:
  942                         case IWN_SDID_x030_14:
  943                         //iwl6030_2agn_cfg
  944                         case IWN_SDID_x030_8:
  945                         case IWN_SDID_x030_11:
  946                         case IWN_SDID_x030_15:
  947                         // iwl6030_2bgn_cfg
  948                         case IWN_SDID_x030_9:
  949                         case IWN_SDID_x030_12:
  950                         case IWN_SDID_x030_16:
  951                         // iwl6030_2abg_cfg
  952                         case IWN_SDID_x030_13:
  953                         //iwl6030_2bg_cfg
  954                                 sc->fwname = "iwn6000g2bfw";
  955                                 sc->limits = &iwn6000_sensitivity_limits;
  956                                 sc->base_params = &iwn_6000g2b_base_params;
  957                                 break;
  958                         default:
  959                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
  960                                     "0x%04x rev %d not supported (subdevice)\n", pid,
  961                                     sc->subdevice_id,sc->hw_type);
  962                                 return ENOTSUP;
  963                 }
  964                 break;
  965 /* 130 Series WiFi */
  966 /* XXX: This series will need adjustment for rate.
  967  * see rx_with_siso_diversity in linux kernel
  968  */
  969         case IWN_DID_130_1:
  970         case IWN_DID_130_2:
  971                 switch(sc->subdevice_id) {
  972                         case IWN_SDID_130_1:
  973                         case IWN_SDID_130_3:
  974                         case IWN_SDID_130_5:
  975                         //iwl130_bgn_cfg
  976                         case IWN_SDID_130_2:
  977                         case IWN_SDID_130_4:
  978                         case IWN_SDID_130_6:
  979                         //iwl130_bg_cfg
  980                                 sc->fwname = "iwn6000g2bfw";
  981                                 sc->limits = &iwn6000_sensitivity_limits;
  982                                 sc->base_params = &iwn_6000g2b_base_params;
  983                                 break;
  984                         default:
  985                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
  986                                     "0x%04x rev %d not supported (subdevice)\n", pid,
  987                                     sc->subdevice_id,sc->hw_type);
  988                                 return ENOTSUP;
  989                 }
  990                 break;
  991 /* 100 Series WiFi */
  992         case IWN_DID_100_1:
  993         case IWN_DID_100_2:
  994                 switch(sc->subdevice_id) {
  995                         case IWN_SDID_100_1:
  996                         case IWN_SDID_100_2:
  997                         case IWN_SDID_100_3:
  998                         case IWN_SDID_100_4:
  999                         case IWN_SDID_100_5:
 1000                         case IWN_SDID_100_6:
 1001                                 sc->limits = &iwn1000_sensitivity_limits;
 1002                                 sc->base_params = &iwn1000_base_params;
 1003                                 sc->fwname = "iwn100fw";
 1004                                 break;
 1005                         default:
 1006                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
 1007                                     "0x%04x rev %d not supported (subdevice)\n", pid,
 1008                                     sc->subdevice_id,sc->hw_type);
 1009                                 return ENOTSUP;
 1010                 }
 1011                 break;
 1012 
 1013 /* 105 Series */
 1014 /* XXX: This series will need adjustment for rate.
 1015  * see rx_with_siso_diversity in linux kernel
 1016  */
 1017         case IWN_DID_105_1:
 1018         case IWN_DID_105_2:
 1019                 switch(sc->subdevice_id) {
 1020                         case IWN_SDID_105_1:
 1021                         case IWN_SDID_105_2:
 1022                         case IWN_SDID_105_3:
 1023                         //iwl105_bgn_cfg
 1024                         case IWN_SDID_105_4:
 1025                         //iwl105_bgn_d_cfg
 1026                                 sc->limits = &iwn2030_sensitivity_limits;
 1027                                 sc->base_params = &iwn2000_base_params;
 1028                                 sc->fwname = "iwn105fw";
 1029                                 break;
 1030                         default:
 1031                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
 1032                                     "0x%04x rev %d not supported (subdevice)\n", pid,
 1033                                     sc->subdevice_id,sc->hw_type);
 1034                                 return ENOTSUP;
 1035                 }
 1036                 break;
 1037 
 1038 /* 135 Series */
 1039 /* XXX: This series will need adjustment for rate.
 1040  * see rx_with_siso_diversity in linux kernel
 1041  */
 1042         case IWN_DID_135_1:
 1043         case IWN_DID_135_2:
 1044                 switch(sc->subdevice_id) {
 1045                         case IWN_SDID_135_1:
 1046                         case IWN_SDID_135_2:
 1047                         case IWN_SDID_135_3:
 1048                                 sc->limits = &iwn2030_sensitivity_limits;
 1049                                 sc->base_params = &iwn2030_base_params;
 1050                                 sc->fwname = "iwn135fw";
 1051                                 break;
 1052                         default:
 1053                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
 1054                                     "0x%04x rev %d not supported (subdevice)\n", pid,
 1055                                     sc->subdevice_id,sc->hw_type);
 1056                                 return ENOTSUP;
 1057                 }
 1058                 break;
 1059 
 1060 /* 2x00 Series */
 1061         case IWN_DID_2x00_1:
 1062         case IWN_DID_2x00_2:
 1063                 switch(sc->subdevice_id) {
 1064                         case IWN_SDID_2x00_1:
 1065                         case IWN_SDID_2x00_2:
 1066                         case IWN_SDID_2x00_3:
 1067                         //iwl2000_2bgn_cfg
 1068                         case IWN_SDID_2x00_4:
 1069                         //iwl2000_2bgn_d_cfg
 1070                                 sc->limits = &iwn2030_sensitivity_limits;
 1071                                 sc->base_params = &iwn2000_base_params;
 1072                                 sc->fwname = "iwn2000fw";
 1073                                 break;
 1074                         default:
 1075                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
 1076                                     "0x%04x rev %d not supported (subdevice) \n",
 1077                                     pid, sc->subdevice_id, sc->hw_type);
 1078                                 return ENOTSUP;
 1079                 }
 1080                 break;
 1081 /* 2x30 Series */
 1082         case IWN_DID_2x30_1:
 1083         case IWN_DID_2x30_2:
 1084                 switch(sc->subdevice_id) {
 1085                         case IWN_SDID_2x30_1:
 1086                         case IWN_SDID_2x30_3:
 1087                         case IWN_SDID_2x30_5:
 1088                         //iwl100_bgn_cfg
 1089                         case IWN_SDID_2x30_2:
 1090                         case IWN_SDID_2x30_4:
 1091                         case IWN_SDID_2x30_6:
 1092                         //iwl100_bg_cfg
 1093                                 sc->limits = &iwn2030_sensitivity_limits;
 1094                                 sc->base_params = &iwn2030_base_params;
 1095                                 sc->fwname = "iwn2030fw";
 1096                                 break;
 1097                         default:
 1098                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
 1099                                     "0x%04x rev %d not supported (subdevice)\n", pid,
 1100                                     sc->subdevice_id,sc->hw_type);
 1101                                 return ENOTSUP;
 1102                 }
 1103                 break;
 1104 /* 5x00 Series */
 1105         case IWN_DID_5x00_1:
 1106         case IWN_DID_5x00_2:
 1107         case IWN_DID_5x00_3:
 1108         case IWN_DID_5x00_4:
 1109                 sc->limits = &iwn5000_sensitivity_limits;
 1110                 sc->base_params = &iwn5000_base_params;
 1111                 sc->fwname = "iwn5000fw";
 1112                 switch(sc->subdevice_id) {
 1113                         case IWN_SDID_5x00_1:
 1114                         case IWN_SDID_5x00_2:
 1115                         case IWN_SDID_5x00_3:
 1116                         case IWN_SDID_5x00_4:
 1117                         case IWN_SDID_5x00_9:
 1118                         case IWN_SDID_5x00_10:
 1119                         case IWN_SDID_5x00_11:
 1120                         case IWN_SDID_5x00_12:
 1121                         case IWN_SDID_5x00_17:
 1122                         case IWN_SDID_5x00_18:
 1123                         case IWN_SDID_5x00_19:
 1124                         case IWN_SDID_5x00_20:
 1125                         //iwl5100_agn_cfg
 1126                                 sc->txchainmask = IWN_ANT_B;
 1127                                 sc->rxchainmask = IWN_ANT_AB;
 1128                                 break;
 1129                         case IWN_SDID_5x00_5:
 1130                         case IWN_SDID_5x00_6:
 1131                         case IWN_SDID_5x00_13:
 1132                         case IWN_SDID_5x00_14:
 1133                         case IWN_SDID_5x00_21:
 1134                         case IWN_SDID_5x00_22:
 1135                         //iwl5100_bgn_cfg
 1136                                 sc->txchainmask = IWN_ANT_B;
 1137                                 sc->rxchainmask = IWN_ANT_AB;
 1138                                 break;
 1139                         case IWN_SDID_5x00_7:
 1140                         case IWN_SDID_5x00_8:
 1141                         case IWN_SDID_5x00_15:
 1142                         case IWN_SDID_5x00_16:
 1143                         case IWN_SDID_5x00_23:
 1144                         case IWN_SDID_5x00_24:
 1145                         //iwl5100_abg_cfg
 1146                                 sc->txchainmask = IWN_ANT_B;
 1147                                 sc->rxchainmask = IWN_ANT_AB;
 1148                                 break;
 1149                         case IWN_SDID_5x00_25:
 1150                         case IWN_SDID_5x00_26:
 1151                         case IWN_SDID_5x00_27:
 1152                         case IWN_SDID_5x00_28:
 1153                         case IWN_SDID_5x00_29:
 1154                         case IWN_SDID_5x00_30:
 1155                         case IWN_SDID_5x00_31:
 1156                         case IWN_SDID_5x00_32:
 1157                         case IWN_SDID_5x00_33:
 1158                         case IWN_SDID_5x00_34:
 1159                         case IWN_SDID_5x00_35:
 1160                         case IWN_SDID_5x00_36:
 1161                         //iwl5300_agn_cfg
 1162                                 sc->txchainmask = IWN_ANT_ABC;
 1163                                 sc->rxchainmask = IWN_ANT_ABC;
 1164                                 break;
 1165                         default:
 1166                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
 1167                                     "0x%04x rev %d not supported (subdevice)\n", pid,
 1168                                     sc->subdevice_id,sc->hw_type);
 1169                                 return ENOTSUP;
 1170                 }
 1171                 break;
 1172 /* 5x50 Series */
 1173         case IWN_DID_5x50_1:
 1174         case IWN_DID_5x50_2:
 1175         case IWN_DID_5x50_3:
 1176         case IWN_DID_5x50_4:
 1177                 sc->limits = &iwn5000_sensitivity_limits;
 1178                 sc->base_params = &iwn5000_base_params;
 1179                 sc->fwname = "iwn5000fw";
 1180                 switch(sc->subdevice_id) {
 1181                         case IWN_SDID_5x50_1:
 1182                         case IWN_SDID_5x50_2:
 1183                         case IWN_SDID_5x50_3:
 1184                         //iwl5350_agn_cfg
 1185                                 sc->limits = &iwn5000_sensitivity_limits;
 1186                                 sc->base_params = &iwn5000_base_params;
 1187                                 sc->fwname = "iwn5000fw";
 1188                                 break;
 1189                         case IWN_SDID_5x50_4:
 1190                         case IWN_SDID_5x50_5:
 1191                         case IWN_SDID_5x50_8:
 1192                         case IWN_SDID_5x50_9:
 1193                         case IWN_SDID_5x50_10:
 1194                         case IWN_SDID_5x50_11:
 1195                         //iwl5150_agn_cfg
 1196                         case IWN_SDID_5x50_6:
 1197                         case IWN_SDID_5x50_7:
 1198                         case IWN_SDID_5x50_12:
 1199                         case IWN_SDID_5x50_13:
 1200                         //iwl5150_abg_cfg
 1201                                 sc->limits = &iwn5000_sensitivity_limits;
 1202                                 sc->fwname = "iwn5150fw";
 1203                                 sc->base_params = &iwn_5x50_base_params;
 1204                                 break;
 1205                         default:
 1206                                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
 1207                                     "0x%04x rev %d not supported (subdevice)\n", pid,
 1208                                     sc->subdevice_id,sc->hw_type);
 1209                                 return ENOTSUP;
 1210                 }
 1211                 break;
 1212         default:
 1213                 device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id : 0x%04x"
 1214                     "rev 0x%08x not supported (device)\n", pid, sc->subdevice_id,
 1215                      sc->hw_type);
 1216                 return ENOTSUP;
 1217         }
 1218         return 0;
 1219 }
 1220 
 1221 static int
 1222 iwn4965_attach(struct iwn_softc *sc, uint16_t pid)
 1223 {
 1224         struct iwn_ops *ops = &sc->ops;
 1225 
 1226         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 1227         ops->load_firmware = iwn4965_load_firmware;
 1228         ops->read_eeprom = iwn4965_read_eeprom;
 1229         ops->post_alive = iwn4965_post_alive;
 1230         ops->nic_config = iwn4965_nic_config;
 1231         ops->update_sched = iwn4965_update_sched;
 1232         ops->get_temperature = iwn4965_get_temperature;
 1233         ops->get_rssi = iwn4965_get_rssi;
 1234         ops->set_txpower = iwn4965_set_txpower;
 1235         ops->init_gains = iwn4965_init_gains;
 1236         ops->set_gains = iwn4965_set_gains;
 1237         ops->rxon_assoc = iwn4965_rxon_assoc;
 1238         ops->add_node = iwn4965_add_node;
 1239         ops->tx_done = iwn4965_tx_done;
 1240         ops->ampdu_tx_start = iwn4965_ampdu_tx_start;
 1241         ops->ampdu_tx_stop = iwn4965_ampdu_tx_stop;
 1242         sc->ntxqs = IWN4965_NTXQUEUES;
 1243         sc->firstaggqueue = IWN4965_FIRSTAGGQUEUE;
 1244         sc->ndmachnls = IWN4965_NDMACHNLS;
 1245         sc->broadcast_id = IWN4965_ID_BROADCAST;
 1246         sc->rxonsz = IWN4965_RXONSZ;
 1247         sc->schedsz = IWN4965_SCHEDSZ;
 1248         sc->fw_text_maxsz = IWN4965_FW_TEXT_MAXSZ;
 1249         sc->fw_data_maxsz = IWN4965_FW_DATA_MAXSZ;
 1250         sc->fwsz = IWN4965_FWSZ;
 1251         sc->sched_txfact_addr = IWN4965_SCHED_TXFACT;
 1252         sc->limits = &iwn4965_sensitivity_limits;
 1253         sc->fwname = "iwn4965fw";
 1254         /* Override chains masks, ROM is known to be broken. */
 1255         sc->txchainmask = IWN_ANT_AB;
 1256         sc->rxchainmask = IWN_ANT_ABC;
 1257         /* Enable normal btcoex */
 1258         sc->sc_flags |= IWN_FLAG_BTCOEX;
 1259 
 1260         DPRINTF(sc, IWN_DEBUG_TRACE, "%s: end\n",__func__);
 1261 
 1262         return 0;
 1263 }
 1264 
 1265 static int
 1266 iwn5000_attach(struct iwn_softc *sc, uint16_t pid)
 1267 {
 1268         struct iwn_ops *ops = &sc->ops;
 1269 
 1270         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 1271 
 1272         ops->load_firmware = iwn5000_load_firmware;
 1273         ops->read_eeprom = iwn5000_read_eeprom;
 1274         ops->post_alive = iwn5000_post_alive;
 1275         ops->nic_config = iwn5000_nic_config;
 1276         ops->update_sched = iwn5000_update_sched;
 1277         ops->get_temperature = iwn5000_get_temperature;
 1278         ops->get_rssi = iwn5000_get_rssi;
 1279         ops->set_txpower = iwn5000_set_txpower;
 1280         ops->init_gains = iwn5000_init_gains;
 1281         ops->set_gains = iwn5000_set_gains;
 1282         ops->rxon_assoc = iwn5000_rxon_assoc;
 1283         ops->add_node = iwn5000_add_node;
 1284         ops->tx_done = iwn5000_tx_done;
 1285         ops->ampdu_tx_start = iwn5000_ampdu_tx_start;
 1286         ops->ampdu_tx_stop = iwn5000_ampdu_tx_stop;
 1287         sc->ntxqs = IWN5000_NTXQUEUES;
 1288         sc->firstaggqueue = IWN5000_FIRSTAGGQUEUE;
 1289         sc->ndmachnls = IWN5000_NDMACHNLS;
 1290         sc->broadcast_id = IWN5000_ID_BROADCAST;
 1291         sc->rxonsz = IWN5000_RXONSZ;
 1292         sc->schedsz = IWN5000_SCHEDSZ;
 1293         sc->fw_text_maxsz = IWN5000_FW_TEXT_MAXSZ;
 1294         sc->fw_data_maxsz = IWN5000_FW_DATA_MAXSZ;
 1295         sc->fwsz = IWN5000_FWSZ;
 1296         sc->sched_txfact_addr = IWN5000_SCHED_TXFACT;
 1297         sc->reset_noise_gain = IWN5000_PHY_CALIB_RESET_NOISE_GAIN;
 1298         sc->noise_gain = IWN5000_PHY_CALIB_NOISE_GAIN;
 1299 
 1300         return 0;
 1301 }
 1302 
 1303 /*
 1304  * Attach the interface to 802.11 radiotap.
 1305  */
 1306 static void
 1307 iwn_radiotap_attach(struct iwn_softc *sc)
 1308 {
 1309 
 1310         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 1311         ieee80211_radiotap_attach(&sc->sc_ic,
 1312             &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap),
 1313                 IWN_TX_RADIOTAP_PRESENT,
 1314             &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
 1315                 IWN_RX_RADIOTAP_PRESENT);
 1316         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
 1317 }
 1318 
 1319 static void
 1320 iwn_sysctlattach(struct iwn_softc *sc)
 1321 {
 1322 #ifdef  IWN_DEBUG
 1323         struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
 1324         struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
 1325 
 1326         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
 1327             "debug", CTLFLAG_RW, &sc->sc_debug, sc->sc_debug,
 1328                 "control debugging printfs");
 1329 #endif
 1330 }
 1331 
 1332 static struct ieee80211vap *
 1333 iwn_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
 1334     enum ieee80211_opmode opmode, int flags,
 1335     const uint8_t bssid[IEEE80211_ADDR_LEN],
 1336     const uint8_t mac[IEEE80211_ADDR_LEN])
 1337 {
 1338         struct iwn_softc *sc = ic->ic_softc;
 1339         struct iwn_vap *ivp;
 1340         struct ieee80211vap *vap;
 1341 
 1342         if (!TAILQ_EMPTY(&ic->ic_vaps))         /* only one at a time */
 1343                 return NULL;
 1344 
 1345         ivp = malloc(sizeof(struct iwn_vap), M_80211_VAP, M_WAITOK | M_ZERO);
 1346         vap = &ivp->iv_vap;
 1347         ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid);
 1348         ivp->ctx = IWN_RXON_BSS_CTX;
 1349         vap->iv_bmissthreshold = 10;            /* override default */
 1350         /* Override with driver methods. */
 1351         ivp->iv_newstate = vap->iv_newstate;
 1352         vap->iv_newstate = iwn_newstate;
 1353         sc->ivap[IWN_RXON_BSS_CTX] = vap;
 1354 
 1355         ieee80211_ratectl_init(vap);
 1356         /* Complete setup. */
 1357         ieee80211_vap_attach(vap, iwn_media_change, ieee80211_media_status,
 1358             mac);
 1359         ic->ic_opmode = opmode;
 1360         return vap;
 1361 }
 1362 
 1363 static void
 1364 iwn_vap_delete(struct ieee80211vap *vap)
 1365 {
 1366         struct iwn_vap *ivp = IWN_VAP(vap);
 1367 
 1368         ieee80211_ratectl_deinit(vap);
 1369         ieee80211_vap_detach(vap);
 1370         free(ivp, M_80211_VAP);
 1371 }
 1372 
 1373 static void
 1374 iwn_xmit_queue_drain(struct iwn_softc *sc)
 1375 {
 1376         struct mbuf *m;
 1377         struct ieee80211_node *ni;
 1378 
 1379         IWN_LOCK_ASSERT(sc);
 1380         while ((m = mbufq_dequeue(&sc->sc_xmit_queue)) != NULL) {
 1381                 ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
 1382                 ieee80211_free_node(ni);
 1383                 m_freem(m);
 1384         }
 1385 }
 1386 
 1387 static int
 1388 iwn_xmit_queue_enqueue(struct iwn_softc *sc, struct mbuf *m)
 1389 {
 1390 
 1391         IWN_LOCK_ASSERT(sc);
 1392         return (mbufq_enqueue(&sc->sc_xmit_queue, m));
 1393 }
 1394 
 1395 static int
 1396 iwn_detach(device_t dev)
 1397 {
 1398         struct iwn_softc *sc = device_get_softc(dev);
 1399         int qid;
 1400 
 1401         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 1402 
 1403         if (sc->sc_ic.ic_softc != NULL) {
 1404                 /* Free the mbuf queue and node references */
 1405                 IWN_LOCK(sc);
 1406                 iwn_xmit_queue_drain(sc);
 1407                 IWN_UNLOCK(sc);
 1408 
 1409                 iwn_stop(sc);
 1410 
 1411                 taskqueue_drain_all(sc->sc_tq);
 1412                 taskqueue_free(sc->sc_tq);
 1413 
 1414                 callout_drain(&sc->watchdog_to);
 1415                 callout_drain(&sc->scan_timeout);
 1416                 callout_drain(&sc->calib_to);
 1417                 ieee80211_ifdetach(&sc->sc_ic);
 1418         }
 1419 
 1420         /* Uninstall interrupt handler. */
 1421         if (sc->irq != NULL) {
 1422                 bus_teardown_intr(dev, sc->irq, sc->sc_ih);
 1423                 bus_release_resource(dev, SYS_RES_IRQ, rman_get_rid(sc->irq),
 1424                     sc->irq);
 1425                 pci_release_msi(dev);
 1426         }
 1427 
 1428         /* Free DMA resources. */
 1429         iwn_free_rx_ring(sc, &sc->rxq);
 1430         for (qid = 0; qid < sc->ntxqs; qid++)
 1431                 iwn_free_tx_ring(sc, &sc->txq[qid]);
 1432         iwn_free_sched(sc);
 1433         iwn_free_kw(sc);
 1434         if (sc->ict != NULL)
 1435                 iwn_free_ict(sc);
 1436         iwn_free_fwmem(sc);
 1437 
 1438         if (sc->mem != NULL)
 1439                 bus_release_resource(dev, SYS_RES_MEMORY,
 1440                     rman_get_rid(sc->mem), sc->mem);
 1441 
 1442         if (sc->sc_cdev) {
 1443                 destroy_dev(sc->sc_cdev);
 1444                 sc->sc_cdev = NULL;
 1445         }
 1446 
 1447         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n", __func__);
 1448         IWN_LOCK_DESTROY(sc);
 1449         return 0;
 1450 }
 1451 
 1452 static int
 1453 iwn_shutdown(device_t dev)
 1454 {
 1455         struct iwn_softc *sc = device_get_softc(dev);
 1456 
 1457         iwn_stop(sc);
 1458         return 0;
 1459 }
 1460 
 1461 static int
 1462 iwn_suspend(device_t dev)
 1463 {
 1464         struct iwn_softc *sc = device_get_softc(dev);
 1465 
 1466         ieee80211_suspend_all(&sc->sc_ic);
 1467         return 0;
 1468 }
 1469 
 1470 static int
 1471 iwn_resume(device_t dev)
 1472 {
 1473         struct iwn_softc *sc = device_get_softc(dev);
 1474 
 1475         /* Clear device-specific "PCI retry timeout" register (41h). */
 1476         pci_write_config(dev, 0x41, 0, 1);
 1477 
 1478         ieee80211_resume_all(&sc->sc_ic);
 1479         return 0;
 1480 }
 1481 
 1482 static int
 1483 iwn_nic_lock(struct iwn_softc *sc)
 1484 {
 1485         int ntries;
 1486 
 1487         /* Request exclusive access to NIC. */
 1488         IWN_SETBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_MAC_ACCESS_REQ);
 1489 
 1490         /* Spin until we actually get the lock. */
 1491         for (ntries = 0; ntries < 1000; ntries++) {
 1492                 if ((IWN_READ(sc, IWN_GP_CNTRL) &
 1493                      (IWN_GP_CNTRL_MAC_ACCESS_ENA | IWN_GP_CNTRL_SLEEP)) ==
 1494                     IWN_GP_CNTRL_MAC_ACCESS_ENA)
 1495                         return 0;
 1496                 DELAY(10);
 1497         }
 1498         return ETIMEDOUT;
 1499 }
 1500 
 1501 static __inline void
 1502 iwn_nic_unlock(struct iwn_softc *sc)
 1503 {
 1504         IWN_CLRBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_MAC_ACCESS_REQ);
 1505 }
 1506 
 1507 static __inline uint32_t
 1508 iwn_prph_read(struct iwn_softc *sc, uint32_t addr)
 1509 {
 1510         IWN_WRITE(sc, IWN_PRPH_RADDR, IWN_PRPH_DWORD | addr);
 1511         IWN_BARRIER_READ_WRITE(sc);
 1512         return IWN_READ(sc, IWN_PRPH_RDATA);
 1513 }
 1514 
 1515 static __inline void
 1516 iwn_prph_write(struct iwn_softc *sc, uint32_t addr, uint32_t data)
 1517 {
 1518         IWN_WRITE(sc, IWN_PRPH_WADDR, IWN_PRPH_DWORD | addr);
 1519         IWN_BARRIER_WRITE(sc);
 1520         IWN_WRITE(sc, IWN_PRPH_WDATA, data);
 1521 }
 1522 
 1523 static __inline void
 1524 iwn_prph_setbits(struct iwn_softc *sc, uint32_t addr, uint32_t mask)
 1525 {
 1526         iwn_prph_write(sc, addr, iwn_prph_read(sc, addr) | mask);
 1527 }
 1528 
 1529 static __inline void
 1530 iwn_prph_clrbits(struct iwn_softc *sc, uint32_t addr, uint32_t mask)
 1531 {
 1532         iwn_prph_write(sc, addr, iwn_prph_read(sc, addr) & ~mask);
 1533 }
 1534 
 1535 static __inline void
 1536 iwn_prph_write_region_4(struct iwn_softc *sc, uint32_t addr,
 1537     const uint32_t *data, int count)
 1538 {
 1539         for (; count > 0; count--, data++, addr += 4)
 1540                 iwn_prph_write(sc, addr, *data);
 1541 }
 1542 
 1543 static __inline uint32_t
 1544 iwn_mem_read(struct iwn_softc *sc, uint32_t addr)
 1545 {
 1546         IWN_WRITE(sc, IWN_MEM_RADDR, addr);
 1547         IWN_BARRIER_READ_WRITE(sc);
 1548         return IWN_READ(sc, IWN_MEM_RDATA);
 1549 }
 1550 
 1551 static __inline void
 1552 iwn_mem_write(struct iwn_softc *sc, uint32_t addr, uint32_t data)
 1553 {
 1554         IWN_WRITE(sc, IWN_MEM_WADDR, addr);
 1555         IWN_BARRIER_WRITE(sc);
 1556         IWN_WRITE(sc, IWN_MEM_WDATA, data);
 1557 }
 1558 
 1559 static __inline void
 1560 iwn_mem_write_2(struct iwn_softc *sc, uint32_t addr, uint16_t data)
 1561 {
 1562         uint32_t tmp;
 1563 
 1564         tmp = iwn_mem_read(sc, addr & ~3);
 1565         if (addr & 3)
 1566                 tmp = (tmp & 0x0000ffff) | data << 16;
 1567         else
 1568                 tmp = (tmp & 0xffff0000) | data;
 1569         iwn_mem_write(sc, addr & ~3, tmp);
 1570 }
 1571 
 1572 static __inline void
 1573 iwn_mem_read_region_4(struct iwn_softc *sc, uint32_t addr, uint32_t *data,
 1574     int count)
 1575 {
 1576         for (; count > 0; count--, addr += 4)
 1577                 *data++ = iwn_mem_read(sc, addr);
 1578 }
 1579 
 1580 static __inline void
 1581 iwn_mem_set_region_4(struct iwn_softc *sc, uint32_t addr, uint32_t val,
 1582     int count)
 1583 {
 1584         for (; count > 0; count--, addr += 4)
 1585                 iwn_mem_write(sc, addr, val);
 1586 }
 1587 
 1588 static int
 1589 iwn_eeprom_lock(struct iwn_softc *sc)
 1590 {
 1591         int i, ntries;
 1592 
 1593         for (i = 0; i < 100; i++) {
 1594                 /* Request exclusive access to EEPROM. */
 1595                 IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
 1596                     IWN_HW_IF_CONFIG_EEPROM_LOCKED);
 1597 
 1598                 /* Spin until we actually get the lock. */
 1599                 for (ntries = 0; ntries < 100; ntries++) {
 1600                         if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
 1601                             IWN_HW_IF_CONFIG_EEPROM_LOCKED)
 1602                                 return 0;
 1603                         DELAY(10);
 1604                 }
 1605         }
 1606         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end timeout\n", __func__);
 1607         return ETIMEDOUT;
 1608 }
 1609 
 1610 static __inline void
 1611 iwn_eeprom_unlock(struct iwn_softc *sc)
 1612 {
 1613         IWN_CLRBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_EEPROM_LOCKED);
 1614 }
 1615 
 1616 /*
 1617  * Initialize access by host to One Time Programmable ROM.
 1618  * NB: This kind of ROM can be found on 1000 or 6000 Series only.
 1619  */
 1620 static int
 1621 iwn_init_otprom(struct iwn_softc *sc)
 1622 {
 1623         uint16_t prev, base, next;
 1624         int count, error;
 1625 
 1626         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 1627 
 1628         /* Wait for clock stabilization before accessing prph. */
 1629         if ((error = iwn_clock_wait(sc)) != 0)
 1630                 return error;
 1631 
 1632         if ((error = iwn_nic_lock(sc)) != 0)
 1633                 return error;
 1634         iwn_prph_setbits(sc, IWN_APMG_PS, IWN_APMG_PS_RESET_REQ);
 1635         DELAY(5);
 1636         iwn_prph_clrbits(sc, IWN_APMG_PS, IWN_APMG_PS_RESET_REQ);
 1637         iwn_nic_unlock(sc);
 1638 
 1639         /* Set auto clock gate disable bit for HW with OTP shadow RAM. */
 1640         if (sc->base_params->shadow_ram_support) {
 1641                 IWN_SETBITS(sc, IWN_DBG_LINK_PWR_MGMT,
 1642                     IWN_RESET_LINK_PWR_MGMT_DIS);
 1643         }
 1644         IWN_CLRBITS(sc, IWN_EEPROM_GP, IWN_EEPROM_GP_IF_OWNER);
 1645         /* Clear ECC status. */
 1646         IWN_SETBITS(sc, IWN_OTP_GP,
 1647             IWN_OTP_GP_ECC_CORR_STTS | IWN_OTP_GP_ECC_UNCORR_STTS);
 1648 
 1649         /*
 1650          * Find the block before last block (contains the EEPROM image)
 1651          * for HW without OTP shadow RAM.
 1652          */
 1653         if (! sc->base_params->shadow_ram_support) {
 1654                 /* Switch to absolute addressing mode. */
 1655                 IWN_CLRBITS(sc, IWN_OTP_GP, IWN_OTP_GP_RELATIVE_ACCESS);
 1656                 base = prev = 0;
 1657                 for (count = 0; count < sc->base_params->max_ll_items;
 1658                     count++) {
 1659                         error = iwn_read_prom_data(sc, base, &next, 2);
 1660                         if (error != 0)
 1661                                 return error;
 1662                         if (next == 0)  /* End of linked-list. */
 1663                                 break;
 1664                         prev = base;
 1665                         base = le16toh(next);
 1666                 }
 1667                 if (count == 0 || count == sc->base_params->max_ll_items)
 1668                         return EIO;
 1669                 /* Skip "next" word. */
 1670                 sc->prom_base = prev + 1;
 1671         }
 1672 
 1673         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
 1674 
 1675         return 0;
 1676 }
 1677 
 1678 static int
 1679 iwn_read_prom_data(struct iwn_softc *sc, uint32_t addr, void *data, int count)
 1680 {
 1681         uint8_t *out = data;
 1682         uint32_t val, tmp;
 1683         int ntries;
 1684 
 1685         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 1686 
 1687         addr += sc->prom_base;
 1688         for (; count > 0; count -= 2, addr++) {
 1689                 IWN_WRITE(sc, IWN_EEPROM, addr << 2);
 1690                 for (ntries = 0; ntries < 10; ntries++) {
 1691                         val = IWN_READ(sc, IWN_EEPROM);
 1692                         if (val & IWN_EEPROM_READ_VALID)
 1693                                 break;
 1694                         DELAY(5);
 1695                 }
 1696                 if (ntries == 10) {
 1697                         device_printf(sc->sc_dev,
 1698                             "timeout reading ROM at 0x%x\n", addr);
 1699                         return ETIMEDOUT;
 1700                 }
 1701                 if (sc->sc_flags & IWN_FLAG_HAS_OTPROM) {
 1702                         /* OTPROM, check for ECC errors. */
 1703                         tmp = IWN_READ(sc, IWN_OTP_GP);
 1704                         if (tmp & IWN_OTP_GP_ECC_UNCORR_STTS) {
 1705                                 device_printf(sc->sc_dev,
 1706                                     "OTPROM ECC error at 0x%x\n", addr);
 1707                                 return EIO;
 1708                         }
 1709                         if (tmp & IWN_OTP_GP_ECC_CORR_STTS) {
 1710                                 /* Correctable ECC error, clear bit. */
 1711                                 IWN_SETBITS(sc, IWN_OTP_GP,
 1712                                     IWN_OTP_GP_ECC_CORR_STTS);
 1713                         }
 1714                 }
 1715                 *out++ = val >> 16;
 1716                 if (count > 1)
 1717                         *out++ = val >> 24;
 1718         }
 1719 
 1720         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
 1721 
 1722         return 0;
 1723 }
 1724 
 1725 static void
 1726 iwn_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
 1727 {
 1728         if (error != 0)
 1729                 return;
 1730         KASSERT(nsegs == 1, ("too many DMA segments, %d should be 1", nsegs));
 1731         *(bus_addr_t *)arg = segs[0].ds_addr;
 1732 }
 1733 
 1734 static int
 1735 iwn_dma_contig_alloc(struct iwn_softc *sc, struct iwn_dma_info *dma,
 1736     void **kvap, bus_size_t size, bus_size_t alignment)
 1737 {
 1738         int error;
 1739 
 1740         dma->tag = NULL;
 1741         dma->size = size;
 1742 
 1743         error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), alignment,
 1744             0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, size,
 1745             1, size, 0, NULL, NULL, &dma->tag);
 1746         if (error != 0)
 1747                 goto fail;
 1748 
 1749         error = bus_dmamem_alloc(dma->tag, (void **)&dma->vaddr,
 1750             BUS_DMA_NOWAIT | BUS_DMA_ZERO | BUS_DMA_COHERENT, &dma->map);
 1751         if (error != 0)
 1752                 goto fail;
 1753 
 1754         error = bus_dmamap_load(dma->tag, dma->map, dma->vaddr, size,
 1755             iwn_dma_map_addr, &dma->paddr, BUS_DMA_NOWAIT);
 1756         if (error != 0)
 1757                 goto fail;
 1758 
 1759         bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
 1760 
 1761         if (kvap != NULL)
 1762                 *kvap = dma->vaddr;
 1763 
 1764         return 0;
 1765 
 1766 fail:   iwn_dma_contig_free(dma);
 1767         return error;
 1768 }
 1769 
 1770 static void
 1771 iwn_dma_contig_free(struct iwn_dma_info *dma)
 1772 {
 1773         if (dma->vaddr != NULL) {
 1774                 bus_dmamap_sync(dma->tag, dma->map,
 1775                     BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
 1776                 bus_dmamap_unload(dma->tag, dma->map);
 1777                 bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
 1778                 dma->vaddr = NULL;
 1779         }
 1780         if (dma->tag != NULL) {
 1781                 bus_dma_tag_destroy(dma->tag);
 1782                 dma->tag = NULL;
 1783         }
 1784 }
 1785 
 1786 static int
 1787 iwn_alloc_sched(struct iwn_softc *sc)
 1788 {
 1789         /* TX scheduler rings must be aligned on a 1KB boundary. */
 1790         return iwn_dma_contig_alloc(sc, &sc->sched_dma, (void **)&sc->sched,
 1791             sc->schedsz, 1024);
 1792 }
 1793 
 1794 static void
 1795 iwn_free_sched(struct iwn_softc *sc)
 1796 {
 1797         iwn_dma_contig_free(&sc->sched_dma);
 1798 }
 1799 
 1800 static int
 1801 iwn_alloc_kw(struct iwn_softc *sc)
 1802 {
 1803         /* "Keep Warm" page must be aligned on a 4KB boundary. */
 1804         return iwn_dma_contig_alloc(sc, &sc->kw_dma, NULL, 4096, 4096);
 1805 }
 1806 
 1807 static void
 1808 iwn_free_kw(struct iwn_softc *sc)
 1809 {
 1810         iwn_dma_contig_free(&sc->kw_dma);
 1811 }
 1812 
 1813 static int
 1814 iwn_alloc_ict(struct iwn_softc *sc)
 1815 {
 1816         /* ICT table must be aligned on a 4KB boundary. */
 1817         return iwn_dma_contig_alloc(sc, &sc->ict_dma, (void **)&sc->ict,
 1818             IWN_ICT_SIZE, 4096);
 1819 }
 1820 
 1821 static void
 1822 iwn_free_ict(struct iwn_softc *sc)
 1823 {
 1824         iwn_dma_contig_free(&sc->ict_dma);
 1825 }
 1826 
 1827 static int
 1828 iwn_alloc_fwmem(struct iwn_softc *sc)
 1829 {
 1830         /* Must be aligned on a 16-byte boundary. */
 1831         return iwn_dma_contig_alloc(sc, &sc->fw_dma, NULL, sc->fwsz, 16);
 1832 }
 1833 
 1834 static void
 1835 iwn_free_fwmem(struct iwn_softc *sc)
 1836 {
 1837         iwn_dma_contig_free(&sc->fw_dma);
 1838 }
 1839 
 1840 static int
 1841 iwn_alloc_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
 1842 {
 1843         bus_size_t size;
 1844         int i, error;
 1845 
 1846         ring->cur = 0;
 1847 
 1848         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 1849 
 1850         /* Allocate RX descriptors (256-byte aligned). */
 1851         size = IWN_RX_RING_COUNT * sizeof (uint32_t);
 1852         error = iwn_dma_contig_alloc(sc, &ring->desc_dma, (void **)&ring->desc,
 1853             size, 256);
 1854         if (error != 0) {
 1855                 device_printf(sc->sc_dev,
 1856                     "%s: could not allocate RX ring DMA memory, error %d\n",
 1857                     __func__, error);
 1858                 goto fail;
 1859         }
 1860 
 1861         /* Allocate RX status area (16-byte aligned). */
 1862         error = iwn_dma_contig_alloc(sc, &ring->stat_dma, (void **)&ring->stat,
 1863             sizeof (struct iwn_rx_status), 16);
 1864         if (error != 0) {
 1865                 device_printf(sc->sc_dev,
 1866                     "%s: could not allocate RX status DMA memory, error %d\n",
 1867                     __func__, error);
 1868                 goto fail;
 1869         }
 1870 
 1871         /* Create RX buffer DMA tag. */
 1872         error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
 1873             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
 1874             IWN_RBUF_SIZE, 1, IWN_RBUF_SIZE, 0, NULL, NULL, &ring->data_dmat);
 1875         if (error != 0) {
 1876                 device_printf(sc->sc_dev,
 1877                     "%s: could not create RX buf DMA tag, error %d\n",
 1878                     __func__, error);
 1879                 goto fail;
 1880         }
 1881 
 1882         /*
 1883          * Allocate and map RX buffers.
 1884          */
 1885         for (i = 0; i < IWN_RX_RING_COUNT; i++) {
 1886                 struct iwn_rx_data *data = &ring->data[i];
 1887                 bus_addr_t paddr;
 1888 
 1889                 error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
 1890                 if (error != 0) {
 1891                         device_printf(sc->sc_dev,
 1892                             "%s: could not create RX buf DMA map, error %d\n",
 1893                             __func__, error);
 1894                         goto fail;
 1895                 }
 1896 
 1897                 data->m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR,
 1898                     IWN_RBUF_SIZE);
 1899                 if (data->m == NULL) {
 1900                         device_printf(sc->sc_dev,
 1901                             "%s: could not allocate RX mbuf\n", __func__);
 1902                         error = ENOBUFS;
 1903                         goto fail;
 1904                 }
 1905 
 1906                 error = bus_dmamap_load(ring->data_dmat, data->map,
 1907                     mtod(data->m, void *), IWN_RBUF_SIZE, iwn_dma_map_addr,
 1908                     &paddr, BUS_DMA_NOWAIT);
 1909                 if (error != 0 && error != EFBIG) {
 1910                         device_printf(sc->sc_dev,
 1911                             "%s: can't map mbuf, error %d\n", __func__,
 1912                             error);
 1913                         goto fail;
 1914                 }
 1915 
 1916                 bus_dmamap_sync(ring->data_dmat, data->map,
 1917                     BUS_DMASYNC_PREREAD);
 1918 
 1919                 /* Set physical address of RX buffer (256-byte aligned). */
 1920                 ring->desc[i] = htole32(paddr >> 8);
 1921         }
 1922 
 1923         bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
 1924             BUS_DMASYNC_PREWRITE);
 1925 
 1926         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 1927 
 1928         return 0;
 1929 
 1930 fail:   iwn_free_rx_ring(sc, ring);
 1931 
 1932         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end in error\n",__func__);
 1933 
 1934         return error;
 1935 }
 1936 
 1937 static void
 1938 iwn_reset_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
 1939 {
 1940         int ntries;
 1941 
 1942         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 1943 
 1944         if (iwn_nic_lock(sc) == 0) {
 1945                 IWN_WRITE(sc, IWN_FH_RX_CONFIG, 0);
 1946                 for (ntries = 0; ntries < 1000; ntries++) {
 1947                         if (IWN_READ(sc, IWN_FH_RX_STATUS) &
 1948                             IWN_FH_RX_STATUS_IDLE)
 1949                                 break;
 1950                         DELAY(10);
 1951                 }
 1952                 iwn_nic_unlock(sc);
 1953         }
 1954         ring->cur = 0;
 1955         sc->last_rx_valid = 0;
 1956 }
 1957 
 1958 static void
 1959 iwn_free_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
 1960 {
 1961         int i;
 1962 
 1963         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s \n", __func__);
 1964 
 1965         iwn_dma_contig_free(&ring->desc_dma);
 1966         iwn_dma_contig_free(&ring->stat_dma);
 1967 
 1968         for (i = 0; i < IWN_RX_RING_COUNT; i++) {
 1969                 struct iwn_rx_data *data = &ring->data[i];
 1970 
 1971                 if (data->m != NULL) {
 1972                         bus_dmamap_sync(ring->data_dmat, data->map,
 1973                             BUS_DMASYNC_POSTREAD);
 1974                         bus_dmamap_unload(ring->data_dmat, data->map);
 1975                         m_freem(data->m);
 1976                         data->m = NULL;
 1977                 }
 1978                 if (data->map != NULL)
 1979                         bus_dmamap_destroy(ring->data_dmat, data->map);
 1980         }
 1981         if (ring->data_dmat != NULL) {
 1982                 bus_dma_tag_destroy(ring->data_dmat);
 1983                 ring->data_dmat = NULL;
 1984         }
 1985 }
 1986 
 1987 static int
 1988 iwn_alloc_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring, int qid)
 1989 {
 1990         bus_addr_t paddr;
 1991         bus_size_t size;
 1992         int i, error;
 1993 
 1994         ring->qid = qid;
 1995         ring->queued = 0;
 1996         ring->cur = 0;
 1997 
 1998         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 1999 
 2000         /* Allocate TX descriptors (256-byte aligned). */
 2001         size = IWN_TX_RING_COUNT * sizeof (struct iwn_tx_desc);
 2002         error = iwn_dma_contig_alloc(sc, &ring->desc_dma, (void **)&ring->desc,
 2003             size, 256);
 2004         if (error != 0) {
 2005                 device_printf(sc->sc_dev,
 2006                     "%s: could not allocate TX ring DMA memory, error %d\n",
 2007                     __func__, error);
 2008                 goto fail;
 2009         }
 2010 
 2011         size = IWN_TX_RING_COUNT * sizeof (struct iwn_tx_cmd);
 2012         error = iwn_dma_contig_alloc(sc, &ring->cmd_dma, (void **)&ring->cmd,
 2013             size, 4);
 2014         if (error != 0) {
 2015                 device_printf(sc->sc_dev,
 2016                     "%s: could not allocate TX cmd DMA memory, error %d\n",
 2017                     __func__, error);
 2018                 goto fail;
 2019         }
 2020 
 2021         error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
 2022             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
 2023             IWN_MAX_SCATTER - 1, MCLBYTES, 0, NULL, NULL, &ring->data_dmat);
 2024         if (error != 0) {
 2025                 device_printf(sc->sc_dev,
 2026                     "%s: could not create TX buf DMA tag, error %d\n",
 2027                     __func__, error);
 2028                 goto fail;
 2029         }
 2030 
 2031         paddr = ring->cmd_dma.paddr;
 2032         for (i = 0; i < IWN_TX_RING_COUNT; i++) {
 2033                 struct iwn_tx_data *data = &ring->data[i];
 2034 
 2035                 data->cmd_paddr = paddr;
 2036                 data->scratch_paddr = paddr + 12;
 2037                 paddr += sizeof (struct iwn_tx_cmd);
 2038 
 2039                 error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
 2040                 if (error != 0) {
 2041                         device_printf(sc->sc_dev,
 2042                             "%s: could not create TX buf DMA map, error %d\n",
 2043                             __func__, error);
 2044                         goto fail;
 2045                 }
 2046         }
 2047 
 2048         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
 2049 
 2050         return 0;
 2051 
 2052 fail:   iwn_free_tx_ring(sc, ring);
 2053         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end in error\n", __func__);
 2054         return error;
 2055 }
 2056 
 2057 static void
 2058 iwn_reset_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
 2059 {
 2060         int i;
 2061 
 2062         DPRINTF(sc, IWN_DEBUG_TRACE, "->doing %s \n", __func__);
 2063 
 2064         for (i = 0; i < IWN_TX_RING_COUNT; i++) {
 2065                 struct iwn_tx_data *data = &ring->data[i];
 2066 
 2067                 if (data->m != NULL) {
 2068                         bus_dmamap_sync(ring->data_dmat, data->map,
 2069                             BUS_DMASYNC_POSTWRITE);
 2070                         bus_dmamap_unload(ring->data_dmat, data->map);
 2071                         m_freem(data->m);
 2072                         data->m = NULL;
 2073                 }
 2074                 if (data->ni != NULL) {
 2075                         ieee80211_free_node(data->ni);
 2076                         data->ni = NULL;
 2077                 }
 2078         }
 2079         /* Clear TX descriptors. */
 2080         memset(ring->desc, 0, ring->desc_dma.size);
 2081         bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
 2082             BUS_DMASYNC_PREWRITE);
 2083         sc->qfullmsk &= ~(1 << ring->qid);
 2084         ring->queued = 0;
 2085         ring->cur = 0;
 2086 }
 2087 
 2088 static void
 2089 iwn_free_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
 2090 {
 2091         int i;
 2092 
 2093         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s \n", __func__);
 2094 
 2095         iwn_dma_contig_free(&ring->desc_dma);
 2096         iwn_dma_contig_free(&ring->cmd_dma);
 2097 
 2098         for (i = 0; i < IWN_TX_RING_COUNT; i++) {
 2099                 struct iwn_tx_data *data = &ring->data[i];
 2100 
 2101                 if (data->m != NULL) {
 2102                         bus_dmamap_sync(ring->data_dmat, data->map,
 2103                             BUS_DMASYNC_POSTWRITE);
 2104                         bus_dmamap_unload(ring->data_dmat, data->map);
 2105                         m_freem(data->m);
 2106                 }
 2107                 if (data->map != NULL)
 2108                         bus_dmamap_destroy(ring->data_dmat, data->map);
 2109         }
 2110         if (ring->data_dmat != NULL) {
 2111                 bus_dma_tag_destroy(ring->data_dmat);
 2112                 ring->data_dmat = NULL;
 2113         }
 2114 }
 2115 
 2116 static void
 2117 iwn5000_ict_reset(struct iwn_softc *sc)
 2118 {
 2119         /* Disable interrupts. */
 2120         IWN_WRITE(sc, IWN_INT_MASK, 0);
 2121 
 2122         /* Reset ICT table. */
 2123         memset(sc->ict, 0, IWN_ICT_SIZE);
 2124         sc->ict_cur = 0;
 2125 
 2126         bus_dmamap_sync(sc->ict_dma.tag, sc->ict_dma.map,
 2127             BUS_DMASYNC_PREWRITE);
 2128 
 2129         /* Set physical address of ICT table (4KB aligned). */
 2130         DPRINTF(sc, IWN_DEBUG_RESET, "%s: enabling ICT\n", __func__);
 2131         IWN_WRITE(sc, IWN_DRAM_INT_TBL, IWN_DRAM_INT_TBL_ENABLE |
 2132             IWN_DRAM_INT_TBL_WRAP_CHECK | sc->ict_dma.paddr >> 12);
 2133 
 2134         /* Enable periodic RX interrupt. */
 2135         sc->int_mask |= IWN_INT_RX_PERIODIC;
 2136         /* Switch to ICT interrupt mode in driver. */
 2137         sc->sc_flags |= IWN_FLAG_USE_ICT;
 2138 
 2139         /* Re-enable interrupts. */
 2140         IWN_WRITE(sc, IWN_INT, 0xffffffff);
 2141         IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
 2142 }
 2143 
 2144 static int
 2145 iwn_read_eeprom(struct iwn_softc *sc, uint8_t macaddr[IEEE80211_ADDR_LEN])
 2146 {
 2147         struct iwn_ops *ops = &sc->ops;
 2148         uint16_t val;
 2149         int error;
 2150 
 2151         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 2152 
 2153         /* Check whether adapter has an EEPROM or an OTPROM. */
 2154         if (sc->hw_type >= IWN_HW_REV_TYPE_1000 &&
 2155             (IWN_READ(sc, IWN_OTP_GP) & IWN_OTP_GP_DEV_SEL_OTP))
 2156                 sc->sc_flags |= IWN_FLAG_HAS_OTPROM;
 2157         DPRINTF(sc, IWN_DEBUG_RESET, "%s found\n",
 2158             (sc->sc_flags & IWN_FLAG_HAS_OTPROM) ? "OTPROM" : "EEPROM");
 2159 
 2160         /* Adapter has to be powered on for EEPROM access to work. */
 2161         if ((error = iwn_apm_init(sc)) != 0) {
 2162                 device_printf(sc->sc_dev,
 2163                     "%s: could not power ON adapter, error %d\n", __func__,
 2164                     error);
 2165                 return error;
 2166         }
 2167 
 2168         if ((IWN_READ(sc, IWN_EEPROM_GP) & 0x7) == 0) {
 2169                 device_printf(sc->sc_dev, "%s: bad ROM signature\n", __func__);
 2170                 return EIO;
 2171         }
 2172         if ((error = iwn_eeprom_lock(sc)) != 0) {
 2173                 device_printf(sc->sc_dev, "%s: could not lock ROM, error %d\n",
 2174                     __func__, error);
 2175                 return error;
 2176         }
 2177         if (sc->sc_flags & IWN_FLAG_HAS_OTPROM) {
 2178                 if ((error = iwn_init_otprom(sc)) != 0) {
 2179                         device_printf(sc->sc_dev,
 2180                             "%s: could not initialize OTPROM, error %d\n",
 2181                             __func__, error);
 2182                         return error;
 2183                 }
 2184         }
 2185 
 2186         iwn_read_prom_data(sc, IWN_EEPROM_SKU_CAP, &val, 2);
 2187         DPRINTF(sc, IWN_DEBUG_RESET, "SKU capabilities=0x%04x\n", le16toh(val));
 2188         /* Check if HT support is bonded out. */
 2189         if (val & htole16(IWN_EEPROM_SKU_CAP_11N))
 2190                 sc->sc_flags |= IWN_FLAG_HAS_11N;
 2191 
 2192         iwn_read_prom_data(sc, IWN_EEPROM_RFCFG, &val, 2);
 2193         sc->rfcfg = le16toh(val);
 2194         DPRINTF(sc, IWN_DEBUG_RESET, "radio config=0x%04x\n", sc->rfcfg);
 2195         /* Read Tx/Rx chains from ROM unless it's known to be broken. */
 2196         if (sc->txchainmask == 0)
 2197                 sc->txchainmask = IWN_RFCFG_TXANTMSK(sc->rfcfg);
 2198         if (sc->rxchainmask == 0)
 2199                 sc->rxchainmask = IWN_RFCFG_RXANTMSK(sc->rfcfg);
 2200 
 2201         /* Read MAC address. */
 2202         iwn_read_prom_data(sc, IWN_EEPROM_MAC, macaddr, 6);
 2203 
 2204         /* Read adapter-specific information from EEPROM. */
 2205         ops->read_eeprom(sc);
 2206 
 2207         iwn_apm_stop(sc);       /* Power OFF adapter. */
 2208 
 2209         iwn_eeprom_unlock(sc);
 2210 
 2211         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
 2212 
 2213         return 0;
 2214 }
 2215 
 2216 static void
 2217 iwn4965_read_eeprom(struct iwn_softc *sc)
 2218 {
 2219         uint32_t addr;
 2220         uint16_t val;
 2221         int i;
 2222 
 2223         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 2224 
 2225         /* Read regulatory domain (4 ASCII characters). */
 2226         iwn_read_prom_data(sc, IWN4965_EEPROM_DOMAIN, sc->eeprom_domain, 4);
 2227 
 2228         /* Read the list of authorized channels (20MHz & 40MHz). */
 2229         for (i = 0; i < IWN_NBANDS - 1; i++) {
 2230                 addr = iwn4965_regulatory_bands[i];
 2231                 iwn_read_eeprom_channels(sc, i, addr);
 2232         }
 2233 
 2234         /* Read maximum allowed TX power for 2GHz and 5GHz bands. */
 2235         iwn_read_prom_data(sc, IWN4965_EEPROM_MAXPOW, &val, 2);
 2236         sc->maxpwr2GHz = val & 0xff;
 2237         sc->maxpwr5GHz = val >> 8;
 2238         /* Check that EEPROM values are within valid range. */
 2239         if (sc->maxpwr5GHz < 20 || sc->maxpwr5GHz > 50)
 2240                 sc->maxpwr5GHz = 38;
 2241         if (sc->maxpwr2GHz < 20 || sc->maxpwr2GHz > 50)
 2242                 sc->maxpwr2GHz = 38;
 2243         DPRINTF(sc, IWN_DEBUG_RESET, "maxpwr 2GHz=%d 5GHz=%d\n",
 2244             sc->maxpwr2GHz, sc->maxpwr5GHz);
 2245 
 2246         /* Read samples for each TX power group. */
 2247         iwn_read_prom_data(sc, IWN4965_EEPROM_BANDS, sc->bands,
 2248             sizeof sc->bands);
 2249 
 2250         /* Read voltage at which samples were taken. */
 2251         iwn_read_prom_data(sc, IWN4965_EEPROM_VOLTAGE, &val, 2);
 2252         sc->eeprom_voltage = (int16_t)le16toh(val);
 2253         DPRINTF(sc, IWN_DEBUG_RESET, "voltage=%d (in 0.3V)\n",
 2254             sc->eeprom_voltage);
 2255 
 2256 #ifdef IWN_DEBUG
 2257         /* Print samples. */
 2258         if (sc->sc_debug & IWN_DEBUG_ANY) {
 2259                 for (i = 0; i < IWN_NBANDS - 1; i++)
 2260                         iwn4965_print_power_group(sc, i);
 2261         }
 2262 #endif
 2263 
 2264         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
 2265 }
 2266 
 2267 #ifdef IWN_DEBUG
 2268 static void
 2269 iwn4965_print_power_group(struct iwn_softc *sc, int i)
 2270 {
 2271         struct iwn4965_eeprom_band *band = &sc->bands[i];
 2272         struct iwn4965_eeprom_chan_samples *chans = band->chans;
 2273         int j, c;
 2274 
 2275         printf("===band %d===\n", i);
 2276         printf("chan lo=%d, chan hi=%d\n", band->lo, band->hi);
 2277         printf("chan1 num=%d\n", chans[0].num);
 2278         for (c = 0; c < 2; c++) {
 2279                 for (j = 0; j < IWN_NSAMPLES; j++) {
 2280                         printf("chain %d, sample %d: temp=%d gain=%d "
 2281                             "power=%d pa_det=%d\n", c, j,
 2282                             chans[0].samples[c][j].temp,
 2283                             chans[0].samples[c][j].gain,
 2284                             chans[0].samples[c][j].power,
 2285                             chans[0].samples[c][j].pa_det);
 2286                 }
 2287         }
 2288         printf("chan2 num=%d\n", chans[1].num);
 2289         for (c = 0; c < 2; c++) {
 2290                 for (j = 0; j < IWN_NSAMPLES; j++) {
 2291                         printf("chain %d, sample %d: temp=%d gain=%d "
 2292                             "power=%d pa_det=%d\n", c, j,
 2293                             chans[1].samples[c][j].temp,
 2294                             chans[1].samples[c][j].gain,
 2295                             chans[1].samples[c][j].power,
 2296                             chans[1].samples[c][j].pa_det);
 2297                 }
 2298         }
 2299 }
 2300 #endif
 2301 
 2302 static void
 2303 iwn5000_read_eeprom(struct iwn_softc *sc)
 2304 {
 2305         struct iwn5000_eeprom_calib_hdr hdr;
 2306         int32_t volt;
 2307         uint32_t base, addr;
 2308         uint16_t val;
 2309         int i;
 2310 
 2311         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 2312 
 2313         /* Read regulatory domain (4 ASCII characters). */
 2314         iwn_read_prom_data(sc, IWN5000_EEPROM_REG, &val, 2);
 2315         base = le16toh(val);
 2316         iwn_read_prom_data(sc, base + IWN5000_EEPROM_DOMAIN,
 2317             sc->eeprom_domain, 4);
 2318 
 2319         /* Read the list of authorized channels (20MHz & 40MHz). */
 2320         for (i = 0; i < IWN_NBANDS - 1; i++) {
 2321                 addr =  base + sc->base_params->regulatory_bands[i];
 2322                 iwn_read_eeprom_channels(sc, i, addr);
 2323         }
 2324 
 2325         /* Read enhanced TX power information for 6000 Series. */
 2326         if (sc->base_params->enhanced_TX_power)
 2327                 iwn_read_eeprom_enhinfo(sc);
 2328 
 2329         iwn_read_prom_data(sc, IWN5000_EEPROM_CAL, &val, 2);
 2330         base = le16toh(val);
 2331         iwn_read_prom_data(sc, base, &hdr, sizeof hdr);
 2332         DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 2333             "%s: calib version=%u pa type=%u voltage=%u\n", __func__,
 2334             hdr.version, hdr.pa_type, le16toh(hdr.volt));
 2335         sc->calib_ver = hdr.version;
 2336 
 2337         if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSETv2) {
 2338                 sc->eeprom_voltage = le16toh(hdr.volt);
 2339                 iwn_read_prom_data(sc, base + IWN5000_EEPROM_TEMP, &val, 2);
 2340                 sc->eeprom_temp_high=le16toh(val);
 2341                 iwn_read_prom_data(sc, base + IWN5000_EEPROM_VOLT, &val, 2);
 2342                 sc->eeprom_temp = le16toh(val);
 2343         }
 2344 
 2345         if (sc->hw_type == IWN_HW_REV_TYPE_5150) {
 2346                 /* Compute temperature offset. */
 2347                 iwn_read_prom_data(sc, base + IWN5000_EEPROM_TEMP, &val, 2);
 2348                 sc->eeprom_temp = le16toh(val);
 2349                 iwn_read_prom_data(sc, base + IWN5000_EEPROM_VOLT, &val, 2);
 2350                 volt = le16toh(val);
 2351                 sc->temp_off = sc->eeprom_temp - (volt / -5);
 2352                 DPRINTF(sc, IWN_DEBUG_CALIBRATE, "temp=%d volt=%d offset=%dK\n",
 2353                     sc->eeprom_temp, volt, sc->temp_off);
 2354         } else {
 2355                 /* Read crystal calibration. */
 2356                 iwn_read_prom_data(sc, base + IWN5000_EEPROM_CRYSTAL,
 2357                     &sc->eeprom_crystal, sizeof (uint32_t));
 2358                 DPRINTF(sc, IWN_DEBUG_CALIBRATE, "crystal calibration 0x%08x\n",
 2359                     le32toh(sc->eeprom_crystal));
 2360         }
 2361 
 2362         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
 2363 
 2364 }
 2365 
 2366 /*
 2367  * Translate EEPROM flags to net80211.
 2368  */
 2369 static uint32_t
 2370 iwn_eeprom_channel_flags(struct iwn_eeprom_chan *channel)
 2371 {
 2372         uint32_t nflags;
 2373 
 2374         nflags = 0;
 2375         if ((channel->flags & IWN_EEPROM_CHAN_ACTIVE) == 0)
 2376                 nflags |= IEEE80211_CHAN_PASSIVE;
 2377         if ((channel->flags & IWN_EEPROM_CHAN_IBSS) == 0)
 2378                 nflags |= IEEE80211_CHAN_NOADHOC;
 2379         if (channel->flags & IWN_EEPROM_CHAN_RADAR) {
 2380                 nflags |= IEEE80211_CHAN_DFS;
 2381                 /* XXX apparently IBSS may still be marked */
 2382                 nflags |= IEEE80211_CHAN_NOADHOC;
 2383         }
 2384 
 2385         return nflags;
 2386 }
 2387 
 2388 static void
 2389 iwn_read_eeprom_band(struct iwn_softc *sc, int n, int maxchans, int *nchans,
 2390     struct ieee80211_channel chans[])
 2391 {
 2392         struct iwn_eeprom_chan *channels = sc->eeprom_channels[n];
 2393         const struct iwn_chan_band *band = &iwn_bands[n];
 2394         uint8_t bands[IEEE80211_MODE_BYTES];
 2395         uint8_t chan;
 2396         int i, error, nflags;
 2397 
 2398         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 2399 
 2400         memset(bands, 0, sizeof(bands));
 2401         if (n == 0) {
 2402                 setbit(bands, IEEE80211_MODE_11B);
 2403                 setbit(bands, IEEE80211_MODE_11G);
 2404                 if (sc->sc_flags & IWN_FLAG_HAS_11N)
 2405                         setbit(bands, IEEE80211_MODE_11NG);
 2406         } else {
 2407                 setbit(bands, IEEE80211_MODE_11A);
 2408                 if (sc->sc_flags & IWN_FLAG_HAS_11N)
 2409                         setbit(bands, IEEE80211_MODE_11NA);
 2410         }
 2411 
 2412         for (i = 0; i < band->nchan; i++) {
 2413                 if (!(channels[i].flags & IWN_EEPROM_CHAN_VALID)) {
 2414                         DPRINTF(sc, IWN_DEBUG_RESET,
 2415                             "skip chan %d flags 0x%x maxpwr %d\n",
 2416                             band->chan[i], channels[i].flags,
 2417                             channels[i].maxpwr);
 2418                         continue;
 2419                 }
 2420 
 2421                 chan = band->chan[i];
 2422                 nflags = iwn_eeprom_channel_flags(&channels[i]);
 2423                 error = ieee80211_add_channel(chans, maxchans, nchans,
 2424                     chan, 0, channels[i].maxpwr, nflags, bands);
 2425                 if (error != 0)
 2426                         break;
 2427 
 2428                 /* Save maximum allowed TX power for this channel. */
 2429                 /* XXX wrong */
 2430                 sc->maxpwr[chan] = channels[i].maxpwr;
 2431 
 2432                 DPRINTF(sc, IWN_DEBUG_RESET,
 2433                     "add chan %d flags 0x%x maxpwr %d\n", chan,
 2434                     channels[i].flags, channels[i].maxpwr);
 2435         }
 2436 
 2437         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
 2438 
 2439 }
 2440 
 2441 static void
 2442 iwn_read_eeprom_ht40(struct iwn_softc *sc, int n, int maxchans, int *nchans,
 2443     struct ieee80211_channel chans[])
 2444 {
 2445         struct iwn_eeprom_chan *channels = sc->eeprom_channels[n];
 2446         const struct iwn_chan_band *band = &iwn_bands[n];
 2447         uint8_t chan;
 2448         int i, error, nflags;
 2449 
 2450         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s start\n", __func__);
 2451 
 2452         if (!(sc->sc_flags & IWN_FLAG_HAS_11N)) {
 2453                 DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end no 11n\n", __func__);
 2454                 return;
 2455         }
 2456 
 2457         for (i = 0; i < band->nchan; i++) {
 2458                 if (!(channels[i].flags & IWN_EEPROM_CHAN_VALID)) {
 2459                         DPRINTF(sc, IWN_DEBUG_RESET,
 2460                             "skip chan %d flags 0x%x maxpwr %d\n",
 2461                             band->chan[i], channels[i].flags,
 2462                             channels[i].maxpwr);
 2463                         continue;
 2464                 }
 2465 
 2466                 chan = band->chan[i];
 2467                 nflags = iwn_eeprom_channel_flags(&channels[i]);
 2468                 nflags |= (n == 5 ? IEEE80211_CHAN_G : IEEE80211_CHAN_A);
 2469                 error = ieee80211_add_channel_ht40(chans, maxchans, nchans,
 2470                     chan, channels[i].maxpwr, nflags);
 2471                 switch (error) {
 2472                 case EINVAL:
 2473                         device_printf(sc->sc_dev,
 2474                             "%s: no entry for channel %d\n", __func__, chan);
 2475                         continue;
 2476                 case ENOENT:
 2477                         DPRINTF(sc, IWN_DEBUG_RESET,
 2478                             "%s: skip chan %d, extension channel not found\n",
 2479                             __func__, chan);
 2480                         continue;
 2481                 case ENOBUFS:
 2482                         device_printf(sc->sc_dev,
 2483                             "%s: channel table is full!\n", __func__);
 2484                         break;
 2485                 case 0:
 2486                         DPRINTF(sc, IWN_DEBUG_RESET,
 2487                             "add ht40 chan %d flags 0x%x maxpwr %d\n",
 2488                             chan, channels[i].flags, channels[i].maxpwr);
 2489                         /* FALLTHROUGH */
 2490                 default:
 2491                         break;
 2492                 }
 2493         }
 2494 
 2495         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
 2496 
 2497 }
 2498 
 2499 static void
 2500 iwn_read_eeprom_channels(struct iwn_softc *sc, int n, uint32_t addr)
 2501 {
 2502         struct ieee80211com *ic = &sc->sc_ic;
 2503 
 2504         iwn_read_prom_data(sc, addr, &sc->eeprom_channels[n],
 2505             iwn_bands[n].nchan * sizeof (struct iwn_eeprom_chan));
 2506 
 2507         if (n < 5) {
 2508                 iwn_read_eeprom_band(sc, n, IEEE80211_CHAN_MAX, &ic->ic_nchans,
 2509                     ic->ic_channels);
 2510         } else {
 2511                 iwn_read_eeprom_ht40(sc, n, IEEE80211_CHAN_MAX, &ic->ic_nchans,
 2512                     ic->ic_channels);
 2513         }
 2514         ieee80211_sort_channels(ic->ic_channels, ic->ic_nchans);
 2515 }
 2516 
 2517 static struct iwn_eeprom_chan *
 2518 iwn_find_eeprom_channel(struct iwn_softc *sc, struct ieee80211_channel *c)
 2519 {
 2520         int band, chan, i, j;
 2521 
 2522         if (IEEE80211_IS_CHAN_HT40(c)) {
 2523                 band = IEEE80211_IS_CHAN_5GHZ(c) ? 6 : 5;
 2524                 if (IEEE80211_IS_CHAN_HT40D(c))
 2525                         chan = c->ic_extieee;
 2526                 else
 2527                         chan = c->ic_ieee;
 2528                 for (i = 0; i < iwn_bands[band].nchan; i++) {
 2529                         if (iwn_bands[band].chan[i] == chan)
 2530                                 return &sc->eeprom_channels[band][i];
 2531                 }
 2532         } else {
 2533                 for (j = 0; j < 5; j++) {
 2534                         for (i = 0; i < iwn_bands[j].nchan; i++) {
 2535                                 if (iwn_bands[j].chan[i] == c->ic_ieee &&
 2536                                     ((j == 0) ^ IEEE80211_IS_CHAN_A(c)) == 1)
 2537                                         return &sc->eeprom_channels[j][i];
 2538                         }
 2539                 }
 2540         }
 2541         return NULL;
 2542 }
 2543 
 2544 static void
 2545 iwn_getradiocaps(struct ieee80211com *ic,
 2546     int maxchans, int *nchans, struct ieee80211_channel chans[])
 2547 {
 2548         struct iwn_softc *sc = ic->ic_softc;
 2549         int i;
 2550 
 2551         /* Parse the list of authorized channels. */
 2552         for (i = 0; i < 5 && *nchans < maxchans; i++)
 2553                 iwn_read_eeprom_band(sc, i, maxchans, nchans, chans);
 2554         for (i = 5; i < IWN_NBANDS - 1 && *nchans < maxchans; i++)
 2555                 iwn_read_eeprom_ht40(sc, i, maxchans, nchans, chans);
 2556 }
 2557 
 2558 /*
 2559  * Enforce flags read from EEPROM.
 2560  */
 2561 static int
 2562 iwn_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *rd,
 2563     int nchan, struct ieee80211_channel chans[])
 2564 {
 2565         struct iwn_softc *sc = ic->ic_softc;
 2566         int i;
 2567 
 2568         for (i = 0; i < nchan; i++) {
 2569                 struct ieee80211_channel *c = &chans[i];
 2570                 struct iwn_eeprom_chan *channel;
 2571 
 2572                 channel = iwn_find_eeprom_channel(sc, c);
 2573                 if (channel == NULL) {
 2574                         ic_printf(ic, "%s: invalid channel %u freq %u/0x%x\n",
 2575                             __func__, c->ic_ieee, c->ic_freq, c->ic_flags);
 2576                         return EINVAL;
 2577                 }
 2578                 c->ic_flags |= iwn_eeprom_channel_flags(channel);
 2579         }
 2580 
 2581         return 0;
 2582 }
 2583 
 2584 static void
 2585 iwn_read_eeprom_enhinfo(struct iwn_softc *sc)
 2586 {
 2587         struct iwn_eeprom_enhinfo enhinfo[35];
 2588         struct ieee80211com *ic = &sc->sc_ic;
 2589         struct ieee80211_channel *c;
 2590         uint16_t val, base;
 2591         int8_t maxpwr;
 2592         uint8_t flags;
 2593         int i, j;
 2594 
 2595         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 2596 
 2597         iwn_read_prom_data(sc, IWN5000_EEPROM_REG, &val, 2);
 2598         base = le16toh(val);
 2599         iwn_read_prom_data(sc, base + IWN6000_EEPROM_ENHINFO,
 2600             enhinfo, sizeof enhinfo);
 2601 
 2602         for (i = 0; i < nitems(enhinfo); i++) {
 2603                 flags = enhinfo[i].flags;
 2604                 if (!(flags & IWN_ENHINFO_VALID))
 2605                         continue;       /* Skip invalid entries. */
 2606 
 2607                 maxpwr = 0;
 2608                 if (sc->txchainmask & IWN_ANT_A)
 2609                         maxpwr = MAX(maxpwr, enhinfo[i].chain[0]);
 2610                 if (sc->txchainmask & IWN_ANT_B)
 2611                         maxpwr = MAX(maxpwr, enhinfo[i].chain[1]);
 2612                 if (sc->txchainmask & IWN_ANT_C)
 2613                         maxpwr = MAX(maxpwr, enhinfo[i].chain[2]);
 2614                 if (sc->ntxchains == 2)
 2615                         maxpwr = MAX(maxpwr, enhinfo[i].mimo2);
 2616                 else if (sc->ntxchains == 3)
 2617                         maxpwr = MAX(maxpwr, enhinfo[i].mimo3);
 2618 
 2619                 for (j = 0; j < ic->ic_nchans; j++) {
 2620                         c = &ic->ic_channels[j];
 2621                         if ((flags & IWN_ENHINFO_5GHZ)) {
 2622                                 if (!IEEE80211_IS_CHAN_A(c))
 2623                                         continue;
 2624                         } else if ((flags & IWN_ENHINFO_OFDM)) {
 2625                                 if (!IEEE80211_IS_CHAN_G(c))
 2626                                         continue;
 2627                         } else if (!IEEE80211_IS_CHAN_B(c))
 2628                                 continue;
 2629                         if ((flags & IWN_ENHINFO_HT40)) {
 2630                                 if (!IEEE80211_IS_CHAN_HT40(c))
 2631                                         continue;
 2632                         } else {
 2633                                 if (IEEE80211_IS_CHAN_HT40(c))
 2634                                         continue;
 2635                         }
 2636                         if (enhinfo[i].chan != 0 &&
 2637                             enhinfo[i].chan != c->ic_ieee)
 2638                                 continue;
 2639 
 2640                         DPRINTF(sc, IWN_DEBUG_RESET,
 2641                             "channel %d(%x), maxpwr %d\n", c->ic_ieee,
 2642                             c->ic_flags, maxpwr / 2);
 2643                         c->ic_maxregpower = maxpwr / 2;
 2644                         c->ic_maxpower = maxpwr;
 2645                 }
 2646         }
 2647 
 2648         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
 2649 
 2650 }
 2651 
 2652 static struct ieee80211_node *
 2653 iwn_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
 2654 {
 2655         struct iwn_node *wn;
 2656 
 2657         wn = malloc(sizeof (struct iwn_node), M_80211_NODE, M_NOWAIT | M_ZERO);
 2658         if (wn == NULL)
 2659                 return (NULL);
 2660 
 2661         wn->id = IWN_ID_UNDEFINED;
 2662 
 2663         return (&wn->ni);
 2664 }
 2665 
 2666 static __inline int
 2667 rate2plcp(int rate)
 2668 {
 2669         switch (rate & 0xff) {
 2670         case 12:        return 0xd;
 2671         case 18:        return 0xf;
 2672         case 24:        return 0x5;
 2673         case 36:        return 0x7;
 2674         case 48:        return 0x9;
 2675         case 72:        return 0xb;
 2676         case 96:        return 0x1;
 2677         case 108:       return 0x3;
 2678         case 2:         return 10;
 2679         case 4:         return 20;
 2680         case 11:        return 55;
 2681         case 22:        return 110;
 2682         }
 2683         return 0;
 2684 }
 2685 
 2686 static __inline uint8_t
 2687 plcp2rate(const uint8_t rate_plcp)
 2688 {
 2689         switch (rate_plcp) {
 2690         case 0xd:       return 12;
 2691         case 0xf:       return 18;
 2692         case 0x5:       return 24;
 2693         case 0x7:       return 36;
 2694         case 0x9:       return 48;
 2695         case 0xb:       return 72;
 2696         case 0x1:       return 96;
 2697         case 0x3:       return 108;
 2698         case 10:        return 2;
 2699         case 20:        return 4;
 2700         case 55:        return 11;
 2701         case 110:       return 22;
 2702         default:        return 0;
 2703         }
 2704 }
 2705 
 2706 static int
 2707 iwn_get_1stream_tx_antmask(struct iwn_softc *sc)
 2708 {
 2709 
 2710         return IWN_LSB(sc->txchainmask);
 2711 }
 2712 
 2713 static int
 2714 iwn_get_2stream_tx_antmask(struct iwn_softc *sc)
 2715 {
 2716         int tx;
 2717 
 2718         /*
 2719          * The '2 stream' setup is a bit .. odd.
 2720          *
 2721          * For NICs that support only 1 antenna, default to IWN_ANT_AB or
 2722          * the firmware panics (eg Intel 5100.)
 2723          *
 2724          * For NICs that support two antennas, we use ANT_AB.
 2725          *
 2726          * For NICs that support three antennas, we use the two that
 2727          * wasn't the default one.
 2728          *
 2729          * XXX TODO: if bluetooth (full concurrent) is enabled, restrict
 2730          * this to only one antenna.
 2731          */
 2732 
 2733         /* Default - transmit on the other antennas */
 2734         tx = (sc->txchainmask & ~IWN_LSB(sc->txchainmask));
 2735 
 2736         /* Now, if it's zero, set it to IWN_ANT_AB, so to not panic firmware */
 2737         if (tx == 0)
 2738                 tx = IWN_ANT_AB;
 2739 
 2740         /*
 2741          * If the NIC is a two-stream TX NIC, configure the TX mask to
 2742          * the default chainmask
 2743          */
 2744         else if (sc->ntxchains == 2)
 2745                 tx = sc->txchainmask;
 2746 
 2747         return (tx);
 2748 }
 2749 
 2750 
 2751 
 2752 /*
 2753  * Calculate the required PLCP value from the given rate,
 2754  * to the given node.
 2755  *
 2756  * This will take the node configuration (eg 11n, rate table
 2757  * setup, etc) into consideration.
 2758  */
 2759 static uint32_t
 2760 iwn_rate_to_plcp(struct iwn_softc *sc, struct ieee80211_node *ni,
 2761     uint8_t rate)
 2762 {
 2763         struct ieee80211com *ic = ni->ni_ic;
 2764         uint32_t plcp = 0;
 2765         int ridx;
 2766 
 2767         /*
 2768          * If it's an MCS rate, let's set the plcp correctly
 2769          * and set the relevant flags based on the node config.
 2770          */
 2771         if (rate & IEEE80211_RATE_MCS) {
 2772                 /*
 2773                  * Set the initial PLCP value to be between 0->31 for
 2774                  * MCS 0 -> MCS 31, then set the "I'm an MCS rate!"
 2775                  * flag.
 2776                  */
 2777                 plcp = IEEE80211_RV(rate) | IWN_RFLAG_MCS;
 2778 
 2779                 /*
 2780                  * XXX the following should only occur if both
 2781                  * the local configuration _and_ the remote node
 2782                  * advertise these capabilities.  Thus this code
 2783                  * may need fixing!
 2784                  */
 2785 
 2786                 /*
 2787                  * Set the channel width and guard interval.
 2788                  */
 2789                 if (IEEE80211_IS_CHAN_HT40(ni->ni_chan)) {
 2790                         plcp |= IWN_RFLAG_HT40;
 2791                         if (ni->ni_htcap & IEEE80211_HTCAP_SHORTGI40)
 2792                                 plcp |= IWN_RFLAG_SGI;
 2793                 } else if (ni->ni_htcap & IEEE80211_HTCAP_SHORTGI20) {
 2794                         plcp |= IWN_RFLAG_SGI;
 2795                 }
 2796 
 2797                 /*
 2798                  * Ensure the selected rate matches the link quality
 2799                  * table entries being used.
 2800                  */
 2801                 if (rate > 0x8f)
 2802                         plcp |= IWN_RFLAG_ANT(sc->txchainmask);
 2803                 else if (rate > 0x87)
 2804                         plcp |= IWN_RFLAG_ANT(iwn_get_2stream_tx_antmask(sc));
 2805                 else
 2806                         plcp |= IWN_RFLAG_ANT(iwn_get_1stream_tx_antmask(sc));
 2807         } else {
 2808                 /*
 2809                  * Set the initial PLCP - fine for both
 2810                  * OFDM and CCK rates.
 2811                  */
 2812                 plcp = rate2plcp(rate);
 2813 
 2814                 /* Set CCK flag if it's CCK */
 2815 
 2816                 /* XXX It would be nice to have a method
 2817                  * to map the ridx -> phy table entry
 2818                  * so we could just query that, rather than
 2819                  * this hack to check against IWN_RIDX_OFDM6.
 2820                  */
 2821                 ridx = ieee80211_legacy_rate_lookup(ic->ic_rt,
 2822                     rate & IEEE80211_RATE_VAL);
 2823                 if (ridx < IWN_RIDX_OFDM6 &&
 2824                     IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
 2825                         plcp |= IWN_RFLAG_CCK;
 2826 
 2827                 /* Set antenna configuration */
 2828                 /* XXX TODO: is this the right antenna to use for legacy? */
 2829                 plcp |= IWN_RFLAG_ANT(iwn_get_1stream_tx_antmask(sc));
 2830         }
 2831 
 2832         DPRINTF(sc, IWN_DEBUG_TXRATE, "%s: rate=0x%02x, plcp=0x%08x\n",
 2833             __func__,
 2834             rate,
 2835             plcp);
 2836 
 2837         return (htole32(plcp));
 2838 }
 2839 
 2840 static void
 2841 iwn_newassoc(struct ieee80211_node *ni, int isnew)
 2842 {
 2843         /* Doesn't do anything at the moment */
 2844 }
 2845 
 2846 static int
 2847 iwn_media_change(struct ifnet *ifp)
 2848 {
 2849         int error;
 2850 
 2851         error = ieee80211_media_change(ifp);
 2852         /* NB: only the fixed rate can change and that doesn't need a reset */
 2853         return (error == ENETRESET ? 0 : error);
 2854 }
 2855 
 2856 static int
 2857 iwn_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 2858 {
 2859         struct iwn_vap *ivp = IWN_VAP(vap);
 2860         struct ieee80211com *ic = vap->iv_ic;
 2861         struct iwn_softc *sc = ic->ic_softc;
 2862         int error = 0;
 2863 
 2864         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 2865 
 2866         DPRINTF(sc, IWN_DEBUG_STATE, "%s: %s -> %s\n", __func__,
 2867             ieee80211_state_name[vap->iv_state], ieee80211_state_name[nstate]);
 2868 
 2869         IEEE80211_UNLOCK(ic);
 2870         IWN_LOCK(sc);
 2871         callout_stop(&sc->calib_to);
 2872 
 2873         sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
 2874 
 2875         switch (nstate) {
 2876         case IEEE80211_S_ASSOC:
 2877                 if (vap->iv_state != IEEE80211_S_RUN)
 2878                         break;
 2879                 /* FALLTHROUGH */
 2880         case IEEE80211_S_AUTH:
 2881                 if (vap->iv_state == IEEE80211_S_AUTH)
 2882                         break;
 2883 
 2884                 /*
 2885                  * !AUTH -> AUTH transition requires state reset to handle
 2886                  * reassociations correctly.
 2887                  */
 2888                 sc->rxon->associd = 0;
 2889                 sc->rxon->filter &= ~htole32(IWN_FILTER_BSS);
 2890                 sc->calib.state = IWN_CALIB_STATE_INIT;
 2891 
 2892                 /* Wait until we hear a beacon before we transmit */
 2893                 if (IEEE80211_IS_CHAN_PASSIVE(ic->ic_curchan))
 2894                         sc->sc_beacon_wait = 1;
 2895 
 2896                 if ((error = iwn_auth(sc, vap)) != 0) {
 2897                         device_printf(sc->sc_dev,
 2898                             "%s: could not move to auth state\n", __func__);
 2899                 }
 2900                 break;
 2901 
 2902         case IEEE80211_S_RUN:
 2903                 /*
 2904                  * RUN -> RUN transition; Just restart the timers.
 2905                  */
 2906                 if (vap->iv_state == IEEE80211_S_RUN) {
 2907                         sc->calib_cnt = 0;
 2908                         break;
 2909                 }
 2910 
 2911                 /* Wait until we hear a beacon before we transmit */
 2912                 if (IEEE80211_IS_CHAN_PASSIVE(ic->ic_curchan))
 2913                         sc->sc_beacon_wait = 1;
 2914 
 2915                 /*
 2916                  * !RUN -> RUN requires setting the association id
 2917                  * which is done with a firmware cmd.  We also defer
 2918                  * starting the timers until that work is done.
 2919                  */
 2920                 if ((error = iwn_run(sc, vap)) != 0) {
 2921                         device_printf(sc->sc_dev,
 2922                             "%s: could not move to run state\n", __func__);
 2923                 }
 2924                 break;
 2925 
 2926         case IEEE80211_S_INIT:
 2927                 sc->calib.state = IWN_CALIB_STATE_INIT;
 2928                 /*
 2929                  * Purge the xmit queue so we don't have old frames
 2930                  * during a new association attempt.
 2931                  */
 2932                 sc->sc_beacon_wait = 0;
 2933                 iwn_xmit_queue_drain(sc);
 2934                 break;
 2935 
 2936         default:
 2937                 break;
 2938         }
 2939         IWN_UNLOCK(sc);
 2940         IEEE80211_LOCK(ic);
 2941         if (error != 0){
 2942                 DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end in error\n", __func__);
 2943                 return error;
 2944         }
 2945 
 2946         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 2947 
 2948         return ivp->iv_newstate(vap, nstate, arg);
 2949 }
 2950 
 2951 static void
 2952 iwn_calib_timeout(void *arg)
 2953 {
 2954         struct iwn_softc *sc = arg;
 2955 
 2956         IWN_LOCK_ASSERT(sc);
 2957 
 2958         /* Force automatic TX power calibration every 60 secs. */
 2959         if (++sc->calib_cnt >= 120) {
 2960                 uint32_t flags = 0;
 2961 
 2962                 DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s\n",
 2963                     "sending request for statistics");
 2964                 (void)iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags,
 2965                     sizeof flags, 1);
 2966                 sc->calib_cnt = 0;
 2967         }
 2968         callout_reset(&sc->calib_to, msecs_to_ticks(500), iwn_calib_timeout,
 2969             sc);
 2970 }
 2971 
 2972 /*
 2973  * Process an RX_PHY firmware notification.  This is usually immediately
 2974  * followed by an MPDU_RX_DONE notification.
 2975  */
 2976 static void
 2977 iwn_rx_phy(struct iwn_softc *sc, struct iwn_rx_desc *desc)
 2978 {
 2979         struct iwn_rx_stat *stat = (struct iwn_rx_stat *)(desc + 1);
 2980 
 2981         DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: received PHY stats\n", __func__);
 2982 
 2983         /* Save RX statistics, they will be used on MPDU_RX_DONE. */
 2984         memcpy(&sc->last_rx_stat, stat, sizeof (*stat));
 2985         sc->last_rx_valid = 1;
 2986 }
 2987 
 2988 /*
 2989  * Process an RX_DONE (4965AGN only) or MPDU_RX_DONE firmware notification.
 2990  * Each MPDU_RX_DONE notification must be preceded by an RX_PHY one.
 2991  */
 2992 static void
 2993 iwn_rx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
 2994     struct iwn_rx_data *data)
 2995 {
 2996         struct iwn_ops *ops = &sc->ops;
 2997         struct ieee80211com *ic = &sc->sc_ic;
 2998         struct iwn_rx_ring *ring = &sc->rxq;
 2999         struct ieee80211_frame_min *wh;
 3000         struct ieee80211_node *ni;
 3001         struct mbuf *m, *m1;
 3002         struct iwn_rx_stat *stat;
 3003         caddr_t head;
 3004         bus_addr_t paddr;
 3005         uint32_t flags;
 3006         int error, len, rssi, nf;
 3007 
 3008         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 3009 
 3010         if (desc->type == IWN_MPDU_RX_DONE) {
 3011                 /* Check for prior RX_PHY notification. */
 3012                 if (!sc->last_rx_valid) {
 3013                         DPRINTF(sc, IWN_DEBUG_ANY,
 3014                             "%s: missing RX_PHY\n", __func__);
 3015                         return;
 3016                 }
 3017                 stat = &sc->last_rx_stat;
 3018         } else
 3019                 stat = (struct iwn_rx_stat *)(desc + 1);
 3020 
 3021         if (stat->cfg_phy_len > IWN_STAT_MAXLEN) {
 3022                 device_printf(sc->sc_dev,
 3023                     "%s: invalid RX statistic header, len %d\n", __func__,
 3024                     stat->cfg_phy_len);
 3025                 return;
 3026         }
 3027         if (desc->type == IWN_MPDU_RX_DONE) {
 3028                 struct iwn_rx_mpdu *mpdu = (struct iwn_rx_mpdu *)(desc + 1);
 3029                 head = (caddr_t)(mpdu + 1);
 3030                 len = le16toh(mpdu->len);
 3031         } else {
 3032                 head = (caddr_t)(stat + 1) + stat->cfg_phy_len;
 3033                 len = le16toh(stat->len);
 3034         }
 3035 
 3036         flags = le32toh(*(uint32_t *)(head + len));
 3037 
 3038         /* Discard frames with a bad FCS early. */
 3039         if ((flags & IWN_RX_NOERROR) != IWN_RX_NOERROR) {
 3040                 DPRINTF(sc, IWN_DEBUG_RECV, "%s: RX flags error %x\n",
 3041                     __func__, flags);
 3042                 counter_u64_add(ic->ic_ierrors, 1);
 3043                 return;
 3044         }
 3045         /* Discard frames that are too short. */
 3046         if (len < sizeof (struct ieee80211_frame_ack)) {
 3047                 DPRINTF(sc, IWN_DEBUG_RECV, "%s: frame too short: %d\n",
 3048                     __func__, len);
 3049                 counter_u64_add(ic->ic_ierrors, 1);
 3050                 return;
 3051         }
 3052 
 3053         m1 = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, IWN_RBUF_SIZE);
 3054         if (m1 == NULL) {
 3055                 DPRINTF(sc, IWN_DEBUG_ANY, "%s: no mbuf to restock ring\n",
 3056                     __func__);
 3057                 counter_u64_add(ic->ic_ierrors, 1);
 3058                 return;
 3059         }
 3060         bus_dmamap_unload(ring->data_dmat, data->map);
 3061 
 3062         error = bus_dmamap_load(ring->data_dmat, data->map, mtod(m1, void *),
 3063             IWN_RBUF_SIZE, iwn_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
 3064         if (error != 0 && error != EFBIG) {
 3065                 device_printf(sc->sc_dev,
 3066                     "%s: bus_dmamap_load failed, error %d\n", __func__, error);
 3067                 m_freem(m1);
 3068 
 3069                 /* Try to reload the old mbuf. */
 3070                 error = bus_dmamap_load(ring->data_dmat, data->map,
 3071                     mtod(data->m, void *), IWN_RBUF_SIZE, iwn_dma_map_addr,
 3072                     &paddr, BUS_DMA_NOWAIT);
 3073                 if (error != 0 && error != EFBIG) {
 3074                         panic("%s: could not load old RX mbuf", __func__);
 3075                 }
 3076                 bus_dmamap_sync(ring->data_dmat, data->map,
 3077                     BUS_DMASYNC_PREREAD);
 3078                 /* Physical address may have changed. */
 3079                 ring->desc[ring->cur] = htole32(paddr >> 8);
 3080                 bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
 3081                     BUS_DMASYNC_PREWRITE);
 3082                 counter_u64_add(ic->ic_ierrors, 1);
 3083                 return;
 3084         }
 3085 
 3086         bus_dmamap_sync(ring->data_dmat, data->map,
 3087             BUS_DMASYNC_PREREAD);
 3088 
 3089         m = data->m;
 3090         data->m = m1;
 3091         /* Update RX descriptor. */
 3092         ring->desc[ring->cur] = htole32(paddr >> 8);
 3093         bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
 3094             BUS_DMASYNC_PREWRITE);
 3095 
 3096         /* Finalize mbuf. */
 3097         m->m_data = head;
 3098         m->m_pkthdr.len = m->m_len = len;
 3099 
 3100         /* Grab a reference to the source node. */
 3101         wh = mtod(m, struct ieee80211_frame_min *);
 3102         if (len >= sizeof(struct ieee80211_frame_min))
 3103                 ni = ieee80211_find_rxnode(ic, wh);
 3104         else
 3105                 ni = NULL;
 3106         nf = (ni != NULL && ni->ni_vap->iv_state == IEEE80211_S_RUN &&
 3107             (ic->ic_flags & IEEE80211_F_SCAN) == 0) ? sc->noise : -95;
 3108 
 3109         rssi = ops->get_rssi(sc, stat);
 3110 
 3111         if (ieee80211_radiotap_active(ic)) {
 3112                 struct iwn_rx_radiotap_header *tap = &sc->sc_rxtap;
 3113                 uint32_t rate = le32toh(stat->rate);
 3114 
 3115                 tap->wr_flags = 0;
 3116                 if (stat->flags & htole16(IWN_STAT_FLAG_SHPREAMBLE))
 3117                         tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
 3118                 tap->wr_dbm_antsignal = (int8_t)rssi;
 3119                 tap->wr_dbm_antnoise = (int8_t)nf;
 3120                 tap->wr_tsft = stat->tstamp;
 3121                 if (rate & IWN_RFLAG_MCS) {
 3122                         tap->wr_rate = rate & IWN_RFLAG_RATE_MCS;
 3123                         tap->wr_rate |= IEEE80211_RATE_MCS;
 3124                 } else
 3125                         tap->wr_rate = plcp2rate(rate & IWN_RFLAG_RATE);
 3126         }
 3127 
 3128         /*
 3129          * If it's a beacon and we're waiting, then do the
 3130          * wakeup.  This should unblock raw_xmit/start.
 3131          */
 3132         if (sc->sc_beacon_wait) {
 3133                 uint8_t type, subtype;
 3134                 /* NB: Re-assign wh */
 3135                 wh = mtod(m, struct ieee80211_frame_min *);
 3136                 type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
 3137                 subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
 3138                 /*
 3139                  * This assumes at this point we've received our own
 3140                  * beacon.
 3141                  */
 3142                 DPRINTF(sc, IWN_DEBUG_TRACE,
 3143                     "%s: beacon_wait, type=%d, subtype=%d\n",
 3144                     __func__, type, subtype);
 3145                 if (type == IEEE80211_FC0_TYPE_MGT &&
 3146                     subtype == IEEE80211_FC0_SUBTYPE_BEACON) {
 3147                         DPRINTF(sc, IWN_DEBUG_TRACE | IWN_DEBUG_XMIT,
 3148                             "%s: waking things up\n", __func__);
 3149                         /* queue taskqueue to transmit! */
 3150                         taskqueue_enqueue(sc->sc_tq, &sc->sc_xmit_task);
 3151                 }
 3152         }
 3153 
 3154         IWN_UNLOCK(sc);
 3155 
 3156         /* Send the frame to the 802.11 layer. */
 3157         if (ni != NULL) {
 3158                 if (ni->ni_flags & IEEE80211_NODE_HT)
 3159                         m->m_flags |= M_AMPDU;
 3160                 (void)ieee80211_input(ni, m, rssi - nf, nf);
 3161                 /* Node is no longer needed. */
 3162                 ieee80211_free_node(ni);
 3163         } else
 3164                 (void)ieee80211_input_all(ic, m, rssi - nf, nf);
 3165 
 3166         IWN_LOCK(sc);
 3167 
 3168         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 3169 
 3170 }
 3171 
 3172 /* Process an incoming Compressed BlockAck. */
 3173 static void
 3174 iwn_rx_compressed_ba(struct iwn_softc *sc, struct iwn_rx_desc *desc)
 3175 {
 3176         struct ieee80211_ratectl_tx_status *txs = &sc->sc_txs;
 3177         struct iwn_ops *ops = &sc->ops;
 3178         struct iwn_node *wn;
 3179         struct ieee80211_node *ni;
 3180         struct iwn_compressed_ba *ba = (struct iwn_compressed_ba *)(desc + 1);
 3181         struct iwn_tx_ring *txq;
 3182         struct iwn_tx_data *txdata;
 3183         struct ieee80211_tx_ampdu *tap;
 3184         struct mbuf *m;
 3185         uint64_t bitmap;
 3186         uint16_t ssn;
 3187         uint8_t tid;
 3188         int i, lastidx, qid, *res, shift;
 3189         int tx_ok = 0, tx_err = 0;
 3190 
 3191         DPRINTF(sc, IWN_DEBUG_TRACE | IWN_DEBUG_XMIT, "->%s begin\n", __func__);
 3192 
 3193         qid = le16toh(ba->qid);
 3194         txq = &sc->txq[ba->qid];
 3195         tap = sc->qid2tap[ba->qid];
 3196         tid = tap->txa_tid;
 3197         wn = (void *)tap->txa_ni;
 3198 
 3199         res = NULL;
 3200         ssn = 0;
 3201         if (!IEEE80211_AMPDU_RUNNING(tap)) {
 3202                 res = tap->txa_private;
 3203                 ssn = tap->txa_start & 0xfff;
 3204         }
 3205 
 3206         for (lastidx = le16toh(ba->ssn) & 0xff; txq->read != lastidx;) {
 3207                 txdata = &txq->data[txq->read];
 3208 
 3209                 /* Unmap and free mbuf. */
 3210                 bus_dmamap_sync(txq->data_dmat, txdata->map,
 3211                     BUS_DMASYNC_POSTWRITE);
 3212                 bus_dmamap_unload(txq->data_dmat, txdata->map);
 3213                 m = txdata->m, txdata->m = NULL;
 3214                 ni = txdata->ni, txdata->ni = NULL;
 3215 
 3216                 KASSERT(ni != NULL, ("no node"));
 3217                 KASSERT(m != NULL, ("no mbuf"));
 3218 
 3219                 DPRINTF(sc, IWN_DEBUG_XMIT, "%s: freeing m=%p\n", __func__, m);
 3220                 ieee80211_tx_complete(ni, m, 1);
 3221 
 3222                 txq->queued--;
 3223                 txq->read = (txq->read + 1) % IWN_TX_RING_COUNT;
 3224         }
 3225 
 3226         if (txq->queued == 0 && res != NULL) {
 3227                 iwn_nic_lock(sc);
 3228                 ops->ampdu_tx_stop(sc, qid, tid, ssn);
 3229                 iwn_nic_unlock(sc);
 3230                 sc->qid2tap[qid] = NULL;
 3231                 free(res, M_DEVBUF);
 3232                 return;
 3233         }
 3234 
 3235         if (wn->agg[tid].bitmap == 0)
 3236                 return;
 3237 
 3238         shift = wn->agg[tid].startidx - ((le16toh(ba->seq) >> 4) & 0xff);
 3239         if (shift < 0)
 3240                 shift += 0x100;
 3241 
 3242         if (wn->agg[tid].nframes > (64 - shift))
 3243                 return;
 3244 
 3245         /*
 3246          * Walk the bitmap and calculate how many successful and failed
 3247          * attempts are made.
 3248          *
 3249          * Yes, the rate control code doesn't know these are A-MPDU
 3250          * subframes and that it's okay to fail some of these.
 3251          */
 3252         ni = tap->txa_ni;
 3253         bitmap = (le64toh(ba->bitmap) >> shift) & wn->agg[tid].bitmap;
 3254         for (i = 0; bitmap; i++) {
 3255                 txs->flags = 0;         /* XXX TODO */
 3256                 if ((bitmap & 1) == 0) {
 3257                         tx_err ++;
 3258                         txs->status = IEEE80211_RATECTL_TX_FAIL_UNSPECIFIED;
 3259                 } else {
 3260                         tx_ok ++;
 3261                         txs->status = IEEE80211_RATECTL_TX_SUCCESS;
 3262                 }
 3263                 ieee80211_ratectl_tx_complete(ni, txs);
 3264                 bitmap >>= 1;
 3265         }
 3266 
 3267         DPRINTF(sc, IWN_DEBUG_TRACE | IWN_DEBUG_XMIT,
 3268             "->%s: end; %d ok; %d err\n",__func__, tx_ok, tx_err);
 3269 
 3270 }
 3271 
 3272 /*
 3273  * Process a CALIBRATION_RESULT notification sent by the initialization
 3274  * firmware on response to a CMD_CALIB_CONFIG command (5000 only).
 3275  */
 3276 static void
 3277 iwn5000_rx_calib_results(struct iwn_softc *sc, struct iwn_rx_desc *desc)
 3278 {
 3279         struct iwn_phy_calib *calib = (struct iwn_phy_calib *)(desc + 1);
 3280         int len, idx = -1;
 3281 
 3282         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 3283 
 3284         /* Runtime firmware should not send such a notification. */
 3285         if (sc->sc_flags & IWN_FLAG_CALIB_DONE){
 3286                 DPRINTF(sc, IWN_DEBUG_TRACE,
 3287                     "->%s received after calib done\n", __func__);
 3288                 return;
 3289         }
 3290         len = (le32toh(desc->len) & 0x3fff) - 4;
 3291 
 3292         switch (calib->code) {
 3293         case IWN5000_PHY_CALIB_DC:
 3294                 if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_DC)
 3295                         idx = 0;
 3296                 break;
 3297         case IWN5000_PHY_CALIB_LO:
 3298                 if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_LO)
 3299                         idx = 1;
 3300                 break;
 3301         case IWN5000_PHY_CALIB_TX_IQ:
 3302                 if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TX_IQ)
 3303                         idx = 2;
 3304                 break;
 3305         case IWN5000_PHY_CALIB_TX_IQ_PERIODIC:
 3306                 if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TX_IQ_PERIODIC)
 3307                         idx = 3;
 3308                 break;
 3309         case IWN5000_PHY_CALIB_BASE_BAND:
 3310                 if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_BASE_BAND)
 3311                         idx = 4;
 3312                 break;
 3313         }
 3314         if (idx == -1)  /* Ignore other results. */
 3315                 return;
 3316 
 3317         /* Save calibration result. */
 3318         if (sc->calibcmd[idx].buf != NULL)
 3319                 free(sc->calibcmd[idx].buf, M_DEVBUF);
 3320         sc->calibcmd[idx].buf = malloc(len, M_DEVBUF, M_NOWAIT);
 3321         if (sc->calibcmd[idx].buf == NULL) {
 3322                 DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 3323                     "not enough memory for calibration result %d\n",
 3324                     calib->code);
 3325                 return;
 3326         }
 3327         DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 3328             "saving calibration result idx=%d, code=%d len=%d\n", idx, calib->code, len);
 3329         sc->calibcmd[idx].len = len;
 3330         memcpy(sc->calibcmd[idx].buf, calib, len);
 3331 }
 3332 
 3333 static void
 3334 iwn_stats_update(struct iwn_softc *sc, struct iwn_calib_state *calib,
 3335     struct iwn_stats *stats, int len)
 3336 {
 3337         struct iwn_stats_bt *stats_bt;
 3338         struct iwn_stats *lstats;
 3339 
 3340         /*
 3341          * First - check whether the length is the bluetooth or normal.
 3342          *
 3343          * If it's normal - just copy it and bump out.
 3344          * Otherwise we have to convert things.
 3345          */
 3346 
 3347         if (len == sizeof(struct iwn_stats) + 4) {
 3348                 memcpy(&sc->last_stat, stats, sizeof(struct iwn_stats));
 3349                 sc->last_stat_valid = 1;
 3350                 return;
 3351         }
 3352 
 3353         /*
 3354          * If it's not the bluetooth size - log, then just copy.
 3355          */
 3356         if (len != sizeof(struct iwn_stats_bt) + 4) {
 3357                 DPRINTF(sc, IWN_DEBUG_STATS,
 3358                     "%s: size of rx statistics (%d) not an expected size!\n",
 3359                     __func__,
 3360                     len);
 3361                 memcpy(&sc->last_stat, stats, sizeof(struct iwn_stats));
 3362                 sc->last_stat_valid = 1;
 3363                 return;
 3364         }
 3365 
 3366         /*
 3367          * Ok. Time to copy.
 3368          */
 3369         stats_bt = (struct iwn_stats_bt *) stats;
 3370         lstats = &sc->last_stat;
 3371 
 3372         /* flags */
 3373         lstats->flags = stats_bt->flags;
 3374         /* rx_bt */
 3375         memcpy(&lstats->rx.ofdm, &stats_bt->rx_bt.ofdm,
 3376             sizeof(struct iwn_rx_phy_stats));
 3377         memcpy(&lstats->rx.cck, &stats_bt->rx_bt.cck,
 3378             sizeof(struct iwn_rx_phy_stats));
 3379         memcpy(&lstats->rx.general, &stats_bt->rx_bt.general_bt.common,
 3380             sizeof(struct iwn_rx_general_stats));
 3381         memcpy(&lstats->rx.ht, &stats_bt->rx_bt.ht,
 3382             sizeof(struct iwn_rx_ht_phy_stats));
 3383         /* tx */
 3384         memcpy(&lstats->tx, &stats_bt->tx,
 3385             sizeof(struct iwn_tx_stats));
 3386         /* general */
 3387         memcpy(&lstats->general, &stats_bt->general,
 3388             sizeof(struct iwn_general_stats));
 3389 
 3390         /* XXX TODO: Squirrel away the extra bluetooth stats somewhere */
 3391         sc->last_stat_valid = 1;
 3392 }
 3393 
 3394 /*
 3395  * Process an RX_STATISTICS or BEACON_STATISTICS firmware notification.
 3396  * The latter is sent by the firmware after each received beacon.
 3397  */
 3398 static void
 3399 iwn_rx_statistics(struct iwn_softc *sc, struct iwn_rx_desc *desc)
 3400 {
 3401         struct iwn_ops *ops = &sc->ops;
 3402         struct ieee80211com *ic = &sc->sc_ic;
 3403         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
 3404         struct iwn_calib_state *calib = &sc->calib;
 3405         struct iwn_stats *stats = (struct iwn_stats *)(desc + 1);
 3406         struct iwn_stats *lstats;
 3407         int temp;
 3408 
 3409         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 3410 
 3411         /* Ignore statistics received during a scan. */
 3412         if (vap->iv_state != IEEE80211_S_RUN ||
 3413             (ic->ic_flags & IEEE80211_F_SCAN)){
 3414                 DPRINTF(sc, IWN_DEBUG_TRACE, "->%s received during calib\n",
 3415             __func__);
 3416                 return;
 3417         }
 3418 
 3419         DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_STATS,
 3420             "%s: received statistics, cmd %d, len %d\n",
 3421             __func__, desc->type, le16toh(desc->len));
 3422         sc->calib_cnt = 0;      /* Reset TX power calibration timeout. */
 3423 
 3424         /*
 3425          * Collect/track general statistics for reporting.
 3426          *
 3427          * This takes care of ensuring that the bluetooth sized message
 3428          * will be correctly converted to the legacy sized message.
 3429          */
 3430         iwn_stats_update(sc, calib, stats, le16toh(desc->len));
 3431 
 3432         /*
 3433          * And now, let's take a reference of it to use!
 3434          */
 3435         lstats = &sc->last_stat;
 3436 
 3437         /* Test if temperature has changed. */
 3438         if (lstats->general.temp != sc->rawtemp) {
 3439                 /* Convert "raw" temperature to degC. */
 3440                 sc->rawtemp = stats->general.temp;
 3441                 temp = ops->get_temperature(sc);
 3442                 DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: temperature %d\n",
 3443                     __func__, temp);
 3444 
 3445                 /* Update TX power if need be (4965AGN only). */
 3446                 if (sc->hw_type == IWN_HW_REV_TYPE_4965)
 3447                         iwn4965_power_calibration(sc, temp);
 3448         }
 3449 
 3450         if (desc->type != IWN_BEACON_STATISTICS)
 3451                 return; /* Reply to a statistics request. */
 3452 
 3453         sc->noise = iwn_get_noise(&lstats->rx.general);
 3454         DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: noise %d\n", __func__, sc->noise);
 3455 
 3456         /* Test that RSSI and noise are present in stats report. */
 3457         if (le32toh(lstats->rx.general.flags) != 1) {
 3458                 DPRINTF(sc, IWN_DEBUG_ANY, "%s\n",
 3459                     "received statistics without RSSI");
 3460                 return;
 3461         }
 3462 
 3463         if (calib->state == IWN_CALIB_STATE_ASSOC)
 3464                 iwn_collect_noise(sc, &lstats->rx.general);
 3465         else if (calib->state == IWN_CALIB_STATE_RUN) {
 3466                 iwn_tune_sensitivity(sc, &lstats->rx);
 3467                 /*
 3468                  * XXX TODO: Only run the RX recovery if we're associated!
 3469                  */
 3470                 iwn_check_rx_recovery(sc, lstats);
 3471                 iwn_save_stats_counters(sc, lstats);
 3472         }
 3473 
 3474         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 3475 }
 3476 
 3477 /*
 3478  * Save the relevant statistic counters for the next calibration
 3479  * pass.
 3480  */
 3481 static void
 3482 iwn_save_stats_counters(struct iwn_softc *sc, const struct iwn_stats *rs)
 3483 {
 3484         struct iwn_calib_state *calib = &sc->calib;
 3485 
 3486         /* Save counters values for next call. */
 3487         calib->bad_plcp_cck = le32toh(rs->rx.cck.bad_plcp);
 3488         calib->fa_cck = le32toh(rs->rx.cck.fa);
 3489         calib->bad_plcp_ht = le32toh(rs->rx.ht.bad_plcp);
 3490         calib->bad_plcp_ofdm = le32toh(rs->rx.ofdm.bad_plcp);
 3491         calib->fa_ofdm = le32toh(rs->rx.ofdm.fa);
 3492 
 3493         /* Last time we received these tick values */
 3494         sc->last_calib_ticks = ticks;
 3495 }
 3496 
 3497 /*
 3498  * Process a TX_DONE firmware notification.  Unfortunately, the 4965AGN
 3499  * and 5000 adapters have different incompatible TX status formats.
 3500  */
 3501 static void
 3502 iwn4965_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
 3503     struct iwn_rx_data *data)
 3504 {
 3505         struct iwn4965_tx_stat *stat = (struct iwn4965_tx_stat *)(desc + 1);
 3506         int qid = desc->qid & IWN_RX_DESC_QID_MSK;
 3507 
 3508         DPRINTF(sc, IWN_DEBUG_XMIT, "%s: "
 3509             "qid %d idx %d RTS retries %d ACK retries %d nkill %d rate %x duration %d status %x\n",
 3510             __func__, desc->qid, desc->idx,
 3511             stat->rtsfailcnt,
 3512             stat->ackfailcnt,
 3513             stat->btkillcnt,
 3514             stat->rate, le16toh(stat->duration),
 3515             le32toh(stat->status));
 3516 
 3517         if (qid >= sc->firstaggqueue) {
 3518                 iwn_ampdu_tx_done(sc, qid, desc->idx, stat->nframes,
 3519                     stat->rtsfailcnt, stat->ackfailcnt, &stat->status);
 3520         } else {
 3521                 iwn_tx_done(sc, desc, stat->rtsfailcnt, stat->ackfailcnt,
 3522                     le32toh(stat->status) & 0xff);
 3523         }
 3524 }
 3525 
 3526 static void
 3527 iwn5000_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
 3528     struct iwn_rx_data *data)
 3529 {
 3530         struct iwn5000_tx_stat *stat = (struct iwn5000_tx_stat *)(desc + 1);
 3531         int qid = desc->qid & IWN_RX_DESC_QID_MSK;
 3532 
 3533         DPRINTF(sc, IWN_DEBUG_XMIT, "%s: "
 3534             "qid %d idx %d RTS retries %d ACK retries %d nkill %d rate %x duration %d status %x\n",
 3535             __func__, desc->qid, desc->idx,
 3536             stat->rtsfailcnt,
 3537             stat->ackfailcnt,
 3538             stat->btkillcnt,
 3539             stat->rate, le16toh(stat->duration),
 3540             le32toh(stat->status));
 3541 
 3542 #ifdef notyet
 3543         /* Reset TX scheduler slot. */
 3544         iwn5000_reset_sched(sc, qid, desc->idx);
 3545 #endif
 3546 
 3547         if (qid >= sc->firstaggqueue) {
 3548                 iwn_ampdu_tx_done(sc, qid, desc->idx, stat->nframes,
 3549                     stat->rtsfailcnt, stat->ackfailcnt, &stat->status);
 3550         } else {
 3551                 iwn_tx_done(sc, desc, stat->rtsfailcnt, stat->ackfailcnt,
 3552                     le16toh(stat->status) & 0xff);
 3553         }
 3554 }
 3555 
 3556 /*
 3557  * Adapter-independent backend for TX_DONE firmware notifications.
 3558  */
 3559 static void
 3560 iwn_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc, int rtsfailcnt,
 3561     int ackfailcnt, uint8_t status)
 3562 {
 3563         struct ieee80211_ratectl_tx_status *txs = &sc->sc_txs;
 3564         struct iwn_tx_ring *ring = &sc->txq[desc->qid & IWN_RX_DESC_QID_MSK];
 3565         struct iwn_tx_data *data = &ring->data[desc->idx];
 3566         struct mbuf *m;
 3567         struct ieee80211_node *ni;
 3568 
 3569         KASSERT(data->ni != NULL, ("no node"));
 3570 
 3571         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 3572 
 3573         /* Unmap and free mbuf. */
 3574         bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTWRITE);
 3575         bus_dmamap_unload(ring->data_dmat, data->map);
 3576         m = data->m, data->m = NULL;
 3577         ni = data->ni, data->ni = NULL;
 3578 
 3579         /*
 3580          * Update rate control statistics for the node.
 3581          */
 3582         txs->flags = IEEE80211_RATECTL_STATUS_SHORT_RETRY |
 3583                      IEEE80211_RATECTL_STATUS_LONG_RETRY;
 3584         txs->short_retries = rtsfailcnt;
 3585         txs->long_retries = ackfailcnt;
 3586         if (!(status & IWN_TX_FAIL))
 3587                 txs->status = IEEE80211_RATECTL_TX_SUCCESS;
 3588         else {
 3589                 switch (status) {
 3590                 case IWN_TX_FAIL_SHORT_LIMIT:
 3591                         txs->status = IEEE80211_RATECTL_TX_FAIL_SHORT;
 3592                         break;
 3593                 case IWN_TX_FAIL_LONG_LIMIT:
 3594                         txs->status = IEEE80211_RATECTL_TX_FAIL_LONG;
 3595                         break;
 3596                 case IWN_TX_STATUS_FAIL_LIFE_EXPIRE:
 3597                         txs->status = IEEE80211_RATECTL_TX_FAIL_EXPIRED;
 3598                         break;
 3599                 default:
 3600                         txs->status = IEEE80211_RATECTL_TX_FAIL_UNSPECIFIED;
 3601                         break;
 3602                 }
 3603         }
 3604         ieee80211_ratectl_tx_complete(ni, txs);
 3605 
 3606         /*
 3607          * Channels marked for "radar" require traffic to be received
 3608          * to unlock before we can transmit.  Until traffic is seen
 3609          * any attempt to transmit is returned immediately with status
 3610          * set to IWN_TX_FAIL_TX_LOCKED.  Unfortunately this can easily
 3611          * happen on first authenticate after scanning.  To workaround
 3612          * this we ignore a failure of this sort in AUTH state so the
 3613          * 802.11 layer will fall back to using a timeout to wait for
 3614          * the AUTH reply.  This allows the firmware time to see
 3615          * traffic so a subsequent retry of AUTH succeeds.  It's
 3616          * unclear why the firmware does not maintain state for
 3617          * channels recently visited as this would allow immediate
 3618          * use of the channel after a scan (where we see traffic).
 3619          */
 3620         if (status == IWN_TX_FAIL_TX_LOCKED &&
 3621             ni->ni_vap->iv_state == IEEE80211_S_AUTH)
 3622                 ieee80211_tx_complete(ni, m, 0);
 3623         else
 3624                 ieee80211_tx_complete(ni, m,
 3625                     (status & IWN_TX_FAIL) != 0);
 3626 
 3627         sc->sc_tx_timer = 0;
 3628         if (--ring->queued < IWN_TX_RING_LOMARK)
 3629                 sc->qfullmsk &= ~(1 << ring->qid);
 3630 
 3631         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 3632 }
 3633 
 3634 /*
 3635  * Process a "command done" firmware notification.  This is where we wakeup
 3636  * processes waiting for a synchronous command completion.
 3637  */
 3638 static void
 3639 iwn_cmd_done(struct iwn_softc *sc, struct iwn_rx_desc *desc)
 3640 {
 3641         struct iwn_tx_ring *ring;
 3642         struct iwn_tx_data *data;
 3643         int cmd_queue_num;
 3644 
 3645         if (sc->sc_flags & IWN_FLAG_PAN_SUPPORT)
 3646                 cmd_queue_num = IWN_PAN_CMD_QUEUE;
 3647         else
 3648                 cmd_queue_num = IWN_CMD_QUEUE_NUM;
 3649 
 3650         if ((desc->qid & IWN_RX_DESC_QID_MSK) != cmd_queue_num)
 3651                 return; /* Not a command ack. */
 3652 
 3653         ring = &sc->txq[cmd_queue_num];
 3654         data = &ring->data[desc->idx];
 3655 
 3656         /* If the command was mapped in an mbuf, free it. */
 3657         if (data->m != NULL) {
 3658                 bus_dmamap_sync(ring->data_dmat, data->map,
 3659                     BUS_DMASYNC_POSTWRITE);
 3660                 bus_dmamap_unload(ring->data_dmat, data->map);
 3661                 m_freem(data->m);
 3662                 data->m = NULL;
 3663         }
 3664         wakeup(&ring->desc[desc->idx]);
 3665 }
 3666 
 3667 static void
 3668 iwn_ampdu_tx_done(struct iwn_softc *sc, int qid, int idx, int nframes,
 3669     int rtsfailcnt, int ackfailcnt, void *stat)
 3670 {
 3671         struct iwn_ops *ops = &sc->ops;
 3672         struct iwn_tx_ring *ring = &sc->txq[qid];
 3673         struct ieee80211_ratectl_tx_status *txs = &sc->sc_txs;
 3674         struct iwn_tx_data *data;
 3675         struct mbuf *m;
 3676         struct iwn_node *wn;
 3677         struct ieee80211_node *ni;
 3678         struct ieee80211_tx_ampdu *tap;
 3679         uint64_t bitmap;
 3680         uint32_t *status = stat;
 3681         uint16_t *aggstatus = stat;
 3682         uint16_t ssn;
 3683         uint8_t tid;
 3684         int bit, i, lastidx, *res, seqno, shift, start;
 3685 
 3686         /* XXX TODO: status is le16 field! Grr */
 3687 
 3688         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 3689         DPRINTF(sc, IWN_DEBUG_XMIT, "%s: nframes=%d, status=0x%08x\n",
 3690             __func__,
 3691             nframes,
 3692             *status);
 3693 
 3694         tap = sc->qid2tap[qid];
 3695         tid = tap->txa_tid;
 3696         wn = (void *)tap->txa_ni;
 3697         ni = tap->txa_ni;
 3698 
 3699         /*
 3700          * XXX TODO: ACK and RTS failures would be nice here!
 3701          */
 3702 
 3703         /*
 3704          * A-MPDU single frame status - if we failed to transmit it
 3705          * in A-MPDU, then it may be a permanent failure.
 3706          *
 3707          * XXX TODO: check what the Linux iwlwifi driver does here;
 3708          * there's some permanent and temporary failures that may be
 3709          * handled differently.
 3710          */
 3711         if (nframes == 1) {
 3712                 txs->flags = IEEE80211_RATECTL_STATUS_SHORT_RETRY |
 3713                              IEEE80211_RATECTL_STATUS_LONG_RETRY;
 3714                 txs->short_retries = rtsfailcnt;
 3715                 txs->long_retries = ackfailcnt;
 3716                 if ((*status & 0xff) != 1 && (*status & 0xff) != 2) {
 3717 #ifdef  NOT_YET
 3718                         printf("ieee80211_send_bar()\n");
 3719 #endif
 3720                         /*
 3721                          * If we completely fail a transmit, make sure a
 3722                          * notification is pushed up to the rate control
 3723                          * layer.
 3724                          */
 3725                         /* XXX */
 3726                         txs->status = IEEE80211_RATECTL_TX_FAIL_UNSPECIFIED;
 3727                 } else {
 3728                         /*
 3729                          * If nframes=1, then we won't be getting a BA for
 3730                          * this frame.  Ensure that we correctly update the
 3731                          * rate control code with how many retries were
 3732                          * needed to send it.
 3733                          */
 3734                         txs->status = IEEE80211_RATECTL_TX_SUCCESS;
 3735                 }
 3736                 ieee80211_ratectl_tx_complete(ni, txs);
 3737         }
 3738 
 3739         bitmap = 0;
 3740         start = idx;
 3741         for (i = 0; i < nframes; i++) {
 3742                 if (le16toh(aggstatus[i * 2]) & 0xc)
 3743                         continue;
 3744 
 3745                 idx = le16toh(aggstatus[2*i + 1]) & 0xff;
 3746                 bit = idx - start;
 3747                 shift = 0;
 3748                 if (bit >= 64) {
 3749                         shift = 0x100 - idx + start;
 3750                         bit = 0;
 3751                         start = idx;
 3752                 } else if (bit <= -64)
 3753                         bit = 0x100 - start + idx;
 3754                 else if (bit < 0) {
 3755                         shift = start - idx;
 3756                         start = idx;
 3757                         bit = 0;
 3758                 }
 3759                 bitmap = bitmap << shift;
 3760                 bitmap |= 1ULL << bit;
 3761         }
 3762         tap = sc->qid2tap[qid];
 3763         tid = tap->txa_tid;
 3764         wn = (void *)tap->txa_ni;
 3765         wn->agg[tid].bitmap = bitmap;
 3766         wn->agg[tid].startidx = start;
 3767         wn->agg[tid].nframes = nframes;
 3768 
 3769         res = NULL;
 3770         ssn = 0;
 3771         if (!IEEE80211_AMPDU_RUNNING(tap)) {
 3772                 res = tap->txa_private;
 3773                 ssn = tap->txa_start & 0xfff;
 3774         }
 3775 
 3776         /* This is going nframes DWORDS into the descriptor? */
 3777         seqno = le32toh(*(status + nframes)) & 0xfff;
 3778         for (lastidx = (seqno & 0xff); ring->read != lastidx;) {
 3779                 data = &ring->data[ring->read];
 3780 
 3781                 /* Unmap and free mbuf. */
 3782                 bus_dmamap_sync(ring->data_dmat, data->map,
 3783                     BUS_DMASYNC_POSTWRITE);
 3784                 bus_dmamap_unload(ring->data_dmat, data->map);
 3785                 m = data->m, data->m = NULL;
 3786                 ni = data->ni, data->ni = NULL;
 3787 
 3788                 KASSERT(ni != NULL, ("no node"));
 3789                 KASSERT(m != NULL, ("no mbuf"));
 3790                 DPRINTF(sc, IWN_DEBUG_XMIT, "%s: freeing m=%p\n", __func__, m);
 3791                 ieee80211_tx_complete(ni, m, 1);
 3792 
 3793                 ring->queued--;
 3794                 ring->read = (ring->read + 1) % IWN_TX_RING_COUNT;
 3795         }
 3796 
 3797         if (ring->queued == 0 && res != NULL) {
 3798                 iwn_nic_lock(sc);
 3799                 ops->ampdu_tx_stop(sc, qid, tid, ssn);
 3800                 iwn_nic_unlock(sc);
 3801                 sc->qid2tap[qid] = NULL;
 3802                 free(res, M_DEVBUF);
 3803                 return;
 3804         }
 3805 
 3806         sc->sc_tx_timer = 0;
 3807         if (ring->queued < IWN_TX_RING_LOMARK)
 3808                 sc->qfullmsk &= ~(1 << ring->qid);
 3809 
 3810         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 3811 }
 3812 
 3813 /*
 3814  * Process an INT_FH_RX or INT_SW_RX interrupt.
 3815  */
 3816 static void
 3817 iwn_notif_intr(struct iwn_softc *sc)
 3818 {
 3819         struct iwn_ops *ops = &sc->ops;
 3820         struct ieee80211com *ic = &sc->sc_ic;
 3821         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
 3822         uint16_t hw;
 3823 
 3824         bus_dmamap_sync(sc->rxq.stat_dma.tag, sc->rxq.stat_dma.map,
 3825             BUS_DMASYNC_POSTREAD);
 3826 
 3827         hw = le16toh(sc->rxq.stat->closed_count) & 0xfff;
 3828         while (sc->rxq.cur != hw) {
 3829                 struct iwn_rx_data *data = &sc->rxq.data[sc->rxq.cur];
 3830                 struct iwn_rx_desc *desc;
 3831 
 3832                 bus_dmamap_sync(sc->rxq.data_dmat, data->map,
 3833                     BUS_DMASYNC_POSTREAD);
 3834                 desc = mtod(data->m, struct iwn_rx_desc *);
 3835 
 3836                 DPRINTF(sc, IWN_DEBUG_RECV,
 3837                     "%s: cur=%d; qid %x idx %d flags %x type %d(%s) len %d\n",
 3838                     __func__, sc->rxq.cur, desc->qid & IWN_RX_DESC_QID_MSK,
 3839                     desc->idx, desc->flags, desc->type,
 3840                     iwn_intr_str(desc->type), le16toh(desc->len));
 3841 
 3842                 if (!(desc->qid & IWN_UNSOLICITED_RX_NOTIF))    /* Reply to a command. */
 3843                         iwn_cmd_done(sc, desc);
 3844 
 3845                 switch (desc->type) {
 3846                 case IWN_RX_PHY:
 3847                         iwn_rx_phy(sc, desc);
 3848                         break;
 3849 
 3850                 case IWN_RX_DONE:               /* 4965AGN only. */
 3851                 case IWN_MPDU_RX_DONE:
 3852                         /* An 802.11 frame has been received. */
 3853                         iwn_rx_done(sc, desc, data);
 3854                         break;
 3855 
 3856                 case IWN_RX_COMPRESSED_BA:
 3857                         /* A Compressed BlockAck has been received. */
 3858                         iwn_rx_compressed_ba(sc, desc);
 3859                         break;
 3860 
 3861                 case IWN_TX_DONE:
 3862                         /* An 802.11 frame has been transmitted. */
 3863                         ops->tx_done(sc, desc, data);
 3864                         break;
 3865 
 3866                 case IWN_RX_STATISTICS:
 3867                 case IWN_BEACON_STATISTICS:
 3868                         iwn_rx_statistics(sc, desc);
 3869                         break;
 3870 
 3871                 case IWN_BEACON_MISSED:
 3872                 {
 3873                         struct iwn_beacon_missed *miss =
 3874                             (struct iwn_beacon_missed *)(desc + 1);
 3875                         int misses;
 3876 
 3877                         misses = le32toh(miss->consecutive);
 3878 
 3879                         DPRINTF(sc, IWN_DEBUG_STATE,
 3880                             "%s: beacons missed %d/%d\n", __func__,
 3881                             misses, le32toh(miss->total));
 3882                         /*
 3883                          * If more than 5 consecutive beacons are missed,
 3884                          * reinitialize the sensitivity state machine.
 3885                          */
 3886                         if (vap->iv_state == IEEE80211_S_RUN &&
 3887                             (ic->ic_flags & IEEE80211_F_SCAN) == 0) {
 3888                                 if (misses > 5)
 3889                                         (void)iwn_init_sensitivity(sc);
 3890                                 if (misses >= vap->iv_bmissthreshold) {
 3891                                         IWN_UNLOCK(sc);
 3892                                         ieee80211_beacon_miss(ic);
 3893                                         IWN_LOCK(sc);
 3894                                 }
 3895                         }
 3896                         break;
 3897                 }
 3898                 case IWN_UC_READY:
 3899                 {
 3900                         struct iwn_ucode_info *uc =
 3901                             (struct iwn_ucode_info *)(desc + 1);
 3902 
 3903                         /* The microcontroller is ready. */
 3904                         DPRINTF(sc, IWN_DEBUG_RESET,
 3905                             "microcode alive notification version=%d.%d "
 3906                             "subtype=%x alive=%x\n", uc->major, uc->minor,
 3907                             uc->subtype, le32toh(uc->valid));
 3908 
 3909                         if (le32toh(uc->valid) != 1) {
 3910                                 device_printf(sc->sc_dev,
 3911                                     "microcontroller initialization failed");
 3912                                 break;
 3913                         }
 3914                         if (uc->subtype == IWN_UCODE_INIT) {
 3915                                 /* Save microcontroller report. */
 3916                                 memcpy(&sc->ucode_info, uc, sizeof (*uc));
 3917                         }
 3918                         /* Save the address of the error log in SRAM. */
 3919                         sc->errptr = le32toh(uc->errptr);
 3920                         break;
 3921                 }
 3922 #ifdef IWN_DEBUG
 3923                 case IWN_STATE_CHANGED:
 3924                 {
 3925                         /*
 3926                          * State change allows hardware switch change to be
 3927                          * noted. However, we handle this in iwn_intr as we
 3928                          * get both the enable/disble intr.
 3929                          */
 3930                         uint32_t *status = (uint32_t *)(desc + 1);
 3931                         DPRINTF(sc, IWN_DEBUG_INTR | IWN_DEBUG_STATE,
 3932                             "state changed to %x\n",
 3933                             le32toh(*status));
 3934                         break;
 3935                 }
 3936                 case IWN_START_SCAN:
 3937                 {
 3938                         struct iwn_start_scan *scan =
 3939                             (struct iwn_start_scan *)(desc + 1);
 3940                         DPRINTF(sc, IWN_DEBUG_ANY,
 3941                             "%s: scanning channel %d status %x\n",
 3942                             __func__, scan->chan, le32toh(scan->status));
 3943                         break;
 3944                 }
 3945 #endif
 3946                 case IWN_STOP_SCAN:
 3947                 {
 3948 #ifdef  IWN_DEBUG
 3949                         struct iwn_stop_scan *scan =
 3950                             (struct iwn_stop_scan *)(desc + 1);
 3951                         DPRINTF(sc, IWN_DEBUG_STATE | IWN_DEBUG_SCAN,
 3952                             "scan finished nchan=%d status=%d chan=%d\n",
 3953                             scan->nchan, scan->status, scan->chan);
 3954 #endif
 3955                         sc->sc_is_scanning = 0;
 3956                         callout_stop(&sc->scan_timeout);
 3957                         IWN_UNLOCK(sc);
 3958                         ieee80211_scan_next(vap);
 3959                         IWN_LOCK(sc);
 3960                         break;
 3961                 }
 3962                 case IWN5000_CALIBRATION_RESULT:
 3963                         iwn5000_rx_calib_results(sc, desc);
 3964                         break;
 3965 
 3966                 case IWN5000_CALIBRATION_DONE:
 3967                         sc->sc_flags |= IWN_FLAG_CALIB_DONE;
 3968                         wakeup(sc);
 3969                         break;
 3970                 }
 3971 
 3972                 sc->rxq.cur = (sc->rxq.cur + 1) % IWN_RX_RING_COUNT;
 3973         }
 3974 
 3975         /* Tell the firmware what we have processed. */
 3976         hw = (hw == 0) ? IWN_RX_RING_COUNT - 1 : hw - 1;
 3977         IWN_WRITE(sc, IWN_FH_RX_WPTR, hw & ~7);
 3978 }
 3979 
 3980 /*
 3981  * Process an INT_WAKEUP interrupt raised when the microcontroller wakes up
 3982  * from power-down sleep mode.
 3983  */
 3984 static void
 3985 iwn_wakeup_intr(struct iwn_softc *sc)
 3986 {
 3987         int qid;
 3988 
 3989         DPRINTF(sc, IWN_DEBUG_RESET, "%s: ucode wakeup from power-down sleep\n",
 3990             __func__);
 3991 
 3992         /* Wakeup RX and TX rings. */
 3993         IWN_WRITE(sc, IWN_FH_RX_WPTR, sc->rxq.cur & ~7);
 3994         for (qid = 0; qid < sc->ntxqs; qid++) {
 3995                 struct iwn_tx_ring *ring = &sc->txq[qid];
 3996                 IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | ring->cur);
 3997         }
 3998 }
 3999 
 4000 static void
 4001 iwn_rftoggle_task(void *arg, int npending)
 4002 {
 4003         struct iwn_softc *sc = arg;
 4004         struct ieee80211com *ic = &sc->sc_ic;
 4005         uint32_t tmp;
 4006 
 4007         IWN_LOCK(sc);
 4008         tmp = IWN_READ(sc, IWN_GP_CNTRL);
 4009         IWN_UNLOCK(sc);
 4010 
 4011         device_printf(sc->sc_dev, "RF switch: radio %s\n",
 4012             (tmp & IWN_GP_CNTRL_RFKILL) ? "enabled" : "disabled");
 4013         if (!(tmp & IWN_GP_CNTRL_RFKILL)) {
 4014                 ieee80211_suspend_all(ic);
 4015 
 4016                 /* Enable interrupts to get RF toggle notification. */
 4017                 IWN_LOCK(sc);
 4018                 IWN_WRITE(sc, IWN_INT, 0xffffffff);
 4019                 IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
 4020                 IWN_UNLOCK(sc);
 4021         } else
 4022                 ieee80211_resume_all(ic);
 4023 }
 4024 
 4025 /*
 4026  * Dump the error log of the firmware when a firmware panic occurs.  Although
 4027  * we can't debug the firmware because it is neither open source nor free, it
 4028  * can help us to identify certain classes of problems.
 4029  */
 4030 static void
 4031 iwn_fatal_intr(struct iwn_softc *sc)
 4032 {
 4033         struct iwn_fw_dump dump;
 4034         int i;
 4035 
 4036         IWN_LOCK_ASSERT(sc);
 4037 
 4038         /* Force a complete recalibration on next init. */
 4039         sc->sc_flags &= ~IWN_FLAG_CALIB_DONE;
 4040 
 4041         /* Check that the error log address is valid. */
 4042         if (sc->errptr < IWN_FW_DATA_BASE ||
 4043             sc->errptr + sizeof (dump) >
 4044             IWN_FW_DATA_BASE + sc->fw_data_maxsz) {
 4045                 printf("%s: bad firmware error log address 0x%08x\n", __func__,
 4046                     sc->errptr);
 4047                 return;
 4048         }
 4049         if (iwn_nic_lock(sc) != 0) {
 4050                 printf("%s: could not read firmware error log\n", __func__);
 4051                 return;
 4052         }
 4053         /* Read firmware error log from SRAM. */
 4054         iwn_mem_read_region_4(sc, sc->errptr, (uint32_t *)&dump,
 4055             sizeof (dump) / sizeof (uint32_t));
 4056         iwn_nic_unlock(sc);
 4057 
 4058         if (dump.valid == 0) {
 4059                 printf("%s: firmware error log is empty\n", __func__);
 4060                 return;
 4061         }
 4062         printf("firmware error log:\n");
 4063         printf("  error type      = \"%s\" (0x%08X)\n",
 4064             (dump.id < nitems(iwn_fw_errmsg)) ?
 4065                 iwn_fw_errmsg[dump.id] : "UNKNOWN",
 4066             dump.id);
 4067         printf("  program counter = 0x%08X\n", dump.pc);
 4068         printf("  source line     = 0x%08X\n", dump.src_line);
 4069         printf("  error data      = 0x%08X%08X\n",
 4070             dump.error_data[0], dump.error_data[1]);
 4071         printf("  branch link     = 0x%08X%08X\n",
 4072             dump.branch_link[0], dump.branch_link[1]);
 4073         printf("  interrupt link  = 0x%08X%08X\n",
 4074             dump.interrupt_link[0], dump.interrupt_link[1]);
 4075         printf("  time            = %u\n", dump.time[0]);
 4076 
 4077         /* Dump driver status (TX and RX rings) while we're here. */
 4078         printf("driver status:\n");
 4079         for (i = 0; i < sc->ntxqs; i++) {
 4080                 struct iwn_tx_ring *ring = &sc->txq[i];
 4081                 printf("  tx ring %2d: qid=%-2d cur=%-3d queued=%-3d\n",
 4082                     i, ring->qid, ring->cur, ring->queued);
 4083         }
 4084         printf("  rx ring: cur=%d\n", sc->rxq.cur);
 4085 }
 4086 
 4087 static void
 4088 iwn_intr(void *arg)
 4089 {
 4090         struct iwn_softc *sc = arg;
 4091         uint32_t r1, r2, tmp;
 4092 
 4093         IWN_LOCK(sc);
 4094 
 4095         /* Disable interrupts. */
 4096         IWN_WRITE(sc, IWN_INT_MASK, 0);
 4097 
 4098         /* Read interrupts from ICT (fast) or from registers (slow). */
 4099         if (sc->sc_flags & IWN_FLAG_USE_ICT) {
 4100                 bus_dmamap_sync(sc->ict_dma.tag, sc->ict_dma.map,
 4101                     BUS_DMASYNC_POSTREAD);
 4102                 tmp = 0;
 4103                 while (sc->ict[sc->ict_cur] != 0) {
 4104                         tmp |= sc->ict[sc->ict_cur];
 4105                         sc->ict[sc->ict_cur] = 0;       /* Acknowledge. */
 4106                         sc->ict_cur = (sc->ict_cur + 1) % IWN_ICT_COUNT;
 4107                 }
 4108                 tmp = le32toh(tmp);
 4109                 if (tmp == 0xffffffff)  /* Shouldn't happen. */
 4110                         tmp = 0;
 4111                 else if (tmp & 0xc0000) /* Workaround a HW bug. */
 4112                         tmp |= 0x8000;
 4113                 r1 = (tmp & 0xff00) << 16 | (tmp & 0xff);
 4114                 r2 = 0; /* Unused. */
 4115         } else {
 4116                 r1 = IWN_READ(sc, IWN_INT);
 4117                 if (r1 == 0xffffffff || (r1 & 0xfffffff0) == 0xa5a5a5a0) {
 4118                         IWN_UNLOCK(sc);
 4119                         return; /* Hardware gone! */
 4120                 }
 4121                 r2 = IWN_READ(sc, IWN_FH_INT);
 4122         }
 4123 
 4124         DPRINTF(sc, IWN_DEBUG_INTR, "interrupt reg1=0x%08x reg2=0x%08x\n"
 4125     , r1, r2);
 4126 
 4127         if (r1 == 0 && r2 == 0)
 4128                 goto done;      /* Interrupt not for us. */
 4129 
 4130         /* Acknowledge interrupts. */
 4131         IWN_WRITE(sc, IWN_INT, r1);
 4132         if (!(sc->sc_flags & IWN_FLAG_USE_ICT))
 4133                 IWN_WRITE(sc, IWN_FH_INT, r2);
 4134 
 4135         if (r1 & IWN_INT_RF_TOGGLED) {
 4136                 taskqueue_enqueue(sc->sc_tq, &sc->sc_rftoggle_task);
 4137                 goto done;
 4138         }
 4139         if (r1 & IWN_INT_CT_REACHED) {
 4140                 device_printf(sc->sc_dev, "%s: critical temperature reached!\n",
 4141                     __func__);
 4142         }
 4143         if (r1 & (IWN_INT_SW_ERR | IWN_INT_HW_ERR)) {
 4144                 device_printf(sc->sc_dev, "%s: fatal firmware error\n",
 4145                     __func__);
 4146 #ifdef  IWN_DEBUG
 4147                 iwn_debug_register(sc);
 4148 #endif
 4149                 /* Dump firmware error log and stop. */
 4150                 iwn_fatal_intr(sc);
 4151 
 4152                 taskqueue_enqueue(sc->sc_tq, &sc->sc_panic_task);
 4153                 goto done;
 4154         }
 4155         if ((r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX | IWN_INT_RX_PERIODIC)) ||
 4156             (r2 & IWN_FH_INT_RX)) {
 4157                 if (sc->sc_flags & IWN_FLAG_USE_ICT) {
 4158                         if (r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX))
 4159                                 IWN_WRITE(sc, IWN_FH_INT, IWN_FH_INT_RX);
 4160                         IWN_WRITE_1(sc, IWN_INT_PERIODIC,
 4161                             IWN_INT_PERIODIC_DIS);
 4162                         iwn_notif_intr(sc);
 4163                         if (r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX)) {
 4164                                 IWN_WRITE_1(sc, IWN_INT_PERIODIC,
 4165                                     IWN_INT_PERIODIC_ENA);
 4166                         }
 4167                 } else
 4168                         iwn_notif_intr(sc);
 4169         }
 4170 
 4171         if ((r1 & IWN_INT_FH_TX) || (r2 & IWN_FH_INT_TX)) {
 4172                 if (sc->sc_flags & IWN_FLAG_USE_ICT)
 4173                         IWN_WRITE(sc, IWN_FH_INT, IWN_FH_INT_TX);
 4174                 wakeup(sc);     /* FH DMA transfer completed. */
 4175         }
 4176 
 4177         if (r1 & IWN_INT_ALIVE)
 4178                 wakeup(sc);     /* Firmware is alive. */
 4179 
 4180         if (r1 & IWN_INT_WAKEUP)
 4181                 iwn_wakeup_intr(sc);
 4182 
 4183 done:
 4184         /* Re-enable interrupts. */
 4185         if (sc->sc_flags & IWN_FLAG_RUNNING)
 4186                 IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
 4187 
 4188         IWN_UNLOCK(sc);
 4189 }
 4190 
 4191 /*
 4192  * Update TX scheduler ring when transmitting an 802.11 frame (4965AGN and
 4193  * 5000 adapters use a slightly different format).
 4194  */
 4195 static void
 4196 iwn4965_update_sched(struct iwn_softc *sc, int qid, int idx, uint8_t id,
 4197     uint16_t len)
 4198 {
 4199         uint16_t *w = &sc->sched[qid * IWN4965_SCHED_COUNT + idx];
 4200 
 4201         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 4202 
 4203         *w = htole16(len + 8);
 4204         bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
 4205             BUS_DMASYNC_PREWRITE);
 4206         if (idx < IWN_SCHED_WINSZ) {
 4207                 *(w + IWN_TX_RING_COUNT) = *w;
 4208                 bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
 4209                     BUS_DMASYNC_PREWRITE);
 4210         }
 4211 }
 4212 
 4213 static void
 4214 iwn5000_update_sched(struct iwn_softc *sc, int qid, int idx, uint8_t id,
 4215     uint16_t len)
 4216 {
 4217         uint16_t *w = &sc->sched[qid * IWN5000_SCHED_COUNT + idx];
 4218 
 4219         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 4220 
 4221         *w = htole16(id << 12 | (len + 8));
 4222         bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
 4223             BUS_DMASYNC_PREWRITE);
 4224         if (idx < IWN_SCHED_WINSZ) {
 4225                 *(w + IWN_TX_RING_COUNT) = *w;
 4226                 bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
 4227                     BUS_DMASYNC_PREWRITE);
 4228         }
 4229 }
 4230 
 4231 #ifdef notyet
 4232 static void
 4233 iwn5000_reset_sched(struct iwn_softc *sc, int qid, int idx)
 4234 {
 4235         uint16_t *w = &sc->sched[qid * IWN5000_SCHED_COUNT + idx];
 4236 
 4237         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 4238 
 4239         *w = (*w & htole16(0xf000)) | htole16(1);
 4240         bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
 4241             BUS_DMASYNC_PREWRITE);
 4242         if (idx < IWN_SCHED_WINSZ) {
 4243                 *(w + IWN_TX_RING_COUNT) = *w;
 4244                 bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
 4245                     BUS_DMASYNC_PREWRITE);
 4246         }
 4247 }
 4248 #endif
 4249 
 4250 /*
 4251  * Check whether OFDM 11g protection will be enabled for the given rate.
 4252  *
 4253  * The original driver code only enabled protection for OFDM rates.
 4254  * It didn't check to see whether it was operating in 11a or 11bg mode.
 4255  */
 4256 static int
 4257 iwn_check_rate_needs_protection(struct iwn_softc *sc,
 4258     struct ieee80211vap *vap, uint8_t rate)
 4259 {
 4260         struct ieee80211com *ic = vap->iv_ic;
 4261 
 4262         /*
 4263          * Not in 2GHz mode? Then there's no need to enable OFDM
 4264          * 11bg protection.
 4265          */
 4266         if (! IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan)) {
 4267                 return (0);
 4268         }
 4269 
 4270         /*
 4271          * 11bg protection not enabled? Then don't use it.
 4272          */
 4273         if ((ic->ic_flags & IEEE80211_F_USEPROT) == 0)
 4274                 return (0);
 4275 
 4276         /*
 4277          * If it's an 11n rate - no protection.
 4278          * We'll do it via a specific 11n check.
 4279          */
 4280         if (rate & IEEE80211_RATE_MCS) {
 4281                 return (0);
 4282         }
 4283 
 4284         /*
 4285          * Do a rate table lookup.  If the PHY is CCK,
 4286          * don't do protection.
 4287          */
 4288         if (ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_CCK)
 4289                 return (0);
 4290 
 4291         /*
 4292          * Yup, enable protection.
 4293          */
 4294         return (1);
 4295 }
 4296 
 4297 /*
 4298  * return a value between 0 and IWN_MAX_TX_RETRIES-1 as an index into
 4299  * the link quality table that reflects this particular entry.
 4300  */
 4301 static int
 4302 iwn_tx_rate_to_linkq_offset(struct iwn_softc *sc, struct ieee80211_node *ni,
 4303     uint8_t rate)
 4304 {
 4305         struct ieee80211_rateset *rs;
 4306         int is_11n;
 4307         int nr;
 4308         int i;
 4309         uint8_t cmp_rate;
 4310 
 4311         /*
 4312          * Figure out if we're using 11n or not here.
 4313          */
 4314         if (IEEE80211_IS_CHAN_HT(ni->ni_chan) && ni->ni_htrates.rs_nrates > 0)
 4315                 is_11n = 1;
 4316         else
 4317                 is_11n = 0;
 4318 
 4319         /*
 4320          * Use the correct rate table.
 4321          */
 4322         if (is_11n) {
 4323                 rs = (struct ieee80211_rateset *) &ni->ni_htrates;
 4324                 nr = ni->ni_htrates.rs_nrates;
 4325         } else {
 4326                 rs = &ni->ni_rates;
 4327                 nr = rs->rs_nrates;
 4328         }
 4329 
 4330         /*
 4331          * Find the relevant link quality entry in the table.
 4332          */
 4333         for (i = 0; i < nr && i < IWN_MAX_TX_RETRIES - 1 ; i++) {
 4334                 /*
 4335                  * The link quality table index starts at 0 == highest
 4336                  * rate, so we walk the rate table backwards.
 4337                  */
 4338                 cmp_rate = rs->rs_rates[(nr - 1) - i];
 4339                 if (rate & IEEE80211_RATE_MCS)
 4340                         cmp_rate |= IEEE80211_RATE_MCS;
 4341 
 4342 #if 0
 4343                 DPRINTF(sc, IWN_DEBUG_XMIT, "%s: idx %d: nr=%d, rate=0x%02x, rateentry=0x%02x\n",
 4344                     __func__,
 4345                     i,
 4346                     nr,
 4347                     rate,
 4348                     cmp_rate);
 4349 #endif
 4350 
 4351                 if (cmp_rate == rate)
 4352                         return (i);
 4353         }
 4354 
 4355         /* Failed? Start at the end */
 4356         return (IWN_MAX_TX_RETRIES - 1);
 4357 }
 4358 
 4359 static int
 4360 iwn_tx_data(struct iwn_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
 4361 {
 4362         const struct ieee80211_txparam *tp = ni->ni_txparms;
 4363         struct ieee80211vap *vap = ni->ni_vap;
 4364         struct ieee80211com *ic = ni->ni_ic;
 4365         struct iwn_node *wn = (void *)ni;
 4366         struct iwn_tx_ring *ring;
 4367         struct iwn_tx_cmd *cmd;
 4368         struct iwn_cmd_data *tx;
 4369         struct ieee80211_frame *wh;
 4370         struct ieee80211_key *k = NULL;
 4371         uint32_t flags;
 4372         uint16_t seqno, qos;
 4373         uint8_t tid, type;
 4374         int ac, totlen, rate;
 4375 
 4376         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 4377 
 4378         IWN_LOCK_ASSERT(sc);
 4379 
 4380         wh = mtod(m, struct ieee80211_frame *);
 4381         type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
 4382 
 4383         /* Select EDCA Access Category and TX ring for this frame. */
 4384         if (IEEE80211_QOS_HAS_SEQ(wh)) {
 4385                 qos = ((const struct ieee80211_qosframe *)wh)->i_qos[0];
 4386                 tid = qos & IEEE80211_QOS_TID;
 4387         } else {
 4388                 qos = 0;
 4389                 tid = 0;
 4390         }
 4391 
 4392         /* Choose a TX rate index. */
 4393         if (type == IEEE80211_FC0_TYPE_MGT ||
 4394             type == IEEE80211_FC0_TYPE_CTL ||
 4395             (m->m_flags & M_EAPOL) != 0)
 4396                 rate = tp->mgmtrate;
 4397         else if (IEEE80211_IS_MULTICAST(wh->i_addr1))
 4398                 rate = tp->mcastrate;
 4399         else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
 4400                 rate = tp->ucastrate;
 4401         else {
 4402                 /* XXX pass pktlen */
 4403                 (void) ieee80211_ratectl_rate(ni, NULL, 0);
 4404                 rate = ni->ni_txrate;
 4405         }
 4406 
 4407         /*
 4408          * XXX TODO: Group addressed frames aren't aggregated and must
 4409          * go to the normal non-aggregation queue, and have a NONQOS TID
 4410          * assigned from net80211.
 4411          */
 4412 
 4413         ac = M_WME_GETAC(m);
 4414         seqno = ni->ni_txseqs[tid];
 4415         if (m->m_flags & M_AMPDU_MPDU) {
 4416                 struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[ac];
 4417 
 4418                 if (!IEEE80211_AMPDU_RUNNING(tap)) {
 4419                         return (EINVAL);
 4420                 }
 4421 
 4422                 /*
 4423                  * Queue this frame to the hardware ring that we've
 4424                  * negotiated AMPDU TX on.
 4425                  *
 4426                  * Note that the sequence number must match the TX slot
 4427                  * being used!
 4428                  */
 4429                 ac = *(int *)tap->txa_private;
 4430                 *(uint16_t *)wh->i_seq =
 4431                     htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT);
 4432                 ni->ni_txseqs[tid]++;
 4433         }
 4434 
 4435         /* Encrypt the frame if need be. */
 4436         if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
 4437                 /* Retrieve key for TX. */
 4438                 k = ieee80211_crypto_encap(ni, m);
 4439                 if (k == NULL) {
 4440                         return ENOBUFS;
 4441                 }
 4442                 /* 802.11 header may have moved. */
 4443                 wh = mtod(m, struct ieee80211_frame *);
 4444         }
 4445         totlen = m->m_pkthdr.len;
 4446 
 4447         if (ieee80211_radiotap_active_vap(vap)) {
 4448                 struct iwn_tx_radiotap_header *tap = &sc->sc_txtap;
 4449 
 4450                 tap->wt_flags = 0;
 4451                 tap->wt_rate = rate;
 4452                 if (k != NULL)
 4453                         tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
 4454 
 4455                 ieee80211_radiotap_tx(vap, m);
 4456         }
 4457 
 4458         flags = 0;
 4459         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
 4460                 /* Unicast frame, check if an ACK is expected. */
 4461                 if (!qos || (qos & IEEE80211_QOS_ACKPOLICY) !=
 4462                     IEEE80211_QOS_ACKPOLICY_NOACK)
 4463                         flags |= IWN_TX_NEED_ACK;
 4464         }
 4465         if ((wh->i_fc[0] &
 4466             (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
 4467             (IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_BAR))
 4468                 flags |= IWN_TX_IMM_BA;         /* Cannot happen yet. */
 4469 
 4470         if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG)
 4471                 flags |= IWN_TX_MORE_FRAG;      /* Cannot happen yet. */
 4472 
 4473         /* Check if frame must be protected using RTS/CTS or CTS-to-self. */
 4474         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
 4475                 /* NB: Group frames are sent using CCK in 802.11b/g. */
 4476                 if (totlen + IEEE80211_CRC_LEN > vap->iv_rtsthreshold) {
 4477                         flags |= IWN_TX_NEED_RTS;
 4478                 } else if (iwn_check_rate_needs_protection(sc, vap, rate)) {
 4479                         if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
 4480                                 flags |= IWN_TX_NEED_CTS;
 4481                         else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
 4482                                 flags |= IWN_TX_NEED_RTS;
 4483                 } else if ((rate & IEEE80211_RATE_MCS) &&
 4484                         (ic->ic_htprotmode == IEEE80211_PROT_RTSCTS)) {
 4485                         flags |= IWN_TX_NEED_RTS;
 4486                 }
 4487 
 4488                 /* XXX HT protection? */
 4489 
 4490                 if (flags & (IWN_TX_NEED_RTS | IWN_TX_NEED_CTS)) {
 4491                         if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
 4492                                 /* 5000 autoselects RTS/CTS or CTS-to-self. */
 4493                                 flags &= ~(IWN_TX_NEED_RTS | IWN_TX_NEED_CTS);
 4494                                 flags |= IWN_TX_NEED_PROTECTION;
 4495                         } else
 4496                                 flags |= IWN_TX_FULL_TXOP;
 4497                 }
 4498         }
 4499 
 4500         ring = &sc->txq[ac];
 4501         if ((m->m_flags & M_AMPDU_MPDU) != 0 &&
 4502             (seqno % 256) != ring->cur) {
 4503                 device_printf(sc->sc_dev,
 4504                     "%s: m=%p: seqno (%d) (%d) != ring index (%d) !\n",
 4505                     __func__,
 4506                     m,
 4507                     seqno,
 4508                     seqno % 256,
 4509                     ring->cur);
 4510         }
 4511 
 4512         /* Prepare TX firmware command. */
 4513         cmd = &ring->cmd[ring->cur];
 4514         tx = (struct iwn_cmd_data *)cmd->data;
 4515 
 4516         /* NB: No need to clear tx, all fields are reinitialized here. */
 4517         tx->scratch = 0;        /* clear "scratch" area */
 4518 
 4519         if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
 4520             type != IEEE80211_FC0_TYPE_DATA)
 4521                 tx->id = sc->broadcast_id;
 4522         else
 4523                 tx->id = wn->id;
 4524 
 4525         if (type == IEEE80211_FC0_TYPE_MGT) {
 4526                 uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
 4527 
 4528                 /* Tell HW to set timestamp in probe responses. */
 4529                 if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
 4530                         flags |= IWN_TX_INSERT_TSTAMP;
 4531                 if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
 4532                     subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
 4533                         tx->timeout = htole16(3);
 4534                 else
 4535                         tx->timeout = htole16(2);
 4536         } else
 4537                 tx->timeout = htole16(0);
 4538 
 4539         if (tx->id == sc->broadcast_id) {
 4540                 /* Group or management frame. */
 4541                 tx->linkq = 0;
 4542         } else {
 4543                 tx->linkq = iwn_tx_rate_to_linkq_offset(sc, ni, rate);
 4544                 flags |= IWN_TX_LINKQ;  /* enable MRR */
 4545         }
 4546 
 4547         tx->tid = tid;
 4548         tx->rts_ntries = 60;
 4549         tx->data_ntries = 15;
 4550         tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
 4551         tx->rate = iwn_rate_to_plcp(sc, ni, rate);
 4552         tx->security = 0;
 4553         tx->flags = htole32(flags);
 4554 
 4555         return (iwn_tx_cmd(sc, m, ni, ring));
 4556 }
 4557 
 4558 static int
 4559 iwn_tx_data_raw(struct iwn_softc *sc, struct mbuf *m,
 4560     struct ieee80211_node *ni, const struct ieee80211_bpf_params *params)
 4561 {
 4562         struct ieee80211vap *vap = ni->ni_vap;
 4563         struct iwn_tx_cmd *cmd;
 4564         struct iwn_cmd_data *tx;
 4565         struct ieee80211_frame *wh;
 4566         struct iwn_tx_ring *ring;
 4567         uint32_t flags;
 4568         int ac, rate;
 4569         uint8_t type;
 4570 
 4571         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 4572 
 4573         IWN_LOCK_ASSERT(sc);
 4574 
 4575         wh = mtod(m, struct ieee80211_frame *);
 4576         type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
 4577 
 4578         ac = params->ibp_pri & 3;
 4579 
 4580         /* Choose a TX rate. */
 4581         rate = params->ibp_rate0;
 4582 
 4583         flags = 0;
 4584         if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0)
 4585                 flags |= IWN_TX_NEED_ACK;
 4586         if (params->ibp_flags & IEEE80211_BPF_RTS) {
 4587                 if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
 4588                         /* 5000 autoselects RTS/CTS or CTS-to-self. */
 4589                         flags &= ~IWN_TX_NEED_RTS;
 4590                         flags |= IWN_TX_NEED_PROTECTION;
 4591                 } else
 4592                         flags |= IWN_TX_NEED_RTS | IWN_TX_FULL_TXOP;
 4593         }
 4594         if (params->ibp_flags & IEEE80211_BPF_CTS) {
 4595                 if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
 4596                         /* 5000 autoselects RTS/CTS or CTS-to-self. */
 4597                         flags &= ~IWN_TX_NEED_CTS;
 4598                         flags |= IWN_TX_NEED_PROTECTION;
 4599                 } else
 4600                         flags |= IWN_TX_NEED_CTS | IWN_TX_FULL_TXOP;
 4601         }
 4602 
 4603         if (ieee80211_radiotap_active_vap(vap)) {
 4604                 struct iwn_tx_radiotap_header *tap = &sc->sc_txtap;
 4605 
 4606                 tap->wt_flags = 0;
 4607                 tap->wt_rate = rate;
 4608 
 4609                 ieee80211_radiotap_tx(vap, m);
 4610         }
 4611 
 4612         ring = &sc->txq[ac];
 4613         cmd = &ring->cmd[ring->cur];
 4614 
 4615         tx = (struct iwn_cmd_data *)cmd->data;
 4616         /* NB: No need to clear tx, all fields are reinitialized here. */
 4617         tx->scratch = 0;        /* clear "scratch" area */
 4618 
 4619         if (type == IEEE80211_FC0_TYPE_MGT) {
 4620                 uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
 4621 
 4622                 /* Tell HW to set timestamp in probe responses. */
 4623                 if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
 4624                         flags |= IWN_TX_INSERT_TSTAMP;
 4625 
 4626                 if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
 4627                     subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
 4628                         tx->timeout = htole16(3);
 4629                 else
 4630                         tx->timeout = htole16(2);
 4631         } else
 4632                 tx->timeout = htole16(0);
 4633 
 4634         tx->tid = 0;
 4635         tx->id = sc->broadcast_id;
 4636         tx->rts_ntries = params->ibp_try1;
 4637         tx->data_ntries = params->ibp_try0;
 4638         tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
 4639         tx->rate = iwn_rate_to_plcp(sc, ni, rate);
 4640         tx->security = 0;
 4641         tx->flags = htole32(flags);
 4642 
 4643         /* Group or management frame. */
 4644         tx->linkq = 0;
 4645 
 4646         return (iwn_tx_cmd(sc, m, ni, ring));
 4647 }
 4648 
 4649 static int
 4650 iwn_tx_cmd(struct iwn_softc *sc, struct mbuf *m, struct ieee80211_node *ni,
 4651     struct iwn_tx_ring *ring)
 4652 {
 4653         struct iwn_ops *ops = &sc->ops;
 4654         struct iwn_tx_cmd *cmd;
 4655         struct iwn_cmd_data *tx;
 4656         struct ieee80211_frame *wh;
 4657         struct iwn_tx_desc *desc;
 4658         struct iwn_tx_data *data;
 4659         bus_dma_segment_t *seg, segs[IWN_MAX_SCATTER];
 4660         struct mbuf *m1;
 4661         u_int hdrlen;
 4662         int totlen, error, pad, nsegs = 0, i;
 4663 
 4664         wh = mtod(m, struct ieee80211_frame *);
 4665         hdrlen = ieee80211_anyhdrsize(wh);
 4666         totlen = m->m_pkthdr.len;
 4667 
 4668         desc = &ring->desc[ring->cur];
 4669         data = &ring->data[ring->cur];
 4670 
 4671         /* Prepare TX firmware command. */
 4672         cmd = &ring->cmd[ring->cur];
 4673         cmd->code = IWN_CMD_TX_DATA;
 4674         cmd->flags = 0;
 4675         cmd->qid = ring->qid;
 4676         cmd->idx = ring->cur;
 4677 
 4678         tx = (struct iwn_cmd_data *)cmd->data;
 4679         tx->len = htole16(totlen);
 4680 
 4681         /* Set physical address of "scratch area". */
 4682         tx->loaddr = htole32(IWN_LOADDR(data->scratch_paddr));
 4683         tx->hiaddr = IWN_HIADDR(data->scratch_paddr);
 4684         if (hdrlen & 3) {
 4685                 /* First segment length must be a multiple of 4. */
 4686                 tx->flags |= htole32(IWN_TX_NEED_PADDING);
 4687                 pad = 4 - (hdrlen & 3);
 4688         } else
 4689                 pad = 0;
 4690 
 4691         /* Copy 802.11 header in TX command. */
 4692         memcpy((uint8_t *)(tx + 1), wh, hdrlen);
 4693 
 4694         /* Trim 802.11 header. */
 4695         m_adj(m, hdrlen);
 4696 
 4697         error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m, segs,
 4698             &nsegs, BUS_DMA_NOWAIT);
 4699         if (error != 0) {
 4700                 if (error != EFBIG) {
 4701                         device_printf(sc->sc_dev,
 4702                             "%s: can't map mbuf (error %d)\n", __func__, error);
 4703                         return error;
 4704                 }
 4705                 /* Too many DMA segments, linearize mbuf. */
 4706                 m1 = m_collapse(m, M_NOWAIT, IWN_MAX_SCATTER - 1);
 4707                 if (m1 == NULL) {
 4708                         device_printf(sc->sc_dev,
 4709                             "%s: could not defrag mbuf\n", __func__);
 4710                         return ENOBUFS;
 4711                 }
 4712                 m = m1;
 4713 
 4714                 error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m,
 4715                     segs, &nsegs, BUS_DMA_NOWAIT);
 4716                 if (error != 0) {
 4717                         /* XXX fix this */
 4718                         /*
 4719                          * NB: Do not return error;
 4720                          * original mbuf does not exist anymore.
 4721                          */
 4722                         device_printf(sc->sc_dev,
 4723                             "%s: can't map mbuf (error %d)\n",
 4724                             __func__, error);
 4725                         if_inc_counter(ni->ni_vap->iv_ifp,
 4726                             IFCOUNTER_OERRORS, 1);
 4727                         ieee80211_free_node(ni);
 4728                         m_freem(m);
 4729                         return 0;
 4730                 }
 4731         }
 4732 
 4733         data->m = m;
 4734         data->ni = ni;
 4735 
 4736         DPRINTF(sc, IWN_DEBUG_XMIT, "%s: qid %d idx %d len %d nsegs %d "
 4737             "plcp %d\n",
 4738             __func__, ring->qid, ring->cur, totlen, nsegs, tx->rate);
 4739 
 4740         /* Fill TX descriptor. */
 4741         desc->nsegs = 1;
 4742         if (m->m_len != 0)
 4743                 desc->nsegs += nsegs;
 4744         /* First DMA segment is used by the TX command. */
 4745         desc->segs[0].addr = htole32(IWN_LOADDR(data->cmd_paddr));
 4746         desc->segs[0].len  = htole16(IWN_HIADDR(data->cmd_paddr) |
 4747             (4 + sizeof (*tx) + hdrlen + pad) << 4);
 4748         /* Other DMA segments are for data payload. */
 4749         seg = &segs[0];
 4750         for (i = 1; i <= nsegs; i++) {
 4751                 desc->segs[i].addr = htole32(IWN_LOADDR(seg->ds_addr));
 4752                 desc->segs[i].len  = htole16(IWN_HIADDR(seg->ds_addr) |
 4753                     seg->ds_len << 4);
 4754                 seg++;
 4755         }
 4756 
 4757         bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
 4758         bus_dmamap_sync(ring->cmd_dma.tag, ring->cmd_dma.map,
 4759             BUS_DMASYNC_PREWRITE);
 4760         bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
 4761             BUS_DMASYNC_PREWRITE);
 4762 
 4763         /* Update TX scheduler. */
 4764         if (ring->qid >= sc->firstaggqueue)
 4765                 ops->update_sched(sc, ring->qid, ring->cur, tx->id, totlen);
 4766 
 4767         /* Kick TX ring. */
 4768         ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
 4769         IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
 4770 
 4771         /* Mark TX ring as full if we reach a certain threshold. */
 4772         if (++ring->queued > IWN_TX_RING_HIMARK)
 4773                 sc->qfullmsk |= 1 << ring->qid;
 4774 
 4775         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 4776 
 4777         return 0;
 4778 }
 4779 
 4780 static void
 4781 iwn_xmit_task(void *arg0, int pending)
 4782 {
 4783         struct iwn_softc *sc = arg0;
 4784         struct ieee80211_node *ni;
 4785         struct mbuf *m;
 4786         int error;
 4787         struct ieee80211_bpf_params p;
 4788         int have_p;
 4789 
 4790         DPRINTF(sc, IWN_DEBUG_XMIT, "%s: called\n", __func__);
 4791 
 4792         IWN_LOCK(sc);
 4793         /*
 4794          * Dequeue frames, attempt to transmit,
 4795          * then disable beaconwait when we're done.
 4796          */
 4797         while ((m = mbufq_dequeue(&sc->sc_xmit_queue)) != NULL) {
 4798                 have_p = 0;
 4799                 ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
 4800 
 4801                 /* Get xmit params if appropriate */
 4802                 if (ieee80211_get_xmit_params(m, &p) == 0)
 4803                         have_p = 1;
 4804 
 4805                 DPRINTF(sc, IWN_DEBUG_XMIT, "%s: m=%p, have_p=%d\n",
 4806                     __func__, m, have_p);
 4807 
 4808                 /* If we have xmit params, use them */
 4809                 if (have_p)
 4810                         error = iwn_tx_data_raw(sc, m, ni, &p);
 4811                 else
 4812                         error = iwn_tx_data(sc, m, ni);
 4813 
 4814                 if (error != 0) {
 4815                         if_inc_counter(ni->ni_vap->iv_ifp,
 4816                             IFCOUNTER_OERRORS, 1);
 4817                         ieee80211_free_node(ni);
 4818                         m_freem(m);
 4819                 }
 4820         }
 4821 
 4822         sc->sc_beacon_wait = 0;
 4823         IWN_UNLOCK(sc);
 4824 }
 4825 
 4826 /*
 4827  * raw frame xmit - free node/reference if failed.
 4828  */
 4829 static int
 4830 iwn_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
 4831     const struct ieee80211_bpf_params *params)
 4832 {
 4833         struct ieee80211com *ic = ni->ni_ic;
 4834         struct iwn_softc *sc = ic->ic_softc;
 4835         int error = 0;
 4836 
 4837         DPRINTF(sc, IWN_DEBUG_XMIT | IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 4838 
 4839         IWN_LOCK(sc);
 4840         if ((sc->sc_flags & IWN_FLAG_RUNNING) == 0) {
 4841                 m_freem(m);
 4842                 IWN_UNLOCK(sc);
 4843                 return (ENETDOWN);
 4844         }
 4845 
 4846         /* queue frame if we have to */
 4847         if (sc->sc_beacon_wait) {
 4848                 if (iwn_xmit_queue_enqueue(sc, m) != 0) {
 4849                         m_freem(m);
 4850                         IWN_UNLOCK(sc);
 4851                         return (ENOBUFS);
 4852                 }
 4853                 /* Queued, so just return OK */
 4854                 IWN_UNLOCK(sc);
 4855                 return (0);
 4856         }
 4857 
 4858         if (params == NULL) {
 4859                 /*
 4860                  * Legacy path; interpret frame contents to decide
 4861                  * precisely how to send the frame.
 4862                  */
 4863                 error = iwn_tx_data(sc, m, ni);
 4864         } else {
 4865                 /*
 4866                  * Caller supplied explicit parameters to use in
 4867                  * sending the frame.
 4868                  */
 4869                 error = iwn_tx_data_raw(sc, m, ni, params);
 4870         }
 4871         if (error == 0)
 4872                 sc->sc_tx_timer = 5;
 4873         else
 4874                 m_freem(m);
 4875 
 4876         IWN_UNLOCK(sc);
 4877 
 4878         DPRINTF(sc, IWN_DEBUG_TRACE | IWN_DEBUG_XMIT, "->%s: end\n",__func__);
 4879 
 4880         return (error);
 4881 }
 4882 
 4883 /*
 4884  * transmit - don't free mbuf if failed; don't free node ref if failed.
 4885  */
 4886 static int
 4887 iwn_transmit(struct ieee80211com *ic, struct mbuf *m)
 4888 {
 4889         struct iwn_softc *sc = ic->ic_softc;
 4890         struct ieee80211_node *ni;
 4891         int error;
 4892 
 4893         ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
 4894 
 4895         IWN_LOCK(sc);
 4896         if ((sc->sc_flags & IWN_FLAG_RUNNING) == 0 || sc->sc_beacon_wait) {
 4897                 IWN_UNLOCK(sc);
 4898                 return (ENXIO);
 4899         }
 4900 
 4901         if (sc->qfullmsk) {
 4902                 IWN_UNLOCK(sc);
 4903                 return (ENOBUFS);
 4904         }
 4905 
 4906         error = iwn_tx_data(sc, m, ni);
 4907         if (!error)
 4908                 sc->sc_tx_timer = 5;
 4909         IWN_UNLOCK(sc);
 4910         return (error);
 4911 }
 4912 
 4913 static void
 4914 iwn_scan_timeout(void *arg)
 4915 {
 4916         struct iwn_softc *sc = arg;
 4917         struct ieee80211com *ic = &sc->sc_ic;
 4918 
 4919         ic_printf(ic, "scan timeout\n");
 4920         ieee80211_restart_all(ic);
 4921 }
 4922 
 4923 static void
 4924 iwn_watchdog(void *arg)
 4925 {
 4926         struct iwn_softc *sc = arg;
 4927         struct ieee80211com *ic = &sc->sc_ic;
 4928 
 4929         IWN_LOCK_ASSERT(sc);
 4930 
 4931         KASSERT(sc->sc_flags & IWN_FLAG_RUNNING, ("not running"));
 4932 
 4933         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 4934 
 4935         if (sc->sc_tx_timer > 0) {
 4936                 if (--sc->sc_tx_timer == 0) {
 4937                         ic_printf(ic, "device timeout\n");
 4938                         ieee80211_restart_all(ic);
 4939                         return;
 4940                 }
 4941         }
 4942         callout_reset(&sc->watchdog_to, hz, iwn_watchdog, sc);
 4943 }
 4944 
 4945 static int
 4946 iwn_cdev_open(struct cdev *dev, int flags, int type, struct thread *td)
 4947 {
 4948 
 4949         return (0);
 4950 }
 4951 
 4952 static int
 4953 iwn_cdev_close(struct cdev *dev, int flags, int type, struct thread *td)
 4954 {
 4955 
 4956         return (0);
 4957 }
 4958 
 4959 static int
 4960 iwn_cdev_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
 4961     struct thread *td)
 4962 {
 4963         int rc;
 4964         struct iwn_softc *sc = dev->si_drv1;
 4965         struct iwn_ioctl_data *d;
 4966 
 4967         rc = priv_check(td, PRIV_DRIVER);
 4968         if (rc != 0)
 4969                 return (0);
 4970 
 4971         switch (cmd) {
 4972         case SIOCGIWNSTATS:
 4973                 d = (struct iwn_ioctl_data *) data;
 4974                 IWN_LOCK(sc);
 4975                 /* XXX validate permissions/memory/etc? */
 4976                 rc = copyout(&sc->last_stat, d->dst_addr, sizeof(struct iwn_stats));
 4977                 IWN_UNLOCK(sc);
 4978                 break;
 4979         case SIOCZIWNSTATS:
 4980                 IWN_LOCK(sc);
 4981                 memset(&sc->last_stat, 0, sizeof(struct iwn_stats));
 4982                 IWN_UNLOCK(sc);
 4983                 break;
 4984         default:
 4985                 rc = EINVAL;
 4986                 break;
 4987         }
 4988         return (rc);
 4989 }
 4990 
 4991 static int
 4992 iwn_ioctl(struct ieee80211com *ic, u_long cmd, void *data)
 4993 {
 4994 
 4995         return (ENOTTY);
 4996 }
 4997 
 4998 static void
 4999 iwn_parent(struct ieee80211com *ic)
 5000 {
 5001         struct iwn_softc *sc = ic->ic_softc;
 5002         struct ieee80211vap *vap;
 5003         int error;
 5004 
 5005         if (ic->ic_nrunning > 0) {
 5006                 error = iwn_init(sc);
 5007 
 5008                 switch (error) {
 5009                 case 0:
 5010                         ieee80211_start_all(ic);
 5011                         break;
 5012                 case 1:
 5013                         /* radio is disabled via RFkill switch */
 5014                         taskqueue_enqueue(sc->sc_tq, &sc->sc_rftoggle_task);
 5015                         break;
 5016                 default:
 5017                         vap = TAILQ_FIRST(&ic->ic_vaps);
 5018                         if (vap != NULL)
 5019                                 ieee80211_stop(vap);
 5020                         break;
 5021                 }
 5022         } else
 5023                 iwn_stop(sc);
 5024 }
 5025 
 5026 /*
 5027  * Send a command to the firmware.
 5028  */
 5029 static int
 5030 iwn_cmd(struct iwn_softc *sc, int code, const void *buf, int size, int async)
 5031 {
 5032         struct iwn_tx_ring *ring;
 5033         struct iwn_tx_desc *desc;
 5034         struct iwn_tx_data *data;
 5035         struct iwn_tx_cmd *cmd;
 5036         struct mbuf *m;
 5037         bus_addr_t paddr;
 5038         int totlen, error;
 5039         int cmd_queue_num;
 5040 
 5041         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 5042 
 5043         if (async == 0)
 5044                 IWN_LOCK_ASSERT(sc);
 5045 
 5046         if (sc->sc_flags & IWN_FLAG_PAN_SUPPORT)
 5047                 cmd_queue_num = IWN_PAN_CMD_QUEUE;
 5048         else
 5049                 cmd_queue_num = IWN_CMD_QUEUE_NUM;
 5050 
 5051         ring = &sc->txq[cmd_queue_num];
 5052         desc = &ring->desc[ring->cur];
 5053         data = &ring->data[ring->cur];
 5054         totlen = 4 + size;
 5055 
 5056         if (size > sizeof cmd->data) {
 5057                 /* Command is too large to fit in a descriptor. */
 5058                 if (totlen > MCLBYTES)
 5059                         return EINVAL;
 5060                 m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE);
 5061                 if (m == NULL)
 5062                         return ENOMEM;
 5063                 cmd = mtod(m, struct iwn_tx_cmd *);
 5064                 error = bus_dmamap_load(ring->data_dmat, data->map, cmd,
 5065                     totlen, iwn_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
 5066                 if (error != 0) {
 5067                         m_freem(m);
 5068                         return error;
 5069                 }
 5070                 data->m = m;
 5071         } else {
 5072                 cmd = &ring->cmd[ring->cur];
 5073                 paddr = data->cmd_paddr;
 5074         }
 5075 
 5076         cmd->code = code;
 5077         cmd->flags = 0;
 5078         cmd->qid = ring->qid;
 5079         cmd->idx = ring->cur;
 5080         memcpy(cmd->data, buf, size);
 5081 
 5082         desc->nsegs = 1;
 5083         desc->segs[0].addr = htole32(IWN_LOADDR(paddr));
 5084         desc->segs[0].len  = htole16(IWN_HIADDR(paddr) | totlen << 4);
 5085 
 5086         DPRINTF(sc, IWN_DEBUG_CMD, "%s: %s (0x%x) flags %d qid %d idx %d\n",
 5087             __func__, iwn_intr_str(cmd->code), cmd->code,
 5088             cmd->flags, cmd->qid, cmd->idx);
 5089 
 5090         if (size > sizeof cmd->data) {
 5091                 bus_dmamap_sync(ring->data_dmat, data->map,
 5092                     BUS_DMASYNC_PREWRITE);
 5093         } else {
 5094                 bus_dmamap_sync(ring->cmd_dma.tag, ring->cmd_dma.map,
 5095                     BUS_DMASYNC_PREWRITE);
 5096         }
 5097         bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
 5098             BUS_DMASYNC_PREWRITE);
 5099 
 5100         /* Kick command ring. */
 5101         ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
 5102         IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
 5103 
 5104         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 5105 
 5106         return async ? 0 : msleep(desc, &sc->sc_mtx, PCATCH, "iwncmd", hz);
 5107 }
 5108 
 5109 static int
 5110 iwn4965_add_node(struct iwn_softc *sc, struct iwn_node_info *node, int async)
 5111 {
 5112         struct iwn4965_node_info hnode;
 5113         caddr_t src, dst;
 5114 
 5115         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5116 
 5117         /*
 5118          * We use the node structure for 5000 Series internally (it is
 5119          * a superset of the one for 4965AGN). We thus copy the common
 5120          * fields before sending the command.
 5121          */
 5122         src = (caddr_t)node;
 5123         dst = (caddr_t)&hnode;
 5124         memcpy(dst, src, 48);
 5125         /* Skip TSC, RX MIC and TX MIC fields from ``src''. */
 5126         memcpy(dst + 48, src + 72, 20);
 5127         return iwn_cmd(sc, IWN_CMD_ADD_NODE, &hnode, sizeof hnode, async);
 5128 }
 5129 
 5130 static int
 5131 iwn5000_add_node(struct iwn_softc *sc, struct iwn_node_info *node, int async)
 5132 {
 5133 
 5134         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5135 
 5136         /* Direct mapping. */
 5137         return iwn_cmd(sc, IWN_CMD_ADD_NODE, node, sizeof (*node), async);
 5138 }
 5139 
 5140 static int
 5141 iwn_set_link_quality(struct iwn_softc *sc, struct ieee80211_node *ni)
 5142 {
 5143         struct iwn_node *wn = (void *)ni;
 5144         struct ieee80211_rateset *rs;
 5145         struct iwn_cmd_link_quality linkq;
 5146         int i, rate, txrate;
 5147         int is_11n;
 5148 
 5149         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 5150 
 5151         memset(&linkq, 0, sizeof linkq);
 5152         linkq.id = wn->id;
 5153         linkq.antmsk_1stream = iwn_get_1stream_tx_antmask(sc);
 5154         linkq.antmsk_2stream = iwn_get_2stream_tx_antmask(sc);
 5155 
 5156         linkq.ampdu_max = 32;           /* XXX negotiated? */
 5157         linkq.ampdu_threshold = 3;
 5158         linkq.ampdu_limit = htole16(4000);      /* 4ms */
 5159 
 5160         DPRINTF(sc, IWN_DEBUG_XMIT,
 5161             "%s: 1stream antenna=0x%02x, 2stream antenna=0x%02x, ntxstreams=%d\n",
 5162             __func__,
 5163             linkq.antmsk_1stream,
 5164             linkq.antmsk_2stream,
 5165             sc->ntxchains);
 5166 
 5167         /*
 5168          * Are we using 11n rates? Ensure the channel is
 5169          * 11n _and_ we have some 11n rates, or don't
 5170          * try.
 5171          */
 5172         if (IEEE80211_IS_CHAN_HT(ni->ni_chan) && ni->ni_htrates.rs_nrates > 0) {
 5173                 rs = (struct ieee80211_rateset *) &ni->ni_htrates;
 5174                 is_11n = 1;
 5175         } else {
 5176                 rs = &ni->ni_rates;
 5177                 is_11n = 0;
 5178         }
 5179 
 5180         /* Start at highest available bit-rate. */
 5181         /*
 5182          * XXX this is all very dirty!
 5183          */
 5184         if (is_11n)
 5185                 txrate = ni->ni_htrates.rs_nrates - 1;
 5186         else
 5187                 txrate = rs->rs_nrates - 1;
 5188         for (i = 0; i < IWN_MAX_TX_RETRIES; i++) {
 5189                 uint32_t plcp;
 5190 
 5191                 /*
 5192                  * XXX TODO: ensure the last two slots are the two lowest
 5193                  * rate entries, just for now.
 5194                  */
 5195                 if (i == 14 || i == 15)
 5196                         txrate = 0;
 5197 
 5198                 if (is_11n)
 5199                         rate = IEEE80211_RATE_MCS | rs->rs_rates[txrate];
 5200                 else
 5201                         rate = IEEE80211_RV(rs->rs_rates[txrate]);
 5202 
 5203                 /* Do rate -> PLCP config mapping */
 5204                 plcp = iwn_rate_to_plcp(sc, ni, rate);
 5205                 linkq.retry[i] = plcp;
 5206                 DPRINTF(sc, IWN_DEBUG_XMIT,
 5207                     "%s: i=%d, txrate=%d, rate=0x%02x, plcp=0x%08x\n",
 5208                     __func__,
 5209                     i,
 5210                     txrate,
 5211                     rate,
 5212                     le32toh(plcp));
 5213 
 5214                 /*
 5215                  * The mimo field is an index into the table which
 5216                  * indicates the first index where it and subsequent entries
 5217                  * will not be using MIMO.
 5218                  *
 5219                  * Since we're filling linkq from 0..15 and we're filling
 5220                  * from the highest MCS rates to the lowest rates, if we
 5221                  * _are_ doing a dual-stream rate, set mimo to idx+1 (ie,
 5222                  * the next entry.)  That way if the next entry is a non-MIMO
 5223                  * entry, we're already pointing at it.
 5224                  */
 5225                 if ((le32toh(plcp) & IWN_RFLAG_MCS) &&
 5226                     IEEE80211_RV(le32toh(plcp)) > 7)
 5227                         linkq.mimo = i + 1;
 5228 
 5229                 /* Next retry at immediate lower bit-rate. */
 5230                 if (txrate > 0)
 5231                         txrate--;
 5232         }
 5233         /*
 5234          * If we reached the end of the list and indeed we hit
 5235          * all MIMO rates (eg 5300 doing MCS23-15) then yes,
 5236          * set mimo to 15.  Setting it to 16 panics the firmware.
 5237          */
 5238         if (linkq.mimo > 15)
 5239                 linkq.mimo = 15;
 5240 
 5241         DPRINTF(sc, IWN_DEBUG_XMIT, "%s: mimo = %d\n", __func__, linkq.mimo);
 5242 
 5243         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 5244 
 5245         return iwn_cmd(sc, IWN_CMD_LINK_QUALITY, &linkq, sizeof linkq, 1);
 5246 }
 5247 
 5248 /*
 5249  * Broadcast node is used to send group-addressed and management frames.
 5250  */
 5251 static int
 5252 iwn_add_broadcast_node(struct iwn_softc *sc, int async)
 5253 {
 5254         struct iwn_ops *ops = &sc->ops;
 5255         struct ieee80211com *ic = &sc->sc_ic;
 5256         struct iwn_node_info node;
 5257         struct iwn_cmd_link_quality linkq;
 5258         uint8_t txant;
 5259         int i, error;
 5260 
 5261         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 5262 
 5263         sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
 5264 
 5265         memset(&node, 0, sizeof node);
 5266         IEEE80211_ADDR_COPY(node.macaddr, ieee80211broadcastaddr);
 5267         node.id = sc->broadcast_id;
 5268         DPRINTF(sc, IWN_DEBUG_RESET, "%s: adding broadcast node\n", __func__);
 5269         if ((error = ops->add_node(sc, &node, async)) != 0)
 5270                 return error;
 5271 
 5272         /* Use the first valid TX antenna. */
 5273         txant = IWN_LSB(sc->txchainmask);
 5274 
 5275         memset(&linkq, 0, sizeof linkq);
 5276         linkq.id = sc->broadcast_id;
 5277         linkq.antmsk_1stream = iwn_get_1stream_tx_antmask(sc);
 5278         linkq.antmsk_2stream = iwn_get_2stream_tx_antmask(sc);
 5279         linkq.ampdu_max = 64;
 5280         linkq.ampdu_threshold = 3;
 5281         linkq.ampdu_limit = htole16(4000);      /* 4ms */
 5282 
 5283         /* Use lowest mandatory bit-rate. */
 5284         /* XXX rate table lookup? */
 5285         if (IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan))
 5286                 linkq.retry[0] = htole32(0xd);
 5287         else
 5288                 linkq.retry[0] = htole32(10 | IWN_RFLAG_CCK);
 5289         linkq.retry[0] |= htole32(IWN_RFLAG_ANT(txant));
 5290         /* Use same bit-rate for all TX retries. */
 5291         for (i = 1; i < IWN_MAX_TX_RETRIES; i++) {
 5292                 linkq.retry[i] = linkq.retry[0];
 5293         }
 5294 
 5295         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 5296 
 5297         return iwn_cmd(sc, IWN_CMD_LINK_QUALITY, &linkq, sizeof linkq, async);
 5298 }
 5299 
 5300 static int
 5301 iwn_updateedca(struct ieee80211com *ic)
 5302 {
 5303 #define IWN_EXP2(x)     ((1 << (x)) - 1)        /* CWmin = 2^ECWmin - 1 */
 5304         struct iwn_softc *sc = ic->ic_softc;
 5305         struct iwn_edca_params cmd;
 5306         struct chanAccParams chp;
 5307         int aci;
 5308 
 5309         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 5310 
 5311         ieee80211_wme_ic_getparams(ic, &chp);
 5312 
 5313         memset(&cmd, 0, sizeof cmd);
 5314         cmd.flags = htole32(IWN_EDCA_UPDATE);
 5315 
 5316         IEEE80211_LOCK(ic);
 5317         for (aci = 0; aci < WME_NUM_AC; aci++) {
 5318                 const struct wmeParams *ac = &chp.cap_wmeParams[aci];
 5319                 cmd.ac[aci].aifsn = ac->wmep_aifsn;
 5320                 cmd.ac[aci].cwmin = htole16(IWN_EXP2(ac->wmep_logcwmin));
 5321                 cmd.ac[aci].cwmax = htole16(IWN_EXP2(ac->wmep_logcwmax));
 5322                 cmd.ac[aci].txoplimit =
 5323                     htole16(IEEE80211_TXOP_TO_US(ac->wmep_txopLimit));
 5324         }
 5325         IEEE80211_UNLOCK(ic);
 5326 
 5327         IWN_LOCK(sc);
 5328         (void)iwn_cmd(sc, IWN_CMD_EDCA_PARAMS, &cmd, sizeof cmd, 1);
 5329         IWN_UNLOCK(sc);
 5330 
 5331         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 5332 
 5333         return 0;
 5334 #undef IWN_EXP2
 5335 }
 5336 
 5337 static void
 5338 iwn_set_promisc(struct iwn_softc *sc)
 5339 {
 5340         struct ieee80211com *ic = &sc->sc_ic;
 5341         uint32_t promisc_filter;
 5342 
 5343         promisc_filter = IWN_FILTER_CTL | IWN_FILTER_PROMISC;
 5344         if (ic->ic_promisc > 0 || ic->ic_opmode == IEEE80211_M_MONITOR)
 5345                 sc->rxon->filter |= htole32(promisc_filter);
 5346         else
 5347                 sc->rxon->filter &= ~htole32(promisc_filter);
 5348 }
 5349 
 5350 static void
 5351 iwn_update_promisc(struct ieee80211com *ic)
 5352 {
 5353         struct iwn_softc *sc = ic->ic_softc;
 5354         int error;
 5355 
 5356         if (ic->ic_opmode == IEEE80211_M_MONITOR)
 5357                 return;         /* nothing to do */
 5358 
 5359         IWN_LOCK(sc);
 5360         if (!(sc->sc_flags & IWN_FLAG_RUNNING)) {
 5361                 IWN_UNLOCK(sc);
 5362                 return;
 5363         }
 5364 
 5365         iwn_set_promisc(sc);
 5366         if ((error = iwn_send_rxon(sc, 1, 1)) != 0) {
 5367                 device_printf(sc->sc_dev,
 5368                     "%s: could not send RXON, error %d\n",
 5369                     __func__, error);
 5370         }
 5371         IWN_UNLOCK(sc);
 5372 }
 5373 
 5374 static void
 5375 iwn_update_mcast(struct ieee80211com *ic)
 5376 {
 5377         /* Ignore */
 5378 }
 5379 
 5380 static void
 5381 iwn_set_led(struct iwn_softc *sc, uint8_t which, uint8_t off, uint8_t on)
 5382 {
 5383         struct iwn_cmd_led led;
 5384 
 5385         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5386 
 5387 #if 0
 5388         /* XXX don't set LEDs during scan? */
 5389         if (sc->sc_is_scanning)
 5390                 return;
 5391 #endif
 5392 
 5393         /* Clear microcode LED ownership. */
 5394         IWN_CLRBITS(sc, IWN_LED, IWN_LED_BSM_CTRL);
 5395 
 5396         led.which = which;
 5397         led.unit = htole32(10000);      /* on/off in unit of 100ms */
 5398         led.off = off;
 5399         led.on = on;
 5400         (void)iwn_cmd(sc, IWN_CMD_SET_LED, &led, sizeof led, 1);
 5401 }
 5402 
 5403 /*
 5404  * Set the critical temperature at which the firmware will stop the radio
 5405  * and notify us.
 5406  */
 5407 static int
 5408 iwn_set_critical_temp(struct iwn_softc *sc)
 5409 {
 5410         struct iwn_critical_temp crit;
 5411         int32_t temp;
 5412 
 5413         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5414 
 5415         IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CTEMP_STOP_RF);
 5416 
 5417         if (sc->hw_type == IWN_HW_REV_TYPE_5150)
 5418                 temp = (IWN_CTOK(110) - sc->temp_off) * -5;
 5419         else if (sc->hw_type == IWN_HW_REV_TYPE_4965)
 5420                 temp = IWN_CTOK(110);
 5421         else
 5422                 temp = 110;
 5423         memset(&crit, 0, sizeof crit);
 5424         crit.tempR = htole32(temp);
 5425         DPRINTF(sc, IWN_DEBUG_RESET, "setting critical temp to %d\n", temp);
 5426         return iwn_cmd(sc, IWN_CMD_SET_CRITICAL_TEMP, &crit, sizeof crit, 0);
 5427 }
 5428 
 5429 static int
 5430 iwn_set_timing(struct iwn_softc *sc, struct ieee80211_node *ni)
 5431 {
 5432         struct iwn_cmd_timing cmd;
 5433         uint64_t val, mod;
 5434 
 5435         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5436 
 5437         memset(&cmd, 0, sizeof cmd);
 5438         memcpy(&cmd.tstamp, ni->ni_tstamp.data, sizeof (uint64_t));
 5439         cmd.bintval = htole16(ni->ni_intval);
 5440         cmd.lintval = htole16(10);
 5441 
 5442         /* Compute remaining time until next beacon. */
 5443         val = (uint64_t)ni->ni_intval * IEEE80211_DUR_TU;
 5444         mod = le64toh(cmd.tstamp) % val;
 5445         cmd.binitval = htole32((uint32_t)(val - mod));
 5446 
 5447         DPRINTF(sc, IWN_DEBUG_RESET, "timing bintval=%u tstamp=%ju, init=%u\n",
 5448             ni->ni_intval, le64toh(cmd.tstamp), (uint32_t)(val - mod));
 5449 
 5450         return iwn_cmd(sc, IWN_CMD_TIMING, &cmd, sizeof cmd, 1);
 5451 }
 5452 
 5453 static void
 5454 iwn4965_power_calibration(struct iwn_softc *sc, int temp)
 5455 {
 5456 
 5457         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5458 
 5459         /* Adjust TX power if need be (delta >= 3 degC). */
 5460         DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: temperature %d->%d\n",
 5461             __func__, sc->temp, temp);
 5462         if (abs(temp - sc->temp) >= 3) {
 5463                 /* Record temperature of last calibration. */
 5464                 sc->temp = temp;
 5465                 (void)iwn4965_set_txpower(sc, 1);
 5466         }
 5467 }
 5468 
 5469 /*
 5470  * Set TX power for current channel (each rate has its own power settings).
 5471  * This function takes into account the regulatory information from EEPROM,
 5472  * the current temperature and the current voltage.
 5473  */
 5474 static int
 5475 iwn4965_set_txpower(struct iwn_softc *sc, int async)
 5476 {
 5477 /* Fixed-point arithmetic division using a n-bit fractional part. */
 5478 #define fdivround(a, b, n)      \
 5479         ((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
 5480 /* Linear interpolation. */
 5481 #define interpolate(x, x1, y1, x2, y2, n)       \
 5482         ((y1) + fdivround(((int)(x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
 5483 
 5484         static const int tdiv[IWN_NATTEN_GROUPS] = { 9, 8, 8, 8, 6 };
 5485         struct iwn_ucode_info *uc = &sc->ucode_info;
 5486         struct iwn4965_cmd_txpower cmd;
 5487         struct iwn4965_eeprom_chan_samples *chans;
 5488         const uint8_t *rf_gain, *dsp_gain;
 5489         int32_t vdiff, tdiff;
 5490         int i, is_chan_5ghz, c, grp, maxpwr;
 5491         uint8_t chan;
 5492 
 5493         sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
 5494         /* Retrieve current channel from last RXON. */
 5495         chan = sc->rxon->chan;
 5496         is_chan_5ghz = (sc->rxon->flags & htole32(IWN_RXON_24GHZ)) == 0;
 5497         DPRINTF(sc, IWN_DEBUG_RESET, "setting TX power for channel %d\n",
 5498             chan);
 5499 
 5500         memset(&cmd, 0, sizeof cmd);
 5501         cmd.band = is_chan_5ghz ? 0 : 1;
 5502         cmd.chan = chan;
 5503 
 5504         if (is_chan_5ghz) {
 5505                 maxpwr   = sc->maxpwr5GHz;
 5506                 rf_gain  = iwn4965_rf_gain_5ghz;
 5507                 dsp_gain = iwn4965_dsp_gain_5ghz;
 5508         } else {
 5509                 maxpwr   = sc->maxpwr2GHz;
 5510                 rf_gain  = iwn4965_rf_gain_2ghz;
 5511                 dsp_gain = iwn4965_dsp_gain_2ghz;
 5512         }
 5513 
 5514         /* Compute voltage compensation. */
 5515         vdiff = ((int32_t)le32toh(uc->volt) - sc->eeprom_voltage) / 7;
 5516         if (vdiff > 0)
 5517                 vdiff *= 2;
 5518         if (abs(vdiff) > 2)
 5519                 vdiff = 0;
 5520         DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
 5521             "%s: voltage compensation=%d (UCODE=%d, EEPROM=%d)\n",
 5522             __func__, vdiff, le32toh(uc->volt), sc->eeprom_voltage);
 5523 
 5524         /* Get channel attenuation group. */
 5525         if (chan <= 20)         /* 1-20 */
 5526                 grp = 4;
 5527         else if (chan <= 43)    /* 34-43 */
 5528                 grp = 0;
 5529         else if (chan <= 70)    /* 44-70 */
 5530                 grp = 1;
 5531         else if (chan <= 124)   /* 71-124 */
 5532                 grp = 2;
 5533         else                    /* 125-200 */
 5534                 grp = 3;
 5535         DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
 5536             "%s: chan %d, attenuation group=%d\n", __func__, chan, grp);
 5537 
 5538         /* Get channel sub-band. */
 5539         for (i = 0; i < IWN_NBANDS; i++)
 5540                 if (sc->bands[i].lo != 0 &&
 5541                     sc->bands[i].lo <= chan && chan <= sc->bands[i].hi)
 5542                         break;
 5543         if (i == IWN_NBANDS)    /* Can't happen in real-life. */
 5544                 return EINVAL;
 5545         chans = sc->bands[i].chans;
 5546         DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
 5547             "%s: chan %d sub-band=%d\n", __func__, chan, i);
 5548 
 5549         for (c = 0; c < 2; c++) {
 5550                 uint8_t power, gain, temp;
 5551                 int maxchpwr, pwr, ridx, idx;
 5552 
 5553                 power = interpolate(chan,
 5554                     chans[0].num, chans[0].samples[c][1].power,
 5555                     chans[1].num, chans[1].samples[c][1].power, 1);
 5556                 gain  = interpolate(chan,
 5557                     chans[0].num, chans[0].samples[c][1].gain,
 5558                     chans[1].num, chans[1].samples[c][1].gain, 1);
 5559                 temp  = interpolate(chan,
 5560                     chans[0].num, chans[0].samples[c][1].temp,
 5561                     chans[1].num, chans[1].samples[c][1].temp, 1);
 5562                 DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
 5563                     "%s: Tx chain %d: power=%d gain=%d temp=%d\n",
 5564                     __func__, c, power, gain, temp);
 5565 
 5566                 /* Compute temperature compensation. */
 5567                 tdiff = ((sc->temp - temp) * 2) / tdiv[grp];
 5568                 DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
 5569                     "%s: temperature compensation=%d (current=%d, EEPROM=%d)\n",
 5570                     __func__, tdiff, sc->temp, temp);
 5571 
 5572                 for (ridx = 0; ridx <= IWN_RIDX_MAX; ridx++) {
 5573                         /* Convert dBm to half-dBm. */
 5574                         maxchpwr = sc->maxpwr[chan] * 2;
 5575                         if ((ridx / 8) & 1)
 5576                                 maxchpwr -= 6;  /* MIMO 2T: -3dB */
 5577 
 5578                         pwr = maxpwr;
 5579 
 5580                         /* Adjust TX power based on rate. */
 5581                         if ((ridx % 8) == 5)
 5582                                 pwr -= 15;      /* OFDM48: -7.5dB */
 5583                         else if ((ridx % 8) == 6)
 5584                                 pwr -= 17;      /* OFDM54: -8.5dB */
 5585                         else if ((ridx % 8) == 7)
 5586                                 pwr -= 20;      /* OFDM60: -10dB */
 5587                         else
 5588                                 pwr -= 10;      /* Others: -5dB */
 5589 
 5590                         /* Do not exceed channel max TX power. */
 5591                         if (pwr > maxchpwr)
 5592                                 pwr = maxchpwr;
 5593 
 5594                         idx = gain - (pwr - power) - tdiff - vdiff;
 5595                         if ((ridx / 8) & 1)     /* MIMO */
 5596                                 idx += (int32_t)le32toh(uc->atten[grp][c]);
 5597 
 5598                         if (cmd.band == 0)
 5599                                 idx += 9;       /* 5GHz */
 5600                         if (ridx == IWN_RIDX_MAX)
 5601                                 idx += 5;       /* CCK */
 5602 
 5603                         /* Make sure idx stays in a valid range. */
 5604                         if (idx < 0)
 5605                                 idx = 0;
 5606                         else if (idx > IWN4965_MAX_PWR_INDEX)
 5607                                 idx = IWN4965_MAX_PWR_INDEX;
 5608 
 5609                         DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
 5610                             "%s: Tx chain %d, rate idx %d: power=%d\n",
 5611                             __func__, c, ridx, idx);
 5612                         cmd.power[ridx].rf_gain[c] = rf_gain[idx];
 5613                         cmd.power[ridx].dsp_gain[c] = dsp_gain[idx];
 5614                 }
 5615         }
 5616 
 5617         DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
 5618             "%s: set tx power for chan %d\n", __func__, chan);
 5619         return iwn_cmd(sc, IWN_CMD_TXPOWER, &cmd, sizeof cmd, async);
 5620 
 5621 #undef interpolate
 5622 #undef fdivround
 5623 }
 5624 
 5625 static int
 5626 iwn5000_set_txpower(struct iwn_softc *sc, int async)
 5627 {
 5628         struct iwn5000_cmd_txpower cmd;
 5629         int cmdid;
 5630 
 5631         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5632 
 5633         /*
 5634          * TX power calibration is handled automatically by the firmware
 5635          * for 5000 Series.
 5636          */
 5637         memset(&cmd, 0, sizeof cmd);
 5638         cmd.global_limit = 2 * IWN5000_TXPOWER_MAX_DBM; /* 16 dBm */
 5639         cmd.flags = IWN5000_TXPOWER_NO_CLOSED;
 5640         cmd.srv_limit = IWN5000_TXPOWER_AUTO;
 5641         DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_XMIT,
 5642             "%s: setting TX power; rev=%d\n",
 5643             __func__,
 5644             IWN_UCODE_API(sc->ucode_rev));
 5645         if (IWN_UCODE_API(sc->ucode_rev) == 1)
 5646                 cmdid = IWN_CMD_TXPOWER_DBM_V1;
 5647         else
 5648                 cmdid = IWN_CMD_TXPOWER_DBM;
 5649         return iwn_cmd(sc, cmdid, &cmd, sizeof cmd, async);
 5650 }
 5651 
 5652 /*
 5653  * Retrieve the maximum RSSI (in dBm) among receivers.
 5654  */
 5655 static int
 5656 iwn4965_get_rssi(struct iwn_softc *sc, struct iwn_rx_stat *stat)
 5657 {
 5658         struct iwn4965_rx_phystat *phy = (void *)stat->phybuf;
 5659         uint8_t mask, agc;
 5660         int rssi;
 5661 
 5662         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5663 
 5664         mask = (le16toh(phy->antenna) >> 4) & IWN_ANT_ABC;
 5665         agc  = (le16toh(phy->agc) >> 7) & 0x7f;
 5666 
 5667         rssi = 0;
 5668         if (mask & IWN_ANT_A)
 5669                 rssi = MAX(rssi, phy->rssi[0]);
 5670         if (mask & IWN_ANT_B)
 5671                 rssi = MAX(rssi, phy->rssi[2]);
 5672         if (mask & IWN_ANT_C)
 5673                 rssi = MAX(rssi, phy->rssi[4]);
 5674 
 5675         DPRINTF(sc, IWN_DEBUG_RECV,
 5676             "%s: agc %d mask 0x%x rssi %d %d %d result %d\n", __func__, agc,
 5677             mask, phy->rssi[0], phy->rssi[2], phy->rssi[4],
 5678             rssi - agc - IWN_RSSI_TO_DBM);
 5679         return rssi - agc - IWN_RSSI_TO_DBM;
 5680 }
 5681 
 5682 static int
 5683 iwn5000_get_rssi(struct iwn_softc *sc, struct iwn_rx_stat *stat)
 5684 {
 5685         struct iwn5000_rx_phystat *phy = (void *)stat->phybuf;
 5686         uint8_t agc;
 5687         int rssi;
 5688 
 5689         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5690 
 5691         agc = (le32toh(phy->agc) >> 9) & 0x7f;
 5692 
 5693         rssi = MAX(le16toh(phy->rssi[0]) & 0xff,
 5694                    le16toh(phy->rssi[1]) & 0xff);
 5695         rssi = MAX(le16toh(phy->rssi[2]) & 0xff, rssi);
 5696 
 5697         DPRINTF(sc, IWN_DEBUG_RECV,
 5698             "%s: agc %d rssi %d %d %d result %d\n", __func__, agc,
 5699             phy->rssi[0], phy->rssi[1], phy->rssi[2],
 5700             rssi - agc - IWN_RSSI_TO_DBM);
 5701         return rssi - agc - IWN_RSSI_TO_DBM;
 5702 }
 5703 
 5704 /*
 5705  * Retrieve the average noise (in dBm) among receivers.
 5706  */
 5707 static int
 5708 iwn_get_noise(const struct iwn_rx_general_stats *stats)
 5709 {
 5710         int i, total, nbant, noise;
 5711 
 5712         total = nbant = 0;
 5713         for (i = 0; i < 3; i++) {
 5714                 if ((noise = le32toh(stats->noise[i]) & 0xff) == 0)
 5715                         continue;
 5716                 total += noise;
 5717                 nbant++;
 5718         }
 5719         /* There should be at least one antenna but check anyway. */
 5720         return (nbant == 0) ? -127 : (total / nbant) - 107;
 5721 }
 5722 
 5723 /*
 5724  * Compute temperature (in degC) from last received statistics.
 5725  */
 5726 static int
 5727 iwn4965_get_temperature(struct iwn_softc *sc)
 5728 {
 5729         struct iwn_ucode_info *uc = &sc->ucode_info;
 5730         int32_t r1, r2, r3, r4, temp;
 5731 
 5732         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5733 
 5734         r1 = le32toh(uc->temp[0].chan20MHz);
 5735         r2 = le32toh(uc->temp[1].chan20MHz);
 5736         r3 = le32toh(uc->temp[2].chan20MHz);
 5737         r4 = le32toh(sc->rawtemp);
 5738 
 5739         if (r1 == r3)   /* Prevents division by 0 (should not happen). */
 5740                 return 0;
 5741 
 5742         /* Sign-extend 23-bit R4 value to 32-bit. */
 5743         r4 = ((r4 & 0xffffff) ^ 0x800000) - 0x800000;
 5744         /* Compute temperature in Kelvin. */
 5745         temp = (259 * (r4 - r2)) / (r3 - r1);
 5746         temp = (temp * 97) / 100 + 8;
 5747 
 5748         DPRINTF(sc, IWN_DEBUG_ANY, "temperature %dK/%dC\n", temp,
 5749             IWN_KTOC(temp));
 5750         return IWN_KTOC(temp);
 5751 }
 5752 
 5753 static int
 5754 iwn5000_get_temperature(struct iwn_softc *sc)
 5755 {
 5756         int32_t temp;
 5757 
 5758         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5759 
 5760         /*
 5761          * Temperature is not used by the driver for 5000 Series because
 5762          * TX power calibration is handled by firmware.
 5763          */
 5764         temp = le32toh(sc->rawtemp);
 5765         if (sc->hw_type == IWN_HW_REV_TYPE_5150) {
 5766                 temp = (temp / -5) + sc->temp_off;
 5767                 temp = IWN_KTOC(temp);
 5768         }
 5769         return temp;
 5770 }
 5771 
 5772 /*
 5773  * Initialize sensitivity calibration state machine.
 5774  */
 5775 static int
 5776 iwn_init_sensitivity(struct iwn_softc *sc)
 5777 {
 5778         struct iwn_ops *ops = &sc->ops;
 5779         struct iwn_calib_state *calib = &sc->calib;
 5780         uint32_t flags;
 5781         int error;
 5782 
 5783         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5784 
 5785         /* Reset calibration state machine. */
 5786         memset(calib, 0, sizeof (*calib));
 5787         calib->state = IWN_CALIB_STATE_INIT;
 5788         calib->cck_state = IWN_CCK_STATE_HIFA;
 5789         /* Set initial correlation values. */
 5790         calib->ofdm_x1     = sc->limits->min_ofdm_x1;
 5791         calib->ofdm_mrc_x1 = sc->limits->min_ofdm_mrc_x1;
 5792         calib->ofdm_x4     = sc->limits->min_ofdm_x4;
 5793         calib->ofdm_mrc_x4 = sc->limits->min_ofdm_mrc_x4;
 5794         calib->cck_x4      = 125;
 5795         calib->cck_mrc_x4  = sc->limits->min_cck_mrc_x4;
 5796         calib->energy_cck  = sc->limits->energy_cck;
 5797 
 5798         /* Write initial sensitivity. */
 5799         if ((error = iwn_send_sensitivity(sc)) != 0)
 5800                 return error;
 5801 
 5802         /* Write initial gains. */
 5803         if ((error = ops->init_gains(sc)) != 0)
 5804                 return error;
 5805 
 5806         /* Request statistics at each beacon interval. */
 5807         flags = 0;
 5808         DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: sending request for statistics\n",
 5809             __func__);
 5810         return iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags, sizeof flags, 1);
 5811 }
 5812 
 5813 /*
 5814  * Collect noise and RSSI statistics for the first 20 beacons received
 5815  * after association and use them to determine connected antennas and
 5816  * to set differential gains.
 5817  */
 5818 static void
 5819 iwn_collect_noise(struct iwn_softc *sc,
 5820     const struct iwn_rx_general_stats *stats)
 5821 {
 5822         struct iwn_ops *ops = &sc->ops;
 5823         struct iwn_calib_state *calib = &sc->calib;
 5824         struct ieee80211com *ic = &sc->sc_ic;
 5825         uint32_t val;
 5826         int i;
 5827 
 5828         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
 5829 
 5830         /* Accumulate RSSI and noise for all 3 antennas. */
 5831         for (i = 0; i < 3; i++) {
 5832                 calib->rssi[i] += le32toh(stats->rssi[i]) & 0xff;
 5833                 calib->noise[i] += le32toh(stats->noise[i]) & 0xff;
 5834         }
 5835         /* NB: We update differential gains only once after 20 beacons. */
 5836         if (++calib->nbeacons < 20)
 5837                 return;
 5838 
 5839         /* Determine highest average RSSI. */
 5840         val = MAX(calib->rssi[0], calib->rssi[1]);
 5841         val = MAX(calib->rssi[2], val);
 5842 
 5843         /* Determine which antennas are connected. */
 5844         sc->chainmask = sc->rxchainmask;
 5845         for (i = 0; i < 3; i++)
 5846                 if (val - calib->rssi[i] > 15 * 20)
 5847                         sc->chainmask &= ~(1 << i);
 5848         DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_XMIT,
 5849             "%s: RX chains mask: theoretical=0x%x, actual=0x%x\n",
 5850             __func__, sc->rxchainmask, sc->chainmask);
 5851 
 5852         /* If none of the TX antennas are connected, keep at least one. */
 5853         if ((sc->chainmask & sc->txchainmask) == 0)
 5854                 sc->chainmask |= IWN_LSB(sc->txchainmask);
 5855 
 5856         (void)ops->set_gains(sc);
 5857         calib->state = IWN_CALIB_STATE_RUN;
 5858 
 5859 #ifdef notyet
 5860         /* XXX Disable RX chains with no antennas connected. */
 5861         sc->rxon->rxchain = htole16(IWN_RXCHAIN_SEL(sc->chainmask));
 5862         if (sc->sc_is_scanning)
 5863                 device_printf(sc->sc_dev,
 5864                     "%s: is_scanning set, before RXON\n",
 5865                     __func__);
 5866         (void)iwn_cmd(sc, IWN_CMD_RXON, sc->rxon, sc->rxonsz, 1);
 5867 #endif
 5868 
 5869         /* Enable power-saving mode if requested by user. */
 5870         if (ic->ic_flags & IEEE80211_F_PMGTON)
 5871                 (void)iwn_set_pslevel(sc, 0, 3, 1);
 5872 
 5873         DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
 5874 
 5875 }
 5876 
 5877 static int
 5878 iwn4965_init_gains(struct iwn_softc *sc)
 5879 {
 5880         struct iwn_phy_calib_gain cmd;
 5881 
 5882         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5883 
 5884         memset(&cmd, 0, sizeof cmd);
 5885         cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN;
 5886         /* Differential gains initially set to 0 for all 3 antennas. */
 5887         DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 5888             "%s: setting initial differential gains\n", __func__);
 5889         return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
 5890 }
 5891 
 5892 static int
 5893 iwn5000_init_gains(struct iwn_softc *sc)
 5894 {
 5895         struct iwn_phy_calib cmd;
 5896 
 5897         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5898 
 5899         memset(&cmd, 0, sizeof cmd);
 5900         cmd.code = sc->reset_noise_gain;
 5901         cmd.ngroups = 1;
 5902         cmd.isvalid = 1;
 5903         DPRINTF(sc, IWN_DEBUG_CALIBRATE,
 5904             "%s: setting initial differential gains\n", __func__);
 5905         return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
 5906 }
 5907 
 5908 static int
 5909 iwn4965_set_gains(struct iwn_softc *sc)
 5910 {
 5911         struct iwn_calib_state *calib = &sc->calib;
 5912         struct iwn_phy_calib_gain cmd;
 5913         int i, delta, noise;
 5914 
 5915         DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
 5916 
 5917         /* Get minimal noise among connected antennas. */
 5918         noise = INT_MAX;        /* NB: There's at least one antenna. */
 5919         for (i = 0; i < 3; i++)
 5920                 if (sc->chainmask & (1 << i))
 5921                         noise = MIN(calib->noise[i], noise);
 5922 
 5923         memset(&cmd, 0, sizeof cmd);
 5924         cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN;
 5925         /* Set differential gains for connected antennas. */
 5926         for (i = 0; i < 3; i++) {
 5927                 if (sc->chainmask & (1 << i)) {
 5928                         /* Compute attenuation (in unit of 1.5dB). */
 5929                         delta = (noise - (int32_t)calib->noise[i]) / 30;
 5930                         /* NB: delta <= 0 */
 5931                         /* Limit to [-4.5dB,0]. */
 5932                         cmd.gain[i] = MIN(abs(delta), 3);
 5933                         if (delta < 0)
 5934                                 cmd.gain[i] |= 1 << 2;  /* sign bit */
 5935                 }
 5936         }
 5937         DPRINTF</