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