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