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