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