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