xref: /freebsd/sys/dev/iwn/if_iwn.c (revision 6ae1554a5d9b318f8ad53ccc39fa5a961403da73)
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 
5348 	IEEE80211_LOCK(ic);
5349 	for (aci = 0; aci < WME_NUM_AC; aci++) {
5350 		const struct wmeParams *ac =
5351 		    &ic->ic_wme.wme_chanParams.cap_wmeParams[aci];
5352 		cmd.ac[aci].aifsn = ac->wmep_aifsn;
5353 		cmd.ac[aci].cwmin = htole16(IWN_EXP2(ac->wmep_logcwmin));
5354 		cmd.ac[aci].cwmax = htole16(IWN_EXP2(ac->wmep_logcwmax));
5355 		cmd.ac[aci].txoplimit =
5356 		    htole16(IEEE80211_TXOP_TO_US(ac->wmep_txopLimit));
5357 	}
5358 	IEEE80211_UNLOCK(ic);
5359 
5360 	IWN_LOCK(sc);
5361 	(void)iwn_cmd(sc, IWN_CMD_EDCA_PARAMS, &cmd, sizeof cmd, 1);
5362 	IWN_UNLOCK(sc);
5363 
5364 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
5365 
5366 	return 0;
5367 #undef IWN_EXP2
5368 }
5369 
5370 static void
5371 iwn_update_mcast(struct ieee80211com *ic)
5372 {
5373 	/* Ignore */
5374 }
5375 
5376 static void
5377 iwn_set_led(struct iwn_softc *sc, uint8_t which, uint8_t off, uint8_t on)
5378 {
5379 	struct iwn_cmd_led led;
5380 
5381 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5382 
5383 #if 0
5384 	/* XXX don't set LEDs during scan? */
5385 	if (sc->sc_is_scanning)
5386 		return;
5387 #endif
5388 
5389 	/* Clear microcode LED ownership. */
5390 	IWN_CLRBITS(sc, IWN_LED, IWN_LED_BSM_CTRL);
5391 
5392 	led.which = which;
5393 	led.unit = htole32(10000);	/* on/off in unit of 100ms */
5394 	led.off = off;
5395 	led.on = on;
5396 	(void)iwn_cmd(sc, IWN_CMD_SET_LED, &led, sizeof led, 1);
5397 }
5398 
5399 /*
5400  * Set the critical temperature at which the firmware will stop the radio
5401  * and notify us.
5402  */
5403 static int
5404 iwn_set_critical_temp(struct iwn_softc *sc)
5405 {
5406 	struct iwn_critical_temp crit;
5407 	int32_t temp;
5408 
5409 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5410 
5411 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CTEMP_STOP_RF);
5412 
5413 	if (sc->hw_type == IWN_HW_REV_TYPE_5150)
5414 		temp = (IWN_CTOK(110) - sc->temp_off) * -5;
5415 	else if (sc->hw_type == IWN_HW_REV_TYPE_4965)
5416 		temp = IWN_CTOK(110);
5417 	else
5418 		temp = 110;
5419 	memset(&crit, 0, sizeof crit);
5420 	crit.tempR = htole32(temp);
5421 	DPRINTF(sc, IWN_DEBUG_RESET, "setting critical temp to %d\n", temp);
5422 	return iwn_cmd(sc, IWN_CMD_SET_CRITICAL_TEMP, &crit, sizeof crit, 0);
5423 }
5424 
5425 static int
5426 iwn_set_timing(struct iwn_softc *sc, struct ieee80211_node *ni)
5427 {
5428 	struct iwn_cmd_timing cmd;
5429 	uint64_t val, mod;
5430 
5431 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5432 
5433 	memset(&cmd, 0, sizeof cmd);
5434 	memcpy(&cmd.tstamp, ni->ni_tstamp.data, sizeof (uint64_t));
5435 	cmd.bintval = htole16(ni->ni_intval);
5436 	cmd.lintval = htole16(10);
5437 
5438 	/* Compute remaining time until next beacon. */
5439 	val = (uint64_t)ni->ni_intval * IEEE80211_DUR_TU;
5440 	mod = le64toh(cmd.tstamp) % val;
5441 	cmd.binitval = htole32((uint32_t)(val - mod));
5442 
5443 	DPRINTF(sc, IWN_DEBUG_RESET, "timing bintval=%u tstamp=%ju, init=%u\n",
5444 	    ni->ni_intval, le64toh(cmd.tstamp), (uint32_t)(val - mod));
5445 
5446 	return iwn_cmd(sc, IWN_CMD_TIMING, &cmd, sizeof cmd, 1);
5447 }
5448 
5449 static void
5450 iwn4965_power_calibration(struct iwn_softc *sc, int temp)
5451 {
5452 	struct ieee80211com *ic = &sc->sc_ic;
5453 
5454 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5455 
5456 	/* Adjust TX power if need be (delta >= 3 degC). */
5457 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: temperature %d->%d\n",
5458 	    __func__, sc->temp, temp);
5459 	if (abs(temp - sc->temp) >= 3) {
5460 		/* Record temperature of last calibration. */
5461 		sc->temp = temp;
5462 		(void)iwn4965_set_txpower(sc, ic->ic_bsschan, 1);
5463 	}
5464 }
5465 
5466 /*
5467  * Set TX power for current channel (each rate has its own power settings).
5468  * This function takes into account the regulatory information from EEPROM,
5469  * the current temperature and the current voltage.
5470  */
5471 static int
5472 iwn4965_set_txpower(struct iwn_softc *sc, struct ieee80211_channel *ch,
5473     int async)
5474 {
5475 /* Fixed-point arithmetic division using a n-bit fractional part. */
5476 #define fdivround(a, b, n)	\
5477 	((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
5478 /* Linear interpolation. */
5479 #define interpolate(x, x1, y1, x2, y2, n)	\
5480 	((y1) + fdivround(((int)(x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
5481 
5482 	static const int tdiv[IWN_NATTEN_GROUPS] = { 9, 8, 8, 8, 6 };
5483 	struct iwn_ucode_info *uc = &sc->ucode_info;
5484 	struct iwn4965_cmd_txpower cmd;
5485 	struct iwn4965_eeprom_chan_samples *chans;
5486 	const uint8_t *rf_gain, *dsp_gain;
5487 	int32_t vdiff, tdiff;
5488 	int i, c, grp, maxpwr;
5489 	uint8_t chan;
5490 
5491 	sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
5492 	/* Retrieve current channel from last RXON. */
5493 	chan = sc->rxon->chan;
5494 	DPRINTF(sc, IWN_DEBUG_RESET, "setting TX power for channel %d\n",
5495 	    chan);
5496 
5497 	memset(&cmd, 0, sizeof cmd);
5498 	cmd.band = IEEE80211_IS_CHAN_5GHZ(ch) ? 0 : 1;
5499 	cmd.chan = chan;
5500 
5501 	if (IEEE80211_IS_CHAN_5GHZ(ch)) {
5502 		maxpwr   = sc->maxpwr5GHz;
5503 		rf_gain  = iwn4965_rf_gain_5ghz;
5504 		dsp_gain = iwn4965_dsp_gain_5ghz;
5505 	} else {
5506 		maxpwr   = sc->maxpwr2GHz;
5507 		rf_gain  = iwn4965_rf_gain_2ghz;
5508 		dsp_gain = iwn4965_dsp_gain_2ghz;
5509 	}
5510 
5511 	/* Compute voltage compensation. */
5512 	vdiff = ((int32_t)le32toh(uc->volt) - sc->eeprom_voltage) / 7;
5513 	if (vdiff > 0)
5514 		vdiff *= 2;
5515 	if (abs(vdiff) > 2)
5516 		vdiff = 0;
5517 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5518 	    "%s: voltage compensation=%d (UCODE=%d, EEPROM=%d)\n",
5519 	    __func__, vdiff, le32toh(uc->volt), sc->eeprom_voltage);
5520 
5521 	/* Get channel attenuation group. */
5522 	if (chan <= 20)		/* 1-20 */
5523 		grp = 4;
5524 	else if (chan <= 43)	/* 34-43 */
5525 		grp = 0;
5526 	else if (chan <= 70)	/* 44-70 */
5527 		grp = 1;
5528 	else if (chan <= 124)	/* 71-124 */
5529 		grp = 2;
5530 	else			/* 125-200 */
5531 		grp = 3;
5532 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5533 	    "%s: chan %d, attenuation group=%d\n", __func__, chan, grp);
5534 
5535 	/* Get channel sub-band. */
5536 	for (i = 0; i < IWN_NBANDS; i++)
5537 		if (sc->bands[i].lo != 0 &&
5538 		    sc->bands[i].lo <= chan && chan <= sc->bands[i].hi)
5539 			break;
5540 	if (i == IWN_NBANDS)	/* Can't happen in real-life. */
5541 		return EINVAL;
5542 	chans = sc->bands[i].chans;
5543 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5544 	    "%s: chan %d sub-band=%d\n", __func__, chan, i);
5545 
5546 	for (c = 0; c < 2; c++) {
5547 		uint8_t power, gain, temp;
5548 		int maxchpwr, pwr, ridx, idx;
5549 
5550 		power = interpolate(chan,
5551 		    chans[0].num, chans[0].samples[c][1].power,
5552 		    chans[1].num, chans[1].samples[c][1].power, 1);
5553 		gain  = interpolate(chan,
5554 		    chans[0].num, chans[0].samples[c][1].gain,
5555 		    chans[1].num, chans[1].samples[c][1].gain, 1);
5556 		temp  = interpolate(chan,
5557 		    chans[0].num, chans[0].samples[c][1].temp,
5558 		    chans[1].num, chans[1].samples[c][1].temp, 1);
5559 		DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5560 		    "%s: Tx chain %d: power=%d gain=%d temp=%d\n",
5561 		    __func__, c, power, gain, temp);
5562 
5563 		/* Compute temperature compensation. */
5564 		tdiff = ((sc->temp - temp) * 2) / tdiv[grp];
5565 		DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5566 		    "%s: temperature compensation=%d (current=%d, EEPROM=%d)\n",
5567 		    __func__, tdiff, sc->temp, temp);
5568 
5569 		for (ridx = 0; ridx <= IWN_RIDX_MAX; ridx++) {
5570 			/* Convert dBm to half-dBm. */
5571 			maxchpwr = sc->maxpwr[chan] * 2;
5572 			if ((ridx / 8) & 1)
5573 				maxchpwr -= 6;	/* MIMO 2T: -3dB */
5574 
5575 			pwr = maxpwr;
5576 
5577 			/* Adjust TX power based on rate. */
5578 			if ((ridx % 8) == 5)
5579 				pwr -= 15;	/* OFDM48: -7.5dB */
5580 			else if ((ridx % 8) == 6)
5581 				pwr -= 17;	/* OFDM54: -8.5dB */
5582 			else if ((ridx % 8) == 7)
5583 				pwr -= 20;	/* OFDM60: -10dB */
5584 			else
5585 				pwr -= 10;	/* Others: -5dB */
5586 
5587 			/* Do not exceed channel max TX power. */
5588 			if (pwr > maxchpwr)
5589 				pwr = maxchpwr;
5590 
5591 			idx = gain - (pwr - power) - tdiff - vdiff;
5592 			if ((ridx / 8) & 1)	/* MIMO */
5593 				idx += (int32_t)le32toh(uc->atten[grp][c]);
5594 
5595 			if (cmd.band == 0)
5596 				idx += 9;	/* 5GHz */
5597 			if (ridx == IWN_RIDX_MAX)
5598 				idx += 5;	/* CCK */
5599 
5600 			/* Make sure idx stays in a valid range. */
5601 			if (idx < 0)
5602 				idx = 0;
5603 			else if (idx > IWN4965_MAX_PWR_INDEX)
5604 				idx = IWN4965_MAX_PWR_INDEX;
5605 
5606 			DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5607 			    "%s: Tx chain %d, rate idx %d: power=%d\n",
5608 			    __func__, c, ridx, idx);
5609 			cmd.power[ridx].rf_gain[c] = rf_gain[idx];
5610 			cmd.power[ridx].dsp_gain[c] = dsp_gain[idx];
5611 		}
5612 	}
5613 
5614 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5615 	    "%s: set tx power for chan %d\n", __func__, chan);
5616 	return iwn_cmd(sc, IWN_CMD_TXPOWER, &cmd, sizeof cmd, async);
5617 
5618 #undef interpolate
5619 #undef fdivround
5620 }
5621 
5622 static int
5623 iwn5000_set_txpower(struct iwn_softc *sc, struct ieee80211_channel *ch,
5624     int async)
5625 {
5626 	struct iwn5000_cmd_txpower cmd;
5627 	int cmdid;
5628 
5629 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5630 
5631 	/*
5632 	 * TX power calibration is handled automatically by the firmware
5633 	 * for 5000 Series.
5634 	 */
5635 	memset(&cmd, 0, sizeof cmd);
5636 	cmd.global_limit = 2 * IWN5000_TXPOWER_MAX_DBM;	/* 16 dBm */
5637 	cmd.flags = IWN5000_TXPOWER_NO_CLOSED;
5638 	cmd.srv_limit = IWN5000_TXPOWER_AUTO;
5639 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_XMIT,
5640 	    "%s: setting TX power; rev=%d\n",
5641 	    __func__,
5642 	    IWN_UCODE_API(sc->ucode_rev));
5643 	if (IWN_UCODE_API(sc->ucode_rev) == 1)
5644 		cmdid = IWN_CMD_TXPOWER_DBM_V1;
5645 	else
5646 		cmdid = IWN_CMD_TXPOWER_DBM;
5647 	return iwn_cmd(sc, cmdid, &cmd, sizeof cmd, async);
5648 }
5649 
5650 /*
5651  * Retrieve the maximum RSSI (in dBm) among receivers.
5652  */
5653 static int
5654 iwn4965_get_rssi(struct iwn_softc *sc, struct iwn_rx_stat *stat)
5655 {
5656 	struct iwn4965_rx_phystat *phy = (void *)stat->phybuf;
5657 	uint8_t mask, agc;
5658 	int rssi;
5659 
5660 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5661 
5662 	mask = (le16toh(phy->antenna) >> 4) & IWN_ANT_ABC;
5663 	agc  = (le16toh(phy->agc) >> 7) & 0x7f;
5664 
5665 	rssi = 0;
5666 	if (mask & IWN_ANT_A)
5667 		rssi = MAX(rssi, phy->rssi[0]);
5668 	if (mask & IWN_ANT_B)
5669 		rssi = MAX(rssi, phy->rssi[2]);
5670 	if (mask & IWN_ANT_C)
5671 		rssi = MAX(rssi, phy->rssi[4]);
5672 
5673 	DPRINTF(sc, IWN_DEBUG_RECV,
5674 	    "%s: agc %d mask 0x%x rssi %d %d %d result %d\n", __func__, agc,
5675 	    mask, phy->rssi[0], phy->rssi[2], phy->rssi[4],
5676 	    rssi - agc - IWN_RSSI_TO_DBM);
5677 	return rssi - agc - IWN_RSSI_TO_DBM;
5678 }
5679 
5680 static int
5681 iwn5000_get_rssi(struct iwn_softc *sc, struct iwn_rx_stat *stat)
5682 {
5683 	struct iwn5000_rx_phystat *phy = (void *)stat->phybuf;
5684 	uint8_t agc;
5685 	int rssi;
5686 
5687 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5688 
5689 	agc = (le32toh(phy->agc) >> 9) & 0x7f;
5690 
5691 	rssi = MAX(le16toh(phy->rssi[0]) & 0xff,
5692 		   le16toh(phy->rssi[1]) & 0xff);
5693 	rssi = MAX(le16toh(phy->rssi[2]) & 0xff, rssi);
5694 
5695 	DPRINTF(sc, IWN_DEBUG_RECV,
5696 	    "%s: agc %d rssi %d %d %d result %d\n", __func__, agc,
5697 	    phy->rssi[0], phy->rssi[1], phy->rssi[2],
5698 	    rssi - agc - IWN_RSSI_TO_DBM);
5699 	return rssi - agc - IWN_RSSI_TO_DBM;
5700 }
5701 
5702 /*
5703  * Retrieve the average noise (in dBm) among receivers.
5704  */
5705 static int
5706 iwn_get_noise(const struct iwn_rx_general_stats *stats)
5707 {
5708 	int i, total, nbant, noise;
5709 
5710 	total = nbant = 0;
5711 	for (i = 0; i < 3; i++) {
5712 		if ((noise = le32toh(stats->noise[i]) & 0xff) == 0)
5713 			continue;
5714 		total += noise;
5715 		nbant++;
5716 	}
5717 	/* There should be at least one antenna but check anyway. */
5718 	return (nbant == 0) ? -127 : (total / nbant) - 107;
5719 }
5720 
5721 /*
5722  * Compute temperature (in degC) from last received statistics.
5723  */
5724 static int
5725 iwn4965_get_temperature(struct iwn_softc *sc)
5726 {
5727 	struct iwn_ucode_info *uc = &sc->ucode_info;
5728 	int32_t r1, r2, r3, r4, temp;
5729 
5730 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5731 
5732 	r1 = le32toh(uc->temp[0].chan20MHz);
5733 	r2 = le32toh(uc->temp[1].chan20MHz);
5734 	r3 = le32toh(uc->temp[2].chan20MHz);
5735 	r4 = le32toh(sc->rawtemp);
5736 
5737 	if (r1 == r3)	/* Prevents division by 0 (should not happen). */
5738 		return 0;
5739 
5740 	/* Sign-extend 23-bit R4 value to 32-bit. */
5741 	r4 = ((r4 & 0xffffff) ^ 0x800000) - 0x800000;
5742 	/* Compute temperature in Kelvin. */
5743 	temp = (259 * (r4 - r2)) / (r3 - r1);
5744 	temp = (temp * 97) / 100 + 8;
5745 
5746 	DPRINTF(sc, IWN_DEBUG_ANY, "temperature %dK/%dC\n", temp,
5747 	    IWN_KTOC(temp));
5748 	return IWN_KTOC(temp);
5749 }
5750 
5751 static int
5752 iwn5000_get_temperature(struct iwn_softc *sc)
5753 {
5754 	int32_t temp;
5755 
5756 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5757 
5758 	/*
5759 	 * Temperature is not used by the driver for 5000 Series because
5760 	 * TX power calibration is handled by firmware.
5761 	 */
5762 	temp = le32toh(sc->rawtemp);
5763 	if (sc->hw_type == IWN_HW_REV_TYPE_5150) {
5764 		temp = (temp / -5) + sc->temp_off;
5765 		temp = IWN_KTOC(temp);
5766 	}
5767 	return temp;
5768 }
5769 
5770 /*
5771  * Initialize sensitivity calibration state machine.
5772  */
5773 static int
5774 iwn_init_sensitivity(struct iwn_softc *sc)
5775 {
5776 	struct iwn_ops *ops = &sc->ops;
5777 	struct iwn_calib_state *calib = &sc->calib;
5778 	uint32_t flags;
5779 	int error;
5780 
5781 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5782 
5783 	/* Reset calibration state machine. */
5784 	memset(calib, 0, sizeof (*calib));
5785 	calib->state = IWN_CALIB_STATE_INIT;
5786 	calib->cck_state = IWN_CCK_STATE_HIFA;
5787 	/* Set initial correlation values. */
5788 	calib->ofdm_x1     = sc->limits->min_ofdm_x1;
5789 	calib->ofdm_mrc_x1 = sc->limits->min_ofdm_mrc_x1;
5790 	calib->ofdm_x4     = sc->limits->min_ofdm_x4;
5791 	calib->ofdm_mrc_x4 = sc->limits->min_ofdm_mrc_x4;
5792 	calib->cck_x4      = 125;
5793 	calib->cck_mrc_x4  = sc->limits->min_cck_mrc_x4;
5794 	calib->energy_cck  = sc->limits->energy_cck;
5795 
5796 	/* Write initial sensitivity. */
5797 	if ((error = iwn_send_sensitivity(sc)) != 0)
5798 		return error;
5799 
5800 	/* Write initial gains. */
5801 	if ((error = ops->init_gains(sc)) != 0)
5802 		return error;
5803 
5804 	/* Request statistics at each beacon interval. */
5805 	flags = 0;
5806 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: sending request for statistics\n",
5807 	    __func__);
5808 	return iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags, sizeof flags, 1);
5809 }
5810 
5811 /*
5812  * Collect noise and RSSI statistics for the first 20 beacons received
5813  * after association and use them to determine connected antennas and
5814  * to set differential gains.
5815  */
5816 static void
5817 iwn_collect_noise(struct iwn_softc *sc,
5818     const struct iwn_rx_general_stats *stats)
5819 {
5820 	struct iwn_ops *ops = &sc->ops;
5821 	struct iwn_calib_state *calib = &sc->calib;
5822 	struct ieee80211com *ic = &sc->sc_ic;
5823 	uint32_t val;
5824 	int i;
5825 
5826 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
5827 
5828 	/* Accumulate RSSI and noise for all 3 antennas. */
5829 	for (i = 0; i < 3; i++) {
5830 		calib->rssi[i] += le32toh(stats->rssi[i]) & 0xff;
5831 		calib->noise[i] += le32toh(stats->noise[i]) & 0xff;
5832 	}
5833 	/* NB: We update differential gains only once after 20 beacons. */
5834 	if (++calib->nbeacons < 20)
5835 		return;
5836 
5837 	/* Determine highest average RSSI. */
5838 	val = MAX(calib->rssi[0], calib->rssi[1]);
5839 	val = MAX(calib->rssi[2], val);
5840 
5841 	/* Determine which antennas are connected. */
5842 	sc->chainmask = sc->rxchainmask;
5843 	for (i = 0; i < 3; i++)
5844 		if (val - calib->rssi[i] > 15 * 20)
5845 			sc->chainmask &= ~(1 << i);
5846 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_XMIT,
5847 	    "%s: RX chains mask: theoretical=0x%x, actual=0x%x\n",
5848 	    __func__, sc->rxchainmask, sc->chainmask);
5849 
5850 	/* If none of the TX antennas are connected, keep at least one. */
5851 	if ((sc->chainmask & sc->txchainmask) == 0)
5852 		sc->chainmask |= IWN_LSB(sc->txchainmask);
5853 
5854 	(void)ops->set_gains(sc);
5855 	calib->state = IWN_CALIB_STATE_RUN;
5856 
5857 #ifdef notyet
5858 	/* XXX Disable RX chains with no antennas connected. */
5859 	sc->rxon->rxchain = htole16(IWN_RXCHAIN_SEL(sc->chainmask));
5860 	if (sc->sc_is_scanning)
5861 		device_printf(sc->sc_dev,
5862 		    "%s: is_scanning set, before RXON\n",
5863 		    __func__);
5864 	(void)iwn_cmd(sc, IWN_CMD_RXON, sc->rxon, sc->rxonsz, 1);
5865 #endif
5866 
5867 	/* Enable power-saving mode if requested by user. */
5868 	if (ic->ic_flags & IEEE80211_F_PMGTON)
5869 		(void)iwn_set_pslevel(sc, 0, 3, 1);
5870 
5871 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
5872 
5873 }
5874 
5875 static int
5876 iwn4965_init_gains(struct iwn_softc *sc)
5877 {
5878 	struct iwn_phy_calib_gain cmd;
5879 
5880 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5881 
5882 	memset(&cmd, 0, sizeof cmd);
5883 	cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN;
5884 	/* Differential gains initially set to 0 for all 3 antennas. */
5885 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
5886 	    "%s: setting initial differential gains\n", __func__);
5887 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
5888 }
5889 
5890 static int
5891 iwn5000_init_gains(struct iwn_softc *sc)
5892 {
5893 	struct iwn_phy_calib cmd;
5894 
5895 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5896 
5897 	memset(&cmd, 0, sizeof cmd);
5898 	cmd.code = sc->reset_noise_gain;
5899 	cmd.ngroups = 1;
5900 	cmd.isvalid = 1;
5901 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
5902 	    "%s: setting initial differential gains\n", __func__);
5903 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
5904 }
5905 
5906 static int
5907 iwn4965_set_gains(struct iwn_softc *sc)
5908 {
5909 	struct iwn_calib_state *calib = &sc->calib;
5910 	struct iwn_phy_calib_gain cmd;
5911 	int i, delta, noise;
5912 
5913 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5914 
5915 	/* Get minimal noise among connected antennas. */
5916 	noise = INT_MAX;	/* NB: There's at least one antenna. */
5917 	for (i = 0; i < 3; i++)
5918 		if (sc->chainmask & (1 << i))
5919 			noise = MIN(calib->noise[i], noise);
5920 
5921 	memset(&cmd, 0, sizeof cmd);
5922 	cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN;
5923 	/* Set differential gains for connected antennas. */
5924 	for (i = 0; i < 3; i++) {
5925 		if (sc->chainmask & (1 << i)) {
5926 			/* Compute attenuation (in unit of 1.5dB). */
5927 			delta = (noise - (int32_t)calib->noise[i]) / 30;
5928 			/* NB: delta <= 0 */
5929 			/* Limit to [-4.5dB,0]. */
5930 			cmd.gain[i] = MIN(abs(delta), 3);
5931 			if (delta < 0)
5932 				cmd.gain[i] |= 1 << 2;	/* sign bit */
5933 		}
5934 	}
5935 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
5936 	    "setting differential gains Ant A/B/C: %x/%x/%x (%x)\n",
5937 	    cmd.gain[0], cmd.gain[1], cmd.gain[2], sc->chainmask);
5938 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
5939 }
5940 
5941 static int
5942 iwn5000_set_gains(struct iwn_softc *sc)
5943 {
5944 	struct iwn_calib_state *calib = &sc->calib;
5945 	struct iwn_phy_calib_gain cmd;
5946 	int i, ant, div, delta;
5947 
5948 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5949 
5950 	/* We collected 20 beacons and !=6050 need a 1.5 factor. */
5951 	div = (sc->hw_type == IWN_HW_REV_TYPE_6050) ? 20 : 30;
5952 
5953 	memset(&cmd, 0, sizeof cmd);
5954 	cmd.code = sc->noise_gain;
5955 	cmd.ngroups = 1;
5956 	cmd.isvalid = 1;
5957 	/* Get first available RX antenna as referential. */
5958 	ant = IWN_LSB(sc->rxchainmask);
5959 	/* Set differential gains for other antennas. */
5960 	for (i = ant + 1; i < 3; i++) {
5961 		if (sc->chainmask & (1 << i)) {
5962 			/* The delta is relative to antenna "ant". */
5963 			delta = ((int32_t)calib->noise[ant] -
5964 			    (int32_t)calib->noise[i]) / div;
5965 			/* Limit to [-4.5dB,+4.5dB]. */
5966 			cmd.gain[i - 1] = MIN(abs(delta), 3);
5967 			if (delta < 0)
5968 				cmd.gain[i - 1] |= 1 << 2;	/* sign bit */
5969 		}
5970 	}
5971 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_XMIT,
5972 	    "setting differential gains Ant B/C: %x/%x (%x)\n",
5973 	    cmd.gain[0], cmd.gain[1], sc->chainmask);
5974 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
5975 }
5976 
5977 /*
5978  * Tune RF RX sensitivity based on the number of false alarms detected
5979  * during the last beacon period.
5980  */
5981 static void
5982 iwn_tune_sensitivity(struct iwn_softc *sc, const struct iwn_rx_stats *stats)
5983 {
5984 #define inc(val, inc, max)			\
5985 	if ((val) < (max)) {			\
5986 		if ((val) < (max) - (inc))	\
5987 			(val) += (inc);		\
5988 		else				\
5989 			(val) = (max);		\
5990 		needs_update = 1;		\
5991 	}
5992 #define dec(val, dec, min)			\
5993 	if ((val) > (min)) {			\
5994 		if ((val) > (min) + (dec))	\
5995 			(val) -= (dec);		\
5996 		else				\
5997 			(val) = (min);		\
5998 		needs_update = 1;		\
5999 	}
6000 
6001 	const struct iwn_sensitivity_limits *limits = sc->limits;
6002 	struct iwn_calib_state *calib = &sc->calib;
6003 	uint32_t val, rxena, fa;
6004 	uint32_t energy[3], energy_min;
6005 	uint8_t noise[3], noise_ref;
6006 	int i, needs_update = 0;
6007 
6008 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
6009 
6010 	/* Check that we've been enabled long enough. */
6011 	if ((rxena = le32toh(stats->general.load)) == 0){
6012 		DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end not so long\n", __func__);
6013 		return;
6014 	}
6015 
6016 	/* Compute number of false alarms since last call for OFDM. */
6017 	fa  = le32toh(stats->ofdm.bad_plcp) - calib->bad_plcp_ofdm;
6018 	fa += le32toh(stats->ofdm.fa) - calib->fa_ofdm;
6019 	fa *= 200 * IEEE80211_DUR_TU;	/* 200TU */
6020 
6021 	if (fa > 50 * rxena) {
6022 		/* High false alarm count, decrease sensitivity. */
6023 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
6024 		    "%s: OFDM high false alarm count: %u\n", __func__, fa);
6025 		inc(calib->ofdm_x1,     1, limits->max_ofdm_x1);
6026 		inc(calib->ofdm_mrc_x1, 1, limits->max_ofdm_mrc_x1);
6027 		inc(calib->ofdm_x4,     1, limits->max_ofdm_x4);
6028 		inc(calib->ofdm_mrc_x4, 1, limits->max_ofdm_mrc_x4);
6029 
6030 	} else if (fa < 5 * rxena) {
6031 		/* Low false alarm count, increase sensitivity. */
6032 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
6033 		    "%s: OFDM low false alarm count: %u\n", __func__, fa);
6034 		dec(calib->ofdm_x1,     1, limits->min_ofdm_x1);
6035 		dec(calib->ofdm_mrc_x1, 1, limits->min_ofdm_mrc_x1);
6036 		dec(calib->ofdm_x4,     1, limits->min_ofdm_x4);
6037 		dec(calib->ofdm_mrc_x4, 1, limits->min_ofdm_mrc_x4);
6038 	}
6039 
6040 	/* Compute maximum noise among 3 receivers. */
6041 	for (i = 0; i < 3; i++)
6042 		noise[i] = (le32toh(stats->general.noise[i]) >> 8) & 0xff;
6043 	val = MAX(noise[0], noise[1]);
6044 	val = MAX(noise[2], val);
6045 	/* Insert it into our samples table. */
6046 	calib->noise_samples[calib->cur_noise_sample] = val;
6047 	calib->cur_noise_sample = (calib->cur_noise_sample + 1) % 20;
6048 
6049 	/* Compute maximum noise among last 20 samples. */
6050 	noise_ref = calib->noise_samples[0];
6051 	for (i = 1; i < 20; i++)
6052 		noise_ref = MAX(noise_ref, calib->noise_samples[i]);
6053 
6054 	/* Compute maximum energy among 3 receivers. */
6055 	for (i = 0; i < 3; i++)
6056 		energy[i] = le32toh(stats->general.energy[i]);
6057 	val = MIN(energy[0], energy[1]);
6058 	val = MIN(energy[2], val);
6059 	/* Insert it into our samples table. */
6060 	calib->energy_samples[calib->cur_energy_sample] = val;
6061 	calib->cur_energy_sample = (calib->cur_energy_sample + 1) % 10;
6062 
6063 	/* Compute minimum energy among last 10 samples. */
6064 	energy_min = calib->energy_samples[0];
6065 	for (i = 1; i < 10; i++)
6066 		energy_min = MAX(energy_min, calib->energy_samples[i]);
6067 	energy_min += 6;
6068 
6069 	/* Compute number of false alarms since last call for CCK. */
6070 	fa  = le32toh(stats->cck.bad_plcp) - calib->bad_plcp_cck;
6071 	fa += le32toh(stats->cck.fa) - calib->fa_cck;
6072 	fa *= 200 * IEEE80211_DUR_TU;	/* 200TU */
6073 
6074 	if (fa > 50 * rxena) {
6075 		/* High false alarm count, decrease sensitivity. */
6076 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
6077 		    "%s: CCK high false alarm count: %u\n", __func__, fa);
6078 		calib->cck_state = IWN_CCK_STATE_HIFA;
6079 		calib->low_fa = 0;
6080 
6081 		if (calib->cck_x4 > 160) {
6082 			calib->noise_ref = noise_ref;
6083 			if (calib->energy_cck > 2)
6084 				dec(calib->energy_cck, 2, energy_min);
6085 		}
6086 		if (calib->cck_x4 < 160) {
6087 			calib->cck_x4 = 161;
6088 			needs_update = 1;
6089 		} else
6090 			inc(calib->cck_x4, 3, limits->max_cck_x4);
6091 
6092 		inc(calib->cck_mrc_x4, 3, limits->max_cck_mrc_x4);
6093 
6094 	} else if (fa < 5 * rxena) {
6095 		/* Low false alarm count, increase sensitivity. */
6096 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
6097 		    "%s: CCK low false alarm count: %u\n", __func__, fa);
6098 		calib->cck_state = IWN_CCK_STATE_LOFA;
6099 		calib->low_fa++;
6100 
6101 		if (calib->cck_state != IWN_CCK_STATE_INIT &&
6102 		    (((int32_t)calib->noise_ref - (int32_t)noise_ref) > 2 ||
6103 		     calib->low_fa > 100)) {
6104 			inc(calib->energy_cck, 2, limits->min_energy_cck);
6105 			dec(calib->cck_x4,     3, limits->min_cck_x4);
6106 			dec(calib->cck_mrc_x4, 3, limits->min_cck_mrc_x4);
6107 		}
6108 	} else {
6109 		/* Not worth to increase or decrease sensitivity. */
6110 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
6111 		    "%s: CCK normal false alarm count: %u\n", __func__, fa);
6112 		calib->low_fa = 0;
6113 		calib->noise_ref = noise_ref;
6114 
6115 		if (calib->cck_state == IWN_CCK_STATE_HIFA) {
6116 			/* Previous interval had many false alarms. */
6117 			dec(calib->energy_cck, 8, energy_min);
6118 		}
6119 		calib->cck_state = IWN_CCK_STATE_INIT;
6120 	}
6121 
6122 	if (needs_update)
6123 		(void)iwn_send_sensitivity(sc);
6124 
6125 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
6126 
6127 #undef dec
6128 #undef inc
6129 }
6130 
6131 static int
6132 iwn_send_sensitivity(struct iwn_softc *sc)
6133 {
6134 	struct iwn_calib_state *calib = &sc->calib;
6135 	struct iwn_enhanced_sensitivity_cmd cmd;
6136 	int len;
6137 
6138 	memset(&cmd, 0, sizeof cmd);
6139 	len = sizeof (struct iwn_sensitivity_cmd);
6140 	cmd.which = IWN_SENSITIVITY_WORKTBL;
6141 	/* OFDM modulation. */
6142 	cmd.corr_ofdm_x1       = htole16(calib->ofdm_x1);
6143 	cmd.corr_ofdm_mrc_x1   = htole16(calib->ofdm_mrc_x1);
6144 	cmd.corr_ofdm_x4       = htole16(calib->ofdm_x4);
6145 	cmd.corr_ofdm_mrc_x4   = htole16(calib->ofdm_mrc_x4);
6146 	cmd.energy_ofdm        = htole16(sc->limits->energy_ofdm);
6147 	cmd.energy_ofdm_th     = htole16(62);
6148 	/* CCK modulation. */
6149 	cmd.corr_cck_x4        = htole16(calib->cck_x4);
6150 	cmd.corr_cck_mrc_x4    = htole16(calib->cck_mrc_x4);
6151 	cmd.energy_cck         = htole16(calib->energy_cck);
6152 	/* Barker modulation: use default values. */
6153 	cmd.corr_barker        = htole16(190);
6154 	cmd.corr_barker_mrc    = htole16(sc->limits->barker_mrc);
6155 
6156 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
6157 	    "%s: set sensitivity %d/%d/%d/%d/%d/%d/%d\n", __func__,
6158 	    calib->ofdm_x1, calib->ofdm_mrc_x1, calib->ofdm_x4,
6159 	    calib->ofdm_mrc_x4, calib->cck_x4,
6160 	    calib->cck_mrc_x4, calib->energy_cck);
6161 
6162 	if (!(sc->sc_flags & IWN_FLAG_ENH_SENS))
6163 		goto send;
6164 	/* Enhanced sensitivity settings. */
6165 	len = sizeof (struct iwn_enhanced_sensitivity_cmd);
6166 	cmd.ofdm_det_slope_mrc = htole16(668);
6167 	cmd.ofdm_det_icept_mrc = htole16(4);
6168 	cmd.ofdm_det_slope     = htole16(486);
6169 	cmd.ofdm_det_icept     = htole16(37);
6170 	cmd.cck_det_slope_mrc  = htole16(853);
6171 	cmd.cck_det_icept_mrc  = htole16(4);
6172 	cmd.cck_det_slope      = htole16(476);
6173 	cmd.cck_det_icept      = htole16(99);
6174 send:
6175 	return iwn_cmd(sc, IWN_CMD_SET_SENSITIVITY, &cmd, len, 1);
6176 }
6177 
6178 /*
6179  * Look at the increase of PLCP errors over time; if it exceeds
6180  * a programmed threshold then trigger an RF retune.
6181  */
6182 static void
6183 iwn_check_rx_recovery(struct iwn_softc *sc, struct iwn_stats *rs)
6184 {
6185 	int32_t delta_ofdm, delta_ht, delta_cck;
6186 	struct iwn_calib_state *calib = &sc->calib;
6187 	int delta_ticks, cur_ticks;
6188 	int delta_msec;
6189 	int thresh;
6190 
6191 	/*
6192 	 * Calculate the difference between the current and
6193 	 * previous statistics.
6194 	 */
6195 	delta_cck = le32toh(rs->rx.cck.bad_plcp) - calib->bad_plcp_cck;
6196 	delta_ofdm = le32toh(rs->rx.ofdm.bad_plcp) - calib->bad_plcp_ofdm;
6197 	delta_ht = le32toh(rs->rx.ht.bad_plcp) - calib->bad_plcp_ht;
6198 
6199 	/*
6200 	 * Calculate the delta in time between successive statistics
6201 	 * messages.  Yes, it can roll over; so we make sure that
6202 	 * this doesn't happen.
6203 	 *
6204 	 * XXX go figure out what to do about rollover
6205 	 * XXX go figure out what to do if ticks rolls over to -ve instead!
6206 	 * XXX go stab signed integer overflow undefined-ness in the face.
6207 	 */
6208 	cur_ticks = ticks;
6209 	delta_ticks = cur_ticks - sc->last_calib_ticks;
6210 
6211 	/*
6212 	 * If any are negative, then the firmware likely reset; so just
6213 	 * bail.  We'll pick this up next time.
6214 	 */
6215 	if (delta_cck < 0 || delta_ofdm < 0 || delta_ht < 0 || delta_ticks < 0)
6216 		return;
6217 
6218 	/*
6219 	 * delta_ticks is in ticks; we need to convert it up to milliseconds
6220 	 * so we can do some useful math with it.
6221 	 */
6222 	delta_msec = ticks_to_msecs(delta_ticks);
6223 
6224 	/*
6225 	 * Calculate what our threshold is given the current delta_msec.
6226 	 */
6227 	thresh = sc->base_params->plcp_err_threshold * delta_msec;
6228 
6229 	DPRINTF(sc, IWN_DEBUG_STATE,
6230 	    "%s: time delta: %d; cck=%d, ofdm=%d, ht=%d, total=%d, thresh=%d\n",
6231 	    __func__,
6232 	    delta_msec,
6233 	    delta_cck,
6234 	    delta_ofdm,
6235 	    delta_ht,
6236 	    (delta_msec + delta_cck + delta_ofdm + delta_ht),
6237 	    thresh);
6238 
6239 	/*
6240 	 * If we need a retune, then schedule a single channel scan
6241 	 * to a channel that isn't the currently active one!
6242 	 *
6243 	 * The math from linux iwlwifi:
6244 	 *
6245 	 * if ((delta * 100 / msecs) > threshold)
6246 	 */
6247 	if (thresh > 0 && (delta_cck + delta_ofdm + delta_ht) * 100 > thresh) {
6248 		DPRINTF(sc, IWN_DEBUG_ANY,
6249 		    "%s: PLCP error threshold raw (%d) comparison (%d) "
6250 		    "over limit (%d); retune!\n",
6251 		    __func__,
6252 		    (delta_cck + delta_ofdm + delta_ht),
6253 		    (delta_cck + delta_ofdm + delta_ht) * 100,
6254 		    thresh);
6255 	}
6256 }
6257 
6258 /*
6259  * Set STA mode power saving level (between 0 and 5).
6260  * Level 0 is CAM (Continuously Aware Mode), 5 is for maximum power saving.
6261  */
6262 static int
6263 iwn_set_pslevel(struct iwn_softc *sc, int dtim, int level, int async)
6264 {
6265 	struct iwn_pmgt_cmd cmd;
6266 	const struct iwn_pmgt *pmgt;
6267 	uint32_t max, skip_dtim;
6268 	uint32_t reg;
6269 	int i;
6270 
6271 	DPRINTF(sc, IWN_DEBUG_PWRSAVE,
6272 	    "%s: dtim=%d, level=%d, async=%d\n",
6273 	    __func__,
6274 	    dtim,
6275 	    level,
6276 	    async);
6277 
6278 	/* Select which PS parameters to use. */
6279 	if (dtim <= 2)
6280 		pmgt = &iwn_pmgt[0][level];
6281 	else if (dtim <= 10)
6282 		pmgt = &iwn_pmgt[1][level];
6283 	else
6284 		pmgt = &iwn_pmgt[2][level];
6285 
6286 	memset(&cmd, 0, sizeof cmd);
6287 	if (level != 0)	/* not CAM */
6288 		cmd.flags |= htole16(IWN_PS_ALLOW_SLEEP);
6289 	if (level == 5)
6290 		cmd.flags |= htole16(IWN_PS_FAST_PD);
6291 	/* Retrieve PCIe Active State Power Management (ASPM). */
6292 	reg = pci_read_config(sc->sc_dev, sc->sc_cap_off + 0x10, 1);
6293 	if (!(reg & 0x1))	/* L0s Entry disabled. */
6294 		cmd.flags |= htole16(IWN_PS_PCI_PMGT);
6295 	cmd.rxtimeout = htole32(pmgt->rxtimeout * 1024);
6296 	cmd.txtimeout = htole32(pmgt->txtimeout * 1024);
6297 
6298 	if (dtim == 0) {
6299 		dtim = 1;
6300 		skip_dtim = 0;
6301 	} else
6302 		skip_dtim = pmgt->skip_dtim;
6303 	if (skip_dtim != 0) {
6304 		cmd.flags |= htole16(IWN_PS_SLEEP_OVER_DTIM);
6305 		max = pmgt->intval[4];
6306 		if (max == (uint32_t)-1)
6307 			max = dtim * (skip_dtim + 1);
6308 		else if (max > dtim)
6309 			max = (max / dtim) * dtim;
6310 	} else
6311 		max = dtim;
6312 	for (i = 0; i < 5; i++)
6313 		cmd.intval[i] = htole32(MIN(max, pmgt->intval[i]));
6314 
6315 	DPRINTF(sc, IWN_DEBUG_RESET, "setting power saving level to %d\n",
6316 	    level);
6317 	return iwn_cmd(sc, IWN_CMD_SET_POWER_MODE, &cmd, sizeof cmd, async);
6318 }
6319 
6320 static int
6321 iwn_send_btcoex(struct iwn_softc *sc)
6322 {
6323 	struct iwn_bluetooth cmd;
6324 
6325 	memset(&cmd, 0, sizeof cmd);
6326 	cmd.flags = IWN_BT_COEX_CHAN_ANN | IWN_BT_COEX_BT_PRIO;
6327 	cmd.lead_time = IWN_BT_LEAD_TIME_DEF;
6328 	cmd.max_kill = IWN_BT_MAX_KILL_DEF;
6329 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: configuring bluetooth coexistence\n",
6330 	    __func__);
6331 	return iwn_cmd(sc, IWN_CMD_BT_COEX, &cmd, sizeof(cmd), 0);
6332 }
6333 
6334 static int
6335 iwn_send_advanced_btcoex(struct iwn_softc *sc)
6336 {
6337 	static const uint32_t btcoex_3wire[12] = {
6338 		0xaaaaaaaa, 0xaaaaaaaa, 0xaeaaaaaa, 0xaaaaaaaa,
6339 		0xcc00ff28, 0x0000aaaa, 0xcc00aaaa, 0x0000aaaa,
6340 		0xc0004000, 0x00004000, 0xf0005000, 0xf0005000,
6341 	};
6342 	struct iwn6000_btcoex_config btconfig;
6343 	struct iwn2000_btcoex_config btconfig2k;
6344 	struct iwn_btcoex_priotable btprio;
6345 	struct iwn_btcoex_prot btprot;
6346 	int error, i;
6347 	uint8_t flags;
6348 
6349 	memset(&btconfig, 0, sizeof btconfig);
6350 	memset(&btconfig2k, 0, sizeof btconfig2k);
6351 
6352 	flags = IWN_BT_FLAG_COEX6000_MODE_3W <<
6353 	    IWN_BT_FLAG_COEX6000_MODE_SHIFT; // Done as is in linux kernel 3.2
6354 
6355 	if (sc->base_params->bt_sco_disable)
6356 		flags &= ~IWN_BT_FLAG_SYNC_2_BT_DISABLE;
6357 	else
6358 		flags |= IWN_BT_FLAG_SYNC_2_BT_DISABLE;
6359 
6360 	flags |= IWN_BT_FLAG_COEX6000_CHAN_INHIBITION;
6361 
6362 	/* Default flags result is 145 as old value */
6363 
6364 	/*
6365 	 * Flags value has to be review. Values must change if we
6366 	 * which to disable it
6367 	 */
6368 	if (sc->base_params->bt_session_2) {
6369 		btconfig2k.flags = flags;
6370 		btconfig2k.max_kill = 5;
6371 		btconfig2k.bt3_t7_timer = 1;
6372 		btconfig2k.kill_ack = htole32(0xffff0000);
6373 		btconfig2k.kill_cts = htole32(0xffff0000);
6374 		btconfig2k.sample_time = 2;
6375 		btconfig2k.bt3_t2_timer = 0xc;
6376 
6377 		for (i = 0; i < 12; i++)
6378 			btconfig2k.lookup_table[i] = htole32(btcoex_3wire[i]);
6379 		btconfig2k.valid = htole16(0xff);
6380 		btconfig2k.prio_boost = htole32(0xf0);
6381 		DPRINTF(sc, IWN_DEBUG_RESET,
6382 		    "%s: configuring advanced bluetooth coexistence"
6383 		    " session 2, flags : 0x%x\n",
6384 		    __func__,
6385 		    flags);
6386 		error = iwn_cmd(sc, IWN_CMD_BT_COEX, &btconfig2k,
6387 		    sizeof(btconfig2k), 1);
6388 	} else {
6389 		btconfig.flags = flags;
6390 		btconfig.max_kill = 5;
6391 		btconfig.bt3_t7_timer = 1;
6392 		btconfig.kill_ack = htole32(0xffff0000);
6393 		btconfig.kill_cts = htole32(0xffff0000);
6394 		btconfig.sample_time = 2;
6395 		btconfig.bt3_t2_timer = 0xc;
6396 
6397 		for (i = 0; i < 12; i++)
6398 			btconfig.lookup_table[i] = htole32(btcoex_3wire[i]);
6399 		btconfig.valid = htole16(0xff);
6400 		btconfig.prio_boost = 0xf0;
6401 		DPRINTF(sc, IWN_DEBUG_RESET,
6402 		    "%s: configuring advanced bluetooth coexistence,"
6403 		    " flags : 0x%x\n",
6404 		    __func__,
6405 		    flags);
6406 		error = iwn_cmd(sc, IWN_CMD_BT_COEX, &btconfig,
6407 		    sizeof(btconfig), 1);
6408 	}
6409 
6410 	if (error != 0)
6411 		return error;
6412 
6413 	memset(&btprio, 0, sizeof btprio);
6414 	btprio.calib_init1 = 0x6;
6415 	btprio.calib_init2 = 0x7;
6416 	btprio.calib_periodic_low1 = 0x2;
6417 	btprio.calib_periodic_low2 = 0x3;
6418 	btprio.calib_periodic_high1 = 0x4;
6419 	btprio.calib_periodic_high2 = 0x5;
6420 	btprio.dtim = 0x6;
6421 	btprio.scan52 = 0x8;
6422 	btprio.scan24 = 0xa;
6423 	error = iwn_cmd(sc, IWN_CMD_BT_COEX_PRIOTABLE, &btprio, sizeof(btprio),
6424 	    1);
6425 	if (error != 0)
6426 		return error;
6427 
6428 	/* Force BT state machine change. */
6429 	memset(&btprot, 0, sizeof btprot);
6430 	btprot.open = 1;
6431 	btprot.type = 1;
6432 	error = iwn_cmd(sc, IWN_CMD_BT_COEX_PROT, &btprot, sizeof(btprot), 1);
6433 	if (error != 0)
6434 		return error;
6435 	btprot.open = 0;
6436 	return iwn_cmd(sc, IWN_CMD_BT_COEX_PROT, &btprot, sizeof(btprot), 1);
6437 }
6438 
6439 static int
6440 iwn5000_runtime_calib(struct iwn_softc *sc)
6441 {
6442 	struct iwn5000_calib_config cmd;
6443 
6444 	memset(&cmd, 0, sizeof cmd);
6445 	cmd.ucode.once.enable = 0xffffffff;
6446 	cmd.ucode.once.start = IWN5000_CALIB_DC;
6447 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
6448 	    "%s: configuring runtime calibration\n", __func__);
6449 	return iwn_cmd(sc, IWN5000_CMD_CALIB_CONFIG, &cmd, sizeof(cmd), 0);
6450 }
6451 
6452 static uint32_t
6453 iwn_get_rxon_ht_flags(struct iwn_softc *sc, struct ieee80211_channel *c)
6454 {
6455 	struct ieee80211com *ic = &sc->sc_ic;
6456 	uint32_t htflags = 0;
6457 
6458 	if (! IEEE80211_IS_CHAN_HT(c))
6459 		return (0);
6460 
6461 	htflags |= IWN_RXON_HT_PROTMODE(ic->ic_curhtprotmode);
6462 
6463 	if (IEEE80211_IS_CHAN_HT40(c)) {
6464 		switch (ic->ic_curhtprotmode) {
6465 		case IEEE80211_HTINFO_OPMODE_HT20PR:
6466 			htflags |= IWN_RXON_HT_MODEPURE40;
6467 			break;
6468 		default:
6469 			htflags |= IWN_RXON_HT_MODEMIXED;
6470 			break;
6471 		}
6472 	}
6473 	if (IEEE80211_IS_CHAN_HT40D(c))
6474 		htflags |= IWN_RXON_HT_HT40MINUS;
6475 
6476 	return (htflags);
6477 }
6478 
6479 static int
6480 iwn_config(struct iwn_softc *sc)
6481 {
6482 	struct iwn_ops *ops = &sc->ops;
6483 	struct ieee80211com *ic = &sc->sc_ic;
6484 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
6485 	const uint8_t *macaddr;
6486 	uint32_t txmask;
6487 	uint16_t rxchain;
6488 	int error;
6489 
6490 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
6491 
6492 	if ((sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSET)
6493 	    && (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSETv2)) {
6494 		device_printf(sc->sc_dev,"%s: temp_offset and temp_offsetv2 are"
6495 		    " exclusive each together. Review NIC config file. Conf"
6496 		    " :  0x%08x Flags :  0x%08x  \n", __func__,
6497 		    sc->base_params->calib_need,
6498 		    (IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSET |
6499 		    IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSETv2));
6500 		return (EINVAL);
6501 	}
6502 
6503 	/* Compute temperature calib if needed. Will be send by send calib */
6504 	if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSET) {
6505 		error = iwn5000_temp_offset_calib(sc);
6506 		if (error != 0) {
6507 			device_printf(sc->sc_dev,
6508 			    "%s: could not set temperature offset\n", __func__);
6509 			return (error);
6510 		}
6511 	} else if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSETv2) {
6512 		error = iwn5000_temp_offset_calibv2(sc);
6513 		if (error != 0) {
6514 			device_printf(sc->sc_dev,
6515 			    "%s: could not compute temperature offset v2\n",
6516 			    __func__);
6517 			return (error);
6518 		}
6519 	}
6520 
6521 	if (sc->hw_type == IWN_HW_REV_TYPE_6050) {
6522 		/* Configure runtime DC calibration. */
6523 		error = iwn5000_runtime_calib(sc);
6524 		if (error != 0) {
6525 			device_printf(sc->sc_dev,
6526 			    "%s: could not configure runtime calibration\n",
6527 			    __func__);
6528 			return error;
6529 		}
6530 	}
6531 
6532 	/* Configure valid TX chains for >=5000 Series. */
6533 	if (sc->hw_type != IWN_HW_REV_TYPE_4965 &&
6534 	    IWN_UCODE_API(sc->ucode_rev) > 1) {
6535 		txmask = htole32(sc->txchainmask);
6536 		DPRINTF(sc, IWN_DEBUG_RESET | IWN_DEBUG_XMIT,
6537 		    "%s: configuring valid TX chains 0x%x\n", __func__, txmask);
6538 		error = iwn_cmd(sc, IWN5000_CMD_TX_ANT_CONFIG, &txmask,
6539 		    sizeof txmask, 0);
6540 		if (error != 0) {
6541 			device_printf(sc->sc_dev,
6542 			    "%s: could not configure valid TX chains, "
6543 			    "error %d\n", __func__, error);
6544 			return error;
6545 		}
6546 	}
6547 
6548 	/* Configure bluetooth coexistence. */
6549 	error = 0;
6550 
6551 	/* Configure bluetooth coexistence if needed. */
6552 	if (sc->base_params->bt_mode == IWN_BT_ADVANCED)
6553 		error = iwn_send_advanced_btcoex(sc);
6554 	if (sc->base_params->bt_mode == IWN_BT_SIMPLE)
6555 		error = iwn_send_btcoex(sc);
6556 
6557 	if (error != 0) {
6558 		device_printf(sc->sc_dev,
6559 		    "%s: could not configure bluetooth coexistence, error %d\n",
6560 		    __func__, error);
6561 		return error;
6562 	}
6563 
6564 	/* Set mode, channel, RX filter and enable RX. */
6565 	sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
6566 	memset(sc->rxon, 0, sizeof (struct iwn_rxon));
6567 	macaddr = vap ? vap->iv_myaddr : ic->ic_macaddr;
6568 	IEEE80211_ADDR_COPY(sc->rxon->myaddr, macaddr);
6569 	IEEE80211_ADDR_COPY(sc->rxon->wlap, macaddr);
6570 	sc->rxon->chan = ieee80211_chan2ieee(ic, ic->ic_curchan);
6571 	sc->rxon->flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
6572 	if (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
6573 		sc->rxon->flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
6574 	switch (ic->ic_opmode) {
6575 	case IEEE80211_M_STA:
6576 		sc->rxon->mode = IWN_MODE_STA;
6577 		sc->rxon->filter = htole32(IWN_FILTER_MULTICAST);
6578 		break;
6579 	case IEEE80211_M_MONITOR:
6580 		sc->rxon->mode = IWN_MODE_MONITOR;
6581 		sc->rxon->filter = htole32(IWN_FILTER_MULTICAST |
6582 		    IWN_FILTER_CTL | IWN_FILTER_PROMISC);
6583 		break;
6584 	default:
6585 		/* Should not get there. */
6586 		break;
6587 	}
6588 	sc->rxon->cck_mask  = 0x0f;	/* not yet negotiated */
6589 	sc->rxon->ofdm_mask = 0xff;	/* not yet negotiated */
6590 	sc->rxon->ht_single_mask = 0xff;
6591 	sc->rxon->ht_dual_mask = 0xff;
6592 	sc->rxon->ht_triple_mask = 0xff;
6593 	/*
6594 	 * In active association mode, ensure that
6595 	 * all the receive chains are enabled.
6596 	 *
6597 	 * Since we're not yet doing SMPS, don't allow the
6598 	 * number of idle RX chains to be less than the active
6599 	 * number.
6600 	 */
6601 	rxchain =
6602 	    IWN_RXCHAIN_VALID(sc->rxchainmask) |
6603 	    IWN_RXCHAIN_MIMO_COUNT(sc->nrxchains) |
6604 	    IWN_RXCHAIN_IDLE_COUNT(sc->nrxchains);
6605 	sc->rxon->rxchain = htole16(rxchain);
6606 	DPRINTF(sc, IWN_DEBUG_RESET | IWN_DEBUG_XMIT,
6607 	    "%s: rxchainmask=0x%x, nrxchains=%d\n",
6608 	    __func__,
6609 	    sc->rxchainmask,
6610 	    sc->nrxchains);
6611 
6612 	sc->rxon->flags |= htole32(iwn_get_rxon_ht_flags(sc, ic->ic_curchan));
6613 
6614 	DPRINTF(sc, IWN_DEBUG_RESET,
6615 	    "%s: setting configuration; flags=0x%08x\n",
6616 	    __func__, le32toh(sc->rxon->flags));
6617 	if (sc->sc_is_scanning)
6618 		device_printf(sc->sc_dev,
6619 		    "%s: is_scanning set, before RXON\n",
6620 		    __func__);
6621 	error = iwn_cmd(sc, IWN_CMD_RXON, sc->rxon, sc->rxonsz, 0);
6622 	if (error != 0) {
6623 		device_printf(sc->sc_dev, "%s: RXON command failed\n",
6624 		    __func__);
6625 		return error;
6626 	}
6627 
6628 	if ((error = iwn_add_broadcast_node(sc, 0)) != 0) {
6629 		device_printf(sc->sc_dev, "%s: could not add broadcast node\n",
6630 		    __func__);
6631 		return error;
6632 	}
6633 
6634 	/* Configuration has changed, set TX power accordingly. */
6635 	if ((error = ops->set_txpower(sc, ic->ic_curchan, 0)) != 0) {
6636 		device_printf(sc->sc_dev, "%s: could not set TX power\n",
6637 		    __func__);
6638 		return error;
6639 	}
6640 
6641 	if ((error = iwn_set_critical_temp(sc)) != 0) {
6642 		device_printf(sc->sc_dev,
6643 		    "%s: could not set critical temperature\n", __func__);
6644 		return error;
6645 	}
6646 
6647 	/* Set power saving level to CAM during initialization. */
6648 	if ((error = iwn_set_pslevel(sc, 0, 0, 0)) != 0) {
6649 		device_printf(sc->sc_dev,
6650 		    "%s: could not set power saving level\n", __func__);
6651 		return error;
6652 	}
6653 
6654 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
6655 
6656 	return 0;
6657 }
6658 
6659 static uint16_t
6660 iwn_get_active_dwell_time(struct iwn_softc *sc,
6661     struct ieee80211_channel *c, uint8_t n_probes)
6662 {
6663 	/* No channel? Default to 2GHz settings */
6664 	if (c == NULL || IEEE80211_IS_CHAN_2GHZ(c)) {
6665 		return (IWN_ACTIVE_DWELL_TIME_2GHZ +
6666 		IWN_ACTIVE_DWELL_FACTOR_2GHZ * (n_probes + 1));
6667 	}
6668 
6669 	/* 5GHz dwell time */
6670 	return (IWN_ACTIVE_DWELL_TIME_5GHZ +
6671 	    IWN_ACTIVE_DWELL_FACTOR_5GHZ * (n_probes + 1));
6672 }
6673 
6674 /*
6675  * Limit the total dwell time to 85% of the beacon interval.
6676  *
6677  * Returns the dwell time in milliseconds.
6678  */
6679 static uint16_t
6680 iwn_limit_dwell(struct iwn_softc *sc, uint16_t dwell_time)
6681 {
6682 	struct ieee80211com *ic = &sc->sc_ic;
6683 	struct ieee80211vap *vap = NULL;
6684 	int bintval = 0;
6685 
6686 	/* bintval is in TU (1.024mS) */
6687 	if (! TAILQ_EMPTY(&ic->ic_vaps)) {
6688 		vap = TAILQ_FIRST(&ic->ic_vaps);
6689 		bintval = vap->iv_bss->ni_intval;
6690 	}
6691 
6692 	/*
6693 	 * If it's non-zero, we should calculate the minimum of
6694 	 * it and the DWELL_BASE.
6695 	 *
6696 	 * XXX Yes, the math should take into account that bintval
6697 	 * is 1.024mS, not 1mS..
6698 	 */
6699 	if (bintval > 0) {
6700 		DPRINTF(sc, IWN_DEBUG_SCAN,
6701 		    "%s: bintval=%d\n",
6702 		    __func__,
6703 		    bintval);
6704 		return (MIN(IWN_PASSIVE_DWELL_BASE, ((bintval * 85) / 100)));
6705 	}
6706 
6707 	/* No association context? Default */
6708 	return (IWN_PASSIVE_DWELL_BASE);
6709 }
6710 
6711 static uint16_t
6712 iwn_get_passive_dwell_time(struct iwn_softc *sc, struct ieee80211_channel *c)
6713 {
6714 	uint16_t passive;
6715 
6716 	if (c == NULL || IEEE80211_IS_CHAN_2GHZ(c)) {
6717 		passive = IWN_PASSIVE_DWELL_BASE + IWN_PASSIVE_DWELL_TIME_2GHZ;
6718 	} else {
6719 		passive = IWN_PASSIVE_DWELL_BASE + IWN_PASSIVE_DWELL_TIME_5GHZ;
6720 	}
6721 
6722 	/* Clamp to the beacon interval if we're associated */
6723 	return (iwn_limit_dwell(sc, passive));
6724 }
6725 
6726 static int
6727 iwn_scan(struct iwn_softc *sc, struct ieee80211vap *vap,
6728     struct ieee80211_scan_state *ss, struct ieee80211_channel *c)
6729 {
6730 	struct ieee80211com *ic = &sc->sc_ic;
6731 	struct ieee80211_node *ni = vap->iv_bss;
6732 	struct iwn_scan_hdr *hdr;
6733 	struct iwn_cmd_data *tx;
6734 	struct iwn_scan_essid *essid;
6735 	struct iwn_scan_chan *chan;
6736 	struct ieee80211_frame *wh;
6737 	struct ieee80211_rateset *rs;
6738 	uint8_t *buf, *frm;
6739 	uint16_t rxchain;
6740 	uint8_t txant;
6741 	int buflen, error;
6742 	int is_active;
6743 	uint16_t dwell_active, dwell_passive;
6744 	uint32_t extra, scan_service_time;
6745 
6746 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
6747 
6748 	/*
6749 	 * We are absolutely not allowed to send a scan command when another
6750 	 * scan command is pending.
6751 	 */
6752 	if (sc->sc_is_scanning) {
6753 		device_printf(sc->sc_dev, "%s: called whilst scanning!\n",
6754 		    __func__);
6755 		return (EAGAIN);
6756 	}
6757 
6758 	/* Assign the scan channel */
6759 	c = ic->ic_curchan;
6760 
6761 	sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
6762 	buf = malloc(IWN_SCAN_MAXSZ, M_DEVBUF, M_NOWAIT | M_ZERO);
6763 	if (buf == NULL) {
6764 		device_printf(sc->sc_dev,
6765 		    "%s: could not allocate buffer for scan command\n",
6766 		    __func__);
6767 		return ENOMEM;
6768 	}
6769 	hdr = (struct iwn_scan_hdr *)buf;
6770 	/*
6771 	 * Move to the next channel if no frames are received within 10ms
6772 	 * after sending the probe request.
6773 	 */
6774 	hdr->quiet_time = htole16(10);		/* timeout in milliseconds */
6775 	hdr->quiet_threshold = htole16(1);	/* min # of packets */
6776 	/*
6777 	 * Max needs to be greater than active and passive and quiet!
6778 	 * It's also in microseconds!
6779 	 */
6780 	hdr->max_svc = htole32(250 * 1024);
6781 
6782 	/*
6783 	 * Reset scan: interval=100
6784 	 * Normal scan: interval=becaon interval
6785 	 * suspend_time: 100 (TU)
6786 	 *
6787 	 */
6788 	extra = (100 /* suspend_time */ / 100 /* beacon interval */) << 22;
6789 	//scan_service_time = extra | ((100 /* susp */ % 100 /* int */) * 1024);
6790 	scan_service_time = (4 << 22) | (100 * 1024);	/* Hardcode for now! */
6791 	hdr->pause_svc = htole32(scan_service_time);
6792 
6793 	/* Select antennas for scanning. */
6794 	rxchain =
6795 	    IWN_RXCHAIN_VALID(sc->rxchainmask) |
6796 	    IWN_RXCHAIN_FORCE_MIMO_SEL(sc->rxchainmask) |
6797 	    IWN_RXCHAIN_DRIVER_FORCE;
6798 	if (IEEE80211_IS_CHAN_A(c) &&
6799 	    sc->hw_type == IWN_HW_REV_TYPE_4965) {
6800 		/* Ant A must be avoided in 5GHz because of an HW bug. */
6801 		rxchain |= IWN_RXCHAIN_FORCE_SEL(IWN_ANT_B);
6802 	} else	/* Use all available RX antennas. */
6803 		rxchain |= IWN_RXCHAIN_FORCE_SEL(sc->rxchainmask);
6804 	hdr->rxchain = htole16(rxchain);
6805 	hdr->filter = htole32(IWN_FILTER_MULTICAST | IWN_FILTER_BEACON);
6806 
6807 	tx = (struct iwn_cmd_data *)(hdr + 1);
6808 	tx->flags = htole32(IWN_TX_AUTO_SEQ);
6809 	tx->id = sc->broadcast_id;
6810 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
6811 
6812 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
6813 		/* Send probe requests at 6Mbps. */
6814 		tx->rate = htole32(0xd);
6815 		rs = &ic->ic_sup_rates[IEEE80211_MODE_11A];
6816 	} else {
6817 		hdr->flags = htole32(IWN_RXON_24GHZ | IWN_RXON_AUTO);
6818 		if (sc->hw_type == IWN_HW_REV_TYPE_4965 &&
6819 		    sc->rxon->associd && sc->rxon->chan > 14)
6820 			tx->rate = htole32(0xd);
6821 		else {
6822 			/* Send probe requests at 1Mbps. */
6823 			tx->rate = htole32(10 | IWN_RFLAG_CCK);
6824 		}
6825 		rs = &ic->ic_sup_rates[IEEE80211_MODE_11G];
6826 	}
6827 	/* Use the first valid TX antenna. */
6828 	txant = IWN_LSB(sc->txchainmask);
6829 	tx->rate |= htole32(IWN_RFLAG_ANT(txant));
6830 
6831 	/*
6832 	 * Only do active scanning if we're announcing a probe request
6833 	 * for a given SSID (or more, if we ever add it to the driver.)
6834 	 */
6835 	is_active = 0;
6836 
6837 	/*
6838 	 * If we're scanning for a specific SSID, add it to the command.
6839 	 *
6840 	 * XXX maybe look at adding support for scanning multiple SSIDs?
6841 	 */
6842 	essid = (struct iwn_scan_essid *)(tx + 1);
6843 	if (ss != NULL) {
6844 		if (ss->ss_ssid[0].len != 0) {
6845 			essid[0].id = IEEE80211_ELEMID_SSID;
6846 			essid[0].len = ss->ss_ssid[0].len;
6847 			memcpy(essid[0].data, ss->ss_ssid[0].ssid, ss->ss_ssid[0].len);
6848 		}
6849 
6850 		DPRINTF(sc, IWN_DEBUG_SCAN, "%s: ssid_len=%d, ssid=%*s\n",
6851 		    __func__,
6852 		    ss->ss_ssid[0].len,
6853 		    ss->ss_ssid[0].len,
6854 		    ss->ss_ssid[0].ssid);
6855 
6856 		if (ss->ss_nssid > 0)
6857 			is_active = 1;
6858 	}
6859 
6860 	/*
6861 	 * Build a probe request frame.  Most of the following code is a
6862 	 * copy & paste of what is done in net80211.
6863 	 */
6864 	wh = (struct ieee80211_frame *)(essid + 20);
6865 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
6866 	    IEEE80211_FC0_SUBTYPE_PROBE_REQ;
6867 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
6868 	IEEE80211_ADDR_COPY(wh->i_addr1, vap->iv_ifp->if_broadcastaddr);
6869 	IEEE80211_ADDR_COPY(wh->i_addr2, IF_LLADDR(vap->iv_ifp));
6870 	IEEE80211_ADDR_COPY(wh->i_addr3, vap->iv_ifp->if_broadcastaddr);
6871 	*(uint16_t *)&wh->i_dur[0] = 0;	/* filled by HW */
6872 	*(uint16_t *)&wh->i_seq[0] = 0;	/* filled by HW */
6873 
6874 	frm = (uint8_t *)(wh + 1);
6875 	frm = ieee80211_add_ssid(frm, NULL, 0);
6876 	frm = ieee80211_add_rates(frm, rs);
6877 	if (rs->rs_nrates > IEEE80211_RATE_SIZE)
6878 		frm = ieee80211_add_xrates(frm, rs);
6879 	if (ic->ic_htcaps & IEEE80211_HTC_HT)
6880 		frm = ieee80211_add_htcap(frm, ni);
6881 
6882 	/* Set length of probe request. */
6883 	tx->len = htole16(frm - (uint8_t *)wh);
6884 
6885 	/*
6886 	 * If active scanning is requested but a certain channel is
6887 	 * marked passive, we can do active scanning if we detect
6888 	 * transmissions.
6889 	 *
6890 	 * There is an issue with some firmware versions that triggers
6891 	 * a sysassert on a "good CRC threshold" of zero (== disabled),
6892 	 * on a radar channel even though this means that we should NOT
6893 	 * send probes.
6894 	 *
6895 	 * The "good CRC threshold" is the number of frames that we
6896 	 * need to receive during our dwell time on a channel before
6897 	 * sending out probes -- setting this to a huge value will
6898 	 * mean we never reach it, but at the same time work around
6899 	 * the aforementioned issue. Thus use IWL_GOOD_CRC_TH_NEVER
6900 	 * here instead of IWL_GOOD_CRC_TH_DISABLED.
6901 	 *
6902 	 * This was fixed in later versions along with some other
6903 	 * scan changes, and the threshold behaves as a flag in those
6904 	 * versions.
6905 	 */
6906 
6907 	/*
6908 	 * If we're doing active scanning, set the crc_threshold
6909 	 * to a suitable value.  This is different to active veruss
6910 	 * passive scanning depending upon the channel flags; the
6911 	 * firmware will obey that particular check for us.
6912 	 */
6913 	if (sc->tlv_feature_flags & IWN_UCODE_TLV_FLAGS_NEWSCAN)
6914 		hdr->crc_threshold = is_active ?
6915 		    IWN_GOOD_CRC_TH_DEFAULT : IWN_GOOD_CRC_TH_DISABLED;
6916 	else
6917 		hdr->crc_threshold = is_active ?
6918 		    IWN_GOOD_CRC_TH_DEFAULT : IWN_GOOD_CRC_TH_NEVER;
6919 
6920 	chan = (struct iwn_scan_chan *)frm;
6921 	chan->chan = htole16(ieee80211_chan2ieee(ic, c));
6922 	chan->flags = 0;
6923 	if (ss->ss_nssid > 0)
6924 		chan->flags |= htole32(IWN_CHAN_NPBREQS(1));
6925 	chan->dsp_gain = 0x6e;
6926 
6927 	/*
6928 	 * Set the passive/active flag depending upon the channel mode.
6929 	 * XXX TODO: take the is_active flag into account as well?
6930 	 */
6931 	if (c->ic_flags & IEEE80211_CHAN_PASSIVE)
6932 		chan->flags |= htole32(IWN_CHAN_PASSIVE);
6933 	else
6934 		chan->flags |= htole32(IWN_CHAN_ACTIVE);
6935 
6936 	/*
6937 	 * Calculate the active/passive dwell times.
6938 	 */
6939 
6940 	dwell_active = iwn_get_active_dwell_time(sc, c, ss->ss_nssid);
6941 	dwell_passive = iwn_get_passive_dwell_time(sc, c);
6942 
6943 	/* Make sure they're valid */
6944 	if (dwell_passive <= dwell_active)
6945 		dwell_passive = dwell_active + 1;
6946 
6947 	chan->active = htole16(dwell_active);
6948 	chan->passive = htole16(dwell_passive);
6949 
6950 	if (IEEE80211_IS_CHAN_5GHZ(c))
6951 		chan->rf_gain = 0x3b;
6952 	else
6953 		chan->rf_gain = 0x28;
6954 
6955 	DPRINTF(sc, IWN_DEBUG_STATE,
6956 	    "%s: chan %u flags 0x%x rf_gain 0x%x "
6957 	    "dsp_gain 0x%x active %d passive %d scan_svc_time %d crc 0x%x "
6958 	    "isactive=%d numssid=%d\n", __func__,
6959 	    chan->chan, chan->flags, chan->rf_gain, chan->dsp_gain,
6960 	    dwell_active, dwell_passive, scan_service_time,
6961 	    hdr->crc_threshold, is_active, ss->ss_nssid);
6962 
6963 	hdr->nchan++;
6964 	chan++;
6965 	buflen = (uint8_t *)chan - buf;
6966 	hdr->len = htole16(buflen);
6967 
6968 	if (sc->sc_is_scanning) {
6969 		device_printf(sc->sc_dev,
6970 		    "%s: called with is_scanning set!\n",
6971 		    __func__);
6972 	}
6973 	sc->sc_is_scanning = 1;
6974 
6975 	DPRINTF(sc, IWN_DEBUG_STATE, "sending scan command nchan=%d\n",
6976 	    hdr->nchan);
6977 	error = iwn_cmd(sc, IWN_CMD_SCAN, buf, buflen, 1);
6978 	free(buf, M_DEVBUF);
6979 
6980 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
6981 
6982 	return error;
6983 }
6984 
6985 static int
6986 iwn_auth(struct iwn_softc *sc, struct ieee80211vap *vap)
6987 {
6988 	struct iwn_ops *ops = &sc->ops;
6989 	struct ieee80211com *ic = &sc->sc_ic;
6990 	struct ieee80211_node *ni = vap->iv_bss;
6991 	int error;
6992 
6993 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
6994 
6995 	sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
6996 	/* Update adapter configuration. */
6997 	IEEE80211_ADDR_COPY(sc->rxon->bssid, ni->ni_bssid);
6998 	sc->rxon->chan = ieee80211_chan2ieee(ic, ni->ni_chan);
6999 	sc->rxon->flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
7000 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
7001 		sc->rxon->flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
7002 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
7003 		sc->rxon->flags |= htole32(IWN_RXON_SHSLOT);
7004 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
7005 		sc->rxon->flags |= htole32(IWN_RXON_SHPREAMBLE);
7006 	if (IEEE80211_IS_CHAN_A(ni->ni_chan)) {
7007 		sc->rxon->cck_mask  = 0;
7008 		sc->rxon->ofdm_mask = 0x15;
7009 	} else if (IEEE80211_IS_CHAN_B(ni->ni_chan)) {
7010 		sc->rxon->cck_mask  = 0x03;
7011 		sc->rxon->ofdm_mask = 0;
7012 	} else {
7013 		/* Assume 802.11b/g. */
7014 		sc->rxon->cck_mask  = 0x03;
7015 		sc->rxon->ofdm_mask = 0x15;
7016 	}
7017 
7018 	/* try HT */
7019 	sc->rxon->flags |= htole32(iwn_get_rxon_ht_flags(sc, ic->ic_curchan));
7020 
7021 	DPRINTF(sc, IWN_DEBUG_STATE, "rxon chan %d flags %x cck %x ofdm %x\n",
7022 	    sc->rxon->chan, sc->rxon->flags, sc->rxon->cck_mask,
7023 	    sc->rxon->ofdm_mask);
7024 	if (sc->sc_is_scanning)
7025 		device_printf(sc->sc_dev,
7026 		    "%s: is_scanning set, before RXON\n",
7027 		    __func__);
7028 	error = iwn_cmd(sc, IWN_CMD_RXON, sc->rxon, sc->rxonsz, 1);
7029 	if (error != 0) {
7030 		device_printf(sc->sc_dev, "%s: RXON command failed, error %d\n",
7031 		    __func__, error);
7032 		return error;
7033 	}
7034 
7035 	/* Configuration has changed, set TX power accordingly. */
7036 	if ((error = ops->set_txpower(sc, ni->ni_chan, 1)) != 0) {
7037 		device_printf(sc->sc_dev,
7038 		    "%s: could not set TX power, error %d\n", __func__, error);
7039 		return error;
7040 	}
7041 	/*
7042 	 * Reconfiguring RXON clears the firmware nodes table so we must
7043 	 * add the broadcast node again.
7044 	 */
7045 	if ((error = iwn_add_broadcast_node(sc, 1)) != 0) {
7046 		device_printf(sc->sc_dev,
7047 		    "%s: could not add broadcast node, error %d\n", __func__,
7048 		    error);
7049 		return error;
7050 	}
7051 
7052 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
7053 
7054 	return 0;
7055 }
7056 
7057 static int
7058 iwn_run(struct iwn_softc *sc, struct ieee80211vap *vap)
7059 {
7060 	struct iwn_ops *ops = &sc->ops;
7061 	struct ieee80211com *ic = &sc->sc_ic;
7062 	struct ieee80211_node *ni = vap->iv_bss;
7063 	struct iwn_node_info node;
7064 	int error;
7065 
7066 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
7067 
7068 	sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
7069 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
7070 		/* Link LED blinks while monitoring. */
7071 		iwn_set_led(sc, IWN_LED_LINK, 5, 5);
7072 		return 0;
7073 	}
7074 	if ((error = iwn_set_timing(sc, ni)) != 0) {
7075 		device_printf(sc->sc_dev,
7076 		    "%s: could not set timing, error %d\n", __func__, error);
7077 		return error;
7078 	}
7079 
7080 	/* Update adapter configuration. */
7081 	IEEE80211_ADDR_COPY(sc->rxon->bssid, ni->ni_bssid);
7082 	sc->rxon->associd = htole16(IEEE80211_AID(ni->ni_associd));
7083 	sc->rxon->chan = ieee80211_chan2ieee(ic, ni->ni_chan);
7084 	sc->rxon->flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
7085 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
7086 		sc->rxon->flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
7087 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
7088 		sc->rxon->flags |= htole32(IWN_RXON_SHSLOT);
7089 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
7090 		sc->rxon->flags |= htole32(IWN_RXON_SHPREAMBLE);
7091 	if (IEEE80211_IS_CHAN_A(ni->ni_chan)) {
7092 		sc->rxon->cck_mask  = 0;
7093 		sc->rxon->ofdm_mask = 0x15;
7094 	} else if (IEEE80211_IS_CHAN_B(ni->ni_chan)) {
7095 		sc->rxon->cck_mask  = 0x03;
7096 		sc->rxon->ofdm_mask = 0;
7097 	} else {
7098 		/* Assume 802.11b/g. */
7099 		sc->rxon->cck_mask  = 0x0f;
7100 		sc->rxon->ofdm_mask = 0x15;
7101 	}
7102 	/* try HT */
7103 	sc->rxon->flags |= htole32(iwn_get_rxon_ht_flags(sc, ni->ni_chan));
7104 	sc->rxon->filter |= htole32(IWN_FILTER_BSS);
7105 	DPRINTF(sc, IWN_DEBUG_STATE, "rxon chan %d flags %x, curhtprotmode=%d\n",
7106 	    sc->rxon->chan, le32toh(sc->rxon->flags), ic->ic_curhtprotmode);
7107 	if (sc->sc_is_scanning)
7108 		device_printf(sc->sc_dev,
7109 		    "%s: is_scanning set, before RXON\n",
7110 		    __func__);
7111 	error = iwn_cmd(sc, IWN_CMD_RXON, sc->rxon, sc->rxonsz, 1);
7112 	if (error != 0) {
7113 		device_printf(sc->sc_dev,
7114 		    "%s: could not update configuration, error %d\n", __func__,
7115 		    error);
7116 		return error;
7117 	}
7118 
7119 	/* Configuration has changed, set TX power accordingly. */
7120 	if ((error = ops->set_txpower(sc, ni->ni_chan, 1)) != 0) {
7121 		device_printf(sc->sc_dev,
7122 		    "%s: could not set TX power, error %d\n", __func__, error);
7123 		return error;
7124 	}
7125 
7126 	/* Fake a join to initialize the TX rate. */
7127 	((struct iwn_node *)ni)->id = IWN_ID_BSS;
7128 	iwn_newassoc(ni, 1);
7129 
7130 	/* Add BSS node. */
7131 	memset(&node, 0, sizeof node);
7132 	IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr);
7133 	node.id = IWN_ID_BSS;
7134 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan)) {
7135 		switch (ni->ni_htcap & IEEE80211_HTCAP_SMPS) {
7136 		case IEEE80211_HTCAP_SMPS_ENA:
7137 			node.htflags |= htole32(IWN_SMPS_MIMO_DIS);
7138 			break;
7139 		case IEEE80211_HTCAP_SMPS_DYNAMIC:
7140 			node.htflags |= htole32(IWN_SMPS_MIMO_PROT);
7141 			break;
7142 		}
7143 		node.htflags |= htole32(IWN_AMDPU_SIZE_FACTOR(3) |
7144 		    IWN_AMDPU_DENSITY(5));	/* 4us */
7145 		if (IEEE80211_IS_CHAN_HT40(ni->ni_chan))
7146 			node.htflags |= htole32(IWN_NODE_HT40);
7147 	}
7148 	DPRINTF(sc, IWN_DEBUG_STATE, "%s: adding BSS node\n", __func__);
7149 	error = ops->add_node(sc, &node, 1);
7150 	if (error != 0) {
7151 		device_printf(sc->sc_dev,
7152 		    "%s: could not add BSS node, error %d\n", __func__, error);
7153 		return error;
7154 	}
7155 	DPRINTF(sc, IWN_DEBUG_STATE, "%s: setting link quality for node %d\n",
7156 	    __func__, node.id);
7157 	if ((error = iwn_set_link_quality(sc, ni)) != 0) {
7158 		device_printf(sc->sc_dev,
7159 		    "%s: could not setup link quality for node %d, error %d\n",
7160 		    __func__, node.id, error);
7161 		return error;
7162 	}
7163 
7164 	if ((error = iwn_init_sensitivity(sc)) != 0) {
7165 		device_printf(sc->sc_dev,
7166 		    "%s: could not set sensitivity, error %d\n", __func__,
7167 		    error);
7168 		return error;
7169 	}
7170 	/* Start periodic calibration timer. */
7171 	sc->calib.state = IWN_CALIB_STATE_ASSOC;
7172 	sc->calib_cnt = 0;
7173 	callout_reset(&sc->calib_to, msecs_to_ticks(500), iwn_calib_timeout,
7174 	    sc);
7175 
7176 	/* Link LED always on while associated. */
7177 	iwn_set_led(sc, IWN_LED_LINK, 0, 1);
7178 
7179 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
7180 
7181 	return 0;
7182 }
7183 
7184 /*
7185  * This function is called by upper layer when an ADDBA request is received
7186  * from another STA and before the ADDBA response is sent.
7187  */
7188 static int
7189 iwn_ampdu_rx_start(struct ieee80211_node *ni, struct ieee80211_rx_ampdu *rap,
7190     int baparamset, int batimeout, int baseqctl)
7191 {
7192 #define MS(_v, _f)	(((_v) & _f) >> _f##_S)
7193 	struct iwn_softc *sc = ni->ni_ic->ic_softc;
7194 	struct iwn_ops *ops = &sc->ops;
7195 	struct iwn_node *wn = (void *)ni;
7196 	struct iwn_node_info node;
7197 	uint16_t ssn;
7198 	uint8_t tid;
7199 	int error;
7200 
7201 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7202 
7203 	tid = MS(le16toh(baparamset), IEEE80211_BAPS_TID);
7204 	ssn = MS(le16toh(baseqctl), IEEE80211_BASEQ_START);
7205 
7206 	memset(&node, 0, sizeof node);
7207 	node.id = wn->id;
7208 	node.control = IWN_NODE_UPDATE;
7209 	node.flags = IWN_FLAG_SET_ADDBA;
7210 	node.addba_tid = tid;
7211 	node.addba_ssn = htole16(ssn);
7212 	DPRINTF(sc, IWN_DEBUG_RECV, "ADDBA RA=%d TID=%d SSN=%d\n",
7213 	    wn->id, tid, ssn);
7214 	error = ops->add_node(sc, &node, 1);
7215 	if (error != 0)
7216 		return error;
7217 	return sc->sc_ampdu_rx_start(ni, rap, baparamset, batimeout, baseqctl);
7218 #undef MS
7219 }
7220 
7221 /*
7222  * This function is called by upper layer on teardown of an HT-immediate
7223  * Block Ack agreement (eg. uppon receipt of a DELBA frame).
7224  */
7225 static void
7226 iwn_ampdu_rx_stop(struct ieee80211_node *ni, struct ieee80211_rx_ampdu *rap)
7227 {
7228 	struct ieee80211com *ic = ni->ni_ic;
7229 	struct iwn_softc *sc = ic->ic_softc;
7230 	struct iwn_ops *ops = &sc->ops;
7231 	struct iwn_node *wn = (void *)ni;
7232 	struct iwn_node_info node;
7233 	uint8_t tid;
7234 
7235 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7236 
7237 	/* XXX: tid as an argument */
7238 	for (tid = 0; tid < WME_NUM_TID; tid++) {
7239 		if (&ni->ni_rx_ampdu[tid] == rap)
7240 			break;
7241 	}
7242 
7243 	memset(&node, 0, sizeof node);
7244 	node.id = wn->id;
7245 	node.control = IWN_NODE_UPDATE;
7246 	node.flags = IWN_FLAG_SET_DELBA;
7247 	node.delba_tid = tid;
7248 	DPRINTF(sc, IWN_DEBUG_RECV, "DELBA RA=%d TID=%d\n", wn->id, tid);
7249 	(void)ops->add_node(sc, &node, 1);
7250 	sc->sc_ampdu_rx_stop(ni, rap);
7251 }
7252 
7253 static int
7254 iwn_addba_request(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
7255     int dialogtoken, int baparamset, int batimeout)
7256 {
7257 	struct iwn_softc *sc = ni->ni_ic->ic_softc;
7258 	int qid;
7259 
7260 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7261 
7262 	for (qid = sc->firstaggqueue; qid < sc->ntxqs; qid++) {
7263 		if (sc->qid2tap[qid] == NULL)
7264 			break;
7265 	}
7266 	if (qid == sc->ntxqs) {
7267 		DPRINTF(sc, IWN_DEBUG_XMIT, "%s: not free aggregation queue\n",
7268 		    __func__);
7269 		return 0;
7270 	}
7271 	tap->txa_private = malloc(sizeof(int), M_DEVBUF, M_NOWAIT);
7272 	if (tap->txa_private == NULL) {
7273 		device_printf(sc->sc_dev,
7274 		    "%s: failed to alloc TX aggregation structure\n", __func__);
7275 		return 0;
7276 	}
7277 	sc->qid2tap[qid] = tap;
7278 	*(int *)tap->txa_private = qid;
7279 	return sc->sc_addba_request(ni, tap, dialogtoken, baparamset,
7280 	    batimeout);
7281 }
7282 
7283 static int
7284 iwn_addba_response(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
7285     int code, int baparamset, int batimeout)
7286 {
7287 	struct iwn_softc *sc = ni->ni_ic->ic_softc;
7288 	int qid = *(int *)tap->txa_private;
7289 	uint8_t tid = tap->txa_tid;
7290 	int ret;
7291 
7292 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7293 
7294 	if (code == IEEE80211_STATUS_SUCCESS) {
7295 		ni->ni_txseqs[tid] = tap->txa_start & 0xfff;
7296 		ret = iwn_ampdu_tx_start(ni->ni_ic, ni, tid);
7297 		if (ret != 1)
7298 			return ret;
7299 	} else {
7300 		sc->qid2tap[qid] = NULL;
7301 		free(tap->txa_private, M_DEVBUF);
7302 		tap->txa_private = NULL;
7303 	}
7304 	return sc->sc_addba_response(ni, tap, code, baparamset, batimeout);
7305 }
7306 
7307 /*
7308  * This function is called by upper layer when an ADDBA response is received
7309  * from another STA.
7310  */
7311 static int
7312 iwn_ampdu_tx_start(struct ieee80211com *ic, struct ieee80211_node *ni,
7313     uint8_t tid)
7314 {
7315 	struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[tid];
7316 	struct iwn_softc *sc = ni->ni_ic->ic_softc;
7317 	struct iwn_ops *ops = &sc->ops;
7318 	struct iwn_node *wn = (void *)ni;
7319 	struct iwn_node_info node;
7320 	int error, qid;
7321 
7322 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7323 
7324 	/* Enable TX for the specified RA/TID. */
7325 	wn->disable_tid &= ~(1 << tid);
7326 	memset(&node, 0, sizeof node);
7327 	node.id = wn->id;
7328 	node.control = IWN_NODE_UPDATE;
7329 	node.flags = IWN_FLAG_SET_DISABLE_TID;
7330 	node.disable_tid = htole16(wn->disable_tid);
7331 	error = ops->add_node(sc, &node, 1);
7332 	if (error != 0)
7333 		return 0;
7334 
7335 	if ((error = iwn_nic_lock(sc)) != 0)
7336 		return 0;
7337 	qid = *(int *)tap->txa_private;
7338 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: ra=%d tid=%d ssn=%d qid=%d\n",
7339 	    __func__, wn->id, tid, tap->txa_start, qid);
7340 	ops->ampdu_tx_start(sc, ni, qid, tid, tap->txa_start & 0xfff);
7341 	iwn_nic_unlock(sc);
7342 
7343 	iwn_set_link_quality(sc, ni);
7344 	return 1;
7345 }
7346 
7347 static void
7348 iwn_ampdu_tx_stop(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap)
7349 {
7350 	struct iwn_softc *sc = ni->ni_ic->ic_softc;
7351 	struct iwn_ops *ops = &sc->ops;
7352 	uint8_t tid = tap->txa_tid;
7353 	int qid;
7354 
7355 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7356 
7357 	sc->sc_addba_stop(ni, tap);
7358 
7359 	if (tap->txa_private == NULL)
7360 		return;
7361 
7362 	qid = *(int *)tap->txa_private;
7363 	if (sc->txq[qid].queued != 0)
7364 		return;
7365 	if (iwn_nic_lock(sc) != 0)
7366 		return;
7367 	ops->ampdu_tx_stop(sc, qid, tid, tap->txa_start & 0xfff);
7368 	iwn_nic_unlock(sc);
7369 	sc->qid2tap[qid] = NULL;
7370 	free(tap->txa_private, M_DEVBUF);
7371 	tap->txa_private = NULL;
7372 }
7373 
7374 static void
7375 iwn4965_ampdu_tx_start(struct iwn_softc *sc, struct ieee80211_node *ni,
7376     int qid, uint8_t tid, uint16_t ssn)
7377 {
7378 	struct iwn_node *wn = (void *)ni;
7379 
7380 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7381 
7382 	/* Stop TX scheduler while we're changing its configuration. */
7383 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
7384 	    IWN4965_TXQ_STATUS_CHGACT);
7385 
7386 	/* Assign RA/TID translation to the queue. */
7387 	iwn_mem_write_2(sc, sc->sched_base + IWN4965_SCHED_TRANS_TBL(qid),
7388 	    wn->id << 4 | tid);
7389 
7390 	/* Enable chain-building mode for the queue. */
7391 	iwn_prph_setbits(sc, IWN4965_SCHED_QCHAIN_SEL, 1 << qid);
7392 
7393 	/* Set starting sequence number from the ADDBA request. */
7394 	sc->txq[qid].cur = sc->txq[qid].read = (ssn & 0xff);
7395 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
7396 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), ssn);
7397 
7398 	/* Set scheduler window size. */
7399 	iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid),
7400 	    IWN_SCHED_WINSZ);
7401 	/* Set scheduler frame limit. */
7402 	iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid) + 4,
7403 	    IWN_SCHED_LIMIT << 16);
7404 
7405 	/* Enable interrupts for the queue. */
7406 	iwn_prph_setbits(sc, IWN4965_SCHED_INTR_MASK, 1 << qid);
7407 
7408 	/* Mark the queue as active. */
7409 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
7410 	    IWN4965_TXQ_STATUS_ACTIVE | IWN4965_TXQ_STATUS_AGGR_ENA |
7411 	    iwn_tid2fifo[tid] << 1);
7412 }
7413 
7414 static void
7415 iwn4965_ampdu_tx_stop(struct iwn_softc *sc, int qid, uint8_t tid, uint16_t ssn)
7416 {
7417 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7418 
7419 	/* Stop TX scheduler while we're changing its configuration. */
7420 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
7421 	    IWN4965_TXQ_STATUS_CHGACT);
7422 
7423 	/* Set starting sequence number from the ADDBA request. */
7424 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
7425 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), ssn);
7426 
7427 	/* Disable interrupts for the queue. */
7428 	iwn_prph_clrbits(sc, IWN4965_SCHED_INTR_MASK, 1 << qid);
7429 
7430 	/* Mark the queue as inactive. */
7431 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
7432 	    IWN4965_TXQ_STATUS_INACTIVE | iwn_tid2fifo[tid] << 1);
7433 }
7434 
7435 static void
7436 iwn5000_ampdu_tx_start(struct iwn_softc *sc, struct ieee80211_node *ni,
7437     int qid, uint8_t tid, uint16_t ssn)
7438 {
7439 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7440 
7441 	struct iwn_node *wn = (void *)ni;
7442 
7443 	/* Stop TX scheduler while we're changing its configuration. */
7444 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
7445 	    IWN5000_TXQ_STATUS_CHGACT);
7446 
7447 	/* Assign RA/TID translation to the queue. */
7448 	iwn_mem_write_2(sc, sc->sched_base + IWN5000_SCHED_TRANS_TBL(qid),
7449 	    wn->id << 4 | tid);
7450 
7451 	/* Enable chain-building mode for the queue. */
7452 	iwn_prph_setbits(sc, IWN5000_SCHED_QCHAIN_SEL, 1 << qid);
7453 
7454 	/* Enable aggregation for the queue. */
7455 	iwn_prph_setbits(sc, IWN5000_SCHED_AGGR_SEL, 1 << qid);
7456 
7457 	/* Set starting sequence number from the ADDBA request. */
7458 	sc->txq[qid].cur = sc->txq[qid].read = (ssn & 0xff);
7459 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
7460 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), ssn);
7461 
7462 	/* Set scheduler window size and frame limit. */
7463 	iwn_mem_write(sc, sc->sched_base + IWN5000_SCHED_QUEUE_OFFSET(qid) + 4,
7464 	    IWN_SCHED_LIMIT << 16 | IWN_SCHED_WINSZ);
7465 
7466 	/* Enable interrupts for the queue. */
7467 	iwn_prph_setbits(sc, IWN5000_SCHED_INTR_MASK, 1 << qid);
7468 
7469 	/* Mark the queue as active. */
7470 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
7471 	    IWN5000_TXQ_STATUS_ACTIVE | iwn_tid2fifo[tid]);
7472 }
7473 
7474 static void
7475 iwn5000_ampdu_tx_stop(struct iwn_softc *sc, int qid, uint8_t tid, uint16_t ssn)
7476 {
7477 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7478 
7479 	/* Stop TX scheduler while we're changing its configuration. */
7480 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
7481 	    IWN5000_TXQ_STATUS_CHGACT);
7482 
7483 	/* Disable aggregation for the queue. */
7484 	iwn_prph_clrbits(sc, IWN5000_SCHED_AGGR_SEL, 1 << qid);
7485 
7486 	/* Set starting sequence number from the ADDBA request. */
7487 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
7488 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), ssn);
7489 
7490 	/* Disable interrupts for the queue. */
7491 	iwn_prph_clrbits(sc, IWN5000_SCHED_INTR_MASK, 1 << qid);
7492 
7493 	/* Mark the queue as inactive. */
7494 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
7495 	    IWN5000_TXQ_STATUS_INACTIVE | iwn_tid2fifo[tid]);
7496 }
7497 
7498 /*
7499  * Query calibration tables from the initialization firmware.  We do this
7500  * only once at first boot.  Called from a process context.
7501  */
7502 static int
7503 iwn5000_query_calibration(struct iwn_softc *sc)
7504 {
7505 	struct iwn5000_calib_config cmd;
7506 	int error;
7507 
7508 	memset(&cmd, 0, sizeof cmd);
7509 	cmd.ucode.once.enable = htole32(0xffffffff);
7510 	cmd.ucode.once.start  = htole32(0xffffffff);
7511 	cmd.ucode.once.send   = htole32(0xffffffff);
7512 	cmd.ucode.flags       = htole32(0xffffffff);
7513 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: sending calibration query\n",
7514 	    __func__);
7515 	error = iwn_cmd(sc, IWN5000_CMD_CALIB_CONFIG, &cmd, sizeof cmd, 0);
7516 	if (error != 0)
7517 		return error;
7518 
7519 	/* Wait at most two seconds for calibration to complete. */
7520 	if (!(sc->sc_flags & IWN_FLAG_CALIB_DONE))
7521 		error = msleep(sc, &sc->sc_mtx, PCATCH, "iwncal", 2 * hz);
7522 	return error;
7523 }
7524 
7525 /*
7526  * Send calibration results to the runtime firmware.  These results were
7527  * obtained on first boot from the initialization firmware.
7528  */
7529 static int
7530 iwn5000_send_calibration(struct iwn_softc *sc)
7531 {
7532 	int idx, error;
7533 
7534 	for (idx = 0; idx < IWN5000_PHY_CALIB_MAX_RESULT; idx++) {
7535 		if (!(sc->base_params->calib_need & (1<<idx))) {
7536 			DPRINTF(sc, IWN_DEBUG_CALIBRATE,
7537 			    "No need of calib %d\n",
7538 			    idx);
7539 			continue; /* no need for this calib */
7540 		}
7541 		if (sc->calibcmd[idx].buf == NULL) {
7542 			DPRINTF(sc, IWN_DEBUG_CALIBRATE,
7543 			    "Need calib idx : %d but no available data\n",
7544 			    idx);
7545 			continue;
7546 		}
7547 
7548 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
7549 		    "send calibration result idx=%d len=%d\n", idx,
7550 		    sc->calibcmd[idx].len);
7551 		error = iwn_cmd(sc, IWN_CMD_PHY_CALIB, sc->calibcmd[idx].buf,
7552 		    sc->calibcmd[idx].len, 0);
7553 		if (error != 0) {
7554 			device_printf(sc->sc_dev,
7555 			    "%s: could not send calibration result, error %d\n",
7556 			    __func__, error);
7557 			return error;
7558 		}
7559 	}
7560 	return 0;
7561 }
7562 
7563 static int
7564 iwn5000_send_wimax_coex(struct iwn_softc *sc)
7565 {
7566 	struct iwn5000_wimax_coex wimax;
7567 
7568 #if 0
7569 	if (sc->hw_type == IWN_HW_REV_TYPE_6050) {
7570 		/* Enable WiMAX coexistence for combo adapters. */
7571 		wimax.flags =
7572 		    IWN_WIMAX_COEX_ASSOC_WA_UNMASK |
7573 		    IWN_WIMAX_COEX_UNASSOC_WA_UNMASK |
7574 		    IWN_WIMAX_COEX_STA_TABLE_VALID |
7575 		    IWN_WIMAX_COEX_ENABLE;
7576 		memcpy(wimax.events, iwn6050_wimax_events,
7577 		    sizeof iwn6050_wimax_events);
7578 	} else
7579 #endif
7580 	{
7581 		/* Disable WiMAX coexistence. */
7582 		wimax.flags = 0;
7583 		memset(wimax.events, 0, sizeof wimax.events);
7584 	}
7585 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: Configuring WiMAX coexistence\n",
7586 	    __func__);
7587 	return iwn_cmd(sc, IWN5000_CMD_WIMAX_COEX, &wimax, sizeof wimax, 0);
7588 }
7589 
7590 static int
7591 iwn5000_crystal_calib(struct iwn_softc *sc)
7592 {
7593 	struct iwn5000_phy_calib_crystal cmd;
7594 
7595 	memset(&cmd, 0, sizeof cmd);
7596 	cmd.code = IWN5000_PHY_CALIB_CRYSTAL;
7597 	cmd.ngroups = 1;
7598 	cmd.isvalid = 1;
7599 	cmd.cap_pin[0] = le32toh(sc->eeprom_crystal) & 0xff;
7600 	cmd.cap_pin[1] = (le32toh(sc->eeprom_crystal) >> 16) & 0xff;
7601 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "sending crystal calibration %d, %d\n",
7602 	    cmd.cap_pin[0], cmd.cap_pin[1]);
7603 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
7604 }
7605 
7606 static int
7607 iwn5000_temp_offset_calib(struct iwn_softc *sc)
7608 {
7609 	struct iwn5000_phy_calib_temp_offset cmd;
7610 
7611 	memset(&cmd, 0, sizeof cmd);
7612 	cmd.code = IWN5000_PHY_CALIB_TEMP_OFFSET;
7613 	cmd.ngroups = 1;
7614 	cmd.isvalid = 1;
7615 	if (sc->eeprom_temp != 0)
7616 		cmd.offset = htole16(sc->eeprom_temp);
7617 	else
7618 		cmd.offset = htole16(IWN_DEFAULT_TEMP_OFFSET);
7619 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "setting radio sensor offset to %d\n",
7620 	    le16toh(cmd.offset));
7621 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
7622 }
7623 
7624 static int
7625 iwn5000_temp_offset_calibv2(struct iwn_softc *sc)
7626 {
7627 	struct iwn5000_phy_calib_temp_offsetv2 cmd;
7628 
7629 	memset(&cmd, 0, sizeof cmd);
7630 	cmd.code = IWN5000_PHY_CALIB_TEMP_OFFSET;
7631 	cmd.ngroups = 1;
7632 	cmd.isvalid = 1;
7633 	if (sc->eeprom_temp != 0) {
7634 		cmd.offset_low = htole16(sc->eeprom_temp);
7635 		cmd.offset_high = htole16(sc->eeprom_temp_high);
7636 	} else {
7637 		cmd.offset_low = htole16(IWN_DEFAULT_TEMP_OFFSET);
7638 		cmd.offset_high = htole16(IWN_DEFAULT_TEMP_OFFSET);
7639 	}
7640 	cmd.burnt_voltage_ref = htole16(sc->eeprom_voltage);
7641 
7642 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
7643 	    "setting radio sensor low offset to %d, high offset to %d, voltage to %d\n",
7644 	    le16toh(cmd.offset_low),
7645 	    le16toh(cmd.offset_high),
7646 	    le16toh(cmd.burnt_voltage_ref));
7647 
7648 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
7649 }
7650 
7651 /*
7652  * This function is called after the runtime firmware notifies us of its
7653  * readiness (called in a process context).
7654  */
7655 static int
7656 iwn4965_post_alive(struct iwn_softc *sc)
7657 {
7658 	int error, qid;
7659 
7660 	if ((error = iwn_nic_lock(sc)) != 0)
7661 		return error;
7662 
7663 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7664 
7665 	/* Clear TX scheduler state in SRAM. */
7666 	sc->sched_base = iwn_prph_read(sc, IWN_SCHED_SRAM_ADDR);
7667 	iwn_mem_set_region_4(sc, sc->sched_base + IWN4965_SCHED_CTX_OFF, 0,
7668 	    IWN4965_SCHED_CTX_LEN / sizeof (uint32_t));
7669 
7670 	/* Set physical address of TX scheduler rings (1KB aligned). */
7671 	iwn_prph_write(sc, IWN4965_SCHED_DRAM_ADDR, sc->sched_dma.paddr >> 10);
7672 
7673 	IWN_SETBITS(sc, IWN_FH_TX_CHICKEN, IWN_FH_TX_CHICKEN_SCHED_RETRY);
7674 
7675 	/* Disable chain mode for all our 16 queues. */
7676 	iwn_prph_write(sc, IWN4965_SCHED_QCHAIN_SEL, 0);
7677 
7678 	for (qid = 0; qid < IWN4965_NTXQUEUES; qid++) {
7679 		iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), 0);
7680 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | 0);
7681 
7682 		/* Set scheduler window size. */
7683 		iwn_mem_write(sc, sc->sched_base +
7684 		    IWN4965_SCHED_QUEUE_OFFSET(qid), IWN_SCHED_WINSZ);
7685 		/* Set scheduler frame limit. */
7686 		iwn_mem_write(sc, sc->sched_base +
7687 		    IWN4965_SCHED_QUEUE_OFFSET(qid) + 4,
7688 		    IWN_SCHED_LIMIT << 16);
7689 	}
7690 
7691 	/* Enable interrupts for all our 16 queues. */
7692 	iwn_prph_write(sc, IWN4965_SCHED_INTR_MASK, 0xffff);
7693 	/* Identify TX FIFO rings (0-7). */
7694 	iwn_prph_write(sc, IWN4965_SCHED_TXFACT, 0xff);
7695 
7696 	/* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
7697 	for (qid = 0; qid < 7; qid++) {
7698 		static uint8_t qid2fifo[] = { 3, 2, 1, 0, 4, 5, 6 };
7699 		iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
7700 		    IWN4965_TXQ_STATUS_ACTIVE | qid2fifo[qid] << 1);
7701 	}
7702 	iwn_nic_unlock(sc);
7703 	return 0;
7704 }
7705 
7706 /*
7707  * This function is called after the initialization or runtime firmware
7708  * notifies us of its readiness (called in a process context).
7709  */
7710 static int
7711 iwn5000_post_alive(struct iwn_softc *sc)
7712 {
7713 	int error, qid;
7714 
7715 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
7716 
7717 	/* Switch to using ICT interrupt mode. */
7718 	iwn5000_ict_reset(sc);
7719 
7720 	if ((error = iwn_nic_lock(sc)) != 0){
7721 		DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end in error\n", __func__);
7722 		return error;
7723 	}
7724 
7725 	/* Clear TX scheduler state in SRAM. */
7726 	sc->sched_base = iwn_prph_read(sc, IWN_SCHED_SRAM_ADDR);
7727 	iwn_mem_set_region_4(sc, sc->sched_base + IWN5000_SCHED_CTX_OFF, 0,
7728 	    IWN5000_SCHED_CTX_LEN / sizeof (uint32_t));
7729 
7730 	/* Set physical address of TX scheduler rings (1KB aligned). */
7731 	iwn_prph_write(sc, IWN5000_SCHED_DRAM_ADDR, sc->sched_dma.paddr >> 10);
7732 
7733 	IWN_SETBITS(sc, IWN_FH_TX_CHICKEN, IWN_FH_TX_CHICKEN_SCHED_RETRY);
7734 
7735 	/* Enable chain mode for all queues, except command queue. */
7736 	if (sc->sc_flags & IWN_FLAG_PAN_SUPPORT)
7737 		iwn_prph_write(sc, IWN5000_SCHED_QCHAIN_SEL, 0xfffdf);
7738 	else
7739 		iwn_prph_write(sc, IWN5000_SCHED_QCHAIN_SEL, 0xfffef);
7740 	iwn_prph_write(sc, IWN5000_SCHED_AGGR_SEL, 0);
7741 
7742 	for (qid = 0; qid < IWN5000_NTXQUEUES; qid++) {
7743 		iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), 0);
7744 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | 0);
7745 
7746 		iwn_mem_write(sc, sc->sched_base +
7747 		    IWN5000_SCHED_QUEUE_OFFSET(qid), 0);
7748 		/* Set scheduler window size and frame limit. */
7749 		iwn_mem_write(sc, sc->sched_base +
7750 		    IWN5000_SCHED_QUEUE_OFFSET(qid) + 4,
7751 		    IWN_SCHED_LIMIT << 16 | IWN_SCHED_WINSZ);
7752 	}
7753 
7754 	/* Enable interrupts for all our 20 queues. */
7755 	iwn_prph_write(sc, IWN5000_SCHED_INTR_MASK, 0xfffff);
7756 	/* Identify TX FIFO rings (0-7). */
7757 	iwn_prph_write(sc, IWN5000_SCHED_TXFACT, 0xff);
7758 
7759 	/* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
7760 	if (sc->sc_flags & IWN_FLAG_PAN_SUPPORT) {
7761 		/* Mark TX rings as active. */
7762 		for (qid = 0; qid < 11; qid++) {
7763 			static uint8_t qid2fifo[] = { 3, 2, 1, 0, 0, 4, 2, 5, 4, 7, 5 };
7764 			iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
7765 			    IWN5000_TXQ_STATUS_ACTIVE | qid2fifo[qid]);
7766 		}
7767 	} else {
7768 		/* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
7769 		for (qid = 0; qid < 7; qid++) {
7770 			static uint8_t qid2fifo[] = { 3, 2, 1, 0, 7, 5, 6 };
7771 			iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
7772 			    IWN5000_TXQ_STATUS_ACTIVE | qid2fifo[qid]);
7773 		}
7774 	}
7775 	iwn_nic_unlock(sc);
7776 
7777 	/* Configure WiMAX coexistence for combo adapters. */
7778 	error = iwn5000_send_wimax_coex(sc);
7779 	if (error != 0) {
7780 		device_printf(sc->sc_dev,
7781 		    "%s: could not configure WiMAX coexistence, error %d\n",
7782 		    __func__, error);
7783 		return error;
7784 	}
7785 	if (sc->hw_type != IWN_HW_REV_TYPE_5150) {
7786 		/* Perform crystal calibration. */
7787 		error = iwn5000_crystal_calib(sc);
7788 		if (error != 0) {
7789 			device_printf(sc->sc_dev,
7790 			    "%s: crystal calibration failed, error %d\n",
7791 			    __func__, error);
7792 			return error;
7793 		}
7794 	}
7795 	if (!(sc->sc_flags & IWN_FLAG_CALIB_DONE)) {
7796 		/* Query calibration from the initialization firmware. */
7797 		if ((error = iwn5000_query_calibration(sc)) != 0) {
7798 			device_printf(sc->sc_dev,
7799 			    "%s: could not query calibration, error %d\n",
7800 			    __func__, error);
7801 			return error;
7802 		}
7803 		/*
7804 		 * We have the calibration results now, reboot with the
7805 		 * runtime firmware (call ourselves recursively!)
7806 		 */
7807 		iwn_hw_stop(sc);
7808 		error = iwn_hw_init(sc);
7809 	} else {
7810 		/* Send calibration results to runtime firmware. */
7811 		error = iwn5000_send_calibration(sc);
7812 	}
7813 
7814 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
7815 
7816 	return error;
7817 }
7818 
7819 /*
7820  * The firmware boot code is small and is intended to be copied directly into
7821  * the NIC internal memory (no DMA transfer).
7822  */
7823 static int
7824 iwn4965_load_bootcode(struct iwn_softc *sc, const uint8_t *ucode, int size)
7825 {
7826 	int error, ntries;
7827 
7828 	size /= sizeof (uint32_t);
7829 
7830 	if ((error = iwn_nic_lock(sc)) != 0)
7831 		return error;
7832 
7833 	/* Copy microcode image into NIC memory. */
7834 	iwn_prph_write_region_4(sc, IWN_BSM_SRAM_BASE,
7835 	    (const uint32_t *)ucode, size);
7836 
7837 	iwn_prph_write(sc, IWN_BSM_WR_MEM_SRC, 0);
7838 	iwn_prph_write(sc, IWN_BSM_WR_MEM_DST, IWN_FW_TEXT_BASE);
7839 	iwn_prph_write(sc, IWN_BSM_WR_DWCOUNT, size);
7840 
7841 	/* Start boot load now. */
7842 	iwn_prph_write(sc, IWN_BSM_WR_CTRL, IWN_BSM_WR_CTRL_START);
7843 
7844 	/* Wait for transfer to complete. */
7845 	for (ntries = 0; ntries < 1000; ntries++) {
7846 		if (!(iwn_prph_read(sc, IWN_BSM_WR_CTRL) &
7847 		    IWN_BSM_WR_CTRL_START))
7848 			break;
7849 		DELAY(10);
7850 	}
7851 	if (ntries == 1000) {
7852 		device_printf(sc->sc_dev, "%s: could not load boot firmware\n",
7853 		    __func__);
7854 		iwn_nic_unlock(sc);
7855 		return ETIMEDOUT;
7856 	}
7857 
7858 	/* Enable boot after power up. */
7859 	iwn_prph_write(sc, IWN_BSM_WR_CTRL, IWN_BSM_WR_CTRL_START_EN);
7860 
7861 	iwn_nic_unlock(sc);
7862 	return 0;
7863 }
7864 
7865 static int
7866 iwn4965_load_firmware(struct iwn_softc *sc)
7867 {
7868 	struct iwn_fw_info *fw = &sc->fw;
7869 	struct iwn_dma_info *dma = &sc->fw_dma;
7870 	int error;
7871 
7872 	/* Copy initialization sections into pre-allocated DMA-safe memory. */
7873 	memcpy(dma->vaddr, fw->init.data, fw->init.datasz);
7874 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
7875 	memcpy(dma->vaddr + IWN4965_FW_DATA_MAXSZ,
7876 	    fw->init.text, fw->init.textsz);
7877 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
7878 
7879 	/* Tell adapter where to find initialization sections. */
7880 	if ((error = iwn_nic_lock(sc)) != 0)
7881 		return error;
7882 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_ADDR, dma->paddr >> 4);
7883 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_SIZE, fw->init.datasz);
7884 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_ADDR,
7885 	    (dma->paddr + IWN4965_FW_DATA_MAXSZ) >> 4);
7886 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_SIZE, fw->init.textsz);
7887 	iwn_nic_unlock(sc);
7888 
7889 	/* Load firmware boot code. */
7890 	error = iwn4965_load_bootcode(sc, fw->boot.text, fw->boot.textsz);
7891 	if (error != 0) {
7892 		device_printf(sc->sc_dev, "%s: could not load boot firmware\n",
7893 		    __func__);
7894 		return error;
7895 	}
7896 	/* Now press "execute". */
7897 	IWN_WRITE(sc, IWN_RESET, 0);
7898 
7899 	/* Wait at most one second for first alive notification. */
7900 	if ((error = msleep(sc, &sc->sc_mtx, PCATCH, "iwninit", hz)) != 0) {
7901 		device_printf(sc->sc_dev,
7902 		    "%s: timeout waiting for adapter to initialize, error %d\n",
7903 		    __func__, error);
7904 		return error;
7905 	}
7906 
7907 	/* Retrieve current temperature for initial TX power calibration. */
7908 	sc->rawtemp = sc->ucode_info.temp[3].chan20MHz;
7909 	sc->temp = iwn4965_get_temperature(sc);
7910 
7911 	/* Copy runtime sections into pre-allocated DMA-safe memory. */
7912 	memcpy(dma->vaddr, fw->main.data, fw->main.datasz);
7913 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
7914 	memcpy(dma->vaddr + IWN4965_FW_DATA_MAXSZ,
7915 	    fw->main.text, fw->main.textsz);
7916 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
7917 
7918 	/* Tell adapter where to find runtime sections. */
7919 	if ((error = iwn_nic_lock(sc)) != 0)
7920 		return error;
7921 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_ADDR, dma->paddr >> 4);
7922 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_SIZE, fw->main.datasz);
7923 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_ADDR,
7924 	    (dma->paddr + IWN4965_FW_DATA_MAXSZ) >> 4);
7925 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_SIZE,
7926 	    IWN_FW_UPDATED | fw->main.textsz);
7927 	iwn_nic_unlock(sc);
7928 
7929 	return 0;
7930 }
7931 
7932 static int
7933 iwn5000_load_firmware_section(struct iwn_softc *sc, uint32_t dst,
7934     const uint8_t *section, int size)
7935 {
7936 	struct iwn_dma_info *dma = &sc->fw_dma;
7937 	int error;
7938 
7939 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7940 
7941 	/* Copy firmware section into pre-allocated DMA-safe memory. */
7942 	memcpy(dma->vaddr, section, size);
7943 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
7944 
7945 	if ((error = iwn_nic_lock(sc)) != 0)
7946 		return error;
7947 
7948 	IWN_WRITE(sc, IWN_FH_TX_CONFIG(IWN_SRVC_DMACHNL),
7949 	    IWN_FH_TX_CONFIG_DMA_PAUSE);
7950 
7951 	IWN_WRITE(sc, IWN_FH_SRAM_ADDR(IWN_SRVC_DMACHNL), dst);
7952 	IWN_WRITE(sc, IWN_FH_TFBD_CTRL0(IWN_SRVC_DMACHNL),
7953 	    IWN_LOADDR(dma->paddr));
7954 	IWN_WRITE(sc, IWN_FH_TFBD_CTRL1(IWN_SRVC_DMACHNL),
7955 	    IWN_HIADDR(dma->paddr) << 28 | size);
7956 	IWN_WRITE(sc, IWN_FH_TXBUF_STATUS(IWN_SRVC_DMACHNL),
7957 	    IWN_FH_TXBUF_STATUS_TBNUM(1) |
7958 	    IWN_FH_TXBUF_STATUS_TBIDX(1) |
7959 	    IWN_FH_TXBUF_STATUS_TFBD_VALID);
7960 
7961 	/* Kick Flow Handler to start DMA transfer. */
7962 	IWN_WRITE(sc, IWN_FH_TX_CONFIG(IWN_SRVC_DMACHNL),
7963 	    IWN_FH_TX_CONFIG_DMA_ENA | IWN_FH_TX_CONFIG_CIRQ_HOST_ENDTFD);
7964 
7965 	iwn_nic_unlock(sc);
7966 
7967 	/* Wait at most five seconds for FH DMA transfer to complete. */
7968 	return msleep(sc, &sc->sc_mtx, PCATCH, "iwninit", 5 * hz);
7969 }
7970 
7971 static int
7972 iwn5000_load_firmware(struct iwn_softc *sc)
7973 {
7974 	struct iwn_fw_part *fw;
7975 	int error;
7976 
7977 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7978 
7979 	/* Load the initialization firmware on first boot only. */
7980 	fw = (sc->sc_flags & IWN_FLAG_CALIB_DONE) ?
7981 	    &sc->fw.main : &sc->fw.init;
7982 
7983 	error = iwn5000_load_firmware_section(sc, IWN_FW_TEXT_BASE,
7984 	    fw->text, fw->textsz);
7985 	if (error != 0) {
7986 		device_printf(sc->sc_dev,
7987 		    "%s: could not load firmware %s section, error %d\n",
7988 		    __func__, ".text", error);
7989 		return error;
7990 	}
7991 	error = iwn5000_load_firmware_section(sc, IWN_FW_DATA_BASE,
7992 	    fw->data, fw->datasz);
7993 	if (error != 0) {
7994 		device_printf(sc->sc_dev,
7995 		    "%s: could not load firmware %s section, error %d\n",
7996 		    __func__, ".data", error);
7997 		return error;
7998 	}
7999 
8000 	/* Now press "execute". */
8001 	IWN_WRITE(sc, IWN_RESET, 0);
8002 	return 0;
8003 }
8004 
8005 /*
8006  * Extract text and data sections from a legacy firmware image.
8007  */
8008 static int
8009 iwn_read_firmware_leg(struct iwn_softc *sc, struct iwn_fw_info *fw)
8010 {
8011 	const uint32_t *ptr;
8012 	size_t hdrlen = 24;
8013 	uint32_t rev;
8014 
8015 	ptr = (const uint32_t *)fw->data;
8016 	rev = le32toh(*ptr++);
8017 
8018 	sc->ucode_rev = rev;
8019 
8020 	/* Check firmware API version. */
8021 	if (IWN_FW_API(rev) <= 1) {
8022 		device_printf(sc->sc_dev,
8023 		    "%s: bad firmware, need API version >=2\n", __func__);
8024 		return EINVAL;
8025 	}
8026 	if (IWN_FW_API(rev) >= 3) {
8027 		/* Skip build number (version 2 header). */
8028 		hdrlen += 4;
8029 		ptr++;
8030 	}
8031 	if (fw->size < hdrlen) {
8032 		device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
8033 		    __func__, fw->size);
8034 		return EINVAL;
8035 	}
8036 	fw->main.textsz = le32toh(*ptr++);
8037 	fw->main.datasz = le32toh(*ptr++);
8038 	fw->init.textsz = le32toh(*ptr++);
8039 	fw->init.datasz = le32toh(*ptr++);
8040 	fw->boot.textsz = le32toh(*ptr++);
8041 
8042 	/* Check that all firmware sections fit. */
8043 	if (fw->size < hdrlen + fw->main.textsz + fw->main.datasz +
8044 	    fw->init.textsz + fw->init.datasz + fw->boot.textsz) {
8045 		device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
8046 		    __func__, fw->size);
8047 		return EINVAL;
8048 	}
8049 
8050 	/* Get pointers to firmware sections. */
8051 	fw->main.text = (const uint8_t *)ptr;
8052 	fw->main.data = fw->main.text + fw->main.textsz;
8053 	fw->init.text = fw->main.data + fw->main.datasz;
8054 	fw->init.data = fw->init.text + fw->init.textsz;
8055 	fw->boot.text = fw->init.data + fw->init.datasz;
8056 	return 0;
8057 }
8058 
8059 /*
8060  * Extract text and data sections from a TLV firmware image.
8061  */
8062 static int
8063 iwn_read_firmware_tlv(struct iwn_softc *sc, struct iwn_fw_info *fw,
8064     uint16_t alt)
8065 {
8066 	const struct iwn_fw_tlv_hdr *hdr;
8067 	const struct iwn_fw_tlv *tlv;
8068 	const uint8_t *ptr, *end;
8069 	uint64_t altmask;
8070 	uint32_t len, tmp;
8071 
8072 	if (fw->size < sizeof (*hdr)) {
8073 		device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
8074 		    __func__, fw->size);
8075 		return EINVAL;
8076 	}
8077 	hdr = (const struct iwn_fw_tlv_hdr *)fw->data;
8078 	if (hdr->signature != htole32(IWN_FW_SIGNATURE)) {
8079 		device_printf(sc->sc_dev, "%s: bad firmware signature 0x%08x\n",
8080 		    __func__, le32toh(hdr->signature));
8081 		return EINVAL;
8082 	}
8083 	DPRINTF(sc, IWN_DEBUG_RESET, "FW: \"%.64s\", build 0x%x\n", hdr->descr,
8084 	    le32toh(hdr->build));
8085 	sc->ucode_rev = le32toh(hdr->rev);
8086 
8087 	/*
8088 	 * Select the closest supported alternative that is less than
8089 	 * or equal to the specified one.
8090 	 */
8091 	altmask = le64toh(hdr->altmask);
8092 	while (alt > 0 && !(altmask & (1ULL << alt)))
8093 		alt--;	/* Downgrade. */
8094 	DPRINTF(sc, IWN_DEBUG_RESET, "using alternative %d\n", alt);
8095 
8096 	ptr = (const uint8_t *)(hdr + 1);
8097 	end = (const uint8_t *)(fw->data + fw->size);
8098 
8099 	/* Parse type-length-value fields. */
8100 	while (ptr + sizeof (*tlv) <= end) {
8101 		tlv = (const struct iwn_fw_tlv *)ptr;
8102 		len = le32toh(tlv->len);
8103 
8104 		ptr += sizeof (*tlv);
8105 		if (ptr + len > end) {
8106 			device_printf(sc->sc_dev,
8107 			    "%s: firmware too short: %zu bytes\n", __func__,
8108 			    fw->size);
8109 			return EINVAL;
8110 		}
8111 		/* Skip other alternatives. */
8112 		if (tlv->alt != 0 && tlv->alt != htole16(alt))
8113 			goto next;
8114 
8115 		switch (le16toh(tlv->type)) {
8116 		case IWN_FW_TLV_MAIN_TEXT:
8117 			fw->main.text = ptr;
8118 			fw->main.textsz = len;
8119 			break;
8120 		case IWN_FW_TLV_MAIN_DATA:
8121 			fw->main.data = ptr;
8122 			fw->main.datasz = len;
8123 			break;
8124 		case IWN_FW_TLV_INIT_TEXT:
8125 			fw->init.text = ptr;
8126 			fw->init.textsz = len;
8127 			break;
8128 		case IWN_FW_TLV_INIT_DATA:
8129 			fw->init.data = ptr;
8130 			fw->init.datasz = len;
8131 			break;
8132 		case IWN_FW_TLV_BOOT_TEXT:
8133 			fw->boot.text = ptr;
8134 			fw->boot.textsz = len;
8135 			break;
8136 		case IWN_FW_TLV_ENH_SENS:
8137 			if (!len)
8138 				sc->sc_flags |= IWN_FLAG_ENH_SENS;
8139 			break;
8140 		case IWN_FW_TLV_PHY_CALIB:
8141 			tmp = le32toh(*ptr);
8142 			if (tmp < 253) {
8143 				sc->reset_noise_gain = tmp;
8144 				sc->noise_gain = tmp + 1;
8145 			}
8146 			break;
8147 		case IWN_FW_TLV_PAN:
8148 			sc->sc_flags |= IWN_FLAG_PAN_SUPPORT;
8149 			DPRINTF(sc, IWN_DEBUG_RESET,
8150 			    "PAN Support found: %d\n", 1);
8151 			break;
8152 		case IWN_FW_TLV_FLAGS:
8153 			if (len < sizeof(uint32_t))
8154 				break;
8155 			if (len % sizeof(uint32_t))
8156 				break;
8157 			sc->tlv_feature_flags = le32toh(*ptr);
8158 			DPRINTF(sc, IWN_DEBUG_RESET,
8159 			    "%s: feature: 0x%08x\n",
8160 			    __func__,
8161 			    sc->tlv_feature_flags);
8162 			break;
8163 		case IWN_FW_TLV_PBREQ_MAXLEN:
8164 		case IWN_FW_TLV_RUNT_EVTLOG_PTR:
8165 		case IWN_FW_TLV_RUNT_EVTLOG_SIZE:
8166 		case IWN_FW_TLV_RUNT_ERRLOG_PTR:
8167 		case IWN_FW_TLV_INIT_EVTLOG_PTR:
8168 		case IWN_FW_TLV_INIT_EVTLOG_SIZE:
8169 		case IWN_FW_TLV_INIT_ERRLOG_PTR:
8170 		case IWN_FW_TLV_WOWLAN_INST:
8171 		case IWN_FW_TLV_WOWLAN_DATA:
8172 			DPRINTF(sc, IWN_DEBUG_RESET,
8173 			    "TLV type %d recognized but not handled\n",
8174 			    le16toh(tlv->type));
8175 			break;
8176 		default:
8177 			DPRINTF(sc, IWN_DEBUG_RESET,
8178 			    "TLV type %d not handled\n", le16toh(tlv->type));
8179 			break;
8180 		}
8181  next:		/* TLV fields are 32-bit aligned. */
8182 		ptr += (len + 3) & ~3;
8183 	}
8184 	return 0;
8185 }
8186 
8187 static int
8188 iwn_read_firmware(struct iwn_softc *sc)
8189 {
8190 	struct iwn_fw_info *fw = &sc->fw;
8191 	int error;
8192 
8193 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8194 
8195 	IWN_UNLOCK(sc);
8196 
8197 	memset(fw, 0, sizeof (*fw));
8198 
8199 	/* Read firmware image from filesystem. */
8200 	sc->fw_fp = firmware_get(sc->fwname);
8201 	if (sc->fw_fp == NULL) {
8202 		device_printf(sc->sc_dev, "%s: could not read firmware %s\n",
8203 		    __func__, sc->fwname);
8204 		IWN_LOCK(sc);
8205 		return EINVAL;
8206 	}
8207 	IWN_LOCK(sc);
8208 
8209 	fw->size = sc->fw_fp->datasize;
8210 	fw->data = (const uint8_t *)sc->fw_fp->data;
8211 	if (fw->size < sizeof (uint32_t)) {
8212 		device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
8213 		    __func__, fw->size);
8214 		firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
8215 		sc->fw_fp = NULL;
8216 		return EINVAL;
8217 	}
8218 
8219 	/* Retrieve text and data sections. */
8220 	if (*(const uint32_t *)fw->data != 0)	/* Legacy image. */
8221 		error = iwn_read_firmware_leg(sc, fw);
8222 	else
8223 		error = iwn_read_firmware_tlv(sc, fw, 1);
8224 	if (error != 0) {
8225 		device_printf(sc->sc_dev,
8226 		    "%s: could not read firmware sections, error %d\n",
8227 		    __func__, error);
8228 		firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
8229 		sc->fw_fp = NULL;
8230 		return error;
8231 	}
8232 
8233 	device_printf(sc->sc_dev, "%s: ucode rev=0x%08x\n", __func__, sc->ucode_rev);
8234 
8235 	/* Make sure text and data sections fit in hardware memory. */
8236 	if (fw->main.textsz > sc->fw_text_maxsz ||
8237 	    fw->main.datasz > sc->fw_data_maxsz ||
8238 	    fw->init.textsz > sc->fw_text_maxsz ||
8239 	    fw->init.datasz > sc->fw_data_maxsz ||
8240 	    fw->boot.textsz > IWN_FW_BOOT_TEXT_MAXSZ ||
8241 	    (fw->boot.textsz & 3) != 0) {
8242 		device_printf(sc->sc_dev, "%s: firmware sections too large\n",
8243 		    __func__);
8244 		firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
8245 		sc->fw_fp = NULL;
8246 		return EINVAL;
8247 	}
8248 
8249 	/* We can proceed with loading the firmware. */
8250 	return 0;
8251 }
8252 
8253 static int
8254 iwn_clock_wait(struct iwn_softc *sc)
8255 {
8256 	int ntries;
8257 
8258 	/* Set "initialization complete" bit. */
8259 	IWN_SETBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_INIT_DONE);
8260 
8261 	/* Wait for clock stabilization. */
8262 	for (ntries = 0; ntries < 2500; ntries++) {
8263 		if (IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_MAC_CLOCK_READY)
8264 			return 0;
8265 		DELAY(10);
8266 	}
8267 	device_printf(sc->sc_dev,
8268 	    "%s: timeout waiting for clock stabilization\n", __func__);
8269 	return ETIMEDOUT;
8270 }
8271 
8272 static int
8273 iwn_apm_init(struct iwn_softc *sc)
8274 {
8275 	uint32_t reg;
8276 	int error;
8277 
8278 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8279 
8280 	/* Disable L0s exit timer (NMI bug workaround). */
8281 	IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_DIS_L0S_TIMER);
8282 	/* Don't wait for ICH L0s (ICH bug workaround). */
8283 	IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_L1A_NO_L0S_RX);
8284 
8285 	/* Set FH wait threshold to max (HW bug under stress workaround). */
8286 	IWN_SETBITS(sc, IWN_DBG_HPET_MEM, 0xffff0000);
8287 
8288 	/* Enable HAP INTA to move adapter from L1a to L0s. */
8289 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_HAP_WAKE_L1A);
8290 
8291 	/* Retrieve PCIe Active State Power Management (ASPM). */
8292 	reg = pci_read_config(sc->sc_dev, sc->sc_cap_off + 0x10, 1);
8293 	/* Workaround for HW instability in PCIe L0->L0s->L1 transition. */
8294 	if (reg & 0x02)	/* L1 Entry enabled. */
8295 		IWN_SETBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA);
8296 	else
8297 		IWN_CLRBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA);
8298 
8299 	if (sc->base_params->pll_cfg_val)
8300 		IWN_SETBITS(sc, IWN_ANA_PLL, sc->base_params->pll_cfg_val);
8301 
8302 	/* Wait for clock stabilization before accessing prph. */
8303 	if ((error = iwn_clock_wait(sc)) != 0)
8304 		return error;
8305 
8306 	if ((error = iwn_nic_lock(sc)) != 0)
8307 		return error;
8308 	if (sc->hw_type == IWN_HW_REV_TYPE_4965) {
8309 		/* Enable DMA and BSM (Bootstrap State Machine). */
8310 		iwn_prph_write(sc, IWN_APMG_CLK_EN,
8311 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT |
8312 		    IWN_APMG_CLK_CTRL_BSM_CLK_RQT);
8313 	} else {
8314 		/* Enable DMA. */
8315 		iwn_prph_write(sc, IWN_APMG_CLK_EN,
8316 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT);
8317 	}
8318 	DELAY(20);
8319 	/* Disable L1-Active. */
8320 	iwn_prph_setbits(sc, IWN_APMG_PCI_STT, IWN_APMG_PCI_STT_L1A_DIS);
8321 	iwn_nic_unlock(sc);
8322 
8323 	return 0;
8324 }
8325 
8326 static void
8327 iwn_apm_stop_master(struct iwn_softc *sc)
8328 {
8329 	int ntries;
8330 
8331 	/* Stop busmaster DMA activity. */
8332 	IWN_SETBITS(sc, IWN_RESET, IWN_RESET_STOP_MASTER);
8333 	for (ntries = 0; ntries < 100; ntries++) {
8334 		if (IWN_READ(sc, IWN_RESET) & IWN_RESET_MASTER_DISABLED)
8335 			return;
8336 		DELAY(10);
8337 	}
8338 	device_printf(sc->sc_dev, "%s: timeout waiting for master\n", __func__);
8339 }
8340 
8341 static void
8342 iwn_apm_stop(struct iwn_softc *sc)
8343 {
8344 	iwn_apm_stop_master(sc);
8345 
8346 	/* Reset the entire device. */
8347 	IWN_SETBITS(sc, IWN_RESET, IWN_RESET_SW);
8348 	DELAY(10);
8349 	/* Clear "initialization complete" bit. */
8350 	IWN_CLRBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_INIT_DONE);
8351 }
8352 
8353 static int
8354 iwn4965_nic_config(struct iwn_softc *sc)
8355 {
8356 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8357 
8358 	if (IWN_RFCFG_TYPE(sc->rfcfg) == 1) {
8359 		/*
8360 		 * I don't believe this to be correct but this is what the
8361 		 * vendor driver is doing. Probably the bits should not be
8362 		 * shifted in IWN_RFCFG_*.
8363 		 */
8364 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
8365 		    IWN_RFCFG_TYPE(sc->rfcfg) |
8366 		    IWN_RFCFG_STEP(sc->rfcfg) |
8367 		    IWN_RFCFG_DASH(sc->rfcfg));
8368 	}
8369 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
8370 	    IWN_HW_IF_CONFIG_RADIO_SI | IWN_HW_IF_CONFIG_MAC_SI);
8371 	return 0;
8372 }
8373 
8374 static int
8375 iwn5000_nic_config(struct iwn_softc *sc)
8376 {
8377 	uint32_t tmp;
8378 	int error;
8379 
8380 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8381 
8382 	if (IWN_RFCFG_TYPE(sc->rfcfg) < 3) {
8383 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
8384 		    IWN_RFCFG_TYPE(sc->rfcfg) |
8385 		    IWN_RFCFG_STEP(sc->rfcfg) |
8386 		    IWN_RFCFG_DASH(sc->rfcfg));
8387 	}
8388 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
8389 	    IWN_HW_IF_CONFIG_RADIO_SI | IWN_HW_IF_CONFIG_MAC_SI);
8390 
8391 	if ((error = iwn_nic_lock(sc)) != 0)
8392 		return error;
8393 	iwn_prph_setbits(sc, IWN_APMG_PS, IWN_APMG_PS_EARLY_PWROFF_DIS);
8394 
8395 	if (sc->hw_type == IWN_HW_REV_TYPE_1000) {
8396 		/*
8397 		 * Select first Switching Voltage Regulator (1.32V) to
8398 		 * solve a stability issue related to noisy DC2DC line
8399 		 * in the silicon of 1000 Series.
8400 		 */
8401 		tmp = iwn_prph_read(sc, IWN_APMG_DIGITAL_SVR);
8402 		tmp &= ~IWN_APMG_DIGITAL_SVR_VOLTAGE_MASK;
8403 		tmp |= IWN_APMG_DIGITAL_SVR_VOLTAGE_1_32;
8404 		iwn_prph_write(sc, IWN_APMG_DIGITAL_SVR, tmp);
8405 	}
8406 	iwn_nic_unlock(sc);
8407 
8408 	if (sc->sc_flags & IWN_FLAG_INTERNAL_PA) {
8409 		/* Use internal power amplifier only. */
8410 		IWN_WRITE(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_RADIO_2X2_IPA);
8411 	}
8412 	if (sc->base_params->additional_nic_config && sc->calib_ver >= 6) {
8413 		/* Indicate that ROM calibration version is >=6. */
8414 		IWN_SETBITS(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_CALIB_VER6);
8415 	}
8416 	if (sc->base_params->additional_gp_drv_bit)
8417 		IWN_SETBITS(sc, IWN_GP_DRIVER,
8418 		    sc->base_params->additional_gp_drv_bit);
8419 	return 0;
8420 }
8421 
8422 /*
8423  * Take NIC ownership over Intel Active Management Technology (AMT).
8424  */
8425 static int
8426 iwn_hw_prepare(struct iwn_softc *sc)
8427 {
8428 	int ntries;
8429 
8430 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8431 
8432 	/* Check if hardware is ready. */
8433 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_NIC_READY);
8434 	for (ntries = 0; ntries < 5; ntries++) {
8435 		if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
8436 		    IWN_HW_IF_CONFIG_NIC_READY)
8437 			return 0;
8438 		DELAY(10);
8439 	}
8440 
8441 	/* Hardware not ready, force into ready state. */
8442 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_PREPARE);
8443 	for (ntries = 0; ntries < 15000; ntries++) {
8444 		if (!(IWN_READ(sc, IWN_HW_IF_CONFIG) &
8445 		    IWN_HW_IF_CONFIG_PREPARE_DONE))
8446 			break;
8447 		DELAY(10);
8448 	}
8449 	if (ntries == 15000)
8450 		return ETIMEDOUT;
8451 
8452 	/* Hardware should be ready now. */
8453 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_NIC_READY);
8454 	for (ntries = 0; ntries < 5; ntries++) {
8455 		if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
8456 		    IWN_HW_IF_CONFIG_NIC_READY)
8457 			return 0;
8458 		DELAY(10);
8459 	}
8460 	return ETIMEDOUT;
8461 }
8462 
8463 static int
8464 iwn_hw_init(struct iwn_softc *sc)
8465 {
8466 	struct iwn_ops *ops = &sc->ops;
8467 	int error, chnl, qid;
8468 
8469 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
8470 
8471 	/* Clear pending interrupts. */
8472 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
8473 
8474 	if ((error = iwn_apm_init(sc)) != 0) {
8475 		device_printf(sc->sc_dev,
8476 		    "%s: could not power ON adapter, error %d\n", __func__,
8477 		    error);
8478 		return error;
8479 	}
8480 
8481 	/* Select VMAIN power source. */
8482 	if ((error = iwn_nic_lock(sc)) != 0)
8483 		return error;
8484 	iwn_prph_clrbits(sc, IWN_APMG_PS, IWN_APMG_PS_PWR_SRC_MASK);
8485 	iwn_nic_unlock(sc);
8486 
8487 	/* Perform adapter-specific initialization. */
8488 	if ((error = ops->nic_config(sc)) != 0)
8489 		return error;
8490 
8491 	/* Initialize RX ring. */
8492 	if ((error = iwn_nic_lock(sc)) != 0)
8493 		return error;
8494 	IWN_WRITE(sc, IWN_FH_RX_CONFIG, 0);
8495 	IWN_WRITE(sc, IWN_FH_RX_WPTR, 0);
8496 	/* Set physical address of RX ring (256-byte aligned). */
8497 	IWN_WRITE(sc, IWN_FH_RX_BASE, sc->rxq.desc_dma.paddr >> 8);
8498 	/* Set physical address of RX status (16-byte aligned). */
8499 	IWN_WRITE(sc, IWN_FH_STATUS_WPTR, sc->rxq.stat_dma.paddr >> 4);
8500 	/* Enable RX. */
8501 	IWN_WRITE(sc, IWN_FH_RX_CONFIG,
8502 	    IWN_FH_RX_CONFIG_ENA           |
8503 	    IWN_FH_RX_CONFIG_IGN_RXF_EMPTY |	/* HW bug workaround */
8504 	    IWN_FH_RX_CONFIG_IRQ_DST_HOST  |
8505 	    IWN_FH_RX_CONFIG_SINGLE_FRAME  |
8506 	    IWN_FH_RX_CONFIG_RB_TIMEOUT(0) |
8507 	    IWN_FH_RX_CONFIG_NRBD(IWN_RX_RING_COUNT_LOG));
8508 	iwn_nic_unlock(sc);
8509 	IWN_WRITE(sc, IWN_FH_RX_WPTR, (IWN_RX_RING_COUNT - 1) & ~7);
8510 
8511 	if ((error = iwn_nic_lock(sc)) != 0)
8512 		return error;
8513 
8514 	/* Initialize TX scheduler. */
8515 	iwn_prph_write(sc, sc->sched_txfact_addr, 0);
8516 
8517 	/* Set physical address of "keep warm" page (16-byte aligned). */
8518 	IWN_WRITE(sc, IWN_FH_KW_ADDR, sc->kw_dma.paddr >> 4);
8519 
8520 	/* Initialize TX rings. */
8521 	for (qid = 0; qid < sc->ntxqs; qid++) {
8522 		struct iwn_tx_ring *txq = &sc->txq[qid];
8523 
8524 		/* Set physical address of TX ring (256-byte aligned). */
8525 		IWN_WRITE(sc, IWN_FH_CBBC_QUEUE(qid),
8526 		    txq->desc_dma.paddr >> 8);
8527 	}
8528 	iwn_nic_unlock(sc);
8529 
8530 	/* Enable DMA channels. */
8531 	for (chnl = 0; chnl < sc->ndmachnls; chnl++) {
8532 		IWN_WRITE(sc, IWN_FH_TX_CONFIG(chnl),
8533 		    IWN_FH_TX_CONFIG_DMA_ENA |
8534 		    IWN_FH_TX_CONFIG_DMA_CREDIT_ENA);
8535 	}
8536 
8537 	/* Clear "radio off" and "commands blocked" bits. */
8538 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
8539 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CMD_BLOCKED);
8540 
8541 	/* Clear pending interrupts. */
8542 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
8543 	/* Enable interrupt coalescing. */
8544 	IWN_WRITE(sc, IWN_INT_COALESCING, 512 / 8);
8545 	/* Enable interrupts. */
8546 	IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
8547 
8548 	/* _Really_ make sure "radio off" bit is cleared! */
8549 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
8550 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
8551 
8552 	/* Enable shadow registers. */
8553 	if (sc->base_params->shadow_reg_enable)
8554 		IWN_SETBITS(sc, IWN_SHADOW_REG_CTRL, 0x800fffff);
8555 
8556 	if ((error = ops->load_firmware(sc)) != 0) {
8557 		device_printf(sc->sc_dev,
8558 		    "%s: could not load firmware, error %d\n", __func__,
8559 		    error);
8560 		return error;
8561 	}
8562 	/* Wait at most one second for firmware alive notification. */
8563 	if ((error = msleep(sc, &sc->sc_mtx, PCATCH, "iwninit", hz)) != 0) {
8564 		device_printf(sc->sc_dev,
8565 		    "%s: timeout waiting for adapter to initialize, error %d\n",
8566 		    __func__, error);
8567 		return error;
8568 	}
8569 	/* Do post-firmware initialization. */
8570 
8571 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
8572 
8573 	return ops->post_alive(sc);
8574 }
8575 
8576 static void
8577 iwn_hw_stop(struct iwn_softc *sc)
8578 {
8579 	int chnl, qid, ntries;
8580 
8581 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8582 
8583 	IWN_WRITE(sc, IWN_RESET, IWN_RESET_NEVO);
8584 
8585 	/* Disable interrupts. */
8586 	IWN_WRITE(sc, IWN_INT_MASK, 0);
8587 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
8588 	IWN_WRITE(sc, IWN_FH_INT, 0xffffffff);
8589 	sc->sc_flags &= ~IWN_FLAG_USE_ICT;
8590 
8591 	/* Make sure we no longer hold the NIC lock. */
8592 	iwn_nic_unlock(sc);
8593 
8594 	/* Stop TX scheduler. */
8595 	iwn_prph_write(sc, sc->sched_txfact_addr, 0);
8596 
8597 	/* Stop all DMA channels. */
8598 	if (iwn_nic_lock(sc) == 0) {
8599 		for (chnl = 0; chnl < sc->ndmachnls; chnl++) {
8600 			IWN_WRITE(sc, IWN_FH_TX_CONFIG(chnl), 0);
8601 			for (ntries = 0; ntries < 200; ntries++) {
8602 				if (IWN_READ(sc, IWN_FH_TX_STATUS) &
8603 				    IWN_FH_TX_STATUS_IDLE(chnl))
8604 					break;
8605 				DELAY(10);
8606 			}
8607 		}
8608 		iwn_nic_unlock(sc);
8609 	}
8610 
8611 	/* Stop RX ring. */
8612 	iwn_reset_rx_ring(sc, &sc->rxq);
8613 
8614 	/* Reset all TX rings. */
8615 	for (qid = 0; qid < sc->ntxqs; qid++)
8616 		iwn_reset_tx_ring(sc, &sc->txq[qid]);
8617 
8618 	if (iwn_nic_lock(sc) == 0) {
8619 		iwn_prph_write(sc, IWN_APMG_CLK_DIS,
8620 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT);
8621 		iwn_nic_unlock(sc);
8622 	}
8623 	DELAY(5);
8624 	/* Power OFF adapter. */
8625 	iwn_apm_stop(sc);
8626 }
8627 
8628 static void
8629 iwn_radio_on(void *arg0, int pending)
8630 {
8631 	struct iwn_softc *sc = arg0;
8632 	struct ieee80211com *ic = &sc->sc_ic;
8633 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
8634 
8635 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8636 
8637 	if (vap != NULL) {
8638 		iwn_init(sc);
8639 		ieee80211_init(vap);
8640 	}
8641 }
8642 
8643 static void
8644 iwn_radio_off(void *arg0, int pending)
8645 {
8646 	struct iwn_softc *sc = arg0;
8647 	struct ieee80211com *ic = &sc->sc_ic;
8648 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
8649 
8650 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8651 
8652 	iwn_stop(sc);
8653 	if (vap != NULL)
8654 		ieee80211_stop(vap);
8655 
8656 	/* Enable interrupts to get RF toggle notification. */
8657 	IWN_LOCK(sc);
8658 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
8659 	IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
8660 	IWN_UNLOCK(sc);
8661 }
8662 
8663 static void
8664 iwn_panicked(void *arg0, int pending)
8665 {
8666 	struct iwn_softc *sc = arg0;
8667 	struct ieee80211com *ic = &sc->sc_ic;
8668 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
8669 	int error;
8670 
8671 	if (vap == NULL) {
8672 		printf("%s: null vap\n", __func__);
8673 		return;
8674 	}
8675 
8676 	device_printf(sc->sc_dev, "%s: controller panicked, iv_state = %d; "
8677 	    "resetting...\n", __func__, vap->iv_state);
8678 
8679 	IWN_LOCK(sc);
8680 
8681 	iwn_stop_locked(sc);
8682 	iwn_init_locked(sc);
8683 	if (vap->iv_state >= IEEE80211_S_AUTH &&
8684 	    (error = iwn_auth(sc, vap)) != 0) {
8685 		device_printf(sc->sc_dev,
8686 		    "%s: could not move to auth state\n", __func__);
8687 	}
8688 	if (vap->iv_state >= IEEE80211_S_RUN &&
8689 	    (error = iwn_run(sc, vap)) != 0) {
8690 		device_printf(sc->sc_dev,
8691 		    "%s: could not move to run state\n", __func__);
8692 	}
8693 
8694 	IWN_UNLOCK(sc);
8695 }
8696 
8697 static void
8698 iwn_init_locked(struct iwn_softc *sc)
8699 {
8700 	int error;
8701 
8702 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
8703 
8704 	IWN_LOCK_ASSERT(sc);
8705 
8706 	sc->sc_flags |= IWN_FLAG_RUNNING;
8707 
8708 	if ((error = iwn_hw_prepare(sc)) != 0) {
8709 		device_printf(sc->sc_dev, "%s: hardware not ready, error %d\n",
8710 		    __func__, error);
8711 		goto fail;
8712 	}
8713 
8714 	/* Initialize interrupt mask to default value. */
8715 	sc->int_mask = IWN_INT_MASK_DEF;
8716 	sc->sc_flags &= ~IWN_FLAG_USE_ICT;
8717 
8718 	/* Check that the radio is not disabled by hardware switch. */
8719 	if (!(IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_RFKILL)) {
8720 		device_printf(sc->sc_dev,
8721 		    "radio is disabled by hardware switch\n");
8722 		/* Enable interrupts to get RF toggle notifications. */
8723 		IWN_WRITE(sc, IWN_INT, 0xffffffff);
8724 		IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
8725 		return;
8726 	}
8727 
8728 	/* Read firmware images from the filesystem. */
8729 	if ((error = iwn_read_firmware(sc)) != 0) {
8730 		device_printf(sc->sc_dev,
8731 		    "%s: could not read firmware, error %d\n", __func__,
8732 		    error);
8733 		goto fail;
8734 	}
8735 
8736 	/* Initialize hardware and upload firmware. */
8737 	error = iwn_hw_init(sc);
8738 	firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
8739 	sc->fw_fp = NULL;
8740 	if (error != 0) {
8741 		device_printf(sc->sc_dev,
8742 		    "%s: could not initialize hardware, error %d\n", __func__,
8743 		    error);
8744 		goto fail;
8745 	}
8746 
8747 	/* Configure adapter now that it is ready. */
8748 	if ((error = iwn_config(sc)) != 0) {
8749 		device_printf(sc->sc_dev,
8750 		    "%s: could not configure device, error %d\n", __func__,
8751 		    error);
8752 		goto fail;
8753 	}
8754 
8755 	callout_reset(&sc->watchdog_to, hz, iwn_watchdog, sc);
8756 
8757 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
8758 
8759 	return;
8760 
8761 fail:
8762 	sc->sc_flags &= ~IWN_FLAG_RUNNING;
8763 	iwn_stop_locked(sc);
8764 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end in error\n",__func__);
8765 }
8766 
8767 static void
8768 iwn_init(struct iwn_softc *sc)
8769 {
8770 
8771 	IWN_LOCK(sc);
8772 	iwn_init_locked(sc);
8773 	IWN_UNLOCK(sc);
8774 
8775 	if (sc->sc_flags & IWN_FLAG_RUNNING)
8776 		ieee80211_start_all(&sc->sc_ic);
8777 }
8778 
8779 static void
8780 iwn_stop_locked(struct iwn_softc *sc)
8781 {
8782 
8783 	IWN_LOCK_ASSERT(sc);
8784 
8785 	sc->sc_is_scanning = 0;
8786 	sc->sc_tx_timer = 0;
8787 	callout_stop(&sc->watchdog_to);
8788 	callout_stop(&sc->calib_to);
8789 	sc->sc_flags &= ~IWN_FLAG_RUNNING;
8790 
8791 	/* Power OFF hardware. */
8792 	iwn_hw_stop(sc);
8793 }
8794 
8795 static void
8796 iwn_stop(struct iwn_softc *sc)
8797 {
8798 	IWN_LOCK(sc);
8799 	iwn_stop_locked(sc);
8800 	IWN_UNLOCK(sc);
8801 }
8802 
8803 /*
8804  * Callback from net80211 to start a scan.
8805  */
8806 static void
8807 iwn_scan_start(struct ieee80211com *ic)
8808 {
8809 	struct iwn_softc *sc = ic->ic_softc;
8810 
8811 	IWN_LOCK(sc);
8812 	/* make the link LED blink while we're scanning */
8813 	iwn_set_led(sc, IWN_LED_LINK, 20, 2);
8814 	IWN_UNLOCK(sc);
8815 }
8816 
8817 /*
8818  * Callback from net80211 to terminate a scan.
8819  */
8820 static void
8821 iwn_scan_end(struct ieee80211com *ic)
8822 {
8823 	struct iwn_softc *sc = ic->ic_softc;
8824 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
8825 
8826 	IWN_LOCK(sc);
8827 	if (vap->iv_state == IEEE80211_S_RUN) {
8828 		/* Set link LED to ON status if we are associated */
8829 		iwn_set_led(sc, IWN_LED_LINK, 0, 1);
8830 	}
8831 	IWN_UNLOCK(sc);
8832 }
8833 
8834 /*
8835  * Callback from net80211 to force a channel change.
8836  */
8837 static void
8838 iwn_set_channel(struct ieee80211com *ic)
8839 {
8840 	const struct ieee80211_channel *c = ic->ic_curchan;
8841 	struct iwn_softc *sc = ic->ic_softc;
8842 	int error;
8843 
8844 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8845 
8846 	IWN_LOCK(sc);
8847 	sc->sc_rxtap.wr_chan_freq = htole16(c->ic_freq);
8848 	sc->sc_rxtap.wr_chan_flags = htole16(c->ic_flags);
8849 	sc->sc_txtap.wt_chan_freq = htole16(c->ic_freq);
8850 	sc->sc_txtap.wt_chan_flags = htole16(c->ic_flags);
8851 
8852 	/*
8853 	 * Only need to set the channel in Monitor mode. AP scanning and auth
8854 	 * are already taken care of by their respective firmware commands.
8855 	 */
8856 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
8857 		error = iwn_config(sc);
8858 		if (error != 0)
8859 		device_printf(sc->sc_dev,
8860 		    "%s: error %d settting channel\n", __func__, error);
8861 	}
8862 	IWN_UNLOCK(sc);
8863 }
8864 
8865 /*
8866  * Callback from net80211 to start scanning of the current channel.
8867  */
8868 static void
8869 iwn_scan_curchan(struct ieee80211_scan_state *ss, unsigned long maxdwell)
8870 {
8871 	struct ieee80211vap *vap = ss->ss_vap;
8872 	struct ieee80211com *ic = vap->iv_ic;
8873 	struct iwn_softc *sc = ic->ic_softc;
8874 	int error;
8875 
8876 	IWN_LOCK(sc);
8877 	error = iwn_scan(sc, vap, ss, ic->ic_curchan);
8878 	IWN_UNLOCK(sc);
8879 	if (error != 0)
8880 		ieee80211_cancel_scan(vap);
8881 }
8882 
8883 /*
8884  * Callback from net80211 to handle the minimum dwell time being met.
8885  * The intent is to terminate the scan but we just let the firmware
8886  * notify us when it's finished as we have no safe way to abort it.
8887  */
8888 static void
8889 iwn_scan_mindwell(struct ieee80211_scan_state *ss)
8890 {
8891 	/* NB: don't try to abort scan; wait for firmware to finish */
8892 }
8893 
8894 static void
8895 iwn_hw_reset(void *arg0, int pending)
8896 {
8897 	struct iwn_softc *sc = arg0;
8898 	struct ieee80211com *ic = &sc->sc_ic;
8899 
8900 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8901 
8902 	iwn_stop(sc);
8903 	iwn_init(sc);
8904 	ieee80211_notify_radio(ic, 1);
8905 }
8906 #ifdef	IWN_DEBUG
8907 #define	IWN_DESC(x) case x:	return #x
8908 
8909 /*
8910  * Translate CSR code to string
8911  */
8912 static char *iwn_get_csr_string(int csr)
8913 {
8914 	switch (csr) {
8915 		IWN_DESC(IWN_HW_IF_CONFIG);
8916 		IWN_DESC(IWN_INT_COALESCING);
8917 		IWN_DESC(IWN_INT);
8918 		IWN_DESC(IWN_INT_MASK);
8919 		IWN_DESC(IWN_FH_INT);
8920 		IWN_DESC(IWN_GPIO_IN);
8921 		IWN_DESC(IWN_RESET);
8922 		IWN_DESC(IWN_GP_CNTRL);
8923 		IWN_DESC(IWN_HW_REV);
8924 		IWN_DESC(IWN_EEPROM);
8925 		IWN_DESC(IWN_EEPROM_GP);
8926 		IWN_DESC(IWN_OTP_GP);
8927 		IWN_DESC(IWN_GIO);
8928 		IWN_DESC(IWN_GP_UCODE);
8929 		IWN_DESC(IWN_GP_DRIVER);
8930 		IWN_DESC(IWN_UCODE_GP1);
8931 		IWN_DESC(IWN_UCODE_GP2);
8932 		IWN_DESC(IWN_LED);
8933 		IWN_DESC(IWN_DRAM_INT_TBL);
8934 		IWN_DESC(IWN_GIO_CHICKEN);
8935 		IWN_DESC(IWN_ANA_PLL);
8936 		IWN_DESC(IWN_HW_REV_WA);
8937 		IWN_DESC(IWN_DBG_HPET_MEM);
8938 	default:
8939 		return "UNKNOWN CSR";
8940 	}
8941 }
8942 
8943 /*
8944  * This function print firmware register
8945  */
8946 static void
8947 iwn_debug_register(struct iwn_softc *sc)
8948 {
8949 	int i;
8950 	static const uint32_t csr_tbl[] = {
8951 		IWN_HW_IF_CONFIG,
8952 		IWN_INT_COALESCING,
8953 		IWN_INT,
8954 		IWN_INT_MASK,
8955 		IWN_FH_INT,
8956 		IWN_GPIO_IN,
8957 		IWN_RESET,
8958 		IWN_GP_CNTRL,
8959 		IWN_HW_REV,
8960 		IWN_EEPROM,
8961 		IWN_EEPROM_GP,
8962 		IWN_OTP_GP,
8963 		IWN_GIO,
8964 		IWN_GP_UCODE,
8965 		IWN_GP_DRIVER,
8966 		IWN_UCODE_GP1,
8967 		IWN_UCODE_GP2,
8968 		IWN_LED,
8969 		IWN_DRAM_INT_TBL,
8970 		IWN_GIO_CHICKEN,
8971 		IWN_ANA_PLL,
8972 		IWN_HW_REV_WA,
8973 		IWN_DBG_HPET_MEM,
8974 	};
8975 	DPRINTF(sc, IWN_DEBUG_REGISTER,
8976 	    "CSR values: (2nd byte of IWN_INT_COALESCING is IWN_INT_PERIODIC)%s",
8977 	    "\n");
8978 	for (i = 0; i <  nitems(csr_tbl); i++){
8979 		DPRINTF(sc, IWN_DEBUG_REGISTER,"  %10s: 0x%08x ",
8980 			iwn_get_csr_string(csr_tbl[i]), IWN_READ(sc, csr_tbl[i]));
8981 		if ((i+1) % 3 == 0)
8982 			DPRINTF(sc, IWN_DEBUG_REGISTER,"%s","\n");
8983 	}
8984 	DPRINTF(sc, IWN_DEBUG_REGISTER,"%s","\n");
8985 }
8986 #endif
8987 
8988 
8989