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