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