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