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