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