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