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