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