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