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