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