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