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