xref: /freebsd/sys/dev/iwn/if_iwn.c (revision 59c7ad52aaa5b26e503871334672af0f58f9c2e8)
1 /*-
2  * Copyright (c) 2007-2009
3  *	Damien Bergamini <damien.bergamini@free.fr>
4  * Copyright (c) 2008
5  *	Benjamin Close <benjsc@FreeBSD.org>
6  * Copyright (c) 2008 Sam Leffler, Errno Consulting
7  *
8  * Permission to use, copy, modify, and distribute this software for any
9  * purpose with or without fee is hereby granted, provided that the above
10  * copyright notice and this permission notice appear in all copies.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19  */
20 
21 /*
22  * Driver for Intel WiFi Link 4965 and 1000/5000/6000 Series 802.11 network
23  * adapters.
24  */
25 
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
28 
29 #include <sys/param.h>
30 #include <sys/sockio.h>
31 #include <sys/sysctl.h>
32 #include <sys/mbuf.h>
33 #include <sys/kernel.h>
34 #include <sys/socket.h>
35 #include <sys/systm.h>
36 #include <sys/malloc.h>
37 #include <sys/bus.h>
38 #include <sys/rman.h>
39 #include <sys/endian.h>
40 #include <sys/firmware.h>
41 #include <sys/limits.h>
42 #include <sys/module.h>
43 #include <sys/queue.h>
44 #include <sys/taskqueue.h>
45 
46 #include <machine/bus.h>
47 #include <machine/resource.h>
48 #include <machine/clock.h>
49 
50 #include <dev/pci/pcireg.h>
51 #include <dev/pci/pcivar.h>
52 
53 #include <net/bpf.h>
54 #include <net/if.h>
55 #include <net/if_arp.h>
56 #include <net/ethernet.h>
57 #include <net/if_dl.h>
58 #include <net/if_media.h>
59 #include <net/if_types.h>
60 
61 #include <netinet/in.h>
62 #include <netinet/in_systm.h>
63 #include <netinet/in_var.h>
64 #include <netinet/if_ether.h>
65 #include <netinet/ip.h>
66 
67 #include <net80211/ieee80211_var.h>
68 #include <net80211/ieee80211_radiotap.h>
69 #include <net80211/ieee80211_regdomain.h>
70 #include <net80211/ieee80211_ratectl.h>
71 
72 #include <dev/iwn/if_iwnreg.h>
73 #include <dev/iwn/if_iwnvar.h>
74 
75 struct iwn_ident {
76 	uint16_t	vendor;
77 	uint16_t	device;
78 	const char	*name;
79 };
80 
81 static const struct iwn_ident iwn_ident_table[] = {
82 	{ 0x8086, 0x0082, "Intel(R) Centrino(R) Advanced-N 6205"	 },
83 	{ 0x8086, 0x0083, "Intel(R) Centrino(R) Wireless-N 1000"	 },
84 	{ 0x8086, 0x0084, "Intel(R) Centrino(R) Wireless-N 1000"	 },
85 	{ 0x8086, 0x0085, "Intel(R) Centrino(R) Advanced-N 6205"	 },
86 	{ 0x8086, 0x0087, "Intel(R) Centrino(R) Advanced-N + WiMAX 6250" },
87 	{ 0x8086, 0x0089, "Intel(R) Centrino(R) Advanced-N + WiMAX 6250" },
88 	{ 0x8086, 0x008a, "Intel(R) Centrino(R) Wireless-N 1030"	 },
89 	{ 0x8086, 0x008b, "Intel(R) Centrino(R) Wireless-N 1030"	 },
90 	{ 0x8086, 0x0090, "Intel(R) Centrino(R) Advanced-N 6230"	 },
91 	{ 0x8086, 0x0091, "Intel(R) Centrino(R) Advanced-N 6230"	 },
92 	{ 0x8086, 0x4229, "Intel(R) Wireless WiFi Link 4965"		 },
93 	{ 0x8086, 0x422b, "Intel(R) Centrino(R) Ultimate-N 6300"	 },
94 	{ 0x8086, 0x422c, "Intel(R) Centrino(R) Advanced-N 6200"	 },
95 	{ 0x8086, 0x422d, "Intel(R) Wireless WiFi Link 4965"		 },
96 	{ 0x8086, 0x4230, "Intel(R) Wireless WiFi Link 4965"		 },
97 	{ 0x8086, 0x4232, "Intel(R) WiFi Link 5100"			 },
98 	{ 0x8086, 0x4233, "Intel(R) Wireless WiFi Link 4965"		 },
99 	{ 0x8086, 0x4235, "Intel(R) Ultimate N WiFi Link 5300"		 },
100 	{ 0x8086, 0x4236, "Intel(R) Ultimate N WiFi Link 5300"		 },
101 	{ 0x8086, 0x4237, "Intel(R) WiFi Link 5100"			 },
102 	{ 0x8086, 0x4238, "Intel(R) Centrino(R) Ultimate-N 6300"	 },
103 	{ 0x8086, 0x4239, "Intel(R) Centrino(R) Advanced-N 6200"	 },
104 	{ 0x8086, 0x423a, "Intel(R) WiMAX/WiFi Link 5350"		 },
105 	{ 0x8086, 0x423b, "Intel(R) WiMAX/WiFi Link 5350"		 },
106 	{ 0x8086, 0x423c, "Intel(R) WiMAX/WiFi Link 5150"		 },
107 	{ 0x8086, 0x423d, "Intel(R) WiMAX/WiFi Link 5150"		 },
108 	{ 0, 0, NULL }
109 };
110 
111 static int	iwn_probe(device_t);
112 static int	iwn_attach(device_t);
113 static int	iwn4965_attach(struct iwn_softc *, uint16_t);
114 static int	iwn5000_attach(struct iwn_softc *, uint16_t);
115 static void	iwn_radiotap_attach(struct iwn_softc *);
116 static void	iwn_sysctlattach(struct iwn_softc *);
117 static struct ieee80211vap *iwn_vap_create(struct ieee80211com *,
118 		    const char name[IFNAMSIZ], int unit, int opmode,
119 		    int flags, const uint8_t bssid[IEEE80211_ADDR_LEN],
120 		    const uint8_t mac[IEEE80211_ADDR_LEN]);
121 static void	iwn_vap_delete(struct ieee80211vap *);
122 static int	iwn_detach(device_t);
123 static int	iwn_shutdown(device_t);
124 static int	iwn_suspend(device_t);
125 static int	iwn_resume(device_t);
126 static int	iwn_nic_lock(struct iwn_softc *);
127 static int	iwn_eeprom_lock(struct iwn_softc *);
128 static int	iwn_init_otprom(struct iwn_softc *);
129 static int	iwn_read_prom_data(struct iwn_softc *, uint32_t, void *, int);
130 static void	iwn_dma_map_addr(void *, bus_dma_segment_t *, int, int);
131 static int	iwn_dma_contig_alloc(struct iwn_softc *, struct iwn_dma_info *,
132 		    void **, bus_size_t, bus_size_t);
133 static void	iwn_dma_contig_free(struct iwn_dma_info *);
134 static int	iwn_alloc_sched(struct iwn_softc *);
135 static void	iwn_free_sched(struct iwn_softc *);
136 static int	iwn_alloc_kw(struct iwn_softc *);
137 static void	iwn_free_kw(struct iwn_softc *);
138 static int	iwn_alloc_ict(struct iwn_softc *);
139 static void	iwn_free_ict(struct iwn_softc *);
140 static int	iwn_alloc_fwmem(struct iwn_softc *);
141 static void	iwn_free_fwmem(struct iwn_softc *);
142 static int	iwn_alloc_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
143 static void	iwn_reset_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
144 static void	iwn_free_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
145 static int	iwn_alloc_tx_ring(struct iwn_softc *, struct iwn_tx_ring *,
146 		    int);
147 static void	iwn_reset_tx_ring(struct iwn_softc *, struct iwn_tx_ring *);
148 static void	iwn_free_tx_ring(struct iwn_softc *, struct iwn_tx_ring *);
149 static void	iwn5000_ict_reset(struct iwn_softc *);
150 static int	iwn_read_eeprom(struct iwn_softc *,
151 		    uint8_t macaddr[IEEE80211_ADDR_LEN]);
152 static void	iwn4965_read_eeprom(struct iwn_softc *);
153 static void	iwn4965_print_power_group(struct iwn_softc *, int);
154 static void	iwn5000_read_eeprom(struct iwn_softc *);
155 static uint32_t	iwn_eeprom_channel_flags(struct iwn_eeprom_chan *);
156 static void	iwn_read_eeprom_band(struct iwn_softc *, int);
157 static void	iwn_read_eeprom_ht40(struct iwn_softc *, int);
158 static void	iwn_read_eeprom_channels(struct iwn_softc *, int, uint32_t);
159 static struct iwn_eeprom_chan *iwn_find_eeprom_channel(struct iwn_softc *,
160 		    struct ieee80211_channel *);
161 static int	iwn_setregdomain(struct ieee80211com *,
162 		    struct ieee80211_regdomain *, int,
163 		    struct ieee80211_channel[]);
164 static void	iwn_read_eeprom_enhinfo(struct iwn_softc *);
165 static struct ieee80211_node *iwn_node_alloc(struct ieee80211vap *,
166 		    const uint8_t mac[IEEE80211_ADDR_LEN]);
167 static void	iwn_newassoc(struct ieee80211_node *, int);
168 static int	iwn_media_change(struct ifnet *);
169 static int	iwn_newstate(struct ieee80211vap *, enum ieee80211_state, int);
170 static void	iwn_calib_timeout(void *);
171 static void	iwn_rx_phy(struct iwn_softc *, struct iwn_rx_desc *,
172 		    struct iwn_rx_data *);
173 static void	iwn_rx_done(struct iwn_softc *, struct iwn_rx_desc *,
174 		    struct iwn_rx_data *);
175 static void	iwn_rx_compressed_ba(struct iwn_softc *, struct iwn_rx_desc *,
176 		    struct iwn_rx_data *);
177 static void	iwn5000_rx_calib_results(struct iwn_softc *,
178 		    struct iwn_rx_desc *, struct iwn_rx_data *);
179 static void	iwn_rx_statistics(struct iwn_softc *, struct iwn_rx_desc *,
180 		    struct iwn_rx_data *);
181 static void	iwn4965_tx_done(struct iwn_softc *, struct iwn_rx_desc *,
182 		    struct iwn_rx_data *);
183 static void	iwn5000_tx_done(struct iwn_softc *, struct iwn_rx_desc *,
184 		    struct iwn_rx_data *);
185 static void	iwn_tx_done(struct iwn_softc *, struct iwn_rx_desc *, int,
186 		    uint8_t);
187 static void	iwn_ampdu_tx_done(struct iwn_softc *, int, int, int, void *);
188 static void	iwn_cmd_done(struct iwn_softc *, struct iwn_rx_desc *);
189 static void	iwn_notif_intr(struct iwn_softc *);
190 static void	iwn_wakeup_intr(struct iwn_softc *);
191 static void	iwn_rftoggle_intr(struct iwn_softc *);
192 static void	iwn_fatal_intr(struct iwn_softc *);
193 static void	iwn_intr(void *);
194 static void	iwn4965_update_sched(struct iwn_softc *, int, int, uint8_t,
195 		    uint16_t);
196 static void	iwn5000_update_sched(struct iwn_softc *, int, int, uint8_t,
197 		    uint16_t);
198 #ifdef notyet
199 static void	iwn5000_reset_sched(struct iwn_softc *, int, int);
200 #endif
201 static int	iwn_tx_data(struct iwn_softc *, struct mbuf *,
202 		    struct ieee80211_node *);
203 static int	iwn_tx_data_raw(struct iwn_softc *, struct mbuf *,
204 		    struct ieee80211_node *,
205 		    const struct ieee80211_bpf_params *params);
206 static int	iwn_raw_xmit(struct ieee80211_node *, struct mbuf *,
207 		    const struct ieee80211_bpf_params *);
208 static void	iwn_start(struct ifnet *);
209 static void	iwn_start_locked(struct ifnet *);
210 static void	iwn_watchdog(void *);
211 static int	iwn_ioctl(struct ifnet *, u_long, caddr_t);
212 static int	iwn_cmd(struct iwn_softc *, int, const void *, int, int);
213 static int	iwn4965_add_node(struct iwn_softc *, struct iwn_node_info *,
214 		    int);
215 static int	iwn5000_add_node(struct iwn_softc *, struct iwn_node_info *,
216 		    int);
217 static int	iwn_set_link_quality(struct iwn_softc *,
218 		    struct ieee80211_node *);
219 static int	iwn_add_broadcast_node(struct iwn_softc *, int);
220 static int	iwn_updateedca(struct ieee80211com *);
221 static void	iwn_update_mcast(struct ifnet *);
222 static void	iwn_set_led(struct iwn_softc *, uint8_t, uint8_t, uint8_t);
223 static int	iwn_set_critical_temp(struct iwn_softc *);
224 static int	iwn_set_timing(struct iwn_softc *, struct ieee80211_node *);
225 static void	iwn4965_power_calibration(struct iwn_softc *, int);
226 static int	iwn4965_set_txpower(struct iwn_softc *,
227 		    struct ieee80211_channel *, int);
228 static int	iwn5000_set_txpower(struct iwn_softc *,
229 		    struct ieee80211_channel *, int);
230 static int	iwn4965_get_rssi(struct iwn_softc *, struct iwn_rx_stat *);
231 static int	iwn5000_get_rssi(struct iwn_softc *, struct iwn_rx_stat *);
232 static int	iwn_get_noise(const struct iwn_rx_general_stats *);
233 static int	iwn4965_get_temperature(struct iwn_softc *);
234 static int	iwn5000_get_temperature(struct iwn_softc *);
235 static int	iwn_init_sensitivity(struct iwn_softc *);
236 static void	iwn_collect_noise(struct iwn_softc *,
237 		    const struct iwn_rx_general_stats *);
238 static int	iwn4965_init_gains(struct iwn_softc *);
239 static int	iwn5000_init_gains(struct iwn_softc *);
240 static int	iwn4965_set_gains(struct iwn_softc *);
241 static int	iwn5000_set_gains(struct iwn_softc *);
242 static void	iwn_tune_sensitivity(struct iwn_softc *,
243 		    const struct iwn_rx_stats *);
244 static int	iwn_send_sensitivity(struct iwn_softc *);
245 static int	iwn_set_pslevel(struct iwn_softc *, int, int, int);
246 static int	iwn_send_btcoex(struct iwn_softc *);
247 static int	iwn_send_advanced_btcoex(struct iwn_softc *);
248 static int	iwn_config(struct iwn_softc *);
249 static uint8_t	*ieee80211_add_ssid(uint8_t *, const uint8_t *, u_int);
250 static int	iwn_scan(struct iwn_softc *);
251 static int	iwn_auth(struct iwn_softc *, struct ieee80211vap *vap);
252 static int	iwn_run(struct iwn_softc *, struct ieee80211vap *vap);
253 static int	iwn_ampdu_rx_start(struct ieee80211_node *,
254 		    struct ieee80211_rx_ampdu *, int, int, int);
255 static void	iwn_ampdu_rx_stop(struct ieee80211_node *,
256 		    struct ieee80211_rx_ampdu *);
257 static int	iwn_addba_request(struct ieee80211_node *,
258 		    struct ieee80211_tx_ampdu *, int, int, int);
259 static int	iwn_addba_response(struct ieee80211_node *,
260 		    struct ieee80211_tx_ampdu *, int, int, int);
261 static int	iwn_ampdu_tx_start(struct ieee80211com *,
262 		    struct ieee80211_node *, uint8_t);
263 static void	iwn_ampdu_tx_stop(struct ieee80211_node *,
264 		    struct ieee80211_tx_ampdu *);
265 static void	iwn4965_ampdu_tx_start(struct iwn_softc *,
266 		    struct ieee80211_node *, int, uint8_t, uint16_t);
267 static void	iwn4965_ampdu_tx_stop(struct iwn_softc *, int,
268 		    uint8_t, uint16_t);
269 static void	iwn5000_ampdu_tx_start(struct iwn_softc *,
270 		    struct ieee80211_node *, int, uint8_t, uint16_t);
271 static void	iwn5000_ampdu_tx_stop(struct iwn_softc *, int,
272 		    uint8_t, uint16_t);
273 static int	iwn5000_query_calibration(struct iwn_softc *);
274 static int	iwn5000_send_calibration(struct iwn_softc *);
275 static int	iwn5000_send_wimax_coex(struct iwn_softc *);
276 static int	iwn5000_crystal_calib(struct iwn_softc *);
277 static int	iwn5000_temp_offset_calib(struct iwn_softc *);
278 static int	iwn4965_post_alive(struct iwn_softc *);
279 static int	iwn5000_post_alive(struct iwn_softc *);
280 static int	iwn4965_load_bootcode(struct iwn_softc *, const uint8_t *,
281 		    int);
282 static int	iwn4965_load_firmware(struct iwn_softc *);
283 static int	iwn5000_load_firmware_section(struct iwn_softc *, uint32_t,
284 		    const uint8_t *, int);
285 static int	iwn5000_load_firmware(struct iwn_softc *);
286 static int	iwn_read_firmware_leg(struct iwn_softc *,
287 		    struct iwn_fw_info *);
288 static int	iwn_read_firmware_tlv(struct iwn_softc *,
289 		    struct iwn_fw_info *, uint16_t);
290 static int	iwn_read_firmware(struct iwn_softc *);
291 static int	iwn_clock_wait(struct iwn_softc *);
292 static int	iwn_apm_init(struct iwn_softc *);
293 static void	iwn_apm_stop_master(struct iwn_softc *);
294 static void	iwn_apm_stop(struct iwn_softc *);
295 static int	iwn4965_nic_config(struct iwn_softc *);
296 static int	iwn5000_nic_config(struct iwn_softc *);
297 static int	iwn_hw_prepare(struct iwn_softc *);
298 static int	iwn_hw_init(struct iwn_softc *);
299 static void	iwn_hw_stop(struct iwn_softc *);
300 static void	iwn_radio_on(void *, int);
301 static void	iwn_radio_off(void *, int);
302 static void	iwn_init_locked(struct iwn_softc *);
303 static void	iwn_init(void *);
304 static void	iwn_stop_locked(struct iwn_softc *);
305 static void	iwn_stop(struct iwn_softc *);
306 static void	iwn_scan_start(struct ieee80211com *);
307 static void	iwn_scan_end(struct ieee80211com *);
308 static void	iwn_set_channel(struct ieee80211com *);
309 static void	iwn_scan_curchan(struct ieee80211_scan_state *, unsigned long);
310 static void	iwn_scan_mindwell(struct ieee80211_scan_state *);
311 static void	iwn_hw_reset(void *, int);
312 
313 #define IWN_DEBUG
314 #ifdef IWN_DEBUG
315 enum {
316 	IWN_DEBUG_XMIT		= 0x00000001,	/* basic xmit operation */
317 	IWN_DEBUG_RECV		= 0x00000002,	/* basic recv operation */
318 	IWN_DEBUG_STATE		= 0x00000004,	/* 802.11 state transitions */
319 	IWN_DEBUG_TXPOW		= 0x00000008,	/* tx power processing */
320 	IWN_DEBUG_RESET		= 0x00000010,	/* reset processing */
321 	IWN_DEBUG_OPS		= 0x00000020,	/* iwn_ops processing */
322 	IWN_DEBUG_BEACON 	= 0x00000040,	/* beacon handling */
323 	IWN_DEBUG_WATCHDOG 	= 0x00000080,	/* watchdog timeout */
324 	IWN_DEBUG_INTR		= 0x00000100,	/* ISR */
325 	IWN_DEBUG_CALIBRATE	= 0x00000200,	/* periodic calibration */
326 	IWN_DEBUG_NODE		= 0x00000400,	/* node management */
327 	IWN_DEBUG_LED		= 0x00000800,	/* led management */
328 	IWN_DEBUG_CMD		= 0x00001000,	/* cmd submission */
329 	IWN_DEBUG_FATAL		= 0x80000000,	/* fatal errors */
330 	IWN_DEBUG_ANY		= 0xffffffff
331 };
332 
333 #define DPRINTF(sc, m, fmt, ...) do {			\
334 	if (sc->sc_debug & (m))				\
335 		printf(fmt, __VA_ARGS__);		\
336 } while (0)
337 
338 static const char *
339 iwn_intr_str(uint8_t cmd)
340 {
341 	switch (cmd) {
342 	/* Notifications */
343 	case IWN_UC_READY:		return "UC_READY";
344 	case IWN_ADD_NODE_DONE:		return "ADD_NODE_DONE";
345 	case IWN_TX_DONE:		return "TX_DONE";
346 	case IWN_START_SCAN:		return "START_SCAN";
347 	case IWN_STOP_SCAN:		return "STOP_SCAN";
348 	case IWN_RX_STATISTICS:		return "RX_STATS";
349 	case IWN_BEACON_STATISTICS:	return "BEACON_STATS";
350 	case IWN_STATE_CHANGED:		return "STATE_CHANGED";
351 	case IWN_BEACON_MISSED:		return "BEACON_MISSED";
352 	case IWN_RX_PHY:		return "RX_PHY";
353 	case IWN_MPDU_RX_DONE:		return "MPDU_RX_DONE";
354 	case IWN_RX_DONE:		return "RX_DONE";
355 
356 	/* Command Notifications */
357 	case IWN_CMD_RXON:		return "IWN_CMD_RXON";
358 	case IWN_CMD_RXON_ASSOC:	return "IWN_CMD_RXON_ASSOC";
359 	case IWN_CMD_EDCA_PARAMS:	return "IWN_CMD_EDCA_PARAMS";
360 	case IWN_CMD_TIMING:		return "IWN_CMD_TIMING";
361 	case IWN_CMD_LINK_QUALITY:	return "IWN_CMD_LINK_QUALITY";
362 	case IWN_CMD_SET_LED:		return "IWN_CMD_SET_LED";
363 	case IWN5000_CMD_WIMAX_COEX:	return "IWN5000_CMD_WIMAX_COEX";
364 	case IWN5000_CMD_CALIB_CONFIG:	return "IWN5000_CMD_CALIB_CONFIG";
365 	case IWN5000_CMD_CALIB_RESULT:	return "IWN5000_CMD_CALIB_RESULT";
366 	case IWN5000_CMD_CALIB_COMPLETE: return "IWN5000_CMD_CALIB_COMPLETE";
367 	case IWN_CMD_SET_POWER_MODE:	return "IWN_CMD_SET_POWER_MODE";
368 	case IWN_CMD_SCAN:		return "IWN_CMD_SCAN";
369 	case IWN_CMD_SCAN_RESULTS:	return "IWN_CMD_SCAN_RESULTS";
370 	case IWN_CMD_TXPOWER:		return "IWN_CMD_TXPOWER";
371 	case IWN_CMD_TXPOWER_DBM:	return "IWN_CMD_TXPOWER_DBM";
372 	case IWN5000_CMD_TX_ANT_CONFIG:	return "IWN5000_CMD_TX_ANT_CONFIG";
373 	case IWN_CMD_BT_COEX:		return "IWN_CMD_BT_COEX";
374 	case IWN_CMD_SET_CRITICAL_TEMP:	return "IWN_CMD_SET_CRITICAL_TEMP";
375 	case IWN_CMD_SET_SENSITIVITY:	return "IWN_CMD_SET_SENSITIVITY";
376 	case IWN_CMD_PHY_CALIB:		return "IWN_CMD_PHY_CALIB";
377 	}
378 	return "UNKNOWN INTR NOTIF/CMD";
379 }
380 #else
381 #define DPRINTF(sc, m, fmt, ...) do { (void) sc; } while (0)
382 #endif
383 
384 static device_method_t iwn_methods[] = {
385 	/* Device interface */
386 	DEVMETHOD(device_probe,		iwn_probe),
387 	DEVMETHOD(device_attach,	iwn_attach),
388 	DEVMETHOD(device_detach,	iwn_detach),
389 	DEVMETHOD(device_shutdown,	iwn_shutdown),
390 	DEVMETHOD(device_suspend,	iwn_suspend),
391 	DEVMETHOD(device_resume,	iwn_resume),
392 	{ 0, 0 }
393 };
394 
395 static driver_t iwn_driver = {
396 	"iwn",
397 	iwn_methods,
398 	sizeof(struct iwn_softc)
399 };
400 static devclass_t iwn_devclass;
401 
402 DRIVER_MODULE(iwn, pci, iwn_driver, iwn_devclass, 0, 0);
403 
404 MODULE_DEPEND(iwn, firmware, 1, 1, 1);
405 MODULE_DEPEND(iwn, pci, 1, 1, 1);
406 MODULE_DEPEND(iwn, wlan, 1, 1, 1);
407 
408 static int
409 iwn_probe(device_t dev)
410 {
411 	const struct iwn_ident *ident;
412 
413 	for (ident = iwn_ident_table; ident->name != NULL; ident++) {
414 		if (pci_get_vendor(dev) == ident->vendor &&
415 		    pci_get_device(dev) == ident->device) {
416 			device_set_desc(dev, ident->name);
417 			return 0;
418 		}
419 	}
420 	return ENXIO;
421 }
422 
423 static int
424 iwn_attach(device_t dev)
425 {
426 	struct iwn_softc *sc = (struct iwn_softc *)device_get_softc(dev);
427 	struct ieee80211com *ic;
428 	struct ifnet *ifp;
429 	uint32_t reg;
430 	int i, error, result;
431 	uint8_t macaddr[IEEE80211_ADDR_LEN];
432 
433 	sc->sc_dev = dev;
434 
435 	/*
436 	 * Get the offset of the PCI Express Capability Structure in PCI
437 	 * Configuration Space.
438 	 */
439 	error = pci_find_cap(dev, PCIY_EXPRESS, &sc->sc_cap_off);
440 	if (error != 0) {
441 		device_printf(dev, "PCIe capability structure not found!\n");
442 		return error;
443 	}
444 
445 	/* Clear device-specific "PCI retry timeout" register (41h). */
446 	pci_write_config(dev, 0x41, 0, 1);
447 
448 	/* Hardware bug workaround. */
449 	reg = pci_read_config(dev, PCIR_COMMAND, 1);
450 	if (reg & PCIM_CMD_INTxDIS) {
451 		DPRINTF(sc, IWN_DEBUG_RESET, "%s: PCIe INTx Disable set\n",
452 		    __func__);
453 		reg &= ~PCIM_CMD_INTxDIS;
454 		pci_write_config(dev, PCIR_COMMAND, reg, 1);
455 	}
456 
457 	/* Enable bus-mastering. */
458 	pci_enable_busmaster(dev);
459 
460 	sc->mem_rid = PCIR_BAR(0);
461 	sc->mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &sc->mem_rid,
462 	    RF_ACTIVE);
463 	if (sc->mem == NULL) {
464 		device_printf(dev, "can't map mem space\n");
465 		error = ENOMEM;
466 		return error;
467 	}
468 	sc->sc_st = rman_get_bustag(sc->mem);
469 	sc->sc_sh = rman_get_bushandle(sc->mem);
470 
471 	sc->irq_rid = 0;
472 	if ((result = pci_msi_count(dev)) == 1 &&
473 	    pci_alloc_msi(dev, &result) == 0)
474 		sc->irq_rid = 1;
475 	/* Install interrupt handler. */
476 	sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->irq_rid,
477 	    RF_ACTIVE | RF_SHAREABLE);
478 	if (sc->irq == NULL) {
479 		device_printf(dev, "can't map interrupt\n");
480 		error = ENOMEM;
481 		goto fail;
482 	}
483 
484 	IWN_LOCK_INIT(sc);
485 
486 	/* Read hardware revision and attach. */
487 	sc->hw_type = (IWN_READ(sc, IWN_HW_REV) >> 4) & 0xf;
488 	if (sc->hw_type == IWN_HW_REV_TYPE_4965)
489 		error = iwn4965_attach(sc, pci_get_device(dev));
490 	else
491 		error = iwn5000_attach(sc, pci_get_device(dev));
492 	if (error != 0) {
493 		device_printf(dev, "could not attach device, error %d\n",
494 		    error);
495 		goto fail;
496 	}
497 
498 	if ((error = iwn_hw_prepare(sc)) != 0) {
499 		device_printf(dev, "hardware not ready, error %d\n", error);
500 		goto fail;
501 	}
502 
503 	/* Allocate DMA memory for firmware transfers. */
504 	if ((error = iwn_alloc_fwmem(sc)) != 0) {
505 		device_printf(dev,
506 		    "could not allocate memory for firmware, error %d\n",
507 		    error);
508 		goto fail;
509 	}
510 
511 	/* Allocate "Keep Warm" page. */
512 	if ((error = iwn_alloc_kw(sc)) != 0) {
513 		device_printf(dev,
514 		    "could not allocate keep warm page, error %d\n", error);
515 		goto fail;
516 	}
517 
518 	/* Allocate ICT table for 5000 Series. */
519 	if (sc->hw_type != IWN_HW_REV_TYPE_4965 &&
520 	    (error = iwn_alloc_ict(sc)) != 0) {
521 		device_printf(dev, "could not allocate ICT table, error %d\n",
522 		    error);
523 		goto fail;
524 	}
525 
526 	/* Allocate TX scheduler "rings". */
527 	if ((error = iwn_alloc_sched(sc)) != 0) {
528 		device_printf(dev,
529 		    "could not allocate TX scheduler rings, error %d\n", error);
530 		goto fail;
531 	}
532 
533 	/* Allocate TX rings (16 on 4965AGN, 20 on >=5000). */
534 	for (i = 0; i < sc->ntxqs; i++) {
535 		if ((error = iwn_alloc_tx_ring(sc, &sc->txq[i], i)) != 0) {
536 			device_printf(dev,
537 			    "could not allocate TX ring %d, error %d\n", i,
538 			    error);
539 			goto fail;
540 		}
541 	}
542 
543 	/* Allocate RX ring. */
544 	if ((error = iwn_alloc_rx_ring(sc, &sc->rxq)) != 0) {
545 		device_printf(dev, "could not allocate RX ring, error %d\n",
546 		    error);
547 		goto fail;
548 	}
549 
550 	/* Clear pending interrupts. */
551 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
552 
553 	ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
554 	if (ifp == NULL) {
555 		device_printf(dev, "can not allocate ifnet structure\n");
556 		goto fail;
557 	}
558 
559 	ic = ifp->if_l2com;
560 	ic->ic_ifp = ifp;
561 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
562 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
563 
564 	/* Set device capabilities. */
565 	ic->ic_caps =
566 		  IEEE80211_C_STA		/* station mode supported */
567 		| IEEE80211_C_MONITOR		/* monitor mode supported */
568 		| IEEE80211_C_TXPMGT		/* tx power management */
569 		| IEEE80211_C_SHSLOT		/* short slot time supported */
570 		| IEEE80211_C_WPA
571 		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
572 #if 0
573 		| IEEE80211_C_IBSS		/* ibss/adhoc mode */
574 #endif
575 		| IEEE80211_C_WME		/* WME */
576 		;
577 	if (sc->hw_type != IWN_HW_REV_TYPE_4965)
578 		ic->ic_caps |= IEEE80211_C_BGSCAN; /* background scanning */
579 
580 	/* Read MAC address, channels, etc from EEPROM. */
581 	if ((error = iwn_read_eeprom(sc, macaddr)) != 0) {
582 		device_printf(dev, "could not read EEPROM, error %d\n",
583 		    error);
584 		goto fail;
585 	}
586 
587 	/* Count the number of available chains. */
588 	sc->ntxchains =
589 	    ((sc->txchainmask >> 2) & 1) +
590 	    ((sc->txchainmask >> 1) & 1) +
591 	    ((sc->txchainmask >> 0) & 1);
592 	sc->nrxchains =
593 	    ((sc->rxchainmask >> 2) & 1) +
594 	    ((sc->rxchainmask >> 1) & 1) +
595 	    ((sc->rxchainmask >> 0) & 1);
596 	if (bootverbose) {
597 		device_printf(dev, "MIMO %dT%dR, %.4s, address %6D\n",
598 		    sc->ntxchains, sc->nrxchains, sc->eeprom_domain,
599 		    macaddr, ":");
600 	}
601 
602 	if (sc->sc_flags & IWN_FLAG_HAS_11N) {
603 		ic->ic_rxstream = sc->nrxchains;
604 		ic->ic_txstream = sc->ntxchains;
605 		ic->ic_htcaps =
606 			  IEEE80211_HTCAP_SMPS_OFF	/* SMPS mode disabled */
607 			| IEEE80211_HTCAP_SHORTGI20	/* short GI in 20MHz */
608 #ifdef notyet
609 			| IEEE80211_HTCAP_CHWIDTH40	/* 40MHz channel width*/
610 			| IEEE80211_HTCAP_SHORTGI40	/* short GI in 40MHz */
611 			| IEEE80211_HTCAP_GREENFIELD
612 #if IWN_RBUF_SIZE == 8192
613 			| IEEE80211_HTCAP_MAXAMSDU_7935	/* max A-MSDU length */
614 #else
615 			| IEEE80211_HTCAP_MAXAMSDU_3839	/* max A-MSDU length */
616 #endif
617 #endif
618 			/* s/w capabilities */
619 			| IEEE80211_HTC_HT		/* HT operation */
620 			| IEEE80211_HTC_AMPDU		/* tx A-MPDU */
621 #ifdef notyet
622 			| IEEE80211_HTC_AMSDU		/* tx A-MSDU */
623 #endif
624 			;
625 	}
626 
627 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
628 	ifp->if_softc = sc;
629 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
630 	ifp->if_init = iwn_init;
631 	ifp->if_ioctl = iwn_ioctl;
632 	ifp->if_start = iwn_start;
633 	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
634 	ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
635 	IFQ_SET_READY(&ifp->if_snd);
636 
637 	ieee80211_ifattach(ic, macaddr);
638 	ic->ic_vap_create = iwn_vap_create;
639 	ic->ic_vap_delete = iwn_vap_delete;
640 	ic->ic_raw_xmit = iwn_raw_xmit;
641 	ic->ic_node_alloc = iwn_node_alloc;
642 	sc->sc_ampdu_rx_start = ic->ic_ampdu_rx_start;
643 	ic->ic_ampdu_rx_start = iwn_ampdu_rx_start;
644 	sc->sc_ampdu_rx_stop = ic->ic_ampdu_rx_stop;
645 	ic->ic_ampdu_rx_stop = iwn_ampdu_rx_stop;
646 	sc->sc_addba_request = ic->ic_addba_request;
647 	ic->ic_addba_request = iwn_addba_request;
648 	sc->sc_addba_response = ic->ic_addba_response;
649 	ic->ic_addba_response = iwn_addba_response;
650 	sc->sc_addba_stop = ic->ic_addba_stop;
651 	ic->ic_addba_stop = iwn_ampdu_tx_stop;
652 	ic->ic_newassoc = iwn_newassoc;
653 	ic->ic_wme.wme_update = iwn_updateedca;
654 	ic->ic_update_mcast = iwn_update_mcast;
655 	ic->ic_scan_start = iwn_scan_start;
656 	ic->ic_scan_end = iwn_scan_end;
657 	ic->ic_set_channel = iwn_set_channel;
658 	ic->ic_scan_curchan = iwn_scan_curchan;
659 	ic->ic_scan_mindwell = iwn_scan_mindwell;
660 	ic->ic_setregdomain = iwn_setregdomain;
661 
662 	iwn_radiotap_attach(sc);
663 
664 	callout_init_mtx(&sc->calib_to, &sc->sc_mtx, 0);
665 	callout_init_mtx(&sc->watchdog_to, &sc->sc_mtx, 0);
666 	TASK_INIT(&sc->sc_reinit_task, 0, iwn_hw_reset, sc);
667 	TASK_INIT(&sc->sc_radioon_task, 0, iwn_radio_on, sc);
668 	TASK_INIT(&sc->sc_radiooff_task, 0, iwn_radio_off, sc);
669 
670 	iwn_sysctlattach(sc);
671 
672 	/*
673 	 * Hook our interrupt after all initialization is complete.
674 	 */
675 	error = bus_setup_intr(dev, sc->irq, INTR_TYPE_NET | INTR_MPSAFE,
676 	    NULL, iwn_intr, sc, &sc->sc_ih);
677 	if (error != 0) {
678 		device_printf(dev, "can't establish interrupt, error %d\n",
679 		    error);
680 		goto fail;
681 	}
682 
683 	if (bootverbose)
684 		ieee80211_announce(ic);
685 	return 0;
686 fail:
687 	iwn_detach(dev);
688 	return error;
689 }
690 
691 static int
692 iwn4965_attach(struct iwn_softc *sc, uint16_t pid)
693 {
694 	struct iwn_ops *ops = &sc->ops;
695 
696 	ops->load_firmware = iwn4965_load_firmware;
697 	ops->read_eeprom = iwn4965_read_eeprom;
698 	ops->post_alive = iwn4965_post_alive;
699 	ops->nic_config = iwn4965_nic_config;
700 	ops->update_sched = iwn4965_update_sched;
701 	ops->get_temperature = iwn4965_get_temperature;
702 	ops->get_rssi = iwn4965_get_rssi;
703 	ops->set_txpower = iwn4965_set_txpower;
704 	ops->init_gains = iwn4965_init_gains;
705 	ops->set_gains = iwn4965_set_gains;
706 	ops->add_node = iwn4965_add_node;
707 	ops->tx_done = iwn4965_tx_done;
708 	ops->ampdu_tx_start = iwn4965_ampdu_tx_start;
709 	ops->ampdu_tx_stop = iwn4965_ampdu_tx_stop;
710 	sc->ntxqs = IWN4965_NTXQUEUES;
711 	sc->firstaggqueue = IWN4965_FIRSTAGGQUEUE;
712 	sc->ndmachnls = IWN4965_NDMACHNLS;
713 	sc->broadcast_id = IWN4965_ID_BROADCAST;
714 	sc->rxonsz = IWN4965_RXONSZ;
715 	sc->schedsz = IWN4965_SCHEDSZ;
716 	sc->fw_text_maxsz = IWN4965_FW_TEXT_MAXSZ;
717 	sc->fw_data_maxsz = IWN4965_FW_DATA_MAXSZ;
718 	sc->fwsz = IWN4965_FWSZ;
719 	sc->sched_txfact_addr = IWN4965_SCHED_TXFACT;
720 	sc->limits = &iwn4965_sensitivity_limits;
721 	sc->fwname = "iwn4965fw";
722 	/* Override chains masks, ROM is known to be broken. */
723 	sc->txchainmask = IWN_ANT_AB;
724 	sc->rxchainmask = IWN_ANT_ABC;
725 
726 	return 0;
727 }
728 
729 static int
730 iwn5000_attach(struct iwn_softc *sc, uint16_t pid)
731 {
732 	struct iwn_ops *ops = &sc->ops;
733 
734 	ops->load_firmware = iwn5000_load_firmware;
735 	ops->read_eeprom = iwn5000_read_eeprom;
736 	ops->post_alive = iwn5000_post_alive;
737 	ops->nic_config = iwn5000_nic_config;
738 	ops->update_sched = iwn5000_update_sched;
739 	ops->get_temperature = iwn5000_get_temperature;
740 	ops->get_rssi = iwn5000_get_rssi;
741 	ops->set_txpower = iwn5000_set_txpower;
742 	ops->init_gains = iwn5000_init_gains;
743 	ops->set_gains = iwn5000_set_gains;
744 	ops->add_node = iwn5000_add_node;
745 	ops->tx_done = iwn5000_tx_done;
746 	ops->ampdu_tx_start = iwn5000_ampdu_tx_start;
747 	ops->ampdu_tx_stop = iwn5000_ampdu_tx_stop;
748 	sc->ntxqs = IWN5000_NTXQUEUES;
749 	sc->firstaggqueue = IWN5000_FIRSTAGGQUEUE;
750 	sc->ndmachnls = IWN5000_NDMACHNLS;
751 	sc->broadcast_id = IWN5000_ID_BROADCAST;
752 	sc->rxonsz = IWN5000_RXONSZ;
753 	sc->schedsz = IWN5000_SCHEDSZ;
754 	sc->fw_text_maxsz = IWN5000_FW_TEXT_MAXSZ;
755 	sc->fw_data_maxsz = IWN5000_FW_DATA_MAXSZ;
756 	sc->fwsz = IWN5000_FWSZ;
757 	sc->sched_txfact_addr = IWN5000_SCHED_TXFACT;
758 	sc->reset_noise_gain = IWN5000_PHY_CALIB_RESET_NOISE_GAIN;
759 	sc->noise_gain = IWN5000_PHY_CALIB_NOISE_GAIN;
760 
761 	switch (sc->hw_type) {
762 	case IWN_HW_REV_TYPE_5100:
763 		sc->limits = &iwn5000_sensitivity_limits;
764 		sc->fwname = "iwn5000fw";
765 		/* Override chains masks, ROM is known to be broken. */
766 		sc->txchainmask = IWN_ANT_B;
767 		sc->rxchainmask = IWN_ANT_AB;
768 		break;
769 	case IWN_HW_REV_TYPE_5150:
770 		sc->limits = &iwn5150_sensitivity_limits;
771 		sc->fwname = "iwn5150fw";
772 		break;
773 	case IWN_HW_REV_TYPE_5300:
774 	case IWN_HW_REV_TYPE_5350:
775 		sc->limits = &iwn5000_sensitivity_limits;
776 		sc->fwname = "iwn5000fw";
777 		break;
778 	case IWN_HW_REV_TYPE_1000:
779 		sc->limits = &iwn1000_sensitivity_limits;
780 		sc->fwname = "iwn1000fw";
781 		break;
782 	case IWN_HW_REV_TYPE_6000:
783 		sc->limits = &iwn6000_sensitivity_limits;
784 		sc->fwname = "iwn6000fw";
785 		if (pid == 0x422c || pid == 0x4239) {
786 			sc->sc_flags |= IWN_FLAG_INTERNAL_PA;
787 			/* Override chains masks, ROM is known to be broken. */
788 			sc->txchainmask = IWN_ANT_BC;
789 			sc->rxchainmask = IWN_ANT_BC;
790 		}
791 		break;
792 	case IWN_HW_REV_TYPE_6050:
793 		sc->limits = &iwn6000_sensitivity_limits;
794 		sc->fwname = "iwn6050fw";
795 		/* Override chains masks, ROM is known to be broken. */
796 		sc->txchainmask = IWN_ANT_AB;
797 		sc->rxchainmask = IWN_ANT_AB;
798 		break;
799 	case IWN_HW_REV_TYPE_6005:
800 		sc->limits = &iwn6000_sensitivity_limits;
801 		if (pid != 0x0082 && pid != 0x0085) {
802 			sc->fwname = "iwn6000g2bfw";
803 			sc->sc_flags |= IWN_FLAG_ADV_BTCOEX;
804 		} else
805 			sc->fwname = "iwn6000g2afw";
806 		break;
807 	default:
808 		device_printf(sc->sc_dev, "adapter type %d not supported\n",
809 		    sc->hw_type);
810 		return ENOTSUP;
811 	}
812 	return 0;
813 }
814 
815 /*
816  * Attach the interface to 802.11 radiotap.
817  */
818 static void
819 iwn_radiotap_attach(struct iwn_softc *sc)
820 {
821 	struct ifnet *ifp = sc->sc_ifp;
822 	struct ieee80211com *ic = ifp->if_l2com;
823 
824 	ieee80211_radiotap_attach(ic,
825 	    &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap),
826 		IWN_TX_RADIOTAP_PRESENT,
827 	    &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
828 		IWN_RX_RADIOTAP_PRESENT);
829 }
830 
831 static void
832 iwn_sysctlattach(struct iwn_softc *sc)
833 {
834 	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
835 	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
836 
837 #ifdef IWN_DEBUG
838 	sc->sc_debug = 0;
839 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
840 	    "debug", CTLFLAG_RW, &sc->sc_debug, 0, "control debugging printfs");
841 #endif
842 }
843 
844 static struct ieee80211vap *
845 iwn_vap_create(struct ieee80211com *ic,
846     const char name[IFNAMSIZ], int unit, int opmode, int flags,
847     const uint8_t bssid[IEEE80211_ADDR_LEN],
848     const uint8_t mac[IEEE80211_ADDR_LEN])
849 {
850 	struct iwn_vap *ivp;
851 	struct ieee80211vap *vap;
852 
853 	if (!TAILQ_EMPTY(&ic->ic_vaps))		/* only one at a time */
854 		return NULL;
855 	ivp = (struct iwn_vap *) malloc(sizeof(struct iwn_vap),
856 	    M_80211_VAP, M_NOWAIT | M_ZERO);
857 	if (ivp == NULL)
858 		return NULL;
859 	vap = &ivp->iv_vap;
860 	ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid, mac);
861 	vap->iv_bmissthreshold = 10;		/* override default */
862 	/* Override with driver methods. */
863 	ivp->iv_newstate = vap->iv_newstate;
864 	vap->iv_newstate = iwn_newstate;
865 
866 	ieee80211_ratectl_init(vap);
867 	/* Complete setup. */
868 	ieee80211_vap_attach(vap, iwn_media_change, ieee80211_media_status);
869 	ic->ic_opmode = opmode;
870 	return vap;
871 }
872 
873 static void
874 iwn_vap_delete(struct ieee80211vap *vap)
875 {
876 	struct iwn_vap *ivp = IWN_VAP(vap);
877 
878 	ieee80211_ratectl_deinit(vap);
879 	ieee80211_vap_detach(vap);
880 	free(ivp, M_80211_VAP);
881 }
882 
883 static int
884 iwn_detach(device_t dev)
885 {
886 	struct iwn_softc *sc = device_get_softc(dev);
887 	struct ifnet *ifp = sc->sc_ifp;
888 	struct ieee80211com *ic;
889 	int qid;
890 
891 	if (ifp != NULL) {
892 		ic = ifp->if_l2com;
893 
894 		ieee80211_draintask(ic, &sc->sc_reinit_task);
895 		ieee80211_draintask(ic, &sc->sc_radioon_task);
896 		ieee80211_draintask(ic, &sc->sc_radiooff_task);
897 
898 		iwn_stop(sc);
899 		callout_drain(&sc->watchdog_to);
900 		callout_drain(&sc->calib_to);
901 		ieee80211_ifdetach(ic);
902 	}
903 
904 	/* Uninstall interrupt handler. */
905 	if (sc->irq != NULL) {
906 		bus_teardown_intr(dev, sc->irq, sc->sc_ih);
907 		bus_release_resource(dev, SYS_RES_IRQ, sc->irq_rid, sc->irq);
908 		if (sc->irq_rid == 1)
909 			pci_release_msi(dev);
910 	}
911 
912 	/* Free DMA resources. */
913 	iwn_free_rx_ring(sc, &sc->rxq);
914 	for (qid = 0; qid < sc->ntxqs; qid++)
915 		iwn_free_tx_ring(sc, &sc->txq[qid]);
916 	iwn_free_sched(sc);
917 	iwn_free_kw(sc);
918 	if (sc->ict != NULL)
919 		iwn_free_ict(sc);
920 	iwn_free_fwmem(sc);
921 
922 	if (sc->mem != NULL)
923 		bus_release_resource(dev, SYS_RES_MEMORY, sc->mem_rid, sc->mem);
924 
925 	if (ifp != NULL)
926 		if_free(ifp);
927 
928 	IWN_LOCK_DESTROY(sc);
929 	return 0;
930 }
931 
932 static int
933 iwn_shutdown(device_t dev)
934 {
935 	struct iwn_softc *sc = device_get_softc(dev);
936 
937 	iwn_stop(sc);
938 	return 0;
939 }
940 
941 static int
942 iwn_suspend(device_t dev)
943 {
944 	struct iwn_softc *sc = device_get_softc(dev);
945 	struct ifnet *ifp = sc->sc_ifp;
946 	struct ieee80211com *ic = ifp->if_l2com;
947 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
948 
949 	iwn_stop(sc);
950 	if (vap != NULL)
951 		ieee80211_stop(vap);
952 	return 0;
953 }
954 
955 static int
956 iwn_resume(device_t dev)
957 {
958 	struct iwn_softc *sc = device_get_softc(dev);
959 	struct ifnet *ifp = sc->sc_ifp;
960 	struct ieee80211com *ic = ifp->if_l2com;
961 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
962 
963 	/* Clear device-specific "PCI retry timeout" register (41h). */
964 	pci_write_config(dev, 0x41, 0, 1);
965 
966 	if (ifp->if_flags & IFF_UP) {
967 		iwn_init(sc);
968 		if (vap != NULL)
969 			ieee80211_init(vap);
970 		if (ifp->if_drv_flags & IFF_DRV_RUNNING)
971 			iwn_start(ifp);
972 	}
973 	return 0;
974 }
975 
976 static int
977 iwn_nic_lock(struct iwn_softc *sc)
978 {
979 	int ntries;
980 
981 	/* Request exclusive access to NIC. */
982 	IWN_SETBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_MAC_ACCESS_REQ);
983 
984 	/* Spin until we actually get the lock. */
985 	for (ntries = 0; ntries < 1000; ntries++) {
986 		if ((IWN_READ(sc, IWN_GP_CNTRL) &
987 		     (IWN_GP_CNTRL_MAC_ACCESS_ENA | IWN_GP_CNTRL_SLEEP)) ==
988 		    IWN_GP_CNTRL_MAC_ACCESS_ENA)
989 			return 0;
990 		DELAY(10);
991 	}
992 	return ETIMEDOUT;
993 }
994 
995 static __inline void
996 iwn_nic_unlock(struct iwn_softc *sc)
997 {
998 	IWN_CLRBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_MAC_ACCESS_REQ);
999 }
1000 
1001 static __inline uint32_t
1002 iwn_prph_read(struct iwn_softc *sc, uint32_t addr)
1003 {
1004 	IWN_WRITE(sc, IWN_PRPH_RADDR, IWN_PRPH_DWORD | addr);
1005 	IWN_BARRIER_READ_WRITE(sc);
1006 	return IWN_READ(sc, IWN_PRPH_RDATA);
1007 }
1008 
1009 static __inline void
1010 iwn_prph_write(struct iwn_softc *sc, uint32_t addr, uint32_t data)
1011 {
1012 	IWN_WRITE(sc, IWN_PRPH_WADDR, IWN_PRPH_DWORD | addr);
1013 	IWN_BARRIER_WRITE(sc);
1014 	IWN_WRITE(sc, IWN_PRPH_WDATA, data);
1015 }
1016 
1017 static __inline void
1018 iwn_prph_setbits(struct iwn_softc *sc, uint32_t addr, uint32_t mask)
1019 {
1020 	iwn_prph_write(sc, addr, iwn_prph_read(sc, addr) | mask);
1021 }
1022 
1023 static __inline void
1024 iwn_prph_clrbits(struct iwn_softc *sc, uint32_t addr, uint32_t mask)
1025 {
1026 	iwn_prph_write(sc, addr, iwn_prph_read(sc, addr) & ~mask);
1027 }
1028 
1029 static __inline void
1030 iwn_prph_write_region_4(struct iwn_softc *sc, uint32_t addr,
1031     const uint32_t *data, int count)
1032 {
1033 	for (; count > 0; count--, data++, addr += 4)
1034 		iwn_prph_write(sc, addr, *data);
1035 }
1036 
1037 static __inline uint32_t
1038 iwn_mem_read(struct iwn_softc *sc, uint32_t addr)
1039 {
1040 	IWN_WRITE(sc, IWN_MEM_RADDR, addr);
1041 	IWN_BARRIER_READ_WRITE(sc);
1042 	return IWN_READ(sc, IWN_MEM_RDATA);
1043 }
1044 
1045 static __inline void
1046 iwn_mem_write(struct iwn_softc *sc, uint32_t addr, uint32_t data)
1047 {
1048 	IWN_WRITE(sc, IWN_MEM_WADDR, addr);
1049 	IWN_BARRIER_WRITE(sc);
1050 	IWN_WRITE(sc, IWN_MEM_WDATA, data);
1051 }
1052 
1053 static __inline void
1054 iwn_mem_write_2(struct iwn_softc *sc, uint32_t addr, uint16_t data)
1055 {
1056 	uint32_t tmp;
1057 
1058 	tmp = iwn_mem_read(sc, addr & ~3);
1059 	if (addr & 3)
1060 		tmp = (tmp & 0x0000ffff) | data << 16;
1061 	else
1062 		tmp = (tmp & 0xffff0000) | data;
1063 	iwn_mem_write(sc, addr & ~3, tmp);
1064 }
1065 
1066 static __inline void
1067 iwn_mem_read_region_4(struct iwn_softc *sc, uint32_t addr, uint32_t *data,
1068     int count)
1069 {
1070 	for (; count > 0; count--, addr += 4)
1071 		*data++ = iwn_mem_read(sc, addr);
1072 }
1073 
1074 static __inline void
1075 iwn_mem_set_region_4(struct iwn_softc *sc, uint32_t addr, uint32_t val,
1076     int count)
1077 {
1078 	for (; count > 0; count--, addr += 4)
1079 		iwn_mem_write(sc, addr, val);
1080 }
1081 
1082 static int
1083 iwn_eeprom_lock(struct iwn_softc *sc)
1084 {
1085 	int i, ntries;
1086 
1087 	for (i = 0; i < 100; i++) {
1088 		/* Request exclusive access to EEPROM. */
1089 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
1090 		    IWN_HW_IF_CONFIG_EEPROM_LOCKED);
1091 
1092 		/* Spin until we actually get the lock. */
1093 		for (ntries = 0; ntries < 100; ntries++) {
1094 			if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
1095 			    IWN_HW_IF_CONFIG_EEPROM_LOCKED)
1096 				return 0;
1097 			DELAY(10);
1098 		}
1099 	}
1100 	return ETIMEDOUT;
1101 }
1102 
1103 static __inline void
1104 iwn_eeprom_unlock(struct iwn_softc *sc)
1105 {
1106 	IWN_CLRBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_EEPROM_LOCKED);
1107 }
1108 
1109 /*
1110  * Initialize access by host to One Time Programmable ROM.
1111  * NB: This kind of ROM can be found on 1000 or 6000 Series only.
1112  */
1113 static int
1114 iwn_init_otprom(struct iwn_softc *sc)
1115 {
1116 	uint16_t prev, base, next;
1117 	int count, error;
1118 
1119 	/* Wait for clock stabilization before accessing prph. */
1120 	if ((error = iwn_clock_wait(sc)) != 0)
1121 		return error;
1122 
1123 	if ((error = iwn_nic_lock(sc)) != 0)
1124 		return error;
1125 	iwn_prph_setbits(sc, IWN_APMG_PS, IWN_APMG_PS_RESET_REQ);
1126 	DELAY(5);
1127 	iwn_prph_clrbits(sc, IWN_APMG_PS, IWN_APMG_PS_RESET_REQ);
1128 	iwn_nic_unlock(sc);
1129 
1130 	/* Set auto clock gate disable bit for HW with OTP shadow RAM. */
1131 	if (sc->hw_type != IWN_HW_REV_TYPE_1000) {
1132 		IWN_SETBITS(sc, IWN_DBG_LINK_PWR_MGMT,
1133 		    IWN_RESET_LINK_PWR_MGMT_DIS);
1134 	}
1135 	IWN_CLRBITS(sc, IWN_EEPROM_GP, IWN_EEPROM_GP_IF_OWNER);
1136 	/* Clear ECC status. */
1137 	IWN_SETBITS(sc, IWN_OTP_GP,
1138 	    IWN_OTP_GP_ECC_CORR_STTS | IWN_OTP_GP_ECC_UNCORR_STTS);
1139 
1140 	/*
1141 	 * Find the block before last block (contains the EEPROM image)
1142 	 * for HW without OTP shadow RAM.
1143 	 */
1144 	if (sc->hw_type == IWN_HW_REV_TYPE_1000) {
1145 		/* Switch to absolute addressing mode. */
1146 		IWN_CLRBITS(sc, IWN_OTP_GP, IWN_OTP_GP_RELATIVE_ACCESS);
1147 		base = prev = 0;
1148 		for (count = 0; count < IWN1000_OTP_NBLOCKS; count++) {
1149 			error = iwn_read_prom_data(sc, base, &next, 2);
1150 			if (error != 0)
1151 				return error;
1152 			if (next == 0)	/* End of linked-list. */
1153 				break;
1154 			prev = base;
1155 			base = le16toh(next);
1156 		}
1157 		if (count == 0 || count == IWN1000_OTP_NBLOCKS)
1158 			return EIO;
1159 		/* Skip "next" word. */
1160 		sc->prom_base = prev + 1;
1161 	}
1162 	return 0;
1163 }
1164 
1165 static int
1166 iwn_read_prom_data(struct iwn_softc *sc, uint32_t addr, void *data, int count)
1167 {
1168 	uint8_t *out = data;
1169 	uint32_t val, tmp;
1170 	int ntries;
1171 
1172 	addr += sc->prom_base;
1173 	for (; count > 0; count -= 2, addr++) {
1174 		IWN_WRITE(sc, IWN_EEPROM, addr << 2);
1175 		for (ntries = 0; ntries < 10; ntries++) {
1176 			val = IWN_READ(sc, IWN_EEPROM);
1177 			if (val & IWN_EEPROM_READ_VALID)
1178 				break;
1179 			DELAY(5);
1180 		}
1181 		if (ntries == 10) {
1182 			device_printf(sc->sc_dev,
1183 			    "timeout reading ROM at 0x%x\n", addr);
1184 			return ETIMEDOUT;
1185 		}
1186 		if (sc->sc_flags & IWN_FLAG_HAS_OTPROM) {
1187 			/* OTPROM, check for ECC errors. */
1188 			tmp = IWN_READ(sc, IWN_OTP_GP);
1189 			if (tmp & IWN_OTP_GP_ECC_UNCORR_STTS) {
1190 				device_printf(sc->sc_dev,
1191 				    "OTPROM ECC error at 0x%x\n", addr);
1192 				return EIO;
1193 			}
1194 			if (tmp & IWN_OTP_GP_ECC_CORR_STTS) {
1195 				/* Correctable ECC error, clear bit. */
1196 				IWN_SETBITS(sc, IWN_OTP_GP,
1197 				    IWN_OTP_GP_ECC_CORR_STTS);
1198 			}
1199 		}
1200 		*out++ = val >> 16;
1201 		if (count > 1)
1202 			*out++ = val >> 24;
1203 	}
1204 	return 0;
1205 }
1206 
1207 static void
1208 iwn_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1209 {
1210 	if (error != 0)
1211 		return;
1212 	KASSERT(nsegs == 1, ("too many DMA segments, %d should be 1", nsegs));
1213 	*(bus_addr_t *)arg = segs[0].ds_addr;
1214 }
1215 
1216 static int
1217 iwn_dma_contig_alloc(struct iwn_softc *sc, struct iwn_dma_info *dma,
1218     void **kvap, bus_size_t size, bus_size_t alignment)
1219 {
1220 	int error;
1221 
1222 	dma->tag = NULL;
1223 	dma->size = size;
1224 
1225 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), alignment,
1226 	    0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, size,
1227 	    1, size, BUS_DMA_NOWAIT, NULL, NULL, &dma->tag);
1228 	if (error != 0)
1229 		goto fail;
1230 
1231 	error = bus_dmamem_alloc(dma->tag, (void **)&dma->vaddr,
1232 	    BUS_DMA_NOWAIT | BUS_DMA_ZERO | BUS_DMA_COHERENT, &dma->map);
1233 	if (error != 0)
1234 		goto fail;
1235 
1236 	error = bus_dmamap_load(dma->tag, dma->map, dma->vaddr, size,
1237 	    iwn_dma_map_addr, &dma->paddr, BUS_DMA_NOWAIT);
1238 	if (error != 0)
1239 		goto fail;
1240 
1241 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
1242 
1243 	if (kvap != NULL)
1244 		*kvap = dma->vaddr;
1245 
1246 	return 0;
1247 
1248 fail:	iwn_dma_contig_free(dma);
1249 	return error;
1250 }
1251 
1252 static void
1253 iwn_dma_contig_free(struct iwn_dma_info *dma)
1254 {
1255 	if (dma->map != NULL) {
1256 		if (dma->vaddr != NULL) {
1257 			bus_dmamap_sync(dma->tag, dma->map,
1258 			    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1259 			bus_dmamap_unload(dma->tag, dma->map);
1260 			bus_dmamem_free(dma->tag, &dma->vaddr, dma->map);
1261 			dma->vaddr = NULL;
1262 		}
1263 		bus_dmamap_destroy(dma->tag, dma->map);
1264 		dma->map = NULL;
1265 	}
1266 	if (dma->tag != NULL) {
1267 		bus_dma_tag_destroy(dma->tag);
1268 		dma->tag = NULL;
1269 	}
1270 }
1271 
1272 static int
1273 iwn_alloc_sched(struct iwn_softc *sc)
1274 {
1275 	/* TX scheduler rings must be aligned on a 1KB boundary. */
1276 	return iwn_dma_contig_alloc(sc, &sc->sched_dma, (void **)&sc->sched,
1277 	    sc->schedsz, 1024);
1278 }
1279 
1280 static void
1281 iwn_free_sched(struct iwn_softc *sc)
1282 {
1283 	iwn_dma_contig_free(&sc->sched_dma);
1284 }
1285 
1286 static int
1287 iwn_alloc_kw(struct iwn_softc *sc)
1288 {
1289 	/* "Keep Warm" page must be aligned on a 4KB boundary. */
1290 	return iwn_dma_contig_alloc(sc, &sc->kw_dma, NULL, 4096, 4096);
1291 }
1292 
1293 static void
1294 iwn_free_kw(struct iwn_softc *sc)
1295 {
1296 	iwn_dma_contig_free(&sc->kw_dma);
1297 }
1298 
1299 static int
1300 iwn_alloc_ict(struct iwn_softc *sc)
1301 {
1302 	/* ICT table must be aligned on a 4KB boundary. */
1303 	return iwn_dma_contig_alloc(sc, &sc->ict_dma, (void **)&sc->ict,
1304 	    IWN_ICT_SIZE, 4096);
1305 }
1306 
1307 static void
1308 iwn_free_ict(struct iwn_softc *sc)
1309 {
1310 	iwn_dma_contig_free(&sc->ict_dma);
1311 }
1312 
1313 static int
1314 iwn_alloc_fwmem(struct iwn_softc *sc)
1315 {
1316 	/* Must be aligned on a 16-byte boundary. */
1317 	return iwn_dma_contig_alloc(sc, &sc->fw_dma, NULL, sc->fwsz, 16);
1318 }
1319 
1320 static void
1321 iwn_free_fwmem(struct iwn_softc *sc)
1322 {
1323 	iwn_dma_contig_free(&sc->fw_dma);
1324 }
1325 
1326 static int
1327 iwn_alloc_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
1328 {
1329 	bus_size_t size;
1330 	int i, error;
1331 
1332 	ring->cur = 0;
1333 
1334 	/* Allocate RX descriptors (256-byte aligned). */
1335 	size = IWN_RX_RING_COUNT * sizeof (uint32_t);
1336 	error = iwn_dma_contig_alloc(sc, &ring->desc_dma, (void **)&ring->desc,
1337 	    size, 256);
1338 	if (error != 0) {
1339 		device_printf(sc->sc_dev,
1340 		    "%s: could not allocate RX ring DMA memory, error %d\n",
1341 		    __func__, error);
1342 		goto fail;
1343 	}
1344 
1345 	/* Allocate RX status area (16-byte aligned). */
1346 	error = iwn_dma_contig_alloc(sc, &ring->stat_dma, (void **)&ring->stat,
1347 	    sizeof (struct iwn_rx_status), 16);
1348 	if (error != 0) {
1349 		device_printf(sc->sc_dev,
1350 		    "%s: could not allocate RX status DMA memory, error %d\n",
1351 		    __func__, error);
1352 		goto fail;
1353 	}
1354 
1355 	/* Create RX buffer DMA tag. */
1356 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
1357 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
1358 	    IWN_RBUF_SIZE, 1, IWN_RBUF_SIZE, BUS_DMA_NOWAIT, NULL, NULL,
1359 	    &ring->data_dmat);
1360 	if (error != 0) {
1361 		device_printf(sc->sc_dev,
1362 		    "%s: could not create RX buf DMA tag, error %d\n",
1363 		    __func__, error);
1364 		goto fail;
1365 	}
1366 
1367 	/*
1368 	 * Allocate and map RX buffers.
1369 	 */
1370 	for (i = 0; i < IWN_RX_RING_COUNT; i++) {
1371 		struct iwn_rx_data *data = &ring->data[i];
1372 		bus_addr_t paddr;
1373 
1374 		error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
1375 		if (error != 0) {
1376 			device_printf(sc->sc_dev,
1377 			    "%s: could not create RX buf DMA map, error %d\n",
1378 			    __func__, error);
1379 			goto fail;
1380 		}
1381 
1382 		data->m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR,
1383 		    IWN_RBUF_SIZE);
1384 		if (data->m == NULL) {
1385 			device_printf(sc->sc_dev,
1386 			    "%s: could not allocate RX mbuf\n", __func__);
1387 			error = ENOBUFS;
1388 			goto fail;
1389 		}
1390 
1391 		error = bus_dmamap_load(ring->data_dmat, data->map,
1392 		    mtod(data->m, void *), IWN_RBUF_SIZE, iwn_dma_map_addr,
1393 		    &paddr, BUS_DMA_NOWAIT);
1394 		if (error != 0 && error != EFBIG) {
1395 			device_printf(sc->sc_dev,
1396 			    "%s: can't not map mbuf, error %d\n", __func__,
1397 			    error);
1398 			goto fail;
1399 		}
1400 
1401 		/* Set physical address of RX buffer (256-byte aligned). */
1402 		ring->desc[i] = htole32(paddr >> 8);
1403 	}
1404 
1405 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
1406 	    BUS_DMASYNC_PREWRITE);
1407 
1408 	return 0;
1409 
1410 fail:	iwn_free_rx_ring(sc, ring);
1411 	return error;
1412 }
1413 
1414 static void
1415 iwn_reset_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
1416 {
1417 	int ntries;
1418 
1419 	if (iwn_nic_lock(sc) == 0) {
1420 		IWN_WRITE(sc, IWN_FH_RX_CONFIG, 0);
1421 		for (ntries = 0; ntries < 1000; ntries++) {
1422 			if (IWN_READ(sc, IWN_FH_RX_STATUS) &
1423 			    IWN_FH_RX_STATUS_IDLE)
1424 				break;
1425 			DELAY(10);
1426 		}
1427 		iwn_nic_unlock(sc);
1428 	}
1429 	ring->cur = 0;
1430 	sc->last_rx_valid = 0;
1431 }
1432 
1433 static void
1434 iwn_free_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
1435 {
1436 	int i;
1437 
1438 	iwn_dma_contig_free(&ring->desc_dma);
1439 	iwn_dma_contig_free(&ring->stat_dma);
1440 
1441 	for (i = 0; i < IWN_RX_RING_COUNT; i++) {
1442 		struct iwn_rx_data *data = &ring->data[i];
1443 
1444 		if (data->m != NULL) {
1445 			bus_dmamap_sync(ring->data_dmat, data->map,
1446 			    BUS_DMASYNC_POSTREAD);
1447 			bus_dmamap_unload(ring->data_dmat, data->map);
1448 			m_freem(data->m);
1449 			data->m = NULL;
1450 		}
1451 		if (data->map != NULL)
1452 			bus_dmamap_destroy(ring->data_dmat, data->map);
1453 	}
1454 	if (ring->data_dmat != NULL) {
1455 		bus_dma_tag_destroy(ring->data_dmat);
1456 		ring->data_dmat = NULL;
1457 	}
1458 }
1459 
1460 static int
1461 iwn_alloc_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring, int qid)
1462 {
1463 	bus_addr_t paddr;
1464 	bus_size_t size;
1465 	int i, error;
1466 
1467 	ring->qid = qid;
1468 	ring->queued = 0;
1469 	ring->cur = 0;
1470 
1471 	/* Allocate TX descriptors (256-byte aligned). */
1472 	size = IWN_TX_RING_COUNT * sizeof (struct iwn_tx_desc);
1473 	error = iwn_dma_contig_alloc(sc, &ring->desc_dma, (void **)&ring->desc,
1474 	    size, 256);
1475 	if (error != 0) {
1476 		device_printf(sc->sc_dev,
1477 		    "%s: could not allocate TX ring DMA memory, error %d\n",
1478 		    __func__, error);
1479 		goto fail;
1480 	}
1481 
1482 	size = IWN_TX_RING_COUNT * sizeof (struct iwn_tx_cmd);
1483 	error = iwn_dma_contig_alloc(sc, &ring->cmd_dma, (void **)&ring->cmd,
1484 	    size, 4);
1485 	if (error != 0) {
1486 		device_printf(sc->sc_dev,
1487 		    "%s: could not allocate TX cmd DMA memory, error %d\n",
1488 		    __func__, error);
1489 		goto fail;
1490 	}
1491 
1492 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
1493 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
1494 	    IWN_MAX_SCATTER - 1, MCLBYTES, BUS_DMA_NOWAIT, NULL, NULL,
1495 	    &ring->data_dmat);
1496 	if (error != 0) {
1497 		device_printf(sc->sc_dev,
1498 		    "%s: could not create TX buf DMA tag, error %d\n",
1499 		    __func__, error);
1500 		goto fail;
1501 	}
1502 
1503 	paddr = ring->cmd_dma.paddr;
1504 	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
1505 		struct iwn_tx_data *data = &ring->data[i];
1506 
1507 		data->cmd_paddr = paddr;
1508 		data->scratch_paddr = paddr + 12;
1509 		paddr += sizeof (struct iwn_tx_cmd);
1510 
1511 		error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
1512 		if (error != 0) {
1513 			device_printf(sc->sc_dev,
1514 			    "%s: could not create TX buf DMA map, error %d\n",
1515 			    __func__, error);
1516 			goto fail;
1517 		}
1518 	}
1519 	return 0;
1520 
1521 fail:	iwn_free_tx_ring(sc, ring);
1522 	return error;
1523 }
1524 
1525 static void
1526 iwn_reset_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
1527 {
1528 	int i;
1529 
1530 	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
1531 		struct iwn_tx_data *data = &ring->data[i];
1532 
1533 		if (data->m != NULL) {
1534 			bus_dmamap_sync(ring->data_dmat, data->map,
1535 			    BUS_DMASYNC_POSTWRITE);
1536 			bus_dmamap_unload(ring->data_dmat, data->map);
1537 			m_freem(data->m);
1538 			data->m = NULL;
1539 		}
1540 	}
1541 	/* Clear TX descriptors. */
1542 	memset(ring->desc, 0, ring->desc_dma.size);
1543 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
1544 	    BUS_DMASYNC_PREWRITE);
1545 	sc->qfullmsk &= ~(1 << ring->qid);
1546 	ring->queued = 0;
1547 	ring->cur = 0;
1548 }
1549 
1550 static void
1551 iwn_free_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
1552 {
1553 	int i;
1554 
1555 	iwn_dma_contig_free(&ring->desc_dma);
1556 	iwn_dma_contig_free(&ring->cmd_dma);
1557 
1558 	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
1559 		struct iwn_tx_data *data = &ring->data[i];
1560 
1561 		if (data->m != NULL) {
1562 			bus_dmamap_sync(ring->data_dmat, data->map,
1563 			    BUS_DMASYNC_POSTWRITE);
1564 			bus_dmamap_unload(ring->data_dmat, data->map);
1565 			m_freem(data->m);
1566 		}
1567 		if (data->map != NULL)
1568 			bus_dmamap_destroy(ring->data_dmat, data->map);
1569 	}
1570 	if (ring->data_dmat != NULL) {
1571 		bus_dma_tag_destroy(ring->data_dmat);
1572 		ring->data_dmat = NULL;
1573 	}
1574 }
1575 
1576 static void
1577 iwn5000_ict_reset(struct iwn_softc *sc)
1578 {
1579 	/* Disable interrupts. */
1580 	IWN_WRITE(sc, IWN_INT_MASK, 0);
1581 
1582 	/* Reset ICT table. */
1583 	memset(sc->ict, 0, IWN_ICT_SIZE);
1584 	sc->ict_cur = 0;
1585 
1586 	/* Set physical address of ICT table (4KB aligned). */
1587 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: enabling ICT\n", __func__);
1588 	IWN_WRITE(sc, IWN_DRAM_INT_TBL, IWN_DRAM_INT_TBL_ENABLE |
1589 	    IWN_DRAM_INT_TBL_WRAP_CHECK | sc->ict_dma.paddr >> 12);
1590 
1591 	/* Enable periodic RX interrupt. */
1592 	sc->int_mask |= IWN_INT_RX_PERIODIC;
1593 	/* Switch to ICT interrupt mode in driver. */
1594 	sc->sc_flags |= IWN_FLAG_USE_ICT;
1595 
1596 	/* Re-enable interrupts. */
1597 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
1598 	IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
1599 }
1600 
1601 static int
1602 iwn_read_eeprom(struct iwn_softc *sc, uint8_t macaddr[IEEE80211_ADDR_LEN])
1603 {
1604 	struct iwn_ops *ops = &sc->ops;
1605 	uint16_t val;
1606 	int error;
1607 
1608 	/* Check whether adapter has an EEPROM or an OTPROM. */
1609 	if (sc->hw_type >= IWN_HW_REV_TYPE_1000 &&
1610 	    (IWN_READ(sc, IWN_OTP_GP) & IWN_OTP_GP_DEV_SEL_OTP))
1611 		sc->sc_flags |= IWN_FLAG_HAS_OTPROM;
1612 	DPRINTF(sc, IWN_DEBUG_RESET, "%s found\n",
1613 	    (sc->sc_flags & IWN_FLAG_HAS_OTPROM) ? "OTPROM" : "EEPROM");
1614 
1615 	/* Adapter has to be powered on for EEPROM access to work. */
1616 	if ((error = iwn_apm_init(sc)) != 0) {
1617 		device_printf(sc->sc_dev,
1618 		    "%s: could not power ON adapter, error %d\n", __func__,
1619 		    error);
1620 		return error;
1621 	}
1622 
1623 	if ((IWN_READ(sc, IWN_EEPROM_GP) & 0x7) == 0) {
1624 		device_printf(sc->sc_dev, "%s: bad ROM signature\n", __func__);
1625 		return EIO;
1626 	}
1627 	if ((error = iwn_eeprom_lock(sc)) != 0) {
1628 		device_printf(sc->sc_dev, "%s: could not lock ROM, error %d\n",
1629 		    __func__, error);
1630 		return error;
1631 	}
1632 	if (sc->sc_flags & IWN_FLAG_HAS_OTPROM) {
1633 		if ((error = iwn_init_otprom(sc)) != 0) {
1634 			device_printf(sc->sc_dev,
1635 			    "%s: could not initialize OTPROM, error %d\n",
1636 			    __func__, error);
1637 			return error;
1638 		}
1639 	}
1640 
1641 	iwn_read_prom_data(sc, IWN_EEPROM_SKU_CAP, &val, 2);
1642 	DPRINTF(sc, IWN_DEBUG_RESET, "SKU capabilities=0x%04x\n", le16toh(val));
1643 	/* Check if HT support is bonded out. */
1644 	if (val & htole16(IWN_EEPROM_SKU_CAP_11N))
1645 		sc->sc_flags |= IWN_FLAG_HAS_11N;
1646 
1647 	iwn_read_prom_data(sc, IWN_EEPROM_RFCFG, &val, 2);
1648 	sc->rfcfg = le16toh(val);
1649 	DPRINTF(sc, IWN_DEBUG_RESET, "radio config=0x%04x\n", sc->rfcfg);
1650 	/* Read Tx/Rx chains from ROM unless it's known to be broken. */
1651 	if (sc->txchainmask == 0)
1652 		sc->txchainmask = IWN_RFCFG_TXANTMSK(sc->rfcfg);
1653 	if (sc->rxchainmask == 0)
1654 		sc->rxchainmask = IWN_RFCFG_RXANTMSK(sc->rfcfg);
1655 
1656 	/* Read MAC address. */
1657 	iwn_read_prom_data(sc, IWN_EEPROM_MAC, macaddr, 6);
1658 
1659 	/* Read adapter-specific information from EEPROM. */
1660 	ops->read_eeprom(sc);
1661 
1662 	iwn_apm_stop(sc);	/* Power OFF adapter. */
1663 
1664 	iwn_eeprom_unlock(sc);
1665 	return 0;
1666 }
1667 
1668 static void
1669 iwn4965_read_eeprom(struct iwn_softc *sc)
1670 {
1671 	uint32_t addr;
1672 	uint16_t val;
1673 	int i;
1674 
1675 	/* Read regulatory domain (4 ASCII characters). */
1676 	iwn_read_prom_data(sc, IWN4965_EEPROM_DOMAIN, sc->eeprom_domain, 4);
1677 
1678 	/* Read the list of authorized channels (20MHz ones only). */
1679 	for (i = 0; i < 7; i++) {
1680 		addr = iwn4965_regulatory_bands[i];
1681 		iwn_read_eeprom_channels(sc, i, addr);
1682 	}
1683 
1684 	/* Read maximum allowed TX power for 2GHz and 5GHz bands. */
1685 	iwn_read_prom_data(sc, IWN4965_EEPROM_MAXPOW, &val, 2);
1686 	sc->maxpwr2GHz = val & 0xff;
1687 	sc->maxpwr5GHz = val >> 8;
1688 	/* Check that EEPROM values are within valid range. */
1689 	if (sc->maxpwr5GHz < 20 || sc->maxpwr5GHz > 50)
1690 		sc->maxpwr5GHz = 38;
1691 	if (sc->maxpwr2GHz < 20 || sc->maxpwr2GHz > 50)
1692 		sc->maxpwr2GHz = 38;
1693 	DPRINTF(sc, IWN_DEBUG_RESET, "maxpwr 2GHz=%d 5GHz=%d\n",
1694 	    sc->maxpwr2GHz, sc->maxpwr5GHz);
1695 
1696 	/* Read samples for each TX power group. */
1697 	iwn_read_prom_data(sc, IWN4965_EEPROM_BANDS, sc->bands,
1698 	    sizeof sc->bands);
1699 
1700 	/* Read voltage at which samples were taken. */
1701 	iwn_read_prom_data(sc, IWN4965_EEPROM_VOLTAGE, &val, 2);
1702 	sc->eeprom_voltage = (int16_t)le16toh(val);
1703 	DPRINTF(sc, IWN_DEBUG_RESET, "voltage=%d (in 0.3V)\n",
1704 	    sc->eeprom_voltage);
1705 
1706 #ifdef IWN_DEBUG
1707 	/* Print samples. */
1708 	if (sc->sc_debug & IWN_DEBUG_ANY) {
1709 		for (i = 0; i < IWN_NBANDS; i++)
1710 			iwn4965_print_power_group(sc, i);
1711 	}
1712 #endif
1713 }
1714 
1715 #ifdef IWN_DEBUG
1716 static void
1717 iwn4965_print_power_group(struct iwn_softc *sc, int i)
1718 {
1719 	struct iwn4965_eeprom_band *band = &sc->bands[i];
1720 	struct iwn4965_eeprom_chan_samples *chans = band->chans;
1721 	int j, c;
1722 
1723 	printf("===band %d===\n", i);
1724 	printf("chan lo=%d, chan hi=%d\n", band->lo, band->hi);
1725 	printf("chan1 num=%d\n", chans[0].num);
1726 	for (c = 0; c < 2; c++) {
1727 		for (j = 0; j < IWN_NSAMPLES; j++) {
1728 			printf("chain %d, sample %d: temp=%d gain=%d "
1729 			    "power=%d pa_det=%d\n", c, j,
1730 			    chans[0].samples[c][j].temp,
1731 			    chans[0].samples[c][j].gain,
1732 			    chans[0].samples[c][j].power,
1733 			    chans[0].samples[c][j].pa_det);
1734 		}
1735 	}
1736 	printf("chan2 num=%d\n", chans[1].num);
1737 	for (c = 0; c < 2; c++) {
1738 		for (j = 0; j < IWN_NSAMPLES; j++) {
1739 			printf("chain %d, sample %d: temp=%d gain=%d "
1740 			    "power=%d pa_det=%d\n", c, j,
1741 			    chans[1].samples[c][j].temp,
1742 			    chans[1].samples[c][j].gain,
1743 			    chans[1].samples[c][j].power,
1744 			    chans[1].samples[c][j].pa_det);
1745 		}
1746 	}
1747 }
1748 #endif
1749 
1750 static void
1751 iwn5000_read_eeprom(struct iwn_softc *sc)
1752 {
1753 	struct iwn5000_eeprom_calib_hdr hdr;
1754 	int32_t volt;
1755 	uint32_t base, addr;
1756 	uint16_t val;
1757 	int i;
1758 
1759 	/* Read regulatory domain (4 ASCII characters). */
1760 	iwn_read_prom_data(sc, IWN5000_EEPROM_REG, &val, 2);
1761 	base = le16toh(val);
1762 	iwn_read_prom_data(sc, base + IWN5000_EEPROM_DOMAIN,
1763 	    sc->eeprom_domain, 4);
1764 
1765 	/* Read the list of authorized channels (20MHz ones only). */
1766 	for (i = 0; i < 7; i++) {
1767 		if (sc->hw_type >= IWN_HW_REV_TYPE_6000)
1768 			addr = base + iwn6000_regulatory_bands[i];
1769 		else
1770 			addr = base + iwn5000_regulatory_bands[i];
1771 		iwn_read_eeprom_channels(sc, i, addr);
1772 	}
1773 
1774 	/* Read enhanced TX power information for 6000 Series. */
1775 	if (sc->hw_type >= IWN_HW_REV_TYPE_6000)
1776 		iwn_read_eeprom_enhinfo(sc);
1777 
1778 	iwn_read_prom_data(sc, IWN5000_EEPROM_CAL, &val, 2);
1779 	base = le16toh(val);
1780 	iwn_read_prom_data(sc, base, &hdr, sizeof hdr);
1781 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
1782 	    "%s: calib version=%u pa type=%u voltage=%u\n", __func__,
1783 	    hdr.version, hdr.pa_type, le16toh(hdr.volt));
1784 	sc->calib_ver = hdr.version;
1785 
1786 	if (sc->hw_type == IWN_HW_REV_TYPE_5150) {
1787 		/* Compute temperature offset. */
1788 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_TEMP, &val, 2);
1789 		sc->eeprom_temp = le16toh(val);
1790 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_VOLT, &val, 2);
1791 		volt = le16toh(val);
1792 		sc->temp_off = sc->eeprom_temp - (volt / -5);
1793 		DPRINTF(sc, IWN_DEBUG_CALIBRATE, "temp=%d volt=%d offset=%dK\n",
1794 		    sc->eeprom_temp, volt, sc->temp_off);
1795 	} else {
1796 		/* Read crystal calibration. */
1797 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_CRYSTAL,
1798 		    &sc->eeprom_crystal, sizeof (uint32_t));
1799 		DPRINTF(sc, IWN_DEBUG_CALIBRATE, "crystal calibration 0x%08x\n",
1800 		    le32toh(sc->eeprom_crystal));
1801 	}
1802 }
1803 
1804 /*
1805  * Translate EEPROM flags to net80211.
1806  */
1807 static uint32_t
1808 iwn_eeprom_channel_flags(struct iwn_eeprom_chan *channel)
1809 {
1810 	uint32_t nflags;
1811 
1812 	nflags = 0;
1813 	if ((channel->flags & IWN_EEPROM_CHAN_ACTIVE) == 0)
1814 		nflags |= IEEE80211_CHAN_PASSIVE;
1815 	if ((channel->flags & IWN_EEPROM_CHAN_IBSS) == 0)
1816 		nflags |= IEEE80211_CHAN_NOADHOC;
1817 	if (channel->flags & IWN_EEPROM_CHAN_RADAR) {
1818 		nflags |= IEEE80211_CHAN_DFS;
1819 		/* XXX apparently IBSS may still be marked */
1820 		nflags |= IEEE80211_CHAN_NOADHOC;
1821 	}
1822 
1823 	return nflags;
1824 }
1825 
1826 static void
1827 iwn_read_eeprom_band(struct iwn_softc *sc, int n)
1828 {
1829 	struct ifnet *ifp = sc->sc_ifp;
1830 	struct ieee80211com *ic = ifp->if_l2com;
1831 	struct iwn_eeprom_chan *channels = sc->eeprom_channels[n];
1832 	const struct iwn_chan_band *band = &iwn_bands[n];
1833 	struct ieee80211_channel *c;
1834 	uint8_t chan;
1835 	int i, nflags;
1836 
1837 	for (i = 0; i < band->nchan; i++) {
1838 		if (!(channels[i].flags & IWN_EEPROM_CHAN_VALID)) {
1839 			DPRINTF(sc, IWN_DEBUG_RESET,
1840 			    "skip chan %d flags 0x%x maxpwr %d\n",
1841 			    band->chan[i], channels[i].flags,
1842 			    channels[i].maxpwr);
1843 			continue;
1844 		}
1845 		chan = band->chan[i];
1846 		nflags = iwn_eeprom_channel_flags(&channels[i]);
1847 
1848 		c = &ic->ic_channels[ic->ic_nchans++];
1849 		c->ic_ieee = chan;
1850 		c->ic_maxregpower = channels[i].maxpwr;
1851 		c->ic_maxpower = 2*c->ic_maxregpower;
1852 
1853 		if (n == 0) {	/* 2GHz band */
1854 			c->ic_freq = ieee80211_ieee2mhz(chan, IEEE80211_CHAN_G);
1855 			/* G =>'s B is supported */
1856 			c->ic_flags = IEEE80211_CHAN_B | nflags;
1857 			c = &ic->ic_channels[ic->ic_nchans++];
1858 			c[0] = c[-1];
1859 			c->ic_flags = IEEE80211_CHAN_G | nflags;
1860 		} else {	/* 5GHz band */
1861 			c->ic_freq = ieee80211_ieee2mhz(chan, IEEE80211_CHAN_A);
1862 			c->ic_flags = IEEE80211_CHAN_A | nflags;
1863 		}
1864 
1865 		/* Save maximum allowed TX power for this channel. */
1866 		sc->maxpwr[chan] = channels[i].maxpwr;
1867 
1868 		DPRINTF(sc, IWN_DEBUG_RESET,
1869 		    "add chan %d flags 0x%x maxpwr %d\n", chan,
1870 		    channels[i].flags, channels[i].maxpwr);
1871 
1872 		if (sc->sc_flags & IWN_FLAG_HAS_11N) {
1873 			/* add HT20, HT40 added separately */
1874 			c = &ic->ic_channels[ic->ic_nchans++];
1875 			c[0] = c[-1];
1876 			c->ic_flags |= IEEE80211_CHAN_HT20;
1877 		}
1878 	}
1879 }
1880 
1881 static void
1882 iwn_read_eeprom_ht40(struct iwn_softc *sc, int n)
1883 {
1884 	struct ifnet *ifp = sc->sc_ifp;
1885 	struct ieee80211com *ic = ifp->if_l2com;
1886 	struct iwn_eeprom_chan *channels = sc->eeprom_channels[n];
1887 	const struct iwn_chan_band *band = &iwn_bands[n];
1888 	struct ieee80211_channel *c, *cent, *extc;
1889 	uint8_t chan;
1890 	int i, nflags;
1891 
1892 	if (!(sc->sc_flags & IWN_FLAG_HAS_11N))
1893 		return;
1894 
1895 	for (i = 0; i < band->nchan; i++) {
1896 		if (!(channels[i].flags & IWN_EEPROM_CHAN_VALID)) {
1897 			DPRINTF(sc, IWN_DEBUG_RESET,
1898 			    "skip chan %d flags 0x%x maxpwr %d\n",
1899 			    band->chan[i], channels[i].flags,
1900 			    channels[i].maxpwr);
1901 			continue;
1902 		}
1903 		chan = band->chan[i];
1904 		nflags = iwn_eeprom_channel_flags(&channels[i]);
1905 
1906 		/*
1907 		 * Each entry defines an HT40 channel pair; find the
1908 		 * center channel, then the extension channel above.
1909 		 */
1910 		cent = ieee80211_find_channel_byieee(ic, chan,
1911 		    (n == 5 ? IEEE80211_CHAN_G : IEEE80211_CHAN_A));
1912 		if (cent == NULL) {	/* XXX shouldn't happen */
1913 			device_printf(sc->sc_dev,
1914 			    "%s: no entry for channel %d\n", __func__, chan);
1915 			continue;
1916 		}
1917 		extc = ieee80211_find_channel(ic, cent->ic_freq+20,
1918 		    (n == 5 ? IEEE80211_CHAN_G : IEEE80211_CHAN_A));
1919 		if (extc == NULL) {
1920 			DPRINTF(sc, IWN_DEBUG_RESET,
1921 			    "%s: skip chan %d, extension channel not found\n",
1922 			    __func__, chan);
1923 			continue;
1924 		}
1925 
1926 		DPRINTF(sc, IWN_DEBUG_RESET,
1927 		    "add ht40 chan %d flags 0x%x maxpwr %d\n",
1928 		    chan, channels[i].flags, channels[i].maxpwr);
1929 
1930 		c = &ic->ic_channels[ic->ic_nchans++];
1931 		c[0] = cent[0];
1932 		c->ic_extieee = extc->ic_ieee;
1933 		c->ic_flags &= ~IEEE80211_CHAN_HT;
1934 		c->ic_flags |= IEEE80211_CHAN_HT40U | nflags;
1935 		c = &ic->ic_channels[ic->ic_nchans++];
1936 		c[0] = extc[0];
1937 		c->ic_extieee = cent->ic_ieee;
1938 		c->ic_flags &= ~IEEE80211_CHAN_HT;
1939 		c->ic_flags |= IEEE80211_CHAN_HT40D | nflags;
1940 	}
1941 }
1942 
1943 static void
1944 iwn_read_eeprom_channels(struct iwn_softc *sc, int n, uint32_t addr)
1945 {
1946 	struct ifnet *ifp = sc->sc_ifp;
1947 	struct ieee80211com *ic = ifp->if_l2com;
1948 
1949 	iwn_read_prom_data(sc, addr, &sc->eeprom_channels[n],
1950 	    iwn_bands[n].nchan * sizeof (struct iwn_eeprom_chan));
1951 
1952 	if (n < 5)
1953 		iwn_read_eeprom_band(sc, n);
1954 	else
1955 		iwn_read_eeprom_ht40(sc, n);
1956 	ieee80211_sort_channels(ic->ic_channels, ic->ic_nchans);
1957 }
1958 
1959 static struct iwn_eeprom_chan *
1960 iwn_find_eeprom_channel(struct iwn_softc *sc, struct ieee80211_channel *c)
1961 {
1962 	int band, chan, i, j;
1963 
1964 	if (IEEE80211_IS_CHAN_HT40(c)) {
1965 		band = IEEE80211_IS_CHAN_5GHZ(c) ? 6 : 5;
1966 		if (IEEE80211_IS_CHAN_HT40D(c))
1967 			chan = c->ic_extieee;
1968 		else
1969 			chan = c->ic_ieee;
1970 		for (i = 0; i < iwn_bands[band].nchan; i++) {
1971 			if (iwn_bands[band].chan[i] == chan)
1972 				return &sc->eeprom_channels[band][i];
1973 		}
1974 	} else {
1975 		for (j = 0; j < 5; j++) {
1976 			for (i = 0; i < iwn_bands[j].nchan; i++) {
1977 				if (iwn_bands[j].chan[i] == c->ic_ieee)
1978 					return &sc->eeprom_channels[j][i];
1979 			}
1980 		}
1981 	}
1982 	return NULL;
1983 }
1984 
1985 /*
1986  * Enforce flags read from EEPROM.
1987  */
1988 static int
1989 iwn_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *rd,
1990     int nchan, struct ieee80211_channel chans[])
1991 {
1992 	struct iwn_softc *sc = ic->ic_ifp->if_softc;
1993 	int i;
1994 
1995 	for (i = 0; i < nchan; i++) {
1996 		struct ieee80211_channel *c = &chans[i];
1997 		struct iwn_eeprom_chan *channel;
1998 
1999 		channel = iwn_find_eeprom_channel(sc, c);
2000 		if (channel == NULL) {
2001 			if_printf(ic->ic_ifp,
2002 			    "%s: invalid channel %u freq %u/0x%x\n",
2003 			    __func__, c->ic_ieee, c->ic_freq, c->ic_flags);
2004 			return EINVAL;
2005 		}
2006 		c->ic_flags |= iwn_eeprom_channel_flags(channel);
2007 	}
2008 
2009 	return 0;
2010 }
2011 
2012 #define nitems(_a)	(sizeof((_a)) / sizeof((_a)[0]))
2013 
2014 static void
2015 iwn_read_eeprom_enhinfo(struct iwn_softc *sc)
2016 {
2017 	struct iwn_eeprom_enhinfo enhinfo[35];
2018 	struct ifnet *ifp = sc->sc_ifp;
2019 	struct ieee80211com *ic = ifp->if_l2com;
2020 	struct ieee80211_channel *c;
2021 	uint16_t val, base;
2022 	int8_t maxpwr;
2023 	uint8_t flags;
2024 	int i, j;
2025 
2026 	iwn_read_prom_data(sc, IWN5000_EEPROM_REG, &val, 2);
2027 	base = le16toh(val);
2028 	iwn_read_prom_data(sc, base + IWN6000_EEPROM_ENHINFO,
2029 	    enhinfo, sizeof enhinfo);
2030 
2031 	for (i = 0; i < nitems(enhinfo); i++) {
2032 		flags = enhinfo[i].flags;
2033 		if (!(flags & IWN_ENHINFO_VALID))
2034 			continue;	/* Skip invalid entries. */
2035 
2036 		maxpwr = 0;
2037 		if (sc->txchainmask & IWN_ANT_A)
2038 			maxpwr = MAX(maxpwr, enhinfo[i].chain[0]);
2039 		if (sc->txchainmask & IWN_ANT_B)
2040 			maxpwr = MAX(maxpwr, enhinfo[i].chain[1]);
2041 		if (sc->txchainmask & IWN_ANT_C)
2042 			maxpwr = MAX(maxpwr, enhinfo[i].chain[2]);
2043 		if (sc->ntxchains == 2)
2044 			maxpwr = MAX(maxpwr, enhinfo[i].mimo2);
2045 		else if (sc->ntxchains == 3)
2046 			maxpwr = MAX(maxpwr, enhinfo[i].mimo3);
2047 
2048 		for (j = 0; j < ic->ic_nchans; j++) {
2049 			c = &ic->ic_channels[j];
2050 			if ((flags & IWN_ENHINFO_5GHZ)) {
2051 				if (!IEEE80211_IS_CHAN_A(c))
2052 					continue;
2053 			} else if ((flags & IWN_ENHINFO_OFDM)) {
2054 				if (!IEEE80211_IS_CHAN_G(c))
2055 					continue;
2056 			} else if (!IEEE80211_IS_CHAN_B(c))
2057 				continue;
2058 			if ((flags & IWN_ENHINFO_HT40)) {
2059 				if (!IEEE80211_IS_CHAN_HT40(c))
2060 					continue;
2061 			} else {
2062 				if (IEEE80211_IS_CHAN_HT40(c))
2063 					continue;
2064 			}
2065 			if (enhinfo[i].chan != 0 &&
2066 			    enhinfo[i].chan != c->ic_ieee)
2067 				continue;
2068 
2069 			DPRINTF(sc, IWN_DEBUG_RESET,
2070 			    "channel %d(%x), maxpwr %d\n", c->ic_ieee,
2071 			    c->ic_flags, maxpwr / 2);
2072 			c->ic_maxregpower = maxpwr / 2;
2073 			c->ic_maxpower = maxpwr;
2074 		}
2075 	}
2076 }
2077 
2078 static struct ieee80211_node *
2079 iwn_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
2080 {
2081 	return malloc(sizeof (struct iwn_node), M_80211_NODE,M_NOWAIT | M_ZERO);
2082 }
2083 
2084 static __inline int
2085 rate2plcp(int rate)
2086 {
2087 	switch (rate & 0xff) {
2088 	case 12:	return 0xd;
2089 	case 18:	return 0xf;
2090 	case 24:	return 0x5;
2091 	case 36:	return 0x7;
2092 	case 48:	return 0x9;
2093 	case 72:	return 0xb;
2094 	case 96:	return 0x1;
2095 	case 108:	return 0x3;
2096 	case 2:		return 10;
2097 	case 4:		return 20;
2098 	case 11:	return 55;
2099 	case 22:	return 110;
2100 	}
2101 	return 0;
2102 }
2103 
2104 static void
2105 iwn_newassoc(struct ieee80211_node *ni, int isnew)
2106 {
2107 	struct ieee80211com *ic = ni->ni_ic;
2108 	struct iwn_softc *sc = ic->ic_ifp->if_softc;
2109 	struct iwn_node *wn = (void *)ni;
2110 	uint8_t txant1, txant2;
2111 	int i, plcp, rate, ridx;
2112 
2113 	/* Use the first valid TX antenna. */
2114 	txant1 = IWN_LSB(sc->txchainmask);
2115 	txant2 = IWN_LSB(sc->txchainmask & ~txant1);
2116 
2117 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan)) {
2118 		ridx = ni->ni_rates.rs_nrates - 1;
2119 		for (i = ni->ni_htrates.rs_nrates - 1; i >= 0; i--) {
2120 			plcp = ni->ni_htrates.rs_rates[i] | IWN_RFLAG_MCS;
2121 			if (IEEE80211_IS_CHAN_HT40(ni->ni_chan)) {
2122 				plcp |= IWN_RFLAG_HT40;
2123 				if (ni->ni_htcap & IEEE80211_HTCAP_SHORTGI40)
2124 					plcp |= IWN_RFLAG_SGI;
2125 			} else if (ni->ni_htcap & IEEE80211_HTCAP_SHORTGI20)
2126 				plcp |= IWN_RFLAG_SGI;
2127 			if (i > 7)
2128 				plcp |= IWN_RFLAG_ANT(txant1 | txant2);
2129 			else
2130 				plcp |= IWN_RFLAG_ANT(txant1);
2131 			if (ridx >= 0) {
2132 				rate = ni->ni_rates.rs_rates[ridx];
2133 				rate &= IEEE80211_RATE_VAL;
2134 				wn->ridx[rate] = plcp;
2135 			}
2136 			wn->ridx[IEEE80211_RATE_MCS | i] = plcp;
2137 			ridx--;
2138 		}
2139 	} else {
2140 		for (i = 0; i < ni->ni_rates.rs_nrates; i++) {
2141 			rate = ni->ni_rates.rs_rates[i] & IEEE80211_RATE_VAL;
2142 
2143 			plcp = rate2plcp(rate);
2144 			ridx = ic->ic_rt->rateCodeToIndex[rate];
2145 			if (ridx < IWN_RIDX_OFDM6 &&
2146 			    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
2147 				plcp |= IWN_RFLAG_CCK;
2148 			plcp |= IWN_RFLAG_ANT(txant1);
2149 			wn->ridx[rate] = htole32(plcp);
2150 		}
2151 	}
2152 }
2153 
2154 static int
2155 iwn_media_change(struct ifnet *ifp)
2156 {
2157 	int error;
2158 
2159 	error = ieee80211_media_change(ifp);
2160 	/* NB: only the fixed rate can change and that doesn't need a reset */
2161 	return (error == ENETRESET ? 0 : error);
2162 }
2163 
2164 static int
2165 iwn_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
2166 {
2167 	struct iwn_vap *ivp = IWN_VAP(vap);
2168 	struct ieee80211com *ic = vap->iv_ic;
2169 	struct iwn_softc *sc = ic->ic_ifp->if_softc;
2170 	int error = 0;
2171 
2172 	DPRINTF(sc, IWN_DEBUG_STATE, "%s: %s -> %s\n", __func__,
2173 	    ieee80211_state_name[vap->iv_state], ieee80211_state_name[nstate]);
2174 
2175 	IEEE80211_UNLOCK(ic);
2176 	IWN_LOCK(sc);
2177 	callout_stop(&sc->calib_to);
2178 
2179 	switch (nstate) {
2180 	case IEEE80211_S_ASSOC:
2181 		if (vap->iv_state != IEEE80211_S_RUN)
2182 			break;
2183 		/* FALLTHROUGH */
2184 	case IEEE80211_S_AUTH:
2185 		if (vap->iv_state == IEEE80211_S_AUTH)
2186 			break;
2187 
2188 		/*
2189 		 * !AUTH -> AUTH transition requires state reset to handle
2190 		 * reassociations correctly.
2191 		 */
2192 		sc->rxon.associd = 0;
2193 		sc->rxon.filter &= ~htole32(IWN_FILTER_BSS);
2194 		sc->calib.state = IWN_CALIB_STATE_INIT;
2195 
2196 		if ((error = iwn_auth(sc, vap)) != 0) {
2197 			device_printf(sc->sc_dev,
2198 			    "%s: could not move to auth state\n", __func__);
2199 		}
2200 		break;
2201 
2202 	case IEEE80211_S_RUN:
2203 		/*
2204 		 * RUN -> RUN transition; Just restart the timers.
2205 		 */
2206 		if (vap->iv_state == IEEE80211_S_RUN) {
2207 			sc->calib_cnt = 0;
2208 			break;
2209 		}
2210 
2211 		/*
2212 		 * !RUN -> RUN requires setting the association id
2213 		 * which is done with a firmware cmd.  We also defer
2214 		 * starting the timers until that work is done.
2215 		 */
2216 		if ((error = iwn_run(sc, vap)) != 0) {
2217 			device_printf(sc->sc_dev,
2218 			    "%s: could not move to run state\n", __func__);
2219 		}
2220 		break;
2221 
2222 	case IEEE80211_S_INIT:
2223 		sc->calib.state = IWN_CALIB_STATE_INIT;
2224 		break;
2225 
2226 	default:
2227 		break;
2228 	}
2229 	IWN_UNLOCK(sc);
2230 	IEEE80211_LOCK(ic);
2231 	if (error != 0)
2232 		return error;
2233 	return ivp->iv_newstate(vap, nstate, arg);
2234 }
2235 
2236 static void
2237 iwn_calib_timeout(void *arg)
2238 {
2239 	struct iwn_softc *sc = arg;
2240 
2241 	IWN_LOCK_ASSERT(sc);
2242 
2243 	/* Force automatic TX power calibration every 60 secs. */
2244 	if (++sc->calib_cnt >= 120) {
2245 		uint32_t flags = 0;
2246 
2247 		DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s\n",
2248 		    "sending request for statistics");
2249 		(void)iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags,
2250 		    sizeof flags, 1);
2251 		sc->calib_cnt = 0;
2252 	}
2253 	callout_reset(&sc->calib_to, msecs_to_ticks(500), iwn_calib_timeout,
2254 	    sc);
2255 }
2256 
2257 /*
2258  * Process an RX_PHY firmware notification.  This is usually immediately
2259  * followed by an MPDU_RX_DONE notification.
2260  */
2261 static void
2262 iwn_rx_phy(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2263     struct iwn_rx_data *data)
2264 {
2265 	struct iwn_rx_stat *stat = (struct iwn_rx_stat *)(desc + 1);
2266 
2267 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: received PHY stats\n", __func__);
2268 	bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
2269 
2270 	/* Save RX statistics, they will be used on MPDU_RX_DONE. */
2271 	memcpy(&sc->last_rx_stat, stat, sizeof (*stat));
2272 	sc->last_rx_valid = 1;
2273 }
2274 
2275 /*
2276  * Process an RX_DONE (4965AGN only) or MPDU_RX_DONE firmware notification.
2277  * Each MPDU_RX_DONE notification must be preceded by an RX_PHY one.
2278  */
2279 static void
2280 iwn_rx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2281     struct iwn_rx_data *data)
2282 {
2283 	struct iwn_ops *ops = &sc->ops;
2284 	struct ifnet *ifp = sc->sc_ifp;
2285 	struct ieee80211com *ic = ifp->if_l2com;
2286 	struct iwn_rx_ring *ring = &sc->rxq;
2287 	struct ieee80211_frame *wh;
2288 	struct ieee80211_node *ni;
2289 	struct mbuf *m, *m1;
2290 	struct iwn_rx_stat *stat;
2291 	caddr_t head;
2292 	bus_addr_t paddr;
2293 	uint32_t flags;
2294 	int error, len, rssi, nf;
2295 
2296 	if (desc->type == IWN_MPDU_RX_DONE) {
2297 		/* Check for prior RX_PHY notification. */
2298 		if (!sc->last_rx_valid) {
2299 			DPRINTF(sc, IWN_DEBUG_ANY,
2300 			    "%s: missing RX_PHY\n", __func__);
2301 			return;
2302 		}
2303 		stat = &sc->last_rx_stat;
2304 	} else
2305 		stat = (struct iwn_rx_stat *)(desc + 1);
2306 
2307 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD);
2308 
2309 	if (stat->cfg_phy_len > IWN_STAT_MAXLEN) {
2310 		device_printf(sc->sc_dev,
2311 		    "%s: invalid RX statistic header, len %d\n", __func__,
2312 		    stat->cfg_phy_len);
2313 		return;
2314 	}
2315 	if (desc->type == IWN_MPDU_RX_DONE) {
2316 		struct iwn_rx_mpdu *mpdu = (struct iwn_rx_mpdu *)(desc + 1);
2317 		head = (caddr_t)(mpdu + 1);
2318 		len = le16toh(mpdu->len);
2319 	} else {
2320 		head = (caddr_t)(stat + 1) + stat->cfg_phy_len;
2321 		len = le16toh(stat->len);
2322 	}
2323 
2324 	flags = le32toh(*(uint32_t *)(head + len));
2325 
2326 	/* Discard frames with a bad FCS early. */
2327 	if ((flags & IWN_RX_NOERROR) != IWN_RX_NOERROR) {
2328 		DPRINTF(sc, IWN_DEBUG_RECV, "%s: RX flags error %x\n",
2329 		    __func__, flags);
2330 		ifp->if_ierrors++;
2331 		return;
2332 	}
2333 	/* Discard frames that are too short. */
2334 	if (len < sizeof (*wh)) {
2335 		DPRINTF(sc, IWN_DEBUG_RECV, "%s: frame too short: %d\n",
2336 		    __func__, len);
2337 		ifp->if_ierrors++;
2338 		return;
2339 	}
2340 
2341 	m1 = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, IWN_RBUF_SIZE);
2342 	if (m1 == NULL) {
2343 		DPRINTF(sc, IWN_DEBUG_ANY, "%s: no mbuf to restock ring\n",
2344 		    __func__);
2345 		ifp->if_ierrors++;
2346 		return;
2347 	}
2348 	bus_dmamap_unload(ring->data_dmat, data->map);
2349 
2350 	error = bus_dmamap_load(ring->data_dmat, data->map, mtod(m1, void *),
2351 	    IWN_RBUF_SIZE, iwn_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
2352 	if (error != 0 && error != EFBIG) {
2353 		device_printf(sc->sc_dev,
2354 		    "%s: bus_dmamap_load failed, error %d\n", __func__, error);
2355 		m_freem(m1);
2356 
2357 		/* Try to reload the old mbuf. */
2358 		error = bus_dmamap_load(ring->data_dmat, data->map,
2359 		    mtod(data->m, void *), IWN_RBUF_SIZE, iwn_dma_map_addr,
2360 		    &paddr, BUS_DMA_NOWAIT);
2361 		if (error != 0 && error != EFBIG) {
2362 			panic("%s: could not load old RX mbuf", __func__);
2363 		}
2364 		/* Physical address may have changed. */
2365 		ring->desc[ring->cur] = htole32(paddr >> 8);
2366 		bus_dmamap_sync(ring->data_dmat, ring->desc_dma.map,
2367 		    BUS_DMASYNC_PREWRITE);
2368 		ifp->if_ierrors++;
2369 		return;
2370 	}
2371 
2372 	m = data->m;
2373 	data->m = m1;
2374 	/* Update RX descriptor. */
2375 	ring->desc[ring->cur] = htole32(paddr >> 8);
2376 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
2377 	    BUS_DMASYNC_PREWRITE);
2378 
2379 	/* Finalize mbuf. */
2380 	m->m_pkthdr.rcvif = ifp;
2381 	m->m_data = head;
2382 	m->m_pkthdr.len = m->m_len = len;
2383 
2384 	/* Grab a reference to the source node. */
2385 	wh = mtod(m, struct ieee80211_frame *);
2386 	ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
2387 	nf = (ni != NULL && ni->ni_vap->iv_state == IEEE80211_S_RUN &&
2388 	    (ic->ic_flags & IEEE80211_F_SCAN) == 0) ? sc->noise : -95;
2389 
2390 	rssi = ops->get_rssi(sc, stat);
2391 
2392 	if (ieee80211_radiotap_active(ic)) {
2393 		struct iwn_rx_radiotap_header *tap = &sc->sc_rxtap;
2394 
2395 		tap->wr_flags = 0;
2396 		if (stat->flags & htole16(IWN_STAT_FLAG_SHPREAMBLE))
2397 			tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
2398 		tap->wr_dbm_antsignal = (int8_t)rssi;
2399 		tap->wr_dbm_antnoise = (int8_t)nf;
2400 		tap->wr_tsft = stat->tstamp;
2401 		switch (stat->rate) {
2402 		/* CCK rates. */
2403 		case  10: tap->wr_rate =   2; break;
2404 		case  20: tap->wr_rate =   4; break;
2405 		case  55: tap->wr_rate =  11; break;
2406 		case 110: tap->wr_rate =  22; break;
2407 		/* OFDM rates. */
2408 		case 0xd: tap->wr_rate =  12; break;
2409 		case 0xf: tap->wr_rate =  18; break;
2410 		case 0x5: tap->wr_rate =  24; break;
2411 		case 0x7: tap->wr_rate =  36; break;
2412 		case 0x9: tap->wr_rate =  48; break;
2413 		case 0xb: tap->wr_rate =  72; break;
2414 		case 0x1: tap->wr_rate =  96; break;
2415 		case 0x3: tap->wr_rate = 108; break;
2416 		/* Unknown rate: should not happen. */
2417 		default:  tap->wr_rate =   0;
2418 		}
2419 	}
2420 
2421 	IWN_UNLOCK(sc);
2422 
2423 	/* Send the frame to the 802.11 layer. */
2424 	if (ni != NULL) {
2425 		if (ni->ni_flags & IEEE80211_NODE_HT)
2426 			m->m_flags |= M_AMPDU;
2427 		(void)ieee80211_input(ni, m, rssi - nf, nf);
2428 		/* Node is no longer needed. */
2429 		ieee80211_free_node(ni);
2430 	} else
2431 		(void)ieee80211_input_all(ic, m, rssi - nf, nf);
2432 
2433 	IWN_LOCK(sc);
2434 }
2435 
2436 /* Process an incoming Compressed BlockAck. */
2437 static void
2438 iwn_rx_compressed_ba(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2439     struct iwn_rx_data *data)
2440 {
2441 	struct ifnet *ifp = sc->sc_ifp;
2442 	struct iwn_node *wn;
2443 	struct ieee80211_node *ni;
2444 	struct iwn_compressed_ba *ba = (struct iwn_compressed_ba *)(desc + 1);
2445 	struct iwn_tx_ring *txq;
2446 	struct ieee80211_tx_ampdu *tap;
2447 	uint64_t bitmap;
2448 	uint8_t tid;
2449 	int ackfailcnt = 0, i, shift;
2450 
2451 	bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
2452 
2453 	txq = &sc->txq[le16toh(ba->qid)];
2454 	tap = sc->qid2tap[le16toh(ba->qid)];
2455 	tid = WME_AC_TO_TID(tap->txa_ac);
2456 	ni = tap->txa_ni;
2457 	wn = (void *)ni;
2458 
2459 	if (wn->agg[tid].bitmap == 0)
2460 		return;
2461 
2462 	shift = wn->agg[tid].startidx - ((le16toh(ba->seq) >> 4) & 0xff);
2463 	if (shift < 0)
2464 		shift += 0x100;
2465 
2466 	if (wn->agg[tid].nframes > (64 - shift))
2467 		return;
2468 
2469 	bitmap = (le64toh(ba->bitmap) >> shift) & wn->agg[tid].bitmap;
2470 	for (i = 0; bitmap; i++) {
2471 		if ((bitmap & 1) == 0) {
2472 			ifp->if_oerrors++;
2473 			ieee80211_ratectl_tx_complete(ni->ni_vap, ni,
2474 			    IEEE80211_RATECTL_TX_FAILURE, &ackfailcnt, NULL);
2475 		} else {
2476 			ifp->if_opackets++;
2477 			ieee80211_ratectl_tx_complete(ni->ni_vap, ni,
2478 			    IEEE80211_RATECTL_TX_SUCCESS, &ackfailcnt, NULL);
2479 		}
2480 		bitmap >>= 1;
2481 	}
2482 }
2483 
2484 /*
2485  * Process a CALIBRATION_RESULT notification sent by the initialization
2486  * firmware on response to a CMD_CALIB_CONFIG command (5000 only).
2487  */
2488 static void
2489 iwn5000_rx_calib_results(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2490     struct iwn_rx_data *data)
2491 {
2492 	struct iwn_phy_calib *calib = (struct iwn_phy_calib *)(desc + 1);
2493 	int len, idx = -1;
2494 
2495 	/* Runtime firmware should not send such a notification. */
2496 	if (sc->sc_flags & IWN_FLAG_CALIB_DONE)
2497 		return;
2498 
2499 	len = (le32toh(desc->len) & 0x3fff) - 4;
2500 	bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
2501 
2502 	switch (calib->code) {
2503 	case IWN5000_PHY_CALIB_DC:
2504 		if ((sc->sc_flags & IWN_FLAG_INTERNAL_PA) == 0 &&
2505 		    (sc->hw_type == IWN_HW_REV_TYPE_5150 ||
2506 		     sc->hw_type >= IWN_HW_REV_TYPE_6000))
2507 			idx = 0;
2508 		break;
2509 	case IWN5000_PHY_CALIB_LO:
2510 		idx = 1;
2511 		break;
2512 	case IWN5000_PHY_CALIB_TX_IQ:
2513 		idx = 2;
2514 		break;
2515 	case IWN5000_PHY_CALIB_TX_IQ_PERIODIC:
2516 		if (sc->hw_type < IWN_HW_REV_TYPE_6000 &&
2517 		    sc->hw_type != IWN_HW_REV_TYPE_5150)
2518 			idx = 3;
2519 		break;
2520 	case IWN5000_PHY_CALIB_BASE_BAND:
2521 		idx = 4;
2522 		break;
2523 	}
2524 	if (idx == -1)	/* Ignore other results. */
2525 		return;
2526 
2527 	/* Save calibration result. */
2528 	if (sc->calibcmd[idx].buf != NULL)
2529 		free(sc->calibcmd[idx].buf, M_DEVBUF);
2530 	sc->calibcmd[idx].buf = malloc(len, M_DEVBUF, M_NOWAIT);
2531 	if (sc->calibcmd[idx].buf == NULL) {
2532 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
2533 		    "not enough memory for calibration result %d\n",
2534 		    calib->code);
2535 		return;
2536 	}
2537 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
2538 	    "saving calibration result code=%d len=%d\n", calib->code, len);
2539 	sc->calibcmd[idx].len = len;
2540 	memcpy(sc->calibcmd[idx].buf, calib, len);
2541 }
2542 
2543 /*
2544  * Process an RX_STATISTICS or BEACON_STATISTICS firmware notification.
2545  * The latter is sent by the firmware after each received beacon.
2546  */
2547 static void
2548 iwn_rx_statistics(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2549     struct iwn_rx_data *data)
2550 {
2551 	struct iwn_ops *ops = &sc->ops;
2552 	struct ifnet *ifp = sc->sc_ifp;
2553 	struct ieee80211com *ic = ifp->if_l2com;
2554 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2555 	struct iwn_calib_state *calib = &sc->calib;
2556 	struct iwn_stats *stats = (struct iwn_stats *)(desc + 1);
2557 	int temp;
2558 
2559 	/* Ignore statistics received during a scan. */
2560 	if (vap->iv_state != IEEE80211_S_RUN ||
2561 	    (ic->ic_flags & IEEE80211_F_SCAN))
2562 		return;
2563 
2564 	bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
2565 
2566 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: received statistics, cmd %d\n",
2567 	    __func__, desc->type);
2568 	sc->calib_cnt = 0;	/* Reset TX power calibration timeout. */
2569 
2570 	/* Test if temperature has changed. */
2571 	if (stats->general.temp != sc->rawtemp) {
2572 		/* Convert "raw" temperature to degC. */
2573 		sc->rawtemp = stats->general.temp;
2574 		temp = ops->get_temperature(sc);
2575 		DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: temperature %d\n",
2576 		    __func__, temp);
2577 
2578 		/* Update TX power if need be (4965AGN only). */
2579 		if (sc->hw_type == IWN_HW_REV_TYPE_4965)
2580 			iwn4965_power_calibration(sc, temp);
2581 	}
2582 
2583 	if (desc->type != IWN_BEACON_STATISTICS)
2584 		return;	/* Reply to a statistics request. */
2585 
2586 	sc->noise = iwn_get_noise(&stats->rx.general);
2587 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: noise %d\n", __func__, sc->noise);
2588 
2589 	/* Test that RSSI and noise are present in stats report. */
2590 	if (le32toh(stats->rx.general.flags) != 1) {
2591 		DPRINTF(sc, IWN_DEBUG_ANY, "%s\n",
2592 		    "received statistics without RSSI");
2593 		return;
2594 	}
2595 
2596 	if (calib->state == IWN_CALIB_STATE_ASSOC)
2597 		iwn_collect_noise(sc, &stats->rx.general);
2598 	else if (calib->state == IWN_CALIB_STATE_RUN)
2599 		iwn_tune_sensitivity(sc, &stats->rx);
2600 }
2601 
2602 /*
2603  * Process a TX_DONE firmware notification.  Unfortunately, the 4965AGN
2604  * and 5000 adapters have different incompatible TX status formats.
2605  */
2606 static void
2607 iwn4965_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2608     struct iwn_rx_data *data)
2609 {
2610 	struct iwn4965_tx_stat *stat = (struct iwn4965_tx_stat *)(desc + 1);
2611 	struct iwn_tx_ring *ring;
2612 	int qid;
2613 
2614 	qid = desc->qid & 0xf;
2615 	ring = &sc->txq[qid];
2616 
2617 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: "
2618 	    "qid %d idx %d retries %d nkill %d rate %x duration %d status %x\n",
2619 	    __func__, desc->qid, desc->idx, stat->ackfailcnt,
2620 	    stat->btkillcnt, stat->rate, le16toh(stat->duration),
2621 	    le32toh(stat->status));
2622 
2623 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD);
2624 	if (qid >= sc->firstaggqueue) {
2625 		iwn_ampdu_tx_done(sc, qid, desc->idx, stat->nframes,
2626 		    &stat->status);
2627 	} else {
2628 		iwn_tx_done(sc, desc, stat->ackfailcnt,
2629 		    le32toh(stat->status) & 0xff);
2630 	}
2631 }
2632 
2633 static void
2634 iwn5000_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2635     struct iwn_rx_data *data)
2636 {
2637 	struct iwn5000_tx_stat *stat = (struct iwn5000_tx_stat *)(desc + 1);
2638 	struct iwn_tx_ring *ring;
2639 	int qid;
2640 
2641 	qid = desc->qid & 0xf;
2642 	ring = &sc->txq[qid];
2643 
2644 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: "
2645 	    "qid %d idx %d retries %d nkill %d rate %x duration %d status %x\n",
2646 	    __func__, desc->qid, desc->idx, stat->ackfailcnt,
2647 	    stat->btkillcnt, stat->rate, le16toh(stat->duration),
2648 	    le32toh(stat->status));
2649 
2650 #ifdef notyet
2651 	/* Reset TX scheduler slot. */
2652 	iwn5000_reset_sched(sc, desc->qid & 0xf, desc->idx);
2653 #endif
2654 
2655 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD);
2656 	if (qid >= sc->firstaggqueue) {
2657 		iwn_ampdu_tx_done(sc, qid, desc->idx, stat->nframes,
2658 		    &stat->status);
2659 	} else {
2660 		iwn_tx_done(sc, desc, stat->ackfailcnt,
2661 		    le16toh(stat->status) & 0xff);
2662 	}
2663 }
2664 
2665 /*
2666  * Adapter-independent backend for TX_DONE firmware notifications.
2667  */
2668 static void
2669 iwn_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc, int ackfailcnt,
2670     uint8_t status)
2671 {
2672 	struct ifnet *ifp = sc->sc_ifp;
2673 	struct iwn_tx_ring *ring = &sc->txq[desc->qid & 0xf];
2674 	struct iwn_tx_data *data = &ring->data[desc->idx];
2675 	struct mbuf *m;
2676 	struct ieee80211_node *ni;
2677 	struct ieee80211vap *vap;
2678 
2679 	KASSERT(data->ni != NULL, ("no node"));
2680 
2681 	/* Unmap and free mbuf. */
2682 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTWRITE);
2683 	bus_dmamap_unload(ring->data_dmat, data->map);
2684 	m = data->m, data->m = NULL;
2685 	ni = data->ni, data->ni = NULL;
2686 	vap = ni->ni_vap;
2687 
2688 	if (m->m_flags & M_TXCB) {
2689 		/*
2690 		 * Channels marked for "radar" require traffic to be received
2691 		 * to unlock before we can transmit.  Until traffic is seen
2692 		 * any attempt to transmit is returned immediately with status
2693 		 * set to IWN_TX_FAIL_TX_LOCKED.  Unfortunately this can easily
2694 		 * happen on first authenticate after scanning.  To workaround
2695 		 * this we ignore a failure of this sort in AUTH state so the
2696 		 * 802.11 layer will fall back to using a timeout to wait for
2697 		 * the AUTH reply.  This allows the firmware time to see
2698 		 * traffic so a subsequent retry of AUTH succeeds.  It's
2699 		 * unclear why the firmware does not maintain state for
2700 		 * channels recently visited as this would allow immediate
2701 		 * use of the channel after a scan (where we see traffic).
2702 		 */
2703 		if (status == IWN_TX_FAIL_TX_LOCKED &&
2704 		    ni->ni_vap->iv_state == IEEE80211_S_AUTH)
2705 			ieee80211_process_callback(ni, m, 0);
2706 		else
2707 			ieee80211_process_callback(ni, m,
2708 			    (status & IWN_TX_FAIL) != 0);
2709 	}
2710 
2711 	/*
2712 	 * Update rate control statistics for the node.
2713 	 */
2714 	if (status & IWN_TX_FAIL) {
2715 		ifp->if_oerrors++;
2716 		ieee80211_ratectl_tx_complete(vap, ni,
2717 		    IEEE80211_RATECTL_TX_FAILURE, &ackfailcnt, NULL);
2718 	} else {
2719 		ifp->if_opackets++;
2720 		ieee80211_ratectl_tx_complete(vap, ni,
2721 		    IEEE80211_RATECTL_TX_SUCCESS, &ackfailcnt, NULL);
2722 	}
2723 	m_freem(m);
2724 	ieee80211_free_node(ni);
2725 
2726 	sc->sc_tx_timer = 0;
2727 	if (--ring->queued < IWN_TX_RING_LOMARK) {
2728 		sc->qfullmsk &= ~(1 << ring->qid);
2729 		if (sc->qfullmsk == 0 &&
2730 		    (ifp->if_drv_flags & IFF_DRV_OACTIVE)) {
2731 			ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2732 			iwn_start_locked(ifp);
2733 		}
2734 	}
2735 }
2736 
2737 /*
2738  * Process a "command done" firmware notification.  This is where we wakeup
2739  * processes waiting for a synchronous command completion.
2740  */
2741 static void
2742 iwn_cmd_done(struct iwn_softc *sc, struct iwn_rx_desc *desc)
2743 {
2744 	struct iwn_tx_ring *ring = &sc->txq[4];
2745 	struct iwn_tx_data *data;
2746 
2747 	if ((desc->qid & 0xf) != 4)
2748 		return;	/* Not a command ack. */
2749 
2750 	data = &ring->data[desc->idx];
2751 
2752 	/* If the command was mapped in an mbuf, free it. */
2753 	if (data->m != NULL) {
2754 		bus_dmamap_sync(ring->data_dmat, data->map,
2755 		    BUS_DMASYNC_POSTWRITE);
2756 		bus_dmamap_unload(ring->data_dmat, data->map);
2757 		m_freem(data->m);
2758 		data->m = NULL;
2759 	}
2760 	wakeup(&ring->desc[desc->idx]);
2761 }
2762 
2763 static void
2764 iwn_ampdu_tx_done(struct iwn_softc *sc, int qid, int idx, int nframes,
2765     void *stat)
2766 {
2767 	struct ifnet *ifp = sc->sc_ifp;
2768 	struct iwn_tx_ring *ring = &sc->txq[qid];
2769 	struct iwn_tx_data *data;
2770 	struct mbuf *m;
2771 	struct iwn_node *wn;
2772 	struct ieee80211_node *ni;
2773 	struct ieee80211vap *vap;
2774 	struct ieee80211_tx_ampdu *tap;
2775 	uint64_t bitmap;
2776 	uint32_t *status = stat;
2777 	uint16_t *aggstatus = stat;
2778 	uint8_t tid;
2779 	int bit, i, lastidx, seqno, shift, start;
2780 
2781 #ifdef NOT_YET
2782 	if (nframes == 1) {
2783 		if ((*status & 0xff) != 1 && (*status & 0xff) != 2)
2784 			printf("ieee80211_send_bar()\n");
2785 	}
2786 #endif
2787 
2788 	bitmap = 0;
2789 	start = idx;
2790 	for (i = 0; i < nframes; i++) {
2791 		if (le16toh(aggstatus[i * 2]) & 0xc)
2792 			continue;
2793 
2794 		idx = le16toh(aggstatus[2*i + 1]) & 0xff;
2795 		bit = idx - start;
2796 		shift = 0;
2797 		if (bit >= 64) {
2798 			shift = 0x100 - idx + start;
2799 			bit = 0;
2800 			start = idx;
2801 		} else if (bit <= -64)
2802 			bit = 0x100 - start + idx;
2803 		else if (bit < 0) {
2804 			shift = start - idx;
2805 			start = idx;
2806 			bit = 0;
2807 		}
2808 		bitmap = bitmap << shift;
2809 		bitmap |= 1ULL << bit;
2810 	}
2811 	tap = sc->qid2tap[qid];
2812 	tid = WME_AC_TO_TID(tap->txa_ac);
2813 	wn = (void *)tap->txa_ni;
2814 	wn->agg[tid].bitmap = bitmap;
2815 	wn->agg[tid].startidx = start;
2816 	wn->agg[tid].nframes = nframes;
2817 
2818 	seqno = le32toh(*(status + nframes)) & 0xfff;
2819 	for (lastidx = (seqno & 0xff); ring->read != lastidx;) {
2820 		data = &ring->data[ring->read];
2821 
2822 		KASSERT(data->ni != NULL, ("no node"));
2823 
2824 		/* Unmap and free mbuf. */
2825 		bus_dmamap_sync(ring->data_dmat, data->map,
2826 		    BUS_DMASYNC_POSTWRITE);
2827 		bus_dmamap_unload(ring->data_dmat, data->map);
2828 		m = data->m, data->m = NULL;
2829 		ni = data->ni, data->ni = NULL;
2830 		vap = ni->ni_vap;
2831 
2832 		if (m->m_flags & M_TXCB)
2833 			ieee80211_process_callback(ni, m, 1);
2834 
2835 		m_freem(m);
2836 		ieee80211_free_node(ni);
2837 
2838 		ring->queued--;
2839 		ring->read = (ring->read + 1) % IWN_TX_RING_COUNT;
2840 	}
2841 
2842 	sc->sc_tx_timer = 0;
2843 	if (ring->queued < IWN_TX_RING_LOMARK) {
2844 		sc->qfullmsk &= ~(1 << ring->qid);
2845 		if (sc->qfullmsk == 0 &&
2846 		    (ifp->if_drv_flags & IFF_DRV_OACTIVE)) {
2847 			ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2848 			iwn_start_locked(ifp);
2849 		}
2850 	}
2851 }
2852 
2853 /*
2854  * Process an INT_FH_RX or INT_SW_RX interrupt.
2855  */
2856 static void
2857 iwn_notif_intr(struct iwn_softc *sc)
2858 {
2859 	struct iwn_ops *ops = &sc->ops;
2860 	struct ifnet *ifp = sc->sc_ifp;
2861 	struct ieee80211com *ic = ifp->if_l2com;
2862 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2863 	uint16_t hw;
2864 
2865 	bus_dmamap_sync(sc->rxq.stat_dma.tag, sc->rxq.stat_dma.map,
2866 	    BUS_DMASYNC_POSTREAD);
2867 
2868 	hw = le16toh(sc->rxq.stat->closed_count) & 0xfff;
2869 	while (sc->rxq.cur != hw) {
2870 		struct iwn_rx_data *data = &sc->rxq.data[sc->rxq.cur];
2871 		struct iwn_rx_desc *desc;
2872 
2873 		bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2874 		    BUS_DMASYNC_POSTREAD);
2875 		desc = mtod(data->m, struct iwn_rx_desc *);
2876 
2877 		DPRINTF(sc, IWN_DEBUG_RECV,
2878 		    "%s: qid %x idx %d flags %x type %d(%s) len %d\n",
2879 		    __func__, desc->qid & 0xf, desc->idx, desc->flags,
2880 		    desc->type, iwn_intr_str(desc->type),
2881 		    le16toh(desc->len));
2882 
2883 		if (!(desc->qid & 0x80))	/* Reply to a command. */
2884 			iwn_cmd_done(sc, desc);
2885 
2886 		switch (desc->type) {
2887 		case IWN_RX_PHY:
2888 			iwn_rx_phy(sc, desc, data);
2889 			break;
2890 
2891 		case IWN_RX_DONE:		/* 4965AGN only. */
2892 		case IWN_MPDU_RX_DONE:
2893 			/* An 802.11 frame has been received. */
2894 			iwn_rx_done(sc, desc, data);
2895 			break;
2896 
2897 		case IWN_RX_COMPRESSED_BA:
2898 			/* A Compressed BlockAck has been received. */
2899 			iwn_rx_compressed_ba(sc, desc, data);
2900 			break;
2901 
2902 		case IWN_TX_DONE:
2903 			/* An 802.11 frame has been transmitted. */
2904 			ops->tx_done(sc, desc, data);
2905 			break;
2906 
2907 		case IWN_RX_STATISTICS:
2908 		case IWN_BEACON_STATISTICS:
2909 			iwn_rx_statistics(sc, desc, data);
2910 			break;
2911 
2912 		case IWN_BEACON_MISSED:
2913 		{
2914 			struct iwn_beacon_missed *miss =
2915 			    (struct iwn_beacon_missed *)(desc + 1);
2916 			int misses;
2917 
2918 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2919 			    BUS_DMASYNC_POSTREAD);
2920 			misses = le32toh(miss->consecutive);
2921 
2922 			DPRINTF(sc, IWN_DEBUG_STATE,
2923 			    "%s: beacons missed %d/%d\n", __func__,
2924 			    misses, le32toh(miss->total));
2925 			/*
2926 			 * If more than 5 consecutive beacons are missed,
2927 			 * reinitialize the sensitivity state machine.
2928 			 */
2929 			if (vap->iv_state == IEEE80211_S_RUN &&
2930 			    (ic->ic_flags & IEEE80211_F_SCAN) != 0) {
2931 				if (misses > 5)
2932 					(void)iwn_init_sensitivity(sc);
2933 				if (misses >= vap->iv_bmissthreshold) {
2934 					IWN_UNLOCK(sc);
2935 					ieee80211_beacon_miss(ic);
2936 					IWN_LOCK(sc);
2937 				}
2938 			}
2939 			break;
2940 		}
2941 		case IWN_UC_READY:
2942 		{
2943 			struct iwn_ucode_info *uc =
2944 			    (struct iwn_ucode_info *)(desc + 1);
2945 
2946 			/* The microcontroller is ready. */
2947 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2948 			    BUS_DMASYNC_POSTREAD);
2949 			DPRINTF(sc, IWN_DEBUG_RESET,
2950 			    "microcode alive notification version=%d.%d "
2951 			    "subtype=%x alive=%x\n", uc->major, uc->minor,
2952 			    uc->subtype, le32toh(uc->valid));
2953 
2954 			if (le32toh(uc->valid) != 1) {
2955 				device_printf(sc->sc_dev,
2956 				    "microcontroller initialization failed");
2957 				break;
2958 			}
2959 			if (uc->subtype == IWN_UCODE_INIT) {
2960 				/* Save microcontroller report. */
2961 				memcpy(&sc->ucode_info, uc, sizeof (*uc));
2962 			}
2963 			/* Save the address of the error log in SRAM. */
2964 			sc->errptr = le32toh(uc->errptr);
2965 			break;
2966 		}
2967 		case IWN_STATE_CHANGED:
2968 		{
2969 			uint32_t *status = (uint32_t *)(desc + 1);
2970 
2971 			/*
2972 			 * State change allows hardware switch change to be
2973 			 * noted. However, we handle this in iwn_intr as we
2974 			 * get both the enable/disble intr.
2975 			 */
2976 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2977 			    BUS_DMASYNC_POSTREAD);
2978 			DPRINTF(sc, IWN_DEBUG_INTR, "state changed to %x\n",
2979 			    le32toh(*status));
2980 			break;
2981 		}
2982 		case IWN_START_SCAN:
2983 		{
2984 			struct iwn_start_scan *scan =
2985 			    (struct iwn_start_scan *)(desc + 1);
2986 
2987 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2988 			    BUS_DMASYNC_POSTREAD);
2989 			DPRINTF(sc, IWN_DEBUG_ANY,
2990 			    "%s: scanning channel %d status %x\n",
2991 			    __func__, scan->chan, le32toh(scan->status));
2992 			break;
2993 		}
2994 		case IWN_STOP_SCAN:
2995 		{
2996 			struct iwn_stop_scan *scan =
2997 			    (struct iwn_stop_scan *)(desc + 1);
2998 
2999 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
3000 			    BUS_DMASYNC_POSTREAD);
3001 			DPRINTF(sc, IWN_DEBUG_STATE,
3002 			    "scan finished nchan=%d status=%d chan=%d\n",
3003 			    scan->nchan, scan->status, scan->chan);
3004 
3005 			IWN_UNLOCK(sc);
3006 			ieee80211_scan_next(vap);
3007 			IWN_LOCK(sc);
3008 			break;
3009 		}
3010 		case IWN5000_CALIBRATION_RESULT:
3011 			iwn5000_rx_calib_results(sc, desc, data);
3012 			break;
3013 
3014 		case IWN5000_CALIBRATION_DONE:
3015 			sc->sc_flags |= IWN_FLAG_CALIB_DONE;
3016 			wakeup(sc);
3017 			break;
3018 		}
3019 
3020 		sc->rxq.cur = (sc->rxq.cur + 1) % IWN_RX_RING_COUNT;
3021 	}
3022 
3023 	/* Tell the firmware what we have processed. */
3024 	hw = (hw == 0) ? IWN_RX_RING_COUNT - 1 : hw - 1;
3025 	IWN_WRITE(sc, IWN_FH_RX_WPTR, hw & ~7);
3026 }
3027 
3028 /*
3029  * Process an INT_WAKEUP interrupt raised when the microcontroller wakes up
3030  * from power-down sleep mode.
3031  */
3032 static void
3033 iwn_wakeup_intr(struct iwn_softc *sc)
3034 {
3035 	int qid;
3036 
3037 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: ucode wakeup from power-down sleep\n",
3038 	    __func__);
3039 
3040 	/* Wakeup RX and TX rings. */
3041 	IWN_WRITE(sc, IWN_FH_RX_WPTR, sc->rxq.cur & ~7);
3042 	for (qid = 0; qid < sc->ntxqs; qid++) {
3043 		struct iwn_tx_ring *ring = &sc->txq[qid];
3044 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | ring->cur);
3045 	}
3046 }
3047 
3048 static void
3049 iwn_rftoggle_intr(struct iwn_softc *sc)
3050 {
3051 	struct ifnet *ifp = sc->sc_ifp;
3052 	struct ieee80211com *ic = ifp->if_l2com;
3053 	uint32_t tmp = IWN_READ(sc, IWN_GP_CNTRL);
3054 
3055 	IWN_LOCK_ASSERT(sc);
3056 
3057 	device_printf(sc->sc_dev, "RF switch: radio %s\n",
3058 	    (tmp & IWN_GP_CNTRL_RFKILL) ? "enabled" : "disabled");
3059 	if (tmp & IWN_GP_CNTRL_RFKILL)
3060 		ieee80211_runtask(ic, &sc->sc_radioon_task);
3061 	else
3062 		ieee80211_runtask(ic, &sc->sc_radiooff_task);
3063 }
3064 
3065 /*
3066  * Dump the error log of the firmware when a firmware panic occurs.  Although
3067  * we can't debug the firmware because it is neither open source nor free, it
3068  * can help us to identify certain classes of problems.
3069  */
3070 static void
3071 iwn_fatal_intr(struct iwn_softc *sc)
3072 {
3073 	struct iwn_fw_dump dump;
3074 	int i;
3075 
3076 	IWN_LOCK_ASSERT(sc);
3077 
3078 	/* Force a complete recalibration on next init. */
3079 	sc->sc_flags &= ~IWN_FLAG_CALIB_DONE;
3080 
3081 	/* Check that the error log address is valid. */
3082 	if (sc->errptr < IWN_FW_DATA_BASE ||
3083 	    sc->errptr + sizeof (dump) >
3084 	    IWN_FW_DATA_BASE + sc->fw_data_maxsz) {
3085 		printf("%s: bad firmware error log address 0x%08x\n", __func__,
3086 		    sc->errptr);
3087 		return;
3088 	}
3089 	if (iwn_nic_lock(sc) != 0) {
3090 		printf("%s: could not read firmware error log\n", __func__);
3091 		return;
3092 	}
3093 	/* Read firmware error log from SRAM. */
3094 	iwn_mem_read_region_4(sc, sc->errptr, (uint32_t *)&dump,
3095 	    sizeof (dump) / sizeof (uint32_t));
3096 	iwn_nic_unlock(sc);
3097 
3098 	if (dump.valid == 0) {
3099 		printf("%s: firmware error log is empty\n", __func__);
3100 		return;
3101 	}
3102 	printf("firmware error log:\n");
3103 	printf("  error type      = \"%s\" (0x%08X)\n",
3104 	    (dump.id < nitems(iwn_fw_errmsg)) ?
3105 		iwn_fw_errmsg[dump.id] : "UNKNOWN",
3106 	    dump.id);
3107 	printf("  program counter = 0x%08X\n", dump.pc);
3108 	printf("  source line     = 0x%08X\n", dump.src_line);
3109 	printf("  error data      = 0x%08X%08X\n",
3110 	    dump.error_data[0], dump.error_data[1]);
3111 	printf("  branch link     = 0x%08X%08X\n",
3112 	    dump.branch_link[0], dump.branch_link[1]);
3113 	printf("  interrupt link  = 0x%08X%08X\n",
3114 	    dump.interrupt_link[0], dump.interrupt_link[1]);
3115 	printf("  time            = %u\n", dump.time[0]);
3116 
3117 	/* Dump driver status (TX and RX rings) while we're here. */
3118 	printf("driver status:\n");
3119 	for (i = 0; i < sc->ntxqs; i++) {
3120 		struct iwn_tx_ring *ring = &sc->txq[i];
3121 		printf("  tx ring %2d: qid=%-2d cur=%-3d queued=%-3d\n",
3122 		    i, ring->qid, ring->cur, ring->queued);
3123 	}
3124 	printf("  rx ring: cur=%d\n", sc->rxq.cur);
3125 }
3126 
3127 static void
3128 iwn_intr(void *arg)
3129 {
3130 	struct iwn_softc *sc = arg;
3131 	struct ifnet *ifp = sc->sc_ifp;
3132 	uint32_t r1, r2, tmp;
3133 
3134 	IWN_LOCK(sc);
3135 
3136 	/* Disable interrupts. */
3137 	IWN_WRITE(sc, IWN_INT_MASK, 0);
3138 
3139 	/* Read interrupts from ICT (fast) or from registers (slow). */
3140 	if (sc->sc_flags & IWN_FLAG_USE_ICT) {
3141 		tmp = 0;
3142 		while (sc->ict[sc->ict_cur] != 0) {
3143 			tmp |= sc->ict[sc->ict_cur];
3144 			sc->ict[sc->ict_cur] = 0;	/* Acknowledge. */
3145 			sc->ict_cur = (sc->ict_cur + 1) % IWN_ICT_COUNT;
3146 		}
3147 		tmp = le32toh(tmp);
3148 		if (tmp == 0xffffffff)	/* Shouldn't happen. */
3149 			tmp = 0;
3150 		else if (tmp & 0xc0000)	/* Workaround a HW bug. */
3151 			tmp |= 0x8000;
3152 		r1 = (tmp & 0xff00) << 16 | (tmp & 0xff);
3153 		r2 = 0;	/* Unused. */
3154 	} else {
3155 		r1 = IWN_READ(sc, IWN_INT);
3156 		if (r1 == 0xffffffff || (r1 & 0xfffffff0) == 0xa5a5a5a0)
3157 			return;	/* Hardware gone! */
3158 		r2 = IWN_READ(sc, IWN_FH_INT);
3159 	}
3160 
3161 	DPRINTF(sc, IWN_DEBUG_INTR, "interrupt reg1=%x reg2=%x\n", r1, r2);
3162 
3163 	if (r1 == 0 && r2 == 0)
3164 		goto done;	/* Interrupt not for us. */
3165 
3166 	/* Acknowledge interrupts. */
3167 	IWN_WRITE(sc, IWN_INT, r1);
3168 	if (!(sc->sc_flags & IWN_FLAG_USE_ICT))
3169 		IWN_WRITE(sc, IWN_FH_INT, r2);
3170 
3171 	if (r1 & IWN_INT_RF_TOGGLED) {
3172 		iwn_rftoggle_intr(sc);
3173 		goto done;
3174 	}
3175 	if (r1 & IWN_INT_CT_REACHED) {
3176 		device_printf(sc->sc_dev, "%s: critical temperature reached!\n",
3177 		    __func__);
3178 	}
3179 	if (r1 & (IWN_INT_SW_ERR | IWN_INT_HW_ERR)) {
3180 		device_printf(sc->sc_dev, "%s: fatal firmware error\n",
3181 		    __func__);
3182 		/* Dump firmware error log and stop. */
3183 		iwn_fatal_intr(sc);
3184 		ifp->if_flags &= ~IFF_UP;
3185 		iwn_stop_locked(sc);
3186 		goto done;
3187 	}
3188 	if ((r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX | IWN_INT_RX_PERIODIC)) ||
3189 	    (r2 & IWN_FH_INT_RX)) {
3190 		if (sc->sc_flags & IWN_FLAG_USE_ICT) {
3191 			if (r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX))
3192 				IWN_WRITE(sc, IWN_FH_INT, IWN_FH_INT_RX);
3193 			IWN_WRITE_1(sc, IWN_INT_PERIODIC,
3194 			    IWN_INT_PERIODIC_DIS);
3195 			iwn_notif_intr(sc);
3196 			if (r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX)) {
3197 				IWN_WRITE_1(sc, IWN_INT_PERIODIC,
3198 				    IWN_INT_PERIODIC_ENA);
3199 			}
3200 		} else
3201 			iwn_notif_intr(sc);
3202 	}
3203 
3204 	if ((r1 & IWN_INT_FH_TX) || (r2 & IWN_FH_INT_TX)) {
3205 		if (sc->sc_flags & IWN_FLAG_USE_ICT)
3206 			IWN_WRITE(sc, IWN_FH_INT, IWN_FH_INT_TX);
3207 		wakeup(sc);	/* FH DMA transfer completed. */
3208 	}
3209 
3210 	if (r1 & IWN_INT_ALIVE)
3211 		wakeup(sc);	/* Firmware is alive. */
3212 
3213 	if (r1 & IWN_INT_WAKEUP)
3214 		iwn_wakeup_intr(sc);
3215 
3216 done:
3217 	/* Re-enable interrupts. */
3218 	if (ifp->if_flags & IFF_UP)
3219 		IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
3220 
3221 	IWN_UNLOCK(sc);
3222 }
3223 
3224 /*
3225  * Update TX scheduler ring when transmitting an 802.11 frame (4965AGN and
3226  * 5000 adapters use a slightly different format).
3227  */
3228 static void
3229 iwn4965_update_sched(struct iwn_softc *sc, int qid, int idx, uint8_t id,
3230     uint16_t len)
3231 {
3232 	uint16_t *w = &sc->sched[qid * IWN4965_SCHED_COUNT + idx];
3233 
3234 	*w = htole16(len + 8);
3235 	bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
3236 	    BUS_DMASYNC_PREWRITE);
3237 	if (idx < IWN_SCHED_WINSZ) {
3238 		*(w + IWN_TX_RING_COUNT) = *w;
3239 		bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
3240 		    BUS_DMASYNC_PREWRITE);
3241 	}
3242 }
3243 
3244 static void
3245 iwn5000_update_sched(struct iwn_softc *sc, int qid, int idx, uint8_t id,
3246     uint16_t len)
3247 {
3248 	uint16_t *w = &sc->sched[qid * IWN5000_SCHED_COUNT + idx];
3249 
3250 	*w = htole16(id << 12 | (len + 8));
3251 	bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
3252 	    BUS_DMASYNC_PREWRITE);
3253 	if (idx < IWN_SCHED_WINSZ) {
3254 		*(w + IWN_TX_RING_COUNT) = *w;
3255 		bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
3256 		    BUS_DMASYNC_PREWRITE);
3257 	}
3258 }
3259 
3260 #ifdef notyet
3261 static void
3262 iwn5000_reset_sched(struct iwn_softc *sc, int qid, int idx)
3263 {
3264 	uint16_t *w = &sc->sched[qid * IWN5000_SCHED_COUNT + idx];
3265 
3266 	*w = (*w & htole16(0xf000)) | htole16(1);
3267 	bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
3268 	    BUS_DMASYNC_PREWRITE);
3269 	if (idx < IWN_SCHED_WINSZ) {
3270 		*(w + IWN_TX_RING_COUNT) = *w;
3271 		bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
3272 		    BUS_DMASYNC_PREWRITE);
3273 	}
3274 }
3275 #endif
3276 
3277 static int
3278 iwn_tx_data(struct iwn_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
3279 {
3280 	struct iwn_ops *ops = &sc->ops;
3281 	const struct ieee80211_txparam *tp;
3282 	struct ieee80211vap *vap = ni->ni_vap;
3283 	struct ieee80211com *ic = ni->ni_ic;
3284 	struct iwn_node *wn = (void *)ni;
3285 	struct iwn_tx_ring *ring;
3286 	struct iwn_tx_desc *desc;
3287 	struct iwn_tx_data *data;
3288 	struct iwn_tx_cmd *cmd;
3289 	struct iwn_cmd_data *tx;
3290 	struct ieee80211_frame *wh;
3291 	struct ieee80211_key *k = NULL;
3292 	struct mbuf *m1;
3293 	uint32_t flags;
3294 	uint16_t qos;
3295 	u_int hdrlen;
3296 	bus_dma_segment_t *seg, segs[IWN_MAX_SCATTER];
3297 	uint8_t tid, ridx, txant, type;
3298 	int ac, i, totlen, error, pad, nsegs = 0, rate;
3299 
3300 	IWN_LOCK_ASSERT(sc);
3301 
3302 	wh = mtod(m, struct ieee80211_frame *);
3303 	hdrlen = ieee80211_anyhdrsize(wh);
3304 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
3305 
3306 	/* Select EDCA Access Category and TX ring for this frame. */
3307 	if (IEEE80211_QOS_HAS_SEQ(wh)) {
3308 		qos = ((const struct ieee80211_qosframe *)wh)->i_qos[0];
3309 		tid = qos & IEEE80211_QOS_TID;
3310 	} else {
3311 		qos = 0;
3312 		tid = 0;
3313 	}
3314 	ac = M_WME_GETAC(m);
3315 
3316 	if (IEEE80211_AMPDU_RUNNING(&ni->ni_tx_ampdu[ac])) {
3317 		struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[ac];
3318 
3319 		ring = &sc->txq[*(int *)tap->txa_private];
3320 		*(uint16_t *)wh->i_seq =
3321 		    htole16(ni->ni_txseqs[tid] << IEEE80211_SEQ_SEQ_SHIFT);
3322 		ni->ni_txseqs[tid]++;
3323 	} else {
3324 		ring = &sc->txq[ac];
3325 	}
3326 	desc = &ring->desc[ring->cur];
3327 	data = &ring->data[ring->cur];
3328 
3329 	/* Choose a TX rate index. */
3330 	tp = &vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)];
3331 	if (type == IEEE80211_FC0_TYPE_MGT)
3332 		rate = tp->mgmtrate;
3333 	else if (IEEE80211_IS_MULTICAST(wh->i_addr1))
3334 		rate = tp->mcastrate;
3335 	else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
3336 		rate = tp->ucastrate;
3337 	else {
3338 		/* XXX pass pktlen */
3339 		(void) ieee80211_ratectl_rate(ni, NULL, 0);
3340 		rate = ni->ni_txrate;
3341 	}
3342 	ridx = ic->ic_rt->rateCodeToIndex[rate];
3343 
3344 	/* Encrypt the frame if need be. */
3345 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
3346 		/* Retrieve key for TX. */
3347 		k = ieee80211_crypto_encap(ni, m);
3348 		if (k == NULL) {
3349 			m_freem(m);
3350 			return ENOBUFS;
3351 		}
3352 		/* 802.11 header may have moved. */
3353 		wh = mtod(m, struct ieee80211_frame *);
3354 	}
3355 	totlen = m->m_pkthdr.len;
3356 
3357 	if (ieee80211_radiotap_active_vap(vap)) {
3358 		struct iwn_tx_radiotap_header *tap = &sc->sc_txtap;
3359 
3360 		tap->wt_flags = 0;
3361 		tap->wt_rate = rate;
3362 		if (k != NULL)
3363 			tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
3364 
3365 		ieee80211_radiotap_tx(vap, m);
3366 	}
3367 
3368 	/* Prepare TX firmware command. */
3369 	cmd = &ring->cmd[ring->cur];
3370 	cmd->code = IWN_CMD_TX_DATA;
3371 	cmd->flags = 0;
3372 	cmd->qid = ring->qid;
3373 	cmd->idx = ring->cur;
3374 
3375 	tx = (struct iwn_cmd_data *)cmd->data;
3376 	/* NB: No need to clear tx, all fields are reinitialized here. */
3377 	tx->scratch = 0;	/* clear "scratch" area */
3378 
3379 	flags = 0;
3380 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
3381 		/* Unicast frame, check if an ACK is expected. */
3382 		if (!qos || (qos & IEEE80211_QOS_ACKPOLICY) !=
3383 		    IEEE80211_QOS_ACKPOLICY_NOACK)
3384 			flags |= IWN_TX_NEED_ACK;
3385 	}
3386 	if ((wh->i_fc[0] &
3387 	    (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
3388 	    (IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_BAR))
3389 		flags |= IWN_TX_IMM_BA;		/* Cannot happen yet. */
3390 
3391 	if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG)
3392 		flags |= IWN_TX_MORE_FRAG;	/* Cannot happen yet. */
3393 
3394 	/* Check if frame must be protected using RTS/CTS or CTS-to-self. */
3395 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
3396 		/* NB: Group frames are sent using CCK in 802.11b/g. */
3397 		if (totlen + IEEE80211_CRC_LEN > vap->iv_rtsthreshold) {
3398 			flags |= IWN_TX_NEED_RTS;
3399 		} else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
3400 		    ridx >= IWN_RIDX_OFDM6) {
3401 			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
3402 				flags |= IWN_TX_NEED_CTS;
3403 			else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
3404 				flags |= IWN_TX_NEED_RTS;
3405 		}
3406 		if (flags & (IWN_TX_NEED_RTS | IWN_TX_NEED_CTS)) {
3407 			if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
3408 				/* 5000 autoselects RTS/CTS or CTS-to-self. */
3409 				flags &= ~(IWN_TX_NEED_RTS | IWN_TX_NEED_CTS);
3410 				flags |= IWN_TX_NEED_PROTECTION;
3411 			} else
3412 				flags |= IWN_TX_FULL_TXOP;
3413 		}
3414 	}
3415 
3416 	if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
3417 	    type != IEEE80211_FC0_TYPE_DATA)
3418 		tx->id = sc->broadcast_id;
3419 	else
3420 		tx->id = wn->id;
3421 
3422 	if (type == IEEE80211_FC0_TYPE_MGT) {
3423 		uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
3424 
3425 		/* Tell HW to set timestamp in probe responses. */
3426 		if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
3427 			flags |= IWN_TX_INSERT_TSTAMP;
3428 		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
3429 		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
3430 			tx->timeout = htole16(3);
3431 		else
3432 			tx->timeout = htole16(2);
3433 	} else
3434 		tx->timeout = htole16(0);
3435 
3436 	if (hdrlen & 3) {
3437 		/* First segment length must be a multiple of 4. */
3438 		flags |= IWN_TX_NEED_PADDING;
3439 		pad = 4 - (hdrlen & 3);
3440 	} else
3441 		pad = 0;
3442 
3443 	tx->len = htole16(totlen);
3444 	tx->tid = tid;
3445 	tx->rts_ntries = 60;
3446 	tx->data_ntries = 15;
3447 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
3448 	tx->rate = wn->ridx[rate];
3449 	if (tx->id == sc->broadcast_id) {
3450 		/* Group or management frame. */
3451 		tx->linkq = 0;
3452 		/* XXX Alternate between antenna A and B? */
3453 		txant = IWN_LSB(sc->txchainmask);
3454 		tx->rate |= htole32(IWN_RFLAG_ANT(txant));
3455 	} else {
3456 		tx->linkq = ni->ni_rates.rs_nrates - ridx - 1;
3457 		flags |= IWN_TX_LINKQ;	/* enable MRR */
3458 	}
3459 	/* Set physical address of "scratch area". */
3460 	tx->loaddr = htole32(IWN_LOADDR(data->scratch_paddr));
3461 	tx->hiaddr = IWN_HIADDR(data->scratch_paddr);
3462 
3463 	/* Copy 802.11 header in TX command. */
3464 	memcpy((uint8_t *)(tx + 1), wh, hdrlen);
3465 
3466 	/* Trim 802.11 header. */
3467 	m_adj(m, hdrlen);
3468 	tx->security = 0;
3469 	tx->flags = htole32(flags);
3470 
3471 	error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m, segs,
3472 	    &nsegs, BUS_DMA_NOWAIT);
3473 	if (error != 0) {
3474 		if (error != EFBIG) {
3475 			device_printf(sc->sc_dev,
3476 			    "%s: can't map mbuf (error %d)\n", __func__, error);
3477 			m_freem(m);
3478 			return error;
3479 		}
3480 		/* Too many DMA segments, linearize mbuf. */
3481 		m1 = m_collapse(m, M_DONTWAIT, IWN_MAX_SCATTER);
3482 		if (m1 == NULL) {
3483 			device_printf(sc->sc_dev,
3484 			    "%s: could not defrag mbuf\n", __func__);
3485 			m_freem(m);
3486 			return ENOBUFS;
3487 		}
3488 		m = m1;
3489 
3490 		error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m,
3491 		    segs, &nsegs, BUS_DMA_NOWAIT);
3492 		if (error != 0) {
3493 			device_printf(sc->sc_dev,
3494 			    "%s: can't map mbuf (error %d)\n", __func__, error);
3495 			m_freem(m);
3496 			return error;
3497 		}
3498 	}
3499 
3500 	data->m = m;
3501 	data->ni = ni;
3502 
3503 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: qid %d idx %d len %d nsegs %d\n",
3504 	    __func__, ring->qid, ring->cur, m->m_pkthdr.len, nsegs);
3505 
3506 	/* Fill TX descriptor. */
3507 	desc->nsegs = 1;
3508 	if (m->m_len != 0)
3509 		desc->nsegs += nsegs;
3510 	/* First DMA segment is used by the TX command. */
3511 	desc->segs[0].addr = htole32(IWN_LOADDR(data->cmd_paddr));
3512 	desc->segs[0].len  = htole16(IWN_HIADDR(data->cmd_paddr) |
3513 	    (4 + sizeof (*tx) + hdrlen + pad) << 4);
3514 	/* Other DMA segments are for data payload. */
3515 	seg = &segs[0];
3516 	for (i = 1; i <= nsegs; i++) {
3517 		desc->segs[i].addr = htole32(IWN_LOADDR(seg->ds_addr));
3518 		desc->segs[i].len  = htole16(IWN_HIADDR(seg->ds_addr) |
3519 		    seg->ds_len << 4);
3520 		seg++;
3521 	}
3522 
3523 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
3524 	bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
3525 	    BUS_DMASYNC_PREWRITE);
3526 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
3527 	    BUS_DMASYNC_PREWRITE);
3528 
3529 	/* Update TX scheduler. */
3530 	ops->update_sched(sc, ring->qid, ring->cur, tx->id, totlen);
3531 
3532 	/* Kick TX ring. */
3533 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
3534 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
3535 
3536 	/* Mark TX ring as full if we reach a certain threshold. */
3537 	if (++ring->queued > IWN_TX_RING_HIMARK)
3538 		sc->qfullmsk |= 1 << ring->qid;
3539 
3540 	return 0;
3541 }
3542 
3543 static int
3544 iwn_tx_data_raw(struct iwn_softc *sc, struct mbuf *m,
3545     struct ieee80211_node *ni, const struct ieee80211_bpf_params *params)
3546 {
3547 	struct iwn_ops *ops = &sc->ops;
3548 	struct ifnet *ifp = sc->sc_ifp;
3549 	struct ieee80211vap *vap = ni->ni_vap;
3550 	struct ieee80211com *ic = ifp->if_l2com;
3551 	struct iwn_tx_cmd *cmd;
3552 	struct iwn_cmd_data *tx;
3553 	struct ieee80211_frame *wh;
3554 	struct iwn_tx_ring *ring;
3555 	struct iwn_tx_desc *desc;
3556 	struct iwn_tx_data *data;
3557 	struct mbuf *m1;
3558 	bus_dma_segment_t *seg, segs[IWN_MAX_SCATTER];
3559 	uint32_t flags;
3560 	u_int hdrlen;
3561 	int ac, totlen, error, pad, nsegs = 0, i, rate;
3562 	uint8_t ridx, type, txant;
3563 
3564 	IWN_LOCK_ASSERT(sc);
3565 
3566 	wh = mtod(m, struct ieee80211_frame *);
3567 	hdrlen = ieee80211_anyhdrsize(wh);
3568 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
3569 
3570 	ac = params->ibp_pri & 3;
3571 
3572 	ring = &sc->txq[ac];
3573 	desc = &ring->desc[ring->cur];
3574 	data = &ring->data[ring->cur];
3575 
3576 	/* Choose a TX rate index. */
3577 	rate = params->ibp_rate0;
3578 	ridx = ic->ic_rt->rateCodeToIndex[rate];
3579 	if (ridx == (uint8_t)-1) {
3580 		/* XXX fall back to mcast/mgmt rate? */
3581 		m_freem(m);
3582 		return EINVAL;
3583 	}
3584 
3585 	totlen = m->m_pkthdr.len;
3586 
3587 	/* Prepare TX firmware command. */
3588 	cmd = &ring->cmd[ring->cur];
3589 	cmd->code = IWN_CMD_TX_DATA;
3590 	cmd->flags = 0;
3591 	cmd->qid = ring->qid;
3592 	cmd->idx = ring->cur;
3593 
3594 	tx = (struct iwn_cmd_data *)cmd->data;
3595 	/* NB: No need to clear tx, all fields are reinitialized here. */
3596 	tx->scratch = 0;	/* clear "scratch" area */
3597 
3598 	flags = 0;
3599 	if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0)
3600 		flags |= IWN_TX_NEED_ACK;
3601 	if (params->ibp_flags & IEEE80211_BPF_RTS) {
3602 		if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
3603 			/* 5000 autoselects RTS/CTS or CTS-to-self. */
3604 			flags &= ~IWN_TX_NEED_RTS;
3605 			flags |= IWN_TX_NEED_PROTECTION;
3606 		} else
3607 			flags |= IWN_TX_NEED_RTS | IWN_TX_FULL_TXOP;
3608 	}
3609 	if (params->ibp_flags & IEEE80211_BPF_CTS) {
3610 		if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
3611 			/* 5000 autoselects RTS/CTS or CTS-to-self. */
3612 			flags &= ~IWN_TX_NEED_CTS;
3613 			flags |= IWN_TX_NEED_PROTECTION;
3614 		} else
3615 			flags |= IWN_TX_NEED_CTS | IWN_TX_FULL_TXOP;
3616 	}
3617 	if (type == IEEE80211_FC0_TYPE_MGT) {
3618 		uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
3619 
3620 		/* Tell HW to set timestamp in probe responses. */
3621 		if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
3622 			flags |= IWN_TX_INSERT_TSTAMP;
3623 
3624 		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
3625 		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
3626 			tx->timeout = htole16(3);
3627 		else
3628 			tx->timeout = htole16(2);
3629 	} else
3630 		tx->timeout = htole16(0);
3631 
3632 	if (hdrlen & 3) {
3633 		/* First segment length must be a multiple of 4. */
3634 		flags |= IWN_TX_NEED_PADDING;
3635 		pad = 4 - (hdrlen & 3);
3636 	} else
3637 		pad = 0;
3638 
3639 	if (ieee80211_radiotap_active_vap(vap)) {
3640 		struct iwn_tx_radiotap_header *tap = &sc->sc_txtap;
3641 
3642 		tap->wt_flags = 0;
3643 		tap->wt_rate = rate;
3644 
3645 		ieee80211_radiotap_tx(vap, m);
3646 	}
3647 
3648 	tx->len = htole16(totlen);
3649 	tx->tid = 0;
3650 	tx->id = sc->broadcast_id;
3651 	tx->rts_ntries = params->ibp_try1;
3652 	tx->data_ntries = params->ibp_try0;
3653 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
3654 	tx->rate = htole32(rate2plcp(rate));
3655 	if (ridx < IWN_RIDX_OFDM6 &&
3656 	    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
3657 		tx->rate |= htole32(IWN_RFLAG_CCK);
3658 	/* Group or management frame. */
3659 	tx->linkq = 0;
3660 	txant = IWN_LSB(sc->txchainmask);
3661 	tx->rate |= htole32(IWN_RFLAG_ANT(txant));
3662 	/* Set physical address of "scratch area". */
3663 	tx->loaddr = htole32(IWN_LOADDR(data->scratch_paddr));
3664 	tx->hiaddr = IWN_HIADDR(data->scratch_paddr);
3665 
3666 	/* Copy 802.11 header in TX command. */
3667 	memcpy((uint8_t *)(tx + 1), wh, hdrlen);
3668 
3669 	/* Trim 802.11 header. */
3670 	m_adj(m, hdrlen);
3671 	tx->security = 0;
3672 	tx->flags = htole32(flags);
3673 
3674 	error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m, segs,
3675 	    &nsegs, BUS_DMA_NOWAIT);
3676 	if (error != 0) {
3677 		if (error != EFBIG) {
3678 			device_printf(sc->sc_dev,
3679 			    "%s: can't map mbuf (error %d)\n", __func__, error);
3680 			m_freem(m);
3681 			return error;
3682 		}
3683 		/* Too many DMA segments, linearize mbuf. */
3684 		m1 = m_collapse(m, M_DONTWAIT, IWN_MAX_SCATTER);
3685 		if (m1 == NULL) {
3686 			device_printf(sc->sc_dev,
3687 			    "%s: could not defrag mbuf\n", __func__);
3688 			m_freem(m);
3689 			return ENOBUFS;
3690 		}
3691 		m = m1;
3692 
3693 		error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m,
3694 		    segs, &nsegs, BUS_DMA_NOWAIT);
3695 		if (error != 0) {
3696 			device_printf(sc->sc_dev,
3697 			    "%s: can't map mbuf (error %d)\n", __func__, error);
3698 			m_freem(m);
3699 			return error;
3700 		}
3701 	}
3702 
3703 	data->m = m;
3704 	data->ni = ni;
3705 
3706 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: qid %d idx %d len %d nsegs %d\n",
3707 	    __func__, ring->qid, ring->cur, m->m_pkthdr.len, nsegs);
3708 
3709 	/* Fill TX descriptor. */
3710 	desc->nsegs = 1;
3711 	if (m->m_len != 0)
3712 		desc->nsegs += nsegs;
3713 	/* First DMA segment is used by the TX command. */
3714 	desc->segs[0].addr = htole32(IWN_LOADDR(data->cmd_paddr));
3715 	desc->segs[0].len  = htole16(IWN_HIADDR(data->cmd_paddr) |
3716 	    (4 + sizeof (*tx) + hdrlen + pad) << 4);
3717 	/* Other DMA segments are for data payload. */
3718 	seg = &segs[0];
3719 	for (i = 1; i <= nsegs; i++) {
3720 		desc->segs[i].addr = htole32(IWN_LOADDR(seg->ds_addr));
3721 		desc->segs[i].len  = htole16(IWN_HIADDR(seg->ds_addr) |
3722 		    seg->ds_len << 4);
3723 		seg++;
3724 	}
3725 
3726 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
3727 	bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
3728 	    BUS_DMASYNC_PREWRITE);
3729 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
3730 	    BUS_DMASYNC_PREWRITE);
3731 
3732 	/* Update TX scheduler. */
3733 	ops->update_sched(sc, ring->qid, ring->cur, tx->id, totlen);
3734 
3735 	/* Kick TX ring. */
3736 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
3737 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
3738 
3739 	/* Mark TX ring as full if we reach a certain threshold. */
3740 	if (++ring->queued > IWN_TX_RING_HIMARK)
3741 		sc->qfullmsk |= 1 << ring->qid;
3742 
3743 	return 0;
3744 }
3745 
3746 static int
3747 iwn_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
3748     const struct ieee80211_bpf_params *params)
3749 {
3750 	struct ieee80211com *ic = ni->ni_ic;
3751 	struct ifnet *ifp = ic->ic_ifp;
3752 	struct iwn_softc *sc = ifp->if_softc;
3753 	int error = 0;
3754 
3755 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
3756 		ieee80211_free_node(ni);
3757 		m_freem(m);
3758 		return ENETDOWN;
3759 	}
3760 
3761 	IWN_LOCK(sc);
3762 	if (params == NULL) {
3763 		/*
3764 		 * Legacy path; interpret frame contents to decide
3765 		 * precisely how to send the frame.
3766 		 */
3767 		error = iwn_tx_data(sc, m, ni);
3768 	} else {
3769 		/*
3770 		 * Caller supplied explicit parameters to use in
3771 		 * sending the frame.
3772 		 */
3773 		error = iwn_tx_data_raw(sc, m, ni, params);
3774 	}
3775 	if (error != 0) {
3776 		/* NB: m is reclaimed on tx failure */
3777 		ieee80211_free_node(ni);
3778 		ifp->if_oerrors++;
3779 	}
3780 	sc->sc_tx_timer = 5;
3781 
3782 	IWN_UNLOCK(sc);
3783 	return error;
3784 }
3785 
3786 static void
3787 iwn_start(struct ifnet *ifp)
3788 {
3789 	struct iwn_softc *sc = ifp->if_softc;
3790 
3791 	IWN_LOCK(sc);
3792 	iwn_start_locked(ifp);
3793 	IWN_UNLOCK(sc);
3794 }
3795 
3796 static void
3797 iwn_start_locked(struct ifnet *ifp)
3798 {
3799 	struct iwn_softc *sc = ifp->if_softc;
3800 	struct ieee80211_node *ni;
3801 	struct mbuf *m;
3802 
3803 	IWN_LOCK_ASSERT(sc);
3804 
3805 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
3806 	    (ifp->if_drv_flags & IFF_DRV_OACTIVE))
3807 		return;
3808 
3809 	for (;;) {
3810 		if (sc->qfullmsk != 0) {
3811 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3812 			break;
3813 		}
3814 		IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
3815 		if (m == NULL)
3816 			break;
3817 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
3818 		if (iwn_tx_data(sc, m, ni) != 0) {
3819 			ieee80211_free_node(ni);
3820 			ifp->if_oerrors++;
3821 			continue;
3822 		}
3823 		sc->sc_tx_timer = 5;
3824 	}
3825 }
3826 
3827 static void
3828 iwn_watchdog(void *arg)
3829 {
3830 	struct iwn_softc *sc = arg;
3831 	struct ifnet *ifp = sc->sc_ifp;
3832 	struct ieee80211com *ic = ifp->if_l2com;
3833 
3834 	IWN_LOCK_ASSERT(sc);
3835 
3836 	KASSERT(ifp->if_drv_flags & IFF_DRV_RUNNING, ("not running"));
3837 
3838 	if (sc->sc_tx_timer > 0) {
3839 		if (--sc->sc_tx_timer == 0) {
3840 			if_printf(ifp, "device timeout\n");
3841 			ieee80211_runtask(ic, &sc->sc_reinit_task);
3842 			return;
3843 		}
3844 	}
3845 	callout_reset(&sc->watchdog_to, hz, iwn_watchdog, sc);
3846 }
3847 
3848 static int
3849 iwn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
3850 {
3851 	struct iwn_softc *sc = ifp->if_softc;
3852 	struct ieee80211com *ic = ifp->if_l2com;
3853 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3854 	struct ifreq *ifr = (struct ifreq *) data;
3855 	int error = 0, startall = 0, stop = 0;
3856 
3857 	switch (cmd) {
3858 	case SIOCGIFADDR:
3859 		error = ether_ioctl(ifp, cmd, data);
3860 		break;
3861 	case SIOCSIFFLAGS:
3862 		IWN_LOCK(sc);
3863 		if (ifp->if_flags & IFF_UP) {
3864 			if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
3865 				iwn_init_locked(sc);
3866 				if (IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_RFKILL)
3867 					startall = 1;
3868 				else
3869 					stop = 1;
3870 			}
3871 		} else {
3872 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
3873 				iwn_stop_locked(sc);
3874 		}
3875 		IWN_UNLOCK(sc);
3876 		if (startall)
3877 			ieee80211_start_all(ic);
3878 		else if (vap != NULL && stop)
3879 			ieee80211_stop(vap);
3880 		break;
3881 	case SIOCGIFMEDIA:
3882 		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
3883 		break;
3884 	default:
3885 		error = EINVAL;
3886 		break;
3887 	}
3888 	return error;
3889 }
3890 
3891 /*
3892  * Send a command to the firmware.
3893  */
3894 static int
3895 iwn_cmd(struct iwn_softc *sc, int code, const void *buf, int size, int async)
3896 {
3897 	struct iwn_ops *ops = &sc->ops;
3898 	struct iwn_tx_ring *ring = &sc->txq[4];
3899 	struct iwn_tx_desc *desc;
3900 	struct iwn_tx_data *data;
3901 	struct iwn_tx_cmd *cmd;
3902 	struct mbuf *m;
3903 	bus_addr_t paddr;
3904 	int totlen, error;
3905 
3906 	if (async == 0)
3907 		IWN_LOCK_ASSERT(sc);
3908 
3909 	desc = &ring->desc[ring->cur];
3910 	data = &ring->data[ring->cur];
3911 	totlen = 4 + size;
3912 
3913 	if (size > sizeof cmd->data) {
3914 		/* Command is too large to fit in a descriptor. */
3915 		if (totlen > MCLBYTES)
3916 			return EINVAL;
3917 		m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE);
3918 		if (m == NULL)
3919 			return ENOMEM;
3920 		cmd = mtod(m, struct iwn_tx_cmd *);
3921 		error = bus_dmamap_load(ring->data_dmat, data->map, cmd,
3922 		    totlen, iwn_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
3923 		if (error != 0) {
3924 			m_freem(m);
3925 			return error;
3926 		}
3927 		data->m = m;
3928 	} else {
3929 		cmd = &ring->cmd[ring->cur];
3930 		paddr = data->cmd_paddr;
3931 	}
3932 
3933 	cmd->code = code;
3934 	cmd->flags = 0;
3935 	cmd->qid = ring->qid;
3936 	cmd->idx = ring->cur;
3937 	memcpy(cmd->data, buf, size);
3938 
3939 	desc->nsegs = 1;
3940 	desc->segs[0].addr = htole32(IWN_LOADDR(paddr));
3941 	desc->segs[0].len  = htole16(IWN_HIADDR(paddr) | totlen << 4);
3942 
3943 	DPRINTF(sc, IWN_DEBUG_CMD, "%s: %s (0x%x) flags %d qid %d idx %d\n",
3944 	    __func__, iwn_intr_str(cmd->code), cmd->code,
3945 	    cmd->flags, cmd->qid, cmd->idx);
3946 
3947 	if (size > sizeof cmd->data) {
3948 		bus_dmamap_sync(ring->data_dmat, data->map,
3949 		    BUS_DMASYNC_PREWRITE);
3950 	} else {
3951 		bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
3952 		    BUS_DMASYNC_PREWRITE);
3953 	}
3954 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
3955 	    BUS_DMASYNC_PREWRITE);
3956 
3957 	/* Update TX scheduler. */
3958 	ops->update_sched(sc, ring->qid, ring->cur, 0, 0);
3959 
3960 	/* Kick command ring. */
3961 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
3962 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
3963 
3964 	return async ? 0 : msleep(desc, &sc->sc_mtx, PCATCH, "iwncmd", hz);
3965 }
3966 
3967 static int
3968 iwn4965_add_node(struct iwn_softc *sc, struct iwn_node_info *node, int async)
3969 {
3970 	struct iwn4965_node_info hnode;
3971 	caddr_t src, dst;
3972 
3973 	/*
3974 	 * We use the node structure for 5000 Series internally (it is
3975 	 * a superset of the one for 4965AGN). We thus copy the common
3976 	 * fields before sending the command.
3977 	 */
3978 	src = (caddr_t)node;
3979 	dst = (caddr_t)&hnode;
3980 	memcpy(dst, src, 48);
3981 	/* Skip TSC, RX MIC and TX MIC fields from ``src''. */
3982 	memcpy(dst + 48, src + 72, 20);
3983 	return iwn_cmd(sc, IWN_CMD_ADD_NODE, &hnode, sizeof hnode, async);
3984 }
3985 
3986 static int
3987 iwn5000_add_node(struct iwn_softc *sc, struct iwn_node_info *node, int async)
3988 {
3989 	/* Direct mapping. */
3990 	return iwn_cmd(sc, IWN_CMD_ADD_NODE, node, sizeof (*node), async);
3991 }
3992 
3993 static int
3994 iwn_set_link_quality(struct iwn_softc *sc, struct ieee80211_node *ni)
3995 {
3996 	struct iwn_node *wn = (void *)ni;
3997 	struct ieee80211_rateset *rs = &ni->ni_rates;
3998 	struct iwn_cmd_link_quality linkq;
3999 	uint8_t txant;
4000 	int i, rate, txrate;
4001 
4002 	/* Use the first valid TX antenna. */
4003 	txant = IWN_LSB(sc->txchainmask);
4004 
4005 	memset(&linkq, 0, sizeof linkq);
4006 	linkq.id = wn->id;
4007 	linkq.antmsk_1stream = txant;
4008 	linkq.antmsk_2stream = IWN_ANT_AB;
4009 	linkq.ampdu_max = 64;
4010 	linkq.ampdu_threshold = 3;
4011 	linkq.ampdu_limit = htole16(4000);	/* 4ms */
4012 
4013 	/* Start at highest available bit-rate. */
4014 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan))
4015 		txrate = ni->ni_htrates.rs_nrates - 1;
4016 	else
4017 		txrate = rs->rs_nrates - 1;
4018 	for (i = 0; i < IWN_MAX_TX_RETRIES; i++) {
4019 		if (IEEE80211_IS_CHAN_HT(ni->ni_chan))
4020 			rate = IEEE80211_RATE_MCS | txrate;
4021 		else
4022 			rate = rs->rs_rates[txrate] & IEEE80211_RATE_VAL;
4023 		linkq.retry[i] = wn->ridx[rate];
4024 
4025 		if ((le32toh(wn->ridx[rate]) & IWN_RFLAG_MCS) &&
4026 		    (le32toh(wn->ridx[rate]) & 0xff) > 7)
4027 			linkq.mimo = i + 1;
4028 
4029 		/* Next retry at immediate lower bit-rate. */
4030 		if (txrate > 0)
4031 			txrate--;
4032 	}
4033 	return iwn_cmd(sc, IWN_CMD_LINK_QUALITY, &linkq, sizeof linkq, 1);
4034 }
4035 
4036 /*
4037  * Broadcast node is used to send group-addressed and management frames.
4038  */
4039 static int
4040 iwn_add_broadcast_node(struct iwn_softc *sc, int async)
4041 {
4042 	struct iwn_ops *ops = &sc->ops;
4043 	struct ifnet *ifp = sc->sc_ifp;
4044 	struct ieee80211com *ic = ifp->if_l2com;
4045 	struct iwn_node_info node;
4046 	struct iwn_cmd_link_quality linkq;
4047 	uint8_t txant;
4048 	int i, error;
4049 
4050 	memset(&node, 0, sizeof node);
4051 	IEEE80211_ADDR_COPY(node.macaddr, ifp->if_broadcastaddr);
4052 	node.id = sc->broadcast_id;
4053 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: adding broadcast node\n", __func__);
4054 	if ((error = ops->add_node(sc, &node, async)) != 0)
4055 		return error;
4056 
4057 	/* Use the first valid TX antenna. */
4058 	txant = IWN_LSB(sc->txchainmask);
4059 
4060 	memset(&linkq, 0, sizeof linkq);
4061 	linkq.id = sc->broadcast_id;
4062 	linkq.antmsk_1stream = txant;
4063 	linkq.antmsk_2stream = IWN_ANT_AB;
4064 	linkq.ampdu_max = 64;
4065 	linkq.ampdu_threshold = 3;
4066 	linkq.ampdu_limit = htole16(4000);	/* 4ms */
4067 
4068 	/* Use lowest mandatory bit-rate. */
4069 	if (IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan))
4070 		linkq.retry[0] = htole32(0xd);
4071 	else
4072 		linkq.retry[0] = htole32(10 | IWN_RFLAG_CCK);
4073 	linkq.retry[0] |= htole32(IWN_RFLAG_ANT(txant));
4074 	/* Use same bit-rate for all TX retries. */
4075 	for (i = 1; i < IWN_MAX_TX_RETRIES; i++) {
4076 		linkq.retry[i] = linkq.retry[0];
4077 	}
4078 	return iwn_cmd(sc, IWN_CMD_LINK_QUALITY, &linkq, sizeof linkq, async);
4079 }
4080 
4081 static int
4082 iwn_updateedca(struct ieee80211com *ic)
4083 {
4084 #define IWN_EXP2(x)	((1 << (x)) - 1)	/* CWmin = 2^ECWmin - 1 */
4085 	struct iwn_softc *sc = ic->ic_ifp->if_softc;
4086 	struct iwn_edca_params cmd;
4087 	int aci;
4088 
4089 	memset(&cmd, 0, sizeof cmd);
4090 	cmd.flags = htole32(IWN_EDCA_UPDATE);
4091 	for (aci = 0; aci < WME_NUM_AC; aci++) {
4092 		const struct wmeParams *ac =
4093 		    &ic->ic_wme.wme_chanParams.cap_wmeParams[aci];
4094 		cmd.ac[aci].aifsn = ac->wmep_aifsn;
4095 		cmd.ac[aci].cwmin = htole16(IWN_EXP2(ac->wmep_logcwmin));
4096 		cmd.ac[aci].cwmax = htole16(IWN_EXP2(ac->wmep_logcwmax));
4097 		cmd.ac[aci].txoplimit =
4098 		    htole16(IEEE80211_TXOP_TO_US(ac->wmep_txopLimit));
4099 	}
4100 	IEEE80211_UNLOCK(ic);
4101 	IWN_LOCK(sc);
4102 	(void)iwn_cmd(sc, IWN_CMD_EDCA_PARAMS, &cmd, sizeof cmd, 1);
4103 	IWN_UNLOCK(sc);
4104 	IEEE80211_LOCK(ic);
4105 	return 0;
4106 #undef IWN_EXP2
4107 }
4108 
4109 static void
4110 iwn_update_mcast(struct ifnet *ifp)
4111 {
4112 	/* Ignore */
4113 }
4114 
4115 static void
4116 iwn_set_led(struct iwn_softc *sc, uint8_t which, uint8_t off, uint8_t on)
4117 {
4118 	struct iwn_cmd_led led;
4119 
4120 	/* Clear microcode LED ownership. */
4121 	IWN_CLRBITS(sc, IWN_LED, IWN_LED_BSM_CTRL);
4122 
4123 	led.which = which;
4124 	led.unit = htole32(10000);	/* on/off in unit of 100ms */
4125 	led.off = off;
4126 	led.on = on;
4127 	(void)iwn_cmd(sc, IWN_CMD_SET_LED, &led, sizeof led, 1);
4128 }
4129 
4130 /*
4131  * Set the critical temperature at which the firmware will stop the radio
4132  * and notify us.
4133  */
4134 static int
4135 iwn_set_critical_temp(struct iwn_softc *sc)
4136 {
4137 	struct iwn_critical_temp crit;
4138 	int32_t temp;
4139 
4140 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CTEMP_STOP_RF);
4141 
4142 	if (sc->hw_type == IWN_HW_REV_TYPE_5150)
4143 		temp = (IWN_CTOK(110) - sc->temp_off) * -5;
4144 	else if (sc->hw_type == IWN_HW_REV_TYPE_4965)
4145 		temp = IWN_CTOK(110);
4146 	else
4147 		temp = 110;
4148 	memset(&crit, 0, sizeof crit);
4149 	crit.tempR = htole32(temp);
4150 	DPRINTF(sc, IWN_DEBUG_RESET, "setting critical temp to %d\n", temp);
4151 	return iwn_cmd(sc, IWN_CMD_SET_CRITICAL_TEMP, &crit, sizeof crit, 0);
4152 }
4153 
4154 static int
4155 iwn_set_timing(struct iwn_softc *sc, struct ieee80211_node *ni)
4156 {
4157 	struct iwn_cmd_timing cmd;
4158 	uint64_t val, mod;
4159 
4160 	memset(&cmd, 0, sizeof cmd);
4161 	memcpy(&cmd.tstamp, ni->ni_tstamp.data, sizeof (uint64_t));
4162 	cmd.bintval = htole16(ni->ni_intval);
4163 	cmd.lintval = htole16(10);
4164 
4165 	/* Compute remaining time until next beacon. */
4166 	val = (uint64_t)ni->ni_intval * IEEE80211_DUR_TU;
4167 	mod = le64toh(cmd.tstamp) % val;
4168 	cmd.binitval = htole32((uint32_t)(val - mod));
4169 
4170 	DPRINTF(sc, IWN_DEBUG_RESET, "timing bintval=%u tstamp=%ju, init=%u\n",
4171 	    ni->ni_intval, le64toh(cmd.tstamp), (uint32_t)(val - mod));
4172 
4173 	return iwn_cmd(sc, IWN_CMD_TIMING, &cmd, sizeof cmd, 1);
4174 }
4175 
4176 static void
4177 iwn4965_power_calibration(struct iwn_softc *sc, int temp)
4178 {
4179 	struct ifnet *ifp = sc->sc_ifp;
4180 	struct ieee80211com *ic = ifp->if_l2com;
4181 
4182 	/* Adjust TX power if need be (delta >= 3 degC). */
4183 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: temperature %d->%d\n",
4184 	    __func__, sc->temp, temp);
4185 	if (abs(temp - sc->temp) >= 3) {
4186 		/* Record temperature of last calibration. */
4187 		sc->temp = temp;
4188 		(void)iwn4965_set_txpower(sc, ic->ic_bsschan, 1);
4189 	}
4190 }
4191 
4192 /*
4193  * Set TX power for current channel (each rate has its own power settings).
4194  * This function takes into account the regulatory information from EEPROM,
4195  * the current temperature and the current voltage.
4196  */
4197 static int
4198 iwn4965_set_txpower(struct iwn_softc *sc, struct ieee80211_channel *ch,
4199     int async)
4200 {
4201 /* Fixed-point arithmetic division using a n-bit fractional part. */
4202 #define fdivround(a, b, n)	\
4203 	((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
4204 /* Linear interpolation. */
4205 #define interpolate(x, x1, y1, x2, y2, n)	\
4206 	((y1) + fdivround(((int)(x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
4207 
4208 	static const int tdiv[IWN_NATTEN_GROUPS] = { 9, 8, 8, 8, 6 };
4209 	struct iwn_ucode_info *uc = &sc->ucode_info;
4210 	struct iwn4965_cmd_txpower cmd;
4211 	struct iwn4965_eeprom_chan_samples *chans;
4212 	const uint8_t *rf_gain, *dsp_gain;
4213 	int32_t vdiff, tdiff;
4214 	int i, c, grp, maxpwr;
4215 	uint8_t chan;
4216 
4217 	/* Retrieve current channel from last RXON. */
4218 	chan = sc->rxon.chan;
4219 	DPRINTF(sc, IWN_DEBUG_RESET, "setting TX power for channel %d\n",
4220 	    chan);
4221 
4222 	memset(&cmd, 0, sizeof cmd);
4223 	cmd.band = IEEE80211_IS_CHAN_5GHZ(ch) ? 0 : 1;
4224 	cmd.chan = chan;
4225 
4226 	if (IEEE80211_IS_CHAN_5GHZ(ch)) {
4227 		maxpwr   = sc->maxpwr5GHz;
4228 		rf_gain  = iwn4965_rf_gain_5ghz;
4229 		dsp_gain = iwn4965_dsp_gain_5ghz;
4230 	} else {
4231 		maxpwr   = sc->maxpwr2GHz;
4232 		rf_gain  = iwn4965_rf_gain_2ghz;
4233 		dsp_gain = iwn4965_dsp_gain_2ghz;
4234 	}
4235 
4236 	/* Compute voltage compensation. */
4237 	vdiff = ((int32_t)le32toh(uc->volt) - sc->eeprom_voltage) / 7;
4238 	if (vdiff > 0)
4239 		vdiff *= 2;
4240 	if (abs(vdiff) > 2)
4241 		vdiff = 0;
4242 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
4243 	    "%s: voltage compensation=%d (UCODE=%d, EEPROM=%d)\n",
4244 	    __func__, vdiff, le32toh(uc->volt), sc->eeprom_voltage);
4245 
4246 	/* Get channel attenuation group. */
4247 	if (chan <= 20)		/* 1-20 */
4248 		grp = 4;
4249 	else if (chan <= 43)	/* 34-43 */
4250 		grp = 0;
4251 	else if (chan <= 70)	/* 44-70 */
4252 		grp = 1;
4253 	else if (chan <= 124)	/* 71-124 */
4254 		grp = 2;
4255 	else			/* 125-200 */
4256 		grp = 3;
4257 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
4258 	    "%s: chan %d, attenuation group=%d\n", __func__, chan, grp);
4259 
4260 	/* Get channel sub-band. */
4261 	for (i = 0; i < IWN_NBANDS; i++)
4262 		if (sc->bands[i].lo != 0 &&
4263 		    sc->bands[i].lo <= chan && chan <= sc->bands[i].hi)
4264 			break;
4265 	if (i == IWN_NBANDS)	/* Can't happen in real-life. */
4266 		return EINVAL;
4267 	chans = sc->bands[i].chans;
4268 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
4269 	    "%s: chan %d sub-band=%d\n", __func__, chan, i);
4270 
4271 	for (c = 0; c < 2; c++) {
4272 		uint8_t power, gain, temp;
4273 		int maxchpwr, pwr, ridx, idx;
4274 
4275 		power = interpolate(chan,
4276 		    chans[0].num, chans[0].samples[c][1].power,
4277 		    chans[1].num, chans[1].samples[c][1].power, 1);
4278 		gain  = interpolate(chan,
4279 		    chans[0].num, chans[0].samples[c][1].gain,
4280 		    chans[1].num, chans[1].samples[c][1].gain, 1);
4281 		temp  = interpolate(chan,
4282 		    chans[0].num, chans[0].samples[c][1].temp,
4283 		    chans[1].num, chans[1].samples[c][1].temp, 1);
4284 		DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
4285 		    "%s: Tx chain %d: power=%d gain=%d temp=%d\n",
4286 		    __func__, c, power, gain, temp);
4287 
4288 		/* Compute temperature compensation. */
4289 		tdiff = ((sc->temp - temp) * 2) / tdiv[grp];
4290 		DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
4291 		    "%s: temperature compensation=%d (current=%d, EEPROM=%d)\n",
4292 		    __func__, tdiff, sc->temp, temp);
4293 
4294 		for (ridx = 0; ridx <= IWN_RIDX_MAX; ridx++) {
4295 			/* Convert dBm to half-dBm. */
4296 			maxchpwr = sc->maxpwr[chan] * 2;
4297 			if ((ridx / 8) & 1)
4298 				maxchpwr -= 6;	/* MIMO 2T: -3dB */
4299 
4300 			pwr = maxpwr;
4301 
4302 			/* Adjust TX power based on rate. */
4303 			if ((ridx % 8) == 5)
4304 				pwr -= 15;	/* OFDM48: -7.5dB */
4305 			else if ((ridx % 8) == 6)
4306 				pwr -= 17;	/* OFDM54: -8.5dB */
4307 			else if ((ridx % 8) == 7)
4308 				pwr -= 20;	/* OFDM60: -10dB */
4309 			else
4310 				pwr -= 10;	/* Others: -5dB */
4311 
4312 			/* Do not exceed channel max TX power. */
4313 			if (pwr > maxchpwr)
4314 				pwr = maxchpwr;
4315 
4316 			idx = gain - (pwr - power) - tdiff - vdiff;
4317 			if ((ridx / 8) & 1)	/* MIMO */
4318 				idx += (int32_t)le32toh(uc->atten[grp][c]);
4319 
4320 			if (cmd.band == 0)
4321 				idx += 9;	/* 5GHz */
4322 			if (ridx == IWN_RIDX_MAX)
4323 				idx += 5;	/* CCK */
4324 
4325 			/* Make sure idx stays in a valid range. */
4326 			if (idx < 0)
4327 				idx = 0;
4328 			else if (idx > IWN4965_MAX_PWR_INDEX)
4329 				idx = IWN4965_MAX_PWR_INDEX;
4330 
4331 			DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
4332 			    "%s: Tx chain %d, rate idx %d: power=%d\n",
4333 			    __func__, c, ridx, idx);
4334 			cmd.power[ridx].rf_gain[c] = rf_gain[idx];
4335 			cmd.power[ridx].dsp_gain[c] = dsp_gain[idx];
4336 		}
4337 	}
4338 
4339 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
4340 	    "%s: set tx power for chan %d\n", __func__, chan);
4341 	return iwn_cmd(sc, IWN_CMD_TXPOWER, &cmd, sizeof cmd, async);
4342 
4343 #undef interpolate
4344 #undef fdivround
4345 }
4346 
4347 static int
4348 iwn5000_set_txpower(struct iwn_softc *sc, struct ieee80211_channel *ch,
4349     int async)
4350 {
4351 	struct iwn5000_cmd_txpower cmd;
4352 
4353 	/*
4354 	 * TX power calibration is handled automatically by the firmware
4355 	 * for 5000 Series.
4356 	 */
4357 	memset(&cmd, 0, sizeof cmd);
4358 	cmd.global_limit = 2 * IWN5000_TXPOWER_MAX_DBM;	/* 16 dBm */
4359 	cmd.flags = IWN5000_TXPOWER_NO_CLOSED;
4360 	cmd.srv_limit = IWN5000_TXPOWER_AUTO;
4361 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: setting TX power\n", __func__);
4362 	return iwn_cmd(sc, IWN_CMD_TXPOWER_DBM, &cmd, sizeof cmd, async);
4363 }
4364 
4365 /*
4366  * Retrieve the maximum RSSI (in dBm) among receivers.
4367  */
4368 static int
4369 iwn4965_get_rssi(struct iwn_softc *sc, struct iwn_rx_stat *stat)
4370 {
4371 	struct iwn4965_rx_phystat *phy = (void *)stat->phybuf;
4372 	uint8_t mask, agc;
4373 	int rssi;
4374 
4375 	mask = (le16toh(phy->antenna) >> 4) & IWN_ANT_ABC;
4376 	agc  = (le16toh(phy->agc) >> 7) & 0x7f;
4377 
4378 	rssi = 0;
4379 	if (mask & IWN_ANT_A)
4380 		rssi = MAX(rssi, phy->rssi[0]);
4381 	if (mask & IWN_ANT_B)
4382 		rssi = MAX(rssi, phy->rssi[2]);
4383 	if (mask & IWN_ANT_C)
4384 		rssi = MAX(rssi, phy->rssi[4]);
4385 
4386 	DPRINTF(sc, IWN_DEBUG_RECV,
4387 	    "%s: agc %d mask 0x%x rssi %d %d %d result %d\n", __func__, agc,
4388 	    mask, phy->rssi[0], phy->rssi[2], phy->rssi[4],
4389 	    rssi - agc - IWN_RSSI_TO_DBM);
4390 	return rssi - agc - IWN_RSSI_TO_DBM;
4391 }
4392 
4393 static int
4394 iwn5000_get_rssi(struct iwn_softc *sc, struct iwn_rx_stat *stat)
4395 {
4396 	struct iwn5000_rx_phystat *phy = (void *)stat->phybuf;
4397 	uint8_t agc;
4398 	int rssi;
4399 
4400 	agc = (le32toh(phy->agc) >> 9) & 0x7f;
4401 
4402 	rssi = MAX(le16toh(phy->rssi[0]) & 0xff,
4403 		   le16toh(phy->rssi[1]) & 0xff);
4404 	rssi = MAX(le16toh(phy->rssi[2]) & 0xff, rssi);
4405 
4406 	DPRINTF(sc, IWN_DEBUG_RECV,
4407 	    "%s: agc %d rssi %d %d %d result %d\n", __func__, agc,
4408 	    phy->rssi[0], phy->rssi[1], phy->rssi[2],
4409 	    rssi - agc - IWN_RSSI_TO_DBM);
4410 	return rssi - agc - IWN_RSSI_TO_DBM;
4411 }
4412 
4413 /*
4414  * Retrieve the average noise (in dBm) among receivers.
4415  */
4416 static int
4417 iwn_get_noise(const struct iwn_rx_general_stats *stats)
4418 {
4419 	int i, total, nbant, noise;
4420 
4421 	total = nbant = 0;
4422 	for (i = 0; i < 3; i++) {
4423 		if ((noise = le32toh(stats->noise[i]) & 0xff) == 0)
4424 			continue;
4425 		total += noise;
4426 		nbant++;
4427 	}
4428 	/* There should be at least one antenna but check anyway. */
4429 	return (nbant == 0) ? -127 : (total / nbant) - 107;
4430 }
4431 
4432 /*
4433  * Compute temperature (in degC) from last received statistics.
4434  */
4435 static int
4436 iwn4965_get_temperature(struct iwn_softc *sc)
4437 {
4438 	struct iwn_ucode_info *uc = &sc->ucode_info;
4439 	int32_t r1, r2, r3, r4, temp;
4440 
4441 	r1 = le32toh(uc->temp[0].chan20MHz);
4442 	r2 = le32toh(uc->temp[1].chan20MHz);
4443 	r3 = le32toh(uc->temp[2].chan20MHz);
4444 	r4 = le32toh(sc->rawtemp);
4445 
4446 	if (r1 == r3)	/* Prevents division by 0 (should not happen). */
4447 		return 0;
4448 
4449 	/* Sign-extend 23-bit R4 value to 32-bit. */
4450 	r4 = ((r4 & 0xffffff) ^ 0x800000) - 0x800000;
4451 	/* Compute temperature in Kelvin. */
4452 	temp = (259 * (r4 - r2)) / (r3 - r1);
4453 	temp = (temp * 97) / 100 + 8;
4454 
4455 	DPRINTF(sc, IWN_DEBUG_ANY, "temperature %dK/%dC\n", temp,
4456 	    IWN_KTOC(temp));
4457 	return IWN_KTOC(temp);
4458 }
4459 
4460 static int
4461 iwn5000_get_temperature(struct iwn_softc *sc)
4462 {
4463 	int32_t temp;
4464 
4465 	/*
4466 	 * Temperature is not used by the driver for 5000 Series because
4467 	 * TX power calibration is handled by firmware.
4468 	 */
4469 	temp = le32toh(sc->rawtemp);
4470 	if (sc->hw_type == IWN_HW_REV_TYPE_5150) {
4471 		temp = (temp / -5) + sc->temp_off;
4472 		temp = IWN_KTOC(temp);
4473 	}
4474 	return temp;
4475 }
4476 
4477 /*
4478  * Initialize sensitivity calibration state machine.
4479  */
4480 static int
4481 iwn_init_sensitivity(struct iwn_softc *sc)
4482 {
4483 	struct iwn_ops *ops = &sc->ops;
4484 	struct iwn_calib_state *calib = &sc->calib;
4485 	uint32_t flags;
4486 	int error;
4487 
4488 	/* Reset calibration state machine. */
4489 	memset(calib, 0, sizeof (*calib));
4490 	calib->state = IWN_CALIB_STATE_INIT;
4491 	calib->cck_state = IWN_CCK_STATE_HIFA;
4492 	/* Set initial correlation values. */
4493 	calib->ofdm_x1     = sc->limits->min_ofdm_x1;
4494 	calib->ofdm_mrc_x1 = sc->limits->min_ofdm_mrc_x1;
4495 	calib->ofdm_x4     = sc->limits->min_ofdm_x4;
4496 	calib->ofdm_mrc_x4 = sc->limits->min_ofdm_mrc_x4;
4497 	calib->cck_x4      = 125;
4498 	calib->cck_mrc_x4  = sc->limits->min_cck_mrc_x4;
4499 	calib->energy_cck  = sc->limits->energy_cck;
4500 
4501 	/* Write initial sensitivity. */
4502 	if ((error = iwn_send_sensitivity(sc)) != 0)
4503 		return error;
4504 
4505 	/* Write initial gains. */
4506 	if ((error = ops->init_gains(sc)) != 0)
4507 		return error;
4508 
4509 	/* Request statistics at each beacon interval. */
4510 	flags = 0;
4511 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: sending request for statistics\n",
4512 	    __func__);
4513 	return iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags, sizeof flags, 1);
4514 }
4515 
4516 /*
4517  * Collect noise and RSSI statistics for the first 20 beacons received
4518  * after association and use them to determine connected antennas and
4519  * to set differential gains.
4520  */
4521 static void
4522 iwn_collect_noise(struct iwn_softc *sc,
4523     const struct iwn_rx_general_stats *stats)
4524 {
4525 	struct iwn_ops *ops = &sc->ops;
4526 	struct iwn_calib_state *calib = &sc->calib;
4527 	uint32_t val;
4528 	int i;
4529 
4530 	/* Accumulate RSSI and noise for all 3 antennas. */
4531 	for (i = 0; i < 3; i++) {
4532 		calib->rssi[i] += le32toh(stats->rssi[i]) & 0xff;
4533 		calib->noise[i] += le32toh(stats->noise[i]) & 0xff;
4534 	}
4535 	/* NB: We update differential gains only once after 20 beacons. */
4536 	if (++calib->nbeacons < 20)
4537 		return;
4538 
4539 	/* Determine highest average RSSI. */
4540 	val = MAX(calib->rssi[0], calib->rssi[1]);
4541 	val = MAX(calib->rssi[2], val);
4542 
4543 	/* Determine which antennas are connected. */
4544 	sc->chainmask = sc->rxchainmask;
4545 	for (i = 0; i < 3; i++)
4546 		if (val - calib->rssi[i] > 15 * 20)
4547 			sc->chainmask &= ~(1 << i);
4548 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4549 	    "%s: RX chains mask: theoretical=0x%x, actual=0x%x\n",
4550 	    __func__, sc->rxchainmask, sc->chainmask);
4551 
4552 	/* If none of the TX antennas are connected, keep at least one. */
4553 	if ((sc->chainmask & sc->txchainmask) == 0)
4554 		sc->chainmask |= IWN_LSB(sc->txchainmask);
4555 
4556 	(void)ops->set_gains(sc);
4557 	calib->state = IWN_CALIB_STATE_RUN;
4558 
4559 #ifdef notyet
4560 	/* XXX Disable RX chains with no antennas connected. */
4561 	sc->rxon.rxchain = htole16(IWN_RXCHAIN_SEL(sc->chainmask));
4562 	(void)iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, sc->rxonsz, 1);
4563 #endif
4564 
4565 #if 0
4566 	/* XXX: not yet */
4567 	/* Enable power-saving mode if requested by user. */
4568 	if (sc->sc_ic.ic_flags & IEEE80211_F_PMGTON)
4569 		(void)iwn_set_pslevel(sc, 0, 3, 1);
4570 #endif
4571 }
4572 
4573 static int
4574 iwn4965_init_gains(struct iwn_softc *sc)
4575 {
4576 	struct iwn_phy_calib_gain cmd;
4577 
4578 	memset(&cmd, 0, sizeof cmd);
4579 	cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN;
4580 	/* Differential gains initially set to 0 for all 3 antennas. */
4581 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4582 	    "%s: setting initial differential gains\n", __func__);
4583 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
4584 }
4585 
4586 static int
4587 iwn5000_init_gains(struct iwn_softc *sc)
4588 {
4589 	struct iwn_phy_calib cmd;
4590 
4591 	memset(&cmd, 0, sizeof cmd);
4592 	cmd.code = sc->reset_noise_gain;
4593 	cmd.ngroups = 1;
4594 	cmd.isvalid = 1;
4595 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4596 	    "%s: setting initial differential gains\n", __func__);
4597 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
4598 }
4599 
4600 static int
4601 iwn4965_set_gains(struct iwn_softc *sc)
4602 {
4603 	struct iwn_calib_state *calib = &sc->calib;
4604 	struct iwn_phy_calib_gain cmd;
4605 	int i, delta, noise;
4606 
4607 	/* Get minimal noise among connected antennas. */
4608 	noise = INT_MAX;	/* NB: There's at least one antenna. */
4609 	for (i = 0; i < 3; i++)
4610 		if (sc->chainmask & (1 << i))
4611 			noise = MIN(calib->noise[i], noise);
4612 
4613 	memset(&cmd, 0, sizeof cmd);
4614 	cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN;
4615 	/* Set differential gains for connected antennas. */
4616 	for (i = 0; i < 3; i++) {
4617 		if (sc->chainmask & (1 << i)) {
4618 			/* Compute attenuation (in unit of 1.5dB). */
4619 			delta = (noise - (int32_t)calib->noise[i]) / 30;
4620 			/* NB: delta <= 0 */
4621 			/* Limit to [-4.5dB,0]. */
4622 			cmd.gain[i] = MIN(abs(delta), 3);
4623 			if (delta < 0)
4624 				cmd.gain[i] |= 1 << 2;	/* sign bit */
4625 		}
4626 	}
4627 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4628 	    "setting differential gains Ant A/B/C: %x/%x/%x (%x)\n",
4629 	    cmd.gain[0], cmd.gain[1], cmd.gain[2], sc->chainmask);
4630 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
4631 }
4632 
4633 static int
4634 iwn5000_set_gains(struct iwn_softc *sc)
4635 {
4636 	struct iwn_calib_state *calib = &sc->calib;
4637 	struct iwn_phy_calib_gain cmd;
4638 	int i, ant, div, delta;
4639 
4640 	/* We collected 20 beacons and !=6050 need a 1.5 factor. */
4641 	div = (sc->hw_type == IWN_HW_REV_TYPE_6050) ? 20 : 30;
4642 
4643 	memset(&cmd, 0, sizeof cmd);
4644 	cmd.code = sc->noise_gain;
4645 	cmd.ngroups = 1;
4646 	cmd.isvalid = 1;
4647 	/* Get first available RX antenna as referential. */
4648 	ant = IWN_LSB(sc->rxchainmask);
4649 	/* Set differential gains for other antennas. */
4650 	for (i = ant + 1; i < 3; i++) {
4651 		if (sc->chainmask & (1 << i)) {
4652 			/* The delta is relative to antenna "ant". */
4653 			delta = ((int32_t)calib->noise[ant] -
4654 			    (int32_t)calib->noise[i]) / div;
4655 			/* Limit to [-4.5dB,+4.5dB]. */
4656 			cmd.gain[i - 1] = MIN(abs(delta), 3);
4657 			if (delta < 0)
4658 				cmd.gain[i - 1] |= 1 << 2;	/* sign bit */
4659 		}
4660 	}
4661 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4662 	    "setting differential gains Ant B/C: %x/%x (%x)\n",
4663 	    cmd.gain[0], cmd.gain[1], sc->chainmask);
4664 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
4665 }
4666 
4667 /*
4668  * Tune RF RX sensitivity based on the number of false alarms detected
4669  * during the last beacon period.
4670  */
4671 static void
4672 iwn_tune_sensitivity(struct iwn_softc *sc, const struct iwn_rx_stats *stats)
4673 {
4674 #define inc(val, inc, max)			\
4675 	if ((val) < (max)) {			\
4676 		if ((val) < (max) - (inc))	\
4677 			(val) += (inc);		\
4678 		else				\
4679 			(val) = (max);		\
4680 		needs_update = 1;		\
4681 	}
4682 #define dec(val, dec, min)			\
4683 	if ((val) > (min)) {			\
4684 		if ((val) > (min) + (dec))	\
4685 			(val) -= (dec);		\
4686 		else				\
4687 			(val) = (min);		\
4688 		needs_update = 1;		\
4689 	}
4690 
4691 	const struct iwn_sensitivity_limits *limits = sc->limits;
4692 	struct iwn_calib_state *calib = &sc->calib;
4693 	uint32_t val, rxena, fa;
4694 	uint32_t energy[3], energy_min;
4695 	uint8_t noise[3], noise_ref;
4696 	int i, needs_update = 0;
4697 
4698 	/* Check that we've been enabled long enough. */
4699 	if ((rxena = le32toh(stats->general.load)) == 0)
4700 		return;
4701 
4702 	/* Compute number of false alarms since last call for OFDM. */
4703 	fa  = le32toh(stats->ofdm.bad_plcp) - calib->bad_plcp_ofdm;
4704 	fa += le32toh(stats->ofdm.fa) - calib->fa_ofdm;
4705 	fa *= 200 * IEEE80211_DUR_TU;	/* 200TU */
4706 
4707 	/* Save counters values for next call. */
4708 	calib->bad_plcp_ofdm = le32toh(stats->ofdm.bad_plcp);
4709 	calib->fa_ofdm = le32toh(stats->ofdm.fa);
4710 
4711 	if (fa > 50 * rxena) {
4712 		/* High false alarm count, decrease sensitivity. */
4713 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4714 		    "%s: OFDM high false alarm count: %u\n", __func__, fa);
4715 		inc(calib->ofdm_x1,     1, limits->max_ofdm_x1);
4716 		inc(calib->ofdm_mrc_x1, 1, limits->max_ofdm_mrc_x1);
4717 		inc(calib->ofdm_x4,     1, limits->max_ofdm_x4);
4718 		inc(calib->ofdm_mrc_x4, 1, limits->max_ofdm_mrc_x4);
4719 
4720 	} else if (fa < 5 * rxena) {
4721 		/* Low false alarm count, increase sensitivity. */
4722 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4723 		    "%s: OFDM low false alarm count: %u\n", __func__, fa);
4724 		dec(calib->ofdm_x1,     1, limits->min_ofdm_x1);
4725 		dec(calib->ofdm_mrc_x1, 1, limits->min_ofdm_mrc_x1);
4726 		dec(calib->ofdm_x4,     1, limits->min_ofdm_x4);
4727 		dec(calib->ofdm_mrc_x4, 1, limits->min_ofdm_mrc_x4);
4728 	}
4729 
4730 	/* Compute maximum noise among 3 receivers. */
4731 	for (i = 0; i < 3; i++)
4732 		noise[i] = (le32toh(stats->general.noise[i]) >> 8) & 0xff;
4733 	val = MAX(noise[0], noise[1]);
4734 	val = MAX(noise[2], val);
4735 	/* Insert it into our samples table. */
4736 	calib->noise_samples[calib->cur_noise_sample] = val;
4737 	calib->cur_noise_sample = (calib->cur_noise_sample + 1) % 20;
4738 
4739 	/* Compute maximum noise among last 20 samples. */
4740 	noise_ref = calib->noise_samples[0];
4741 	for (i = 1; i < 20; i++)
4742 		noise_ref = MAX(noise_ref, calib->noise_samples[i]);
4743 
4744 	/* Compute maximum energy among 3 receivers. */
4745 	for (i = 0; i < 3; i++)
4746 		energy[i] = le32toh(stats->general.energy[i]);
4747 	val = MIN(energy[0], energy[1]);
4748 	val = MIN(energy[2], val);
4749 	/* Insert it into our samples table. */
4750 	calib->energy_samples[calib->cur_energy_sample] = val;
4751 	calib->cur_energy_sample = (calib->cur_energy_sample + 1) % 10;
4752 
4753 	/* Compute minimum energy among last 10 samples. */
4754 	energy_min = calib->energy_samples[0];
4755 	for (i = 1; i < 10; i++)
4756 		energy_min = MAX(energy_min, calib->energy_samples[i]);
4757 	energy_min += 6;
4758 
4759 	/* Compute number of false alarms since last call for CCK. */
4760 	fa  = le32toh(stats->cck.bad_plcp) - calib->bad_plcp_cck;
4761 	fa += le32toh(stats->cck.fa) - calib->fa_cck;
4762 	fa *= 200 * IEEE80211_DUR_TU;	/* 200TU */
4763 
4764 	/* Save counters values for next call. */
4765 	calib->bad_plcp_cck = le32toh(stats->cck.bad_plcp);
4766 	calib->fa_cck = le32toh(stats->cck.fa);
4767 
4768 	if (fa > 50 * rxena) {
4769 		/* High false alarm count, decrease sensitivity. */
4770 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4771 		    "%s: CCK high false alarm count: %u\n", __func__, fa);
4772 		calib->cck_state = IWN_CCK_STATE_HIFA;
4773 		calib->low_fa = 0;
4774 
4775 		if (calib->cck_x4 > 160) {
4776 			calib->noise_ref = noise_ref;
4777 			if (calib->energy_cck > 2)
4778 				dec(calib->energy_cck, 2, energy_min);
4779 		}
4780 		if (calib->cck_x4 < 160) {
4781 			calib->cck_x4 = 161;
4782 			needs_update = 1;
4783 		} else
4784 			inc(calib->cck_x4, 3, limits->max_cck_x4);
4785 
4786 		inc(calib->cck_mrc_x4, 3, limits->max_cck_mrc_x4);
4787 
4788 	} else if (fa < 5 * rxena) {
4789 		/* Low false alarm count, increase sensitivity. */
4790 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4791 		    "%s: CCK low false alarm count: %u\n", __func__, fa);
4792 		calib->cck_state = IWN_CCK_STATE_LOFA;
4793 		calib->low_fa++;
4794 
4795 		if (calib->cck_state != IWN_CCK_STATE_INIT &&
4796 		    (((int32_t)calib->noise_ref - (int32_t)noise_ref) > 2 ||
4797 		     calib->low_fa > 100)) {
4798 			inc(calib->energy_cck, 2, limits->min_energy_cck);
4799 			dec(calib->cck_x4,     3, limits->min_cck_x4);
4800 			dec(calib->cck_mrc_x4, 3, limits->min_cck_mrc_x4);
4801 		}
4802 	} else {
4803 		/* Not worth to increase or decrease sensitivity. */
4804 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4805 		    "%s: CCK normal false alarm count: %u\n", __func__, fa);
4806 		calib->low_fa = 0;
4807 		calib->noise_ref = noise_ref;
4808 
4809 		if (calib->cck_state == IWN_CCK_STATE_HIFA) {
4810 			/* Previous interval had many false alarms. */
4811 			dec(calib->energy_cck, 8, energy_min);
4812 		}
4813 		calib->cck_state = IWN_CCK_STATE_INIT;
4814 	}
4815 
4816 	if (needs_update)
4817 		(void)iwn_send_sensitivity(sc);
4818 #undef dec
4819 #undef inc
4820 }
4821 
4822 static int
4823 iwn_send_sensitivity(struct iwn_softc *sc)
4824 {
4825 	struct iwn_calib_state *calib = &sc->calib;
4826 	struct iwn_enhanced_sensitivity_cmd cmd;
4827 	int len;
4828 
4829 	memset(&cmd, 0, sizeof cmd);
4830 	len = sizeof (struct iwn_sensitivity_cmd);
4831 	cmd.which = IWN_SENSITIVITY_WORKTBL;
4832 	/* OFDM modulation. */
4833 	cmd.corr_ofdm_x1       = htole16(calib->ofdm_x1);
4834 	cmd.corr_ofdm_mrc_x1   = htole16(calib->ofdm_mrc_x1);
4835 	cmd.corr_ofdm_x4       = htole16(calib->ofdm_x4);
4836 	cmd.corr_ofdm_mrc_x4   = htole16(calib->ofdm_mrc_x4);
4837 	cmd.energy_ofdm        = htole16(sc->limits->energy_ofdm);
4838 	cmd.energy_ofdm_th     = htole16(62);
4839 	/* CCK modulation. */
4840 	cmd.corr_cck_x4        = htole16(calib->cck_x4);
4841 	cmd.corr_cck_mrc_x4    = htole16(calib->cck_mrc_x4);
4842 	cmd.energy_cck         = htole16(calib->energy_cck);
4843 	/* Barker modulation: use default values. */
4844 	cmd.corr_barker        = htole16(190);
4845 	cmd.corr_barker_mrc    = htole16(390);
4846 
4847 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4848 	    "%s: set sensitivity %d/%d/%d/%d/%d/%d/%d\n", __func__,
4849 	    calib->ofdm_x1, calib->ofdm_mrc_x1, calib->ofdm_x4,
4850 	    calib->ofdm_mrc_x4, calib->cck_x4,
4851 	    calib->cck_mrc_x4, calib->energy_cck);
4852 
4853 	if (!(sc->sc_flags & IWN_FLAG_ENH_SENS))
4854 		goto send;
4855 	/* Enhanced sensitivity settings. */
4856 	len = sizeof (struct iwn_enhanced_sensitivity_cmd);
4857 	cmd.ofdm_det_slope_mrc = htole16(668);
4858 	cmd.ofdm_det_icept_mrc = htole16(4);
4859 	cmd.ofdm_det_slope     = htole16(486);
4860 	cmd.ofdm_det_icept     = htole16(37);
4861 	cmd.cck_det_slope_mrc  = htole16(853);
4862 	cmd.cck_det_icept_mrc  = htole16(4);
4863 	cmd.cck_det_slope      = htole16(476);
4864 	cmd.cck_det_icept      = htole16(99);
4865 send:
4866 	return iwn_cmd(sc, IWN_CMD_SET_SENSITIVITY, &cmd, len, 1);
4867 }
4868 
4869 /*
4870  * Set STA mode power saving level (between 0 and 5).
4871  * Level 0 is CAM (Continuously Aware Mode), 5 is for maximum power saving.
4872  */
4873 static int
4874 iwn_set_pslevel(struct iwn_softc *sc, int dtim, int level, int async)
4875 {
4876 	struct iwn_pmgt_cmd cmd;
4877 	const struct iwn_pmgt *pmgt;
4878 	uint32_t max, skip_dtim;
4879 	uint32_t reg;
4880 	int i;
4881 
4882 	/* Select which PS parameters to use. */
4883 	if (dtim <= 2)
4884 		pmgt = &iwn_pmgt[0][level];
4885 	else if (dtim <= 10)
4886 		pmgt = &iwn_pmgt[1][level];
4887 	else
4888 		pmgt = &iwn_pmgt[2][level];
4889 
4890 	memset(&cmd, 0, sizeof cmd);
4891 	if (level != 0)	/* not CAM */
4892 		cmd.flags |= htole16(IWN_PS_ALLOW_SLEEP);
4893 	if (level == 5)
4894 		cmd.flags |= htole16(IWN_PS_FAST_PD);
4895 	/* Retrieve PCIe Active State Power Management (ASPM). */
4896 	reg = pci_read_config(sc->sc_dev, sc->sc_cap_off + 0x10, 1);
4897 	if (!(reg & 0x1))	/* L0s Entry disabled. */
4898 		cmd.flags |= htole16(IWN_PS_PCI_PMGT);
4899 	cmd.rxtimeout = htole32(pmgt->rxtimeout * 1024);
4900 	cmd.txtimeout = htole32(pmgt->txtimeout * 1024);
4901 
4902 	if (dtim == 0) {
4903 		dtim = 1;
4904 		skip_dtim = 0;
4905 	} else
4906 		skip_dtim = pmgt->skip_dtim;
4907 	if (skip_dtim != 0) {
4908 		cmd.flags |= htole16(IWN_PS_SLEEP_OVER_DTIM);
4909 		max = pmgt->intval[4];
4910 		if (max == (uint32_t)-1)
4911 			max = dtim * (skip_dtim + 1);
4912 		else if (max > dtim)
4913 			max = (max / dtim) * dtim;
4914 	} else
4915 		max = dtim;
4916 	for (i = 0; i < 5; i++)
4917 		cmd.intval[i] = htole32(MIN(max, pmgt->intval[i]));
4918 
4919 	DPRINTF(sc, IWN_DEBUG_RESET, "setting power saving level to %d\n",
4920 	    level);
4921 	return iwn_cmd(sc, IWN_CMD_SET_POWER_MODE, &cmd, sizeof cmd, async);
4922 }
4923 
4924 static int
4925 iwn_send_btcoex(struct iwn_softc *sc)
4926 {
4927 	struct iwn_bluetooth cmd;
4928 
4929 	memset(&cmd, 0, sizeof cmd);
4930 	cmd.flags = IWN_BT_COEX_CHAN_ANN | IWN_BT_COEX_BT_PRIO;
4931 	cmd.lead_time = IWN_BT_LEAD_TIME_DEF;
4932 	cmd.max_kill = IWN_BT_MAX_KILL_DEF;
4933 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: configuring bluetooth coexistence\n",
4934 	    __func__);
4935 	return iwn_cmd(sc, IWN_CMD_BT_COEX, &cmd, sizeof(cmd), 0);
4936 }
4937 
4938 static int
4939 iwn_send_advanced_btcoex(struct iwn_softc *sc)
4940 {
4941 	static const uint32_t btcoex_3wire[12] = {
4942 		0xaaaaaaaa, 0xaaaaaaaa, 0xaeaaaaaa, 0xaaaaaaaa,
4943 		0xcc00ff28, 0x0000aaaa, 0xcc00aaaa, 0x0000aaaa,
4944 		0xc0004000, 0x00004000, 0xf0005000, 0xf0005000,
4945 	};
4946 	struct iwn6000_btcoex_config btconfig;
4947 	struct iwn_btcoex_priotable btprio;
4948 	struct iwn_btcoex_prot btprot;
4949 	int error, i;
4950 
4951 	memset(&btconfig, 0, sizeof btconfig);
4952 	btconfig.flags = 145;
4953 	btconfig.max_kill = 5;
4954 	btconfig.bt3_t7_timer = 1;
4955 	btconfig.kill_ack = htole32(0xffff0000);
4956 	btconfig.kill_cts = htole32(0xffff0000);
4957 	btconfig.sample_time = 2;
4958 	btconfig.bt3_t2_timer = 0xc;
4959 	for (i = 0; i < 12; i++)
4960 		btconfig.lookup_table[i] = htole32(btcoex_3wire[i]);
4961 	btconfig.valid = htole16(0xff);
4962 	btconfig.prio_boost = 0xf0;
4963 	DPRINTF(sc, IWN_DEBUG_RESET,
4964 	    "%s: configuring advanced bluetooth coexistence\n", __func__);
4965 	error = iwn_cmd(sc, IWN_CMD_BT_COEX, &btconfig, sizeof(btconfig), 1);
4966 	if (error != 0)
4967 		return error;
4968 
4969 	memset(&btprio, 0, sizeof btprio);
4970 	btprio.calib_init1 = 0x6;
4971 	btprio.calib_init2 = 0x7;
4972 	btprio.calib_periodic_low1 = 0x2;
4973 	btprio.calib_periodic_low2 = 0x3;
4974 	btprio.calib_periodic_high1 = 0x4;
4975 	btprio.calib_periodic_high2 = 0x5;
4976 	btprio.dtim = 0x6;
4977 	btprio.scan52 = 0x8;
4978 	btprio.scan24 = 0xa;
4979 	error = iwn_cmd(sc, IWN_CMD_BT_COEX_PRIOTABLE, &btprio, sizeof(btprio),
4980 	    1);
4981 	if (error != 0)
4982 		return error;
4983 
4984 	/* Force BT state machine change. */
4985 	memset(&btprot, 0, sizeof btprio);
4986 	btprot.open = 1;
4987 	btprot.type = 1;
4988 	error = iwn_cmd(sc, IWN_CMD_BT_COEX_PROT, &btprot, sizeof(btprot), 1);
4989 	if (error != 0)
4990 		return error;
4991 	btprot.open = 0;
4992 	return iwn_cmd(sc, IWN_CMD_BT_COEX_PROT, &btprot, sizeof(btprot), 1);
4993 }
4994 
4995 static int
4996 iwn_config(struct iwn_softc *sc)
4997 {
4998 	struct iwn_ops *ops = &sc->ops;
4999 	struct ifnet *ifp = sc->sc_ifp;
5000 	struct ieee80211com *ic = ifp->if_l2com;
5001 	uint32_t txmask;
5002 	uint16_t rxchain;
5003 	int error;
5004 
5005 	if (sc->hw_type == IWN_HW_REV_TYPE_6005) {
5006 		/* Set radio temperature sensor offset. */
5007 		error = iwn5000_temp_offset_calib(sc);
5008 		if (error != 0) {
5009 			device_printf(sc->sc_dev,
5010 			    "%s: could not set temperature offset\n", __func__);
5011 			return error;
5012 		}
5013 	}
5014 
5015 	/* Configure valid TX chains for >=5000 Series. */
5016 	if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
5017 		txmask = htole32(sc->txchainmask);
5018 		DPRINTF(sc, IWN_DEBUG_RESET,
5019 		    "%s: configuring valid TX chains 0x%x\n", __func__, txmask);
5020 		error = iwn_cmd(sc, IWN5000_CMD_TX_ANT_CONFIG, &txmask,
5021 		    sizeof txmask, 0);
5022 		if (error != 0) {
5023 			device_printf(sc->sc_dev,
5024 			    "%s: could not configure valid TX chains, "
5025 			    "error %d\n", __func__, error);
5026 			return error;
5027 		}
5028 	}
5029 
5030 	/* Configure bluetooth coexistence. */
5031 	if (sc->sc_flags & IWN_FLAG_ADV_BTCOEX)
5032 		error = iwn_send_advanced_btcoex(sc);
5033 	else
5034 		error = iwn_send_btcoex(sc);
5035 	if (error != 0) {
5036 		device_printf(sc->sc_dev,
5037 		    "%s: could not configure bluetooth coexistence, error %d\n",
5038 		    __func__, error);
5039 		return error;
5040 	}
5041 
5042 	/* Set mode, channel, RX filter and enable RX. */
5043 	memset(&sc->rxon, 0, sizeof (struct iwn_rxon));
5044 	IEEE80211_ADDR_COPY(sc->rxon.myaddr, IF_LLADDR(ifp));
5045 	IEEE80211_ADDR_COPY(sc->rxon.wlap, IF_LLADDR(ifp));
5046 	sc->rxon.chan = ieee80211_chan2ieee(ic, ic->ic_curchan);
5047 	sc->rxon.flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
5048 	if (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
5049 		sc->rxon.flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
5050 	switch (ic->ic_opmode) {
5051 	case IEEE80211_M_STA:
5052 		sc->rxon.mode = IWN_MODE_STA;
5053 		sc->rxon.filter = htole32(IWN_FILTER_MULTICAST);
5054 		break;
5055 	case IEEE80211_M_MONITOR:
5056 		sc->rxon.mode = IWN_MODE_MONITOR;
5057 		sc->rxon.filter = htole32(IWN_FILTER_MULTICAST |
5058 		    IWN_FILTER_CTL | IWN_FILTER_PROMISC);
5059 		break;
5060 	default:
5061 		/* Should not get there. */
5062 		break;
5063 	}
5064 	sc->rxon.cck_mask  = 0x0f;	/* not yet negotiated */
5065 	sc->rxon.ofdm_mask = 0xff;	/* not yet negotiated */
5066 	sc->rxon.ht_single_mask = 0xff;
5067 	sc->rxon.ht_dual_mask = 0xff;
5068 	sc->rxon.ht_triple_mask = 0xff;
5069 	rxchain =
5070 	    IWN_RXCHAIN_VALID(sc->rxchainmask) |
5071 	    IWN_RXCHAIN_MIMO_COUNT(2) |
5072 	    IWN_RXCHAIN_IDLE_COUNT(2);
5073 	sc->rxon.rxchain = htole16(rxchain);
5074 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: setting configuration\n", __func__);
5075 	error = iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, sc->rxonsz, 0);
5076 	if (error != 0) {
5077 		device_printf(sc->sc_dev, "%s: RXON command failed\n",
5078 		    __func__);
5079 		return error;
5080 	}
5081 
5082 	if ((error = iwn_add_broadcast_node(sc, 0)) != 0) {
5083 		device_printf(sc->sc_dev, "%s: could not add broadcast node\n",
5084 		    __func__);
5085 		return error;
5086 	}
5087 
5088 	/* Configuration has changed, set TX power accordingly. */
5089 	if ((error = ops->set_txpower(sc, ic->ic_curchan, 0)) != 0) {
5090 		device_printf(sc->sc_dev, "%s: could not set TX power\n",
5091 		    __func__);
5092 		return error;
5093 	}
5094 
5095 	if ((error = iwn_set_critical_temp(sc)) != 0) {
5096 		device_printf(sc->sc_dev,
5097 		    "%s: could not set critical temperature\n", __func__);
5098 		return error;
5099 	}
5100 
5101 	/* Set power saving level to CAM during initialization. */
5102 	if ((error = iwn_set_pslevel(sc, 0, 0, 0)) != 0) {
5103 		device_printf(sc->sc_dev,
5104 		    "%s: could not set power saving level\n", __func__);
5105 		return error;
5106 	}
5107 	return 0;
5108 }
5109 
5110 /*
5111  * Add an ssid element to a frame.
5112  */
5113 static uint8_t *
5114 ieee80211_add_ssid(uint8_t *frm, const uint8_t *ssid, u_int len)
5115 {
5116 	*frm++ = IEEE80211_ELEMID_SSID;
5117 	*frm++ = len;
5118 	memcpy(frm, ssid, len);
5119 	return frm + len;
5120 }
5121 
5122 static int
5123 iwn_scan(struct iwn_softc *sc)
5124 {
5125 	struct ifnet *ifp = sc->sc_ifp;
5126 	struct ieee80211com *ic = ifp->if_l2com;
5127 	struct ieee80211_scan_state *ss = ic->ic_scan;	/*XXX*/
5128 	struct ieee80211_node *ni = ss->ss_vap->iv_bss;
5129 	struct iwn_scan_hdr *hdr;
5130 	struct iwn_cmd_data *tx;
5131 	struct iwn_scan_essid *essid;
5132 	struct iwn_scan_chan *chan;
5133 	struct ieee80211_frame *wh;
5134 	struct ieee80211_rateset *rs;
5135 	struct ieee80211_channel *c;
5136 	uint8_t *buf, *frm;
5137 	uint16_t rxchain;
5138 	uint8_t txant;
5139 	int buflen, error;
5140 
5141 	buf = malloc(IWN_SCAN_MAXSZ, M_DEVBUF, M_NOWAIT | M_ZERO);
5142 	if (buf == NULL) {
5143 		device_printf(sc->sc_dev,
5144 		    "%s: could not allocate buffer for scan command\n",
5145 		    __func__);
5146 		return ENOMEM;
5147 	}
5148 	hdr = (struct iwn_scan_hdr *)buf;
5149 	/*
5150 	 * Move to the next channel if no frames are received within 10ms
5151 	 * after sending the probe request.
5152 	 */
5153 	hdr->quiet_time = htole16(10);		/* timeout in milliseconds */
5154 	hdr->quiet_threshold = htole16(1);	/* min # of packets */
5155 
5156 	/* Select antennas for scanning. */
5157 	rxchain =
5158 	    IWN_RXCHAIN_VALID(sc->rxchainmask) |
5159 	    IWN_RXCHAIN_FORCE_MIMO_SEL(sc->rxchainmask) |
5160 	    IWN_RXCHAIN_DRIVER_FORCE;
5161 	if (IEEE80211_IS_CHAN_A(ic->ic_curchan) &&
5162 	    sc->hw_type == IWN_HW_REV_TYPE_4965) {
5163 		/* Ant A must be avoided in 5GHz because of an HW bug. */
5164 		rxchain |= IWN_RXCHAIN_FORCE_SEL(IWN_ANT_BC);
5165 	} else	/* Use all available RX antennas. */
5166 		rxchain |= IWN_RXCHAIN_FORCE_SEL(sc->rxchainmask);
5167 	hdr->rxchain = htole16(rxchain);
5168 	hdr->filter = htole32(IWN_FILTER_MULTICAST | IWN_FILTER_BEACON);
5169 
5170 	tx = (struct iwn_cmd_data *)(hdr + 1);
5171 	tx->flags = htole32(IWN_TX_AUTO_SEQ);
5172 	tx->id = sc->broadcast_id;
5173 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
5174 
5175 	if (IEEE80211_IS_CHAN_A(ic->ic_curchan)) {
5176 		/* Send probe requests at 6Mbps. */
5177 		tx->rate = htole32(0xd);
5178 		rs = &ic->ic_sup_rates[IEEE80211_MODE_11A];
5179 	} else {
5180 		hdr->flags = htole32(IWN_RXON_24GHZ | IWN_RXON_AUTO);
5181 		/* Send probe requests at 1Mbps. */
5182 		tx->rate = htole32(10 | IWN_RFLAG_CCK);
5183 		rs = &ic->ic_sup_rates[IEEE80211_MODE_11G];
5184 	}
5185 	/* Use the first valid TX antenna. */
5186 	txant = IWN_LSB(sc->txchainmask);
5187 	tx->rate |= htole32(IWN_RFLAG_ANT(txant));
5188 
5189 	essid = (struct iwn_scan_essid *)(tx + 1);
5190 	if (ss->ss_ssid[0].len != 0) {
5191 		essid[0].id = IEEE80211_ELEMID_SSID;
5192 		essid[0].len = ss->ss_ssid[0].len;
5193 		memcpy(essid[0].data, ss->ss_ssid[0].ssid, ss->ss_ssid[0].len);
5194 	}
5195 	/*
5196 	 * Build a probe request frame.  Most of the following code is a
5197 	 * copy & paste of what is done in net80211.
5198 	 */
5199 	wh = (struct ieee80211_frame *)(essid + 20);
5200 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
5201 	    IEEE80211_FC0_SUBTYPE_PROBE_REQ;
5202 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
5203 	IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
5204 	IEEE80211_ADDR_COPY(wh->i_addr2, IF_LLADDR(ifp));
5205 	IEEE80211_ADDR_COPY(wh->i_addr3, ifp->if_broadcastaddr);
5206 	*(uint16_t *)&wh->i_dur[0] = 0;	/* filled by HW */
5207 	*(uint16_t *)&wh->i_seq[0] = 0;	/* filled by HW */
5208 
5209 	frm = (uint8_t *)(wh + 1);
5210 	frm = ieee80211_add_ssid(frm, NULL, 0);
5211 	frm = ieee80211_add_rates(frm, rs);
5212 	if (rs->rs_nrates > IEEE80211_RATE_SIZE)
5213 		frm = ieee80211_add_xrates(frm, rs);
5214 	if (ic->ic_htcaps & IEEE80211_HTC_HT)
5215 		frm = ieee80211_add_htcap(frm, ni);
5216 
5217 	/* Set length of probe request. */
5218 	tx->len = htole16(frm - (uint8_t *)wh);
5219 
5220 	c = ic->ic_curchan;
5221 	chan = (struct iwn_scan_chan *)frm;
5222 	chan->chan = htole16(ieee80211_chan2ieee(ic, c));
5223 	chan->flags = 0;
5224 	if (ss->ss_nssid > 0)
5225 		chan->flags |= htole32(IWN_CHAN_NPBREQS(1));
5226 	chan->dsp_gain = 0x6e;
5227 	if (IEEE80211_IS_CHAN_5GHZ(c) &&
5228 	    !(c->ic_flags & IEEE80211_CHAN_PASSIVE)) {
5229 		chan->rf_gain = 0x3b;
5230 		chan->active  = htole16(24);
5231 		chan->passive = htole16(110);
5232 		chan->flags |= htole32(IWN_CHAN_ACTIVE);
5233 	} else if (IEEE80211_IS_CHAN_5GHZ(c)) {
5234 		chan->rf_gain = 0x3b;
5235 		chan->active  = htole16(24);
5236 		if (sc->rxon.associd)
5237 			chan->passive = htole16(78);
5238 		else
5239 			chan->passive = htole16(110);
5240 		hdr->crc_threshold = 0xffff;
5241 	} else if (!(c->ic_flags & IEEE80211_CHAN_PASSIVE)) {
5242 		chan->rf_gain = 0x28;
5243 		chan->active  = htole16(36);
5244 		chan->passive = htole16(120);
5245 		chan->flags |= htole32(IWN_CHAN_ACTIVE);
5246 	} else {
5247 		chan->rf_gain = 0x28;
5248 		chan->active  = htole16(36);
5249 		if (sc->rxon.associd)
5250 			chan->passive = htole16(88);
5251 		else
5252 			chan->passive = htole16(120);
5253 		hdr->crc_threshold = 0xffff;
5254 	}
5255 
5256 	DPRINTF(sc, IWN_DEBUG_STATE,
5257 	    "%s: chan %u flags 0x%x rf_gain 0x%x "
5258 	    "dsp_gain 0x%x active 0x%x passive 0x%x\n", __func__,
5259 	    chan->chan, chan->flags, chan->rf_gain, chan->dsp_gain,
5260 	    chan->active, chan->passive);
5261 
5262 	hdr->nchan++;
5263 	chan++;
5264 	buflen = (uint8_t *)chan - buf;
5265 	hdr->len = htole16(buflen);
5266 
5267 	DPRINTF(sc, IWN_DEBUG_STATE, "sending scan command nchan=%d\n",
5268 	    hdr->nchan);
5269 	error = iwn_cmd(sc, IWN_CMD_SCAN, buf, buflen, 1);
5270 	free(buf, M_DEVBUF);
5271 	return error;
5272 }
5273 
5274 static int
5275 iwn_auth(struct iwn_softc *sc, struct ieee80211vap *vap)
5276 {
5277 	struct iwn_ops *ops = &sc->ops;
5278 	struct ifnet *ifp = sc->sc_ifp;
5279 	struct ieee80211com *ic = ifp->if_l2com;
5280 	struct ieee80211_node *ni = vap->iv_bss;
5281 	int error;
5282 
5283 	/* Update adapter configuration. */
5284 	IEEE80211_ADDR_COPY(sc->rxon.bssid, ni->ni_bssid);
5285 	sc->rxon.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
5286 	sc->rxon.flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
5287 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
5288 		sc->rxon.flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
5289 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
5290 		sc->rxon.flags |= htole32(IWN_RXON_SHSLOT);
5291 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
5292 		sc->rxon.flags |= htole32(IWN_RXON_SHPREAMBLE);
5293 	if (IEEE80211_IS_CHAN_A(ni->ni_chan)) {
5294 		sc->rxon.cck_mask  = 0;
5295 		sc->rxon.ofdm_mask = 0x15;
5296 	} else if (IEEE80211_IS_CHAN_B(ni->ni_chan)) {
5297 		sc->rxon.cck_mask  = 0x03;
5298 		sc->rxon.ofdm_mask = 0;
5299 	} else {
5300 		/* Assume 802.11b/g. */
5301 		sc->rxon.cck_mask  = 0x0f;
5302 		sc->rxon.ofdm_mask = 0x15;
5303 	}
5304 	DPRINTF(sc, IWN_DEBUG_STATE, "rxon chan %d flags %x cck %x ofdm %x\n",
5305 	    sc->rxon.chan, sc->rxon.flags, sc->rxon.cck_mask,
5306 	    sc->rxon.ofdm_mask);
5307 	error = iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, sc->rxonsz, 1);
5308 	if (error != 0) {
5309 		device_printf(sc->sc_dev, "%s: RXON command failed, error %d\n",
5310 		    __func__, error);
5311 		return error;
5312 	}
5313 
5314 	/* Configuration has changed, set TX power accordingly. */
5315 	if ((error = ops->set_txpower(sc, ni->ni_chan, 1)) != 0) {
5316 		device_printf(sc->sc_dev,
5317 		    "%s: could not set TX power, error %d\n", __func__, error);
5318 		return error;
5319 	}
5320 	/*
5321 	 * Reconfiguring RXON clears the firmware nodes table so we must
5322 	 * add the broadcast node again.
5323 	 */
5324 	if ((error = iwn_add_broadcast_node(sc, 1)) != 0) {
5325 		device_printf(sc->sc_dev,
5326 		    "%s: could not add broadcast node, error %d\n", __func__,
5327 		    error);
5328 		return error;
5329 	}
5330 	return 0;
5331 }
5332 
5333 static int
5334 iwn_run(struct iwn_softc *sc, struct ieee80211vap *vap)
5335 {
5336 	struct iwn_ops *ops = &sc->ops;
5337 	struct ifnet *ifp = sc->sc_ifp;
5338 	struct ieee80211com *ic = ifp->if_l2com;
5339 	struct ieee80211_node *ni = vap->iv_bss;
5340 	struct iwn_node_info node;
5341 	uint32_t htflags = 0;
5342 	int error;
5343 
5344 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
5345 		/* Link LED blinks while monitoring. */
5346 		iwn_set_led(sc, IWN_LED_LINK, 5, 5);
5347 		return 0;
5348 	}
5349 	if ((error = iwn_set_timing(sc, ni)) != 0) {
5350 		device_printf(sc->sc_dev,
5351 		    "%s: could not set timing, error %d\n", __func__, error);
5352 		return error;
5353 	}
5354 
5355 	/* Update adapter configuration. */
5356 	IEEE80211_ADDR_COPY(sc->rxon.bssid, ni->ni_bssid);
5357 	sc->rxon.associd = htole16(IEEE80211_AID(ni->ni_associd));
5358 	sc->rxon.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
5359 	sc->rxon.flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
5360 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
5361 		sc->rxon.flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
5362 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
5363 		sc->rxon.flags |= htole32(IWN_RXON_SHSLOT);
5364 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
5365 		sc->rxon.flags |= htole32(IWN_RXON_SHPREAMBLE);
5366 	if (IEEE80211_IS_CHAN_A(ni->ni_chan)) {
5367 		sc->rxon.cck_mask  = 0;
5368 		sc->rxon.ofdm_mask = 0x15;
5369 	} else if (IEEE80211_IS_CHAN_B(ni->ni_chan)) {
5370 		sc->rxon.cck_mask  = 0x03;
5371 		sc->rxon.ofdm_mask = 0;
5372 	} else {
5373 		/* Assume 802.11b/g. */
5374 		sc->rxon.cck_mask  = 0x0f;
5375 		sc->rxon.ofdm_mask = 0x15;
5376 	}
5377 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan)) {
5378 		htflags |= IWN_RXON_HT_PROTMODE(ic->ic_curhtprotmode);
5379 		if (IEEE80211_IS_CHAN_HT40(ni->ni_chan)) {
5380 			switch (ic->ic_curhtprotmode) {
5381 			case IEEE80211_HTINFO_OPMODE_HT20PR:
5382 				htflags |= IWN_RXON_HT_MODEPURE40;
5383 				break;
5384 			default:
5385 				htflags |= IWN_RXON_HT_MODEMIXED;
5386 				break;
5387 			}
5388 		}
5389 		if (IEEE80211_IS_CHAN_HT40D(ni->ni_chan))
5390 			htflags |= IWN_RXON_HT_HT40MINUS;
5391 	}
5392 	sc->rxon.flags |= htole32(htflags);
5393 	sc->rxon.filter |= htole32(IWN_FILTER_BSS);
5394 	DPRINTF(sc, IWN_DEBUG_STATE, "rxon chan %d flags %x\n",
5395 	    sc->rxon.chan, sc->rxon.flags);
5396 	error = iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, sc->rxonsz, 1);
5397 	if (error != 0) {
5398 		device_printf(sc->sc_dev,
5399 		    "%s: could not update configuration, error %d\n", __func__,
5400 		    error);
5401 		return error;
5402 	}
5403 
5404 	/* Configuration has changed, set TX power accordingly. */
5405 	if ((error = ops->set_txpower(sc, ni->ni_chan, 1)) != 0) {
5406 		device_printf(sc->sc_dev,
5407 		    "%s: could not set TX power, error %d\n", __func__, error);
5408 		return error;
5409 	}
5410 
5411 	/* Fake a join to initialize the TX rate. */
5412 	((struct iwn_node *)ni)->id = IWN_ID_BSS;
5413 	iwn_newassoc(ni, 1);
5414 
5415 	/* Add BSS node. */
5416 	memset(&node, 0, sizeof node);
5417 	IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr);
5418 	node.id = IWN_ID_BSS;
5419 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan)) {
5420 		switch (ni->ni_htcap & IEEE80211_HTCAP_SMPS) {
5421 		case IEEE80211_HTCAP_SMPS_ENA:
5422 			node.htflags |= htole32(IWN_SMPS_MIMO_DIS);
5423 			break;
5424 		case IEEE80211_HTCAP_SMPS_DYNAMIC:
5425 			node.htflags |= htole32(IWN_SMPS_MIMO_PROT);
5426 			break;
5427 		}
5428 		node.htflags |= htole32(IWN_AMDPU_SIZE_FACTOR(3) |
5429 		    IWN_AMDPU_DENSITY(5));	/* 4us */
5430 		if (IEEE80211_IS_CHAN_HT40(ni->ni_chan))
5431 			node.htflags |= htole32(IWN_NODE_HT40);
5432 	}
5433 	DPRINTF(sc, IWN_DEBUG_STATE, "%s: adding BSS node\n", __func__);
5434 	error = ops->add_node(sc, &node, 1);
5435 	if (error != 0) {
5436 		device_printf(sc->sc_dev,
5437 		    "%s: could not add BSS node, error %d\n", __func__, error);
5438 		return error;
5439 	}
5440 	DPRINTF(sc, IWN_DEBUG_STATE, "%s: setting link quality for node %d\n",
5441 	    __func__, node.id);
5442 	if ((error = iwn_set_link_quality(sc, ni)) != 0) {
5443 		device_printf(sc->sc_dev,
5444 		    "%s: could not setup link quality for node %d, error %d\n",
5445 		    __func__, node.id, error);
5446 		return error;
5447 	}
5448 
5449 	if ((error = iwn_init_sensitivity(sc)) != 0) {
5450 		device_printf(sc->sc_dev,
5451 		    "%s: could not set sensitivity, error %d\n", __func__,
5452 		    error);
5453 		return error;
5454 	}
5455 	/* Start periodic calibration timer. */
5456 	sc->calib.state = IWN_CALIB_STATE_ASSOC;
5457 	sc->calib_cnt = 0;
5458 	callout_reset(&sc->calib_to, msecs_to_ticks(500), iwn_calib_timeout,
5459 	    sc);
5460 
5461 	/* Link LED always on while associated. */
5462 	iwn_set_led(sc, IWN_LED_LINK, 0, 1);
5463 	return 0;
5464 }
5465 
5466 /*
5467  * This function is called by upper layer when an ADDBA request is received
5468  * from another STA and before the ADDBA response is sent.
5469  */
5470 static int
5471 iwn_ampdu_rx_start(struct ieee80211_node *ni, struct ieee80211_rx_ampdu *rap,
5472     int baparamset, int batimeout, int baseqctl)
5473 {
5474 #define MS(_v, _f)	(((_v) & _f) >> _f##_S)
5475 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
5476 	struct iwn_ops *ops = &sc->ops;
5477 	struct iwn_node *wn = (void *)ni;
5478 	struct iwn_node_info node;
5479 	uint16_t ssn;
5480 	uint8_t tid;
5481 	int error;
5482 
5483 	tid = MS(le16toh(baparamset), IEEE80211_BAPS_TID);
5484 	ssn = MS(le16toh(baseqctl), IEEE80211_BASEQ_START);
5485 
5486 	memset(&node, 0, sizeof node);
5487 	node.id = wn->id;
5488 	node.control = IWN_NODE_UPDATE;
5489 	node.flags = IWN_FLAG_SET_ADDBA;
5490 	node.addba_tid = tid;
5491 	node.addba_ssn = htole16(ssn);
5492 	DPRINTF(sc, IWN_DEBUG_RECV, "ADDBA RA=%d TID=%d SSN=%d\n",
5493 	    wn->id, tid, ssn);
5494 	error = ops->add_node(sc, &node, 1);
5495 	if (error != 0)
5496 		return error;
5497 	return sc->sc_ampdu_rx_start(ni, rap, baparamset, batimeout, baseqctl);
5498 #undef MS
5499 }
5500 
5501 /*
5502  * This function is called by upper layer on teardown of an HT-immediate
5503  * Block Ack agreement (eg. uppon receipt of a DELBA frame).
5504  */
5505 static void
5506 iwn_ampdu_rx_stop(struct ieee80211_node *ni, struct ieee80211_rx_ampdu *rap)
5507 {
5508 	struct ieee80211com *ic = ni->ni_ic;
5509 	struct iwn_softc *sc = ic->ic_ifp->if_softc;
5510 	struct iwn_ops *ops = &sc->ops;
5511 	struct iwn_node *wn = (void *)ni;
5512 	struct iwn_node_info node;
5513 	uint8_t tid;
5514 
5515 	/* XXX: tid as an argument */
5516 	for (tid = 0; tid < WME_NUM_TID; tid++) {
5517 		if (&ni->ni_rx_ampdu[tid] == rap)
5518 			break;
5519 	}
5520 
5521 	memset(&node, 0, sizeof node);
5522 	node.id = wn->id;
5523 	node.control = IWN_NODE_UPDATE;
5524 	node.flags = IWN_FLAG_SET_DELBA;
5525 	node.delba_tid = tid;
5526 	DPRINTF(sc, IWN_DEBUG_RECV, "DELBA RA=%d TID=%d\n", wn->id, tid);
5527 	(void)ops->add_node(sc, &node, 1);
5528 	sc->sc_ampdu_rx_stop(ni, rap);
5529 }
5530 
5531 static int
5532 iwn_addba_request(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
5533     int dialogtoken, int baparamset, int batimeout)
5534 {
5535 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
5536 	int qid;
5537 
5538 	for (qid = sc->firstaggqueue; qid < sc->ntxqs; qid++) {
5539 		if (sc->qid2tap[qid] == NULL)
5540 			break;
5541 	}
5542 	if (qid == sc->ntxqs) {
5543 		DPRINTF(sc, IWN_DEBUG_XMIT, "%s: not free aggregation queue\n",
5544 		    __func__);
5545 		return 0;
5546 	}
5547 	tap->txa_private = malloc(sizeof(int), M_DEVBUF, M_NOWAIT);
5548 	if (tap->txa_private == NULL) {
5549 		device_printf(sc->sc_dev,
5550 		    "%s: failed to alloc TX aggregation structure\n", __func__);
5551 		return 0;
5552 	}
5553 	sc->qid2tap[qid] = tap;
5554 	*(int *)tap->txa_private = qid;
5555 	return sc->sc_addba_request(ni, tap, dialogtoken, baparamset,
5556 	    batimeout);
5557 }
5558 
5559 static int
5560 iwn_addba_response(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
5561     int code, int baparamset, int batimeout)
5562 {
5563 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
5564 	int qid = *(int *)tap->txa_private;
5565 	uint8_t tid = WME_AC_TO_TID(tap->txa_ac);
5566 	int ret;
5567 
5568 	if (code == IEEE80211_STATUS_SUCCESS) {
5569 		ni->ni_txseqs[tid] = tap->txa_start & 0xfff;
5570 		ret = iwn_ampdu_tx_start(ni->ni_ic, ni, tid);
5571 		if (ret != 1)
5572 			return ret;
5573 	} else {
5574 		sc->qid2tap[qid] = NULL;
5575 		free(tap->txa_private, M_DEVBUF);
5576 		tap->txa_private = NULL;
5577 	}
5578 	return sc->sc_addba_response(ni, tap, code, baparamset, batimeout);
5579 }
5580 
5581 /*
5582  * This function is called by upper layer when an ADDBA response is received
5583  * from another STA.
5584  */
5585 static int
5586 iwn_ampdu_tx_start(struct ieee80211com *ic, struct ieee80211_node *ni,
5587     uint8_t tid)
5588 {
5589 	struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[TID_TO_WME_AC(tid)];
5590 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
5591 	struct iwn_ops *ops = &sc->ops;
5592 	struct iwn_node *wn = (void *)ni;
5593 	struct iwn_node_info node;
5594 	int error, qid;
5595 
5596 	/* Enable TX for the specified RA/TID. */
5597 	wn->disable_tid &= ~(1 << tid);
5598 	memset(&node, 0, sizeof node);
5599 	node.id = wn->id;
5600 	node.control = IWN_NODE_UPDATE;
5601 	node.flags = IWN_FLAG_SET_DISABLE_TID;
5602 	node.disable_tid = htole16(wn->disable_tid);
5603 	error = ops->add_node(sc, &node, 1);
5604 	if (error != 0)
5605 		return 0;
5606 
5607 	if ((error = iwn_nic_lock(sc)) != 0)
5608 		return 0;
5609 	qid = *(int *)tap->txa_private;
5610 	ops->ampdu_tx_start(sc, ni, qid, tid, tap->txa_start & 0xfff);
5611 	iwn_nic_unlock(sc);
5612 
5613 	iwn_set_link_quality(sc, ni);
5614 	return 1;
5615 }
5616 
5617 static void
5618 iwn_ampdu_tx_stop(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap)
5619 {
5620 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
5621 	struct iwn_ops *ops = &sc->ops;
5622 	uint8_t tid = WME_AC_TO_TID(tap->txa_ac);
5623 	int qid;
5624 
5625 	if (tap->txa_private == NULL)
5626 		return;
5627 
5628 	qid = *(int *)tap->txa_private;
5629 	if (iwn_nic_lock(sc) != 0)
5630 		return;
5631 	ops->ampdu_tx_stop(sc, qid, tid, tap->txa_start & 0xfff);
5632 	iwn_nic_unlock(sc);
5633 	sc->qid2tap[qid] = NULL;
5634 	free(tap->txa_private, M_DEVBUF);
5635 	tap->txa_private = NULL;
5636 }
5637 
5638 static void
5639 iwn4965_ampdu_tx_start(struct iwn_softc *sc, struct ieee80211_node *ni,
5640     int qid, uint8_t tid, uint16_t ssn)
5641 {
5642 	struct iwn_node *wn = (void *)ni;
5643 
5644 	/* Stop TX scheduler while we're changing its configuration. */
5645 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
5646 	    IWN4965_TXQ_STATUS_CHGACT);
5647 
5648 	/* Assign RA/TID translation to the queue. */
5649 	iwn_mem_write_2(sc, sc->sched_base + IWN4965_SCHED_TRANS_TBL(qid),
5650 	    wn->id << 4 | tid);
5651 
5652 	/* Enable chain-building mode for the queue. */
5653 	iwn_prph_setbits(sc, IWN4965_SCHED_QCHAIN_SEL, 1 << qid);
5654 
5655 	/* Set starting sequence number from the ADDBA request. */
5656 	sc->txq[qid].cur = sc->txq[qid].read = (ssn & 0xff);
5657 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
5658 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), ssn);
5659 
5660 	/* Set scheduler window size. */
5661 	iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid),
5662 	    IWN_SCHED_WINSZ);
5663 	/* Set scheduler frame limit. */
5664 	iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid) + 4,
5665 	    IWN_SCHED_LIMIT << 16);
5666 
5667 	/* Enable interrupts for the queue. */
5668 	iwn_prph_setbits(sc, IWN4965_SCHED_INTR_MASK, 1 << qid);
5669 
5670 	/* Mark the queue as active. */
5671 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
5672 	    IWN4965_TXQ_STATUS_ACTIVE | IWN4965_TXQ_STATUS_AGGR_ENA |
5673 	    iwn_tid2fifo[tid] << 1);
5674 }
5675 
5676 static void
5677 iwn4965_ampdu_tx_stop(struct iwn_softc *sc, int qid, uint8_t tid, uint16_t ssn)
5678 {
5679 	/* Stop TX scheduler while we're changing its configuration. */
5680 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
5681 	    IWN4965_TXQ_STATUS_CHGACT);
5682 
5683 	/* Set starting sequence number from the ADDBA request. */
5684 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
5685 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), ssn);
5686 
5687 	/* Disable interrupts for the queue. */
5688 	iwn_prph_clrbits(sc, IWN4965_SCHED_INTR_MASK, 1 << qid);
5689 
5690 	/* Mark the queue as inactive. */
5691 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
5692 	    IWN4965_TXQ_STATUS_INACTIVE | iwn_tid2fifo[tid] << 1);
5693 }
5694 
5695 static void
5696 iwn5000_ampdu_tx_start(struct iwn_softc *sc, struct ieee80211_node *ni,
5697     int qid, uint8_t tid, uint16_t ssn)
5698 {
5699 	struct iwn_node *wn = (void *)ni;
5700 
5701 	/* Stop TX scheduler while we're changing its configuration. */
5702 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
5703 	    IWN5000_TXQ_STATUS_CHGACT);
5704 
5705 	/* Assign RA/TID translation to the queue. */
5706 	iwn_mem_write_2(sc, sc->sched_base + IWN5000_SCHED_TRANS_TBL(qid),
5707 	    wn->id << 4 | tid);
5708 
5709 	/* Enable chain-building mode for the queue. */
5710 	iwn_prph_setbits(sc, IWN5000_SCHED_QCHAIN_SEL, 1 << qid);
5711 
5712 	/* Enable aggregation for the queue. */
5713 	iwn_prph_setbits(sc, IWN5000_SCHED_AGGR_SEL, 1 << qid);
5714 
5715 	/* Set starting sequence number from the ADDBA request. */
5716 	sc->txq[qid].cur = sc->txq[qid].read = (ssn & 0xff);
5717 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
5718 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), ssn);
5719 
5720 	/* Set scheduler window size and frame limit. */
5721 	iwn_mem_write(sc, sc->sched_base + IWN5000_SCHED_QUEUE_OFFSET(qid) + 4,
5722 	    IWN_SCHED_LIMIT << 16 | IWN_SCHED_WINSZ);
5723 
5724 	/* Enable interrupts for the queue. */
5725 	iwn_prph_setbits(sc, IWN5000_SCHED_INTR_MASK, 1 << qid);
5726 
5727 	/* Mark the queue as active. */
5728 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
5729 	    IWN5000_TXQ_STATUS_ACTIVE | iwn_tid2fifo[tid]);
5730 }
5731 
5732 static void
5733 iwn5000_ampdu_tx_stop(struct iwn_softc *sc, int qid, uint8_t tid, uint16_t ssn)
5734 {
5735 	/* Stop TX scheduler while we're changing its configuration. */
5736 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
5737 	    IWN5000_TXQ_STATUS_CHGACT);
5738 
5739 	/* Disable aggregation for the queue. */
5740 	iwn_prph_clrbits(sc, IWN5000_SCHED_AGGR_SEL, 1 << qid);
5741 
5742 	/* Set starting sequence number from the ADDBA request. */
5743 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
5744 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), ssn);
5745 
5746 	/* Disable interrupts for the queue. */
5747 	iwn_prph_clrbits(sc, IWN5000_SCHED_INTR_MASK, 1 << qid);
5748 
5749 	/* Mark the queue as inactive. */
5750 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
5751 	    IWN5000_TXQ_STATUS_INACTIVE | iwn_tid2fifo[tid]);
5752 }
5753 
5754 /*
5755  * Query calibration tables from the initialization firmware.  We do this
5756  * only once at first boot.  Called from a process context.
5757  */
5758 static int
5759 iwn5000_query_calibration(struct iwn_softc *sc)
5760 {
5761 	struct iwn5000_calib_config cmd;
5762 	int error;
5763 
5764 	memset(&cmd, 0, sizeof cmd);
5765 	cmd.ucode.once.enable = 0xffffffff;
5766 	cmd.ucode.once.start  = 0xffffffff;
5767 	cmd.ucode.once.send   = 0xffffffff;
5768 	cmd.ucode.flags       = 0xffffffff;
5769 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: sending calibration query\n",
5770 	    __func__);
5771 	error = iwn_cmd(sc, IWN5000_CMD_CALIB_CONFIG, &cmd, sizeof cmd, 0);
5772 	if (error != 0)
5773 		return error;
5774 
5775 	/* Wait at most two seconds for calibration to complete. */
5776 	if (!(sc->sc_flags & IWN_FLAG_CALIB_DONE))
5777 		error = msleep(sc, &sc->sc_mtx, PCATCH, "iwncal", 2 * hz);
5778 	return error;
5779 }
5780 
5781 /*
5782  * Send calibration results to the runtime firmware.  These results were
5783  * obtained on first boot from the initialization firmware.
5784  */
5785 static int
5786 iwn5000_send_calibration(struct iwn_softc *sc)
5787 {
5788 	int idx, error;
5789 
5790 	for (idx = 0; idx < 5; idx++) {
5791 		if (sc->calibcmd[idx].buf == NULL)
5792 			continue;	/* No results available. */
5793 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
5794 		    "send calibration result idx=%d len=%d\n", idx,
5795 		    sc->calibcmd[idx].len);
5796 		error = iwn_cmd(sc, IWN_CMD_PHY_CALIB, sc->calibcmd[idx].buf,
5797 		    sc->calibcmd[idx].len, 0);
5798 		if (error != 0) {
5799 			device_printf(sc->sc_dev,
5800 			    "%s: could not send calibration result, error %d\n",
5801 			    __func__, error);
5802 			return error;
5803 		}
5804 	}
5805 	return 0;
5806 }
5807 
5808 static int
5809 iwn5000_send_wimax_coex(struct iwn_softc *sc)
5810 {
5811 	struct iwn5000_wimax_coex wimax;
5812 
5813 #ifdef notyet
5814 	if (sc->hw_type == IWN_HW_REV_TYPE_6050) {
5815 		/* Enable WiMAX coexistence for combo adapters. */
5816 		wimax.flags =
5817 		    IWN_WIMAX_COEX_ASSOC_WA_UNMASK |
5818 		    IWN_WIMAX_COEX_UNASSOC_WA_UNMASK |
5819 		    IWN_WIMAX_COEX_STA_TABLE_VALID |
5820 		    IWN_WIMAX_COEX_ENABLE;
5821 		memcpy(wimax.events, iwn6050_wimax_events,
5822 		    sizeof iwn6050_wimax_events);
5823 	} else
5824 #endif
5825 	{
5826 		/* Disable WiMAX coexistence. */
5827 		wimax.flags = 0;
5828 		memset(wimax.events, 0, sizeof wimax.events);
5829 	}
5830 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: Configuring WiMAX coexistence\n",
5831 	    __func__);
5832 	return iwn_cmd(sc, IWN5000_CMD_WIMAX_COEX, &wimax, sizeof wimax, 0);
5833 }
5834 
5835 static int
5836 iwn5000_crystal_calib(struct iwn_softc *sc)
5837 {
5838 	struct iwn5000_phy_calib_crystal cmd;
5839 
5840 	memset(&cmd, 0, sizeof cmd);
5841 	cmd.code = IWN5000_PHY_CALIB_CRYSTAL;
5842 	cmd.ngroups = 1;
5843 	cmd.isvalid = 1;
5844 	cmd.cap_pin[0] = le32toh(sc->eeprom_crystal) & 0xff;
5845 	cmd.cap_pin[1] = (le32toh(sc->eeprom_crystal) >> 16) & 0xff;
5846 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "sending crystal calibration %d, %d\n",
5847 	    cmd.cap_pin[0], cmd.cap_pin[1]);
5848 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
5849 }
5850 
5851 static int
5852 iwn5000_temp_offset_calib(struct iwn_softc *sc)
5853 {
5854 	struct iwn5000_phy_calib_temp_offset cmd;
5855 
5856 	memset(&cmd, 0, sizeof cmd);
5857 	cmd.code = IWN5000_PHY_CALIB_TEMP_OFFSET;
5858 	cmd.ngroups = 1;
5859 	cmd.isvalid = 1;
5860 	if (sc->eeprom_temp != 0)
5861 		cmd.offset = htole16(sc->eeprom_temp);
5862 	else
5863 		cmd.offset = htole16(IWN_DEFAULT_TEMP_OFFSET);
5864 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "setting radio sensor offset to %d\n",
5865 	    le16toh(cmd.offset));
5866 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
5867 }
5868 
5869 /*
5870  * This function is called after the runtime firmware notifies us of its
5871  * readiness (called in a process context).
5872  */
5873 static int
5874 iwn4965_post_alive(struct iwn_softc *sc)
5875 {
5876 	int error, qid;
5877 
5878 	if ((error = iwn_nic_lock(sc)) != 0)
5879 		return error;
5880 
5881 	/* Clear TX scheduler state in SRAM. */
5882 	sc->sched_base = iwn_prph_read(sc, IWN_SCHED_SRAM_ADDR);
5883 	iwn_mem_set_region_4(sc, sc->sched_base + IWN4965_SCHED_CTX_OFF, 0,
5884 	    IWN4965_SCHED_CTX_LEN / sizeof (uint32_t));
5885 
5886 	/* Set physical address of TX scheduler rings (1KB aligned). */
5887 	iwn_prph_write(sc, IWN4965_SCHED_DRAM_ADDR, sc->sched_dma.paddr >> 10);
5888 
5889 	IWN_SETBITS(sc, IWN_FH_TX_CHICKEN, IWN_FH_TX_CHICKEN_SCHED_RETRY);
5890 
5891 	/* Disable chain mode for all our 16 queues. */
5892 	iwn_prph_write(sc, IWN4965_SCHED_QCHAIN_SEL, 0);
5893 
5894 	for (qid = 0; qid < IWN4965_NTXQUEUES; qid++) {
5895 		iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), 0);
5896 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | 0);
5897 
5898 		/* Set scheduler window size. */
5899 		iwn_mem_write(sc, sc->sched_base +
5900 		    IWN4965_SCHED_QUEUE_OFFSET(qid), IWN_SCHED_WINSZ);
5901 		/* Set scheduler frame limit. */
5902 		iwn_mem_write(sc, sc->sched_base +
5903 		    IWN4965_SCHED_QUEUE_OFFSET(qid) + 4,
5904 		    IWN_SCHED_LIMIT << 16);
5905 	}
5906 
5907 	/* Enable interrupts for all our 16 queues. */
5908 	iwn_prph_write(sc, IWN4965_SCHED_INTR_MASK, 0xffff);
5909 	/* Identify TX FIFO rings (0-7). */
5910 	iwn_prph_write(sc, IWN4965_SCHED_TXFACT, 0xff);
5911 
5912 	/* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
5913 	for (qid = 0; qid < 7; qid++) {
5914 		static uint8_t qid2fifo[] = { 3, 2, 1, 0, 4, 5, 6 };
5915 		iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
5916 		    IWN4965_TXQ_STATUS_ACTIVE | qid2fifo[qid] << 1);
5917 	}
5918 	iwn_nic_unlock(sc);
5919 	return 0;
5920 }
5921 
5922 /*
5923  * This function is called after the initialization or runtime firmware
5924  * notifies us of its readiness (called in a process context).
5925  */
5926 static int
5927 iwn5000_post_alive(struct iwn_softc *sc)
5928 {
5929 	int error, qid;
5930 
5931 	/* Switch to using ICT interrupt mode. */
5932 	iwn5000_ict_reset(sc);
5933 
5934 	if ((error = iwn_nic_lock(sc)) != 0)
5935 		return error;
5936 
5937 	/* Clear TX scheduler state in SRAM. */
5938 	sc->sched_base = iwn_prph_read(sc, IWN_SCHED_SRAM_ADDR);
5939 	iwn_mem_set_region_4(sc, sc->sched_base + IWN5000_SCHED_CTX_OFF, 0,
5940 	    IWN5000_SCHED_CTX_LEN / sizeof (uint32_t));
5941 
5942 	/* Set physical address of TX scheduler rings (1KB aligned). */
5943 	iwn_prph_write(sc, IWN5000_SCHED_DRAM_ADDR, sc->sched_dma.paddr >> 10);
5944 
5945 	IWN_SETBITS(sc, IWN_FH_TX_CHICKEN, IWN_FH_TX_CHICKEN_SCHED_RETRY);
5946 
5947 	/* Enable chain mode for all queues, except command queue. */
5948 	iwn_prph_write(sc, IWN5000_SCHED_QCHAIN_SEL, 0xfffef);
5949 	iwn_prph_write(sc, IWN5000_SCHED_AGGR_SEL, 0);
5950 
5951 	for (qid = 0; qid < IWN5000_NTXQUEUES; qid++) {
5952 		iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), 0);
5953 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | 0);
5954 
5955 		iwn_mem_write(sc, sc->sched_base +
5956 		    IWN5000_SCHED_QUEUE_OFFSET(qid), 0);
5957 		/* Set scheduler window size and frame limit. */
5958 		iwn_mem_write(sc, sc->sched_base +
5959 		    IWN5000_SCHED_QUEUE_OFFSET(qid) + 4,
5960 		    IWN_SCHED_LIMIT << 16 | IWN_SCHED_WINSZ);
5961 	}
5962 
5963 	/* Enable interrupts for all our 20 queues. */
5964 	iwn_prph_write(sc, IWN5000_SCHED_INTR_MASK, 0xfffff);
5965 	/* Identify TX FIFO rings (0-7). */
5966 	iwn_prph_write(sc, IWN5000_SCHED_TXFACT, 0xff);
5967 
5968 	/* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
5969 	for (qid = 0; qid < 7; qid++) {
5970 		static uint8_t qid2fifo[] = { 3, 2, 1, 0, 7, 5, 6 };
5971 		iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
5972 		    IWN5000_TXQ_STATUS_ACTIVE | qid2fifo[qid]);
5973 	}
5974 	iwn_nic_unlock(sc);
5975 
5976 	/* Configure WiMAX coexistence for combo adapters. */
5977 	error = iwn5000_send_wimax_coex(sc);
5978 	if (error != 0) {
5979 		device_printf(sc->sc_dev,
5980 		    "%s: could not configure WiMAX coexistence, error %d\n",
5981 		    __func__, error);
5982 		return error;
5983 	}
5984 	if (sc->hw_type != IWN_HW_REV_TYPE_5150) {
5985 		/* Perform crystal calibration. */
5986 		error = iwn5000_crystal_calib(sc);
5987 		if (error != 0) {
5988 			device_printf(sc->sc_dev,
5989 			    "%s: crystal calibration failed, error %d\n",
5990 			    __func__, error);
5991 			return error;
5992 		}
5993 	}
5994 	if (!(sc->sc_flags & IWN_FLAG_CALIB_DONE)) {
5995 		/* Query calibration from the initialization firmware. */
5996 		if ((error = iwn5000_query_calibration(sc)) != 0) {
5997 			device_printf(sc->sc_dev,
5998 			    "%s: could not query calibration, error %d\n",
5999 			    __func__, error);
6000 			return error;
6001 		}
6002 		/*
6003 		 * We have the calibration results now, reboot with the
6004 		 * runtime firmware (call ourselves recursively!)
6005 		 */
6006 		iwn_hw_stop(sc);
6007 		error = iwn_hw_init(sc);
6008 	} else {
6009 		/* Send calibration results to runtime firmware. */
6010 		error = iwn5000_send_calibration(sc);
6011 	}
6012 	return error;
6013 }
6014 
6015 /*
6016  * The firmware boot code is small and is intended to be copied directly into
6017  * the NIC internal memory (no DMA transfer).
6018  */
6019 static int
6020 iwn4965_load_bootcode(struct iwn_softc *sc, const uint8_t *ucode, int size)
6021 {
6022 	int error, ntries;
6023 
6024 	size /= sizeof (uint32_t);
6025 
6026 	if ((error = iwn_nic_lock(sc)) != 0)
6027 		return error;
6028 
6029 	/* Copy microcode image into NIC memory. */
6030 	iwn_prph_write_region_4(sc, IWN_BSM_SRAM_BASE,
6031 	    (const uint32_t *)ucode, size);
6032 
6033 	iwn_prph_write(sc, IWN_BSM_WR_MEM_SRC, 0);
6034 	iwn_prph_write(sc, IWN_BSM_WR_MEM_DST, IWN_FW_TEXT_BASE);
6035 	iwn_prph_write(sc, IWN_BSM_WR_DWCOUNT, size);
6036 
6037 	/* Start boot load now. */
6038 	iwn_prph_write(sc, IWN_BSM_WR_CTRL, IWN_BSM_WR_CTRL_START);
6039 
6040 	/* Wait for transfer to complete. */
6041 	for (ntries = 0; ntries < 1000; ntries++) {
6042 		if (!(iwn_prph_read(sc, IWN_BSM_WR_CTRL) &
6043 		    IWN_BSM_WR_CTRL_START))
6044 			break;
6045 		DELAY(10);
6046 	}
6047 	if (ntries == 1000) {
6048 		device_printf(sc->sc_dev, "%s: could not load boot firmware\n",
6049 		    __func__);
6050 		iwn_nic_unlock(sc);
6051 		return ETIMEDOUT;
6052 	}
6053 
6054 	/* Enable boot after power up. */
6055 	iwn_prph_write(sc, IWN_BSM_WR_CTRL, IWN_BSM_WR_CTRL_START_EN);
6056 
6057 	iwn_nic_unlock(sc);
6058 	return 0;
6059 }
6060 
6061 static int
6062 iwn4965_load_firmware(struct iwn_softc *sc)
6063 {
6064 	struct iwn_fw_info *fw = &sc->fw;
6065 	struct iwn_dma_info *dma = &sc->fw_dma;
6066 	int error;
6067 
6068 	/* Copy initialization sections into pre-allocated DMA-safe memory. */
6069 	memcpy(dma->vaddr, fw->init.data, fw->init.datasz);
6070 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
6071 	memcpy(dma->vaddr + IWN4965_FW_DATA_MAXSZ,
6072 	    fw->init.text, fw->init.textsz);
6073 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
6074 
6075 	/* Tell adapter where to find initialization sections. */
6076 	if ((error = iwn_nic_lock(sc)) != 0)
6077 		return error;
6078 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_ADDR, dma->paddr >> 4);
6079 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_SIZE, fw->init.datasz);
6080 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_ADDR,
6081 	    (dma->paddr + IWN4965_FW_DATA_MAXSZ) >> 4);
6082 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_SIZE, fw->init.textsz);
6083 	iwn_nic_unlock(sc);
6084 
6085 	/* Load firmware boot code. */
6086 	error = iwn4965_load_bootcode(sc, fw->boot.text, fw->boot.textsz);
6087 	if (error != 0) {
6088 		device_printf(sc->sc_dev, "%s: could not load boot firmware\n",
6089 		    __func__);
6090 		return error;
6091 	}
6092 	/* Now press "execute". */
6093 	IWN_WRITE(sc, IWN_RESET, 0);
6094 
6095 	/* Wait at most one second for first alive notification. */
6096 	if ((error = msleep(sc, &sc->sc_mtx, PCATCH, "iwninit", hz)) != 0) {
6097 		device_printf(sc->sc_dev,
6098 		    "%s: timeout waiting for adapter to initialize, error %d\n",
6099 		    __func__, error);
6100 		return error;
6101 	}
6102 
6103 	/* Retrieve current temperature for initial TX power calibration. */
6104 	sc->rawtemp = sc->ucode_info.temp[3].chan20MHz;
6105 	sc->temp = iwn4965_get_temperature(sc);
6106 
6107 	/* Copy runtime sections into pre-allocated DMA-safe memory. */
6108 	memcpy(dma->vaddr, fw->main.data, fw->main.datasz);
6109 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
6110 	memcpy(dma->vaddr + IWN4965_FW_DATA_MAXSZ,
6111 	    fw->main.text, fw->main.textsz);
6112 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
6113 
6114 	/* Tell adapter where to find runtime sections. */
6115 	if ((error = iwn_nic_lock(sc)) != 0)
6116 		return error;
6117 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_ADDR, dma->paddr >> 4);
6118 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_SIZE, fw->main.datasz);
6119 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_ADDR,
6120 	    (dma->paddr + IWN4965_FW_DATA_MAXSZ) >> 4);
6121 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_SIZE,
6122 	    IWN_FW_UPDATED | fw->main.textsz);
6123 	iwn_nic_unlock(sc);
6124 
6125 	return 0;
6126 }
6127 
6128 static int
6129 iwn5000_load_firmware_section(struct iwn_softc *sc, uint32_t dst,
6130     const uint8_t *section, int size)
6131 {
6132 	struct iwn_dma_info *dma = &sc->fw_dma;
6133 	int error;
6134 
6135 	/* Copy firmware section into pre-allocated DMA-safe memory. */
6136 	memcpy(dma->vaddr, section, size);
6137 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
6138 
6139 	if ((error = iwn_nic_lock(sc)) != 0)
6140 		return error;
6141 
6142 	IWN_WRITE(sc, IWN_FH_TX_CONFIG(IWN_SRVC_DMACHNL),
6143 	    IWN_FH_TX_CONFIG_DMA_PAUSE);
6144 
6145 	IWN_WRITE(sc, IWN_FH_SRAM_ADDR(IWN_SRVC_DMACHNL), dst);
6146 	IWN_WRITE(sc, IWN_FH_TFBD_CTRL0(IWN_SRVC_DMACHNL),
6147 	    IWN_LOADDR(dma->paddr));
6148 	IWN_WRITE(sc, IWN_FH_TFBD_CTRL1(IWN_SRVC_DMACHNL),
6149 	    IWN_HIADDR(dma->paddr) << 28 | size);
6150 	IWN_WRITE(sc, IWN_FH_TXBUF_STATUS(IWN_SRVC_DMACHNL),
6151 	    IWN_FH_TXBUF_STATUS_TBNUM(1) |
6152 	    IWN_FH_TXBUF_STATUS_TBIDX(1) |
6153 	    IWN_FH_TXBUF_STATUS_TFBD_VALID);
6154 
6155 	/* Kick Flow Handler to start DMA transfer. */
6156 	IWN_WRITE(sc, IWN_FH_TX_CONFIG(IWN_SRVC_DMACHNL),
6157 	    IWN_FH_TX_CONFIG_DMA_ENA | IWN_FH_TX_CONFIG_CIRQ_HOST_ENDTFD);
6158 
6159 	iwn_nic_unlock(sc);
6160 
6161 	/* Wait at most five seconds for FH DMA transfer to complete. */
6162 	return msleep(sc, &sc->sc_mtx, PCATCH, "iwninit", 5 * hz);
6163 }
6164 
6165 static int
6166 iwn5000_load_firmware(struct iwn_softc *sc)
6167 {
6168 	struct iwn_fw_part *fw;
6169 	int error;
6170 
6171 	/* Load the initialization firmware on first boot only. */
6172 	fw = (sc->sc_flags & IWN_FLAG_CALIB_DONE) ?
6173 	    &sc->fw.main : &sc->fw.init;
6174 
6175 	error = iwn5000_load_firmware_section(sc, IWN_FW_TEXT_BASE,
6176 	    fw->text, fw->textsz);
6177 	if (error != 0) {
6178 		device_printf(sc->sc_dev,
6179 		    "%s: could not load firmware %s section, error %d\n",
6180 		    __func__, ".text", error);
6181 		return error;
6182 	}
6183 	error = iwn5000_load_firmware_section(sc, IWN_FW_DATA_BASE,
6184 	    fw->data, fw->datasz);
6185 	if (error != 0) {
6186 		device_printf(sc->sc_dev,
6187 		    "%s: could not load firmware %s section, error %d\n",
6188 		    __func__, ".data", error);
6189 		return error;
6190 	}
6191 
6192 	/* Now press "execute". */
6193 	IWN_WRITE(sc, IWN_RESET, 0);
6194 	return 0;
6195 }
6196 
6197 /*
6198  * Extract text and data sections from a legacy firmware image.
6199  */
6200 static int
6201 iwn_read_firmware_leg(struct iwn_softc *sc, struct iwn_fw_info *fw)
6202 {
6203 	const uint32_t *ptr;
6204 	size_t hdrlen = 24;
6205 	uint32_t rev;
6206 
6207 	ptr = (const uint32_t *)fw->data;
6208 	rev = le32toh(*ptr++);
6209 
6210 	/* Check firmware API version. */
6211 	if (IWN_FW_API(rev) <= 1) {
6212 		device_printf(sc->sc_dev,
6213 		    "%s: bad firmware, need API version >=2\n", __func__);
6214 		return EINVAL;
6215 	}
6216 	if (IWN_FW_API(rev) >= 3) {
6217 		/* Skip build number (version 2 header). */
6218 		hdrlen += 4;
6219 		ptr++;
6220 	}
6221 	if (fw->size < hdrlen) {
6222 		device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
6223 		    __func__, fw->size);
6224 		return EINVAL;
6225 	}
6226 	fw->main.textsz = le32toh(*ptr++);
6227 	fw->main.datasz = le32toh(*ptr++);
6228 	fw->init.textsz = le32toh(*ptr++);
6229 	fw->init.datasz = le32toh(*ptr++);
6230 	fw->boot.textsz = le32toh(*ptr++);
6231 
6232 	/* Check that all firmware sections fit. */
6233 	if (fw->size < hdrlen + fw->main.textsz + fw->main.datasz +
6234 	    fw->init.textsz + fw->init.datasz + fw->boot.textsz) {
6235 		device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
6236 		    __func__, fw->size);
6237 		return EINVAL;
6238 	}
6239 
6240 	/* Get pointers to firmware sections. */
6241 	fw->main.text = (const uint8_t *)ptr;
6242 	fw->main.data = fw->main.text + fw->main.textsz;
6243 	fw->init.text = fw->main.data + fw->main.datasz;
6244 	fw->init.data = fw->init.text + fw->init.textsz;
6245 	fw->boot.text = fw->init.data + fw->init.datasz;
6246 	return 0;
6247 }
6248 
6249 /*
6250  * Extract text and data sections from a TLV firmware image.
6251  */
6252 static int
6253 iwn_read_firmware_tlv(struct iwn_softc *sc, struct iwn_fw_info *fw,
6254     uint16_t alt)
6255 {
6256 	const struct iwn_fw_tlv_hdr *hdr;
6257 	const struct iwn_fw_tlv *tlv;
6258 	const uint8_t *ptr, *end;
6259 	uint64_t altmask;
6260 	uint32_t len, tmp;
6261 
6262 	if (fw->size < sizeof (*hdr)) {
6263 		device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
6264 		    __func__, fw->size);
6265 		return EINVAL;
6266 	}
6267 	hdr = (const struct iwn_fw_tlv_hdr *)fw->data;
6268 	if (hdr->signature != htole32(IWN_FW_SIGNATURE)) {
6269 		device_printf(sc->sc_dev, "%s: bad firmware signature 0x%08x\n",
6270 		    __func__, le32toh(hdr->signature));
6271 		return EINVAL;
6272 	}
6273 	DPRINTF(sc, IWN_DEBUG_RESET, "FW: \"%.64s\", build 0x%x\n", hdr->descr,
6274 	    le32toh(hdr->build));
6275 
6276 	/*
6277 	 * Select the closest supported alternative that is less than
6278 	 * or equal to the specified one.
6279 	 */
6280 	altmask = le64toh(hdr->altmask);
6281 	while (alt > 0 && !(altmask & (1ULL << alt)))
6282 		alt--;	/* Downgrade. */
6283 	DPRINTF(sc, IWN_DEBUG_RESET, "using alternative %d\n", alt);
6284 
6285 	ptr = (const uint8_t *)(hdr + 1);
6286 	end = (const uint8_t *)(fw->data + fw->size);
6287 
6288 	/* Parse type-length-value fields. */
6289 	while (ptr + sizeof (*tlv) <= end) {
6290 		tlv = (const struct iwn_fw_tlv *)ptr;
6291 		len = le32toh(tlv->len);
6292 
6293 		ptr += sizeof (*tlv);
6294 		if (ptr + len > end) {
6295 			device_printf(sc->sc_dev,
6296 			    "%s: firmware too short: %zu bytes\n", __func__,
6297 			    fw->size);
6298 			return EINVAL;
6299 		}
6300 		/* Skip other alternatives. */
6301 		if (tlv->alt != 0 && tlv->alt != htole16(alt))
6302 			goto next;
6303 
6304 		switch (le16toh(tlv->type)) {
6305 		case IWN_FW_TLV_MAIN_TEXT:
6306 			fw->main.text = ptr;
6307 			fw->main.textsz = len;
6308 			break;
6309 		case IWN_FW_TLV_MAIN_DATA:
6310 			fw->main.data = ptr;
6311 			fw->main.datasz = len;
6312 			break;
6313 		case IWN_FW_TLV_INIT_TEXT:
6314 			fw->init.text = ptr;
6315 			fw->init.textsz = len;
6316 			break;
6317 		case IWN_FW_TLV_INIT_DATA:
6318 			fw->init.data = ptr;
6319 			fw->init.datasz = len;
6320 			break;
6321 		case IWN_FW_TLV_BOOT_TEXT:
6322 			fw->boot.text = ptr;
6323 			fw->boot.textsz = len;
6324 			break;
6325 		case IWN_FW_TLV_ENH_SENS:
6326 			if (!len)
6327 				sc->sc_flags |= IWN_FLAG_ENH_SENS;
6328 			break;
6329 		case IWN_FW_TLV_PHY_CALIB:
6330 			tmp = htole32(*ptr);
6331 			if (tmp < 253) {
6332 				sc->reset_noise_gain = tmp;
6333 				sc->noise_gain = tmp + 1;
6334 			}
6335 			break;
6336 		default:
6337 			DPRINTF(sc, IWN_DEBUG_RESET,
6338 			    "TLV type %d not handled\n", le16toh(tlv->type));
6339 			break;
6340 		}
6341  next:		/* TLV fields are 32-bit aligned. */
6342 		ptr += (len + 3) & ~3;
6343 	}
6344 	return 0;
6345 }
6346 
6347 static int
6348 iwn_read_firmware(struct iwn_softc *sc)
6349 {
6350 	struct iwn_fw_info *fw = &sc->fw;
6351 	int error;
6352 
6353 	IWN_UNLOCK(sc);
6354 
6355 	memset(fw, 0, sizeof (*fw));
6356 
6357 	/* Read firmware image from filesystem. */
6358 	sc->fw_fp = firmware_get(sc->fwname);
6359 	if (sc->fw_fp == NULL) {
6360 		device_printf(sc->sc_dev, "%s: could not read firmware %s\n",
6361 		    __func__, sc->fwname);
6362 		IWN_LOCK(sc);
6363 		return EINVAL;
6364 	}
6365 	IWN_LOCK(sc);
6366 
6367 	fw->size = sc->fw_fp->datasize;
6368 	fw->data = (const uint8_t *)sc->fw_fp->data;
6369 	if (fw->size < sizeof (uint32_t)) {
6370 		device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
6371 		    __func__, fw->size);
6372 		firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
6373 		sc->fw_fp = NULL;
6374 		return EINVAL;
6375 	}
6376 
6377 	/* Retrieve text and data sections. */
6378 	if (*(const uint32_t *)fw->data != 0)	/* Legacy image. */
6379 		error = iwn_read_firmware_leg(sc, fw);
6380 	else
6381 		error = iwn_read_firmware_tlv(sc, fw, 1);
6382 	if (error != 0) {
6383 		device_printf(sc->sc_dev,
6384 		    "%s: could not read firmware sections, error %d\n",
6385 		    __func__, error);
6386 		firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
6387 		sc->fw_fp = NULL;
6388 		return error;
6389 	}
6390 
6391 	/* Make sure text and data sections fit in hardware memory. */
6392 	if (fw->main.textsz > sc->fw_text_maxsz ||
6393 	    fw->main.datasz > sc->fw_data_maxsz ||
6394 	    fw->init.textsz > sc->fw_text_maxsz ||
6395 	    fw->init.datasz > sc->fw_data_maxsz ||
6396 	    fw->boot.textsz > IWN_FW_BOOT_TEXT_MAXSZ ||
6397 	    (fw->boot.textsz & 3) != 0) {
6398 		device_printf(sc->sc_dev, "%s: firmware sections too large\n",
6399 		    __func__);
6400 		firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
6401 		sc->fw_fp = NULL;
6402 		return EINVAL;
6403 	}
6404 
6405 	/* We can proceed with loading the firmware. */
6406 	return 0;
6407 }
6408 
6409 static int
6410 iwn_clock_wait(struct iwn_softc *sc)
6411 {
6412 	int ntries;
6413 
6414 	/* Set "initialization complete" bit. */
6415 	IWN_SETBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_INIT_DONE);
6416 
6417 	/* Wait for clock stabilization. */
6418 	for (ntries = 0; ntries < 2500; ntries++) {
6419 		if (IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_MAC_CLOCK_READY)
6420 			return 0;
6421 		DELAY(10);
6422 	}
6423 	device_printf(sc->sc_dev,
6424 	    "%s: timeout waiting for clock stabilization\n", __func__);
6425 	return ETIMEDOUT;
6426 }
6427 
6428 static int
6429 iwn_apm_init(struct iwn_softc *sc)
6430 {
6431 	uint32_t reg;
6432 	int error;
6433 
6434 	/* Disable L0s exit timer (NMI bug workaround). */
6435 	IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_DIS_L0S_TIMER);
6436 	/* Don't wait for ICH L0s (ICH bug workaround). */
6437 	IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_L1A_NO_L0S_RX);
6438 
6439 	/* Set FH wait threshold to max (HW bug under stress workaround). */
6440 	IWN_SETBITS(sc, IWN_DBG_HPET_MEM, 0xffff0000);
6441 
6442 	/* Enable HAP INTA to move adapter from L1a to L0s. */
6443 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_HAP_WAKE_L1A);
6444 
6445 	/* Retrieve PCIe Active State Power Management (ASPM). */
6446 	reg = pci_read_config(sc->sc_dev, sc->sc_cap_off + 0x10, 1);
6447 	/* Workaround for HW instability in PCIe L0->L0s->L1 transition. */
6448 	if (reg & 0x02)	/* L1 Entry enabled. */
6449 		IWN_SETBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA);
6450 	else
6451 		IWN_CLRBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA);
6452 
6453 	if (sc->hw_type != IWN_HW_REV_TYPE_4965 &&
6454 	    sc->hw_type <= IWN_HW_REV_TYPE_1000)
6455 		IWN_SETBITS(sc, IWN_ANA_PLL, IWN_ANA_PLL_INIT);
6456 
6457 	/* Wait for clock stabilization before accessing prph. */
6458 	if ((error = iwn_clock_wait(sc)) != 0)
6459 		return error;
6460 
6461 	if ((error = iwn_nic_lock(sc)) != 0)
6462 		return error;
6463 	if (sc->hw_type == IWN_HW_REV_TYPE_4965) {
6464 		/* Enable DMA and BSM (Bootstrap State Machine). */
6465 		iwn_prph_write(sc, IWN_APMG_CLK_EN,
6466 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT |
6467 		    IWN_APMG_CLK_CTRL_BSM_CLK_RQT);
6468 	} else {
6469 		/* Enable DMA. */
6470 		iwn_prph_write(sc, IWN_APMG_CLK_EN,
6471 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT);
6472 	}
6473 	DELAY(20);
6474 	/* Disable L1-Active. */
6475 	iwn_prph_setbits(sc, IWN_APMG_PCI_STT, IWN_APMG_PCI_STT_L1A_DIS);
6476 	iwn_nic_unlock(sc);
6477 
6478 	return 0;
6479 }
6480 
6481 static void
6482 iwn_apm_stop_master(struct iwn_softc *sc)
6483 {
6484 	int ntries;
6485 
6486 	/* Stop busmaster DMA activity. */
6487 	IWN_SETBITS(sc, IWN_RESET, IWN_RESET_STOP_MASTER);
6488 	for (ntries = 0; ntries < 100; ntries++) {
6489 		if (IWN_READ(sc, IWN_RESET) & IWN_RESET_MASTER_DISABLED)
6490 			return;
6491 		DELAY(10);
6492 	}
6493 	device_printf(sc->sc_dev, "%s: timeout waiting for master\n", __func__);
6494 }
6495 
6496 static void
6497 iwn_apm_stop(struct iwn_softc *sc)
6498 {
6499 	iwn_apm_stop_master(sc);
6500 
6501 	/* Reset the entire device. */
6502 	IWN_SETBITS(sc, IWN_RESET, IWN_RESET_SW);
6503 	DELAY(10);
6504 	/* Clear "initialization complete" bit. */
6505 	IWN_CLRBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_INIT_DONE);
6506 }
6507 
6508 static int
6509 iwn4965_nic_config(struct iwn_softc *sc)
6510 {
6511 	if (IWN_RFCFG_TYPE(sc->rfcfg) == 1) {
6512 		/*
6513 		 * I don't believe this to be correct but this is what the
6514 		 * vendor driver is doing. Probably the bits should not be
6515 		 * shifted in IWN_RFCFG_*.
6516 		 */
6517 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
6518 		    IWN_RFCFG_TYPE(sc->rfcfg) |
6519 		    IWN_RFCFG_STEP(sc->rfcfg) |
6520 		    IWN_RFCFG_DASH(sc->rfcfg));
6521 	}
6522 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
6523 	    IWN_HW_IF_CONFIG_RADIO_SI | IWN_HW_IF_CONFIG_MAC_SI);
6524 	return 0;
6525 }
6526 
6527 static int
6528 iwn5000_nic_config(struct iwn_softc *sc)
6529 {
6530 	uint32_t tmp;
6531 	int error;
6532 
6533 	if (IWN_RFCFG_TYPE(sc->rfcfg) < 3) {
6534 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
6535 		    IWN_RFCFG_TYPE(sc->rfcfg) |
6536 		    IWN_RFCFG_STEP(sc->rfcfg) |
6537 		    IWN_RFCFG_DASH(sc->rfcfg));
6538 	}
6539 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
6540 	    IWN_HW_IF_CONFIG_RADIO_SI | IWN_HW_IF_CONFIG_MAC_SI);
6541 
6542 	if ((error = iwn_nic_lock(sc)) != 0)
6543 		return error;
6544 	iwn_prph_setbits(sc, IWN_APMG_PS, IWN_APMG_PS_EARLY_PWROFF_DIS);
6545 
6546 	if (sc->hw_type == IWN_HW_REV_TYPE_1000) {
6547 		/*
6548 		 * Select first Switching Voltage Regulator (1.32V) to
6549 		 * solve a stability issue related to noisy DC2DC line
6550 		 * in the silicon of 1000 Series.
6551 		 */
6552 		tmp = iwn_prph_read(sc, IWN_APMG_DIGITAL_SVR);
6553 		tmp &= ~IWN_APMG_DIGITAL_SVR_VOLTAGE_MASK;
6554 		tmp |= IWN_APMG_DIGITAL_SVR_VOLTAGE_1_32;
6555 		iwn_prph_write(sc, IWN_APMG_DIGITAL_SVR, tmp);
6556 	}
6557 	iwn_nic_unlock(sc);
6558 
6559 	if (sc->sc_flags & IWN_FLAG_INTERNAL_PA) {
6560 		/* Use internal power amplifier only. */
6561 		IWN_WRITE(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_RADIO_2X2_IPA);
6562 	}
6563 	if ((sc->hw_type == IWN_HW_REV_TYPE_6050 ||
6564 	     sc->hw_type == IWN_HW_REV_TYPE_6005) && sc->calib_ver >= 6) {
6565 		/* Indicate that ROM calibration version is >=6. */
6566 		IWN_SETBITS(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_CALIB_VER6);
6567 	}
6568 	if (sc->hw_type == IWN_HW_REV_TYPE_6005)
6569 		IWN_SETBITS(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_6050_1X2);
6570 	return 0;
6571 }
6572 
6573 /*
6574  * Take NIC ownership over Intel Active Management Technology (AMT).
6575  */
6576 static int
6577 iwn_hw_prepare(struct iwn_softc *sc)
6578 {
6579 	int ntries;
6580 
6581 	/* Check if hardware is ready. */
6582 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_NIC_READY);
6583 	for (ntries = 0; ntries < 5; ntries++) {
6584 		if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
6585 		    IWN_HW_IF_CONFIG_NIC_READY)
6586 			return 0;
6587 		DELAY(10);
6588 	}
6589 
6590 	/* Hardware not ready, force into ready state. */
6591 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_PREPARE);
6592 	for (ntries = 0; ntries < 15000; ntries++) {
6593 		if (!(IWN_READ(sc, IWN_HW_IF_CONFIG) &
6594 		    IWN_HW_IF_CONFIG_PREPARE_DONE))
6595 			break;
6596 		DELAY(10);
6597 	}
6598 	if (ntries == 15000)
6599 		return ETIMEDOUT;
6600 
6601 	/* Hardware should be ready now. */
6602 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_NIC_READY);
6603 	for (ntries = 0; ntries < 5; ntries++) {
6604 		if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
6605 		    IWN_HW_IF_CONFIG_NIC_READY)
6606 			return 0;
6607 		DELAY(10);
6608 	}
6609 	return ETIMEDOUT;
6610 }
6611 
6612 static int
6613 iwn_hw_init(struct iwn_softc *sc)
6614 {
6615 	struct iwn_ops *ops = &sc->ops;
6616 	int error, chnl, qid;
6617 
6618 	/* Clear pending interrupts. */
6619 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
6620 
6621 	if ((error = iwn_apm_init(sc)) != 0) {
6622 		device_printf(sc->sc_dev,
6623 		    "%s: could not power ON adapter, error %d\n", __func__,
6624 		    error);
6625 		return error;
6626 	}
6627 
6628 	/* Select VMAIN power source. */
6629 	if ((error = iwn_nic_lock(sc)) != 0)
6630 		return error;
6631 	iwn_prph_clrbits(sc, IWN_APMG_PS, IWN_APMG_PS_PWR_SRC_MASK);
6632 	iwn_nic_unlock(sc);
6633 
6634 	/* Perform adapter-specific initialization. */
6635 	if ((error = ops->nic_config(sc)) != 0)
6636 		return error;
6637 
6638 	/* Initialize RX ring. */
6639 	if ((error = iwn_nic_lock(sc)) != 0)
6640 		return error;
6641 	IWN_WRITE(sc, IWN_FH_RX_CONFIG, 0);
6642 	IWN_WRITE(sc, IWN_FH_RX_WPTR, 0);
6643 	/* Set physical address of RX ring (256-byte aligned). */
6644 	IWN_WRITE(sc, IWN_FH_RX_BASE, sc->rxq.desc_dma.paddr >> 8);
6645 	/* Set physical address of RX status (16-byte aligned). */
6646 	IWN_WRITE(sc, IWN_FH_STATUS_WPTR, sc->rxq.stat_dma.paddr >> 4);
6647 	/* Enable RX. */
6648 	IWN_WRITE(sc, IWN_FH_RX_CONFIG,
6649 	    IWN_FH_RX_CONFIG_ENA           |
6650 	    IWN_FH_RX_CONFIG_IGN_RXF_EMPTY |	/* HW bug workaround */
6651 	    IWN_FH_RX_CONFIG_IRQ_DST_HOST  |
6652 	    IWN_FH_RX_CONFIG_SINGLE_FRAME  |
6653 	    IWN_FH_RX_CONFIG_RB_TIMEOUT(0) |
6654 	    IWN_FH_RX_CONFIG_NRBD(IWN_RX_RING_COUNT_LOG));
6655 	iwn_nic_unlock(sc);
6656 	IWN_WRITE(sc, IWN_FH_RX_WPTR, (IWN_RX_RING_COUNT - 1) & ~7);
6657 
6658 	if ((error = iwn_nic_lock(sc)) != 0)
6659 		return error;
6660 
6661 	/* Initialize TX scheduler. */
6662 	iwn_prph_write(sc, sc->sched_txfact_addr, 0);
6663 
6664 	/* Set physical address of "keep warm" page (16-byte aligned). */
6665 	IWN_WRITE(sc, IWN_FH_KW_ADDR, sc->kw_dma.paddr >> 4);
6666 
6667 	/* Initialize TX rings. */
6668 	for (qid = 0; qid < sc->ntxqs; qid++) {
6669 		struct iwn_tx_ring *txq = &sc->txq[qid];
6670 
6671 		/* Set physical address of TX ring (256-byte aligned). */
6672 		IWN_WRITE(sc, IWN_FH_CBBC_QUEUE(qid),
6673 		    txq->desc_dma.paddr >> 8);
6674 	}
6675 	iwn_nic_unlock(sc);
6676 
6677 	/* Enable DMA channels. */
6678 	for (chnl = 0; chnl < sc->ndmachnls; chnl++) {
6679 		IWN_WRITE(sc, IWN_FH_TX_CONFIG(chnl),
6680 		    IWN_FH_TX_CONFIG_DMA_ENA |
6681 		    IWN_FH_TX_CONFIG_DMA_CREDIT_ENA);
6682 	}
6683 
6684 	/* Clear "radio off" and "commands blocked" bits. */
6685 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
6686 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CMD_BLOCKED);
6687 
6688 	/* Clear pending interrupts. */
6689 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
6690 	/* Enable interrupt coalescing. */
6691 	IWN_WRITE(sc, IWN_INT_COALESCING, 512 / 8);
6692 	/* Enable interrupts. */
6693 	IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
6694 
6695 	/* _Really_ make sure "radio off" bit is cleared! */
6696 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
6697 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
6698 
6699 	/* Enable shadow registers. */
6700 	if (sc->hw_type >= IWN_HW_REV_TYPE_6000)
6701 		IWN_SETBITS(sc, IWN_SHADOW_REG_CTRL, 0x800fffff);
6702 
6703 	if ((error = ops->load_firmware(sc)) != 0) {
6704 		device_printf(sc->sc_dev,
6705 		    "%s: could not load firmware, error %d\n", __func__,
6706 		    error);
6707 		return error;
6708 	}
6709 	/* Wait at most one second for firmware alive notification. */
6710 	if ((error = msleep(sc, &sc->sc_mtx, PCATCH, "iwninit", hz)) != 0) {
6711 		device_printf(sc->sc_dev,
6712 		    "%s: timeout waiting for adapter to initialize, error %d\n",
6713 		    __func__, error);
6714 		return error;
6715 	}
6716 	/* Do post-firmware initialization. */
6717 	return ops->post_alive(sc);
6718 }
6719 
6720 static void
6721 iwn_hw_stop(struct iwn_softc *sc)
6722 {
6723 	int chnl, qid, ntries;
6724 
6725 	IWN_WRITE(sc, IWN_RESET, IWN_RESET_NEVO);
6726 
6727 	/* Disable interrupts. */
6728 	IWN_WRITE(sc, IWN_INT_MASK, 0);
6729 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
6730 	IWN_WRITE(sc, IWN_FH_INT, 0xffffffff);
6731 	sc->sc_flags &= ~IWN_FLAG_USE_ICT;
6732 
6733 	/* Make sure we no longer hold the NIC lock. */
6734 	iwn_nic_unlock(sc);
6735 
6736 	/* Stop TX scheduler. */
6737 	iwn_prph_write(sc, sc->sched_txfact_addr, 0);
6738 
6739 	/* Stop all DMA channels. */
6740 	if (iwn_nic_lock(sc) == 0) {
6741 		for (chnl = 0; chnl < sc->ndmachnls; chnl++) {
6742 			IWN_WRITE(sc, IWN_FH_TX_CONFIG(chnl), 0);
6743 			for (ntries = 0; ntries < 200; ntries++) {
6744 				if (IWN_READ(sc, IWN_FH_TX_STATUS) &
6745 				    IWN_FH_TX_STATUS_IDLE(chnl))
6746 					break;
6747 				DELAY(10);
6748 			}
6749 		}
6750 		iwn_nic_unlock(sc);
6751 	}
6752 
6753 	/* Stop RX ring. */
6754 	iwn_reset_rx_ring(sc, &sc->rxq);
6755 
6756 	/* Reset all TX rings. */
6757 	for (qid = 0; qid < sc->ntxqs; qid++)
6758 		iwn_reset_tx_ring(sc, &sc->txq[qid]);
6759 
6760 	if (iwn_nic_lock(sc) == 0) {
6761 		iwn_prph_write(sc, IWN_APMG_CLK_DIS,
6762 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT);
6763 		iwn_nic_unlock(sc);
6764 	}
6765 	DELAY(5);
6766 	/* Power OFF adapter. */
6767 	iwn_apm_stop(sc);
6768 }
6769 
6770 static void
6771 iwn_radio_on(void *arg0, int pending)
6772 {
6773 	struct iwn_softc *sc = arg0;
6774 	struct ifnet *ifp = sc->sc_ifp;
6775 	struct ieee80211com *ic = ifp->if_l2com;
6776 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
6777 
6778 	if (vap != NULL) {
6779 		iwn_init(sc);
6780 		ieee80211_init(vap);
6781 	}
6782 }
6783 
6784 static void
6785 iwn_radio_off(void *arg0, int pending)
6786 {
6787 	struct iwn_softc *sc = arg0;
6788 	struct ifnet *ifp = sc->sc_ifp;
6789 	struct ieee80211com *ic = ifp->if_l2com;
6790 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
6791 
6792 	iwn_stop(sc);
6793 	if (vap != NULL)
6794 		ieee80211_stop(vap);
6795 
6796 	/* Enable interrupts to get RF toggle notification. */
6797 	IWN_LOCK(sc);
6798 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
6799 	IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
6800 	IWN_UNLOCK(sc);
6801 }
6802 
6803 static void
6804 iwn_init_locked(struct iwn_softc *sc)
6805 {
6806 	struct ifnet *ifp = sc->sc_ifp;
6807 	int error;
6808 
6809 	IWN_LOCK_ASSERT(sc);
6810 
6811 	if ((error = iwn_hw_prepare(sc)) != 0) {
6812 		device_printf(sc->sc_dev, "%s: hardware not ready, error %d\n",
6813 		    __func__, error);
6814 		goto fail;
6815 	}
6816 
6817 	/* Initialize interrupt mask to default value. */
6818 	sc->int_mask = IWN_INT_MASK_DEF;
6819 	sc->sc_flags &= ~IWN_FLAG_USE_ICT;
6820 
6821 	/* Check that the radio is not disabled by hardware switch. */
6822 	if (!(IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_RFKILL)) {
6823 		device_printf(sc->sc_dev,
6824 		    "radio is disabled by hardware switch\n");
6825 		/* Enable interrupts to get RF toggle notifications. */
6826 		IWN_WRITE(sc, IWN_INT, 0xffffffff);
6827 		IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
6828 		return;
6829 	}
6830 
6831 	/* Read firmware images from the filesystem. */
6832 	if ((error = iwn_read_firmware(sc)) != 0) {
6833 		device_printf(sc->sc_dev,
6834 		    "%s: could not read firmware, error %d\n", __func__,
6835 		    error);
6836 		goto fail;
6837 	}
6838 
6839 	/* Initialize hardware and upload firmware. */
6840 	error = iwn_hw_init(sc);
6841 	firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
6842 	sc->fw_fp = NULL;
6843 	if (error != 0) {
6844 		device_printf(sc->sc_dev,
6845 		    "%s: could not initialize hardware, error %d\n", __func__,
6846 		    error);
6847 		goto fail;
6848 	}
6849 
6850 	/* Configure adapter now that it is ready. */
6851 	if ((error = iwn_config(sc)) != 0) {
6852 		device_printf(sc->sc_dev,
6853 		    "%s: could not configure device, error %d\n", __func__,
6854 		    error);
6855 		goto fail;
6856 	}
6857 
6858 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
6859 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
6860 
6861 	callout_reset(&sc->watchdog_to, hz, iwn_watchdog, sc);
6862 	return;
6863 
6864 fail:	iwn_stop_locked(sc);
6865 }
6866 
6867 static void
6868 iwn_init(void *arg)
6869 {
6870 	struct iwn_softc *sc = arg;
6871 	struct ifnet *ifp = sc->sc_ifp;
6872 	struct ieee80211com *ic = ifp->if_l2com;
6873 
6874 	IWN_LOCK(sc);
6875 	iwn_init_locked(sc);
6876 	IWN_UNLOCK(sc);
6877 
6878 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
6879 		ieee80211_start_all(ic);
6880 }
6881 
6882 static void
6883 iwn_stop_locked(struct iwn_softc *sc)
6884 {
6885 	struct ifnet *ifp = sc->sc_ifp;
6886 
6887 	IWN_LOCK_ASSERT(sc);
6888 
6889 	sc->sc_tx_timer = 0;
6890 	callout_stop(&sc->watchdog_to);
6891 	callout_stop(&sc->calib_to);
6892 	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
6893 
6894 	/* Power OFF hardware. */
6895 	iwn_hw_stop(sc);
6896 }
6897 
6898 static void
6899 iwn_stop(struct iwn_softc *sc)
6900 {
6901 	IWN_LOCK(sc);
6902 	iwn_stop_locked(sc);
6903 	IWN_UNLOCK(sc);
6904 }
6905 
6906 /*
6907  * Callback from net80211 to start a scan.
6908  */
6909 static void
6910 iwn_scan_start(struct ieee80211com *ic)
6911 {
6912 	struct ifnet *ifp = ic->ic_ifp;
6913 	struct iwn_softc *sc = ifp->if_softc;
6914 
6915 	IWN_LOCK(sc);
6916 	/* make the link LED blink while we're scanning */
6917 	iwn_set_led(sc, IWN_LED_LINK, 20, 2);
6918 	IWN_UNLOCK(sc);
6919 }
6920 
6921 /*
6922  * Callback from net80211 to terminate a scan.
6923  */
6924 static void
6925 iwn_scan_end(struct ieee80211com *ic)
6926 {
6927 	struct ifnet *ifp = ic->ic_ifp;
6928 	struct iwn_softc *sc = ifp->if_softc;
6929 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
6930 
6931 	IWN_LOCK(sc);
6932 	if (vap->iv_state == IEEE80211_S_RUN) {
6933 		/* Set link LED to ON status if we are associated */
6934 		iwn_set_led(sc, IWN_LED_LINK, 0, 1);
6935 	}
6936 	IWN_UNLOCK(sc);
6937 }
6938 
6939 /*
6940  * Callback from net80211 to force a channel change.
6941  */
6942 static void
6943 iwn_set_channel(struct ieee80211com *ic)
6944 {
6945 	const struct ieee80211_channel *c = ic->ic_curchan;
6946 	struct ifnet *ifp = ic->ic_ifp;
6947 	struct iwn_softc *sc = ifp->if_softc;
6948 
6949 	IWN_LOCK(sc);
6950 	sc->sc_rxtap.wr_chan_freq = htole16(c->ic_freq);
6951 	sc->sc_rxtap.wr_chan_flags = htole16(c->ic_flags);
6952 	sc->sc_txtap.wt_chan_freq = htole16(c->ic_freq);
6953 	sc->sc_txtap.wt_chan_flags = htole16(c->ic_flags);
6954 	IWN_UNLOCK(sc);
6955 }
6956 
6957 /*
6958  * Callback from net80211 to start scanning of the current channel.
6959  */
6960 static void
6961 iwn_scan_curchan(struct ieee80211_scan_state *ss, unsigned long maxdwell)
6962 {
6963 	struct ieee80211vap *vap = ss->ss_vap;
6964 	struct iwn_softc *sc = vap->iv_ic->ic_ifp->if_softc;
6965 	int error;
6966 
6967 	IWN_LOCK(sc);
6968 	error = iwn_scan(sc);
6969 	IWN_UNLOCK(sc);
6970 	if (error != 0)
6971 		ieee80211_cancel_scan(vap);
6972 }
6973 
6974 /*
6975  * Callback from net80211 to handle the minimum dwell time being met.
6976  * The intent is to terminate the scan but we just let the firmware
6977  * notify us when it's finished as we have no safe way to abort it.
6978  */
6979 static void
6980 iwn_scan_mindwell(struct ieee80211_scan_state *ss)
6981 {
6982 	/* NB: don't try to abort scan; wait for firmware to finish */
6983 }
6984 
6985 static void
6986 iwn_hw_reset(void *arg0, int pending)
6987 {
6988 	struct iwn_softc *sc = arg0;
6989 	struct ifnet *ifp = sc->sc_ifp;
6990 	struct ieee80211com *ic = ifp->if_l2com;
6991 
6992 	iwn_stop(sc);
6993 	iwn_init(sc);
6994 	ieee80211_notify_radio(ic, 1);
6995 }
6996