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