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