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