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