xref: /freebsd/sys/dev/iwn/if_iwn.c (revision 7750ad47a9a7dbc83f87158464170c8640723293)
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 #define nitems(_a)	(sizeof((_a)) / sizeof((_a)[0]))
2009 
2010 static void
2011 iwn_read_eeprom_enhinfo(struct iwn_softc *sc)
2012 {
2013 	struct iwn_eeprom_enhinfo enhinfo[35];
2014 	struct ifnet *ifp = sc->sc_ifp;
2015 	struct ieee80211com *ic = ifp->if_l2com;
2016 	struct ieee80211_channel *c;
2017 	uint16_t val, base;
2018 	int8_t maxpwr;
2019 	uint8_t flags;
2020 	int i, j;
2021 
2022 	iwn_read_prom_data(sc, IWN5000_EEPROM_REG, &val, 2);
2023 	base = le16toh(val);
2024 	iwn_read_prom_data(sc, base + IWN6000_EEPROM_ENHINFO,
2025 	    enhinfo, sizeof enhinfo);
2026 
2027 	for (i = 0; i < nitems(enhinfo); i++) {
2028 		flags = enhinfo[i].flags;
2029 		if (!(flags & IWN_ENHINFO_VALID))
2030 			continue;	/* Skip invalid entries. */
2031 
2032 		maxpwr = 0;
2033 		if (sc->txchainmask & IWN_ANT_A)
2034 			maxpwr = MAX(maxpwr, enhinfo[i].chain[0]);
2035 		if (sc->txchainmask & IWN_ANT_B)
2036 			maxpwr = MAX(maxpwr, enhinfo[i].chain[1]);
2037 		if (sc->txchainmask & IWN_ANT_C)
2038 			maxpwr = MAX(maxpwr, enhinfo[i].chain[2]);
2039 		if (sc->ntxchains == 2)
2040 			maxpwr = MAX(maxpwr, enhinfo[i].mimo2);
2041 		else if (sc->ntxchains == 3)
2042 			maxpwr = MAX(maxpwr, enhinfo[i].mimo3);
2043 
2044 		for (j = 0; j < ic->ic_nchans; j++) {
2045 			c = &ic->ic_channels[j];
2046 			if ((flags & IWN_ENHINFO_5GHZ)) {
2047 				if (!IEEE80211_IS_CHAN_A(c))
2048 					continue;
2049 			} else if ((flags & IWN_ENHINFO_OFDM)) {
2050 				if (!IEEE80211_IS_CHAN_G(c))
2051 					continue;
2052 			} else if (!IEEE80211_IS_CHAN_B(c))
2053 				continue;
2054 			if ((flags & IWN_ENHINFO_HT40)) {
2055 				if (!IEEE80211_IS_CHAN_HT40(c))
2056 					continue;
2057 			} else {
2058 				if (IEEE80211_IS_CHAN_HT40(c))
2059 					continue;
2060 			}
2061 			if (enhinfo[i].chan != 0 &&
2062 			    enhinfo[i].chan != c->ic_ieee)
2063 				continue;
2064 
2065 			DPRINTF(sc, IWN_DEBUG_RESET,
2066 			    "channel %d(%x), maxpwr %d\n", c->ic_ieee,
2067 			    c->ic_flags, maxpwr / 2);
2068 			c->ic_maxregpower = maxpwr / 2;
2069 			c->ic_maxpower = maxpwr;
2070 		}
2071 	}
2072 }
2073 
2074 static struct ieee80211_node *
2075 iwn_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
2076 {
2077 	return malloc(sizeof (struct iwn_node), M_80211_NODE,M_NOWAIT | M_ZERO);
2078 }
2079 
2080 static __inline int
2081 rate2plcp(int rate)
2082 {
2083 	switch (rate & 0xff) {
2084 	case 12:	return 0xd;
2085 	case 18:	return 0xf;
2086 	case 24:	return 0x5;
2087 	case 36:	return 0x7;
2088 	case 48:	return 0x9;
2089 	case 72:	return 0xb;
2090 	case 96:	return 0x1;
2091 	case 108:	return 0x3;
2092 	case 2:		return 10;
2093 	case 4:		return 20;
2094 	case 11:	return 55;
2095 	case 22:	return 110;
2096 	}
2097 	return 0;
2098 }
2099 
2100 static void
2101 iwn_newassoc(struct ieee80211_node *ni, int isnew)
2102 {
2103 #define	RV(v)	((v) & IEEE80211_RATE_VAL)
2104 	struct ieee80211com *ic = ni->ni_ic;
2105 	struct iwn_softc *sc = ic->ic_ifp->if_softc;
2106 	struct iwn_node *wn = (void *)ni;
2107 	uint8_t txant1, txant2;
2108 	int i, plcp, rate, ridx;
2109 
2110 	/* Use the first valid TX antenna. */
2111 	txant1 = IWN_LSB(sc->txchainmask);
2112 	txant2 = IWN_LSB(sc->txchainmask & ~txant1);
2113 
2114 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan)) {
2115 		ridx = ni->ni_rates.rs_nrates - 1;
2116 		for (i = ni->ni_htrates.rs_nrates - 1; i >= 0; i--) {
2117 			plcp = RV(ni->ni_htrates.rs_rates[i]) | IWN_RFLAG_MCS;
2118 			if (IEEE80211_IS_CHAN_HT40(ni->ni_chan)) {
2119 				plcp |= IWN_RFLAG_HT40;
2120 				if (ni->ni_htcap & IEEE80211_HTCAP_SHORTGI40)
2121 					plcp |= IWN_RFLAG_SGI;
2122 			} else if (ni->ni_htcap & IEEE80211_HTCAP_SHORTGI20)
2123 				plcp |= IWN_RFLAG_SGI;
2124 			if (RV(ni->ni_htrates.rs_rates[i]) > 7)
2125 				plcp |= IWN_RFLAG_ANT(txant1 | txant2);
2126 			else
2127 				plcp |= IWN_RFLAG_ANT(txant1);
2128 			if (ridx >= 0) {
2129 				rate = RV(ni->ni_rates.rs_rates[ridx]);
2130 				wn->ridx[rate] = plcp;
2131 			}
2132 			wn->ridx[IEEE80211_RATE_MCS | i] = plcp;
2133 			ridx--;
2134 		}
2135 	} else {
2136 		for (i = 0; i < ni->ni_rates.rs_nrates; i++) {
2137 			rate = RV(ni->ni_rates.rs_rates[i]);
2138 			plcp = rate2plcp(rate);
2139 			ridx = ic->ic_rt->rateCodeToIndex[rate];
2140 			if (ridx < IWN_RIDX_OFDM6 &&
2141 			    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
2142 				plcp |= IWN_RFLAG_CCK;
2143 			plcp |= IWN_RFLAG_ANT(txant1);
2144 			wn->ridx[rate] = htole32(plcp);
2145 		}
2146 	}
2147 #undef	RV
2148 }
2149 
2150 static int
2151 iwn_media_change(struct ifnet *ifp)
2152 {
2153 	int error;
2154 
2155 	error = ieee80211_media_change(ifp);
2156 	/* NB: only the fixed rate can change and that doesn't need a reset */
2157 	return (error == ENETRESET ? 0 : error);
2158 }
2159 
2160 static int
2161 iwn_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
2162 {
2163 	struct iwn_vap *ivp = IWN_VAP(vap);
2164 	struct ieee80211com *ic = vap->iv_ic;
2165 	struct iwn_softc *sc = ic->ic_ifp->if_softc;
2166 	int error = 0;
2167 
2168 	DPRINTF(sc, IWN_DEBUG_STATE, "%s: %s -> %s\n", __func__,
2169 	    ieee80211_state_name[vap->iv_state], ieee80211_state_name[nstate]);
2170 
2171 	IEEE80211_UNLOCK(ic);
2172 	IWN_LOCK(sc);
2173 	callout_stop(&sc->calib_to);
2174 
2175 	switch (nstate) {
2176 	case IEEE80211_S_ASSOC:
2177 		if (vap->iv_state != IEEE80211_S_RUN)
2178 			break;
2179 		/* FALLTHROUGH */
2180 	case IEEE80211_S_AUTH:
2181 		if (vap->iv_state == IEEE80211_S_AUTH)
2182 			break;
2183 
2184 		/*
2185 		 * !AUTH -> AUTH transition requires state reset to handle
2186 		 * reassociations correctly.
2187 		 */
2188 		sc->rxon.associd = 0;
2189 		sc->rxon.filter &= ~htole32(IWN_FILTER_BSS);
2190 		sc->calib.state = IWN_CALIB_STATE_INIT;
2191 
2192 		if ((error = iwn_auth(sc, vap)) != 0) {
2193 			device_printf(sc->sc_dev,
2194 			    "%s: could not move to auth state\n", __func__);
2195 		}
2196 		break;
2197 
2198 	case IEEE80211_S_RUN:
2199 		/*
2200 		 * RUN -> RUN transition; Just restart the timers.
2201 		 */
2202 		if (vap->iv_state == IEEE80211_S_RUN) {
2203 			sc->calib_cnt = 0;
2204 			break;
2205 		}
2206 
2207 		/*
2208 		 * !RUN -> RUN requires setting the association id
2209 		 * which is done with a firmware cmd.  We also defer
2210 		 * starting the timers until that work is done.
2211 		 */
2212 		if ((error = iwn_run(sc, vap)) != 0) {
2213 			device_printf(sc->sc_dev,
2214 			    "%s: could not move to run state\n", __func__);
2215 		}
2216 		break;
2217 
2218 	case IEEE80211_S_INIT:
2219 		sc->calib.state = IWN_CALIB_STATE_INIT;
2220 		break;
2221 
2222 	default:
2223 		break;
2224 	}
2225 	IWN_UNLOCK(sc);
2226 	IEEE80211_LOCK(ic);
2227 	if (error != 0)
2228 		return error;
2229 	return ivp->iv_newstate(vap, nstate, arg);
2230 }
2231 
2232 static void
2233 iwn_calib_timeout(void *arg)
2234 {
2235 	struct iwn_softc *sc = arg;
2236 
2237 	IWN_LOCK_ASSERT(sc);
2238 
2239 	/* Force automatic TX power calibration every 60 secs. */
2240 	if (++sc->calib_cnt >= 120) {
2241 		uint32_t flags = 0;
2242 
2243 		DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s\n",
2244 		    "sending request for statistics");
2245 		(void)iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags,
2246 		    sizeof flags, 1);
2247 		sc->calib_cnt = 0;
2248 	}
2249 	callout_reset(&sc->calib_to, msecs_to_ticks(500), iwn_calib_timeout,
2250 	    sc);
2251 }
2252 
2253 /*
2254  * Process an RX_PHY firmware notification.  This is usually immediately
2255  * followed by an MPDU_RX_DONE notification.
2256  */
2257 static void
2258 iwn_rx_phy(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2259     struct iwn_rx_data *data)
2260 {
2261 	struct iwn_rx_stat *stat = (struct iwn_rx_stat *)(desc + 1);
2262 
2263 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: received PHY stats\n", __func__);
2264 	bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
2265 
2266 	/* Save RX statistics, they will be used on MPDU_RX_DONE. */
2267 	memcpy(&sc->last_rx_stat, stat, sizeof (*stat));
2268 	sc->last_rx_valid = 1;
2269 }
2270 
2271 /*
2272  * Process an RX_DONE (4965AGN only) or MPDU_RX_DONE firmware notification.
2273  * Each MPDU_RX_DONE notification must be preceded by an RX_PHY one.
2274  */
2275 static void
2276 iwn_rx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2277     struct iwn_rx_data *data)
2278 {
2279 	struct iwn_ops *ops = &sc->ops;
2280 	struct ifnet *ifp = sc->sc_ifp;
2281 	struct ieee80211com *ic = ifp->if_l2com;
2282 	struct iwn_rx_ring *ring = &sc->rxq;
2283 	struct ieee80211_frame *wh;
2284 	struct ieee80211_node *ni;
2285 	struct mbuf *m, *m1;
2286 	struct iwn_rx_stat *stat;
2287 	caddr_t head;
2288 	bus_addr_t paddr;
2289 	uint32_t flags;
2290 	int error, len, rssi, nf;
2291 
2292 	if (desc->type == IWN_MPDU_RX_DONE) {
2293 		/* Check for prior RX_PHY notification. */
2294 		if (!sc->last_rx_valid) {
2295 			DPRINTF(sc, IWN_DEBUG_ANY,
2296 			    "%s: missing RX_PHY\n", __func__);
2297 			return;
2298 		}
2299 		stat = &sc->last_rx_stat;
2300 	} else
2301 		stat = (struct iwn_rx_stat *)(desc + 1);
2302 
2303 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD);
2304 
2305 	if (stat->cfg_phy_len > IWN_STAT_MAXLEN) {
2306 		device_printf(sc->sc_dev,
2307 		    "%s: invalid RX statistic header, len %d\n", __func__,
2308 		    stat->cfg_phy_len);
2309 		return;
2310 	}
2311 	if (desc->type == IWN_MPDU_RX_DONE) {
2312 		struct iwn_rx_mpdu *mpdu = (struct iwn_rx_mpdu *)(desc + 1);
2313 		head = (caddr_t)(mpdu + 1);
2314 		len = le16toh(mpdu->len);
2315 	} else {
2316 		head = (caddr_t)(stat + 1) + stat->cfg_phy_len;
2317 		len = le16toh(stat->len);
2318 	}
2319 
2320 	flags = le32toh(*(uint32_t *)(head + len));
2321 
2322 	/* Discard frames with a bad FCS early. */
2323 	if ((flags & IWN_RX_NOERROR) != IWN_RX_NOERROR) {
2324 		DPRINTF(sc, IWN_DEBUG_RECV, "%s: RX flags error %x\n",
2325 		    __func__, flags);
2326 		ifp->if_ierrors++;
2327 		return;
2328 	}
2329 	/* Discard frames that are too short. */
2330 	if (len < sizeof (*wh)) {
2331 		DPRINTF(sc, IWN_DEBUG_RECV, "%s: frame too short: %d\n",
2332 		    __func__, len);
2333 		ifp->if_ierrors++;
2334 		return;
2335 	}
2336 
2337 	m1 = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, IWN_RBUF_SIZE);
2338 	if (m1 == NULL) {
2339 		DPRINTF(sc, IWN_DEBUG_ANY, "%s: no mbuf to restock ring\n",
2340 		    __func__);
2341 		ifp->if_ierrors++;
2342 		return;
2343 	}
2344 	bus_dmamap_unload(ring->data_dmat, data->map);
2345 
2346 	error = bus_dmamap_load(ring->data_dmat, data->map, mtod(m1, void *),
2347 	    IWN_RBUF_SIZE, iwn_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
2348 	if (error != 0 && error != EFBIG) {
2349 		device_printf(sc->sc_dev,
2350 		    "%s: bus_dmamap_load failed, error %d\n", __func__, error);
2351 		m_freem(m1);
2352 
2353 		/* Try to reload the old mbuf. */
2354 		error = bus_dmamap_load(ring->data_dmat, data->map,
2355 		    mtod(data->m, void *), IWN_RBUF_SIZE, iwn_dma_map_addr,
2356 		    &paddr, BUS_DMA_NOWAIT);
2357 		if (error != 0 && error != EFBIG) {
2358 			panic("%s: could not load old RX mbuf", __func__);
2359 		}
2360 		/* Physical address may have changed. */
2361 		ring->desc[ring->cur] = htole32(paddr >> 8);
2362 		bus_dmamap_sync(ring->data_dmat, ring->desc_dma.map,
2363 		    BUS_DMASYNC_PREWRITE);
2364 		ifp->if_ierrors++;
2365 		return;
2366 	}
2367 
2368 	m = data->m;
2369 	data->m = m1;
2370 	/* Update RX descriptor. */
2371 	ring->desc[ring->cur] = htole32(paddr >> 8);
2372 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
2373 	    BUS_DMASYNC_PREWRITE);
2374 
2375 	/* Finalize mbuf. */
2376 	m->m_pkthdr.rcvif = ifp;
2377 	m->m_data = head;
2378 	m->m_pkthdr.len = m->m_len = len;
2379 
2380 	/* Grab a reference to the source node. */
2381 	wh = mtod(m, struct ieee80211_frame *);
2382 	ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
2383 	nf = (ni != NULL && ni->ni_vap->iv_state == IEEE80211_S_RUN &&
2384 	    (ic->ic_flags & IEEE80211_F_SCAN) == 0) ? sc->noise : -95;
2385 
2386 	rssi = ops->get_rssi(sc, stat);
2387 
2388 	if (ieee80211_radiotap_active(ic)) {
2389 		struct iwn_rx_radiotap_header *tap = &sc->sc_rxtap;
2390 
2391 		tap->wr_flags = 0;
2392 		if (stat->flags & htole16(IWN_STAT_FLAG_SHPREAMBLE))
2393 			tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
2394 		tap->wr_dbm_antsignal = (int8_t)rssi;
2395 		tap->wr_dbm_antnoise = (int8_t)nf;
2396 		tap->wr_tsft = stat->tstamp;
2397 		switch (stat->rate) {
2398 		/* CCK rates. */
2399 		case  10: tap->wr_rate =   2; break;
2400 		case  20: tap->wr_rate =   4; break;
2401 		case  55: tap->wr_rate =  11; break;
2402 		case 110: tap->wr_rate =  22; break;
2403 		/* OFDM rates. */
2404 		case 0xd: tap->wr_rate =  12; break;
2405 		case 0xf: tap->wr_rate =  18; break;
2406 		case 0x5: tap->wr_rate =  24; break;
2407 		case 0x7: tap->wr_rate =  36; break;
2408 		case 0x9: tap->wr_rate =  48; break;
2409 		case 0xb: tap->wr_rate =  72; break;
2410 		case 0x1: tap->wr_rate =  96; break;
2411 		case 0x3: tap->wr_rate = 108; break;
2412 		/* Unknown rate: should not happen. */
2413 		default:  tap->wr_rate =   0;
2414 		}
2415 	}
2416 
2417 	IWN_UNLOCK(sc);
2418 
2419 	/* Send the frame to the 802.11 layer. */
2420 	if (ni != NULL) {
2421 		if (ni->ni_flags & IEEE80211_NODE_HT)
2422 			m->m_flags |= M_AMPDU;
2423 		(void)ieee80211_input(ni, m, rssi - nf, nf);
2424 		/* Node is no longer needed. */
2425 		ieee80211_free_node(ni);
2426 	} else
2427 		(void)ieee80211_input_all(ic, m, rssi - nf, nf);
2428 
2429 	IWN_LOCK(sc);
2430 }
2431 
2432 /* Process an incoming Compressed BlockAck. */
2433 static void
2434 iwn_rx_compressed_ba(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2435     struct iwn_rx_data *data)
2436 {
2437 	struct ifnet *ifp = sc->sc_ifp;
2438 	struct iwn_node *wn;
2439 	struct ieee80211_node *ni;
2440 	struct iwn_compressed_ba *ba = (struct iwn_compressed_ba *)(desc + 1);
2441 	struct iwn_tx_ring *txq;
2442 	struct ieee80211_tx_ampdu *tap;
2443 	uint64_t bitmap;
2444 	uint8_t tid;
2445 	int ackfailcnt = 0, i, shift;
2446 
2447 	bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
2448 
2449 	txq = &sc->txq[le16toh(ba->qid)];
2450 	tap = sc->qid2tap[le16toh(ba->qid)];
2451 	tid = tap->txa_tid;
2452 	ni = tap->txa_ni;
2453 	wn = (void *)ni;
2454 
2455 	if (wn->agg[tid].bitmap == 0)
2456 		return;
2457 
2458 	shift = wn->agg[tid].startidx - ((le16toh(ba->seq) >> 4) & 0xff);
2459 	if (shift < 0)
2460 		shift += 0x100;
2461 
2462 	if (wn->agg[tid].nframes > (64 - shift))
2463 		return;
2464 
2465 	bitmap = (le64toh(ba->bitmap) >> shift) & wn->agg[tid].bitmap;
2466 	for (i = 0; bitmap; i++) {
2467 		if ((bitmap & 1) == 0) {
2468 			ifp->if_oerrors++;
2469 			ieee80211_ratectl_tx_complete(ni->ni_vap, ni,
2470 			    IEEE80211_RATECTL_TX_FAILURE, &ackfailcnt, NULL);
2471 		} else {
2472 			ifp->if_opackets++;
2473 			ieee80211_ratectl_tx_complete(ni->ni_vap, ni,
2474 			    IEEE80211_RATECTL_TX_SUCCESS, &ackfailcnt, NULL);
2475 		}
2476 		bitmap >>= 1;
2477 	}
2478 }
2479 
2480 /*
2481  * Process a CALIBRATION_RESULT notification sent by the initialization
2482  * firmware on response to a CMD_CALIB_CONFIG command (5000 only).
2483  */
2484 static void
2485 iwn5000_rx_calib_results(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2486     struct iwn_rx_data *data)
2487 {
2488 	struct iwn_phy_calib *calib = (struct iwn_phy_calib *)(desc + 1);
2489 	int len, idx = -1;
2490 
2491 	/* Runtime firmware should not send such a notification. */
2492 	if (sc->sc_flags & IWN_FLAG_CALIB_DONE)
2493 		return;
2494 
2495 	len = (le32toh(desc->len) & 0x3fff) - 4;
2496 	bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
2497 
2498 	switch (calib->code) {
2499 	case IWN5000_PHY_CALIB_DC:
2500 		if ((sc->sc_flags & IWN_FLAG_INTERNAL_PA) == 0 &&
2501 		    (sc->hw_type == IWN_HW_REV_TYPE_5150 ||
2502 		     sc->hw_type >= IWN_HW_REV_TYPE_6000) &&
2503 		     sc->hw_type != IWN_HW_REV_TYPE_6050)
2504 			idx = 0;
2505 		break;
2506 	case IWN5000_PHY_CALIB_LO:
2507 		idx = 1;
2508 		break;
2509 	case IWN5000_PHY_CALIB_TX_IQ:
2510 		idx = 2;
2511 		break;
2512 	case IWN5000_PHY_CALIB_TX_IQ_PERIODIC:
2513 		if (sc->hw_type < IWN_HW_REV_TYPE_6000 &&
2514 		    sc->hw_type != IWN_HW_REV_TYPE_5150)
2515 			idx = 3;
2516 		break;
2517 	case IWN5000_PHY_CALIB_BASE_BAND:
2518 		idx = 4;
2519 		break;
2520 	}
2521 	if (idx == -1)	/* Ignore other results. */
2522 		return;
2523 
2524 	/* Save calibration result. */
2525 	if (sc->calibcmd[idx].buf != NULL)
2526 		free(sc->calibcmd[idx].buf, M_DEVBUF);
2527 	sc->calibcmd[idx].buf = malloc(len, M_DEVBUF, M_NOWAIT);
2528 	if (sc->calibcmd[idx].buf == NULL) {
2529 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
2530 		    "not enough memory for calibration result %d\n",
2531 		    calib->code);
2532 		return;
2533 	}
2534 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
2535 	    "saving calibration result code=%d len=%d\n", calib->code, len);
2536 	sc->calibcmd[idx].len = len;
2537 	memcpy(sc->calibcmd[idx].buf, calib, len);
2538 }
2539 
2540 /*
2541  * Process an RX_STATISTICS or BEACON_STATISTICS firmware notification.
2542  * The latter is sent by the firmware after each received beacon.
2543  */
2544 static void
2545 iwn_rx_statistics(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2546     struct iwn_rx_data *data)
2547 {
2548 	struct iwn_ops *ops = &sc->ops;
2549 	struct ifnet *ifp = sc->sc_ifp;
2550 	struct ieee80211com *ic = ifp->if_l2com;
2551 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2552 	struct iwn_calib_state *calib = &sc->calib;
2553 	struct iwn_stats *stats = (struct iwn_stats *)(desc + 1);
2554 	int temp;
2555 
2556 	/* Ignore statistics received during a scan. */
2557 	if (vap->iv_state != IEEE80211_S_RUN ||
2558 	    (ic->ic_flags & IEEE80211_F_SCAN))
2559 		return;
2560 
2561 	bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
2562 
2563 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: received statistics, cmd %d\n",
2564 	    __func__, desc->type);
2565 	sc->calib_cnt = 0;	/* Reset TX power calibration timeout. */
2566 
2567 	/* Test if temperature has changed. */
2568 	if (stats->general.temp != sc->rawtemp) {
2569 		/* Convert "raw" temperature to degC. */
2570 		sc->rawtemp = stats->general.temp;
2571 		temp = ops->get_temperature(sc);
2572 		DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: temperature %d\n",
2573 		    __func__, temp);
2574 
2575 		/* Update TX power if need be (4965AGN only). */
2576 		if (sc->hw_type == IWN_HW_REV_TYPE_4965)
2577 			iwn4965_power_calibration(sc, temp);
2578 	}
2579 
2580 	if (desc->type != IWN_BEACON_STATISTICS)
2581 		return;	/* Reply to a statistics request. */
2582 
2583 	sc->noise = iwn_get_noise(&stats->rx.general);
2584 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: noise %d\n", __func__, sc->noise);
2585 
2586 	/* Test that RSSI and noise are present in stats report. */
2587 	if (le32toh(stats->rx.general.flags) != 1) {
2588 		DPRINTF(sc, IWN_DEBUG_ANY, "%s\n",
2589 		    "received statistics without RSSI");
2590 		return;
2591 	}
2592 
2593 	if (calib->state == IWN_CALIB_STATE_ASSOC)
2594 		iwn_collect_noise(sc, &stats->rx.general);
2595 	else if (calib->state == IWN_CALIB_STATE_RUN)
2596 		iwn_tune_sensitivity(sc, &stats->rx);
2597 }
2598 
2599 /*
2600  * Process a TX_DONE firmware notification.  Unfortunately, the 4965AGN
2601  * and 5000 adapters have different incompatible TX status formats.
2602  */
2603 static void
2604 iwn4965_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2605     struct iwn_rx_data *data)
2606 {
2607 	struct iwn4965_tx_stat *stat = (struct iwn4965_tx_stat *)(desc + 1);
2608 	struct iwn_tx_ring *ring;
2609 	int qid;
2610 
2611 	qid = desc->qid & 0xf;
2612 	ring = &sc->txq[qid];
2613 
2614 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: "
2615 	    "qid %d idx %d retries %d nkill %d rate %x duration %d status %x\n",
2616 	    __func__, desc->qid, desc->idx, stat->ackfailcnt,
2617 	    stat->btkillcnt, stat->rate, le16toh(stat->duration),
2618 	    le32toh(stat->status));
2619 
2620 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD);
2621 	if (qid >= sc->firstaggqueue) {
2622 		iwn_ampdu_tx_done(sc, qid, desc->idx, stat->nframes,
2623 		    &stat->status);
2624 	} else {
2625 		iwn_tx_done(sc, desc, stat->ackfailcnt,
2626 		    le32toh(stat->status) & 0xff);
2627 	}
2628 }
2629 
2630 static void
2631 iwn5000_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2632     struct iwn_rx_data *data)
2633 {
2634 	struct iwn5000_tx_stat *stat = (struct iwn5000_tx_stat *)(desc + 1);
2635 	struct iwn_tx_ring *ring;
2636 	int qid;
2637 
2638 	qid = desc->qid & 0xf;
2639 	ring = &sc->txq[qid];
2640 
2641 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: "
2642 	    "qid %d idx %d retries %d nkill %d rate %x duration %d status %x\n",
2643 	    __func__, desc->qid, desc->idx, stat->ackfailcnt,
2644 	    stat->btkillcnt, stat->rate, le16toh(stat->duration),
2645 	    le32toh(stat->status));
2646 
2647 #ifdef notyet
2648 	/* Reset TX scheduler slot. */
2649 	iwn5000_reset_sched(sc, desc->qid & 0xf, desc->idx);
2650 #endif
2651 
2652 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD);
2653 	if (qid >= sc->firstaggqueue) {
2654 		iwn_ampdu_tx_done(sc, qid, desc->idx, stat->nframes,
2655 		    &stat->status);
2656 	} else {
2657 		iwn_tx_done(sc, desc, stat->ackfailcnt,
2658 		    le16toh(stat->status) & 0xff);
2659 	}
2660 }
2661 
2662 /*
2663  * Adapter-independent backend for TX_DONE firmware notifications.
2664  */
2665 static void
2666 iwn_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc, int ackfailcnt,
2667     uint8_t status)
2668 {
2669 	struct ifnet *ifp = sc->sc_ifp;
2670 	struct iwn_tx_ring *ring = &sc->txq[desc->qid & 0xf];
2671 	struct iwn_tx_data *data = &ring->data[desc->idx];
2672 	struct mbuf *m;
2673 	struct ieee80211_node *ni;
2674 	struct ieee80211vap *vap;
2675 
2676 	KASSERT(data->ni != NULL, ("no node"));
2677 
2678 	/* Unmap and free mbuf. */
2679 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTWRITE);
2680 	bus_dmamap_unload(ring->data_dmat, data->map);
2681 	m = data->m, data->m = NULL;
2682 	ni = data->ni, data->ni = NULL;
2683 	vap = ni->ni_vap;
2684 
2685 	if (m->m_flags & M_TXCB) {
2686 		/*
2687 		 * Channels marked for "radar" require traffic to be received
2688 		 * to unlock before we can transmit.  Until traffic is seen
2689 		 * any attempt to transmit is returned immediately with status
2690 		 * set to IWN_TX_FAIL_TX_LOCKED.  Unfortunately this can easily
2691 		 * happen on first authenticate after scanning.  To workaround
2692 		 * this we ignore a failure of this sort in AUTH state so the
2693 		 * 802.11 layer will fall back to using a timeout to wait for
2694 		 * the AUTH reply.  This allows the firmware time to see
2695 		 * traffic so a subsequent retry of AUTH succeeds.  It's
2696 		 * unclear why the firmware does not maintain state for
2697 		 * channels recently visited as this would allow immediate
2698 		 * use of the channel after a scan (where we see traffic).
2699 		 */
2700 		if (status == IWN_TX_FAIL_TX_LOCKED &&
2701 		    ni->ni_vap->iv_state == IEEE80211_S_AUTH)
2702 			ieee80211_process_callback(ni, m, 0);
2703 		else
2704 			ieee80211_process_callback(ni, m,
2705 			    (status & IWN_TX_FAIL) != 0);
2706 	}
2707 
2708 	/*
2709 	 * Update rate control statistics for the node.
2710 	 */
2711 	if (status & IWN_TX_FAIL) {
2712 		ifp->if_oerrors++;
2713 		ieee80211_ratectl_tx_complete(vap, ni,
2714 		    IEEE80211_RATECTL_TX_FAILURE, &ackfailcnt, NULL);
2715 	} else {
2716 		ifp->if_opackets++;
2717 		ieee80211_ratectl_tx_complete(vap, ni,
2718 		    IEEE80211_RATECTL_TX_SUCCESS, &ackfailcnt, NULL);
2719 	}
2720 	m_freem(m);
2721 	ieee80211_free_node(ni);
2722 
2723 	sc->sc_tx_timer = 0;
2724 	if (--ring->queued < IWN_TX_RING_LOMARK) {
2725 		sc->qfullmsk &= ~(1 << ring->qid);
2726 		if (sc->qfullmsk == 0 &&
2727 		    (ifp->if_drv_flags & IFF_DRV_OACTIVE)) {
2728 			ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2729 			iwn_start_locked(ifp);
2730 		}
2731 	}
2732 }
2733 
2734 /*
2735  * Process a "command done" firmware notification.  This is where we wakeup
2736  * processes waiting for a synchronous command completion.
2737  */
2738 static void
2739 iwn_cmd_done(struct iwn_softc *sc, struct iwn_rx_desc *desc)
2740 {
2741 	struct iwn_tx_ring *ring = &sc->txq[4];
2742 	struct iwn_tx_data *data;
2743 
2744 	if ((desc->qid & 0xf) != 4)
2745 		return;	/* Not a command ack. */
2746 
2747 	data = &ring->data[desc->idx];
2748 
2749 	/* If the command was mapped in an mbuf, free it. */
2750 	if (data->m != NULL) {
2751 		bus_dmamap_sync(ring->data_dmat, data->map,
2752 		    BUS_DMASYNC_POSTWRITE);
2753 		bus_dmamap_unload(ring->data_dmat, data->map);
2754 		m_freem(data->m);
2755 		data->m = NULL;
2756 	}
2757 	wakeup(&ring->desc[desc->idx]);
2758 }
2759 
2760 static void
2761 iwn_ampdu_tx_done(struct iwn_softc *sc, int qid, int idx, int nframes,
2762     void *stat)
2763 {
2764 	struct ifnet *ifp = sc->sc_ifp;
2765 	struct iwn_tx_ring *ring = &sc->txq[qid];
2766 	struct iwn_tx_data *data;
2767 	struct mbuf *m;
2768 	struct iwn_node *wn;
2769 	struct ieee80211_node *ni;
2770 	struct ieee80211_tx_ampdu *tap;
2771 	uint64_t bitmap;
2772 	uint32_t *status = stat;
2773 	uint16_t *aggstatus = stat;
2774 	uint8_t tid;
2775 	int bit, i, lastidx, seqno, shift, start;
2776 
2777 #ifdef NOT_YET
2778 	if (nframes == 1) {
2779 		if ((*status & 0xff) != 1 && (*status & 0xff) != 2)
2780 			printf("ieee80211_send_bar()\n");
2781 	}
2782 #endif
2783 
2784 	bitmap = 0;
2785 	start = idx;
2786 	for (i = 0; i < nframes; i++) {
2787 		if (le16toh(aggstatus[i * 2]) & 0xc)
2788 			continue;
2789 
2790 		idx = le16toh(aggstatus[2*i + 1]) & 0xff;
2791 		bit = idx - start;
2792 		shift = 0;
2793 		if (bit >= 64) {
2794 			shift = 0x100 - idx + start;
2795 			bit = 0;
2796 			start = idx;
2797 		} else if (bit <= -64)
2798 			bit = 0x100 - start + idx;
2799 		else if (bit < 0) {
2800 			shift = start - idx;
2801 			start = idx;
2802 			bit = 0;
2803 		}
2804 		bitmap = bitmap << shift;
2805 		bitmap |= 1ULL << bit;
2806 	}
2807 	tap = sc->qid2tap[qid];
2808 	if (tap != NULL) {
2809 		tid = tap->txa_tid;
2810 		wn = (void *)tap->txa_ni;
2811 		wn->agg[tid].bitmap = bitmap;
2812 		wn->agg[tid].startidx = start;
2813 		wn->agg[tid].nframes = nframes;
2814 	}
2815 
2816 	seqno = le32toh(*(status + nframes)) & 0xfff;
2817 	for (lastidx = (seqno & 0xff); ring->read != lastidx;) {
2818 		data = &ring->data[ring->read];
2819 
2820 		KASSERT(data->ni != NULL, ("no node"));
2821 
2822 		/* Unmap and free mbuf. */
2823 		bus_dmamap_sync(ring->data_dmat, data->map,
2824 		    BUS_DMASYNC_POSTWRITE);
2825 		bus_dmamap_unload(ring->data_dmat, data->map);
2826 		m = data->m, data->m = NULL;
2827 		ni = data->ni, data->ni = NULL;
2828 
2829 		if (m->m_flags & M_TXCB)
2830 			ieee80211_process_callback(ni, m, 1);
2831 
2832 		m_freem(m);
2833 		ieee80211_free_node(ni);
2834 
2835 		ring->queued--;
2836 		ring->read = (ring->read + 1) % IWN_TX_RING_COUNT;
2837 	}
2838 
2839 	sc->sc_tx_timer = 0;
2840 	if (ring->queued < IWN_TX_RING_LOMARK) {
2841 		sc->qfullmsk &= ~(1 << ring->qid);
2842 		if (sc->qfullmsk == 0 &&
2843 		    (ifp->if_drv_flags & IFF_DRV_OACTIVE)) {
2844 			ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2845 			iwn_start_locked(ifp);
2846 		}
2847 	}
2848 }
2849 
2850 /*
2851  * Process an INT_FH_RX or INT_SW_RX interrupt.
2852  */
2853 static void
2854 iwn_notif_intr(struct iwn_softc *sc)
2855 {
2856 	struct iwn_ops *ops = &sc->ops;
2857 	struct ifnet *ifp = sc->sc_ifp;
2858 	struct ieee80211com *ic = ifp->if_l2com;
2859 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2860 	uint16_t hw;
2861 
2862 	bus_dmamap_sync(sc->rxq.stat_dma.tag, sc->rxq.stat_dma.map,
2863 	    BUS_DMASYNC_POSTREAD);
2864 
2865 	hw = le16toh(sc->rxq.stat->closed_count) & 0xfff;
2866 	while (sc->rxq.cur != hw) {
2867 		struct iwn_rx_data *data = &sc->rxq.data[sc->rxq.cur];
2868 		struct iwn_rx_desc *desc;
2869 
2870 		bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2871 		    BUS_DMASYNC_POSTREAD);
2872 		desc = mtod(data->m, struct iwn_rx_desc *);
2873 
2874 		DPRINTF(sc, IWN_DEBUG_RECV,
2875 		    "%s: qid %x idx %d flags %x type %d(%s) len %d\n",
2876 		    __func__, desc->qid & 0xf, desc->idx, desc->flags,
2877 		    desc->type, iwn_intr_str(desc->type),
2878 		    le16toh(desc->len));
2879 
2880 		if (!(desc->qid & 0x80))	/* Reply to a command. */
2881 			iwn_cmd_done(sc, desc);
2882 
2883 		switch (desc->type) {
2884 		case IWN_RX_PHY:
2885 			iwn_rx_phy(sc, desc, data);
2886 			break;
2887 
2888 		case IWN_RX_DONE:		/* 4965AGN only. */
2889 		case IWN_MPDU_RX_DONE:
2890 			/* An 802.11 frame has been received. */
2891 			iwn_rx_done(sc, desc, data);
2892 			break;
2893 
2894 		case IWN_RX_COMPRESSED_BA:
2895 			/* A Compressed BlockAck has been received. */
2896 			iwn_rx_compressed_ba(sc, desc, data);
2897 			break;
2898 
2899 		case IWN_TX_DONE:
2900 			/* An 802.11 frame has been transmitted. */
2901 			ops->tx_done(sc, desc, data);
2902 			break;
2903 
2904 		case IWN_RX_STATISTICS:
2905 		case IWN_BEACON_STATISTICS:
2906 			iwn_rx_statistics(sc, desc, data);
2907 			break;
2908 
2909 		case IWN_BEACON_MISSED:
2910 		{
2911 			struct iwn_beacon_missed *miss =
2912 			    (struct iwn_beacon_missed *)(desc + 1);
2913 			int misses;
2914 
2915 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2916 			    BUS_DMASYNC_POSTREAD);
2917 			misses = le32toh(miss->consecutive);
2918 
2919 			DPRINTF(sc, IWN_DEBUG_STATE,
2920 			    "%s: beacons missed %d/%d\n", __func__,
2921 			    misses, le32toh(miss->total));
2922 			/*
2923 			 * If more than 5 consecutive beacons are missed,
2924 			 * reinitialize the sensitivity state machine.
2925 			 */
2926 			if (vap->iv_state == IEEE80211_S_RUN &&
2927 			    (ic->ic_flags & IEEE80211_F_SCAN) == 0) {
2928 				if (misses > 5)
2929 					(void)iwn_init_sensitivity(sc);
2930 				if (misses >= vap->iv_bmissthreshold) {
2931 					IWN_UNLOCK(sc);
2932 					ieee80211_beacon_miss(ic);
2933 					IWN_LOCK(sc);
2934 				}
2935 			}
2936 			break;
2937 		}
2938 		case IWN_UC_READY:
2939 		{
2940 			struct iwn_ucode_info *uc =
2941 			    (struct iwn_ucode_info *)(desc + 1);
2942 
2943 			/* The microcontroller is ready. */
2944 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2945 			    BUS_DMASYNC_POSTREAD);
2946 			DPRINTF(sc, IWN_DEBUG_RESET,
2947 			    "microcode alive notification version=%d.%d "
2948 			    "subtype=%x alive=%x\n", uc->major, uc->minor,
2949 			    uc->subtype, le32toh(uc->valid));
2950 
2951 			if (le32toh(uc->valid) != 1) {
2952 				device_printf(sc->sc_dev,
2953 				    "microcontroller initialization failed");
2954 				break;
2955 			}
2956 			if (uc->subtype == IWN_UCODE_INIT) {
2957 				/* Save microcontroller report. */
2958 				memcpy(&sc->ucode_info, uc, sizeof (*uc));
2959 			}
2960 			/* Save the address of the error log in SRAM. */
2961 			sc->errptr = le32toh(uc->errptr);
2962 			break;
2963 		}
2964 		case IWN_STATE_CHANGED:
2965 		{
2966 			uint32_t *status = (uint32_t *)(desc + 1);
2967 
2968 			/*
2969 			 * State change allows hardware switch change to be
2970 			 * noted. However, we handle this in iwn_intr as we
2971 			 * get both the enable/disble intr.
2972 			 */
2973 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2974 			    BUS_DMASYNC_POSTREAD);
2975 			DPRINTF(sc, IWN_DEBUG_INTR, "state changed to %x\n",
2976 			    le32toh(*status));
2977 			break;
2978 		}
2979 		case IWN_START_SCAN:
2980 		{
2981 			struct iwn_start_scan *scan =
2982 			    (struct iwn_start_scan *)(desc + 1);
2983 
2984 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2985 			    BUS_DMASYNC_POSTREAD);
2986 			DPRINTF(sc, IWN_DEBUG_ANY,
2987 			    "%s: scanning channel %d status %x\n",
2988 			    __func__, scan->chan, le32toh(scan->status));
2989 			break;
2990 		}
2991 		case IWN_STOP_SCAN:
2992 		{
2993 			struct iwn_stop_scan *scan =
2994 			    (struct iwn_stop_scan *)(desc + 1);
2995 
2996 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2997 			    BUS_DMASYNC_POSTREAD);
2998 			DPRINTF(sc, IWN_DEBUG_STATE,
2999 			    "scan finished nchan=%d status=%d chan=%d\n",
3000 			    scan->nchan, scan->status, scan->chan);
3001 
3002 			IWN_UNLOCK(sc);
3003 			ieee80211_scan_next(vap);
3004 			IWN_LOCK(sc);
3005 			break;
3006 		}
3007 		case IWN5000_CALIBRATION_RESULT:
3008 			iwn5000_rx_calib_results(sc, desc, data);
3009 			break;
3010 
3011 		case IWN5000_CALIBRATION_DONE:
3012 			sc->sc_flags |= IWN_FLAG_CALIB_DONE;
3013 			wakeup(sc);
3014 			break;
3015 		}
3016 
3017 		sc->rxq.cur = (sc->rxq.cur + 1) % IWN_RX_RING_COUNT;
3018 	}
3019 
3020 	/* Tell the firmware what we have processed. */
3021 	hw = (hw == 0) ? IWN_RX_RING_COUNT - 1 : hw - 1;
3022 	IWN_WRITE(sc, IWN_FH_RX_WPTR, hw & ~7);
3023 }
3024 
3025 /*
3026  * Process an INT_WAKEUP interrupt raised when the microcontroller wakes up
3027  * from power-down sleep mode.
3028  */
3029 static void
3030 iwn_wakeup_intr(struct iwn_softc *sc)
3031 {
3032 	int qid;
3033 
3034 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: ucode wakeup from power-down sleep\n",
3035 	    __func__);
3036 
3037 	/* Wakeup RX and TX rings. */
3038 	IWN_WRITE(sc, IWN_FH_RX_WPTR, sc->rxq.cur & ~7);
3039 	for (qid = 0; qid < sc->ntxqs; qid++) {
3040 		struct iwn_tx_ring *ring = &sc->txq[qid];
3041 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | ring->cur);
3042 	}
3043 }
3044 
3045 static void
3046 iwn_rftoggle_intr(struct iwn_softc *sc)
3047 {
3048 	struct ifnet *ifp = sc->sc_ifp;
3049 	struct ieee80211com *ic = ifp->if_l2com;
3050 	uint32_t tmp = IWN_READ(sc, IWN_GP_CNTRL);
3051 
3052 	IWN_LOCK_ASSERT(sc);
3053 
3054 	device_printf(sc->sc_dev, "RF switch: radio %s\n",
3055 	    (tmp & IWN_GP_CNTRL_RFKILL) ? "enabled" : "disabled");
3056 	if (tmp & IWN_GP_CNTRL_RFKILL)
3057 		ieee80211_runtask(ic, &sc->sc_radioon_task);
3058 	else
3059 		ieee80211_runtask(ic, &sc->sc_radiooff_task);
3060 }
3061 
3062 /*
3063  * Dump the error log of the firmware when a firmware panic occurs.  Although
3064  * we can't debug the firmware because it is neither open source nor free, it
3065  * can help us to identify certain classes of problems.
3066  */
3067 static void
3068 iwn_fatal_intr(struct iwn_softc *sc)
3069 {
3070 	struct iwn_fw_dump dump;
3071 	int i;
3072 
3073 	IWN_LOCK_ASSERT(sc);
3074 
3075 	/* Force a complete recalibration on next init. */
3076 	sc->sc_flags &= ~IWN_FLAG_CALIB_DONE;
3077 
3078 	/* Check that the error log address is valid. */
3079 	if (sc->errptr < IWN_FW_DATA_BASE ||
3080 	    sc->errptr + sizeof (dump) >
3081 	    IWN_FW_DATA_BASE + sc->fw_data_maxsz) {
3082 		printf("%s: bad firmware error log address 0x%08x\n", __func__,
3083 		    sc->errptr);
3084 		return;
3085 	}
3086 	if (iwn_nic_lock(sc) != 0) {
3087 		printf("%s: could not read firmware error log\n", __func__);
3088 		return;
3089 	}
3090 	/* Read firmware error log from SRAM. */
3091 	iwn_mem_read_region_4(sc, sc->errptr, (uint32_t *)&dump,
3092 	    sizeof (dump) / sizeof (uint32_t));
3093 	iwn_nic_unlock(sc);
3094 
3095 	if (dump.valid == 0) {
3096 		printf("%s: firmware error log is empty\n", __func__);
3097 		return;
3098 	}
3099 	printf("firmware error log:\n");
3100 	printf("  error type      = \"%s\" (0x%08X)\n",
3101 	    (dump.id < nitems(iwn_fw_errmsg)) ?
3102 		iwn_fw_errmsg[dump.id] : "UNKNOWN",
3103 	    dump.id);
3104 	printf("  program counter = 0x%08X\n", dump.pc);
3105 	printf("  source line     = 0x%08X\n", dump.src_line);
3106 	printf("  error data      = 0x%08X%08X\n",
3107 	    dump.error_data[0], dump.error_data[1]);
3108 	printf("  branch link     = 0x%08X%08X\n",
3109 	    dump.branch_link[0], dump.branch_link[1]);
3110 	printf("  interrupt link  = 0x%08X%08X\n",
3111 	    dump.interrupt_link[0], dump.interrupt_link[1]);
3112 	printf("  time            = %u\n", dump.time[0]);
3113 
3114 	/* Dump driver status (TX and RX rings) while we're here. */
3115 	printf("driver status:\n");
3116 	for (i = 0; i < sc->ntxqs; i++) {
3117 		struct iwn_tx_ring *ring = &sc->txq[i];
3118 		printf("  tx ring %2d: qid=%-2d cur=%-3d queued=%-3d\n",
3119 		    i, ring->qid, ring->cur, ring->queued);
3120 	}
3121 	printf("  rx ring: cur=%d\n", sc->rxq.cur);
3122 }
3123 
3124 static void
3125 iwn_intr(void *arg)
3126 {
3127 	struct iwn_softc *sc = arg;
3128 	struct ifnet *ifp = sc->sc_ifp;
3129 	uint32_t r1, r2, tmp;
3130 
3131 	IWN_LOCK(sc);
3132 
3133 	/* Disable interrupts. */
3134 	IWN_WRITE(sc, IWN_INT_MASK, 0);
3135 
3136 	/* Read interrupts from ICT (fast) or from registers (slow). */
3137 	if (sc->sc_flags & IWN_FLAG_USE_ICT) {
3138 		tmp = 0;
3139 		while (sc->ict[sc->ict_cur] != 0) {
3140 			tmp |= sc->ict[sc->ict_cur];
3141 			sc->ict[sc->ict_cur] = 0;	/* Acknowledge. */
3142 			sc->ict_cur = (sc->ict_cur + 1) % IWN_ICT_COUNT;
3143 		}
3144 		tmp = le32toh(tmp);
3145 		if (tmp == 0xffffffff)	/* Shouldn't happen. */
3146 			tmp = 0;
3147 		else if (tmp & 0xc0000)	/* Workaround a HW bug. */
3148 			tmp |= 0x8000;
3149 		r1 = (tmp & 0xff00) << 16 | (tmp & 0xff);
3150 		r2 = 0;	/* Unused. */
3151 	} else {
3152 		r1 = IWN_READ(sc, IWN_INT);
3153 		if (r1 == 0xffffffff || (r1 & 0xfffffff0) == 0xa5a5a5a0)
3154 			return;	/* Hardware gone! */
3155 		r2 = IWN_READ(sc, IWN_FH_INT);
3156 	}
3157 
3158 	DPRINTF(sc, IWN_DEBUG_INTR, "interrupt reg1=%x reg2=%x\n", r1, r2);
3159 
3160 	if (r1 == 0 && r2 == 0)
3161 		goto done;	/* Interrupt not for us. */
3162 
3163 	/* Acknowledge interrupts. */
3164 	IWN_WRITE(sc, IWN_INT, r1);
3165 	if (!(sc->sc_flags & IWN_FLAG_USE_ICT))
3166 		IWN_WRITE(sc, IWN_FH_INT, r2);
3167 
3168 	if (r1 & IWN_INT_RF_TOGGLED) {
3169 		iwn_rftoggle_intr(sc);
3170 		goto done;
3171 	}
3172 	if (r1 & IWN_INT_CT_REACHED) {
3173 		device_printf(sc->sc_dev, "%s: critical temperature reached!\n",
3174 		    __func__);
3175 	}
3176 	if (r1 & (IWN_INT_SW_ERR | IWN_INT_HW_ERR)) {
3177 		device_printf(sc->sc_dev, "%s: fatal firmware error\n",
3178 		    __func__);
3179 		/* Dump firmware error log and stop. */
3180 		iwn_fatal_intr(sc);
3181 		ifp->if_flags &= ~IFF_UP;
3182 		iwn_stop_locked(sc);
3183 		goto done;
3184 	}
3185 	if ((r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX | IWN_INT_RX_PERIODIC)) ||
3186 	    (r2 & IWN_FH_INT_RX)) {
3187 		if (sc->sc_flags & IWN_FLAG_USE_ICT) {
3188 			if (r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX))
3189 				IWN_WRITE(sc, IWN_FH_INT, IWN_FH_INT_RX);
3190 			IWN_WRITE_1(sc, IWN_INT_PERIODIC,
3191 			    IWN_INT_PERIODIC_DIS);
3192 			iwn_notif_intr(sc);
3193 			if (r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX)) {
3194 				IWN_WRITE_1(sc, IWN_INT_PERIODIC,
3195 				    IWN_INT_PERIODIC_ENA);
3196 			}
3197 		} else
3198 			iwn_notif_intr(sc);
3199 	}
3200 
3201 	if ((r1 & IWN_INT_FH_TX) || (r2 & IWN_FH_INT_TX)) {
3202 		if (sc->sc_flags & IWN_FLAG_USE_ICT)
3203 			IWN_WRITE(sc, IWN_FH_INT, IWN_FH_INT_TX);
3204 		wakeup(sc);	/* FH DMA transfer completed. */
3205 	}
3206 
3207 	if (r1 & IWN_INT_ALIVE)
3208 		wakeup(sc);	/* Firmware is alive. */
3209 
3210 	if (r1 & IWN_INT_WAKEUP)
3211 		iwn_wakeup_intr(sc);
3212 
3213 done:
3214 	/* Re-enable interrupts. */
3215 	if (ifp->if_flags & IFF_UP)
3216 		IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
3217 
3218 	IWN_UNLOCK(sc);
3219 }
3220 
3221 /*
3222  * Update TX scheduler ring when transmitting an 802.11 frame (4965AGN and
3223  * 5000 adapters use a slightly different format).
3224  */
3225 static void
3226 iwn4965_update_sched(struct iwn_softc *sc, int qid, int idx, uint8_t id,
3227     uint16_t len)
3228 {
3229 	uint16_t *w = &sc->sched[qid * IWN4965_SCHED_COUNT + idx];
3230 
3231 	*w = htole16(len + 8);
3232 	bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
3233 	    BUS_DMASYNC_PREWRITE);
3234 	if (idx < IWN_SCHED_WINSZ) {
3235 		*(w + IWN_TX_RING_COUNT) = *w;
3236 		bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
3237 		    BUS_DMASYNC_PREWRITE);
3238 	}
3239 }
3240 
3241 static void
3242 iwn5000_update_sched(struct iwn_softc *sc, int qid, int idx, uint8_t id,
3243     uint16_t len)
3244 {
3245 	uint16_t *w = &sc->sched[qid * IWN5000_SCHED_COUNT + idx];
3246 
3247 	*w = htole16(id << 12 | (len + 8));
3248 	bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
3249 	    BUS_DMASYNC_PREWRITE);
3250 	if (idx < IWN_SCHED_WINSZ) {
3251 		*(w + IWN_TX_RING_COUNT) = *w;
3252 		bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
3253 		    BUS_DMASYNC_PREWRITE);
3254 	}
3255 }
3256 
3257 #ifdef notyet
3258 static void
3259 iwn5000_reset_sched(struct iwn_softc *sc, int qid, int idx)
3260 {
3261 	uint16_t *w = &sc->sched[qid * IWN5000_SCHED_COUNT + idx];
3262 
3263 	*w = (*w & htole16(0xf000)) | htole16(1);
3264 	bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
3265 	    BUS_DMASYNC_PREWRITE);
3266 	if (idx < IWN_SCHED_WINSZ) {
3267 		*(w + IWN_TX_RING_COUNT) = *w;
3268 		bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
3269 		    BUS_DMASYNC_PREWRITE);
3270 	}
3271 }
3272 #endif
3273 
3274 static int
3275 iwn_tx_data(struct iwn_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
3276 {
3277 	struct iwn_ops *ops = &sc->ops;
3278 	const struct ieee80211_txparam *tp;
3279 	struct ieee80211vap *vap = ni->ni_vap;
3280 	struct ieee80211com *ic = ni->ni_ic;
3281 	struct iwn_node *wn = (void *)ni;
3282 	struct iwn_tx_ring *ring;
3283 	struct iwn_tx_desc *desc;
3284 	struct iwn_tx_data *data;
3285 	struct iwn_tx_cmd *cmd;
3286 	struct iwn_cmd_data *tx;
3287 	struct ieee80211_frame *wh;
3288 	struct ieee80211_key *k = NULL;
3289 	struct mbuf *m1;
3290 	uint32_t flags;
3291 	uint16_t qos;
3292 	u_int hdrlen;
3293 	bus_dma_segment_t *seg, segs[IWN_MAX_SCATTER];
3294 	uint8_t tid, ridx, txant, type;
3295 	int ac, i, totlen, error, pad, nsegs = 0, rate;
3296 
3297 	IWN_LOCK_ASSERT(sc);
3298 
3299 	wh = mtod(m, struct ieee80211_frame *);
3300 	hdrlen = ieee80211_anyhdrsize(wh);
3301 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
3302 
3303 	/* Select EDCA Access Category and TX ring for this frame. */
3304 	if (IEEE80211_QOS_HAS_SEQ(wh)) {
3305 		qos = ((const struct ieee80211_qosframe *)wh)->i_qos[0];
3306 		tid = qos & IEEE80211_QOS_TID;
3307 	} else {
3308 		qos = 0;
3309 		tid = 0;
3310 	}
3311 	ac = M_WME_GETAC(m);
3312 	if (m->m_flags & M_AMPDU_MPDU) {
3313 		struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[ac];
3314 
3315 		if (!IEEE80211_AMPDU_RUNNING(tap)) {
3316 			m_freem(m);
3317 			return EINVAL;
3318 		}
3319 
3320 		ac = *(int *)tap->txa_private;
3321 		*(uint16_t *)wh->i_seq =
3322 		    htole16(ni->ni_txseqs[tid] << IEEE80211_SEQ_SEQ_SHIFT);
3323 		ni->ni_txseqs[tid]++;
3324 	}
3325 	ring = &sc->txq[ac];
3326 	desc = &ring->desc[ring->cur];
3327 	data = &ring->data[ring->cur];
3328 
3329 	/* Choose a TX rate index. */
3330 	tp = &vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)];
3331 	if (type == IEEE80211_FC0_TYPE_MGT)
3332 		rate = tp->mgmtrate;
3333 	else if (IEEE80211_IS_MULTICAST(wh->i_addr1))
3334 		rate = tp->mcastrate;
3335 	else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
3336 		rate = tp->ucastrate;
3337 	else {
3338 		/* XXX pass pktlen */
3339 		(void) ieee80211_ratectl_rate(ni, NULL, 0);
3340 		rate = ni->ni_txrate;
3341 	}
3342 	ridx = ic->ic_rt->rateCodeToIndex[rate];
3343 
3344 	/* Encrypt the frame if need be. */
3345 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
3346 		/* Retrieve key for TX. */
3347 		k = ieee80211_crypto_encap(ni, m);
3348 		if (k == NULL) {
3349 			m_freem(m);
3350 			return ENOBUFS;
3351 		}
3352 		/* 802.11 header may have moved. */
3353 		wh = mtod(m, struct ieee80211_frame *);
3354 	}
3355 	totlen = m->m_pkthdr.len;
3356 
3357 	if (ieee80211_radiotap_active_vap(vap)) {
3358 		struct iwn_tx_radiotap_header *tap = &sc->sc_txtap;
3359 
3360 		tap->wt_flags = 0;
3361 		tap->wt_rate = rate;
3362 		if (k != NULL)
3363 			tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
3364 
3365 		ieee80211_radiotap_tx(vap, m);
3366 	}
3367 
3368 	/* Prepare TX firmware command. */
3369 	cmd = &ring->cmd[ring->cur];
3370 	cmd->code = IWN_CMD_TX_DATA;
3371 	cmd->flags = 0;
3372 	cmd->qid = ring->qid;
3373 	cmd->idx = ring->cur;
3374 
3375 	tx = (struct iwn_cmd_data *)cmd->data;
3376 	/* NB: No need to clear tx, all fields are reinitialized here. */
3377 	tx->scratch = 0;	/* clear "scratch" area */
3378 
3379 	flags = 0;
3380 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
3381 		/* Unicast frame, check if an ACK is expected. */
3382 		if (!qos || (qos & IEEE80211_QOS_ACKPOLICY) !=
3383 		    IEEE80211_QOS_ACKPOLICY_NOACK)
3384 			flags |= IWN_TX_NEED_ACK;
3385 	}
3386 	if ((wh->i_fc[0] &
3387 	    (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
3388 	    (IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_BAR))
3389 		flags |= IWN_TX_IMM_BA;		/* Cannot happen yet. */
3390 
3391 	if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG)
3392 		flags |= IWN_TX_MORE_FRAG;	/* Cannot happen yet. */
3393 
3394 	/* Check if frame must be protected using RTS/CTS or CTS-to-self. */
3395 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
3396 		/* NB: Group frames are sent using CCK in 802.11b/g. */
3397 		if (totlen + IEEE80211_CRC_LEN > vap->iv_rtsthreshold) {
3398 			flags |= IWN_TX_NEED_RTS;
3399 		} else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
3400 		    ridx >= IWN_RIDX_OFDM6) {
3401 			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
3402 				flags |= IWN_TX_NEED_CTS;
3403 			else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
3404 				flags |= IWN_TX_NEED_RTS;
3405 		}
3406 		if (flags & (IWN_TX_NEED_RTS | IWN_TX_NEED_CTS)) {
3407 			if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
3408 				/* 5000 autoselects RTS/CTS or CTS-to-self. */
3409 				flags &= ~(IWN_TX_NEED_RTS | IWN_TX_NEED_CTS);
3410 				flags |= IWN_TX_NEED_PROTECTION;
3411 			} else
3412 				flags |= IWN_TX_FULL_TXOP;
3413 		}
3414 	}
3415 
3416 	if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
3417 	    type != IEEE80211_FC0_TYPE_DATA)
3418 		tx->id = sc->broadcast_id;
3419 	else
3420 		tx->id = wn->id;
3421 
3422 	if (type == IEEE80211_FC0_TYPE_MGT) {
3423 		uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
3424 
3425 		/* Tell HW to set timestamp in probe responses. */
3426 		if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
3427 			flags |= IWN_TX_INSERT_TSTAMP;
3428 		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
3429 		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
3430 			tx->timeout = htole16(3);
3431 		else
3432 			tx->timeout = htole16(2);
3433 	} else
3434 		tx->timeout = htole16(0);
3435 
3436 	if (hdrlen & 3) {
3437 		/* First segment length must be a multiple of 4. */
3438 		flags |= IWN_TX_NEED_PADDING;
3439 		pad = 4 - (hdrlen & 3);
3440 	} else
3441 		pad = 0;
3442 
3443 	tx->len = htole16(totlen);
3444 	tx->tid = tid;
3445 	tx->rts_ntries = 60;
3446 	tx->data_ntries = 15;
3447 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
3448 	tx->rate = wn->ridx[rate];
3449 	if (tx->id == sc->broadcast_id) {
3450 		/* Group or management frame. */
3451 		tx->linkq = 0;
3452 		/* XXX Alternate between antenna A and B? */
3453 		txant = IWN_LSB(sc->txchainmask);
3454 		tx->rate |= htole32(IWN_RFLAG_ANT(txant));
3455 	} else {
3456 		tx->linkq = ni->ni_rates.rs_nrates - ridx - 1;
3457 		flags |= IWN_TX_LINKQ;	/* enable MRR */
3458 	}
3459 	/* Set physical address of "scratch area". */
3460 	tx->loaddr = htole32(IWN_LOADDR(data->scratch_paddr));
3461 	tx->hiaddr = IWN_HIADDR(data->scratch_paddr);
3462 
3463 	/* Copy 802.11 header in TX command. */
3464 	memcpy((uint8_t *)(tx + 1), wh, hdrlen);
3465 
3466 	/* Trim 802.11 header. */
3467 	m_adj(m, hdrlen);
3468 	tx->security = 0;
3469 	tx->flags = htole32(flags);
3470 
3471 	error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m, segs,
3472 	    &nsegs, BUS_DMA_NOWAIT);
3473 	if (error != 0) {
3474 		if (error != EFBIG) {
3475 			device_printf(sc->sc_dev,
3476 			    "%s: can't map mbuf (error %d)\n", __func__, error);
3477 			m_freem(m);
3478 			return error;
3479 		}
3480 		/* Too many DMA segments, linearize mbuf. */
3481 		m1 = m_collapse(m, M_DONTWAIT, IWN_MAX_SCATTER);
3482 		if (m1 == NULL) {
3483 			device_printf(sc->sc_dev,
3484 			    "%s: could not defrag mbuf\n", __func__);
3485 			m_freem(m);
3486 			return ENOBUFS;
3487 		}
3488 		m = m1;
3489 
3490 		error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m,
3491 		    segs, &nsegs, BUS_DMA_NOWAIT);
3492 		if (error != 0) {
3493 			device_printf(sc->sc_dev,
3494 			    "%s: can't map mbuf (error %d)\n", __func__, error);
3495 			m_freem(m);
3496 			return error;
3497 		}
3498 	}
3499 
3500 	data->m = m;
3501 	data->ni = ni;
3502 
3503 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: qid %d idx %d len %d nsegs %d\n",
3504 	    __func__, ring->qid, ring->cur, m->m_pkthdr.len, nsegs);
3505 
3506 	/* Fill TX descriptor. */
3507 	desc->nsegs = 1;
3508 	if (m->m_len != 0)
3509 		desc->nsegs += nsegs;
3510 	/* First DMA segment is used by the TX command. */
3511 	desc->segs[0].addr = htole32(IWN_LOADDR(data->cmd_paddr));
3512 	desc->segs[0].len  = htole16(IWN_HIADDR(data->cmd_paddr) |
3513 	    (4 + sizeof (*tx) + hdrlen + pad) << 4);
3514 	/* Other DMA segments are for data payload. */
3515 	seg = &segs[0];
3516 	for (i = 1; i <= nsegs; i++) {
3517 		desc->segs[i].addr = htole32(IWN_LOADDR(seg->ds_addr));
3518 		desc->segs[i].len  = htole16(IWN_HIADDR(seg->ds_addr) |
3519 		    seg->ds_len << 4);
3520 		seg++;
3521 	}
3522 
3523 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
3524 	bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
3525 	    BUS_DMASYNC_PREWRITE);
3526 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
3527 	    BUS_DMASYNC_PREWRITE);
3528 
3529 	/* Update TX scheduler. */
3530 	if (ring->qid >= sc->firstaggqueue)
3531 		ops->update_sched(sc, ring->qid, ring->cur, tx->id, totlen);
3532 
3533 	/* Kick TX ring. */
3534 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
3535 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
3536 
3537 	/* Mark TX ring as full if we reach a certain threshold. */
3538 	if (++ring->queued > IWN_TX_RING_HIMARK)
3539 		sc->qfullmsk |= 1 << ring->qid;
3540 
3541 	return 0;
3542 }
3543 
3544 static int
3545 iwn_tx_data_raw(struct iwn_softc *sc, struct mbuf *m,
3546     struct ieee80211_node *ni, const struct ieee80211_bpf_params *params)
3547 {
3548 	struct iwn_ops *ops = &sc->ops;
3549 	struct ifnet *ifp = sc->sc_ifp;
3550 	struct ieee80211vap *vap = ni->ni_vap;
3551 	struct ieee80211com *ic = ifp->if_l2com;
3552 	struct iwn_tx_cmd *cmd;
3553 	struct iwn_cmd_data *tx;
3554 	struct ieee80211_frame *wh;
3555 	struct iwn_tx_ring *ring;
3556 	struct iwn_tx_desc *desc;
3557 	struct iwn_tx_data *data;
3558 	struct mbuf *m1;
3559 	bus_dma_segment_t *seg, segs[IWN_MAX_SCATTER];
3560 	uint32_t flags;
3561 	u_int hdrlen;
3562 	int ac, totlen, error, pad, nsegs = 0, i, rate;
3563 	uint8_t ridx, type, txant;
3564 
3565 	IWN_LOCK_ASSERT(sc);
3566 
3567 	wh = mtod(m, struct ieee80211_frame *);
3568 	hdrlen = ieee80211_anyhdrsize(wh);
3569 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
3570 
3571 	ac = params->ibp_pri & 3;
3572 
3573 	ring = &sc->txq[ac];
3574 	desc = &ring->desc[ring->cur];
3575 	data = &ring->data[ring->cur];
3576 
3577 	/* Choose a TX rate index. */
3578 	rate = params->ibp_rate0;
3579 	ridx = ic->ic_rt->rateCodeToIndex[rate];
3580 	if (ridx == (uint8_t)-1) {
3581 		/* XXX fall back to mcast/mgmt rate? */
3582 		m_freem(m);
3583 		return EINVAL;
3584 	}
3585 
3586 	totlen = m->m_pkthdr.len;
3587 
3588 	/* Prepare TX firmware command. */
3589 	cmd = &ring->cmd[ring->cur];
3590 	cmd->code = IWN_CMD_TX_DATA;
3591 	cmd->flags = 0;
3592 	cmd->qid = ring->qid;
3593 	cmd->idx = ring->cur;
3594 
3595 	tx = (struct iwn_cmd_data *)cmd->data;
3596 	/* NB: No need to clear tx, all fields are reinitialized here. */
3597 	tx->scratch = 0;	/* clear "scratch" area */
3598 
3599 	flags = 0;
3600 	if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0)
3601 		flags |= IWN_TX_NEED_ACK;
3602 	if (params->ibp_flags & IEEE80211_BPF_RTS) {
3603 		if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
3604 			/* 5000 autoselects RTS/CTS or CTS-to-self. */
3605 			flags &= ~IWN_TX_NEED_RTS;
3606 			flags |= IWN_TX_NEED_PROTECTION;
3607 		} else
3608 			flags |= IWN_TX_NEED_RTS | IWN_TX_FULL_TXOP;
3609 	}
3610 	if (params->ibp_flags & IEEE80211_BPF_CTS) {
3611 		if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
3612 			/* 5000 autoselects RTS/CTS or CTS-to-self. */
3613 			flags &= ~IWN_TX_NEED_CTS;
3614 			flags |= IWN_TX_NEED_PROTECTION;
3615 		} else
3616 			flags |= IWN_TX_NEED_CTS | IWN_TX_FULL_TXOP;
3617 	}
3618 	if (type == IEEE80211_FC0_TYPE_MGT) {
3619 		uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
3620 
3621 		/* Tell HW to set timestamp in probe responses. */
3622 		if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
3623 			flags |= IWN_TX_INSERT_TSTAMP;
3624 
3625 		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
3626 		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
3627 			tx->timeout = htole16(3);
3628 		else
3629 			tx->timeout = htole16(2);
3630 	} else
3631 		tx->timeout = htole16(0);
3632 
3633 	if (hdrlen & 3) {
3634 		/* First segment length must be a multiple of 4. */
3635 		flags |= IWN_TX_NEED_PADDING;
3636 		pad = 4 - (hdrlen & 3);
3637 	} else
3638 		pad = 0;
3639 
3640 	if (ieee80211_radiotap_active_vap(vap)) {
3641 		struct iwn_tx_radiotap_header *tap = &sc->sc_txtap;
3642 
3643 		tap->wt_flags = 0;
3644 		tap->wt_rate = rate;
3645 
3646 		ieee80211_radiotap_tx(vap, m);
3647 	}
3648 
3649 	tx->len = htole16(totlen);
3650 	tx->tid = 0;
3651 	tx->id = sc->broadcast_id;
3652 	tx->rts_ntries = params->ibp_try1;
3653 	tx->data_ntries = params->ibp_try0;
3654 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
3655 	tx->rate = htole32(rate2plcp(rate));
3656 	if (ridx < IWN_RIDX_OFDM6 &&
3657 	    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
3658 		tx->rate |= htole32(IWN_RFLAG_CCK);
3659 	/* Group or management frame. */
3660 	tx->linkq = 0;
3661 	txant = IWN_LSB(sc->txchainmask);
3662 	tx->rate |= htole32(IWN_RFLAG_ANT(txant));
3663 	/* Set physical address of "scratch area". */
3664 	tx->loaddr = htole32(IWN_LOADDR(data->scratch_paddr));
3665 	tx->hiaddr = IWN_HIADDR(data->scratch_paddr);
3666 
3667 	/* Copy 802.11 header in TX command. */
3668 	memcpy((uint8_t *)(tx + 1), wh, hdrlen);
3669 
3670 	/* Trim 802.11 header. */
3671 	m_adj(m, hdrlen);
3672 	tx->security = 0;
3673 	tx->flags = htole32(flags);
3674 
3675 	error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m, segs,
3676 	    &nsegs, BUS_DMA_NOWAIT);
3677 	if (error != 0) {
3678 		if (error != EFBIG) {
3679 			device_printf(sc->sc_dev,
3680 			    "%s: can't map mbuf (error %d)\n", __func__, error);
3681 			m_freem(m);
3682 			return error;
3683 		}
3684 		/* Too many DMA segments, linearize mbuf. */
3685 		m1 = m_collapse(m, M_DONTWAIT, IWN_MAX_SCATTER);
3686 		if (m1 == NULL) {
3687 			device_printf(sc->sc_dev,
3688 			    "%s: could not defrag mbuf\n", __func__);
3689 			m_freem(m);
3690 			return ENOBUFS;
3691 		}
3692 		m = m1;
3693 
3694 		error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m,
3695 		    segs, &nsegs, BUS_DMA_NOWAIT);
3696 		if (error != 0) {
3697 			device_printf(sc->sc_dev,
3698 			    "%s: can't map mbuf (error %d)\n", __func__, error);
3699 			m_freem(m);
3700 			return error;
3701 		}
3702 	}
3703 
3704 	data->m = m;
3705 	data->ni = ni;
3706 
3707 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: qid %d idx %d len %d nsegs %d\n",
3708 	    __func__, ring->qid, ring->cur, m->m_pkthdr.len, nsegs);
3709 
3710 	/* Fill TX descriptor. */
3711 	desc->nsegs = 1;
3712 	if (m->m_len != 0)
3713 		desc->nsegs += nsegs;
3714 	/* First DMA segment is used by the TX command. */
3715 	desc->segs[0].addr = htole32(IWN_LOADDR(data->cmd_paddr));
3716 	desc->segs[0].len  = htole16(IWN_HIADDR(data->cmd_paddr) |
3717 	    (4 + sizeof (*tx) + hdrlen + pad) << 4);
3718 	/* Other DMA segments are for data payload. */
3719 	seg = &segs[0];
3720 	for (i = 1; i <= nsegs; i++) {
3721 		desc->segs[i].addr = htole32(IWN_LOADDR(seg->ds_addr));
3722 		desc->segs[i].len  = htole16(IWN_HIADDR(seg->ds_addr) |
3723 		    seg->ds_len << 4);
3724 		seg++;
3725 	}
3726 
3727 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
3728 	bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
3729 	    BUS_DMASYNC_PREWRITE);
3730 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
3731 	    BUS_DMASYNC_PREWRITE);
3732 
3733 	/* Update TX scheduler. */
3734 	if (ring->qid >= sc->firstaggqueue)
3735 		ops->update_sched(sc, ring->qid, ring->cur, tx->id, totlen);
3736 
3737 	/* Kick TX ring. */
3738 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
3739 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
3740 
3741 	/* Mark TX ring as full if we reach a certain threshold. */
3742 	if (++ring->queued > IWN_TX_RING_HIMARK)
3743 		sc->qfullmsk |= 1 << ring->qid;
3744 
3745 	return 0;
3746 }
3747 
3748 static int
3749 iwn_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
3750     const struct ieee80211_bpf_params *params)
3751 {
3752 	struct ieee80211com *ic = ni->ni_ic;
3753 	struct ifnet *ifp = ic->ic_ifp;
3754 	struct iwn_softc *sc = ifp->if_softc;
3755 	int error = 0;
3756 
3757 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
3758 		ieee80211_free_node(ni);
3759 		m_freem(m);
3760 		return ENETDOWN;
3761 	}
3762 
3763 	IWN_LOCK(sc);
3764 	if (params == NULL) {
3765 		/*
3766 		 * Legacy path; interpret frame contents to decide
3767 		 * precisely how to send the frame.
3768 		 */
3769 		error = iwn_tx_data(sc, m, ni);
3770 	} else {
3771 		/*
3772 		 * Caller supplied explicit parameters to use in
3773 		 * sending the frame.
3774 		 */
3775 		error = iwn_tx_data_raw(sc, m, ni, params);
3776 	}
3777 	if (error != 0) {
3778 		/* NB: m is reclaimed on tx failure */
3779 		ieee80211_free_node(ni);
3780 		ifp->if_oerrors++;
3781 	}
3782 	sc->sc_tx_timer = 5;
3783 
3784 	IWN_UNLOCK(sc);
3785 	return error;
3786 }
3787 
3788 static void
3789 iwn_start(struct ifnet *ifp)
3790 {
3791 	struct iwn_softc *sc = ifp->if_softc;
3792 
3793 	IWN_LOCK(sc);
3794 	iwn_start_locked(ifp);
3795 	IWN_UNLOCK(sc);
3796 }
3797 
3798 static void
3799 iwn_start_locked(struct ifnet *ifp)
3800 {
3801 	struct iwn_softc *sc = ifp->if_softc;
3802 	struct ieee80211_node *ni;
3803 	struct mbuf *m;
3804 
3805 	IWN_LOCK_ASSERT(sc);
3806 
3807 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
3808 	    (ifp->if_drv_flags & IFF_DRV_OACTIVE))
3809 		return;
3810 
3811 	for (;;) {
3812 		if (sc->qfullmsk != 0) {
3813 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3814 			break;
3815 		}
3816 		IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
3817 		if (m == NULL)
3818 			break;
3819 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
3820 		if (iwn_tx_data(sc, m, ni) != 0) {
3821 			ieee80211_free_node(ni);
3822 			ifp->if_oerrors++;
3823 			continue;
3824 		}
3825 		sc->sc_tx_timer = 5;
3826 	}
3827 }
3828 
3829 static void
3830 iwn_watchdog(void *arg)
3831 {
3832 	struct iwn_softc *sc = arg;
3833 	struct ifnet *ifp = sc->sc_ifp;
3834 	struct ieee80211com *ic = ifp->if_l2com;
3835 
3836 	IWN_LOCK_ASSERT(sc);
3837 
3838 	KASSERT(ifp->if_drv_flags & IFF_DRV_RUNNING, ("not running"));
3839 
3840 	if (sc->sc_tx_timer > 0) {
3841 		if (--sc->sc_tx_timer == 0) {
3842 			if_printf(ifp, "device timeout\n");
3843 			ieee80211_runtask(ic, &sc->sc_reinit_task);
3844 			return;
3845 		}
3846 	}
3847 	callout_reset(&sc->watchdog_to, hz, iwn_watchdog, sc);
3848 }
3849 
3850 static int
3851 iwn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
3852 {
3853 	struct iwn_softc *sc = ifp->if_softc;
3854 	struct ieee80211com *ic = ifp->if_l2com;
3855 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3856 	struct ifreq *ifr = (struct ifreq *) data;
3857 	int error = 0, startall = 0, stop = 0;
3858 
3859 	switch (cmd) {
3860 	case SIOCGIFADDR:
3861 		error = ether_ioctl(ifp, cmd, data);
3862 		break;
3863 	case SIOCSIFFLAGS:
3864 		IWN_LOCK(sc);
3865 		if (ifp->if_flags & IFF_UP) {
3866 			if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
3867 				iwn_init_locked(sc);
3868 				if (IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_RFKILL)
3869 					startall = 1;
3870 				else
3871 					stop = 1;
3872 			}
3873 		} else {
3874 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
3875 				iwn_stop_locked(sc);
3876 		}
3877 		IWN_UNLOCK(sc);
3878 		if (startall)
3879 			ieee80211_start_all(ic);
3880 		else if (vap != NULL && stop)
3881 			ieee80211_stop(vap);
3882 		break;
3883 	case SIOCGIFMEDIA:
3884 		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
3885 		break;
3886 	default:
3887 		error = EINVAL;
3888 		break;
3889 	}
3890 	return error;
3891 }
3892 
3893 /*
3894  * Send a command to the firmware.
3895  */
3896 static int
3897 iwn_cmd(struct iwn_softc *sc, int code, const void *buf, int size, int async)
3898 {
3899 	struct iwn_tx_ring *ring = &sc->txq[4];
3900 	struct iwn_tx_desc *desc;
3901 	struct iwn_tx_data *data;
3902 	struct iwn_tx_cmd *cmd;
3903 	struct mbuf *m;
3904 	bus_addr_t paddr;
3905 	int totlen, error;
3906 
3907 	if (async == 0)
3908 		IWN_LOCK_ASSERT(sc);
3909 
3910 	desc = &ring->desc[ring->cur];
3911 	data = &ring->data[ring->cur];
3912 	totlen = 4 + size;
3913 
3914 	if (size > sizeof cmd->data) {
3915 		/* Command is too large to fit in a descriptor. */
3916 		if (totlen > MCLBYTES)
3917 			return EINVAL;
3918 		m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE);
3919 		if (m == NULL)
3920 			return ENOMEM;
3921 		cmd = mtod(m, struct iwn_tx_cmd *);
3922 		error = bus_dmamap_load(ring->data_dmat, data->map, cmd,
3923 		    totlen, iwn_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
3924 		if (error != 0) {
3925 			m_freem(m);
3926 			return error;
3927 		}
3928 		data->m = m;
3929 	} else {
3930 		cmd = &ring->cmd[ring->cur];
3931 		paddr = data->cmd_paddr;
3932 	}
3933 
3934 	cmd->code = code;
3935 	cmd->flags = 0;
3936 	cmd->qid = ring->qid;
3937 	cmd->idx = ring->cur;
3938 	memcpy(cmd->data, buf, size);
3939 
3940 	desc->nsegs = 1;
3941 	desc->segs[0].addr = htole32(IWN_LOADDR(paddr));
3942 	desc->segs[0].len  = htole16(IWN_HIADDR(paddr) | totlen << 4);
3943 
3944 	DPRINTF(sc, IWN_DEBUG_CMD, "%s: %s (0x%x) flags %d qid %d idx %d\n",
3945 	    __func__, iwn_intr_str(cmd->code), cmd->code,
3946 	    cmd->flags, cmd->qid, cmd->idx);
3947 
3948 	if (size > sizeof cmd->data) {
3949 		bus_dmamap_sync(ring->data_dmat, data->map,
3950 		    BUS_DMASYNC_PREWRITE);
3951 	} else {
3952 		bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
3953 		    BUS_DMASYNC_PREWRITE);
3954 	}
3955 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
3956 	    BUS_DMASYNC_PREWRITE);
3957 
3958 	/* Kick command ring. */
3959 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
3960 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
3961 
3962 	return async ? 0 : msleep(desc, &sc->sc_mtx, PCATCH, "iwncmd", hz);
3963 }
3964 
3965 static int
3966 iwn4965_add_node(struct iwn_softc *sc, struct iwn_node_info *node, int async)
3967 {
3968 	struct iwn4965_node_info hnode;
3969 	caddr_t src, dst;
3970 
3971 	/*
3972 	 * We use the node structure for 5000 Series internally (it is
3973 	 * a superset of the one for 4965AGN). We thus copy the common
3974 	 * fields before sending the command.
3975 	 */
3976 	src = (caddr_t)node;
3977 	dst = (caddr_t)&hnode;
3978 	memcpy(dst, src, 48);
3979 	/* Skip TSC, RX MIC and TX MIC fields from ``src''. */
3980 	memcpy(dst + 48, src + 72, 20);
3981 	return iwn_cmd(sc, IWN_CMD_ADD_NODE, &hnode, sizeof hnode, async);
3982 }
3983 
3984 static int
3985 iwn5000_add_node(struct iwn_softc *sc, struct iwn_node_info *node, int async)
3986 {
3987 	/* Direct mapping. */
3988 	return iwn_cmd(sc, IWN_CMD_ADD_NODE, node, sizeof (*node), async);
3989 }
3990 
3991 static int
3992 iwn_set_link_quality(struct iwn_softc *sc, struct ieee80211_node *ni)
3993 {
3994 #define	RV(v)	((v) & IEEE80211_RATE_VAL)
3995 	struct iwn_node *wn = (void *)ni;
3996 	struct ieee80211_rateset *rs = &ni->ni_rates;
3997 	struct iwn_cmd_link_quality linkq;
3998 	uint8_t txant;
3999 	int i, rate, txrate;
4000 
4001 	/* Use the first valid TX antenna. */
4002 	txant = IWN_LSB(sc->txchainmask);
4003 
4004 	memset(&linkq, 0, sizeof linkq);
4005 	linkq.id = wn->id;
4006 	linkq.antmsk_1stream = txant;
4007 	linkq.antmsk_2stream = IWN_ANT_AB;
4008 	linkq.ampdu_max = 64;
4009 	linkq.ampdu_threshold = 3;
4010 	linkq.ampdu_limit = htole16(4000);	/* 4ms */
4011 
4012 	/* Start at highest available bit-rate. */
4013 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan))
4014 		txrate = ni->ni_htrates.rs_nrates - 1;
4015 	else
4016 		txrate = rs->rs_nrates - 1;
4017 	for (i = 0; i < IWN_MAX_TX_RETRIES; i++) {
4018 		if (IEEE80211_IS_CHAN_HT(ni->ni_chan))
4019 			rate = IEEE80211_RATE_MCS | txrate;
4020 		else
4021 			rate = RV(rs->rs_rates[txrate]);
4022 		linkq.retry[i] = wn->ridx[rate];
4023 
4024 		if ((le32toh(wn->ridx[rate]) & IWN_RFLAG_MCS) &&
4025 		    RV(le32toh(wn->ridx[rate])) > 7)
4026 			linkq.mimo = i + 1;
4027 
4028 		/* Next retry at immediate lower bit-rate. */
4029 		if (txrate > 0)
4030 			txrate--;
4031 	}
4032 	return iwn_cmd(sc, IWN_CMD_LINK_QUALITY, &linkq, sizeof linkq, 1);
4033 #undef	RV
4034 }
4035 
4036 /*
4037  * Broadcast node is used to send group-addressed and management frames.
4038  */
4039 static int
4040 iwn_add_broadcast_node(struct iwn_softc *sc, int async)
4041 {
4042 	struct iwn_ops *ops = &sc->ops;
4043 	struct ifnet *ifp = sc->sc_ifp;
4044 	struct ieee80211com *ic = ifp->if_l2com;
4045 	struct iwn_node_info node;
4046 	struct iwn_cmd_link_quality linkq;
4047 	uint8_t txant;
4048 	int i, error;
4049 
4050 	memset(&node, 0, sizeof node);
4051 	IEEE80211_ADDR_COPY(node.macaddr, ifp->if_broadcastaddr);
4052 	node.id = sc->broadcast_id;
4053 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: adding broadcast node\n", __func__);
4054 	if ((error = ops->add_node(sc, &node, async)) != 0)
4055 		return error;
4056 
4057 	/* Use the first valid TX antenna. */
4058 	txant = IWN_LSB(sc->txchainmask);
4059 
4060 	memset(&linkq, 0, sizeof linkq);
4061 	linkq.id = sc->broadcast_id;
4062 	linkq.antmsk_1stream = txant;
4063 	linkq.antmsk_2stream = IWN_ANT_AB;
4064 	linkq.ampdu_max = 64;
4065 	linkq.ampdu_threshold = 3;
4066 	linkq.ampdu_limit = htole16(4000);	/* 4ms */
4067 
4068 	/* Use lowest mandatory bit-rate. */
4069 	if (IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan))
4070 		linkq.retry[0] = htole32(0xd);
4071 	else
4072 		linkq.retry[0] = htole32(10 | IWN_RFLAG_CCK);
4073 	linkq.retry[0] |= htole32(IWN_RFLAG_ANT(txant));
4074 	/* Use same bit-rate for all TX retries. */
4075 	for (i = 1; i < IWN_MAX_TX_RETRIES; i++) {
4076 		linkq.retry[i] = linkq.retry[0];
4077 	}
4078 	return iwn_cmd(sc, IWN_CMD_LINK_QUALITY, &linkq, sizeof linkq, async);
4079 }
4080 
4081 static int
4082 iwn_updateedca(struct ieee80211com *ic)
4083 {
4084 #define IWN_EXP2(x)	((1 << (x)) - 1)	/* CWmin = 2^ECWmin - 1 */
4085 	struct iwn_softc *sc = ic->ic_ifp->if_softc;
4086 	struct iwn_edca_params cmd;
4087 	int aci;
4088 
4089 	memset(&cmd, 0, sizeof cmd);
4090 	cmd.flags = htole32(IWN_EDCA_UPDATE);
4091 	for (aci = 0; aci < WME_NUM_AC; aci++) {
4092 		const struct wmeParams *ac =
4093 		    &ic->ic_wme.wme_chanParams.cap_wmeParams[aci];
4094 		cmd.ac[aci].aifsn = ac->wmep_aifsn;
4095 		cmd.ac[aci].cwmin = htole16(IWN_EXP2(ac->wmep_logcwmin));
4096 		cmd.ac[aci].cwmax = htole16(IWN_EXP2(ac->wmep_logcwmax));
4097 		cmd.ac[aci].txoplimit =
4098 		    htole16(IEEE80211_TXOP_TO_US(ac->wmep_txopLimit));
4099 	}
4100 	IEEE80211_UNLOCK(ic);
4101 	IWN_LOCK(sc);
4102 	(void)iwn_cmd(sc, IWN_CMD_EDCA_PARAMS, &cmd, sizeof cmd, 1);
4103 	IWN_UNLOCK(sc);
4104 	IEEE80211_LOCK(ic);
4105 	return 0;
4106 #undef IWN_EXP2
4107 }
4108 
4109 static void
4110 iwn_update_mcast(struct ifnet *ifp)
4111 {
4112 	/* Ignore */
4113 }
4114 
4115 static void
4116 iwn_set_led(struct iwn_softc *sc, uint8_t which, uint8_t off, uint8_t on)
4117 {
4118 	struct iwn_cmd_led led;
4119 
4120 	/* Clear microcode LED ownership. */
4121 	IWN_CLRBITS(sc, IWN_LED, IWN_LED_BSM_CTRL);
4122 
4123 	led.which = which;
4124 	led.unit = htole32(10000);	/* on/off in unit of 100ms */
4125 	led.off = off;
4126 	led.on = on;
4127 	(void)iwn_cmd(sc, IWN_CMD_SET_LED, &led, sizeof led, 1);
4128 }
4129 
4130 /*
4131  * Set the critical temperature at which the firmware will stop the radio
4132  * and notify us.
4133  */
4134 static int
4135 iwn_set_critical_temp(struct iwn_softc *sc)
4136 {
4137 	struct iwn_critical_temp crit;
4138 	int32_t temp;
4139 
4140 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CTEMP_STOP_RF);
4141 
4142 	if (sc->hw_type == IWN_HW_REV_TYPE_5150)
4143 		temp = (IWN_CTOK(110) - sc->temp_off) * -5;
4144 	else if (sc->hw_type == IWN_HW_REV_TYPE_4965)
4145 		temp = IWN_CTOK(110);
4146 	else
4147 		temp = 110;
4148 	memset(&crit, 0, sizeof crit);
4149 	crit.tempR = htole32(temp);
4150 	DPRINTF(sc, IWN_DEBUG_RESET, "setting critical temp to %d\n", temp);
4151 	return iwn_cmd(sc, IWN_CMD_SET_CRITICAL_TEMP, &crit, sizeof crit, 0);
4152 }
4153 
4154 static int
4155 iwn_set_timing(struct iwn_softc *sc, struct ieee80211_node *ni)
4156 {
4157 	struct iwn_cmd_timing cmd;
4158 	uint64_t val, mod;
4159 
4160 	memset(&cmd, 0, sizeof cmd);
4161 	memcpy(&cmd.tstamp, ni->ni_tstamp.data, sizeof (uint64_t));
4162 	cmd.bintval = htole16(ni->ni_intval);
4163 	cmd.lintval = htole16(10);
4164 
4165 	/* Compute remaining time until next beacon. */
4166 	val = (uint64_t)ni->ni_intval * IEEE80211_DUR_TU;
4167 	mod = le64toh(cmd.tstamp) % val;
4168 	cmd.binitval = htole32((uint32_t)(val - mod));
4169 
4170 	DPRINTF(sc, IWN_DEBUG_RESET, "timing bintval=%u tstamp=%ju, init=%u\n",
4171 	    ni->ni_intval, le64toh(cmd.tstamp), (uint32_t)(val - mod));
4172 
4173 	return iwn_cmd(sc, IWN_CMD_TIMING, &cmd, sizeof cmd, 1);
4174 }
4175 
4176 static void
4177 iwn4965_power_calibration(struct iwn_softc *sc, int temp)
4178 {
4179 	struct ifnet *ifp = sc->sc_ifp;
4180 	struct ieee80211com *ic = ifp->if_l2com;
4181 
4182 	/* Adjust TX power if need be (delta >= 3 degC). */
4183 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: temperature %d->%d\n",
4184 	    __func__, sc->temp, temp);
4185 	if (abs(temp - sc->temp) >= 3) {
4186 		/* Record temperature of last calibration. */
4187 		sc->temp = temp;
4188 		(void)iwn4965_set_txpower(sc, ic->ic_bsschan, 1);
4189 	}
4190 }
4191 
4192 /*
4193  * Set TX power for current channel (each rate has its own power settings).
4194  * This function takes into account the regulatory information from EEPROM,
4195  * the current temperature and the current voltage.
4196  */
4197 static int
4198 iwn4965_set_txpower(struct iwn_softc *sc, struct ieee80211_channel *ch,
4199     int async)
4200 {
4201 /* Fixed-point arithmetic division using a n-bit fractional part. */
4202 #define fdivround(a, b, n)	\
4203 	((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
4204 /* Linear interpolation. */
4205 #define interpolate(x, x1, y1, x2, y2, n)	\
4206 	((y1) + fdivround(((int)(x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
4207 
4208 	static const int tdiv[IWN_NATTEN_GROUPS] = { 9, 8, 8, 8, 6 };
4209 	struct iwn_ucode_info *uc = &sc->ucode_info;
4210 	struct iwn4965_cmd_txpower cmd;
4211 	struct iwn4965_eeprom_chan_samples *chans;
4212 	const uint8_t *rf_gain, *dsp_gain;
4213 	int32_t vdiff, tdiff;
4214 	int i, c, grp, maxpwr;
4215 	uint8_t chan;
4216 
4217 	/* Retrieve current channel from last RXON. */
4218 	chan = sc->rxon.chan;
4219 	DPRINTF(sc, IWN_DEBUG_RESET, "setting TX power for channel %d\n",
4220 	    chan);
4221 
4222 	memset(&cmd, 0, sizeof cmd);
4223 	cmd.band = IEEE80211_IS_CHAN_5GHZ(ch) ? 0 : 1;
4224 	cmd.chan = chan;
4225 
4226 	if (IEEE80211_IS_CHAN_5GHZ(ch)) {
4227 		maxpwr   = sc->maxpwr5GHz;
4228 		rf_gain  = iwn4965_rf_gain_5ghz;
4229 		dsp_gain = iwn4965_dsp_gain_5ghz;
4230 	} else {
4231 		maxpwr   = sc->maxpwr2GHz;
4232 		rf_gain  = iwn4965_rf_gain_2ghz;
4233 		dsp_gain = iwn4965_dsp_gain_2ghz;
4234 	}
4235 
4236 	/* Compute voltage compensation. */
4237 	vdiff = ((int32_t)le32toh(uc->volt) - sc->eeprom_voltage) / 7;
4238 	if (vdiff > 0)
4239 		vdiff *= 2;
4240 	if (abs(vdiff) > 2)
4241 		vdiff = 0;
4242 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
4243 	    "%s: voltage compensation=%d (UCODE=%d, EEPROM=%d)\n",
4244 	    __func__, vdiff, le32toh(uc->volt), sc->eeprom_voltage);
4245 
4246 	/* Get channel attenuation group. */
4247 	if (chan <= 20)		/* 1-20 */
4248 		grp = 4;
4249 	else if (chan <= 43)	/* 34-43 */
4250 		grp = 0;
4251 	else if (chan <= 70)	/* 44-70 */
4252 		grp = 1;
4253 	else if (chan <= 124)	/* 71-124 */
4254 		grp = 2;
4255 	else			/* 125-200 */
4256 		grp = 3;
4257 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
4258 	    "%s: chan %d, attenuation group=%d\n", __func__, chan, grp);
4259 
4260 	/* Get channel sub-band. */
4261 	for (i = 0; i < IWN_NBANDS; i++)
4262 		if (sc->bands[i].lo != 0 &&
4263 		    sc->bands[i].lo <= chan && chan <= sc->bands[i].hi)
4264 			break;
4265 	if (i == IWN_NBANDS)	/* Can't happen in real-life. */
4266 		return EINVAL;
4267 	chans = sc->bands[i].chans;
4268 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
4269 	    "%s: chan %d sub-band=%d\n", __func__, chan, i);
4270 
4271 	for (c = 0; c < 2; c++) {
4272 		uint8_t power, gain, temp;
4273 		int maxchpwr, pwr, ridx, idx;
4274 
4275 		power = interpolate(chan,
4276 		    chans[0].num, chans[0].samples[c][1].power,
4277 		    chans[1].num, chans[1].samples[c][1].power, 1);
4278 		gain  = interpolate(chan,
4279 		    chans[0].num, chans[0].samples[c][1].gain,
4280 		    chans[1].num, chans[1].samples[c][1].gain, 1);
4281 		temp  = interpolate(chan,
4282 		    chans[0].num, chans[0].samples[c][1].temp,
4283 		    chans[1].num, chans[1].samples[c][1].temp, 1);
4284 		DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
4285 		    "%s: Tx chain %d: power=%d gain=%d temp=%d\n",
4286 		    __func__, c, power, gain, temp);
4287 
4288 		/* Compute temperature compensation. */
4289 		tdiff = ((sc->temp - temp) * 2) / tdiv[grp];
4290 		DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
4291 		    "%s: temperature compensation=%d (current=%d, EEPROM=%d)\n",
4292 		    __func__, tdiff, sc->temp, temp);
4293 
4294 		for (ridx = 0; ridx <= IWN_RIDX_MAX; ridx++) {
4295 			/* Convert dBm to half-dBm. */
4296 			maxchpwr = sc->maxpwr[chan] * 2;
4297 			if ((ridx / 8) & 1)
4298 				maxchpwr -= 6;	/* MIMO 2T: -3dB */
4299 
4300 			pwr = maxpwr;
4301 
4302 			/* Adjust TX power based on rate. */
4303 			if ((ridx % 8) == 5)
4304 				pwr -= 15;	/* OFDM48: -7.5dB */
4305 			else if ((ridx % 8) == 6)
4306 				pwr -= 17;	/* OFDM54: -8.5dB */
4307 			else if ((ridx % 8) == 7)
4308 				pwr -= 20;	/* OFDM60: -10dB */
4309 			else
4310 				pwr -= 10;	/* Others: -5dB */
4311 
4312 			/* Do not exceed channel max TX power. */
4313 			if (pwr > maxchpwr)
4314 				pwr = maxchpwr;
4315 
4316 			idx = gain - (pwr - power) - tdiff - vdiff;
4317 			if ((ridx / 8) & 1)	/* MIMO */
4318 				idx += (int32_t)le32toh(uc->atten[grp][c]);
4319 
4320 			if (cmd.band == 0)
4321 				idx += 9;	/* 5GHz */
4322 			if (ridx == IWN_RIDX_MAX)
4323 				idx += 5;	/* CCK */
4324 
4325 			/* Make sure idx stays in a valid range. */
4326 			if (idx < 0)
4327 				idx = 0;
4328 			else if (idx > IWN4965_MAX_PWR_INDEX)
4329 				idx = IWN4965_MAX_PWR_INDEX;
4330 
4331 			DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
4332 			    "%s: Tx chain %d, rate idx %d: power=%d\n",
4333 			    __func__, c, ridx, idx);
4334 			cmd.power[ridx].rf_gain[c] = rf_gain[idx];
4335 			cmd.power[ridx].dsp_gain[c] = dsp_gain[idx];
4336 		}
4337 	}
4338 
4339 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
4340 	    "%s: set tx power for chan %d\n", __func__, chan);
4341 	return iwn_cmd(sc, IWN_CMD_TXPOWER, &cmd, sizeof cmd, async);
4342 
4343 #undef interpolate
4344 #undef fdivround
4345 }
4346 
4347 static int
4348 iwn5000_set_txpower(struct iwn_softc *sc, struct ieee80211_channel *ch,
4349     int async)
4350 {
4351 	struct iwn5000_cmd_txpower cmd;
4352 
4353 	/*
4354 	 * TX power calibration is handled automatically by the firmware
4355 	 * for 5000 Series.
4356 	 */
4357 	memset(&cmd, 0, sizeof cmd);
4358 	cmd.global_limit = 2 * IWN5000_TXPOWER_MAX_DBM;	/* 16 dBm */
4359 	cmd.flags = IWN5000_TXPOWER_NO_CLOSED;
4360 	cmd.srv_limit = IWN5000_TXPOWER_AUTO;
4361 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: setting TX power\n", __func__);
4362 	return iwn_cmd(sc, IWN_CMD_TXPOWER_DBM, &cmd, sizeof cmd, async);
4363 }
4364 
4365 /*
4366  * Retrieve the maximum RSSI (in dBm) among receivers.
4367  */
4368 static int
4369 iwn4965_get_rssi(struct iwn_softc *sc, struct iwn_rx_stat *stat)
4370 {
4371 	struct iwn4965_rx_phystat *phy = (void *)stat->phybuf;
4372 	uint8_t mask, agc;
4373 	int rssi;
4374 
4375 	mask = (le16toh(phy->antenna) >> 4) & IWN_ANT_ABC;
4376 	agc  = (le16toh(phy->agc) >> 7) & 0x7f;
4377 
4378 	rssi = 0;
4379 	if (mask & IWN_ANT_A)
4380 		rssi = MAX(rssi, phy->rssi[0]);
4381 	if (mask & IWN_ANT_B)
4382 		rssi = MAX(rssi, phy->rssi[2]);
4383 	if (mask & IWN_ANT_C)
4384 		rssi = MAX(rssi, phy->rssi[4]);
4385 
4386 	DPRINTF(sc, IWN_DEBUG_RECV,
4387 	    "%s: agc %d mask 0x%x rssi %d %d %d result %d\n", __func__, agc,
4388 	    mask, phy->rssi[0], phy->rssi[2], phy->rssi[4],
4389 	    rssi - agc - IWN_RSSI_TO_DBM);
4390 	return rssi - agc - IWN_RSSI_TO_DBM;
4391 }
4392 
4393 static int
4394 iwn5000_get_rssi(struct iwn_softc *sc, struct iwn_rx_stat *stat)
4395 {
4396 	struct iwn5000_rx_phystat *phy = (void *)stat->phybuf;
4397 	uint8_t agc;
4398 	int rssi;
4399 
4400 	agc = (le32toh(phy->agc) >> 9) & 0x7f;
4401 
4402 	rssi = MAX(le16toh(phy->rssi[0]) & 0xff,
4403 		   le16toh(phy->rssi[1]) & 0xff);
4404 	rssi = MAX(le16toh(phy->rssi[2]) & 0xff, rssi);
4405 
4406 	DPRINTF(sc, IWN_DEBUG_RECV,
4407 	    "%s: agc %d rssi %d %d %d result %d\n", __func__, agc,
4408 	    phy->rssi[0], phy->rssi[1], phy->rssi[2],
4409 	    rssi - agc - IWN_RSSI_TO_DBM);
4410 	return rssi - agc - IWN_RSSI_TO_DBM;
4411 }
4412 
4413 /*
4414  * Retrieve the average noise (in dBm) among receivers.
4415  */
4416 static int
4417 iwn_get_noise(const struct iwn_rx_general_stats *stats)
4418 {
4419 	int i, total, nbant, noise;
4420 
4421 	total = nbant = 0;
4422 	for (i = 0; i < 3; i++) {
4423 		if ((noise = le32toh(stats->noise[i]) & 0xff) == 0)
4424 			continue;
4425 		total += noise;
4426 		nbant++;
4427 	}
4428 	/* There should be at least one antenna but check anyway. */
4429 	return (nbant == 0) ? -127 : (total / nbant) - 107;
4430 }
4431 
4432 /*
4433  * Compute temperature (in degC) from last received statistics.
4434  */
4435 static int
4436 iwn4965_get_temperature(struct iwn_softc *sc)
4437 {
4438 	struct iwn_ucode_info *uc = &sc->ucode_info;
4439 	int32_t r1, r2, r3, r4, temp;
4440 
4441 	r1 = le32toh(uc->temp[0].chan20MHz);
4442 	r2 = le32toh(uc->temp[1].chan20MHz);
4443 	r3 = le32toh(uc->temp[2].chan20MHz);
4444 	r4 = le32toh(sc->rawtemp);
4445 
4446 	if (r1 == r3)	/* Prevents division by 0 (should not happen). */
4447 		return 0;
4448 
4449 	/* Sign-extend 23-bit R4 value to 32-bit. */
4450 	r4 = ((r4 & 0xffffff) ^ 0x800000) - 0x800000;
4451 	/* Compute temperature in Kelvin. */
4452 	temp = (259 * (r4 - r2)) / (r3 - r1);
4453 	temp = (temp * 97) / 100 + 8;
4454 
4455 	DPRINTF(sc, IWN_DEBUG_ANY, "temperature %dK/%dC\n", temp,
4456 	    IWN_KTOC(temp));
4457 	return IWN_KTOC(temp);
4458 }
4459 
4460 static int
4461 iwn5000_get_temperature(struct iwn_softc *sc)
4462 {
4463 	int32_t temp;
4464 
4465 	/*
4466 	 * Temperature is not used by the driver for 5000 Series because
4467 	 * TX power calibration is handled by firmware.
4468 	 */
4469 	temp = le32toh(sc->rawtemp);
4470 	if (sc->hw_type == IWN_HW_REV_TYPE_5150) {
4471 		temp = (temp / -5) + sc->temp_off;
4472 		temp = IWN_KTOC(temp);
4473 	}
4474 	return temp;
4475 }
4476 
4477 /*
4478  * Initialize sensitivity calibration state machine.
4479  */
4480 static int
4481 iwn_init_sensitivity(struct iwn_softc *sc)
4482 {
4483 	struct iwn_ops *ops = &sc->ops;
4484 	struct iwn_calib_state *calib = &sc->calib;
4485 	uint32_t flags;
4486 	int error;
4487 
4488 	/* Reset calibration state machine. */
4489 	memset(calib, 0, sizeof (*calib));
4490 	calib->state = IWN_CALIB_STATE_INIT;
4491 	calib->cck_state = IWN_CCK_STATE_HIFA;
4492 	/* Set initial correlation values. */
4493 	calib->ofdm_x1     = sc->limits->min_ofdm_x1;
4494 	calib->ofdm_mrc_x1 = sc->limits->min_ofdm_mrc_x1;
4495 	calib->ofdm_x4     = sc->limits->min_ofdm_x4;
4496 	calib->ofdm_mrc_x4 = sc->limits->min_ofdm_mrc_x4;
4497 	calib->cck_x4      = 125;
4498 	calib->cck_mrc_x4  = sc->limits->min_cck_mrc_x4;
4499 	calib->energy_cck  = sc->limits->energy_cck;
4500 
4501 	/* Write initial sensitivity. */
4502 	if ((error = iwn_send_sensitivity(sc)) != 0)
4503 		return error;
4504 
4505 	/* Write initial gains. */
4506 	if ((error = ops->init_gains(sc)) != 0)
4507 		return error;
4508 
4509 	/* Request statistics at each beacon interval. */
4510 	flags = 0;
4511 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: sending request for statistics\n",
4512 	    __func__);
4513 	return iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags, sizeof flags, 1);
4514 }
4515 
4516 /*
4517  * Collect noise and RSSI statistics for the first 20 beacons received
4518  * after association and use them to determine connected antennas and
4519  * to set differential gains.
4520  */
4521 static void
4522 iwn_collect_noise(struct iwn_softc *sc,
4523     const struct iwn_rx_general_stats *stats)
4524 {
4525 	struct iwn_ops *ops = &sc->ops;
4526 	struct iwn_calib_state *calib = &sc->calib;
4527 	uint32_t val;
4528 	int i;
4529 
4530 	/* Accumulate RSSI and noise for all 3 antennas. */
4531 	for (i = 0; i < 3; i++) {
4532 		calib->rssi[i] += le32toh(stats->rssi[i]) & 0xff;
4533 		calib->noise[i] += le32toh(stats->noise[i]) & 0xff;
4534 	}
4535 	/* NB: We update differential gains only once after 20 beacons. */
4536 	if (++calib->nbeacons < 20)
4537 		return;
4538 
4539 	/* Determine highest average RSSI. */
4540 	val = MAX(calib->rssi[0], calib->rssi[1]);
4541 	val = MAX(calib->rssi[2], val);
4542 
4543 	/* Determine which antennas are connected. */
4544 	sc->chainmask = sc->rxchainmask;
4545 	for (i = 0; i < 3; i++)
4546 		if (val - calib->rssi[i] > 15 * 20)
4547 			sc->chainmask &= ~(1 << i);
4548 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4549 	    "%s: RX chains mask: theoretical=0x%x, actual=0x%x\n",
4550 	    __func__, sc->rxchainmask, sc->chainmask);
4551 
4552 	/* If none of the TX antennas are connected, keep at least one. */
4553 	if ((sc->chainmask & sc->txchainmask) == 0)
4554 		sc->chainmask |= IWN_LSB(sc->txchainmask);
4555 
4556 	(void)ops->set_gains(sc);
4557 	calib->state = IWN_CALIB_STATE_RUN;
4558 
4559 #ifdef notyet
4560 	/* XXX Disable RX chains with no antennas connected. */
4561 	sc->rxon.rxchain = htole16(IWN_RXCHAIN_SEL(sc->chainmask));
4562 	(void)iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, sc->rxonsz, 1);
4563 #endif
4564 
4565 #if 0
4566 	/* XXX: not yet */
4567 	/* Enable power-saving mode if requested by user. */
4568 	if (sc->sc_ic.ic_flags & IEEE80211_F_PMGTON)
4569 		(void)iwn_set_pslevel(sc, 0, 3, 1);
4570 #endif
4571 }
4572 
4573 static int
4574 iwn4965_init_gains(struct iwn_softc *sc)
4575 {
4576 	struct iwn_phy_calib_gain cmd;
4577 
4578 	memset(&cmd, 0, sizeof cmd);
4579 	cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN;
4580 	/* Differential gains initially set to 0 for all 3 antennas. */
4581 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4582 	    "%s: setting initial differential gains\n", __func__);
4583 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
4584 }
4585 
4586 static int
4587 iwn5000_init_gains(struct iwn_softc *sc)
4588 {
4589 	struct iwn_phy_calib cmd;
4590 
4591 	memset(&cmd, 0, sizeof cmd);
4592 	cmd.code = sc->reset_noise_gain;
4593 	cmd.ngroups = 1;
4594 	cmd.isvalid = 1;
4595 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4596 	    "%s: setting initial differential gains\n", __func__);
4597 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
4598 }
4599 
4600 static int
4601 iwn4965_set_gains(struct iwn_softc *sc)
4602 {
4603 	struct iwn_calib_state *calib = &sc->calib;
4604 	struct iwn_phy_calib_gain cmd;
4605 	int i, delta, noise;
4606 
4607 	/* Get minimal noise among connected antennas. */
4608 	noise = INT_MAX;	/* NB: There's at least one antenna. */
4609 	for (i = 0; i < 3; i++)
4610 		if (sc->chainmask & (1 << i))
4611 			noise = MIN(calib->noise[i], noise);
4612 
4613 	memset(&cmd, 0, sizeof cmd);
4614 	cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN;
4615 	/* Set differential gains for connected antennas. */
4616 	for (i = 0; i < 3; i++) {
4617 		if (sc->chainmask & (1 << i)) {
4618 			/* Compute attenuation (in unit of 1.5dB). */
4619 			delta = (noise - (int32_t)calib->noise[i]) / 30;
4620 			/* NB: delta <= 0 */
4621 			/* Limit to [-4.5dB,0]. */
4622 			cmd.gain[i] = MIN(abs(delta), 3);
4623 			if (delta < 0)
4624 				cmd.gain[i] |= 1 << 2;	/* sign bit */
4625 		}
4626 	}
4627 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4628 	    "setting differential gains Ant A/B/C: %x/%x/%x (%x)\n",
4629 	    cmd.gain[0], cmd.gain[1], cmd.gain[2], sc->chainmask);
4630 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
4631 }
4632 
4633 static int
4634 iwn5000_set_gains(struct iwn_softc *sc)
4635 {
4636 	struct iwn_calib_state *calib = &sc->calib;
4637 	struct iwn_phy_calib_gain cmd;
4638 	int i, ant, div, delta;
4639 
4640 	/* We collected 20 beacons and !=6050 need a 1.5 factor. */
4641 	div = (sc->hw_type == IWN_HW_REV_TYPE_6050) ? 20 : 30;
4642 
4643 	memset(&cmd, 0, sizeof cmd);
4644 	cmd.code = sc->noise_gain;
4645 	cmd.ngroups = 1;
4646 	cmd.isvalid = 1;
4647 	/* Get first available RX antenna as referential. */
4648 	ant = IWN_LSB(sc->rxchainmask);
4649 	/* Set differential gains for other antennas. */
4650 	for (i = ant + 1; i < 3; i++) {
4651 		if (sc->chainmask & (1 << i)) {
4652 			/* The delta is relative to antenna "ant". */
4653 			delta = ((int32_t)calib->noise[ant] -
4654 			    (int32_t)calib->noise[i]) / div;
4655 			/* Limit to [-4.5dB,+4.5dB]. */
4656 			cmd.gain[i - 1] = MIN(abs(delta), 3);
4657 			if (delta < 0)
4658 				cmd.gain[i - 1] |= 1 << 2;	/* sign bit */
4659 		}
4660 	}
4661 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4662 	    "setting differential gains Ant B/C: %x/%x (%x)\n",
4663 	    cmd.gain[0], cmd.gain[1], sc->chainmask);
4664 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
4665 }
4666 
4667 /*
4668  * Tune RF RX sensitivity based on the number of false alarms detected
4669  * during the last beacon period.
4670  */
4671 static void
4672 iwn_tune_sensitivity(struct iwn_softc *sc, const struct iwn_rx_stats *stats)
4673 {
4674 #define inc(val, inc, max)			\
4675 	if ((val) < (max)) {			\
4676 		if ((val) < (max) - (inc))	\
4677 			(val) += (inc);		\
4678 		else				\
4679 			(val) = (max);		\
4680 		needs_update = 1;		\
4681 	}
4682 #define dec(val, dec, min)			\
4683 	if ((val) > (min)) {			\
4684 		if ((val) > (min) + (dec))	\
4685 			(val) -= (dec);		\
4686 		else				\
4687 			(val) = (min);		\
4688 		needs_update = 1;		\
4689 	}
4690 
4691 	const struct iwn_sensitivity_limits *limits = sc->limits;
4692 	struct iwn_calib_state *calib = &sc->calib;
4693 	uint32_t val, rxena, fa;
4694 	uint32_t energy[3], energy_min;
4695 	uint8_t noise[3], noise_ref;
4696 	int i, needs_update = 0;
4697 
4698 	/* Check that we've been enabled long enough. */
4699 	if ((rxena = le32toh(stats->general.load)) == 0)
4700 		return;
4701 
4702 	/* Compute number of false alarms since last call for OFDM. */
4703 	fa  = le32toh(stats->ofdm.bad_plcp) - calib->bad_plcp_ofdm;
4704 	fa += le32toh(stats->ofdm.fa) - calib->fa_ofdm;
4705 	fa *= 200 * IEEE80211_DUR_TU;	/* 200TU */
4706 
4707 	/* Save counters values for next call. */
4708 	calib->bad_plcp_ofdm = le32toh(stats->ofdm.bad_plcp);
4709 	calib->fa_ofdm = le32toh(stats->ofdm.fa);
4710 
4711 	if (fa > 50 * rxena) {
4712 		/* High false alarm count, decrease sensitivity. */
4713 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4714 		    "%s: OFDM high false alarm count: %u\n", __func__, fa);
4715 		inc(calib->ofdm_x1,     1, limits->max_ofdm_x1);
4716 		inc(calib->ofdm_mrc_x1, 1, limits->max_ofdm_mrc_x1);
4717 		inc(calib->ofdm_x4,     1, limits->max_ofdm_x4);
4718 		inc(calib->ofdm_mrc_x4, 1, limits->max_ofdm_mrc_x4);
4719 
4720 	} else if (fa < 5 * rxena) {
4721 		/* Low false alarm count, increase sensitivity. */
4722 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4723 		    "%s: OFDM low false alarm count: %u\n", __func__, fa);
4724 		dec(calib->ofdm_x1,     1, limits->min_ofdm_x1);
4725 		dec(calib->ofdm_mrc_x1, 1, limits->min_ofdm_mrc_x1);
4726 		dec(calib->ofdm_x4,     1, limits->min_ofdm_x4);
4727 		dec(calib->ofdm_mrc_x4, 1, limits->min_ofdm_mrc_x4);
4728 	}
4729 
4730 	/* Compute maximum noise among 3 receivers. */
4731 	for (i = 0; i < 3; i++)
4732 		noise[i] = (le32toh(stats->general.noise[i]) >> 8) & 0xff;
4733 	val = MAX(noise[0], noise[1]);
4734 	val = MAX(noise[2], val);
4735 	/* Insert it into our samples table. */
4736 	calib->noise_samples[calib->cur_noise_sample] = val;
4737 	calib->cur_noise_sample = (calib->cur_noise_sample + 1) % 20;
4738 
4739 	/* Compute maximum noise among last 20 samples. */
4740 	noise_ref = calib->noise_samples[0];
4741 	for (i = 1; i < 20; i++)
4742 		noise_ref = MAX(noise_ref, calib->noise_samples[i]);
4743 
4744 	/* Compute maximum energy among 3 receivers. */
4745 	for (i = 0; i < 3; i++)
4746 		energy[i] = le32toh(stats->general.energy[i]);
4747 	val = MIN(energy[0], energy[1]);
4748 	val = MIN(energy[2], val);
4749 	/* Insert it into our samples table. */
4750 	calib->energy_samples[calib->cur_energy_sample] = val;
4751 	calib->cur_energy_sample = (calib->cur_energy_sample + 1) % 10;
4752 
4753 	/* Compute minimum energy among last 10 samples. */
4754 	energy_min = calib->energy_samples[0];
4755 	for (i = 1; i < 10; i++)
4756 		energy_min = MAX(energy_min, calib->energy_samples[i]);
4757 	energy_min += 6;
4758 
4759 	/* Compute number of false alarms since last call for CCK. */
4760 	fa  = le32toh(stats->cck.bad_plcp) - calib->bad_plcp_cck;
4761 	fa += le32toh(stats->cck.fa) - calib->fa_cck;
4762 	fa *= 200 * IEEE80211_DUR_TU;	/* 200TU */
4763 
4764 	/* Save counters values for next call. */
4765 	calib->bad_plcp_cck = le32toh(stats->cck.bad_plcp);
4766 	calib->fa_cck = le32toh(stats->cck.fa);
4767 
4768 	if (fa > 50 * rxena) {
4769 		/* High false alarm count, decrease sensitivity. */
4770 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4771 		    "%s: CCK high false alarm count: %u\n", __func__, fa);
4772 		calib->cck_state = IWN_CCK_STATE_HIFA;
4773 		calib->low_fa = 0;
4774 
4775 		if (calib->cck_x4 > 160) {
4776 			calib->noise_ref = noise_ref;
4777 			if (calib->energy_cck > 2)
4778 				dec(calib->energy_cck, 2, energy_min);
4779 		}
4780 		if (calib->cck_x4 < 160) {
4781 			calib->cck_x4 = 161;
4782 			needs_update = 1;
4783 		} else
4784 			inc(calib->cck_x4, 3, limits->max_cck_x4);
4785 
4786 		inc(calib->cck_mrc_x4, 3, limits->max_cck_mrc_x4);
4787 
4788 	} else if (fa < 5 * rxena) {
4789 		/* Low false alarm count, increase sensitivity. */
4790 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4791 		    "%s: CCK low false alarm count: %u\n", __func__, fa);
4792 		calib->cck_state = IWN_CCK_STATE_LOFA;
4793 		calib->low_fa++;
4794 
4795 		if (calib->cck_state != IWN_CCK_STATE_INIT &&
4796 		    (((int32_t)calib->noise_ref - (int32_t)noise_ref) > 2 ||
4797 		     calib->low_fa > 100)) {
4798 			inc(calib->energy_cck, 2, limits->min_energy_cck);
4799 			dec(calib->cck_x4,     3, limits->min_cck_x4);
4800 			dec(calib->cck_mrc_x4, 3, limits->min_cck_mrc_x4);
4801 		}
4802 	} else {
4803 		/* Not worth to increase or decrease sensitivity. */
4804 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4805 		    "%s: CCK normal false alarm count: %u\n", __func__, fa);
4806 		calib->low_fa = 0;
4807 		calib->noise_ref = noise_ref;
4808 
4809 		if (calib->cck_state == IWN_CCK_STATE_HIFA) {
4810 			/* Previous interval had many false alarms. */
4811 			dec(calib->energy_cck, 8, energy_min);
4812 		}
4813 		calib->cck_state = IWN_CCK_STATE_INIT;
4814 	}
4815 
4816 	if (needs_update)
4817 		(void)iwn_send_sensitivity(sc);
4818 #undef dec
4819 #undef inc
4820 }
4821 
4822 static int
4823 iwn_send_sensitivity(struct iwn_softc *sc)
4824 {
4825 	struct iwn_calib_state *calib = &sc->calib;
4826 	struct iwn_enhanced_sensitivity_cmd cmd;
4827 	int len;
4828 
4829 	memset(&cmd, 0, sizeof cmd);
4830 	len = sizeof (struct iwn_sensitivity_cmd);
4831 	cmd.which = IWN_SENSITIVITY_WORKTBL;
4832 	/* OFDM modulation. */
4833 	cmd.corr_ofdm_x1       = htole16(calib->ofdm_x1);
4834 	cmd.corr_ofdm_mrc_x1   = htole16(calib->ofdm_mrc_x1);
4835 	cmd.corr_ofdm_x4       = htole16(calib->ofdm_x4);
4836 	cmd.corr_ofdm_mrc_x4   = htole16(calib->ofdm_mrc_x4);
4837 	cmd.energy_ofdm        = htole16(sc->limits->energy_ofdm);
4838 	cmd.energy_ofdm_th     = htole16(62);
4839 	/* CCK modulation. */
4840 	cmd.corr_cck_x4        = htole16(calib->cck_x4);
4841 	cmd.corr_cck_mrc_x4    = htole16(calib->cck_mrc_x4);
4842 	cmd.energy_cck         = htole16(calib->energy_cck);
4843 	/* Barker modulation: use default values. */
4844 	cmd.corr_barker        = htole16(190);
4845 	cmd.corr_barker_mrc    = htole16(390);
4846 
4847 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
4848 	    "%s: set sensitivity %d/%d/%d/%d/%d/%d/%d\n", __func__,
4849 	    calib->ofdm_x1, calib->ofdm_mrc_x1, calib->ofdm_x4,
4850 	    calib->ofdm_mrc_x4, calib->cck_x4,
4851 	    calib->cck_mrc_x4, calib->energy_cck);
4852 
4853 	if (!(sc->sc_flags & IWN_FLAG_ENH_SENS))
4854 		goto send;
4855 	/* Enhanced sensitivity settings. */
4856 	len = sizeof (struct iwn_enhanced_sensitivity_cmd);
4857 	cmd.ofdm_det_slope_mrc = htole16(668);
4858 	cmd.ofdm_det_icept_mrc = htole16(4);
4859 	cmd.ofdm_det_slope     = htole16(486);
4860 	cmd.ofdm_det_icept     = htole16(37);
4861 	cmd.cck_det_slope_mrc  = htole16(853);
4862 	cmd.cck_det_icept_mrc  = htole16(4);
4863 	cmd.cck_det_slope      = htole16(476);
4864 	cmd.cck_det_icept      = htole16(99);
4865 send:
4866 	return iwn_cmd(sc, IWN_CMD_SET_SENSITIVITY, &cmd, len, 1);
4867 }
4868 
4869 /*
4870  * Set STA mode power saving level (between 0 and 5).
4871  * Level 0 is CAM (Continuously Aware Mode), 5 is for maximum power saving.
4872  */
4873 static int
4874 iwn_set_pslevel(struct iwn_softc *sc, int dtim, int level, int async)
4875 {
4876 	struct iwn_pmgt_cmd cmd;
4877 	const struct iwn_pmgt *pmgt;
4878 	uint32_t max, skip_dtim;
4879 	uint32_t reg;
4880 	int i;
4881 
4882 	/* Select which PS parameters to use. */
4883 	if (dtim <= 2)
4884 		pmgt = &iwn_pmgt[0][level];
4885 	else if (dtim <= 10)
4886 		pmgt = &iwn_pmgt[1][level];
4887 	else
4888 		pmgt = &iwn_pmgt[2][level];
4889 
4890 	memset(&cmd, 0, sizeof cmd);
4891 	if (level != 0)	/* not CAM */
4892 		cmd.flags |= htole16(IWN_PS_ALLOW_SLEEP);
4893 	if (level == 5)
4894 		cmd.flags |= htole16(IWN_PS_FAST_PD);
4895 	/* Retrieve PCIe Active State Power Management (ASPM). */
4896 	reg = pci_read_config(sc->sc_dev, sc->sc_cap_off + 0x10, 1);
4897 	if (!(reg & 0x1))	/* L0s Entry disabled. */
4898 		cmd.flags |= htole16(IWN_PS_PCI_PMGT);
4899 	cmd.rxtimeout = htole32(pmgt->rxtimeout * 1024);
4900 	cmd.txtimeout = htole32(pmgt->txtimeout * 1024);
4901 
4902 	if (dtim == 0) {
4903 		dtim = 1;
4904 		skip_dtim = 0;
4905 	} else
4906 		skip_dtim = pmgt->skip_dtim;
4907 	if (skip_dtim != 0) {
4908 		cmd.flags |= htole16(IWN_PS_SLEEP_OVER_DTIM);
4909 		max = pmgt->intval[4];
4910 		if (max == (uint32_t)-1)
4911 			max = dtim * (skip_dtim + 1);
4912 		else if (max > dtim)
4913 			max = (max / dtim) * dtim;
4914 	} else
4915 		max = dtim;
4916 	for (i = 0; i < 5; i++)
4917 		cmd.intval[i] = htole32(MIN(max, pmgt->intval[i]));
4918 
4919 	DPRINTF(sc, IWN_DEBUG_RESET, "setting power saving level to %d\n",
4920 	    level);
4921 	return iwn_cmd(sc, IWN_CMD_SET_POWER_MODE, &cmd, sizeof cmd, async);
4922 }
4923 
4924 static int
4925 iwn_send_btcoex(struct iwn_softc *sc)
4926 {
4927 	struct iwn_bluetooth cmd;
4928 
4929 	memset(&cmd, 0, sizeof cmd);
4930 	cmd.flags = IWN_BT_COEX_CHAN_ANN | IWN_BT_COEX_BT_PRIO;
4931 	cmd.lead_time = IWN_BT_LEAD_TIME_DEF;
4932 	cmd.max_kill = IWN_BT_MAX_KILL_DEF;
4933 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: configuring bluetooth coexistence\n",
4934 	    __func__);
4935 	return iwn_cmd(sc, IWN_CMD_BT_COEX, &cmd, sizeof(cmd), 0);
4936 }
4937 
4938 static int
4939 iwn_send_advanced_btcoex(struct iwn_softc *sc)
4940 {
4941 	static const uint32_t btcoex_3wire[12] = {
4942 		0xaaaaaaaa, 0xaaaaaaaa, 0xaeaaaaaa, 0xaaaaaaaa,
4943 		0xcc00ff28, 0x0000aaaa, 0xcc00aaaa, 0x0000aaaa,
4944 		0xc0004000, 0x00004000, 0xf0005000, 0xf0005000,
4945 	};
4946 	struct iwn6000_btcoex_config btconfig;
4947 	struct iwn_btcoex_priotable btprio;
4948 	struct iwn_btcoex_prot btprot;
4949 	int error, i;
4950 
4951 	memset(&btconfig, 0, sizeof btconfig);
4952 	btconfig.flags = 145;
4953 	btconfig.max_kill = 5;
4954 	btconfig.bt3_t7_timer = 1;
4955 	btconfig.kill_ack = htole32(0xffff0000);
4956 	btconfig.kill_cts = htole32(0xffff0000);
4957 	btconfig.sample_time = 2;
4958 	btconfig.bt3_t2_timer = 0xc;
4959 	for (i = 0; i < 12; i++)
4960 		btconfig.lookup_table[i] = htole32(btcoex_3wire[i]);
4961 	btconfig.valid = htole16(0xff);
4962 	btconfig.prio_boost = 0xf0;
4963 	DPRINTF(sc, IWN_DEBUG_RESET,
4964 	    "%s: configuring advanced bluetooth coexistence\n", __func__);
4965 	error = iwn_cmd(sc, IWN_CMD_BT_COEX, &btconfig, sizeof(btconfig), 1);
4966 	if (error != 0)
4967 		return error;
4968 
4969 	memset(&btprio, 0, sizeof btprio);
4970 	btprio.calib_init1 = 0x6;
4971 	btprio.calib_init2 = 0x7;
4972 	btprio.calib_periodic_low1 = 0x2;
4973 	btprio.calib_periodic_low2 = 0x3;
4974 	btprio.calib_periodic_high1 = 0x4;
4975 	btprio.calib_periodic_high2 = 0x5;
4976 	btprio.dtim = 0x6;
4977 	btprio.scan52 = 0x8;
4978 	btprio.scan24 = 0xa;
4979 	error = iwn_cmd(sc, IWN_CMD_BT_COEX_PRIOTABLE, &btprio, sizeof(btprio),
4980 	    1);
4981 	if (error != 0)
4982 		return error;
4983 
4984 	/* Force BT state machine change. */
4985 	memset(&btprot, 0, sizeof btprio);
4986 	btprot.open = 1;
4987 	btprot.type = 1;
4988 	error = iwn_cmd(sc, IWN_CMD_BT_COEX_PROT, &btprot, sizeof(btprot), 1);
4989 	if (error != 0)
4990 		return error;
4991 	btprot.open = 0;
4992 	return iwn_cmd(sc, IWN_CMD_BT_COEX_PROT, &btprot, sizeof(btprot), 1);
4993 }
4994 
4995 static int
4996 iwn5000_runtime_calib(struct iwn_softc *sc)
4997 {
4998 	struct iwn5000_calib_config cmd;
4999 
5000 	memset(&cmd, 0, sizeof cmd);
5001 	cmd.ucode.once.enable = 0xffffffff;
5002 	cmd.ucode.once.start = IWN5000_CALIB_DC;
5003 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
5004 	    "%s: configuring runtime calibration\n", __func__);
5005 	return iwn_cmd(sc, IWN5000_CMD_CALIB_CONFIG, &cmd, sizeof(cmd), 0);
5006 }
5007 
5008 static int
5009 iwn_config(struct iwn_softc *sc)
5010 {
5011 	struct iwn_ops *ops = &sc->ops;
5012 	struct ifnet *ifp = sc->sc_ifp;
5013 	struct ieee80211com *ic = ifp->if_l2com;
5014 	uint32_t txmask;
5015 	uint16_t rxchain;
5016 	int error;
5017 
5018 	if (sc->hw_type == IWN_HW_REV_TYPE_6005) {
5019 		/* Set radio temperature sensor offset. */
5020 		error = iwn5000_temp_offset_calib(sc);
5021 		if (error != 0) {
5022 			device_printf(sc->sc_dev,
5023 			    "%s: could not set temperature offset\n", __func__);
5024 			return error;
5025 		}
5026 	}
5027 
5028 	if (sc->hw_type == IWN_HW_REV_TYPE_6050) {
5029 		/* Configure runtime DC calibration. */
5030 		error = iwn5000_runtime_calib(sc);
5031 		if (error != 0) {
5032 			device_printf(sc->sc_dev,
5033 			    "%s: could not configure runtime calibration\n",
5034 			    __func__);
5035 			return error;
5036 		}
5037 	}
5038 
5039 	/* Configure valid TX chains for >=5000 Series. */
5040 	if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
5041 		txmask = htole32(sc->txchainmask);
5042 		DPRINTF(sc, IWN_DEBUG_RESET,
5043 		    "%s: configuring valid TX chains 0x%x\n", __func__, txmask);
5044 		error = iwn_cmd(sc, IWN5000_CMD_TX_ANT_CONFIG, &txmask,
5045 		    sizeof txmask, 0);
5046 		if (error != 0) {
5047 			device_printf(sc->sc_dev,
5048 			    "%s: could not configure valid TX chains, "
5049 			    "error %d\n", __func__, error);
5050 			return error;
5051 		}
5052 	}
5053 
5054 	/* Configure bluetooth coexistence. */
5055 	if (sc->sc_flags & IWN_FLAG_ADV_BTCOEX)
5056 		error = iwn_send_advanced_btcoex(sc);
5057 	else
5058 		error = iwn_send_btcoex(sc);
5059 	if (error != 0) {
5060 		device_printf(sc->sc_dev,
5061 		    "%s: could not configure bluetooth coexistence, error %d\n",
5062 		    __func__, error);
5063 		return error;
5064 	}
5065 
5066 	/* Set mode, channel, RX filter and enable RX. */
5067 	memset(&sc->rxon, 0, sizeof (struct iwn_rxon));
5068 	IEEE80211_ADDR_COPY(sc->rxon.myaddr, IF_LLADDR(ifp));
5069 	IEEE80211_ADDR_COPY(sc->rxon.wlap, IF_LLADDR(ifp));
5070 	sc->rxon.chan = ieee80211_chan2ieee(ic, ic->ic_curchan);
5071 	sc->rxon.flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
5072 	if (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
5073 		sc->rxon.flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
5074 	switch (ic->ic_opmode) {
5075 	case IEEE80211_M_STA:
5076 		sc->rxon.mode = IWN_MODE_STA;
5077 		sc->rxon.filter = htole32(IWN_FILTER_MULTICAST);
5078 		break;
5079 	case IEEE80211_M_MONITOR:
5080 		sc->rxon.mode = IWN_MODE_MONITOR;
5081 		sc->rxon.filter = htole32(IWN_FILTER_MULTICAST |
5082 		    IWN_FILTER_CTL | IWN_FILTER_PROMISC);
5083 		break;
5084 	default:
5085 		/* Should not get there. */
5086 		break;
5087 	}
5088 	sc->rxon.cck_mask  = 0x0f;	/* not yet negotiated */
5089 	sc->rxon.ofdm_mask = 0xff;	/* not yet negotiated */
5090 	sc->rxon.ht_single_mask = 0xff;
5091 	sc->rxon.ht_dual_mask = 0xff;
5092 	sc->rxon.ht_triple_mask = 0xff;
5093 	rxchain =
5094 	    IWN_RXCHAIN_VALID(sc->rxchainmask) |
5095 	    IWN_RXCHAIN_MIMO_COUNT(2) |
5096 	    IWN_RXCHAIN_IDLE_COUNT(2);
5097 	sc->rxon.rxchain = htole16(rxchain);
5098 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: setting configuration\n", __func__);
5099 	error = iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, sc->rxonsz, 0);
5100 	if (error != 0) {
5101 		device_printf(sc->sc_dev, "%s: RXON command failed\n",
5102 		    __func__);
5103 		return error;
5104 	}
5105 
5106 	if ((error = iwn_add_broadcast_node(sc, 0)) != 0) {
5107 		device_printf(sc->sc_dev, "%s: could not add broadcast node\n",
5108 		    __func__);
5109 		return error;
5110 	}
5111 
5112 	/* Configuration has changed, set TX power accordingly. */
5113 	if ((error = ops->set_txpower(sc, ic->ic_curchan, 0)) != 0) {
5114 		device_printf(sc->sc_dev, "%s: could not set TX power\n",
5115 		    __func__);
5116 		return error;
5117 	}
5118 
5119 	if ((error = iwn_set_critical_temp(sc)) != 0) {
5120 		device_printf(sc->sc_dev,
5121 		    "%s: could not set critical temperature\n", __func__);
5122 		return error;
5123 	}
5124 
5125 	/* Set power saving level to CAM during initialization. */
5126 	if ((error = iwn_set_pslevel(sc, 0, 0, 0)) != 0) {
5127 		device_printf(sc->sc_dev,
5128 		    "%s: could not set power saving level\n", __func__);
5129 		return error;
5130 	}
5131 	return 0;
5132 }
5133 
5134 /*
5135  * Add an ssid element to a frame.
5136  */
5137 static uint8_t *
5138 ieee80211_add_ssid(uint8_t *frm, const uint8_t *ssid, u_int len)
5139 {
5140 	*frm++ = IEEE80211_ELEMID_SSID;
5141 	*frm++ = len;
5142 	memcpy(frm, ssid, len);
5143 	return frm + len;
5144 }
5145 
5146 static int
5147 iwn_scan(struct iwn_softc *sc)
5148 {
5149 	struct ifnet *ifp = sc->sc_ifp;
5150 	struct ieee80211com *ic = ifp->if_l2com;
5151 	struct ieee80211_scan_state *ss = ic->ic_scan;	/*XXX*/
5152 	struct ieee80211_node *ni = ss->ss_vap->iv_bss;
5153 	struct iwn_scan_hdr *hdr;
5154 	struct iwn_cmd_data *tx;
5155 	struct iwn_scan_essid *essid;
5156 	struct iwn_scan_chan *chan;
5157 	struct ieee80211_frame *wh;
5158 	struct ieee80211_rateset *rs;
5159 	struct ieee80211_channel *c;
5160 	uint8_t *buf, *frm;
5161 	uint16_t rxchain;
5162 	uint8_t txant;
5163 	int buflen, error;
5164 
5165 	buf = malloc(IWN_SCAN_MAXSZ, M_DEVBUF, M_NOWAIT | M_ZERO);
5166 	if (buf == NULL) {
5167 		device_printf(sc->sc_dev,
5168 		    "%s: could not allocate buffer for scan command\n",
5169 		    __func__);
5170 		return ENOMEM;
5171 	}
5172 	hdr = (struct iwn_scan_hdr *)buf;
5173 	/*
5174 	 * Move to the next channel if no frames are received within 10ms
5175 	 * after sending the probe request.
5176 	 */
5177 	hdr->quiet_time = htole16(10);		/* timeout in milliseconds */
5178 	hdr->quiet_threshold = htole16(1);	/* min # of packets */
5179 
5180 	/* Select antennas for scanning. */
5181 	rxchain =
5182 	    IWN_RXCHAIN_VALID(sc->rxchainmask) |
5183 	    IWN_RXCHAIN_FORCE_MIMO_SEL(sc->rxchainmask) |
5184 	    IWN_RXCHAIN_DRIVER_FORCE;
5185 	if (IEEE80211_IS_CHAN_A(ic->ic_curchan) &&
5186 	    sc->hw_type == IWN_HW_REV_TYPE_4965) {
5187 		/* Ant A must be avoided in 5GHz because of an HW bug. */
5188 		rxchain |= IWN_RXCHAIN_FORCE_SEL(IWN_ANT_B);
5189 	} else	/* Use all available RX antennas. */
5190 		rxchain |= IWN_RXCHAIN_FORCE_SEL(sc->rxchainmask);
5191 	hdr->rxchain = htole16(rxchain);
5192 	hdr->filter = htole32(IWN_FILTER_MULTICAST | IWN_FILTER_BEACON);
5193 
5194 	tx = (struct iwn_cmd_data *)(hdr + 1);
5195 	tx->flags = htole32(IWN_TX_AUTO_SEQ);
5196 	tx->id = sc->broadcast_id;
5197 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
5198 
5199 	if (IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan)) {
5200 		/* Send probe requests at 6Mbps. */
5201 		tx->rate = htole32(0xd);
5202 		rs = &ic->ic_sup_rates[IEEE80211_MODE_11A];
5203 	} else {
5204 		hdr->flags = htole32(IWN_RXON_24GHZ | IWN_RXON_AUTO);
5205 		if (sc->hw_type == IWN_HW_REV_TYPE_4965 &&
5206 		    sc->rxon.associd && sc->rxon.chan > 14)
5207 			tx->rate = htole32(0xd);
5208 		else {
5209 			/* Send probe requests at 1Mbps. */
5210 			tx->rate = htole32(10 | IWN_RFLAG_CCK);
5211 		}
5212 		rs = &ic->ic_sup_rates[IEEE80211_MODE_11G];
5213 	}
5214 	/* Use the first valid TX antenna. */
5215 	txant = IWN_LSB(sc->txchainmask);
5216 	tx->rate |= htole32(IWN_RFLAG_ANT(txant));
5217 
5218 	essid = (struct iwn_scan_essid *)(tx + 1);
5219 	if (ss->ss_ssid[0].len != 0) {
5220 		essid[0].id = IEEE80211_ELEMID_SSID;
5221 		essid[0].len = ss->ss_ssid[0].len;
5222 		memcpy(essid[0].data, ss->ss_ssid[0].ssid, ss->ss_ssid[0].len);
5223 	}
5224 	/*
5225 	 * Build a probe request frame.  Most of the following code is a
5226 	 * copy & paste of what is done in net80211.
5227 	 */
5228 	wh = (struct ieee80211_frame *)(essid + 20);
5229 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
5230 	    IEEE80211_FC0_SUBTYPE_PROBE_REQ;
5231 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
5232 	IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
5233 	IEEE80211_ADDR_COPY(wh->i_addr2, IF_LLADDR(ifp));
5234 	IEEE80211_ADDR_COPY(wh->i_addr3, ifp->if_broadcastaddr);
5235 	*(uint16_t *)&wh->i_dur[0] = 0;	/* filled by HW */
5236 	*(uint16_t *)&wh->i_seq[0] = 0;	/* filled by HW */
5237 
5238 	frm = (uint8_t *)(wh + 1);
5239 	frm = ieee80211_add_ssid(frm, NULL, 0);
5240 	frm = ieee80211_add_rates(frm, rs);
5241 	if (rs->rs_nrates > IEEE80211_RATE_SIZE)
5242 		frm = ieee80211_add_xrates(frm, rs);
5243 	if (ic->ic_htcaps & IEEE80211_HTC_HT)
5244 		frm = ieee80211_add_htcap(frm, ni);
5245 
5246 	/* Set length of probe request. */
5247 	tx->len = htole16(frm - (uint8_t *)wh);
5248 
5249 	c = ic->ic_curchan;
5250 	chan = (struct iwn_scan_chan *)frm;
5251 	chan->chan = htole16(ieee80211_chan2ieee(ic, c));
5252 	chan->flags = 0;
5253 	if (ss->ss_nssid > 0)
5254 		chan->flags |= htole32(IWN_CHAN_NPBREQS(1));
5255 	chan->dsp_gain = 0x6e;
5256 	if (IEEE80211_IS_CHAN_5GHZ(c) &&
5257 	    !(c->ic_flags & IEEE80211_CHAN_PASSIVE)) {
5258 		chan->rf_gain = 0x3b;
5259 		chan->active  = htole16(24);
5260 		chan->passive = htole16(110);
5261 		chan->flags |= htole32(IWN_CHAN_ACTIVE);
5262 	} else if (IEEE80211_IS_CHAN_5GHZ(c)) {
5263 		chan->rf_gain = 0x3b;
5264 		chan->active  = htole16(24);
5265 		if (sc->rxon.associd)
5266 			chan->passive = htole16(78);
5267 		else
5268 			chan->passive = htole16(110);
5269 		hdr->crc_threshold = 0xffff;
5270 	} else if (!(c->ic_flags & IEEE80211_CHAN_PASSIVE)) {
5271 		chan->rf_gain = 0x28;
5272 		chan->active  = htole16(36);
5273 		chan->passive = htole16(120);
5274 		chan->flags |= htole32(IWN_CHAN_ACTIVE);
5275 	} else {
5276 		chan->rf_gain = 0x28;
5277 		chan->active  = htole16(36);
5278 		if (sc->rxon.associd)
5279 			chan->passive = htole16(88);
5280 		else
5281 			chan->passive = htole16(120);
5282 		hdr->crc_threshold = 0xffff;
5283 	}
5284 
5285 	DPRINTF(sc, IWN_DEBUG_STATE,
5286 	    "%s: chan %u flags 0x%x rf_gain 0x%x "
5287 	    "dsp_gain 0x%x active 0x%x passive 0x%x\n", __func__,
5288 	    chan->chan, chan->flags, chan->rf_gain, chan->dsp_gain,
5289 	    chan->active, chan->passive);
5290 
5291 	hdr->nchan++;
5292 	chan++;
5293 	buflen = (uint8_t *)chan - buf;
5294 	hdr->len = htole16(buflen);
5295 
5296 	DPRINTF(sc, IWN_DEBUG_STATE, "sending scan command nchan=%d\n",
5297 	    hdr->nchan);
5298 	error = iwn_cmd(sc, IWN_CMD_SCAN, buf, buflen, 1);
5299 	free(buf, M_DEVBUF);
5300 	return error;
5301 }
5302 
5303 static int
5304 iwn_auth(struct iwn_softc *sc, struct ieee80211vap *vap)
5305 {
5306 	struct iwn_ops *ops = &sc->ops;
5307 	struct ifnet *ifp = sc->sc_ifp;
5308 	struct ieee80211com *ic = ifp->if_l2com;
5309 	struct ieee80211_node *ni = vap->iv_bss;
5310 	int error;
5311 
5312 	/* Update adapter configuration. */
5313 	IEEE80211_ADDR_COPY(sc->rxon.bssid, ni->ni_bssid);
5314 	sc->rxon.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
5315 	sc->rxon.flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
5316 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
5317 		sc->rxon.flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
5318 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
5319 		sc->rxon.flags |= htole32(IWN_RXON_SHSLOT);
5320 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
5321 		sc->rxon.flags |= htole32(IWN_RXON_SHPREAMBLE);
5322 	if (IEEE80211_IS_CHAN_A(ni->ni_chan)) {
5323 		sc->rxon.cck_mask  = 0;
5324 		sc->rxon.ofdm_mask = 0x15;
5325 	} else if (IEEE80211_IS_CHAN_B(ni->ni_chan)) {
5326 		sc->rxon.cck_mask  = 0x03;
5327 		sc->rxon.ofdm_mask = 0;
5328 	} else {
5329 		/* Assume 802.11b/g. */
5330 		sc->rxon.cck_mask  = 0x0f;
5331 		sc->rxon.ofdm_mask = 0x15;
5332 	}
5333 	DPRINTF(sc, IWN_DEBUG_STATE, "rxon chan %d flags %x cck %x ofdm %x\n",
5334 	    sc->rxon.chan, sc->rxon.flags, sc->rxon.cck_mask,
5335 	    sc->rxon.ofdm_mask);
5336 	error = iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, sc->rxonsz, 1);
5337 	if (error != 0) {
5338 		device_printf(sc->sc_dev, "%s: RXON command failed, error %d\n",
5339 		    __func__, error);
5340 		return error;
5341 	}
5342 
5343 	/* Configuration has changed, set TX power accordingly. */
5344 	if ((error = ops->set_txpower(sc, ni->ni_chan, 1)) != 0) {
5345 		device_printf(sc->sc_dev,
5346 		    "%s: could not set TX power, error %d\n", __func__, error);
5347 		return error;
5348 	}
5349 	/*
5350 	 * Reconfiguring RXON clears the firmware nodes table so we must
5351 	 * add the broadcast node again.
5352 	 */
5353 	if ((error = iwn_add_broadcast_node(sc, 1)) != 0) {
5354 		device_printf(sc->sc_dev,
5355 		    "%s: could not add broadcast node, error %d\n", __func__,
5356 		    error);
5357 		return error;
5358 	}
5359 	return 0;
5360 }
5361 
5362 static int
5363 iwn_run(struct iwn_softc *sc, struct ieee80211vap *vap)
5364 {
5365 	struct iwn_ops *ops = &sc->ops;
5366 	struct ifnet *ifp = sc->sc_ifp;
5367 	struct ieee80211com *ic = ifp->if_l2com;
5368 	struct ieee80211_node *ni = vap->iv_bss;
5369 	struct iwn_node_info node;
5370 	uint32_t htflags = 0;
5371 	int error;
5372 
5373 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
5374 		/* Link LED blinks while monitoring. */
5375 		iwn_set_led(sc, IWN_LED_LINK, 5, 5);
5376 		return 0;
5377 	}
5378 	if ((error = iwn_set_timing(sc, ni)) != 0) {
5379 		device_printf(sc->sc_dev,
5380 		    "%s: could not set timing, error %d\n", __func__, error);
5381 		return error;
5382 	}
5383 
5384 	/* Update adapter configuration. */
5385 	IEEE80211_ADDR_COPY(sc->rxon.bssid, ni->ni_bssid);
5386 	sc->rxon.associd = htole16(IEEE80211_AID(ni->ni_associd));
5387 	sc->rxon.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
5388 	sc->rxon.flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
5389 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
5390 		sc->rxon.flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
5391 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
5392 		sc->rxon.flags |= htole32(IWN_RXON_SHSLOT);
5393 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
5394 		sc->rxon.flags |= htole32(IWN_RXON_SHPREAMBLE);
5395 	if (IEEE80211_IS_CHAN_A(ni->ni_chan)) {
5396 		sc->rxon.cck_mask  = 0;
5397 		sc->rxon.ofdm_mask = 0x15;
5398 	} else if (IEEE80211_IS_CHAN_B(ni->ni_chan)) {
5399 		sc->rxon.cck_mask  = 0x03;
5400 		sc->rxon.ofdm_mask = 0;
5401 	} else {
5402 		/* Assume 802.11b/g. */
5403 		sc->rxon.cck_mask  = 0x0f;
5404 		sc->rxon.ofdm_mask = 0x15;
5405 	}
5406 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan)) {
5407 		htflags |= IWN_RXON_HT_PROTMODE(ic->ic_curhtprotmode);
5408 		if (IEEE80211_IS_CHAN_HT40(ni->ni_chan)) {
5409 			switch (ic->ic_curhtprotmode) {
5410 			case IEEE80211_HTINFO_OPMODE_HT20PR:
5411 				htflags |= IWN_RXON_HT_MODEPURE40;
5412 				break;
5413 			default:
5414 				htflags |= IWN_RXON_HT_MODEMIXED;
5415 				break;
5416 			}
5417 		}
5418 		if (IEEE80211_IS_CHAN_HT40D(ni->ni_chan))
5419 			htflags |= IWN_RXON_HT_HT40MINUS;
5420 	}
5421 	sc->rxon.flags |= htole32(htflags);
5422 	sc->rxon.filter |= htole32(IWN_FILTER_BSS);
5423 	DPRINTF(sc, IWN_DEBUG_STATE, "rxon chan %d flags %x\n",
5424 	    sc->rxon.chan, sc->rxon.flags);
5425 	error = iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, sc->rxonsz, 1);
5426 	if (error != 0) {
5427 		device_printf(sc->sc_dev,
5428 		    "%s: could not update configuration, error %d\n", __func__,
5429 		    error);
5430 		return error;
5431 	}
5432 
5433 	/* Configuration has changed, set TX power accordingly. */
5434 	if ((error = ops->set_txpower(sc, ni->ni_chan, 1)) != 0) {
5435 		device_printf(sc->sc_dev,
5436 		    "%s: could not set TX power, error %d\n", __func__, error);
5437 		return error;
5438 	}
5439 
5440 	/* Fake a join to initialize the TX rate. */
5441 	((struct iwn_node *)ni)->id = IWN_ID_BSS;
5442 	iwn_newassoc(ni, 1);
5443 
5444 	/* Add BSS node. */
5445 	memset(&node, 0, sizeof node);
5446 	IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr);
5447 	node.id = IWN_ID_BSS;
5448 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan)) {
5449 		switch (ni->ni_htcap & IEEE80211_HTCAP_SMPS) {
5450 		case IEEE80211_HTCAP_SMPS_ENA:
5451 			node.htflags |= htole32(IWN_SMPS_MIMO_DIS);
5452 			break;
5453 		case IEEE80211_HTCAP_SMPS_DYNAMIC:
5454 			node.htflags |= htole32(IWN_SMPS_MIMO_PROT);
5455 			break;
5456 		}
5457 		node.htflags |= htole32(IWN_AMDPU_SIZE_FACTOR(3) |
5458 		    IWN_AMDPU_DENSITY(5));	/* 4us */
5459 		if (IEEE80211_IS_CHAN_HT40(ni->ni_chan))
5460 			node.htflags |= htole32(IWN_NODE_HT40);
5461 	}
5462 	DPRINTF(sc, IWN_DEBUG_STATE, "%s: adding BSS node\n", __func__);
5463 	error = ops->add_node(sc, &node, 1);
5464 	if (error != 0) {
5465 		device_printf(sc->sc_dev,
5466 		    "%s: could not add BSS node, error %d\n", __func__, error);
5467 		return error;
5468 	}
5469 	DPRINTF(sc, IWN_DEBUG_STATE, "%s: setting link quality for node %d\n",
5470 	    __func__, node.id);
5471 	if ((error = iwn_set_link_quality(sc, ni)) != 0) {
5472 		device_printf(sc->sc_dev,
5473 		    "%s: could not setup link quality for node %d, error %d\n",
5474 		    __func__, node.id, error);
5475 		return error;
5476 	}
5477 
5478 	if ((error = iwn_init_sensitivity(sc)) != 0) {
5479 		device_printf(sc->sc_dev,
5480 		    "%s: could not set sensitivity, error %d\n", __func__,
5481 		    error);
5482 		return error;
5483 	}
5484 	/* Start periodic calibration timer. */
5485 	sc->calib.state = IWN_CALIB_STATE_ASSOC;
5486 	sc->calib_cnt = 0;
5487 	callout_reset(&sc->calib_to, msecs_to_ticks(500), iwn_calib_timeout,
5488 	    sc);
5489 
5490 	/* Link LED always on while associated. */
5491 	iwn_set_led(sc, IWN_LED_LINK, 0, 1);
5492 	return 0;
5493 }
5494 
5495 /*
5496  * This function is called by upper layer when an ADDBA request is received
5497  * from another STA and before the ADDBA response is sent.
5498  */
5499 static int
5500 iwn_ampdu_rx_start(struct ieee80211_node *ni, struct ieee80211_rx_ampdu *rap,
5501     int baparamset, int batimeout, int baseqctl)
5502 {
5503 #define MS(_v, _f)	(((_v) & _f) >> _f##_S)
5504 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
5505 	struct iwn_ops *ops = &sc->ops;
5506 	struct iwn_node *wn = (void *)ni;
5507 	struct iwn_node_info node;
5508 	uint16_t ssn;
5509 	uint8_t tid;
5510 	int error;
5511 
5512 	tid = MS(le16toh(baparamset), IEEE80211_BAPS_TID);
5513 	ssn = MS(le16toh(baseqctl), IEEE80211_BASEQ_START);
5514 
5515 	memset(&node, 0, sizeof node);
5516 	node.id = wn->id;
5517 	node.control = IWN_NODE_UPDATE;
5518 	node.flags = IWN_FLAG_SET_ADDBA;
5519 	node.addba_tid = tid;
5520 	node.addba_ssn = htole16(ssn);
5521 	DPRINTF(sc, IWN_DEBUG_RECV, "ADDBA RA=%d TID=%d SSN=%d\n",
5522 	    wn->id, tid, ssn);
5523 	error = ops->add_node(sc, &node, 1);
5524 	if (error != 0)
5525 		return error;
5526 	return sc->sc_ampdu_rx_start(ni, rap, baparamset, batimeout, baseqctl);
5527 #undef MS
5528 }
5529 
5530 /*
5531  * This function is called by upper layer on teardown of an HT-immediate
5532  * Block Ack agreement (eg. uppon receipt of a DELBA frame).
5533  */
5534 static void
5535 iwn_ampdu_rx_stop(struct ieee80211_node *ni, struct ieee80211_rx_ampdu *rap)
5536 {
5537 	struct ieee80211com *ic = ni->ni_ic;
5538 	struct iwn_softc *sc = ic->ic_ifp->if_softc;
5539 	struct iwn_ops *ops = &sc->ops;
5540 	struct iwn_node *wn = (void *)ni;
5541 	struct iwn_node_info node;
5542 	uint8_t tid;
5543 
5544 	/* XXX: tid as an argument */
5545 	for (tid = 0; tid < WME_NUM_TID; tid++) {
5546 		if (&ni->ni_rx_ampdu[tid] == rap)
5547 			break;
5548 	}
5549 
5550 	memset(&node, 0, sizeof node);
5551 	node.id = wn->id;
5552 	node.control = IWN_NODE_UPDATE;
5553 	node.flags = IWN_FLAG_SET_DELBA;
5554 	node.delba_tid = tid;
5555 	DPRINTF(sc, IWN_DEBUG_RECV, "DELBA RA=%d TID=%d\n", wn->id, tid);
5556 	(void)ops->add_node(sc, &node, 1);
5557 	sc->sc_ampdu_rx_stop(ni, rap);
5558 }
5559 
5560 static int
5561 iwn_addba_request(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
5562     int dialogtoken, int baparamset, int batimeout)
5563 {
5564 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
5565 	int qid;
5566 
5567 	for (qid = sc->firstaggqueue; qid < sc->ntxqs; qid++) {
5568 		if (sc->qid2tap[qid] == NULL)
5569 			break;
5570 	}
5571 	if (qid == sc->ntxqs) {
5572 		DPRINTF(sc, IWN_DEBUG_XMIT, "%s: not free aggregation queue\n",
5573 		    __func__);
5574 		return 0;
5575 	}
5576 	tap->txa_private = malloc(sizeof(int), M_DEVBUF, M_NOWAIT);
5577 	if (tap->txa_private == NULL) {
5578 		device_printf(sc->sc_dev,
5579 		    "%s: failed to alloc TX aggregation structure\n", __func__);
5580 		return 0;
5581 	}
5582 	sc->qid2tap[qid] = tap;
5583 	*(int *)tap->txa_private = qid;
5584 	return sc->sc_addba_request(ni, tap, dialogtoken, baparamset,
5585 	    batimeout);
5586 }
5587 
5588 static int
5589 iwn_addba_response(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
5590     int code, int baparamset, int batimeout)
5591 {
5592 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
5593 	int qid = *(int *)tap->txa_private;
5594 	uint8_t tid = tap->txa_tid;
5595 	int ret;
5596 
5597 	if (code == IEEE80211_STATUS_SUCCESS) {
5598 		ni->ni_txseqs[tid] = tap->txa_start & 0xfff;
5599 		ret = iwn_ampdu_tx_start(ni->ni_ic, ni, tid);
5600 		if (ret != 1)
5601 			return ret;
5602 	} else {
5603 		sc->qid2tap[qid] = NULL;
5604 		free(tap->txa_private, M_DEVBUF);
5605 		tap->txa_private = NULL;
5606 	}
5607 	return sc->sc_addba_response(ni, tap, code, baparamset, batimeout);
5608 }
5609 
5610 /*
5611  * This function is called by upper layer when an ADDBA response is received
5612  * from another STA.
5613  */
5614 static int
5615 iwn_ampdu_tx_start(struct ieee80211com *ic, struct ieee80211_node *ni,
5616     uint8_t tid)
5617 {
5618 	struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[tid];
5619 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
5620 	struct iwn_ops *ops = &sc->ops;
5621 	struct iwn_node *wn = (void *)ni;
5622 	struct iwn_node_info node;
5623 	int error, qid;
5624 
5625 	/* Enable TX for the specified RA/TID. */
5626 	wn->disable_tid &= ~(1 << tid);
5627 	memset(&node, 0, sizeof node);
5628 	node.id = wn->id;
5629 	node.control = IWN_NODE_UPDATE;
5630 	node.flags = IWN_FLAG_SET_DISABLE_TID;
5631 	node.disable_tid = htole16(wn->disable_tid);
5632 	error = ops->add_node(sc, &node, 1);
5633 	if (error != 0)
5634 		return 0;
5635 
5636 	if ((error = iwn_nic_lock(sc)) != 0)
5637 		return 0;
5638 	qid = *(int *)tap->txa_private;
5639 	ops->ampdu_tx_start(sc, ni, qid, tid, tap->txa_start & 0xfff);
5640 	iwn_nic_unlock(sc);
5641 
5642 	iwn_set_link_quality(sc, ni);
5643 	return 1;
5644 }
5645 
5646 static void
5647 iwn_ampdu_tx_stop(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap)
5648 {
5649 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
5650 	struct iwn_ops *ops = &sc->ops;
5651 	uint8_t tid = tap->txa_tid;
5652 	int qid;
5653 
5654 	if (tap->txa_private == NULL)
5655 		return;
5656 
5657 	qid = *(int *)tap->txa_private;
5658 	if (iwn_nic_lock(sc) != 0)
5659 		return;
5660 	ops->ampdu_tx_stop(sc, qid, tid, tap->txa_start & 0xfff);
5661 	iwn_nic_unlock(sc);
5662 	sc->qid2tap[qid] = NULL;
5663 	free(tap->txa_private, M_DEVBUF);
5664 	tap->txa_private = NULL;
5665 	sc->sc_addba_stop(ni, tap);
5666 }
5667 
5668 static void
5669 iwn4965_ampdu_tx_start(struct iwn_softc *sc, struct ieee80211_node *ni,
5670     int qid, uint8_t tid, uint16_t ssn)
5671 {
5672 	struct iwn_node *wn = (void *)ni;
5673 
5674 	/* Stop TX scheduler while we're changing its configuration. */
5675 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
5676 	    IWN4965_TXQ_STATUS_CHGACT);
5677 
5678 	/* Assign RA/TID translation to the queue. */
5679 	iwn_mem_write_2(sc, sc->sched_base + IWN4965_SCHED_TRANS_TBL(qid),
5680 	    wn->id << 4 | tid);
5681 
5682 	/* Enable chain-building mode for the queue. */
5683 	iwn_prph_setbits(sc, IWN4965_SCHED_QCHAIN_SEL, 1 << qid);
5684 
5685 	/* Set starting sequence number from the ADDBA request. */
5686 	sc->txq[qid].cur = sc->txq[qid].read = (ssn & 0xff);
5687 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
5688 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), ssn);
5689 
5690 	/* Set scheduler window size. */
5691 	iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid),
5692 	    IWN_SCHED_WINSZ);
5693 	/* Set scheduler frame limit. */
5694 	iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid) + 4,
5695 	    IWN_SCHED_LIMIT << 16);
5696 
5697 	/* Enable interrupts for the queue. */
5698 	iwn_prph_setbits(sc, IWN4965_SCHED_INTR_MASK, 1 << qid);
5699 
5700 	/* Mark the queue as active. */
5701 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
5702 	    IWN4965_TXQ_STATUS_ACTIVE | IWN4965_TXQ_STATUS_AGGR_ENA |
5703 	    iwn_tid2fifo[tid] << 1);
5704 }
5705 
5706 static void
5707 iwn4965_ampdu_tx_stop(struct iwn_softc *sc, int qid, uint8_t tid, uint16_t ssn)
5708 {
5709 	/* Stop TX scheduler while we're changing its configuration. */
5710 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
5711 	    IWN4965_TXQ_STATUS_CHGACT);
5712 
5713 	/* Set starting sequence number from the ADDBA request. */
5714 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
5715 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), ssn);
5716 
5717 	/* Disable interrupts for the queue. */
5718 	iwn_prph_clrbits(sc, IWN4965_SCHED_INTR_MASK, 1 << qid);
5719 
5720 	/* Mark the queue as inactive. */
5721 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
5722 	    IWN4965_TXQ_STATUS_INACTIVE | iwn_tid2fifo[tid] << 1);
5723 }
5724 
5725 static void
5726 iwn5000_ampdu_tx_start(struct iwn_softc *sc, struct ieee80211_node *ni,
5727     int qid, uint8_t tid, uint16_t ssn)
5728 {
5729 	struct iwn_node *wn = (void *)ni;
5730 
5731 	/* Stop TX scheduler while we're changing its configuration. */
5732 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
5733 	    IWN5000_TXQ_STATUS_CHGACT);
5734 
5735 	/* Assign RA/TID translation to the queue. */
5736 	iwn_mem_write_2(sc, sc->sched_base + IWN5000_SCHED_TRANS_TBL(qid),
5737 	    wn->id << 4 | tid);
5738 
5739 	/* Enable chain-building mode for the queue. */
5740 	iwn_prph_setbits(sc, IWN5000_SCHED_QCHAIN_SEL, 1 << qid);
5741 
5742 	/* Enable aggregation for the queue. */
5743 	iwn_prph_setbits(sc, IWN5000_SCHED_AGGR_SEL, 1 << qid);
5744 
5745 	/* Set starting sequence number from the ADDBA request. */
5746 	sc->txq[qid].cur = sc->txq[qid].read = (ssn & 0xff);
5747 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
5748 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), ssn);
5749 
5750 	/* Set scheduler window size and frame limit. */
5751 	iwn_mem_write(sc, sc->sched_base + IWN5000_SCHED_QUEUE_OFFSET(qid) + 4,
5752 	    IWN_SCHED_LIMIT << 16 | IWN_SCHED_WINSZ);
5753 
5754 	/* Enable interrupts for the queue. */
5755 	iwn_prph_setbits(sc, IWN5000_SCHED_INTR_MASK, 1 << qid);
5756 
5757 	/* Mark the queue as active. */
5758 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
5759 	    IWN5000_TXQ_STATUS_ACTIVE | iwn_tid2fifo[tid]);
5760 }
5761 
5762 static void
5763 iwn5000_ampdu_tx_stop(struct iwn_softc *sc, int qid, uint8_t tid, uint16_t ssn)
5764 {
5765 	/* Stop TX scheduler while we're changing its configuration. */
5766 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
5767 	    IWN5000_TXQ_STATUS_CHGACT);
5768 
5769 	/* Disable aggregation for the queue. */
5770 	iwn_prph_clrbits(sc, IWN5000_SCHED_AGGR_SEL, 1 << qid);
5771 
5772 	/* Set starting sequence number from the ADDBA request. */
5773 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
5774 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), ssn);
5775 
5776 	/* Disable interrupts for the queue. */
5777 	iwn_prph_clrbits(sc, IWN5000_SCHED_INTR_MASK, 1 << qid);
5778 
5779 	/* Mark the queue as inactive. */
5780 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
5781 	    IWN5000_TXQ_STATUS_INACTIVE | iwn_tid2fifo[tid]);
5782 }
5783 
5784 /*
5785  * Query calibration tables from the initialization firmware.  We do this
5786  * only once at first boot.  Called from a process context.
5787  */
5788 static int
5789 iwn5000_query_calibration(struct iwn_softc *sc)
5790 {
5791 	struct iwn5000_calib_config cmd;
5792 	int error;
5793 
5794 	memset(&cmd, 0, sizeof cmd);
5795 	cmd.ucode.once.enable = 0xffffffff;
5796 	cmd.ucode.once.start  = 0xffffffff;
5797 	cmd.ucode.once.send   = 0xffffffff;
5798 	cmd.ucode.flags       = 0xffffffff;
5799 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: sending calibration query\n",
5800 	    __func__);
5801 	error = iwn_cmd(sc, IWN5000_CMD_CALIB_CONFIG, &cmd, sizeof cmd, 0);
5802 	if (error != 0)
5803 		return error;
5804 
5805 	/* Wait at most two seconds for calibration to complete. */
5806 	if (!(sc->sc_flags & IWN_FLAG_CALIB_DONE))
5807 		error = msleep(sc, &sc->sc_mtx, PCATCH, "iwncal", 2 * hz);
5808 	return error;
5809 }
5810 
5811 /*
5812  * Send calibration results to the runtime firmware.  These results were
5813  * obtained on first boot from the initialization firmware.
5814  */
5815 static int
5816 iwn5000_send_calibration(struct iwn_softc *sc)
5817 {
5818 	int idx, error;
5819 
5820 	for (idx = 0; idx < 5; idx++) {
5821 		if (sc->calibcmd[idx].buf == NULL)
5822 			continue;	/* No results available. */
5823 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
5824 		    "send calibration result idx=%d len=%d\n", idx,
5825 		    sc->calibcmd[idx].len);
5826 		error = iwn_cmd(sc, IWN_CMD_PHY_CALIB, sc->calibcmd[idx].buf,
5827 		    sc->calibcmd[idx].len, 0);
5828 		if (error != 0) {
5829 			device_printf(sc->sc_dev,
5830 			    "%s: could not send calibration result, error %d\n",
5831 			    __func__, error);
5832 			return error;
5833 		}
5834 	}
5835 	return 0;
5836 }
5837 
5838 static int
5839 iwn5000_send_wimax_coex(struct iwn_softc *sc)
5840 {
5841 	struct iwn5000_wimax_coex wimax;
5842 
5843 #ifdef notyet
5844 	if (sc->hw_type == IWN_HW_REV_TYPE_6050) {
5845 		/* Enable WiMAX coexistence for combo adapters. */
5846 		wimax.flags =
5847 		    IWN_WIMAX_COEX_ASSOC_WA_UNMASK |
5848 		    IWN_WIMAX_COEX_UNASSOC_WA_UNMASK |
5849 		    IWN_WIMAX_COEX_STA_TABLE_VALID |
5850 		    IWN_WIMAX_COEX_ENABLE;
5851 		memcpy(wimax.events, iwn6050_wimax_events,
5852 		    sizeof iwn6050_wimax_events);
5853 	} else
5854 #endif
5855 	{
5856 		/* Disable WiMAX coexistence. */
5857 		wimax.flags = 0;
5858 		memset(wimax.events, 0, sizeof wimax.events);
5859 	}
5860 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: Configuring WiMAX coexistence\n",
5861 	    __func__);
5862 	return iwn_cmd(sc, IWN5000_CMD_WIMAX_COEX, &wimax, sizeof wimax, 0);
5863 }
5864 
5865 static int
5866 iwn5000_crystal_calib(struct iwn_softc *sc)
5867 {
5868 	struct iwn5000_phy_calib_crystal cmd;
5869 
5870 	memset(&cmd, 0, sizeof cmd);
5871 	cmd.code = IWN5000_PHY_CALIB_CRYSTAL;
5872 	cmd.ngroups = 1;
5873 	cmd.isvalid = 1;
5874 	cmd.cap_pin[0] = le32toh(sc->eeprom_crystal) & 0xff;
5875 	cmd.cap_pin[1] = (le32toh(sc->eeprom_crystal) >> 16) & 0xff;
5876 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "sending crystal calibration %d, %d\n",
5877 	    cmd.cap_pin[0], cmd.cap_pin[1]);
5878 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
5879 }
5880 
5881 static int
5882 iwn5000_temp_offset_calib(struct iwn_softc *sc)
5883 {
5884 	struct iwn5000_phy_calib_temp_offset cmd;
5885 
5886 	memset(&cmd, 0, sizeof cmd);
5887 	cmd.code = IWN5000_PHY_CALIB_TEMP_OFFSET;
5888 	cmd.ngroups = 1;
5889 	cmd.isvalid = 1;
5890 	if (sc->eeprom_temp != 0)
5891 		cmd.offset = htole16(sc->eeprom_temp);
5892 	else
5893 		cmd.offset = htole16(IWN_DEFAULT_TEMP_OFFSET);
5894 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "setting radio sensor offset to %d\n",
5895 	    le16toh(cmd.offset));
5896 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
5897 }
5898 
5899 /*
5900  * This function is called after the runtime firmware notifies us of its
5901  * readiness (called in a process context).
5902  */
5903 static int
5904 iwn4965_post_alive(struct iwn_softc *sc)
5905 {
5906 	int error, qid;
5907 
5908 	if ((error = iwn_nic_lock(sc)) != 0)
5909 		return error;
5910 
5911 	/* Clear TX scheduler state in SRAM. */
5912 	sc->sched_base = iwn_prph_read(sc, IWN_SCHED_SRAM_ADDR);
5913 	iwn_mem_set_region_4(sc, sc->sched_base + IWN4965_SCHED_CTX_OFF, 0,
5914 	    IWN4965_SCHED_CTX_LEN / sizeof (uint32_t));
5915 
5916 	/* Set physical address of TX scheduler rings (1KB aligned). */
5917 	iwn_prph_write(sc, IWN4965_SCHED_DRAM_ADDR, sc->sched_dma.paddr >> 10);
5918 
5919 	IWN_SETBITS(sc, IWN_FH_TX_CHICKEN, IWN_FH_TX_CHICKEN_SCHED_RETRY);
5920 
5921 	/* Disable chain mode for all our 16 queues. */
5922 	iwn_prph_write(sc, IWN4965_SCHED_QCHAIN_SEL, 0);
5923 
5924 	for (qid = 0; qid < IWN4965_NTXQUEUES; qid++) {
5925 		iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), 0);
5926 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | 0);
5927 
5928 		/* Set scheduler window size. */
5929 		iwn_mem_write(sc, sc->sched_base +
5930 		    IWN4965_SCHED_QUEUE_OFFSET(qid), IWN_SCHED_WINSZ);
5931 		/* Set scheduler frame limit. */
5932 		iwn_mem_write(sc, sc->sched_base +
5933 		    IWN4965_SCHED_QUEUE_OFFSET(qid) + 4,
5934 		    IWN_SCHED_LIMIT << 16);
5935 	}
5936 
5937 	/* Enable interrupts for all our 16 queues. */
5938 	iwn_prph_write(sc, IWN4965_SCHED_INTR_MASK, 0xffff);
5939 	/* Identify TX FIFO rings (0-7). */
5940 	iwn_prph_write(sc, IWN4965_SCHED_TXFACT, 0xff);
5941 
5942 	/* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
5943 	for (qid = 0; qid < 7; qid++) {
5944 		static uint8_t qid2fifo[] = { 3, 2, 1, 0, 4, 5, 6 };
5945 		iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
5946 		    IWN4965_TXQ_STATUS_ACTIVE | qid2fifo[qid] << 1);
5947 	}
5948 	iwn_nic_unlock(sc);
5949 	return 0;
5950 }
5951 
5952 /*
5953  * This function is called after the initialization or runtime firmware
5954  * notifies us of its readiness (called in a process context).
5955  */
5956 static int
5957 iwn5000_post_alive(struct iwn_softc *sc)
5958 {
5959 	int error, qid;
5960 
5961 	/* Switch to using ICT interrupt mode. */
5962 	iwn5000_ict_reset(sc);
5963 
5964 	if ((error = iwn_nic_lock(sc)) != 0)
5965 		return error;
5966 
5967 	/* Clear TX scheduler state in SRAM. */
5968 	sc->sched_base = iwn_prph_read(sc, IWN_SCHED_SRAM_ADDR);
5969 	iwn_mem_set_region_4(sc, sc->sched_base + IWN5000_SCHED_CTX_OFF, 0,
5970 	    IWN5000_SCHED_CTX_LEN / sizeof (uint32_t));
5971 
5972 	/* Set physical address of TX scheduler rings (1KB aligned). */
5973 	iwn_prph_write(sc, IWN5000_SCHED_DRAM_ADDR, sc->sched_dma.paddr >> 10);
5974 
5975 	IWN_SETBITS(sc, IWN_FH_TX_CHICKEN, IWN_FH_TX_CHICKEN_SCHED_RETRY);
5976 
5977 	/* Enable chain mode for all queues, except command queue. */
5978 	iwn_prph_write(sc, IWN5000_SCHED_QCHAIN_SEL, 0xfffef);
5979 	iwn_prph_write(sc, IWN5000_SCHED_AGGR_SEL, 0);
5980 
5981 	for (qid = 0; qid < IWN5000_NTXQUEUES; qid++) {
5982 		iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), 0);
5983 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | 0);
5984 
5985 		iwn_mem_write(sc, sc->sched_base +
5986 		    IWN5000_SCHED_QUEUE_OFFSET(qid), 0);
5987 		/* Set scheduler window size and frame limit. */
5988 		iwn_mem_write(sc, sc->sched_base +
5989 		    IWN5000_SCHED_QUEUE_OFFSET(qid) + 4,
5990 		    IWN_SCHED_LIMIT << 16 | IWN_SCHED_WINSZ);
5991 	}
5992 
5993 	/* Enable interrupts for all our 20 queues. */
5994 	iwn_prph_write(sc, IWN5000_SCHED_INTR_MASK, 0xfffff);
5995 	/* Identify TX FIFO rings (0-7). */
5996 	iwn_prph_write(sc, IWN5000_SCHED_TXFACT, 0xff);
5997 
5998 	/* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
5999 	for (qid = 0; qid < 7; qid++) {
6000 		static uint8_t qid2fifo[] = { 3, 2, 1, 0, 7, 5, 6 };
6001 		iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
6002 		    IWN5000_TXQ_STATUS_ACTIVE | qid2fifo[qid]);
6003 	}
6004 	iwn_nic_unlock(sc);
6005 
6006 	/* Configure WiMAX coexistence for combo adapters. */
6007 	error = iwn5000_send_wimax_coex(sc);
6008 	if (error != 0) {
6009 		device_printf(sc->sc_dev,
6010 		    "%s: could not configure WiMAX coexistence, error %d\n",
6011 		    __func__, error);
6012 		return error;
6013 	}
6014 	if (sc->hw_type != IWN_HW_REV_TYPE_5150) {
6015 		/* Perform crystal calibration. */
6016 		error = iwn5000_crystal_calib(sc);
6017 		if (error != 0) {
6018 			device_printf(sc->sc_dev,
6019 			    "%s: crystal calibration failed, error %d\n",
6020 			    __func__, error);
6021 			return error;
6022 		}
6023 	}
6024 	if (!(sc->sc_flags & IWN_FLAG_CALIB_DONE)) {
6025 		/* Query calibration from the initialization firmware. */
6026 		if ((error = iwn5000_query_calibration(sc)) != 0) {
6027 			device_printf(sc->sc_dev,
6028 			    "%s: could not query calibration, error %d\n",
6029 			    __func__, error);
6030 			return error;
6031 		}
6032 		/*
6033 		 * We have the calibration results now, reboot with the
6034 		 * runtime firmware (call ourselves recursively!)
6035 		 */
6036 		iwn_hw_stop(sc);
6037 		error = iwn_hw_init(sc);
6038 	} else {
6039 		/* Send calibration results to runtime firmware. */
6040 		error = iwn5000_send_calibration(sc);
6041 	}
6042 	return error;
6043 }
6044 
6045 /*
6046  * The firmware boot code is small and is intended to be copied directly into
6047  * the NIC internal memory (no DMA transfer).
6048  */
6049 static int
6050 iwn4965_load_bootcode(struct iwn_softc *sc, const uint8_t *ucode, int size)
6051 {
6052 	int error, ntries;
6053 
6054 	size /= sizeof (uint32_t);
6055 
6056 	if ((error = iwn_nic_lock(sc)) != 0)
6057 		return error;
6058 
6059 	/* Copy microcode image into NIC memory. */
6060 	iwn_prph_write_region_4(sc, IWN_BSM_SRAM_BASE,
6061 	    (const uint32_t *)ucode, size);
6062 
6063 	iwn_prph_write(sc, IWN_BSM_WR_MEM_SRC, 0);
6064 	iwn_prph_write(sc, IWN_BSM_WR_MEM_DST, IWN_FW_TEXT_BASE);
6065 	iwn_prph_write(sc, IWN_BSM_WR_DWCOUNT, size);
6066 
6067 	/* Start boot load now. */
6068 	iwn_prph_write(sc, IWN_BSM_WR_CTRL, IWN_BSM_WR_CTRL_START);
6069 
6070 	/* Wait for transfer to complete. */
6071 	for (ntries = 0; ntries < 1000; ntries++) {
6072 		if (!(iwn_prph_read(sc, IWN_BSM_WR_CTRL) &
6073 		    IWN_BSM_WR_CTRL_START))
6074 			break;
6075 		DELAY(10);
6076 	}
6077 	if (ntries == 1000) {
6078 		device_printf(sc->sc_dev, "%s: could not load boot firmware\n",
6079 		    __func__);
6080 		iwn_nic_unlock(sc);
6081 		return ETIMEDOUT;
6082 	}
6083 
6084 	/* Enable boot after power up. */
6085 	iwn_prph_write(sc, IWN_BSM_WR_CTRL, IWN_BSM_WR_CTRL_START_EN);
6086 
6087 	iwn_nic_unlock(sc);
6088 	return 0;
6089 }
6090 
6091 static int
6092 iwn4965_load_firmware(struct iwn_softc *sc)
6093 {
6094 	struct iwn_fw_info *fw = &sc->fw;
6095 	struct iwn_dma_info *dma = &sc->fw_dma;
6096 	int error;
6097 
6098 	/* Copy initialization sections into pre-allocated DMA-safe memory. */
6099 	memcpy(dma->vaddr, fw->init.data, fw->init.datasz);
6100 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
6101 	memcpy(dma->vaddr + IWN4965_FW_DATA_MAXSZ,
6102 	    fw->init.text, fw->init.textsz);
6103 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
6104 
6105 	/* Tell adapter where to find initialization sections. */
6106 	if ((error = iwn_nic_lock(sc)) != 0)
6107 		return error;
6108 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_ADDR, dma->paddr >> 4);
6109 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_SIZE, fw->init.datasz);
6110 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_ADDR,
6111 	    (dma->paddr + IWN4965_FW_DATA_MAXSZ) >> 4);
6112 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_SIZE, fw->init.textsz);
6113 	iwn_nic_unlock(sc);
6114 
6115 	/* Load firmware boot code. */
6116 	error = iwn4965_load_bootcode(sc, fw->boot.text, fw->boot.textsz);
6117 	if (error != 0) {
6118 		device_printf(sc->sc_dev, "%s: could not load boot firmware\n",
6119 		    __func__);
6120 		return error;
6121 	}
6122 	/* Now press "execute". */
6123 	IWN_WRITE(sc, IWN_RESET, 0);
6124 
6125 	/* Wait at most one second for first alive notification. */
6126 	if ((error = msleep(sc, &sc->sc_mtx, PCATCH, "iwninit", hz)) != 0) {
6127 		device_printf(sc->sc_dev,
6128 		    "%s: timeout waiting for adapter to initialize, error %d\n",
6129 		    __func__, error);
6130 		return error;
6131 	}
6132 
6133 	/* Retrieve current temperature for initial TX power calibration. */
6134 	sc->rawtemp = sc->ucode_info.temp[3].chan20MHz;
6135 	sc->temp = iwn4965_get_temperature(sc);
6136 
6137 	/* Copy runtime sections into pre-allocated DMA-safe memory. */
6138 	memcpy(dma->vaddr, fw->main.data, fw->main.datasz);
6139 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
6140 	memcpy(dma->vaddr + IWN4965_FW_DATA_MAXSZ,
6141 	    fw->main.text, fw->main.textsz);
6142 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
6143 
6144 	/* Tell adapter where to find runtime sections. */
6145 	if ((error = iwn_nic_lock(sc)) != 0)
6146 		return error;
6147 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_ADDR, dma->paddr >> 4);
6148 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_SIZE, fw->main.datasz);
6149 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_ADDR,
6150 	    (dma->paddr + IWN4965_FW_DATA_MAXSZ) >> 4);
6151 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_SIZE,
6152 	    IWN_FW_UPDATED | fw->main.textsz);
6153 	iwn_nic_unlock(sc);
6154 
6155 	return 0;
6156 }
6157 
6158 static int
6159 iwn5000_load_firmware_section(struct iwn_softc *sc, uint32_t dst,
6160     const uint8_t *section, int size)
6161 {
6162 	struct iwn_dma_info *dma = &sc->fw_dma;
6163 	int error;
6164 
6165 	/* Copy firmware section into pre-allocated DMA-safe memory. */
6166 	memcpy(dma->vaddr, section, size);
6167 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
6168 
6169 	if ((error = iwn_nic_lock(sc)) != 0)
6170 		return error;
6171 
6172 	IWN_WRITE(sc, IWN_FH_TX_CONFIG(IWN_SRVC_DMACHNL),
6173 	    IWN_FH_TX_CONFIG_DMA_PAUSE);
6174 
6175 	IWN_WRITE(sc, IWN_FH_SRAM_ADDR(IWN_SRVC_DMACHNL), dst);
6176 	IWN_WRITE(sc, IWN_FH_TFBD_CTRL0(IWN_SRVC_DMACHNL),
6177 	    IWN_LOADDR(dma->paddr));
6178 	IWN_WRITE(sc, IWN_FH_TFBD_CTRL1(IWN_SRVC_DMACHNL),
6179 	    IWN_HIADDR(dma->paddr) << 28 | size);
6180 	IWN_WRITE(sc, IWN_FH_TXBUF_STATUS(IWN_SRVC_DMACHNL),
6181 	    IWN_FH_TXBUF_STATUS_TBNUM(1) |
6182 	    IWN_FH_TXBUF_STATUS_TBIDX(1) |
6183 	    IWN_FH_TXBUF_STATUS_TFBD_VALID);
6184 
6185 	/* Kick Flow Handler to start DMA transfer. */
6186 	IWN_WRITE(sc, IWN_FH_TX_CONFIG(IWN_SRVC_DMACHNL),
6187 	    IWN_FH_TX_CONFIG_DMA_ENA | IWN_FH_TX_CONFIG_CIRQ_HOST_ENDTFD);
6188 
6189 	iwn_nic_unlock(sc);
6190 
6191 	/* Wait at most five seconds for FH DMA transfer to complete. */
6192 	return msleep(sc, &sc->sc_mtx, PCATCH, "iwninit", 5 * hz);
6193 }
6194 
6195 static int
6196 iwn5000_load_firmware(struct iwn_softc *sc)
6197 {
6198 	struct iwn_fw_part *fw;
6199 	int error;
6200 
6201 	/* Load the initialization firmware on first boot only. */
6202 	fw = (sc->sc_flags & IWN_FLAG_CALIB_DONE) ?
6203 	    &sc->fw.main : &sc->fw.init;
6204 
6205 	error = iwn5000_load_firmware_section(sc, IWN_FW_TEXT_BASE,
6206 	    fw->text, fw->textsz);
6207 	if (error != 0) {
6208 		device_printf(sc->sc_dev,
6209 		    "%s: could not load firmware %s section, error %d\n",
6210 		    __func__, ".text", error);
6211 		return error;
6212 	}
6213 	error = iwn5000_load_firmware_section(sc, IWN_FW_DATA_BASE,
6214 	    fw->data, fw->datasz);
6215 	if (error != 0) {
6216 		device_printf(sc->sc_dev,
6217 		    "%s: could not load firmware %s section, error %d\n",
6218 		    __func__, ".data", error);
6219 		return error;
6220 	}
6221 
6222 	/* Now press "execute". */
6223 	IWN_WRITE(sc, IWN_RESET, 0);
6224 	return 0;
6225 }
6226 
6227 /*
6228  * Extract text and data sections from a legacy firmware image.
6229  */
6230 static int
6231 iwn_read_firmware_leg(struct iwn_softc *sc, struct iwn_fw_info *fw)
6232 {
6233 	const uint32_t *ptr;
6234 	size_t hdrlen = 24;
6235 	uint32_t rev;
6236 
6237 	ptr = (const uint32_t *)fw->data;
6238 	rev = le32toh(*ptr++);
6239 
6240 	/* Check firmware API version. */
6241 	if (IWN_FW_API(rev) <= 1) {
6242 		device_printf(sc->sc_dev,
6243 		    "%s: bad firmware, need API version >=2\n", __func__);
6244 		return EINVAL;
6245 	}
6246 	if (IWN_FW_API(rev) >= 3) {
6247 		/* Skip build number (version 2 header). */
6248 		hdrlen += 4;
6249 		ptr++;
6250 	}
6251 	if (fw->size < hdrlen) {
6252 		device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
6253 		    __func__, fw->size);
6254 		return EINVAL;
6255 	}
6256 	fw->main.textsz = le32toh(*ptr++);
6257 	fw->main.datasz = le32toh(*ptr++);
6258 	fw->init.textsz = le32toh(*ptr++);
6259 	fw->init.datasz = le32toh(*ptr++);
6260 	fw->boot.textsz = le32toh(*ptr++);
6261 
6262 	/* Check that all firmware sections fit. */
6263 	if (fw->size < hdrlen + fw->main.textsz + fw->main.datasz +
6264 	    fw->init.textsz + fw->init.datasz + fw->boot.textsz) {
6265 		device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
6266 		    __func__, fw->size);
6267 		return EINVAL;
6268 	}
6269 
6270 	/* Get pointers to firmware sections. */
6271 	fw->main.text = (const uint8_t *)ptr;
6272 	fw->main.data = fw->main.text + fw->main.textsz;
6273 	fw->init.text = fw->main.data + fw->main.datasz;
6274 	fw->init.data = fw->init.text + fw->init.textsz;
6275 	fw->boot.text = fw->init.data + fw->init.datasz;
6276 	return 0;
6277 }
6278 
6279 /*
6280  * Extract text and data sections from a TLV firmware image.
6281  */
6282 static int
6283 iwn_read_firmware_tlv(struct iwn_softc *sc, struct iwn_fw_info *fw,
6284     uint16_t alt)
6285 {
6286 	const struct iwn_fw_tlv_hdr *hdr;
6287 	const struct iwn_fw_tlv *tlv;
6288 	const uint8_t *ptr, *end;
6289 	uint64_t altmask;
6290 	uint32_t len, tmp;
6291 
6292 	if (fw->size < sizeof (*hdr)) {
6293 		device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
6294 		    __func__, fw->size);
6295 		return EINVAL;
6296 	}
6297 	hdr = (const struct iwn_fw_tlv_hdr *)fw->data;
6298 	if (hdr->signature != htole32(IWN_FW_SIGNATURE)) {
6299 		device_printf(sc->sc_dev, "%s: bad firmware signature 0x%08x\n",
6300 		    __func__, le32toh(hdr->signature));
6301 		return EINVAL;
6302 	}
6303 	DPRINTF(sc, IWN_DEBUG_RESET, "FW: \"%.64s\", build 0x%x\n", hdr->descr,
6304 	    le32toh(hdr->build));
6305 
6306 	/*
6307 	 * Select the closest supported alternative that is less than
6308 	 * or equal to the specified one.
6309 	 */
6310 	altmask = le64toh(hdr->altmask);
6311 	while (alt > 0 && !(altmask & (1ULL << alt)))
6312 		alt--;	/* Downgrade. */
6313 	DPRINTF(sc, IWN_DEBUG_RESET, "using alternative %d\n", alt);
6314 
6315 	ptr = (const uint8_t *)(hdr + 1);
6316 	end = (const uint8_t *)(fw->data + fw->size);
6317 
6318 	/* Parse type-length-value fields. */
6319 	while (ptr + sizeof (*tlv) <= end) {
6320 		tlv = (const struct iwn_fw_tlv *)ptr;
6321 		len = le32toh(tlv->len);
6322 
6323 		ptr += sizeof (*tlv);
6324 		if (ptr + len > end) {
6325 			device_printf(sc->sc_dev,
6326 			    "%s: firmware too short: %zu bytes\n", __func__,
6327 			    fw->size);
6328 			return EINVAL;
6329 		}
6330 		/* Skip other alternatives. */
6331 		if (tlv->alt != 0 && tlv->alt != htole16(alt))
6332 			goto next;
6333 
6334 		switch (le16toh(tlv->type)) {
6335 		case IWN_FW_TLV_MAIN_TEXT:
6336 			fw->main.text = ptr;
6337 			fw->main.textsz = len;
6338 			break;
6339 		case IWN_FW_TLV_MAIN_DATA:
6340 			fw->main.data = ptr;
6341 			fw->main.datasz = len;
6342 			break;
6343 		case IWN_FW_TLV_INIT_TEXT:
6344 			fw->init.text = ptr;
6345 			fw->init.textsz = len;
6346 			break;
6347 		case IWN_FW_TLV_INIT_DATA:
6348 			fw->init.data = ptr;
6349 			fw->init.datasz = len;
6350 			break;
6351 		case IWN_FW_TLV_BOOT_TEXT:
6352 			fw->boot.text = ptr;
6353 			fw->boot.textsz = len;
6354 			break;
6355 		case IWN_FW_TLV_ENH_SENS:
6356 			if (!len)
6357 				sc->sc_flags |= IWN_FLAG_ENH_SENS;
6358 			break;
6359 		case IWN_FW_TLV_PHY_CALIB:
6360 			tmp = htole32(*ptr);
6361 			if (tmp < 253) {
6362 				sc->reset_noise_gain = tmp;
6363 				sc->noise_gain = tmp + 1;
6364 			}
6365 			break;
6366 		default:
6367 			DPRINTF(sc, IWN_DEBUG_RESET,
6368 			    "TLV type %d not handled\n", le16toh(tlv->type));
6369 			break;
6370 		}
6371  next:		/* TLV fields are 32-bit aligned. */
6372 		ptr += (len + 3) & ~3;
6373 	}
6374 	return 0;
6375 }
6376 
6377 static int
6378 iwn_read_firmware(struct iwn_softc *sc)
6379 {
6380 	struct iwn_fw_info *fw = &sc->fw;
6381 	int error;
6382 
6383 	IWN_UNLOCK(sc);
6384 
6385 	memset(fw, 0, sizeof (*fw));
6386 
6387 	/* Read firmware image from filesystem. */
6388 	sc->fw_fp = firmware_get(sc->fwname);
6389 	if (sc->fw_fp == NULL) {
6390 		device_printf(sc->sc_dev, "%s: could not read firmware %s\n",
6391 		    __func__, sc->fwname);
6392 		IWN_LOCK(sc);
6393 		return EINVAL;
6394 	}
6395 	IWN_LOCK(sc);
6396 
6397 	fw->size = sc->fw_fp->datasize;
6398 	fw->data = (const uint8_t *)sc->fw_fp->data;
6399 	if (fw->size < sizeof (uint32_t)) {
6400 		device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
6401 		    __func__, fw->size);
6402 		firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
6403 		sc->fw_fp = NULL;
6404 		return EINVAL;
6405 	}
6406 
6407 	/* Retrieve text and data sections. */
6408 	if (*(const uint32_t *)fw->data != 0)	/* Legacy image. */
6409 		error = iwn_read_firmware_leg(sc, fw);
6410 	else
6411 		error = iwn_read_firmware_tlv(sc, fw, 1);
6412 	if (error != 0) {
6413 		device_printf(sc->sc_dev,
6414 		    "%s: could not read firmware sections, error %d\n",
6415 		    __func__, error);
6416 		firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
6417 		sc->fw_fp = NULL;
6418 		return error;
6419 	}
6420 
6421 	/* Make sure text and data sections fit in hardware memory. */
6422 	if (fw->main.textsz > sc->fw_text_maxsz ||
6423 	    fw->main.datasz > sc->fw_data_maxsz ||
6424 	    fw->init.textsz > sc->fw_text_maxsz ||
6425 	    fw->init.datasz > sc->fw_data_maxsz ||
6426 	    fw->boot.textsz > IWN_FW_BOOT_TEXT_MAXSZ ||
6427 	    (fw->boot.textsz & 3) != 0) {
6428 		device_printf(sc->sc_dev, "%s: firmware sections too large\n",
6429 		    __func__);
6430 		firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
6431 		sc->fw_fp = NULL;
6432 		return EINVAL;
6433 	}
6434 
6435 	/* We can proceed with loading the firmware. */
6436 	return 0;
6437 }
6438 
6439 static int
6440 iwn_clock_wait(struct iwn_softc *sc)
6441 {
6442 	int ntries;
6443 
6444 	/* Set "initialization complete" bit. */
6445 	IWN_SETBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_INIT_DONE);
6446 
6447 	/* Wait for clock stabilization. */
6448 	for (ntries = 0; ntries < 2500; ntries++) {
6449 		if (IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_MAC_CLOCK_READY)
6450 			return 0;
6451 		DELAY(10);
6452 	}
6453 	device_printf(sc->sc_dev,
6454 	    "%s: timeout waiting for clock stabilization\n", __func__);
6455 	return ETIMEDOUT;
6456 }
6457 
6458 static int
6459 iwn_apm_init(struct iwn_softc *sc)
6460 {
6461 	uint32_t reg;
6462 	int error;
6463 
6464 	/* Disable L0s exit timer (NMI bug workaround). */
6465 	IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_DIS_L0S_TIMER);
6466 	/* Don't wait for ICH L0s (ICH bug workaround). */
6467 	IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_L1A_NO_L0S_RX);
6468 
6469 	/* Set FH wait threshold to max (HW bug under stress workaround). */
6470 	IWN_SETBITS(sc, IWN_DBG_HPET_MEM, 0xffff0000);
6471 
6472 	/* Enable HAP INTA to move adapter from L1a to L0s. */
6473 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_HAP_WAKE_L1A);
6474 
6475 	/* Retrieve PCIe Active State Power Management (ASPM). */
6476 	reg = pci_read_config(sc->sc_dev, sc->sc_cap_off + 0x10, 1);
6477 	/* Workaround for HW instability in PCIe L0->L0s->L1 transition. */
6478 	if (reg & 0x02)	/* L1 Entry enabled. */
6479 		IWN_SETBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA);
6480 	else
6481 		IWN_CLRBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA);
6482 
6483 	if (sc->hw_type != IWN_HW_REV_TYPE_4965 &&
6484 	    sc->hw_type <= IWN_HW_REV_TYPE_1000)
6485 		IWN_SETBITS(sc, IWN_ANA_PLL, IWN_ANA_PLL_INIT);
6486 
6487 	/* Wait for clock stabilization before accessing prph. */
6488 	if ((error = iwn_clock_wait(sc)) != 0)
6489 		return error;
6490 
6491 	if ((error = iwn_nic_lock(sc)) != 0)
6492 		return error;
6493 	if (sc->hw_type == IWN_HW_REV_TYPE_4965) {
6494 		/* Enable DMA and BSM (Bootstrap State Machine). */
6495 		iwn_prph_write(sc, IWN_APMG_CLK_EN,
6496 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT |
6497 		    IWN_APMG_CLK_CTRL_BSM_CLK_RQT);
6498 	} else {
6499 		/* Enable DMA. */
6500 		iwn_prph_write(sc, IWN_APMG_CLK_EN,
6501 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT);
6502 	}
6503 	DELAY(20);
6504 	/* Disable L1-Active. */
6505 	iwn_prph_setbits(sc, IWN_APMG_PCI_STT, IWN_APMG_PCI_STT_L1A_DIS);
6506 	iwn_nic_unlock(sc);
6507 
6508 	return 0;
6509 }
6510 
6511 static void
6512 iwn_apm_stop_master(struct iwn_softc *sc)
6513 {
6514 	int ntries;
6515 
6516 	/* Stop busmaster DMA activity. */
6517 	IWN_SETBITS(sc, IWN_RESET, IWN_RESET_STOP_MASTER);
6518 	for (ntries = 0; ntries < 100; ntries++) {
6519 		if (IWN_READ(sc, IWN_RESET) & IWN_RESET_MASTER_DISABLED)
6520 			return;
6521 		DELAY(10);
6522 	}
6523 	device_printf(sc->sc_dev, "%s: timeout waiting for master\n", __func__);
6524 }
6525 
6526 static void
6527 iwn_apm_stop(struct iwn_softc *sc)
6528 {
6529 	iwn_apm_stop_master(sc);
6530 
6531 	/* Reset the entire device. */
6532 	IWN_SETBITS(sc, IWN_RESET, IWN_RESET_SW);
6533 	DELAY(10);
6534 	/* Clear "initialization complete" bit. */
6535 	IWN_CLRBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_INIT_DONE);
6536 }
6537 
6538 static int
6539 iwn4965_nic_config(struct iwn_softc *sc)
6540 {
6541 	if (IWN_RFCFG_TYPE(sc->rfcfg) == 1) {
6542 		/*
6543 		 * I don't believe this to be correct but this is what the
6544 		 * vendor driver is doing. Probably the bits should not be
6545 		 * shifted in IWN_RFCFG_*.
6546 		 */
6547 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
6548 		    IWN_RFCFG_TYPE(sc->rfcfg) |
6549 		    IWN_RFCFG_STEP(sc->rfcfg) |
6550 		    IWN_RFCFG_DASH(sc->rfcfg));
6551 	}
6552 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
6553 	    IWN_HW_IF_CONFIG_RADIO_SI | IWN_HW_IF_CONFIG_MAC_SI);
6554 	return 0;
6555 }
6556 
6557 static int
6558 iwn5000_nic_config(struct iwn_softc *sc)
6559 {
6560 	uint32_t tmp;
6561 	int error;
6562 
6563 	if (IWN_RFCFG_TYPE(sc->rfcfg) < 3) {
6564 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
6565 		    IWN_RFCFG_TYPE(sc->rfcfg) |
6566 		    IWN_RFCFG_STEP(sc->rfcfg) |
6567 		    IWN_RFCFG_DASH(sc->rfcfg));
6568 	}
6569 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
6570 	    IWN_HW_IF_CONFIG_RADIO_SI | IWN_HW_IF_CONFIG_MAC_SI);
6571 
6572 	if ((error = iwn_nic_lock(sc)) != 0)
6573 		return error;
6574 	iwn_prph_setbits(sc, IWN_APMG_PS, IWN_APMG_PS_EARLY_PWROFF_DIS);
6575 
6576 	if (sc->hw_type == IWN_HW_REV_TYPE_1000) {
6577 		/*
6578 		 * Select first Switching Voltage Regulator (1.32V) to
6579 		 * solve a stability issue related to noisy DC2DC line
6580 		 * in the silicon of 1000 Series.
6581 		 */
6582 		tmp = iwn_prph_read(sc, IWN_APMG_DIGITAL_SVR);
6583 		tmp &= ~IWN_APMG_DIGITAL_SVR_VOLTAGE_MASK;
6584 		tmp |= IWN_APMG_DIGITAL_SVR_VOLTAGE_1_32;
6585 		iwn_prph_write(sc, IWN_APMG_DIGITAL_SVR, tmp);
6586 	}
6587 	iwn_nic_unlock(sc);
6588 
6589 	if (sc->sc_flags & IWN_FLAG_INTERNAL_PA) {
6590 		/* Use internal power amplifier only. */
6591 		IWN_WRITE(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_RADIO_2X2_IPA);
6592 	}
6593 	if ((sc->hw_type == IWN_HW_REV_TYPE_6050 ||
6594 	     sc->hw_type == IWN_HW_REV_TYPE_6005) && sc->calib_ver >= 6) {
6595 		/* Indicate that ROM calibration version is >=6. */
6596 		IWN_SETBITS(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_CALIB_VER6);
6597 	}
6598 	if (sc->hw_type == IWN_HW_REV_TYPE_6005)
6599 		IWN_SETBITS(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_6050_1X2);
6600 	return 0;
6601 }
6602 
6603 /*
6604  * Take NIC ownership over Intel Active Management Technology (AMT).
6605  */
6606 static int
6607 iwn_hw_prepare(struct iwn_softc *sc)
6608 {
6609 	int ntries;
6610 
6611 	/* Check if hardware is ready. */
6612 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_NIC_READY);
6613 	for (ntries = 0; ntries < 5; ntries++) {
6614 		if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
6615 		    IWN_HW_IF_CONFIG_NIC_READY)
6616 			return 0;
6617 		DELAY(10);
6618 	}
6619 
6620 	/* Hardware not ready, force into ready state. */
6621 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_PREPARE);
6622 	for (ntries = 0; ntries < 15000; ntries++) {
6623 		if (!(IWN_READ(sc, IWN_HW_IF_CONFIG) &
6624 		    IWN_HW_IF_CONFIG_PREPARE_DONE))
6625 			break;
6626 		DELAY(10);
6627 	}
6628 	if (ntries == 15000)
6629 		return ETIMEDOUT;
6630 
6631 	/* Hardware should be ready now. */
6632 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_NIC_READY);
6633 	for (ntries = 0; ntries < 5; ntries++) {
6634 		if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
6635 		    IWN_HW_IF_CONFIG_NIC_READY)
6636 			return 0;
6637 		DELAY(10);
6638 	}
6639 	return ETIMEDOUT;
6640 }
6641 
6642 static int
6643 iwn_hw_init(struct iwn_softc *sc)
6644 {
6645 	struct iwn_ops *ops = &sc->ops;
6646 	int error, chnl, qid;
6647 
6648 	/* Clear pending interrupts. */
6649 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
6650 
6651 	if ((error = iwn_apm_init(sc)) != 0) {
6652 		device_printf(sc->sc_dev,
6653 		    "%s: could not power ON adapter, error %d\n", __func__,
6654 		    error);
6655 		return error;
6656 	}
6657 
6658 	/* Select VMAIN power source. */
6659 	if ((error = iwn_nic_lock(sc)) != 0)
6660 		return error;
6661 	iwn_prph_clrbits(sc, IWN_APMG_PS, IWN_APMG_PS_PWR_SRC_MASK);
6662 	iwn_nic_unlock(sc);
6663 
6664 	/* Perform adapter-specific initialization. */
6665 	if ((error = ops->nic_config(sc)) != 0)
6666 		return error;
6667 
6668 	/* Initialize RX ring. */
6669 	if ((error = iwn_nic_lock(sc)) != 0)
6670 		return error;
6671 	IWN_WRITE(sc, IWN_FH_RX_CONFIG, 0);
6672 	IWN_WRITE(sc, IWN_FH_RX_WPTR, 0);
6673 	/* Set physical address of RX ring (256-byte aligned). */
6674 	IWN_WRITE(sc, IWN_FH_RX_BASE, sc->rxq.desc_dma.paddr >> 8);
6675 	/* Set physical address of RX status (16-byte aligned). */
6676 	IWN_WRITE(sc, IWN_FH_STATUS_WPTR, sc->rxq.stat_dma.paddr >> 4);
6677 	/* Enable RX. */
6678 	IWN_WRITE(sc, IWN_FH_RX_CONFIG,
6679 	    IWN_FH_RX_CONFIG_ENA           |
6680 	    IWN_FH_RX_CONFIG_IGN_RXF_EMPTY |	/* HW bug workaround */
6681 	    IWN_FH_RX_CONFIG_IRQ_DST_HOST  |
6682 	    IWN_FH_RX_CONFIG_SINGLE_FRAME  |
6683 	    IWN_FH_RX_CONFIG_RB_TIMEOUT(0) |
6684 	    IWN_FH_RX_CONFIG_NRBD(IWN_RX_RING_COUNT_LOG));
6685 	iwn_nic_unlock(sc);
6686 	IWN_WRITE(sc, IWN_FH_RX_WPTR, (IWN_RX_RING_COUNT - 1) & ~7);
6687 
6688 	if ((error = iwn_nic_lock(sc)) != 0)
6689 		return error;
6690 
6691 	/* Initialize TX scheduler. */
6692 	iwn_prph_write(sc, sc->sched_txfact_addr, 0);
6693 
6694 	/* Set physical address of "keep warm" page (16-byte aligned). */
6695 	IWN_WRITE(sc, IWN_FH_KW_ADDR, sc->kw_dma.paddr >> 4);
6696 
6697 	/* Initialize TX rings. */
6698 	for (qid = 0; qid < sc->ntxqs; qid++) {
6699 		struct iwn_tx_ring *txq = &sc->txq[qid];
6700 
6701 		/* Set physical address of TX ring (256-byte aligned). */
6702 		IWN_WRITE(sc, IWN_FH_CBBC_QUEUE(qid),
6703 		    txq->desc_dma.paddr >> 8);
6704 	}
6705 	iwn_nic_unlock(sc);
6706 
6707 	/* Enable DMA channels. */
6708 	for (chnl = 0; chnl < sc->ndmachnls; chnl++) {
6709 		IWN_WRITE(sc, IWN_FH_TX_CONFIG(chnl),
6710 		    IWN_FH_TX_CONFIG_DMA_ENA |
6711 		    IWN_FH_TX_CONFIG_DMA_CREDIT_ENA);
6712 	}
6713 
6714 	/* Clear "radio off" and "commands blocked" bits. */
6715 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
6716 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CMD_BLOCKED);
6717 
6718 	/* Clear pending interrupts. */
6719 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
6720 	/* Enable interrupt coalescing. */
6721 	IWN_WRITE(sc, IWN_INT_COALESCING, 512 / 8);
6722 	/* Enable interrupts. */
6723 	IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
6724 
6725 	/* _Really_ make sure "radio off" bit is cleared! */
6726 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
6727 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
6728 
6729 	/* Enable shadow registers. */
6730 	if (sc->hw_type >= IWN_HW_REV_TYPE_6000)
6731 		IWN_SETBITS(sc, IWN_SHADOW_REG_CTRL, 0x800fffff);
6732 
6733 	if ((error = ops->load_firmware(sc)) != 0) {
6734 		device_printf(sc->sc_dev,
6735 		    "%s: could not load firmware, error %d\n", __func__,
6736 		    error);
6737 		return error;
6738 	}
6739 	/* Wait at most one second for firmware alive notification. */
6740 	if ((error = msleep(sc, &sc->sc_mtx, PCATCH, "iwninit", hz)) != 0) {
6741 		device_printf(sc->sc_dev,
6742 		    "%s: timeout waiting for adapter to initialize, error %d\n",
6743 		    __func__, error);
6744 		return error;
6745 	}
6746 	/* Do post-firmware initialization. */
6747 	return ops->post_alive(sc);
6748 }
6749 
6750 static void
6751 iwn_hw_stop(struct iwn_softc *sc)
6752 {
6753 	int chnl, qid, ntries;
6754 
6755 	IWN_WRITE(sc, IWN_RESET, IWN_RESET_NEVO);
6756 
6757 	/* Disable interrupts. */
6758 	IWN_WRITE(sc, IWN_INT_MASK, 0);
6759 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
6760 	IWN_WRITE(sc, IWN_FH_INT, 0xffffffff);
6761 	sc->sc_flags &= ~IWN_FLAG_USE_ICT;
6762 
6763 	/* Make sure we no longer hold the NIC lock. */
6764 	iwn_nic_unlock(sc);
6765 
6766 	/* Stop TX scheduler. */
6767 	iwn_prph_write(sc, sc->sched_txfact_addr, 0);
6768 
6769 	/* Stop all DMA channels. */
6770 	if (iwn_nic_lock(sc) == 0) {
6771 		for (chnl = 0; chnl < sc->ndmachnls; chnl++) {
6772 			IWN_WRITE(sc, IWN_FH_TX_CONFIG(chnl), 0);
6773 			for (ntries = 0; ntries < 200; ntries++) {
6774 				if (IWN_READ(sc, IWN_FH_TX_STATUS) &
6775 				    IWN_FH_TX_STATUS_IDLE(chnl))
6776 					break;
6777 				DELAY(10);
6778 			}
6779 		}
6780 		iwn_nic_unlock(sc);
6781 	}
6782 
6783 	/* Stop RX ring. */
6784 	iwn_reset_rx_ring(sc, &sc->rxq);
6785 
6786 	/* Reset all TX rings. */
6787 	for (qid = 0; qid < sc->ntxqs; qid++)
6788 		iwn_reset_tx_ring(sc, &sc->txq[qid]);
6789 
6790 	if (iwn_nic_lock(sc) == 0) {
6791 		iwn_prph_write(sc, IWN_APMG_CLK_DIS,
6792 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT);
6793 		iwn_nic_unlock(sc);
6794 	}
6795 	DELAY(5);
6796 	/* Power OFF adapter. */
6797 	iwn_apm_stop(sc);
6798 }
6799 
6800 static void
6801 iwn_radio_on(void *arg0, int pending)
6802 {
6803 	struct iwn_softc *sc = arg0;
6804 	struct ifnet *ifp = sc->sc_ifp;
6805 	struct ieee80211com *ic = ifp->if_l2com;
6806 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
6807 
6808 	if (vap != NULL) {
6809 		iwn_init(sc);
6810 		ieee80211_init(vap);
6811 	}
6812 }
6813 
6814 static void
6815 iwn_radio_off(void *arg0, int pending)
6816 {
6817 	struct iwn_softc *sc = arg0;
6818 	struct ifnet *ifp = sc->sc_ifp;
6819 	struct ieee80211com *ic = ifp->if_l2com;
6820 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
6821 
6822 	iwn_stop(sc);
6823 	if (vap != NULL)
6824 		ieee80211_stop(vap);
6825 
6826 	/* Enable interrupts to get RF toggle notification. */
6827 	IWN_LOCK(sc);
6828 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
6829 	IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
6830 	IWN_UNLOCK(sc);
6831 }
6832 
6833 static void
6834 iwn_init_locked(struct iwn_softc *sc)
6835 {
6836 	struct ifnet *ifp = sc->sc_ifp;
6837 	int error;
6838 
6839 	IWN_LOCK_ASSERT(sc);
6840 
6841 	if ((error = iwn_hw_prepare(sc)) != 0) {
6842 		device_printf(sc->sc_dev, "%s: hardware not ready, error %d\n",
6843 		    __func__, error);
6844 		goto fail;
6845 	}
6846 
6847 	/* Initialize interrupt mask to default value. */
6848 	sc->int_mask = IWN_INT_MASK_DEF;
6849 	sc->sc_flags &= ~IWN_FLAG_USE_ICT;
6850 
6851 	/* Check that the radio is not disabled by hardware switch. */
6852 	if (!(IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_RFKILL)) {
6853 		device_printf(sc->sc_dev,
6854 		    "radio is disabled by hardware switch\n");
6855 		/* Enable interrupts to get RF toggle notifications. */
6856 		IWN_WRITE(sc, IWN_INT, 0xffffffff);
6857 		IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
6858 		return;
6859 	}
6860 
6861 	/* Read firmware images from the filesystem. */
6862 	if ((error = iwn_read_firmware(sc)) != 0) {
6863 		device_printf(sc->sc_dev,
6864 		    "%s: could not read firmware, error %d\n", __func__,
6865 		    error);
6866 		goto fail;
6867 	}
6868 
6869 	/* Initialize hardware and upload firmware. */
6870 	error = iwn_hw_init(sc);
6871 	firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
6872 	sc->fw_fp = NULL;
6873 	if (error != 0) {
6874 		device_printf(sc->sc_dev,
6875 		    "%s: could not initialize hardware, error %d\n", __func__,
6876 		    error);
6877 		goto fail;
6878 	}
6879 
6880 	/* Configure adapter now that it is ready. */
6881 	if ((error = iwn_config(sc)) != 0) {
6882 		device_printf(sc->sc_dev,
6883 		    "%s: could not configure device, error %d\n", __func__,
6884 		    error);
6885 		goto fail;
6886 	}
6887 
6888 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
6889 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
6890 
6891 	callout_reset(&sc->watchdog_to, hz, iwn_watchdog, sc);
6892 	return;
6893 
6894 fail:	iwn_stop_locked(sc);
6895 }
6896 
6897 static void
6898 iwn_init(void *arg)
6899 {
6900 	struct iwn_softc *sc = arg;
6901 	struct ifnet *ifp = sc->sc_ifp;
6902 	struct ieee80211com *ic = ifp->if_l2com;
6903 
6904 	IWN_LOCK(sc);
6905 	iwn_init_locked(sc);
6906 	IWN_UNLOCK(sc);
6907 
6908 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
6909 		ieee80211_start_all(ic);
6910 }
6911 
6912 static void
6913 iwn_stop_locked(struct iwn_softc *sc)
6914 {
6915 	struct ifnet *ifp = sc->sc_ifp;
6916 
6917 	IWN_LOCK_ASSERT(sc);
6918 
6919 	sc->sc_tx_timer = 0;
6920 	callout_stop(&sc->watchdog_to);
6921 	callout_stop(&sc->calib_to);
6922 	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
6923 
6924 	/* Power OFF hardware. */
6925 	iwn_hw_stop(sc);
6926 }
6927 
6928 static void
6929 iwn_stop(struct iwn_softc *sc)
6930 {
6931 	IWN_LOCK(sc);
6932 	iwn_stop_locked(sc);
6933 	IWN_UNLOCK(sc);
6934 }
6935 
6936 /*
6937  * Callback from net80211 to start a scan.
6938  */
6939 static void
6940 iwn_scan_start(struct ieee80211com *ic)
6941 {
6942 	struct ifnet *ifp = ic->ic_ifp;
6943 	struct iwn_softc *sc = ifp->if_softc;
6944 
6945 	IWN_LOCK(sc);
6946 	/* make the link LED blink while we're scanning */
6947 	iwn_set_led(sc, IWN_LED_LINK, 20, 2);
6948 	IWN_UNLOCK(sc);
6949 }
6950 
6951 /*
6952  * Callback from net80211 to terminate a scan.
6953  */
6954 static void
6955 iwn_scan_end(struct ieee80211com *ic)
6956 {
6957 	struct ifnet *ifp = ic->ic_ifp;
6958 	struct iwn_softc *sc = ifp->if_softc;
6959 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
6960 
6961 	IWN_LOCK(sc);
6962 	if (vap->iv_state == IEEE80211_S_RUN) {
6963 		/* Set link LED to ON status if we are associated */
6964 		iwn_set_led(sc, IWN_LED_LINK, 0, 1);
6965 	}
6966 	IWN_UNLOCK(sc);
6967 }
6968 
6969 /*
6970  * Callback from net80211 to force a channel change.
6971  */
6972 static void
6973 iwn_set_channel(struct ieee80211com *ic)
6974 {
6975 	const struct ieee80211_channel *c = ic->ic_curchan;
6976 	struct ifnet *ifp = ic->ic_ifp;
6977 	struct iwn_softc *sc = ifp->if_softc;
6978 	int error;
6979 
6980 	IWN_LOCK(sc);
6981 	sc->sc_rxtap.wr_chan_freq = htole16(c->ic_freq);
6982 	sc->sc_rxtap.wr_chan_flags = htole16(c->ic_flags);
6983 	sc->sc_txtap.wt_chan_freq = htole16(c->ic_freq);
6984 	sc->sc_txtap.wt_chan_flags = htole16(c->ic_flags);
6985 
6986 	/*
6987 	 * Only need to set the channel in Monitor mode. AP scanning and auth
6988 	 * are already taken care of by their respective firmware commands.
6989 	 */
6990 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
6991 		error = iwn_config(sc);
6992 		if (error != 0)
6993 		device_printf(sc->sc_dev,
6994 		    "%s: error %d settting channel\n", __func__, error);
6995 	}
6996 	IWN_UNLOCK(sc);
6997 }
6998 
6999 /*
7000  * Callback from net80211 to start scanning of the current channel.
7001  */
7002 static void
7003 iwn_scan_curchan(struct ieee80211_scan_state *ss, unsigned long maxdwell)
7004 {
7005 	struct ieee80211vap *vap = ss->ss_vap;
7006 	struct iwn_softc *sc = vap->iv_ic->ic_ifp->if_softc;
7007 	int error;
7008 
7009 	IWN_LOCK(sc);
7010 	error = iwn_scan(sc);
7011 	IWN_UNLOCK(sc);
7012 	if (error != 0)
7013 		ieee80211_cancel_scan(vap);
7014 }
7015 
7016 /*
7017  * Callback from net80211 to handle the minimum dwell time being met.
7018  * The intent is to terminate the scan but we just let the firmware
7019  * notify us when it's finished as we have no safe way to abort it.
7020  */
7021 static void
7022 iwn_scan_mindwell(struct ieee80211_scan_state *ss)
7023 {
7024 	/* NB: don't try to abort scan; wait for firmware to finish */
7025 }
7026 
7027 static void
7028 iwn_hw_reset(void *arg0, int pending)
7029 {
7030 	struct iwn_softc *sc = arg0;
7031 	struct ifnet *ifp = sc->sc_ifp;
7032 	struct ieee80211com *ic = ifp->if_l2com;
7033 
7034 	iwn_stop(sc);
7035 	iwn_init(sc);
7036 	ieee80211_notify_radio(ic, 1);
7037 }
7038