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