xref: /netbsd-src/sys/dev/pci/if_wpi.c (revision 4d6fc14bc9b0c5bf3e30be318c143ee82cadd108)
1 /*	$NetBSD: if_wpi.c,v 1.90 2021/02/05 16:06:24 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 2006, 2007
5  *	Damien Bergamini <damien.bergamini@free.fr>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include <sys/cdefs.h>
21 __KERNEL_RCSID(0, "$NetBSD: if_wpi.c,v 1.90 2021/02/05 16:06:24 christos Exp $");
22 
23 /*
24  * Driver for Intel PRO/Wireless 3945ABG 802.11 network adapters.
25  */
26 
27 
28 #include <sys/param.h>
29 #include <sys/sockio.h>
30 #include <sys/sysctl.h>
31 #include <sys/mbuf.h>
32 #include <sys/kernel.h>
33 #include <sys/socket.h>
34 #include <sys/systm.h>
35 #include <sys/malloc.h>
36 #include <sys/mutex.h>
37 #include <sys/once.h>
38 #include <sys/conf.h>
39 #include <sys/kauth.h>
40 #include <sys/callout.h>
41 #include <sys/proc.h>
42 #include <sys/kthread.h>
43 
44 #include <sys/bus.h>
45 #include <machine/endian.h>
46 #include <sys/intr.h>
47 
48 #include <dev/pci/pcireg.h>
49 #include <dev/pci/pcivar.h>
50 #include <dev/pci/pcidevs.h>
51 
52 #include <dev/sysmon/sysmonvar.h>
53 
54 #include <net/bpf.h>
55 #include <net/if.h>
56 #include <net/if_arp.h>
57 #include <net/if_dl.h>
58 #include <net/if_ether.h>
59 #include <net/if_media.h>
60 #include <net/if_types.h>
61 
62 #include <netinet/in.h>
63 #include <netinet/in_systm.h>
64 #include <netinet/in_var.h>
65 #include <netinet/ip.h>
66 
67 #include <net80211/ieee80211_var.h>
68 #include <net80211/ieee80211_amrr.h>
69 #include <net80211/ieee80211_radiotap.h>
70 
71 #include <dev/firmload.h>
72 
73 #include <dev/pci/if_wpireg.h>
74 #include <dev/pci/if_wpivar.h>
75 
76 static const char wpi_firmware_name[] = "iwlwifi-3945.ucode";
77 static once_t wpi_firmware_init;
78 static kmutex_t wpi_firmware_mutex;
79 static size_t wpi_firmware_users;
80 static uint8_t *wpi_firmware_image;
81 static size_t wpi_firmware_size;
82 
83 static int	wpi_match(device_t, cfdata_t, void *);
84 static void	wpi_attach(device_t, device_t, void *);
85 static int	wpi_detach(device_t , int);
86 static int	wpi_dma_contig_alloc(bus_dma_tag_t, struct wpi_dma_info *,
87 		    void **, bus_size_t, bus_size_t, int);
88 static void	wpi_dma_contig_free(struct wpi_dma_info *);
89 static int	wpi_alloc_shared(struct wpi_softc *);
90 static void	wpi_free_shared(struct wpi_softc *);
91 static int	wpi_alloc_fwmem(struct wpi_softc *);
92 static void	wpi_free_fwmem(struct wpi_softc *);
93 static struct	wpi_rbuf *wpi_alloc_rbuf(struct wpi_softc *);
94 static void	wpi_free_rbuf(struct mbuf *, void *, size_t, void *);
95 static int	wpi_alloc_rpool(struct wpi_softc *);
96 static void	wpi_free_rpool(struct wpi_softc *);
97 static int	wpi_alloc_rx_ring(struct wpi_softc *, struct wpi_rx_ring *);
98 static void	wpi_reset_rx_ring(struct wpi_softc *, struct wpi_rx_ring *);
99 static void	wpi_free_rx_ring(struct wpi_softc *, struct wpi_rx_ring *);
100 static int	wpi_alloc_tx_ring(struct wpi_softc *, struct wpi_tx_ring *,
101 		    int, int);
102 static void	wpi_reset_tx_ring(struct wpi_softc *, struct wpi_tx_ring *);
103 static void	wpi_free_tx_ring(struct wpi_softc *, struct wpi_tx_ring *);
104 static struct	ieee80211_node * wpi_node_alloc(struct ieee80211_node_table *);
105 static void	wpi_newassoc(struct ieee80211_node *, int);
106 static int	wpi_media_change(struct ifnet *);
107 static int	wpi_newstate(struct ieee80211com *, enum ieee80211_state, int);
108 static void	wpi_mem_lock(struct wpi_softc *);
109 static void	wpi_mem_unlock(struct wpi_softc *);
110 static uint32_t	wpi_mem_read(struct wpi_softc *, uint16_t);
111 static void	wpi_mem_write(struct wpi_softc *, uint16_t, uint32_t);
112 static void	wpi_mem_write_region_4(struct wpi_softc *, uint16_t,
113 		    const uint32_t *, int);
114 static int	wpi_read_prom_data(struct wpi_softc *, uint32_t, void *, int);
115 static int	wpi_load_microcode(struct wpi_softc *,  const uint8_t *, int);
116 static int	wpi_cache_firmware(struct wpi_softc *);
117 static void	wpi_release_firmware(void);
118 static int	wpi_load_firmware(struct wpi_softc *);
119 static void	wpi_calib_timeout(void *);
120 static void	wpi_iter_func(void *, struct ieee80211_node *);
121 static void	wpi_power_calibration(struct wpi_softc *, int);
122 static void	wpi_rx_intr(struct wpi_softc *, struct wpi_rx_desc *,
123 		    struct wpi_rx_data *);
124 static void	wpi_tx_intr(struct wpi_softc *, struct wpi_rx_desc *);
125 static void	wpi_cmd_intr(struct wpi_softc *, struct wpi_rx_desc *);
126 static void	wpi_notif_intr(struct wpi_softc *);
127 static int	wpi_intr(void *);
128 static void	wpi_softintr(void *);
129 static void	wpi_read_eeprom(struct wpi_softc *);
130 static void	wpi_read_eeprom_channels(struct wpi_softc *, int);
131 static void	wpi_read_eeprom_group(struct wpi_softc *, int);
132 static uint8_t	wpi_plcp_signal(int);
133 static int	wpi_tx_data(struct wpi_softc *, struct mbuf *,
134 		    struct ieee80211_node *, int);
135 static void	wpi_start(struct ifnet *);
136 static void	wpi_watchdog(struct ifnet *);
137 static int	wpi_ioctl(struct ifnet *, u_long, void *);
138 static int	wpi_cmd(struct wpi_softc *, int, const void *, int, int);
139 static int	wpi_wme_update(struct ieee80211com *);
140 static int	wpi_mrr_setup(struct wpi_softc *);
141 static void	wpi_set_led(struct wpi_softc *, uint8_t, uint8_t, uint8_t);
142 static void	wpi_enable_tsf(struct wpi_softc *, struct ieee80211_node *);
143 static int	wpi_set_txpower(struct wpi_softc *,
144 		    struct ieee80211_channel *, int);
145 static int	wpi_get_power_index(struct wpi_softc *,
146 		    struct wpi_power_group *, struct ieee80211_channel *, int);
147 static int	wpi_setup_beacon(struct wpi_softc *, struct ieee80211_node *);
148 static int	wpi_auth(struct wpi_softc *);
149 static int	wpi_scan(struct wpi_softc *);
150 static int	wpi_config(struct wpi_softc *);
151 static void	wpi_stop_master(struct wpi_softc *);
152 static int	wpi_power_up(struct wpi_softc *);
153 static int	wpi_reset(struct wpi_softc *);
154 static void	wpi_hw_config(struct wpi_softc *);
155 static int	wpi_init(struct ifnet *);
156 static void	wpi_stop(struct ifnet *, int);
157 static bool	wpi_resume(device_t, const pmf_qual_t *);
158 static int	wpi_getrfkill(struct wpi_softc *);
159 static void	wpi_sysctlattach(struct wpi_softc *);
160 static void	wpi_rsw_thread(void *);
161 static void	wpi_rsw_suspend(struct wpi_softc *);
162 static void	wpi_stop_intr(struct ifnet *, int);
163 
164 #ifdef WPI_DEBUG
165 #define DPRINTF(x)	do { if (wpi_debug > 0) printf x; } while (0)
166 #define DPRINTFN(n, x)	do { if (wpi_debug >= (n)) printf x; } while (0)
167 int wpi_debug = 1;
168 #else
169 #define DPRINTF(x)
170 #define DPRINTFN(n, x)
171 #endif
172 
173 CFATTACH_DECL_NEW(wpi, sizeof (struct wpi_softc), wpi_match, wpi_attach,
174 	wpi_detach, NULL);
175 
176 static int
177 wpi_match(device_t parent, cfdata_t match __unused, void *aux)
178 {
179 	struct pci_attach_args *pa = aux;
180 
181 	if (PCI_VENDOR(pa->pa_id) != PCI_VENDOR_INTEL)
182 		return 0;
183 
184 	if (PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_INTEL_PRO_WL_3945ABG_1 ||
185 	    PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_INTEL_PRO_WL_3945ABG_2)
186 		return 1;
187 
188 	return 0;
189 }
190 
191 /* Base Address Register */
192 #define WPI_PCI_BAR0	0x10
193 
194 static int
195 wpi_attach_once(void)
196 {
197 
198 	mutex_init(&wpi_firmware_mutex, MUTEX_DEFAULT, IPL_NONE);
199 	return 0;
200 }
201 
202 static void
203 wpi_attach(device_t parent __unused, device_t self, void *aux)
204 {
205 	struct wpi_softc *sc = device_private(self);
206 	struct ieee80211com *ic = &sc->sc_ic;
207 	struct ifnet *ifp = &sc->sc_ec.ec_if;
208 	struct pci_attach_args *pa = aux;
209 	const char *intrstr;
210 	bus_space_tag_t memt;
211 	bus_space_handle_t memh;
212 	pcireg_t data;
213 	int ac, error;
214 	char intrbuf[PCI_INTRSTR_LEN];
215 
216 	RUN_ONCE(&wpi_firmware_init, wpi_attach_once);
217 	sc->fw_used = false;
218 
219 	sc->sc_dev = self;
220 	sc->sc_pct = pa->pa_pc;
221 	sc->sc_pcitag = pa->pa_tag;
222 
223 	sc->sc_rsw_status = WPI_RSW_UNKNOWN;
224 	sc->sc_rsw.smpsw_name = device_xname(self);
225 	sc->sc_rsw.smpsw_type = PSWITCH_TYPE_RADIO;
226 	error = sysmon_pswitch_register(&sc->sc_rsw);
227 	if (error) {
228 		aprint_error_dev(self,
229 		    "unable to register radio switch with sysmon\n");
230 		return;
231 	}
232 	mutex_init(&sc->sc_rsw_mtx, MUTEX_DEFAULT, IPL_NONE);
233 	cv_init(&sc->sc_rsw_cv, "wpirsw");
234 	sc->sc_rsw_suspend = false;
235 	sc->sc_rsw_suspended = false;
236 	if (kthread_create(PRI_NONE, 0, NULL,
237 	    wpi_rsw_thread, sc, &sc->sc_rsw_lwp, "%s", device_xname(self))) {
238 		aprint_error_dev(self, "couldn't create switch thread\n");
239 	}
240 
241 	callout_init(&sc->calib_to, 0);
242 	callout_setfunc(&sc->calib_to, wpi_calib_timeout, sc);
243 
244 	pci_aprint_devinfo(pa, NULL);
245 
246 	/* enable bus-mastering */
247 	data = pci_conf_read(sc->sc_pct, sc->sc_pcitag, PCI_COMMAND_STATUS_REG);
248 	data |= PCI_COMMAND_MASTER_ENABLE;
249 	pci_conf_write(sc->sc_pct, sc->sc_pcitag, PCI_COMMAND_STATUS_REG, data);
250 
251 	/* map the register window */
252 	error = pci_mapreg_map(pa, WPI_PCI_BAR0, PCI_MAPREG_TYPE_MEM |
253 	    PCI_MAPREG_MEM_TYPE_32BIT, 0, &memt, &memh, NULL, &sc->sc_sz);
254 	if (error != 0) {
255 		aprint_error_dev(self, "could not map memory space\n");
256 		return;
257 	}
258 
259 	sc->sc_st = memt;
260 	sc->sc_sh = memh;
261 	sc->sc_dmat = pa->pa_dmat;
262 
263 	sc->sc_soft_ih = softint_establish(SOFTINT_NET, wpi_softintr, sc);
264 	if (sc->sc_soft_ih == NULL) {
265 		aprint_error_dev(self, "could not establish softint\n");
266 		goto unmap;
267 	}
268 
269 	if (pci_intr_alloc(pa, &sc->sc_pihp, NULL, 0)) {
270 		aprint_error_dev(self, "could not map interrupt\n");
271 		goto failsi;
272 	}
273 
274 	intrstr = pci_intr_string(sc->sc_pct, sc->sc_pihp[0], intrbuf,
275 	    sizeof(intrbuf));
276 	sc->sc_ih = pci_intr_establish_xname(sc->sc_pct, sc->sc_pihp[0],
277 	    IPL_NET, wpi_intr, sc, device_xname(self));
278 	if (sc->sc_ih == NULL) {
279 		aprint_error_dev(self, "could not establish interrupt");
280 		if (intrstr != NULL)
281 			aprint_error(" at %s", intrstr);
282 		aprint_error("\n");
283 		goto failia;
284 	}
285 	aprint_normal_dev(self, "interrupting at %s\n", intrstr);
286 
287 	/*
288 	 * Put adapter into a known state.
289 	 */
290 	if ((error = wpi_reset(sc)) != 0) {
291 		aprint_error_dev(self, "could not reset adapter\n");
292 		goto failih;
293 	}
294 
295 	/*
296 	 * Allocate DMA memory for firmware transfers.
297 	 */
298 	if ((error = wpi_alloc_fwmem(sc)) != 0) {
299 		aprint_error_dev(self, "could not allocate firmware memory\n");
300 		goto failih;
301 	}
302 
303 	/*
304 	 * Allocate shared page and Tx/Rx rings.
305 	 */
306 	if ((error = wpi_alloc_shared(sc)) != 0) {
307 		aprint_error_dev(self, "could not allocate shared area\n");
308 		goto fail1;
309 	}
310 
311 	if ((error = wpi_alloc_rpool(sc)) != 0) {
312 		aprint_error_dev(self, "could not allocate Rx buffers\n");
313 		goto fail2;
314 	}
315 
316 	for (ac = 0; ac < 4; ac++) {
317 		error = wpi_alloc_tx_ring(sc, &sc->txq[ac], WPI_TX_RING_COUNT,
318 		    ac);
319 		if (error != 0) {
320 			aprint_error_dev(self,
321 			    "could not allocate Tx ring %d\n", ac);
322 			goto fail3;
323 		}
324 	}
325 
326 	error = wpi_alloc_tx_ring(sc, &sc->cmdq, WPI_CMD_RING_COUNT, 4);
327 	if (error != 0) {
328 		aprint_error_dev(self, "could not allocate command ring\n");
329 		goto fail3;
330 	}
331 
332 	error = wpi_alloc_rx_ring(sc, &sc->rxq);
333 	if (error != 0) {
334 		aprint_error_dev(self, "could not allocate Rx ring\n");
335 		goto fail4;
336 	}
337 
338 	ic->ic_ifp = ifp;
339 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
340 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
341 	ic->ic_state = IEEE80211_S_INIT;
342 
343 	/* set device capabilities */
344 	ic->ic_caps =
345 	    IEEE80211_C_WPA |		/* 802.11i */
346 	    IEEE80211_C_MONITOR |	/* monitor mode supported */
347 	    IEEE80211_C_TXPMGT |	/* tx power management */
348 	    IEEE80211_C_SHSLOT |	/* short slot time supported */
349 	    IEEE80211_C_SHPREAMBLE |	/* short preamble supported */
350 	    IEEE80211_C_WME;		/* 802.11e */
351 
352 	/* read supported channels and MAC address from EEPROM */
353 	wpi_read_eeprom(sc);
354 
355 	/* set supported .11a, .11b and .11g rates */
356 	ic->ic_sup_rates[IEEE80211_MODE_11A] = ieee80211_std_rateset_11a;
357 	ic->ic_sup_rates[IEEE80211_MODE_11B] = ieee80211_std_rateset_11b;
358 	ic->ic_sup_rates[IEEE80211_MODE_11G] = ieee80211_std_rateset_11g;
359 
360 	/* IBSS channel undefined for now */
361 	ic->ic_ibss_chan = &ic->ic_channels[0];
362 
363 	ifp->if_softc = sc;
364 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
365 	ifp->if_init = wpi_init;
366 	ifp->if_stop = wpi_stop;
367 	ifp->if_ioctl = wpi_ioctl;
368 	ifp->if_start = wpi_start;
369 	ifp->if_watchdog = wpi_watchdog;
370 	IFQ_SET_READY(&ifp->if_snd);
371 	memcpy(ifp->if_xname, device_xname(self), IFNAMSIZ);
372 
373 	error = if_initialize(ifp);
374 	if (error != 0) {
375 		aprint_error_dev(sc->sc_dev, "if_initialize failed(%d)\n",
376 		    error);
377 		goto fail5;
378 	}
379 	ieee80211_ifattach(ic);
380 	/* Use common softint-based if_input */
381 	ifp->if_percpuq = if_percpuq_create(ifp);
382 	if_register(ifp);
383 
384 	/* override default methods */
385 	ic->ic_node_alloc = wpi_node_alloc;
386 	ic->ic_newassoc = wpi_newassoc;
387 	ic->ic_wme.wme_update = wpi_wme_update;
388 
389 	/* override state transition machine */
390 	sc->sc_newstate = ic->ic_newstate;
391 	ic->ic_newstate = wpi_newstate;
392 
393 	/* XXX media locking needs revisiting */
394 	mutex_init(&sc->sc_media_mtx, MUTEX_DEFAULT, IPL_SOFTNET);
395 	ieee80211_media_init_with_lock(ic,
396 	    wpi_media_change, ieee80211_media_status, &sc->sc_media_mtx);
397 
398 	sc->amrr.amrr_min_success_threshold =  1;
399 	sc->amrr.amrr_max_success_threshold = 15;
400 
401 	wpi_sysctlattach(sc);
402 
403 	if (pmf_device_register(self, NULL, wpi_resume))
404 		pmf_class_network_register(self, ifp);
405 	else
406 		aprint_error_dev(self, "couldn't establish power handler\n");
407 
408 	bpf_attach2(ifp, DLT_IEEE802_11_RADIO,
409 	    sizeof(struct ieee80211_frame) + IEEE80211_RADIOTAP_HDRLEN,
410 	    &sc->sc_drvbpf);
411 
412 	sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
413 	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
414 	sc->sc_rxtap.wr_ihdr.it_present = htole32(WPI_RX_RADIOTAP_PRESENT);
415 
416 	sc->sc_txtap_len = sizeof sc->sc_txtapu;
417 	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
418 	sc->sc_txtap.wt_ihdr.it_present = htole32(WPI_TX_RADIOTAP_PRESENT);
419 
420 	ieee80211_announce(ic);
421 
422 	return;
423 
424 	/* free allocated memory if something failed during attachment */
425 fail5:	wpi_free_rx_ring(sc, &sc->rxq);
426 fail4:	wpi_free_tx_ring(sc, &sc->cmdq);
427 fail3:	while (--ac >= 0)
428 		wpi_free_tx_ring(sc, &sc->txq[ac]);
429 	wpi_free_rpool(sc);
430 fail2:	wpi_free_shared(sc);
431 fail1:	wpi_free_fwmem(sc);
432 failih:	pci_intr_disestablish(sc->sc_pct, sc->sc_ih);
433 	sc->sc_ih = NULL;
434 failia:	pci_intr_release(sc->sc_pct, sc->sc_pihp, 1);
435 	sc->sc_pihp = NULL;
436 failsi:	softint_disestablish(sc->sc_soft_ih);
437 	sc->sc_soft_ih = NULL;
438 unmap:	bus_space_unmap(sc->sc_st, sc->sc_sh, sc->sc_sz);
439 }
440 
441 static int
442 wpi_detach(device_t self, int flags __unused)
443 {
444 	struct wpi_softc *sc = device_private(self);
445 	struct ifnet *ifp = sc->sc_ic.ic_ifp;
446 	int ac;
447 
448 	wpi_stop(ifp, 1);
449 
450 	if (ifp != NULL)
451 		bpf_detach(ifp);
452 	ieee80211_ifdetach(&sc->sc_ic);
453 	if (ifp != NULL)
454 		if_detach(ifp);
455 
456 	for (ac = 0; ac < 4; ac++)
457 		wpi_free_tx_ring(sc, &sc->txq[ac]);
458 	wpi_free_tx_ring(sc, &sc->cmdq);
459 	wpi_free_rx_ring(sc, &sc->rxq);
460 	wpi_free_rpool(sc);
461 	wpi_free_shared(sc);
462 
463 	if (sc->sc_ih != NULL) {
464 		pci_intr_disestablish(sc->sc_pct, sc->sc_ih);
465 		sc->sc_ih = NULL;
466 	}
467 	if (sc->sc_pihp != NULL) {
468 		pci_intr_release(sc->sc_pct, sc->sc_pihp, 1);
469 		sc->sc_pihp = NULL;
470 	}
471 	if (sc->sc_soft_ih != NULL) {
472 		softint_disestablish(sc->sc_soft_ih);
473 		sc->sc_soft_ih = NULL;
474 	}
475 
476 	mutex_enter(&sc->sc_rsw_mtx);
477 	sc->sc_dying = 1;
478 	cv_signal(&sc->sc_rsw_cv);
479 	while (sc->sc_rsw_lwp != NULL)
480 		cv_wait(&sc->sc_rsw_cv, &sc->sc_rsw_mtx);
481 	mutex_exit(&sc->sc_rsw_mtx);
482 	sysmon_pswitch_unregister(&sc->sc_rsw);
483 
484 	bus_space_unmap(sc->sc_st, sc->sc_sh, sc->sc_sz);
485 
486 	if (sc->fw_used) {
487 		sc->fw_used = false;
488 		wpi_release_firmware();
489 	}
490 	cv_destroy(&sc->sc_rsw_cv);
491 	mutex_destroy(&sc->sc_rsw_mtx);
492 	return 0;
493 }
494 
495 static int
496 wpi_dma_contig_alloc(bus_dma_tag_t tag, struct wpi_dma_info *dma, void **kvap,
497     bus_size_t size, bus_size_t alignment, int flags)
498 {
499 	int nsegs, error;
500 
501 	dma->tag = tag;
502 	dma->size = size;
503 
504 	error = bus_dmamap_create(tag, size, 1, size, 0, flags, &dma->map);
505 	if (error != 0)
506 		goto fail;
507 
508 	error = bus_dmamem_alloc(tag, size, alignment, 0, &dma->seg, 1, &nsegs,
509 	    flags);
510 	if (error != 0)
511 		goto fail;
512 
513 	error = bus_dmamem_map(tag, &dma->seg, 1, size, &dma->vaddr, flags);
514 	if (error != 0)
515 		goto fail;
516 
517 	error = bus_dmamap_load(tag, dma->map, dma->vaddr, size, NULL, flags);
518 	if (error != 0)
519 		goto fail;
520 
521 	memset(dma->vaddr, 0, size);
522 	bus_dmamap_sync(dma->tag, dma->map, 0, size, BUS_DMASYNC_PREWRITE);
523 
524 	dma->paddr = dma->map->dm_segs[0].ds_addr;
525 	if (kvap != NULL)
526 		*kvap = dma->vaddr;
527 
528 	return 0;
529 
530 fail:	wpi_dma_contig_free(dma);
531 	return error;
532 }
533 
534 static void
535 wpi_dma_contig_free(struct wpi_dma_info *dma)
536 {
537 	if (dma->map != NULL) {
538 		if (dma->vaddr != NULL) {
539 			bus_dmamap_unload(dma->tag, dma->map);
540 			bus_dmamem_unmap(dma->tag, dma->vaddr, dma->size);
541 			bus_dmamem_free(dma->tag, &dma->seg, 1);
542 			dma->vaddr = NULL;
543 		}
544 		bus_dmamap_destroy(dma->tag, dma->map);
545 		dma->map = NULL;
546 	}
547 }
548 
549 /*
550  * Allocate a shared page between host and NIC.
551  */
552 static int
553 wpi_alloc_shared(struct wpi_softc *sc)
554 {
555 	int error;
556 
557 	/* must be aligned on a 4K-page boundary */
558 	error = wpi_dma_contig_alloc(sc->sc_dmat, &sc->shared_dma,
559 	    (void **)&sc->shared, sizeof (struct wpi_shared), WPI_BUF_ALIGN,
560 	    BUS_DMA_NOWAIT);
561 	if (error != 0)
562 		aprint_error_dev(sc->sc_dev,
563 		    "could not allocate shared area DMA memory\n");
564 
565 	return error;
566 }
567 
568 static void
569 wpi_free_shared(struct wpi_softc *sc)
570 {
571 	wpi_dma_contig_free(&sc->shared_dma);
572 }
573 
574 /*
575  * Allocate DMA-safe memory for firmware transfer.
576  */
577 static int
578 wpi_alloc_fwmem(struct wpi_softc *sc)
579 {
580 	int error;
581 
582 	/* allocate enough contiguous space to store text and data */
583 	error = wpi_dma_contig_alloc(sc->sc_dmat, &sc->fw_dma, NULL,
584 	    WPI_FW_MAIN_TEXT_MAXSZ + WPI_FW_MAIN_DATA_MAXSZ, 0,
585 	    BUS_DMA_NOWAIT);
586 
587 	if (error != 0)
588 		aprint_error_dev(sc->sc_dev,
589 		    "could not allocate firmware transfer area DMA memory\n");
590 	return error;
591 }
592 
593 static void
594 wpi_free_fwmem(struct wpi_softc *sc)
595 {
596 	wpi_dma_contig_free(&sc->fw_dma);
597 }
598 
599 static struct wpi_rbuf *
600 wpi_alloc_rbuf(struct wpi_softc *sc)
601 {
602 	struct wpi_rbuf *rbuf;
603 
604 	mutex_enter(&sc->rxq.freelist_mtx);
605 	rbuf = SLIST_FIRST(&sc->rxq.freelist);
606 	if (rbuf != NULL) {
607 		SLIST_REMOVE_HEAD(&sc->rxq.freelist, next);
608 	}
609 	mutex_exit(&sc->rxq.freelist_mtx);
610 
611 	return rbuf;
612 }
613 
614 /*
615  * This is called automatically by the network stack when the mbuf to which our
616  * Rx buffer is attached is freed.
617  */
618 static void
619 wpi_free_rbuf(struct mbuf* m, void *buf, size_t size, void *arg)
620 {
621 	struct wpi_rbuf *rbuf = arg;
622 	struct wpi_softc *sc = rbuf->sc;
623 
624 	/* put the buffer back in the free list */
625 
626 	mutex_enter(&sc->rxq.freelist_mtx);
627 	SLIST_INSERT_HEAD(&sc->rxq.freelist, rbuf, next);
628 	mutex_exit(&sc->rxq.freelist_mtx);
629 
630 	if (__predict_true(m != NULL))
631 		pool_cache_put(mb_cache, m);
632 }
633 
634 static int
635 wpi_alloc_rpool(struct wpi_softc *sc)
636 {
637 	struct wpi_rx_ring *ring = &sc->rxq;
638 	int i, error;
639 
640 	/* allocate a big chunk of DMA'able memory.. */
641 	error = wpi_dma_contig_alloc(sc->sc_dmat, &ring->buf_dma, NULL,
642 	    WPI_RBUF_COUNT * WPI_RBUF_SIZE, WPI_BUF_ALIGN, BUS_DMA_NOWAIT);
643 	if (error != 0) {
644 		aprint_normal_dev(sc->sc_dev,
645 		    "could not allocate Rx buffers DMA memory\n");
646 		return error;
647 	}
648 
649 	/* ..and split it into 3KB chunks */
650 	mutex_init(&ring->freelist_mtx, MUTEX_DEFAULT, IPL_NET);
651 	SLIST_INIT(&ring->freelist);
652 	for (i = 0; i < WPI_RBUF_COUNT; i++) {
653 		struct wpi_rbuf *rbuf = &ring->rbuf[i];
654 
655 		rbuf->sc = sc;	/* backpointer for callbacks */
656 		rbuf->vaddr = (char *)ring->buf_dma.vaddr + i * WPI_RBUF_SIZE;
657 		rbuf->paddr = ring->buf_dma.paddr + i * WPI_RBUF_SIZE;
658 
659 		SLIST_INSERT_HEAD(&ring->freelist, rbuf, next);
660 	}
661 
662 	return 0;
663 }
664 
665 static void
666 wpi_free_rpool(struct wpi_softc *sc)
667 {
668 	mutex_destroy(&sc->rxq.freelist_mtx);
669 	wpi_dma_contig_free(&sc->rxq.buf_dma);
670 }
671 
672 static int
673 wpi_alloc_rx_ring(struct wpi_softc *sc, struct wpi_rx_ring *ring)
674 {
675 	bus_size_t size;
676 	int i, error;
677 
678 	ring->cur = 0;
679 
680 	size = WPI_RX_RING_COUNT * sizeof (struct wpi_rx_desc);
681 	error = wpi_dma_contig_alloc(sc->sc_dmat, &ring->desc_dma,
682 	    (void **)&ring->desc, size,
683 	    WPI_RING_DMA_ALIGN, BUS_DMA_NOWAIT);
684 	if (error != 0) {
685 		aprint_error_dev(sc->sc_dev,
686 		    "could not allocate rx ring DMA memory\n");
687 		goto fail;
688 	}
689 
690 	/*
691 	 * Setup Rx buffers.
692 	 */
693 	for (i = 0; i < WPI_RX_RING_COUNT; i++) {
694 		struct wpi_rx_data *data = &ring->data[i];
695 		struct wpi_rbuf *rbuf;
696 
697 		error = bus_dmamap_create(sc->sc_dmat, WPI_RBUF_SIZE, 1,
698 		    WPI_RBUF_SIZE, 0, BUS_DMA_NOWAIT, &data->map);
699 		if (error) {
700 			aprint_error_dev(sc->sc_dev,
701 			    "could not allocate rx dma map\n");
702 			goto fail;
703 		}
704 
705 		MGETHDR(data->m, M_DONTWAIT, MT_DATA);
706 		if (data->m == NULL) {
707 			aprint_error_dev(sc->sc_dev,
708 			    "could not allocate rx mbuf\n");
709 			error = ENOMEM;
710 			goto fail;
711 		}
712 		if ((rbuf = wpi_alloc_rbuf(sc)) == NULL) {
713 			m_freem(data->m);
714 			data->m = NULL;
715 			aprint_error_dev(sc->sc_dev,
716 			    "could not allocate rx cluster\n");
717 			error = ENOMEM;
718 			goto fail;
719 		}
720 		/* attach Rx buffer to mbuf */
721 		MEXTADD(data->m, rbuf->vaddr, WPI_RBUF_SIZE, 0, wpi_free_rbuf,
722 		    rbuf);
723 		data->m->m_flags |= M_EXT_RW;
724 
725 		error = bus_dmamap_load(sc->sc_dmat, data->map,
726 		    mtod(data->m, void *), WPI_RBUF_SIZE, NULL,
727 		    BUS_DMA_NOWAIT | BUS_DMA_READ);
728 		if (error) {
729 			aprint_error_dev(sc->sc_dev,
730 			    "could not load mbuf: %d\n", error);
731 			goto fail;
732 		}
733 
734 		ring->desc[i] = htole32(rbuf->paddr);
735 	}
736 
737 	bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map, 0, size,
738 	    BUS_DMASYNC_PREWRITE);
739 
740 	return 0;
741 
742 fail:	wpi_free_rx_ring(sc, ring);
743 	return error;
744 }
745 
746 static void
747 wpi_reset_rx_ring(struct wpi_softc *sc, struct wpi_rx_ring *ring)
748 {
749 	int ntries;
750 
751 	wpi_mem_lock(sc);
752 
753 	WPI_WRITE(sc, WPI_RX_CONFIG, 0);
754 	for (ntries = 0; ntries < 100; ntries++) {
755 		if (WPI_READ(sc, WPI_RX_STATUS) & WPI_RX_IDLE)
756 			break;
757 		DELAY(10);
758 	}
759 #ifdef WPI_DEBUG
760 	if (ntries == 100 && wpi_debug > 0)
761 		aprint_error_dev(sc->sc_dev, "timeout resetting Rx ring\n");
762 #endif
763 	wpi_mem_unlock(sc);
764 
765 	ring->cur = 0;
766 }
767 
768 static void
769 wpi_free_rx_ring(struct wpi_softc *sc, struct wpi_rx_ring *ring)
770 {
771 	int i;
772 
773 	wpi_dma_contig_free(&ring->desc_dma);
774 
775 	for (i = 0; i < WPI_RX_RING_COUNT; i++) {
776 		if (ring->data[i].m != NULL) {
777 			bus_dmamap_unload(sc->sc_dmat, ring->data[i].map);
778 			m_freem(ring->data[i].m);
779 		}
780 		if (ring->data[i].map != NULL) {
781 			bus_dmamap_destroy(sc->sc_dmat, ring->data[i].map);
782 		}
783 	}
784 }
785 
786 static int
787 wpi_alloc_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring, int count,
788     int qid)
789 {
790 	int i, error;
791 
792 	ring->qid = qid;
793 	ring->count = count;
794 	ring->queued = 0;
795 	ring->cur = 0;
796 
797 	error = wpi_dma_contig_alloc(sc->sc_dmat, &ring->desc_dma,
798 	    (void **)&ring->desc, count * sizeof (struct wpi_tx_desc),
799 	    WPI_RING_DMA_ALIGN, BUS_DMA_NOWAIT);
800 	if (error != 0) {
801 		aprint_error_dev(sc->sc_dev,
802 		    "could not allocate tx ring DMA memory\n");
803 		goto fail;
804 	}
805 
806 	/* update shared page with ring's base address */
807 	sc->shared->txbase[qid] = htole32(ring->desc_dma.paddr);
808 	bus_dmamap_sync(sc->sc_dmat, sc->shared_dma.map, 0,
809 	    sizeof(struct wpi_shared), BUS_DMASYNC_PREWRITE);
810 
811 	error = wpi_dma_contig_alloc(sc->sc_dmat, &ring->cmd_dma,
812 	    (void **)&ring->cmd, count * sizeof (struct wpi_tx_cmd), 4,
813 	    BUS_DMA_NOWAIT);
814 	if (error != 0) {
815 		aprint_error_dev(sc->sc_dev,
816 		    "could not allocate tx cmd DMA memory\n");
817 		goto fail;
818 	}
819 
820 	ring->data = malloc(count * sizeof (struct wpi_tx_data), M_DEVBUF,
821 	    M_WAITOK | M_ZERO);
822 
823 	for (i = 0; i < count; i++) {
824 		struct wpi_tx_data *data = &ring->data[i];
825 
826 		error = bus_dmamap_create(sc->sc_dmat, MCLBYTES,
827 		    WPI_MAX_SCATTER - 1, MCLBYTES, 0, BUS_DMA_NOWAIT,
828 		    &data->map);
829 		if (error != 0) {
830 			aprint_error_dev(sc->sc_dev,
831 			    "could not create tx buf DMA map\n");
832 			goto fail;
833 		}
834 	}
835 
836 	return 0;
837 
838 fail:	wpi_free_tx_ring(sc, ring);
839 	return error;
840 }
841 
842 static void
843 wpi_reset_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring)
844 {
845 	int i, ntries;
846 
847 	wpi_mem_lock(sc);
848 
849 	WPI_WRITE(sc, WPI_TX_CONFIG(ring->qid), 0);
850 	for (ntries = 0; ntries < 100; ntries++) {
851 		if (WPI_READ(sc, WPI_TX_STATUS) & WPI_TX_IDLE(ring->qid))
852 			break;
853 		DELAY(10);
854 	}
855 #ifdef WPI_DEBUG
856 	if (ntries == 100 && wpi_debug > 0) {
857 		aprint_error_dev(sc->sc_dev, "timeout resetting Tx ring %d\n",
858 		    ring->qid);
859 	}
860 #endif
861 	wpi_mem_unlock(sc);
862 
863 	for (i = 0; i < ring->count; i++) {
864 		struct wpi_tx_data *data = &ring->data[i];
865 
866 		if (data->m != NULL) {
867 			bus_dmamap_unload(sc->sc_dmat, data->map);
868 			m_freem(data->m);
869 			data->m = NULL;
870 		}
871 	}
872 
873 	ring->queued = 0;
874 	ring->cur = 0;
875 }
876 
877 static void
878 wpi_free_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring)
879 {
880 	int i;
881 
882 	wpi_dma_contig_free(&ring->desc_dma);
883 	wpi_dma_contig_free(&ring->cmd_dma);
884 
885 	if (ring->data != NULL) {
886 		for (i = 0; i < ring->count; i++) {
887 			struct wpi_tx_data *data = &ring->data[i];
888 
889 			if (data->m != NULL) {
890 				bus_dmamap_unload(sc->sc_dmat, data->map);
891 				m_freem(data->m);
892 			}
893 		}
894 		free(ring->data, M_DEVBUF);
895 	}
896 }
897 
898 /*ARGUSED*/
899 static struct ieee80211_node *
900 wpi_node_alloc(struct ieee80211_node_table *nt __unused)
901 {
902 	struct wpi_node *wn;
903 
904 	wn = malloc(sizeof (struct wpi_node), M_80211_NODE, M_NOWAIT | M_ZERO);
905 
906 	return (struct ieee80211_node *)wn;
907 }
908 
909 static void
910 wpi_newassoc(struct ieee80211_node *ni, int isnew)
911 {
912 	struct wpi_softc *sc = ni->ni_ic->ic_ifp->if_softc;
913 	int i;
914 
915 	ieee80211_amrr_node_init(&sc->amrr, &((struct wpi_node *)ni)->amn);
916 
917 	/* set rate to some reasonable initial value */
918 	for (i = ni->ni_rates.rs_nrates - 1;
919 	     i > 0 && (ni->ni_rates.rs_rates[i] & IEEE80211_RATE_VAL) > 72;
920 	     i--);
921 	ni->ni_txrate = i;
922 }
923 
924 static int
925 wpi_media_change(struct ifnet *ifp)
926 {
927 	int error;
928 
929 	error = ieee80211_media_change(ifp);
930 	if (error != ENETRESET)
931 		return error;
932 
933 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
934 		wpi_init(ifp);
935 
936 	return 0;
937 }
938 
939 static int
940 wpi_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
941 {
942 	struct ifnet *ifp = ic->ic_ifp;
943 	struct wpi_softc *sc = ifp->if_softc;
944 	struct ieee80211_node *ni;
945 	enum ieee80211_state ostate = ic->ic_state;
946 	int error;
947 
948 	callout_stop(&sc->calib_to);
949 
950 	switch (nstate) {
951 	case IEEE80211_S_SCAN:
952 
953 		if (sc->is_scanning)
954 			break;
955 
956 		sc->is_scanning = true;
957 
958 		if (ostate != IEEE80211_S_SCAN) {
959 			/* make the link LED blink while we're scanning */
960 			wpi_set_led(sc, WPI_LED_LINK, 20, 2);
961 		}
962 
963 		if ((error = wpi_scan(sc)) != 0) {
964 			aprint_error_dev(sc->sc_dev,
965 			    "could not initiate scan\n");
966 			return error;
967 		}
968 		break;
969 
970 	case IEEE80211_S_ASSOC:
971 		if (ic->ic_state != IEEE80211_S_RUN)
972 			break;
973 		/* FALLTHROUGH */
974 	case IEEE80211_S_AUTH:
975 		/* reset state to handle reassociations correctly */
976 		sc->config.associd = 0;
977 		sc->config.filter &= ~htole32(WPI_FILTER_BSS);
978 
979 		if ((error = wpi_auth(sc)) != 0) {
980 			aprint_error_dev(sc->sc_dev,
981 			    "could not send authentication request\n");
982 			return error;
983 		}
984 		break;
985 
986 	case IEEE80211_S_RUN:
987 		if (ic->ic_opmode == IEEE80211_M_MONITOR) {
988 			/* link LED blinks while monitoring */
989 			wpi_set_led(sc, WPI_LED_LINK, 5, 5);
990 			break;
991 		}
992 		ni = ic->ic_bss;
993 
994 		if (ic->ic_opmode != IEEE80211_M_STA) {
995 			(void) wpi_auth(sc);    /* XXX */
996 			wpi_setup_beacon(sc, ni);
997 		}
998 
999 		wpi_enable_tsf(sc, ni);
1000 
1001 		/* update adapter's configuration */
1002 		sc->config.associd = htole16(ni->ni_associd & ~0xc000);
1003 		/* short preamble/slot time are negotiated when associating */
1004 		sc->config.flags &= ~htole32(WPI_CONFIG_SHPREAMBLE |
1005 		    WPI_CONFIG_SHSLOT);
1006 		if (ic->ic_flags & IEEE80211_F_SHSLOT)
1007 			sc->config.flags |= htole32(WPI_CONFIG_SHSLOT);
1008 		if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
1009 			sc->config.flags |= htole32(WPI_CONFIG_SHPREAMBLE);
1010 		sc->config.filter |= htole32(WPI_FILTER_BSS);
1011 		if (ic->ic_opmode != IEEE80211_M_STA)
1012 			sc->config.filter |= htole32(WPI_FILTER_BEACON);
1013 
1014 /* XXX put somewhere HC_QOS_SUPPORT_ASSOC + HC_IBSS_START */
1015 
1016 		DPRINTF(("config chan %d flags %x\n", sc->config.chan,
1017 		    sc->config.flags));
1018 		error = wpi_cmd(sc, WPI_CMD_CONFIGURE, &sc->config,
1019 		    sizeof (struct wpi_config), 1);
1020 		if (error != 0) {
1021 			aprint_error_dev(sc->sc_dev,
1022 			    "could not update configuration\n");
1023 			return error;
1024 		}
1025 
1026 		/* configuration has changed, set Tx power accordingly */
1027 		if ((error = wpi_set_txpower(sc, ic->ic_curchan, 1)) != 0) {
1028 			aprint_error_dev(sc->sc_dev,
1029 			    "could not set Tx power\n");
1030 			return error;
1031 		}
1032 
1033 		if (ic->ic_opmode == IEEE80211_M_STA) {
1034 			/* fake a join to init the tx rate */
1035 			wpi_newassoc(ni, 1);
1036 		}
1037 
1038 		/* start periodic calibration timer */
1039 		sc->calib_cnt = 0;
1040 		callout_schedule(&sc->calib_to, hz/2);
1041 
1042 		/* link LED always on while associated */
1043 		wpi_set_led(sc, WPI_LED_LINK, 0, 1);
1044 		break;
1045 
1046 	case IEEE80211_S_INIT:
1047 		sc->is_scanning = false;
1048 		break;
1049 	}
1050 
1051 	return sc->sc_newstate(ic, nstate, arg);
1052 }
1053 
1054 /*
1055  * Grab exclusive access to NIC memory.
1056  */
1057 static void
1058 wpi_mem_lock(struct wpi_softc *sc)
1059 {
1060 	uint32_t tmp;
1061 	int ntries;
1062 
1063 	tmp = WPI_READ(sc, WPI_GPIO_CTL);
1064 	WPI_WRITE(sc, WPI_GPIO_CTL, tmp | WPI_GPIO_MAC);
1065 
1066 	/* spin until we actually get the lock */
1067 	for (ntries = 0; ntries < 1000; ntries++) {
1068 		if ((WPI_READ(sc, WPI_GPIO_CTL) &
1069 		    (WPI_GPIO_CLOCK | WPI_GPIO_SLEEP)) == WPI_GPIO_CLOCK)
1070 			break;
1071 		DELAY(10);
1072 	}
1073 	if (ntries == 1000)
1074 		aprint_error_dev(sc->sc_dev, "could not lock memory\n");
1075 }
1076 
1077 /*
1078  * Release lock on NIC memory.
1079  */
1080 static void
1081 wpi_mem_unlock(struct wpi_softc *sc)
1082 {
1083 	uint32_t tmp = WPI_READ(sc, WPI_GPIO_CTL);
1084 	WPI_WRITE(sc, WPI_GPIO_CTL, tmp & ~WPI_GPIO_MAC);
1085 }
1086 
1087 static uint32_t
1088 wpi_mem_read(struct wpi_softc *sc, uint16_t addr)
1089 {
1090 	WPI_WRITE(sc, WPI_READ_MEM_ADDR, WPI_MEM_4 | addr);
1091 	return WPI_READ(sc, WPI_READ_MEM_DATA);
1092 }
1093 
1094 static void
1095 wpi_mem_write(struct wpi_softc *sc, uint16_t addr, uint32_t data)
1096 {
1097 	WPI_WRITE(sc, WPI_WRITE_MEM_ADDR, WPI_MEM_4 | addr);
1098 	WPI_WRITE(sc, WPI_WRITE_MEM_DATA, data);
1099 }
1100 
1101 static void
1102 wpi_mem_write_region_4(struct wpi_softc *sc, uint16_t addr,
1103     const uint32_t *data, int wlen)
1104 {
1105 	for (; wlen > 0; wlen--, data++, addr += 4)
1106 		wpi_mem_write(sc, addr, *data);
1107 }
1108 
1109 /*
1110  * Read `len' bytes from the EEPROM.  We access the EEPROM through the MAC
1111  * instead of using the traditional bit-bang method.
1112  */
1113 static int
1114 wpi_read_prom_data(struct wpi_softc *sc, uint32_t addr, void *data, int len)
1115 {
1116 	uint8_t *out = data;
1117 	uint32_t val;
1118 	int ntries;
1119 
1120 	wpi_mem_lock(sc);
1121 	for (; len > 0; len -= 2, addr++) {
1122 		WPI_WRITE(sc, WPI_EEPROM_CTL, addr << 2);
1123 
1124 		for (ntries = 0; ntries < 10; ntries++) {
1125 			if ((val = WPI_READ(sc, WPI_EEPROM_CTL)) &
1126 			    WPI_EEPROM_READY)
1127 				break;
1128 			DELAY(5);
1129 		}
1130 		if (ntries == 10) {
1131 			aprint_error_dev(sc->sc_dev, "could not read EEPROM\n");
1132 			return ETIMEDOUT;
1133 		}
1134 		*out++ = val >> 16;
1135 		if (len > 1)
1136 			*out++ = val >> 24;
1137 	}
1138 	wpi_mem_unlock(sc);
1139 
1140 	return 0;
1141 }
1142 
1143 /*
1144  * The firmware boot code is small and is intended to be copied directly into
1145  * the NIC internal memory.
1146  */
1147 int
1148 wpi_load_microcode(struct wpi_softc *sc, const uint8_t *ucode, int size)
1149 {
1150 	int ntries;
1151 
1152 	size /= sizeof (uint32_t);
1153 
1154 	wpi_mem_lock(sc);
1155 
1156 	/* copy microcode image into NIC memory */
1157 	wpi_mem_write_region_4(sc, WPI_MEM_UCODE_BASE,
1158 	    (const uint32_t *)ucode, size);
1159 
1160 	wpi_mem_write(sc, WPI_MEM_UCODE_SRC, 0);
1161 	wpi_mem_write(sc, WPI_MEM_UCODE_DST, WPI_FW_TEXT);
1162 	wpi_mem_write(sc, WPI_MEM_UCODE_SIZE, size);
1163 
1164 	/* run microcode */
1165 	wpi_mem_write(sc, WPI_MEM_UCODE_CTL, WPI_UC_RUN);
1166 
1167 	/* wait for transfer to complete */
1168 	for (ntries = 0; ntries < 1000; ntries++) {
1169 		if (!(wpi_mem_read(sc, WPI_MEM_UCODE_CTL) & WPI_UC_RUN))
1170 			break;
1171 		DELAY(10);
1172 	}
1173 	if (ntries == 1000) {
1174 		wpi_mem_unlock(sc);
1175 		aprint_error_dev(sc->sc_dev, "could not load boot firmware\n");
1176 		return ETIMEDOUT;
1177 	}
1178 	wpi_mem_write(sc, WPI_MEM_UCODE_CTL, WPI_UC_ENABLE);
1179 
1180 	wpi_mem_unlock(sc);
1181 
1182 	return 0;
1183 }
1184 
1185 static int
1186 wpi_cache_firmware(struct wpi_softc *sc)
1187 {
1188 	const char *const fwname = wpi_firmware_name;
1189 	firmware_handle_t fw;
1190 	int error;
1191 
1192 	/* sc is used here only to report error messages.  */
1193 
1194 	mutex_enter(&wpi_firmware_mutex);
1195 
1196 	if (wpi_firmware_users == SIZE_MAX) {
1197 		mutex_exit(&wpi_firmware_mutex);
1198 		return ENFILE;	/* Too many of something in the system...  */
1199 	}
1200 	if (wpi_firmware_users++) {
1201 		KASSERT(wpi_firmware_image != NULL);
1202 		KASSERT(wpi_firmware_size > 0);
1203 		mutex_exit(&wpi_firmware_mutex);
1204 		return 0;	/* Already good to go.  */
1205 	}
1206 
1207 	KASSERT(wpi_firmware_image == NULL);
1208 	KASSERT(wpi_firmware_size == 0);
1209 
1210 	/* load firmware image from disk */
1211 	if ((error = firmware_open("if_wpi", fwname, &fw)) != 0) {
1212 		aprint_error_dev(sc->sc_dev,
1213 		    "could not open firmware file %s: %d\n", fwname, error);
1214 		goto fail0;
1215 	}
1216 
1217 	wpi_firmware_size = firmware_get_size(fw);
1218 
1219 	if (wpi_firmware_size > sizeof (struct wpi_firmware_hdr) +
1220 	    WPI_FW_MAIN_TEXT_MAXSZ + WPI_FW_MAIN_DATA_MAXSZ +
1221 	    WPI_FW_INIT_TEXT_MAXSZ + WPI_FW_INIT_DATA_MAXSZ +
1222 	    WPI_FW_BOOT_TEXT_MAXSZ) {
1223 		aprint_error_dev(sc->sc_dev,
1224 		    "firmware file %s too large: %zu bytes\n",
1225 		    fwname, wpi_firmware_size);
1226 		error = EFBIG;
1227 		goto fail1;
1228 	}
1229 
1230 	if (wpi_firmware_size < sizeof (struct wpi_firmware_hdr)) {
1231 		aprint_error_dev(sc->sc_dev,
1232 		    "firmware file %s too small: %zu bytes\n",
1233 		    fwname, wpi_firmware_size);
1234 		error = EINVAL;
1235 		goto fail1;
1236 	}
1237 
1238 	wpi_firmware_image = firmware_malloc(wpi_firmware_size);
1239 	if (wpi_firmware_image == NULL) {
1240 		aprint_error_dev(sc->sc_dev,
1241 		    "not enough memory for firmware file %s\n", fwname);
1242 		error = ENOMEM;
1243 		goto fail1;
1244 	}
1245 
1246 	error = firmware_read(fw, 0, wpi_firmware_image, wpi_firmware_size);
1247 	if (error != 0) {
1248 		aprint_error_dev(sc->sc_dev,
1249 		    "error reading firmware file %s: %d\n", fwname, error);
1250 		goto fail2;
1251 	}
1252 
1253 	/* Success!  */
1254 	firmware_close(fw);
1255 	mutex_exit(&wpi_firmware_mutex);
1256 	return 0;
1257 
1258 fail2:
1259 	firmware_free(wpi_firmware_image, wpi_firmware_size);
1260 	wpi_firmware_image = NULL;
1261 fail1:
1262 	wpi_firmware_size = 0;
1263 	firmware_close(fw);
1264 fail0:
1265 	KASSERT(wpi_firmware_users == 1);
1266 	wpi_firmware_users = 0;
1267 	KASSERT(wpi_firmware_image == NULL);
1268 	KASSERT(wpi_firmware_size == 0);
1269 
1270 	mutex_exit(&wpi_firmware_mutex);
1271 	return error;
1272 }
1273 
1274 static void
1275 wpi_release_firmware(void)
1276 {
1277 
1278 	mutex_enter(&wpi_firmware_mutex);
1279 
1280 	KASSERT(wpi_firmware_users > 0);
1281 	KASSERT(wpi_firmware_image != NULL);
1282 	KASSERT(wpi_firmware_size != 0);
1283 
1284 	if (--wpi_firmware_users == 0) {
1285 		firmware_free(wpi_firmware_image, wpi_firmware_size);
1286 		wpi_firmware_image = NULL;
1287 		wpi_firmware_size = 0;
1288 	}
1289 
1290 	mutex_exit(&wpi_firmware_mutex);
1291 }
1292 
1293 static int
1294 wpi_load_firmware(struct wpi_softc *sc)
1295 {
1296 	struct wpi_dma_info *dma = &sc->fw_dma;
1297 	struct wpi_firmware_hdr hdr;
1298 	const uint8_t *init_text, *init_data, *main_text, *main_data;
1299 	const uint8_t *boot_text;
1300 	uint32_t init_textsz, init_datasz, main_textsz, main_datasz;
1301 	uint32_t boot_textsz;
1302 	size_t size;
1303 	int error;
1304 
1305 	if (!sc->fw_used) {
1306 		if ((error = wpi_cache_firmware(sc)) != 0)
1307 			return error;
1308 		sc->fw_used = true;
1309 	}
1310 
1311 	KASSERT(sc->fw_used);
1312 	KASSERT(wpi_firmware_image != NULL);
1313 	KASSERT(wpi_firmware_size > sizeof(hdr));
1314 
1315 	memcpy(&hdr, wpi_firmware_image, sizeof(hdr));
1316 
1317 	main_textsz = le32toh(hdr.main_textsz);
1318 	main_datasz = le32toh(hdr.main_datasz);
1319 	init_textsz = le32toh(hdr.init_textsz);
1320 	init_datasz = le32toh(hdr.init_datasz);
1321 	boot_textsz = le32toh(hdr.boot_textsz);
1322 
1323 	/* sanity-check firmware segments sizes */
1324 	if (main_textsz > WPI_FW_MAIN_TEXT_MAXSZ ||
1325 	    main_datasz > WPI_FW_MAIN_DATA_MAXSZ ||
1326 	    init_textsz > WPI_FW_INIT_TEXT_MAXSZ ||
1327 	    init_datasz > WPI_FW_INIT_DATA_MAXSZ ||
1328 	    boot_textsz > WPI_FW_BOOT_TEXT_MAXSZ ||
1329 	    (boot_textsz & 3) != 0) {
1330 		aprint_error_dev(sc->sc_dev, "invalid firmware header\n");
1331 		error = EINVAL;
1332 		goto free_firmware;
1333 	}
1334 
1335 	/* check that all firmware segments are present */
1336 	size = sizeof (struct wpi_firmware_hdr) + main_textsz +
1337 	    main_datasz + init_textsz + init_datasz + boot_textsz;
1338 	if (wpi_firmware_size < size) {
1339 		aprint_error_dev(sc->sc_dev,
1340 		    "firmware file truncated: %zu bytes, expected %zu bytes\n",
1341 		    wpi_firmware_size, size);
1342 		error = EINVAL;
1343 		goto free_firmware;
1344 	}
1345 
1346 	/* get pointers to firmware segments */
1347 	main_text = wpi_firmware_image + sizeof (struct wpi_firmware_hdr);
1348 	main_data = main_text + main_textsz;
1349 	init_text = main_data + main_datasz;
1350 	init_data = init_text + init_textsz;
1351 	boot_text = init_data + init_datasz;
1352 
1353 	/* copy initialization images into pre-allocated DMA-safe memory */
1354 	memcpy(dma->vaddr, init_data, init_datasz);
1355 	memcpy((char *)dma->vaddr + WPI_FW_INIT_DATA_MAXSZ, init_text,
1356 	    init_textsz);
1357 
1358 	bus_dmamap_sync(dma->tag, dma->map, 0, dma->size, BUS_DMASYNC_PREWRITE);
1359 
1360 	/* tell adapter where to find initialization images */
1361 	wpi_mem_lock(sc);
1362 	wpi_mem_write(sc, WPI_MEM_DATA_BASE, dma->paddr);
1363 	wpi_mem_write(sc, WPI_MEM_DATA_SIZE, init_datasz);
1364 	wpi_mem_write(sc, WPI_MEM_TEXT_BASE,
1365 	    dma->paddr + WPI_FW_INIT_DATA_MAXSZ);
1366 	wpi_mem_write(sc, WPI_MEM_TEXT_SIZE, init_textsz);
1367 	wpi_mem_unlock(sc);
1368 
1369 	/* load firmware boot code */
1370 	if ((error = wpi_load_microcode(sc, boot_text, boot_textsz)) != 0) {
1371 		aprint_error_dev(sc->sc_dev, "could not load boot firmware\n");
1372 		return error;
1373 	}
1374 
1375 	/* now press "execute" ;-) */
1376 	WPI_WRITE(sc, WPI_RESET, 0);
1377 
1378 	/* wait at most one second for first alive notification */
1379 	if ((error = tsleep(sc, PCATCH, "wpiinit", hz)) != 0) {
1380 		/* this isn't what was supposed to happen.. */
1381 		aprint_error_dev(sc->sc_dev,
1382 		    "timeout waiting for adapter to initialize\n");
1383 	}
1384 
1385 	/* copy runtime images into pre-allocated DMA-safe memory */
1386 	memcpy(dma->vaddr, main_data, main_datasz);
1387 	memcpy((char *)dma->vaddr + WPI_FW_MAIN_DATA_MAXSZ, main_text,
1388 	    main_textsz);
1389 
1390 	bus_dmamap_sync(dma->tag, dma->map, 0, dma->size, BUS_DMASYNC_PREWRITE);
1391 
1392 	/* tell adapter where to find runtime images */
1393 	wpi_mem_lock(sc);
1394 	wpi_mem_write(sc, WPI_MEM_DATA_BASE, dma->paddr);
1395 	wpi_mem_write(sc, WPI_MEM_DATA_SIZE, main_datasz);
1396 	wpi_mem_write(sc, WPI_MEM_TEXT_BASE,
1397 	    dma->paddr + WPI_FW_MAIN_DATA_MAXSZ);
1398 	wpi_mem_write(sc, WPI_MEM_TEXT_SIZE, WPI_FW_UPDATED | main_textsz);
1399 	wpi_mem_unlock(sc);
1400 
1401 	/* wait at most one second for second alive notification */
1402 	if ((error = tsleep(sc, PCATCH, "wpiinit", hz)) != 0) {
1403 		/* this isn't what was supposed to happen.. */
1404 		aprint_error_dev(sc->sc_dev,
1405 		    "timeout waiting for adapter to initialize\n");
1406 	}
1407 
1408 	return error;
1409 
1410 free_firmware:
1411 	sc->fw_used = false;
1412 	wpi_release_firmware();
1413 	return error;
1414 }
1415 
1416 static void
1417 wpi_calib_timeout(void *arg)
1418 {
1419 	struct wpi_softc *sc = arg;
1420 	struct ieee80211com *ic = &sc->sc_ic;
1421 	int temp, s;
1422 
1423 	/* automatic rate control triggered every 500ms */
1424 	if (ic->ic_fixed_rate == -1) {
1425 		s = splnet();
1426 		if (ic->ic_opmode == IEEE80211_M_STA)
1427 			wpi_iter_func(sc, ic->ic_bss);
1428 		else
1429 			ieee80211_iterate_nodes(&ic->ic_sta, wpi_iter_func, sc);
1430 		splx(s);
1431 	}
1432 
1433 	/* update sensor data */
1434 	temp = (int)WPI_READ(sc, WPI_TEMPERATURE);
1435 
1436 	/* automatic power calibration every 60s */
1437 	if (++sc->calib_cnt >= 120) {
1438 		wpi_power_calibration(sc, temp);
1439 		sc->calib_cnt = 0;
1440 	}
1441 
1442 	callout_schedule(&sc->calib_to, hz/2);
1443 }
1444 
1445 static void
1446 wpi_iter_func(void *arg, struct ieee80211_node *ni)
1447 {
1448 	struct wpi_softc *sc = arg;
1449 	struct wpi_node *wn = (struct wpi_node *)ni;
1450 
1451 	ieee80211_amrr_choose(&sc->amrr, ni, &wn->amn);
1452 }
1453 
1454 /*
1455  * This function is called periodically (every 60 seconds) to adjust output
1456  * power to temperature changes.
1457  */
1458 void
1459 wpi_power_calibration(struct wpi_softc *sc, int temp)
1460 {
1461 	/* sanity-check read value */
1462 	if (temp < -260 || temp > 25) {
1463 		/* this can't be correct, ignore */
1464 		DPRINTF(("out-of-range temperature reported: %d\n", temp));
1465 		return;
1466 	}
1467 
1468 	DPRINTF(("temperature %d->%d\n", sc->temp, temp));
1469 
1470 	/* adjust Tx power if need be */
1471 	if (abs(temp - sc->temp) <= 6)
1472 		return;
1473 
1474 	sc->temp = temp;
1475 
1476 	if (wpi_set_txpower(sc, sc->sc_ic.ic_curchan, 1) != 0) {
1477 		/* just warn, too bad for the automatic calibration... */
1478 		aprint_error_dev(sc->sc_dev, "could not adjust Tx power\n");
1479 	}
1480 }
1481 
1482 static void
1483 wpi_rx_intr(struct wpi_softc *sc, struct wpi_rx_desc *desc,
1484     struct wpi_rx_data *data)
1485 {
1486 	struct ieee80211com *ic = &sc->sc_ic;
1487 	struct ifnet *ifp = ic->ic_ifp;
1488 	struct wpi_rx_ring *ring = &sc->rxq;
1489 	struct wpi_rx_stat *stat;
1490 	struct wpi_rx_head *head;
1491 	struct wpi_rx_tail *tail;
1492 	struct wpi_rbuf *rbuf;
1493 	struct ieee80211_frame *wh;
1494 	struct ieee80211_node *ni;
1495 	struct mbuf *m, *mnew;
1496 	int data_off, error, s;
1497 
1498 	bus_dmamap_sync(sc->sc_dmat, data->map, 0, data->map->dm_mapsize,
1499 	    BUS_DMASYNC_POSTREAD);
1500 	stat = (struct wpi_rx_stat *)(desc + 1);
1501 
1502 	if (stat->len > WPI_STAT_MAXLEN) {
1503 		aprint_error_dev(sc->sc_dev, "invalid rx statistic header\n");
1504 		if_statinc(ifp, if_ierrors);
1505 		return;
1506 	}
1507 
1508 	head = (struct wpi_rx_head *)((char *)(stat + 1) + stat->len);
1509 	tail = (struct wpi_rx_tail *)((char *)(head + 1) + le16toh(head->len));
1510 
1511 	DPRINTFN(4, ("rx intr: idx=%d len=%d stat len=%d rssi=%d rate=%x "
1512 	    "chan=%d tstamp=%" PRIu64 "\n", ring->cur, le32toh(desc->len),
1513 	    le16toh(head->len), (int8_t)stat->rssi, head->rate, head->chan,
1514 	    le64toh(tail->tstamp)));
1515 
1516 	/*
1517 	 * Discard Rx frames with bad CRC early (XXX we may want to pass them
1518 	 * to radiotap in monitor mode).
1519 	 */
1520 	if ((le32toh(tail->flags) & WPI_RX_NOERROR) != WPI_RX_NOERROR) {
1521 		DPRINTF(("rx tail flags error %x\n",
1522 		    le32toh(tail->flags)));
1523 		if_statinc(ifp, if_ierrors);
1524 		return;
1525 	}
1526 
1527 	/* Compute where are the useful datas */
1528 	data_off = (char*)(head + 1) - mtod(data->m, char*);
1529 
1530 	MGETHDR(mnew, M_DONTWAIT, MT_DATA);
1531 	if (mnew == NULL) {
1532 		if_statinc(ifp, if_ierrors);
1533 		return;
1534 	}
1535 
1536 	rbuf = wpi_alloc_rbuf(sc);
1537 	if (rbuf == NULL) {
1538 		m_freem(mnew);
1539 		if_statinc(ifp, if_ierrors);
1540 		return;
1541 	}
1542 
1543 	/* attach Rx buffer to mbuf */
1544 	MEXTADD(mnew, rbuf->vaddr, WPI_RBUF_SIZE, 0, wpi_free_rbuf,
1545 		rbuf);
1546 	mnew->m_flags |= M_EXT_RW;
1547 
1548 	bus_dmamap_unload(sc->sc_dmat, data->map);
1549 
1550 	error = bus_dmamap_load(sc->sc_dmat, data->map,
1551 	    mtod(mnew, void *), WPI_RBUF_SIZE, NULL,
1552 	    BUS_DMA_NOWAIT | BUS_DMA_READ);
1553 	if (error) {
1554 		device_printf(sc->sc_dev,
1555 		    "couldn't load rx mbuf: %d\n", error);
1556 		m_freem(mnew);
1557 		if_statinc(ifp, if_ierrors);
1558 
1559 		error = bus_dmamap_load(sc->sc_dmat, data->map,
1560 		    mtod(data->m, void *), WPI_RBUF_SIZE, NULL,
1561 		    BUS_DMA_NOWAIT | BUS_DMA_READ);
1562 		if (error)
1563 			panic("%s: bus_dmamap_load failed: %d\n",
1564 			    device_xname(sc->sc_dev), error);
1565 		return;
1566 	}
1567 
1568 	/* new mbuf loaded successfully */
1569 	m = data->m;
1570 	data->m = mnew;
1571 
1572 	/* update Rx descriptor */
1573 	ring->desc[ring->cur] = htole32(rbuf->paddr);
1574 	bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map, 0,
1575 	    ring->desc_dma.size,
1576 	    BUS_DMASYNC_PREWRITE);
1577 
1578 	m->m_data = (char*)m->m_data + data_off;
1579 	m->m_pkthdr.len = m->m_len = le16toh(head->len);
1580 
1581 	/* finalize mbuf */
1582 	m_set_rcvif(m, ifp);
1583 
1584 	s = splnet();
1585 
1586 	if (sc->sc_drvbpf != NULL) {
1587 		struct wpi_rx_radiotap_header *tap = &sc->sc_rxtap;
1588 
1589 		tap->wr_flags = 0;
1590 		tap->wr_chan_freq =
1591 		    htole16(ic->ic_channels[head->chan].ic_freq);
1592 		tap->wr_chan_flags =
1593 		    htole16(ic->ic_channels[head->chan].ic_flags);
1594 		tap->wr_dbm_antsignal = (int8_t)(stat->rssi - WPI_RSSI_OFFSET);
1595 		tap->wr_dbm_antnoise = (int8_t)le16toh(stat->noise);
1596 		tap->wr_tsft = tail->tstamp;
1597 		tap->wr_antenna = (le16toh(head->flags) >> 4) & 0xf;
1598 		switch (head->rate) {
1599 		/* CCK rates */
1600 		case  10: tap->wr_rate =   2; break;
1601 		case  20: tap->wr_rate =   4; break;
1602 		case  55: tap->wr_rate =  11; break;
1603 		case 110: tap->wr_rate =  22; break;
1604 		/* OFDM rates */
1605 		case 0xd: tap->wr_rate =  12; break;
1606 		case 0xf: tap->wr_rate =  18; break;
1607 		case 0x5: tap->wr_rate =  24; break;
1608 		case 0x7: tap->wr_rate =  36; break;
1609 		case 0x9: tap->wr_rate =  48; break;
1610 		case 0xb: tap->wr_rate =  72; break;
1611 		case 0x1: tap->wr_rate =  96; break;
1612 		case 0x3: tap->wr_rate = 108; break;
1613 		/* unknown rate: should not happen */
1614 		default:  tap->wr_rate =   0;
1615 		}
1616 		if (le16toh(head->flags) & 0x4)
1617 			tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
1618 
1619 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_rxtap_len, m, BPF_D_IN);
1620 	}
1621 
1622 	/* grab a reference to the source node */
1623 	wh = mtod(m, struct ieee80211_frame *);
1624 	ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
1625 
1626 	/* send the frame to the 802.11 layer */
1627 	ieee80211_input(ic, m, ni, stat->rssi, 0);
1628 
1629 	/* release node reference */
1630 	ieee80211_free_node(ni);
1631 
1632 	splx(s);
1633 }
1634 
1635 static void
1636 wpi_tx_intr(struct wpi_softc *sc, struct wpi_rx_desc *desc)
1637 {
1638 	struct ifnet *ifp = sc->sc_ic.ic_ifp;
1639 	struct wpi_tx_ring *ring = &sc->txq[desc->qid & 0x3];
1640 	struct wpi_tx_data *data = &ring->data[desc->idx];
1641 	struct wpi_tx_stat *stat = (struct wpi_tx_stat *)(desc + 1);
1642 	struct wpi_node *wn = (struct wpi_node *)data->ni;
1643 	int s;
1644 
1645 	DPRINTFN(4, ("tx done: qid=%d idx=%d retries=%d nkill=%d rate=%x "
1646 	    "duration=%d status=%x\n", desc->qid, desc->idx, stat->ntries,
1647 	    stat->nkill, stat->rate, le32toh(stat->duration),
1648 	    le32toh(stat->status)));
1649 
1650 	s = splnet();
1651 
1652 	/*
1653 	 * Update rate control statistics for the node.
1654 	 * XXX we should not count mgmt frames since they're always sent at
1655 	 * the lowest available bit-rate.
1656 	 */
1657 	wn->amn.amn_txcnt++;
1658 	if (stat->ntries > 0) {
1659 		DPRINTFN(3, ("tx intr ntries %d\n", stat->ntries));
1660 		wn->amn.amn_retrycnt++;
1661 	}
1662 
1663 	if ((le32toh(stat->status) & 0xff) != 1)
1664 		if_statinc(ifp, if_oerrors);
1665 	else
1666 		if_statinc(ifp, if_opackets);
1667 
1668 	bus_dmamap_unload(sc->sc_dmat, data->map);
1669 	m_freem(data->m);
1670 	data->m = NULL;
1671 	ieee80211_free_node(data->ni);
1672 	data->ni = NULL;
1673 
1674 	ring->queued--;
1675 
1676 	sc->sc_tx_timer = 0;
1677 	ifp->if_flags &= ~IFF_OACTIVE;
1678 	wpi_start(ifp); /* in softint */
1679 
1680 	splx(s);
1681 }
1682 
1683 static void
1684 wpi_cmd_intr(struct wpi_softc *sc, struct wpi_rx_desc *desc)
1685 {
1686 	struct wpi_tx_ring *ring = &sc->cmdq;
1687 	struct wpi_tx_data *data;
1688 
1689 	if ((desc->qid & 7) != 4)
1690 		return;	/* not a command ack */
1691 
1692 	data = &ring->data[desc->idx];
1693 
1694 	/* if the command was mapped in a mbuf, free it */
1695 	if (data->m != NULL) {
1696 		bus_dmamap_unload(sc->sc_dmat, data->map);
1697 		m_freem(data->m);
1698 		data->m = NULL;
1699 	}
1700 
1701 	wakeup(&ring->cmd[desc->idx]);
1702 }
1703 
1704 static void
1705 wpi_notif_intr(struct wpi_softc *sc)
1706 {
1707 	struct ieee80211com *ic = &sc->sc_ic;
1708 	struct ifnet *ifp =  ic->ic_ifp;
1709 	uint32_t hw;
1710 	int s;
1711 
1712 	bus_dmamap_sync(sc->sc_dmat, sc->shared_dma.map, 0,
1713 	    sizeof(struct wpi_shared), BUS_DMASYNC_POSTREAD);
1714 
1715 	hw = le32toh(sc->shared->next);
1716 	while (sc->rxq.cur != hw) {
1717 		struct wpi_rx_data *data = &sc->rxq.data[sc->rxq.cur];
1718 		struct wpi_rx_desc *desc;
1719 
1720 		bus_dmamap_sync(sc->sc_dmat, data->map, 0, data->map->dm_mapsize,
1721 		    BUS_DMASYNC_POSTREAD);
1722 		desc = mtod(data->m, struct wpi_rx_desc *);
1723 
1724 		DPRINTFN(4, ("rx notification qid=%x idx=%d flags=%x type=%d "
1725 		    "len=%d\n", desc->qid, desc->idx, desc->flags,
1726 		    desc->type, le32toh(desc->len)));
1727 
1728 		if (!(desc->qid & 0x80))	/* reply to a command */
1729 			wpi_cmd_intr(sc, desc);
1730 
1731 		switch (desc->type) {
1732 		case WPI_RX_DONE:
1733 			/* a 802.11 frame was received */
1734 			wpi_rx_intr(sc, desc, data);
1735 			break;
1736 
1737 		case WPI_TX_DONE:
1738 			/* a 802.11 frame has been transmitted */
1739 			wpi_tx_intr(sc, desc);
1740 			break;
1741 
1742 		case WPI_UC_READY:
1743 		{
1744 			struct wpi_ucode_info *uc =
1745 			    (struct wpi_ucode_info *)(desc + 1);
1746 
1747 			/* the microcontroller is ready */
1748 			DPRINTF(("microcode alive notification version %x "
1749 			    "alive %x\n", le32toh(uc->version),
1750 			    le32toh(uc->valid)));
1751 
1752 			if (le32toh(uc->valid) != 1) {
1753 				aprint_error_dev(sc->sc_dev,
1754 				    "microcontroller initialization failed\n");
1755 			}
1756 			break;
1757 		}
1758 		case WPI_STATE_CHANGED:
1759 		{
1760 			uint32_t *status = (uint32_t *)(desc + 1);
1761 
1762 			/* enabled/disabled notification */
1763 			DPRINTF(("state changed to %x\n", le32toh(*status)));
1764 
1765 			if (le32toh(*status) & 1) {
1766 				s = splnet();
1767 				/* the radio button has to be pushed */
1768 				/* wake up thread to signal powerd */
1769 				cv_signal(&sc->sc_rsw_cv);
1770 				aprint_error_dev(sc->sc_dev,
1771 				    "Radio transmitter is off\n");
1772 				/* turn the interface down */
1773 				ifp->if_flags &= ~IFF_UP;
1774 				wpi_stop_intr(ifp, 1);
1775 				splx(s);
1776 				return;	/* no further processing */
1777 			}
1778 			break;
1779 		}
1780 		case WPI_START_SCAN:
1781 		{
1782 #if 0
1783 			struct wpi_start_scan *scan =
1784 			    (struct wpi_start_scan *)(desc + 1);
1785 
1786 			DPRINTFN(2, ("scanning channel %d status %x\n",
1787 			    scan->chan, le32toh(scan->status)));
1788 
1789 			/* fix current channel */
1790 			ic->ic_curchan = &ic->ic_channels[scan->chan];
1791 #endif
1792 			break;
1793 		}
1794 		case WPI_STOP_SCAN:
1795 		{
1796 #ifdef WPI_DEBUG
1797 			struct wpi_stop_scan *scan =
1798 			    (struct wpi_stop_scan *)(desc + 1);
1799 #endif
1800 
1801 			DPRINTF(("scan finished nchan=%d status=%d chan=%d\n",
1802 			    scan->nchan, scan->status, scan->chan));
1803 
1804 			s = splnet();
1805 			sc->is_scanning = false;
1806 			if (ic->ic_state == IEEE80211_S_SCAN)
1807 				ieee80211_next_scan(ic);
1808 			splx(s);
1809 			break;
1810 		}
1811 		}
1812 
1813 		sc->rxq.cur = (sc->rxq.cur + 1) % WPI_RX_RING_COUNT;
1814 	}
1815 
1816 	/* tell the firmware what we have processed */
1817 	hw = (hw == 0) ? WPI_RX_RING_COUNT - 1 : hw - 1;
1818 	WPI_WRITE(sc, WPI_RX_WIDX, hw & ~7);
1819 }
1820 
1821 static int
1822 wpi_intr(void *arg)
1823 {
1824 	struct wpi_softc *sc = arg;
1825 	uint32_t r;
1826 
1827 	r = WPI_READ(sc, WPI_INTR);
1828 	if (r == 0 || r == 0xffffffff)
1829 		return 0;	/* not for us */
1830 
1831 	DPRINTFN(6, ("interrupt reg %x\n", r));
1832 
1833 	/* disable interrupts */
1834 	WPI_WRITE(sc, WPI_MASK, 0);
1835 
1836 	softint_schedule(sc->sc_soft_ih);
1837 	return 1;
1838 }
1839 
1840 static void
1841 wpi_softintr(void *arg)
1842 {
1843 	struct wpi_softc *sc = arg;
1844 	struct ifnet *ifp = sc->sc_ic.ic_ifp;
1845 	uint32_t r;
1846 
1847 	r = WPI_READ(sc, WPI_INTR);
1848 	if (r == 0 || r == 0xffffffff)
1849 		goto out;
1850 
1851 	/* ack interrupts */
1852 	WPI_WRITE(sc, WPI_INTR, r);
1853 
1854 	if (r & (WPI_SW_ERROR | WPI_HW_ERROR)) {
1855 		/* SYSTEM FAILURE, SYSTEM FAILURE */
1856 		aprint_error_dev(sc->sc_dev, "fatal firmware error\n");
1857 		ifp->if_flags &= ~IFF_UP;
1858 		wpi_stop_intr(ifp, 1);
1859 		return;
1860 	}
1861 
1862 	if (r & WPI_RX_INTR)
1863 		wpi_notif_intr(sc);
1864 
1865 	if (r & WPI_ALIVE_INTR)	/* firmware initialized */
1866 		wakeup(sc);
1867 
1868  out:
1869 	/* re-enable interrupts */
1870 	if (ifp->if_flags & IFF_UP)
1871 		WPI_WRITE(sc, WPI_MASK, WPI_INTR_MASK);
1872 }
1873 
1874 static uint8_t
1875 wpi_plcp_signal(int rate)
1876 {
1877 	switch (rate) {
1878 	/* CCK rates (returned values are device-dependent) */
1879 	case 2:		return 10;
1880 	case 4:		return 20;
1881 	case 11:	return 55;
1882 	case 22:	return 110;
1883 
1884 	/* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
1885 	/* R1-R4, (u)ral is R4-R1 */
1886 	case 12:	return 0xd;
1887 	case 18:	return 0xf;
1888 	case 24:	return 0x5;
1889 	case 36:	return 0x7;
1890 	case 48:	return 0x9;
1891 	case 72:	return 0xb;
1892 	case 96:	return 0x1;
1893 	case 108:	return 0x3;
1894 
1895 	/* unsupported rates (should not get there) */
1896 	default:	return 0;
1897 	}
1898 }
1899 
1900 /* quickly determine if a given rate is CCK or OFDM */
1901 #define WPI_RATE_IS_OFDM(rate) ((rate) >= 12 && (rate) != 22)
1902 
1903 static int
1904 wpi_tx_data(struct wpi_softc *sc, struct mbuf *m0, struct ieee80211_node *ni,
1905     int ac)
1906 {
1907 	struct ieee80211com *ic = &sc->sc_ic;
1908 	struct wpi_tx_ring *ring = &sc->txq[ac];
1909 	struct wpi_tx_desc *desc;
1910 	struct wpi_tx_data *data;
1911 	struct wpi_tx_cmd *cmd;
1912 	struct wpi_cmd_data *tx;
1913 	struct ieee80211_frame *wh;
1914 	struct ieee80211_key *k;
1915 	const struct chanAccParams *cap;
1916 	struct mbuf *mnew;
1917 	int i, rate, error, hdrlen, noack = 0;
1918 
1919 	desc = &ring->desc[ring->cur];
1920 	data = &ring->data[ring->cur];
1921 
1922 	wh = mtod(m0, struct ieee80211_frame *);
1923 
1924 	if (ieee80211_has_qos(wh)) {
1925 		cap = &ic->ic_wme.wme_chanParams;
1926 		noack = cap->cap_wmeParams[ac].wmep_noackPolicy;
1927 	}
1928 
1929 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1930 		k = ieee80211_crypto_encap(ic, ni, m0);
1931 		if (k == NULL) {
1932 			m_freem(m0);
1933 			return ENOBUFS;
1934 		}
1935 
1936 		/* packet header may have moved, reset our local pointer */
1937 		wh = mtod(m0, struct ieee80211_frame *);
1938 	}
1939 
1940 	hdrlen = ieee80211_anyhdrsize(wh);
1941 
1942 	/* pickup a rate */
1943 	if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
1944 	    IEEE80211_FC0_TYPE_MGT) {
1945 		/* mgmt frames are sent at the lowest available bit-rate */
1946 		rate = ni->ni_rates.rs_rates[0];
1947 	} else {
1948 		if (ic->ic_fixed_rate != -1) {
1949 			rate = ic->ic_sup_rates[ic->ic_curmode].
1950 			    rs_rates[ic->ic_fixed_rate];
1951 		} else
1952 			rate = ni->ni_rates.rs_rates[ni->ni_txrate];
1953 	}
1954 	rate &= IEEE80211_RATE_VAL;
1955 
1956 	if (sc->sc_drvbpf != NULL) {
1957 		struct wpi_tx_radiotap_header *tap = &sc->sc_txtap;
1958 
1959 		tap->wt_flags = 0;
1960 		tap->wt_chan_freq = htole16(ni->ni_chan->ic_freq);
1961 		tap->wt_chan_flags = htole16(ni->ni_chan->ic_flags);
1962 		tap->wt_rate = rate;
1963 		tap->wt_hwqueue = ac;
1964 		if (wh->i_fc[1] & IEEE80211_FC1_WEP)
1965 			tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
1966 
1967 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m0, BPF_D_OUT);
1968 	}
1969 
1970 	cmd = &ring->cmd[ring->cur];
1971 	cmd->code = WPI_CMD_TX_DATA;
1972 	cmd->flags = 0;
1973 	cmd->qid = ring->qid;
1974 	cmd->idx = ring->cur;
1975 
1976 	tx = (struct wpi_cmd_data *)cmd->data;
1977 	/* no need to zero tx, all fields are reinitialized here */
1978 	tx->flags = 0;
1979 
1980 	if (!noack && !IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1981 		tx->flags |= htole32(WPI_TX_NEED_ACK);
1982 	} else if (m0->m_pkthdr.len + IEEE80211_CRC_LEN > ic->ic_rtsthreshold)
1983 		tx->flags |= htole32(WPI_TX_NEED_RTS | WPI_TX_FULL_TXOP);
1984 
1985 	tx->flags |= htole32(WPI_TX_AUTO_SEQ);
1986 
1987 	/* retrieve destination node's id */
1988 	tx->id = IEEE80211_IS_MULTICAST(wh->i_addr1) ? WPI_ID_BROADCAST :
1989 		WPI_ID_BSS;
1990 
1991 	if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
1992 	    IEEE80211_FC0_TYPE_MGT) {
1993 		/* tell h/w to set timestamp in probe responses */
1994 		if ((wh->i_fc[0] &
1995 		    (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
1996 		    (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP))
1997 			tx->flags |= htole32(WPI_TX_INSERT_TSTAMP);
1998 
1999 		if (((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
2000 			 IEEE80211_FC0_SUBTYPE_ASSOC_REQ) ||
2001 			((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
2002 			 IEEE80211_FC0_SUBTYPE_REASSOC_REQ))
2003 			tx->timeout = htole16(3);
2004 		else
2005 			tx->timeout = htole16(2);
2006 	} else
2007 		tx->timeout = htole16(0);
2008 
2009 	tx->rate = wpi_plcp_signal(rate);
2010 
2011 	/* be very persistant at sending frames out */
2012 	tx->rts_ntries = 7;
2013 	tx->data_ntries = 15;
2014 
2015 	tx->ofdm_mask = 0xff;
2016 	tx->cck_mask = 0x0f;
2017 	tx->lifetime = htole32(WPI_LIFETIME_INFINITE);
2018 
2019 	tx->len = htole16(m0->m_pkthdr.len);
2020 
2021 	/* save and trim IEEE802.11 header */
2022 	memcpy((uint8_t *)(tx + 1), wh, hdrlen);
2023 	m_adj(m0, hdrlen);
2024 
2025 	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
2026 	    BUS_DMA_WRITE | BUS_DMA_NOWAIT);
2027 	if (error != 0 && error != EFBIG) {
2028 		aprint_error_dev(sc->sc_dev, "could not map mbuf (error %d)\n",
2029 		    error);
2030 		m_freem(m0);
2031 		return error;
2032 	}
2033 	if (error != 0) {
2034 		/* too many fragments, linearize */
2035 
2036 		MGETHDR(mnew, M_DONTWAIT, MT_DATA);
2037 		if (mnew == NULL) {
2038 			m_freem(m0);
2039 			return ENOMEM;
2040 		}
2041 		m_copy_pkthdr(mnew, m0);
2042 		if (m0->m_pkthdr.len > MHLEN) {
2043 			MCLGET(mnew, M_DONTWAIT);
2044 			if (!(mnew->m_flags & M_EXT)) {
2045 				m_freem(m0);
2046 				m_freem(mnew);
2047 				return ENOMEM;
2048 			}
2049 		}
2050 
2051 		m_copydata(m0, 0, m0->m_pkthdr.len, mtod(mnew, void *));
2052 		m_freem(m0);
2053 		mnew->m_len = mnew->m_pkthdr.len;
2054 		m0 = mnew;
2055 
2056 		error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
2057 		    BUS_DMA_WRITE | BUS_DMA_NOWAIT);
2058 		if (error != 0) {
2059 			aprint_error_dev(sc->sc_dev,
2060 			    "could not map mbuf (error %d)\n", error);
2061 			m_freem(m0);
2062 			return error;
2063 		}
2064 	}
2065 
2066 	data->m = m0;
2067 	data->ni = ni;
2068 
2069 	DPRINTFN(4, ("sending data: qid=%d idx=%d len=%d nsegs=%d\n",
2070 	    ring->qid, ring->cur, m0->m_pkthdr.len, data->map->dm_nsegs));
2071 
2072 	/* first scatter/gather segment is used by the tx data command */
2073 	desc->flags = htole32(WPI_PAD32(m0->m_pkthdr.len) << 28 |
2074 	    (1 + data->map->dm_nsegs) << 24);
2075 	desc->segs[0].addr = htole32(ring->cmd_dma.paddr +
2076 	    ring->cur * sizeof (struct wpi_tx_cmd));
2077 	desc->segs[0].len  = htole32(4 + sizeof (struct wpi_cmd_data) +
2078 	    ((hdrlen + 3) & ~3));
2079 	for (i = 1; i <= data->map->dm_nsegs; i++) {
2080 		desc->segs[i].addr =
2081 		    htole32(data->map->dm_segs[i - 1].ds_addr);
2082 		desc->segs[i].len  =
2083 		    htole32(data->map->dm_segs[i - 1].ds_len);
2084 	}
2085 
2086 	ring->queued++;
2087 
2088 	bus_dmamap_sync(sc->sc_dmat, data->map, 0,
2089 	    data->map->dm_mapsize,
2090 	    BUS_DMASYNC_PREWRITE);
2091 	bus_dmamap_sync(sc->sc_dmat, ring->cmd_dma.map, 0,
2092 	    ring->cmd_dma.size,
2093 	    BUS_DMASYNC_PREWRITE);
2094 	bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map, 0,
2095 	    ring->desc_dma.size,
2096 	    BUS_DMASYNC_PREWRITE);
2097 
2098 	/* kick ring */
2099 	ring->cur = (ring->cur + 1) % WPI_TX_RING_COUNT;
2100 	WPI_WRITE(sc, WPI_TX_WIDX, ring->qid << 8 | ring->cur);
2101 
2102 	return 0;
2103 }
2104 
2105 static void
2106 wpi_start(struct ifnet *ifp)
2107 {
2108 	struct wpi_softc *sc = ifp->if_softc;
2109 	struct ieee80211com *ic = &sc->sc_ic;
2110 	struct ieee80211_node *ni;
2111 	struct ether_header *eh;
2112 	struct mbuf *m0;
2113 	int ac;
2114 
2115 	/*
2116 	 * net80211 may still try to send management frames even if the
2117 	 * IFF_RUNNING flag is not set...
2118 	 */
2119 	if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
2120 		return;
2121 
2122 	for (;;) {
2123 		IF_DEQUEUE(&ic->ic_mgtq, m0);
2124 		if (m0 != NULL) {
2125 
2126 			ni = M_GETCTX(m0, struct ieee80211_node *);
2127 			M_CLEARCTX(m0);
2128 
2129 			/* management frames go into ring 0 */
2130 			if (sc->txq[0].queued > sc->txq[0].count - 8) {
2131 				if_statinc(ifp, if_oerrors);
2132 				continue;
2133 			}
2134 			bpf_mtap3(ic->ic_rawbpf, m0, BPF_D_OUT);
2135 			if (wpi_tx_data(sc, m0, ni, 0) != 0) {
2136 				if_statinc(ifp, if_oerrors);
2137 				break;
2138 			}
2139 		} else {
2140 			if (ic->ic_state != IEEE80211_S_RUN)
2141 				break;
2142 			IFQ_POLL(&ifp->if_snd, m0);
2143 			if (m0 == NULL)
2144 				break;
2145 
2146 			if (m0->m_len < sizeof (*eh) &&
2147 			    (m0 = m_pullup(m0, sizeof (*eh))) == NULL) {
2148 				if_statinc(ifp, if_oerrors);
2149 				continue;
2150 			}
2151 			eh = mtod(m0, struct ether_header *);
2152 			ni = ieee80211_find_txnode(ic, eh->ether_dhost);
2153 			if (ni == NULL) {
2154 				m_freem(m0);
2155 				if_statinc(ifp, if_oerrors);
2156 				continue;
2157 			}
2158 
2159 			/* classify mbuf so we can find which tx ring to use */
2160 			if (ieee80211_classify(ic, m0, ni) != 0) {
2161 				m_freem(m0);
2162 				ieee80211_free_node(ni);
2163 				if_statinc(ifp, if_oerrors);
2164 				continue;
2165 			}
2166 
2167 			/* no QoS encapsulation for EAPOL frames */
2168 			ac = (eh->ether_type != htons(ETHERTYPE_PAE)) ?
2169 			    M_WME_GETAC(m0) : WME_AC_BE;
2170 
2171 			if (sc->txq[ac].queued > sc->txq[ac].count - 8) {
2172 				/* there is no place left in this ring */
2173 				ifp->if_flags |= IFF_OACTIVE;
2174 				break;
2175 			}
2176 			IFQ_DEQUEUE(&ifp->if_snd, m0);
2177 			bpf_mtap(ifp, m0, BPF_D_OUT);
2178 			m0 = ieee80211_encap(ic, m0, ni);
2179 			if (m0 == NULL) {
2180 				ieee80211_free_node(ni);
2181 				if_statinc(ifp, if_oerrors);
2182 				continue;
2183 			}
2184 			bpf_mtap3(ic->ic_rawbpf, m0, BPF_D_OUT);
2185 			if (wpi_tx_data(sc, m0, ni, ac) != 0) {
2186 				ieee80211_free_node(ni);
2187 				if_statinc(ifp, if_oerrors);
2188 				break;
2189 			}
2190 		}
2191 
2192 		sc->sc_tx_timer = 5;
2193 		ifp->if_timer = 1;
2194 	}
2195 }
2196 
2197 static void
2198 wpi_watchdog(struct ifnet *ifp)
2199 {
2200 	struct wpi_softc *sc = ifp->if_softc;
2201 
2202 	ifp->if_timer = 0;
2203 
2204 	if (sc->sc_tx_timer > 0) {
2205 		if (--sc->sc_tx_timer == 0) {
2206 			aprint_error_dev(sc->sc_dev, "device timeout\n");
2207 			ifp->if_flags &= ~IFF_UP;
2208 			wpi_stop_intr(ifp, 1);
2209 			if_statinc(ifp, if_oerrors);
2210 			return;
2211 		}
2212 		ifp->if_timer = 1;
2213 	}
2214 
2215 	ieee80211_watchdog(&sc->sc_ic);
2216 }
2217 
2218 static int
2219 wpi_ioctl(struct ifnet *ifp, u_long cmd, void *data)
2220 {
2221 #define IS_RUNNING(ifp) \
2222 	((ifp->if_flags & IFF_UP) && (ifp->if_flags & IFF_RUNNING))
2223 
2224 	struct wpi_softc *sc = ifp->if_softc;
2225 	struct ieee80211com *ic = &sc->sc_ic;
2226 	int s, error = 0;
2227 
2228 	s = splnet();
2229 
2230 	switch (cmd) {
2231 	case SIOCSIFFLAGS:
2232 		if ((error = ifioctl_common(ifp, cmd, data)) != 0)
2233 			break;
2234 		if (ifp->if_flags & IFF_UP) {
2235 			if (!(ifp->if_flags & IFF_RUNNING))
2236 				wpi_init(ifp);
2237 		} else {
2238 			if (ifp->if_flags & IFF_RUNNING)
2239 				wpi_stop(ifp, 1);
2240 		}
2241 		break;
2242 
2243 	case SIOCADDMULTI:
2244 	case SIOCDELMULTI:
2245 		/* XXX no h/w multicast filter? --dyoung */
2246 		if ((error = ether_ioctl(ifp, cmd, data)) == ENETRESET) {
2247 			/* setup multicast filter, etc */
2248 			error = 0;
2249 		}
2250 		break;
2251 
2252 	default:
2253 		error = ieee80211_ioctl(ic, cmd, data);
2254 	}
2255 
2256 	if (error == ENETRESET) {
2257 		if (IS_RUNNING(ifp) &&
2258 			(ic->ic_roaming != IEEE80211_ROAMING_MANUAL))
2259 			wpi_init(ifp);
2260 		error = 0;
2261 	}
2262 
2263 	splx(s);
2264 	return error;
2265 
2266 #undef IS_RUNNING
2267 }
2268 
2269 /*
2270  * Extract various information from EEPROM.
2271  */
2272 static void
2273 wpi_read_eeprom(struct wpi_softc *sc)
2274 {
2275 	struct ieee80211com *ic = &sc->sc_ic;
2276 	char domain[4];
2277 	int i;
2278 
2279 	wpi_read_prom_data(sc, WPI_EEPROM_CAPABILITIES, &sc->cap, 1);
2280 	wpi_read_prom_data(sc, WPI_EEPROM_REVISION, &sc->rev, 2);
2281 	wpi_read_prom_data(sc, WPI_EEPROM_TYPE, &sc->type, 1);
2282 
2283 	DPRINTF(("cap=%x rev=%x type=%x\n", sc->cap, le16toh(sc->rev),
2284 	    sc->type));
2285 
2286 	/* read and print regulatory domain */
2287 	wpi_read_prom_data(sc, WPI_EEPROM_DOMAIN, domain, 4);
2288 	aprint_normal_dev(sc->sc_dev, "%.4s", domain);
2289 
2290 	/* read and print MAC address */
2291 	wpi_read_prom_data(sc, WPI_EEPROM_MAC, ic->ic_myaddr, 6);
2292 	aprint_normal(", address %s\n", ether_sprintf(ic->ic_myaddr));
2293 
2294 	/* read the list of authorized channels */
2295 	for (i = 0; i < WPI_CHAN_BANDS_COUNT; i++)
2296 		wpi_read_eeprom_channels(sc, i);
2297 
2298 	/* read the list of power groups */
2299 	for (i = 0; i < WPI_POWER_GROUPS_COUNT; i++)
2300 		wpi_read_eeprom_group(sc, i);
2301 }
2302 
2303 static void
2304 wpi_read_eeprom_channels(struct wpi_softc *sc, int n)
2305 {
2306 	struct ieee80211com *ic = &sc->sc_ic;
2307 	const struct wpi_chan_band *band = &wpi_bands[n];
2308 	struct wpi_eeprom_chan channels[WPI_MAX_CHAN_PER_BAND];
2309 	int chan, i;
2310 
2311 	wpi_read_prom_data(sc, band->addr, channels,
2312 	    band->nchan * sizeof (struct wpi_eeprom_chan));
2313 
2314 	for (i = 0; i < band->nchan; i++) {
2315 		if (!(channels[i].flags & WPI_EEPROM_CHAN_VALID))
2316 			continue;
2317 
2318 		chan = band->chan[i];
2319 
2320 		if (n == 0) {	/* 2GHz band */
2321 			ic->ic_channels[chan].ic_freq =
2322 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_2GHZ);
2323 			ic->ic_channels[chan].ic_flags =
2324 			    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
2325 			    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
2326 
2327 		} else {	/* 5GHz band */
2328 			/*
2329 			 * Some 3945ABG adapters support channels 7, 8, 11
2330 			 * and 12 in the 2GHz *and* 5GHz bands.
2331 			 * Because of limitations in our net80211(9) stack,
2332 			 * we can't support these channels in 5GHz band.
2333 			 */
2334 			if (chan <= 14)
2335 				continue;
2336 
2337 			ic->ic_channels[chan].ic_freq =
2338 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_5GHZ);
2339 			ic->ic_channels[chan].ic_flags = IEEE80211_CHAN_A;
2340 		}
2341 
2342 		/* is active scan allowed on this channel? */
2343 		if (!(channels[i].flags & WPI_EEPROM_CHAN_ACTIVE)) {
2344 			ic->ic_channels[chan].ic_flags |=
2345 			    IEEE80211_CHAN_PASSIVE;
2346 		}
2347 
2348 		/* save maximum allowed power for this channel */
2349 		sc->maxpwr[chan] = channels[i].maxpwr;
2350 
2351 		DPRINTF(("adding chan %d flags=0x%x maxpwr=%d\n",
2352 		    chan, channels[i].flags, sc->maxpwr[chan]));
2353 	}
2354 }
2355 
2356 static void
2357 wpi_read_eeprom_group(struct wpi_softc *sc, int n)
2358 {
2359 	struct wpi_power_group *group = &sc->groups[n];
2360 	struct wpi_eeprom_group rgroup;
2361 	int i;
2362 
2363 	wpi_read_prom_data(sc, WPI_EEPROM_POWER_GRP + n * 32, &rgroup,
2364 	    sizeof rgroup);
2365 
2366 	/* save power group information */
2367 	group->chan   = rgroup.chan;
2368 	group->maxpwr = rgroup.maxpwr;
2369 	/* temperature at which the samples were taken */
2370 	group->temp   = (int16_t)le16toh(rgroup.temp);
2371 
2372 	DPRINTF(("power group %d: chan=%d maxpwr=%d temp=%d\n", n,
2373 	    group->chan, group->maxpwr, group->temp));
2374 
2375 	for (i = 0; i < WPI_SAMPLES_COUNT; i++) {
2376 		group->samples[i].index = rgroup.samples[i].index;
2377 		group->samples[i].power = rgroup.samples[i].power;
2378 
2379 		DPRINTF(("\tsample %d: index=%d power=%d\n", i,
2380 		    group->samples[i].index, group->samples[i].power));
2381 	}
2382 }
2383 
2384 /*
2385  * Send a command to the firmware.
2386  */
2387 static int
2388 wpi_cmd(struct wpi_softc *sc, int code, const void *buf, int size, int async)
2389 {
2390 	struct wpi_tx_ring *ring = &sc->cmdq;
2391 	struct wpi_tx_desc *desc;
2392 	struct wpi_tx_cmd *cmd;
2393 	struct wpi_dma_info *dma;
2394 
2395 	KASSERT(size <= sizeof cmd->data);
2396 
2397 	desc = &ring->desc[ring->cur];
2398 	cmd = &ring->cmd[ring->cur];
2399 
2400 	cmd->code = code;
2401 	cmd->flags = 0;
2402 	cmd->qid = ring->qid;
2403 	cmd->idx = ring->cur;
2404 	memcpy(cmd->data, buf, size);
2405 
2406 	dma = &ring->cmd_dma;
2407 	bus_dmamap_sync(dma->tag, dma->map, 0, dma->size, BUS_DMASYNC_PREWRITE);
2408 
2409 	desc->flags = htole32(WPI_PAD32(size) << 28 | 1 << 24);
2410 	desc->segs[0].addr = htole32(ring->cmd_dma.paddr +
2411 	    ring->cur * sizeof (struct wpi_tx_cmd));
2412 	desc->segs[0].len  = htole32(4 + size);
2413 
2414 	dma = &ring->desc_dma;
2415 	bus_dmamap_sync(dma->tag, dma->map, 0, dma->size, BUS_DMASYNC_PREWRITE);
2416 
2417 	/* kick cmd ring */
2418 	ring->cur = (ring->cur + 1) % WPI_CMD_RING_COUNT;
2419 	WPI_WRITE(sc, WPI_TX_WIDX, ring->qid << 8 | ring->cur);
2420 
2421 	return async ? 0 : tsleep(cmd, PCATCH, "wpicmd", hz);
2422 }
2423 
2424 static int
2425 wpi_wme_update(struct ieee80211com *ic)
2426 {
2427 #define WPI_EXP2(v)	htole16((1 << (v)) - 1)
2428 #define WPI_USEC(v)	htole16(IEEE80211_TXOP_TO_US(v))
2429 	struct wpi_softc *sc = ic->ic_ifp->if_softc;
2430 	const struct wmeParams *wmep;
2431 	struct wpi_wme_setup wme;
2432 	int ac;
2433 
2434 	/* don't override default WME values if WME is not actually enabled */
2435 	if (!(ic->ic_flags & IEEE80211_F_WME))
2436 		return 0;
2437 
2438 	wme.flags = 0;
2439 	for (ac = 0; ac < WME_NUM_AC; ac++) {
2440 		wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
2441 		wme.ac[ac].aifsn = wmep->wmep_aifsn;
2442 		wme.ac[ac].cwmin = WPI_EXP2(wmep->wmep_logcwmin);
2443 		wme.ac[ac].cwmax = WPI_EXP2(wmep->wmep_logcwmax);
2444 		wme.ac[ac].txop  = WPI_USEC(wmep->wmep_txopLimit);
2445 
2446 		DPRINTF(("setting WME for queue %d aifsn=%d cwmin=%d cwmax=%d "
2447 		    "txop=%d\n", ac, wme.ac[ac].aifsn, wme.ac[ac].cwmin,
2448 		    wme.ac[ac].cwmax, wme.ac[ac].txop));
2449 	}
2450 
2451 	return wpi_cmd(sc, WPI_CMD_SET_WME, &wme, sizeof wme, 1);
2452 #undef WPI_USEC
2453 #undef WPI_EXP2
2454 }
2455 
2456 /*
2457  * Configure h/w multi-rate retries.
2458  */
2459 static int
2460 wpi_mrr_setup(struct wpi_softc *sc)
2461 {
2462 	struct ieee80211com *ic = &sc->sc_ic;
2463 	struct wpi_mrr_setup mrr;
2464 	int i, error;
2465 
2466 	/* CCK rates (not used with 802.11a) */
2467 	for (i = WPI_CCK1; i <= WPI_CCK11; i++) {
2468 		mrr.rates[i].flags = 0;
2469 		mrr.rates[i].plcp = wpi_ridx_to_plcp[i];
2470 		/* fallback to the immediate lower CCK rate (if any) */
2471 		mrr.rates[i].next = (i == WPI_CCK1) ? WPI_CCK1 : i - 1;
2472 		/* try one time at this rate before falling back to "next" */
2473 		mrr.rates[i].ntries = 1;
2474 	}
2475 
2476 	/* OFDM rates (not used with 802.11b) */
2477 	for (i = WPI_OFDM6; i <= WPI_OFDM54; i++) {
2478 		mrr.rates[i].flags = 0;
2479 		mrr.rates[i].plcp = wpi_ridx_to_plcp[i];
2480 		/* fallback to the immediate lower rate (if any) */
2481 		/* we allow fallback from OFDM/6 to CCK/2 in 11b/g mode */
2482 		mrr.rates[i].next = (i == WPI_OFDM6) ?
2483 		    ((ic->ic_curmode == IEEE80211_MODE_11A) ?
2484 			WPI_OFDM6 : WPI_CCK2) :
2485 		    i - 1;
2486 		/* try one time at this rate before falling back to "next" */
2487 		mrr.rates[i].ntries = 1;
2488 	}
2489 
2490 	/* setup MRR for control frames */
2491 	mrr.which = htole32(WPI_MRR_CTL);
2492 	error = wpi_cmd(sc, WPI_CMD_MRR_SETUP, &mrr, sizeof mrr, 0);
2493 	if (error != 0) {
2494 		aprint_error_dev(sc->sc_dev,
2495 		    "could not setup MRR for control frames\n");
2496 		return error;
2497 	}
2498 
2499 	/* setup MRR for data frames */
2500 	mrr.which = htole32(WPI_MRR_DATA);
2501 	error = wpi_cmd(sc, WPI_CMD_MRR_SETUP, &mrr, sizeof mrr, 0);
2502 	if (error != 0) {
2503 		aprint_error_dev(sc->sc_dev,
2504 		    "could not setup MRR for data frames\n");
2505 		return error;
2506 	}
2507 
2508 	return 0;
2509 }
2510 
2511 static void
2512 wpi_set_led(struct wpi_softc *sc, uint8_t which, uint8_t off, uint8_t on)
2513 {
2514 	struct wpi_cmd_led led;
2515 
2516 	led.which = which;
2517 	led.unit = htole32(100000);	/* on/off in unit of 100ms */
2518 	led.off = off;
2519 	led.on = on;
2520 
2521 	(void)wpi_cmd(sc, WPI_CMD_SET_LED, &led, sizeof led, 1);
2522 }
2523 
2524 static void
2525 wpi_enable_tsf(struct wpi_softc *sc, struct ieee80211_node *ni)
2526 {
2527 	struct wpi_cmd_tsf tsf;
2528 	uint64_t val, mod;
2529 
2530 	memset(&tsf, 0, sizeof tsf);
2531 	memcpy(&tsf.tstamp, ni->ni_tstamp.data, sizeof (uint64_t));
2532 	tsf.bintval = htole16(ni->ni_intval);
2533 	tsf.lintval = htole16(10);
2534 
2535 	/* compute remaining time until next beacon */
2536 	val = (uint64_t)ni->ni_intval * 1024;	/* msecs -> usecs */
2537 	mod = le64toh(tsf.tstamp) % val;
2538 	tsf.binitval = htole32((uint32_t)(val - mod));
2539 
2540 	DPRINTF(("TSF bintval=%u tstamp=%" PRIu64 ", init=%u\n",
2541 	    ni->ni_intval, le64toh(tsf.tstamp), (uint32_t)(val - mod)));
2542 
2543 	if (wpi_cmd(sc, WPI_CMD_TSF, &tsf, sizeof tsf, 1) != 0)
2544 		aprint_error_dev(sc->sc_dev, "could not enable TSF\n");
2545 }
2546 
2547 /*
2548  * Update Tx power to match what is defined for channel `c'.
2549  */
2550 static int
2551 wpi_set_txpower(struct wpi_softc *sc, struct ieee80211_channel *c, int async)
2552 {
2553 	struct ieee80211com *ic = &sc->sc_ic;
2554 	struct wpi_power_group *group;
2555 	struct wpi_cmd_txpower txpower;
2556 	u_int chan;
2557 	int i;
2558 
2559 	/* get channel number */
2560 	chan = ieee80211_chan2ieee(ic, c);
2561 
2562 	/* find the power group to which this channel belongs */
2563 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
2564 		for (group = &sc->groups[1]; group < &sc->groups[4]; group++)
2565 			if (chan <= group->chan)
2566 				break;
2567 	} else
2568 		group = &sc->groups[0];
2569 
2570 	memset(&txpower, 0, sizeof txpower);
2571 	txpower.band = IEEE80211_IS_CHAN_5GHZ(c) ? 0 : 1;
2572 	txpower.chan = htole16(chan);
2573 
2574 	/* set Tx power for all OFDM and CCK rates */
2575 	for (i = 0; i <= 11 ; i++) {
2576 		/* retrieve Tx power for this channel/rate combination */
2577 		int idx = wpi_get_power_index(sc, group, c,
2578 		    wpi_ridx_to_rate[i]);
2579 
2580 		txpower.rates[i].plcp = wpi_ridx_to_plcp[i];
2581 
2582 		if (IEEE80211_IS_CHAN_5GHZ(c)) {
2583 			txpower.rates[i].rf_gain = wpi_rf_gain_5ghz[idx];
2584 			txpower.rates[i].dsp_gain = wpi_dsp_gain_5ghz[idx];
2585 		} else {
2586 			txpower.rates[i].rf_gain = wpi_rf_gain_2ghz[idx];
2587 			txpower.rates[i].dsp_gain = wpi_dsp_gain_2ghz[idx];
2588 		}
2589 		DPRINTF(("chan %d/rate %d: power index %d\n", chan,
2590 		    wpi_ridx_to_rate[i], idx));
2591 	}
2592 
2593 	return wpi_cmd(sc, WPI_CMD_TXPOWER, &txpower, sizeof txpower, async);
2594 }
2595 
2596 /*
2597  * Determine Tx power index for a given channel/rate combination.
2598  * This takes into account the regulatory information from EEPROM and the
2599  * current temperature.
2600  */
2601 static int
2602 wpi_get_power_index(struct wpi_softc *sc, struct wpi_power_group *group,
2603     struct ieee80211_channel *c, int rate)
2604 {
2605 /* fixed-point arithmetic division using a n-bit fractional part */
2606 #define fdivround(a, b, n)	\
2607 	((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
2608 
2609 /* linear interpolation */
2610 #define interpolate(x, x1, y1, x2, y2, n)	\
2611 	((y1) + fdivround(((x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
2612 
2613 	struct ieee80211com *ic = &sc->sc_ic;
2614 	struct wpi_power_sample *sample;
2615 	int pwr, idx;
2616 	u_int chan;
2617 
2618 	/* get channel number */
2619 	chan = ieee80211_chan2ieee(ic, c);
2620 
2621 	/* default power is group's maximum power - 3dB */
2622 	pwr = group->maxpwr / 2;
2623 
2624 	/* decrease power for highest OFDM rates to reduce distortion */
2625 	switch (rate) {
2626 	case 72:	/* 36Mb/s */
2627 		pwr -= IEEE80211_IS_CHAN_2GHZ(c) ? 0 :  5;
2628 		break;
2629 	case 96:	/* 48Mb/s */
2630 		pwr -= IEEE80211_IS_CHAN_2GHZ(c) ? 7 : 10;
2631 		break;
2632 	case 108:	/* 54Mb/s */
2633 		pwr -= IEEE80211_IS_CHAN_2GHZ(c) ? 9 : 12;
2634 		break;
2635 	}
2636 
2637 	/* never exceed channel's maximum allowed Tx power */
2638 	pwr = uimin(pwr, sc->maxpwr[chan]);
2639 
2640 	/* retrieve power index into gain tables from samples */
2641 	for (sample = group->samples; sample < &group->samples[3]; sample++)
2642 		if (pwr > sample[1].power)
2643 			break;
2644 	/* fixed-point linear interpolation using a 19-bit fractional part */
2645 	idx = interpolate(pwr, sample[0].power, sample[0].index,
2646 	    sample[1].power, sample[1].index, 19);
2647 
2648 	/*-
2649 	 * Adjust power index based on current temperature:
2650 	 * - if cooler than factory-calibrated: decrease output power
2651 	 * - if warmer than factory-calibrated: increase output power
2652 	 */
2653 	idx -= (sc->temp - group->temp) * 11 / 100;
2654 
2655 	/* decrease power for CCK rates (-5dB) */
2656 	if (!WPI_RATE_IS_OFDM(rate))
2657 		idx += 10;
2658 
2659 	/* keep power index in a valid range */
2660 	if (idx < 0)
2661 		return 0;
2662 	if (idx > WPI_MAX_PWR_INDEX)
2663 		return WPI_MAX_PWR_INDEX;
2664 	return idx;
2665 
2666 #undef interpolate
2667 #undef fdivround
2668 }
2669 
2670 /*
2671  * Build a beacon frame that the firmware will broadcast periodically in
2672  * IBSS or HostAP modes.
2673  */
2674 static int
2675 wpi_setup_beacon(struct wpi_softc *sc, struct ieee80211_node *ni)
2676 {
2677 	struct ieee80211com *ic = &sc->sc_ic;
2678 	struct wpi_tx_ring *ring = &sc->cmdq;
2679 	struct wpi_tx_desc *desc;
2680 	struct wpi_tx_data *data;
2681 	struct wpi_tx_cmd *cmd;
2682 	struct wpi_cmd_beacon *bcn;
2683 	struct ieee80211_beacon_offsets bo;
2684 	struct mbuf *m0;
2685 	int error;
2686 
2687 	desc = &ring->desc[ring->cur];
2688 	data = &ring->data[ring->cur];
2689 
2690 	m0 = ieee80211_beacon_alloc(ic, ni, &bo);
2691 	if (m0 == NULL) {
2692 		aprint_error_dev(sc->sc_dev,
2693 		    "could not allocate beacon frame\n");
2694 		return ENOMEM;
2695 	}
2696 
2697 	cmd = &ring->cmd[ring->cur];
2698 	cmd->code = WPI_CMD_SET_BEACON;
2699 	cmd->flags = 0;
2700 	cmd->qid = ring->qid;
2701 	cmd->idx = ring->cur;
2702 
2703 	bcn = (struct wpi_cmd_beacon *)cmd->data;
2704 	memset(bcn, 0, sizeof (struct wpi_cmd_beacon));
2705 	bcn->id = WPI_ID_BROADCAST;
2706 	bcn->ofdm_mask = 0xff;
2707 	bcn->cck_mask = 0x0f;
2708 	bcn->lifetime = htole32(WPI_LIFETIME_INFINITE);
2709 	bcn->len = htole16(m0->m_pkthdr.len);
2710 	bcn->rate = (ic->ic_curmode == IEEE80211_MODE_11A) ?
2711 	    wpi_plcp_signal(12) : wpi_plcp_signal(2);
2712 	bcn->flags = htole32(WPI_TX_AUTO_SEQ | WPI_TX_INSERT_TSTAMP);
2713 
2714 	/* save and trim IEEE802.11 header */
2715 	m_copydata(m0, 0, sizeof (struct ieee80211_frame), (void *)&bcn->wh);
2716 	m_adj(m0, sizeof (struct ieee80211_frame));
2717 
2718 	/* assume beacon frame is contiguous */
2719 	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
2720 	    BUS_DMA_READ | BUS_DMA_NOWAIT);
2721 	if (error != 0) {
2722 		aprint_error_dev(sc->sc_dev, "could not map beacon\n");
2723 		m_freem(m0);
2724 		return error;
2725 	}
2726 
2727 	data->m = m0;
2728 
2729 	/* first scatter/gather segment is used by the beacon command */
2730 	desc->flags = htole32(WPI_PAD32(m0->m_pkthdr.len) << 28 | 2 << 24);
2731 	desc->segs[0].addr = htole32(ring->cmd_dma.paddr +
2732 	    ring->cur * sizeof (struct wpi_tx_cmd));
2733 	desc->segs[0].len  = htole32(4 + sizeof (struct wpi_cmd_beacon));
2734 	desc->segs[1].addr = htole32(data->map->dm_segs[0].ds_addr);
2735 	desc->segs[1].len  = htole32(data->map->dm_segs[0].ds_len);
2736 
2737 	bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map, 0,
2738 	    ring->desc_dma.map->dm_mapsize, BUS_DMASYNC_PREWRITE);
2739 	bus_dmamap_sync(sc->sc_dmat, data->map, 0, data->map->dm_mapsize,
2740 	    BUS_DMASYNC_PREWRITE);
2741 
2742 	/* kick cmd ring */
2743 	ring->cur = (ring->cur + 1) % WPI_CMD_RING_COUNT;
2744 	WPI_WRITE(sc, WPI_TX_WIDX, ring->qid << 8 | ring->cur);
2745 
2746 	return 0;
2747 }
2748 
2749 static int
2750 wpi_auth(struct wpi_softc *sc)
2751 {
2752 	struct ieee80211com *ic = &sc->sc_ic;
2753 	struct ieee80211_node *ni = ic->ic_bss;
2754 	struct wpi_node_info node;
2755 	int error;
2756 
2757 	/* update adapter's configuration */
2758 	IEEE80211_ADDR_COPY(sc->config.bssid, ni->ni_bssid);
2759 	sc->config.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
2760 	sc->config.flags = htole32(WPI_CONFIG_TSF);
2761 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) {
2762 		sc->config.flags |= htole32(WPI_CONFIG_AUTO |
2763 		    WPI_CONFIG_24GHZ);
2764 	}
2765 	switch (ic->ic_curmode) {
2766 	case IEEE80211_MODE_11A:
2767 		sc->config.cck_mask  = 0;
2768 		sc->config.ofdm_mask = 0x15;
2769 		break;
2770 	case IEEE80211_MODE_11B:
2771 		sc->config.cck_mask  = 0x03;
2772 		sc->config.ofdm_mask = 0;
2773 		break;
2774 	default:	/* assume 802.11b/g */
2775 		sc->config.cck_mask  = 0x0f;
2776 		sc->config.ofdm_mask = 0x15;
2777 	}
2778 	DPRINTF(("config chan %d flags %x cck %x ofdm %x\n", sc->config.chan,
2779 	    sc->config.flags, sc->config.cck_mask, sc->config.ofdm_mask));
2780 	error = wpi_cmd(sc, WPI_CMD_CONFIGURE, &sc->config,
2781 	    sizeof (struct wpi_config), 1);
2782 	if (error != 0) {
2783 		aprint_error_dev(sc->sc_dev, "could not configure\n");
2784 		return error;
2785 	}
2786 
2787 	/* configuration has changed, set Tx power accordingly */
2788 	if ((error = wpi_set_txpower(sc, ni->ni_chan, 1)) != 0) {
2789 		aprint_error_dev(sc->sc_dev, "could not set Tx power\n");
2790 		return error;
2791 	}
2792 
2793 	/* add default node */
2794 	memset(&node, 0, sizeof node);
2795 	IEEE80211_ADDR_COPY(node.bssid, ni->ni_bssid);
2796 	node.id = WPI_ID_BSS;
2797 	node.rate = (ic->ic_curmode == IEEE80211_MODE_11A) ?
2798 	    wpi_plcp_signal(12) : wpi_plcp_signal(2);
2799 	node.action = htole32(WPI_ACTION_SET_RATE);
2800 	node.antenna = WPI_ANTENNA_BOTH;
2801 	error = wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, 1);
2802 	if (error != 0) {
2803 		aprint_error_dev(sc->sc_dev, "could not add BSS node\n");
2804 		return error;
2805 	}
2806 
2807 	return 0;
2808 }
2809 
2810 /*
2811  * Send a scan request to the firmware.  Since this command is huge, we map it
2812  * into a mbuf instead of using the pre-allocated set of commands.
2813  */
2814 static int
2815 wpi_scan(struct wpi_softc *sc)
2816 {
2817 	struct ieee80211com *ic = &sc->sc_ic;
2818 	struct wpi_tx_ring *ring = &sc->cmdq;
2819 	struct wpi_tx_desc *desc;
2820 	struct wpi_tx_data *data;
2821 	struct wpi_tx_cmd *cmd;
2822 	struct wpi_scan_hdr *hdr;
2823 	struct wpi_scan_chan *chan;
2824 	struct ieee80211_frame *wh;
2825 	struct ieee80211_rateset *rs;
2826 	struct ieee80211_channel *c;
2827 	uint8_t *frm;
2828 	int pktlen, error, nrates;
2829 
2830 	if (ic->ic_curchan == NULL)
2831 		return EIO;
2832 
2833 	desc = &ring->desc[ring->cur];
2834 	data = &ring->data[ring->cur];
2835 
2836 	MGETHDR(data->m, M_DONTWAIT, MT_DATA);
2837 	if (data->m == NULL) {
2838 		aprint_error_dev(sc->sc_dev,
2839 		    "could not allocate mbuf for scan command\n");
2840 		return ENOMEM;
2841 	}
2842 	MCLGET(data->m, M_DONTWAIT);
2843 	if (!(data->m->m_flags & M_EXT)) {
2844 		m_freem(data->m);
2845 		data->m = NULL;
2846 		aprint_error_dev(sc->sc_dev,
2847 		    "could not allocate mbuf for scan command\n");
2848 		return ENOMEM;
2849 	}
2850 
2851 	cmd = mtod(data->m, struct wpi_tx_cmd *);
2852 	cmd->code = WPI_CMD_SCAN;
2853 	cmd->flags = 0;
2854 	cmd->qid = ring->qid;
2855 	cmd->idx = ring->cur;
2856 
2857 	hdr = (struct wpi_scan_hdr *)cmd->data;
2858 	memset(hdr, 0, sizeof (struct wpi_scan_hdr));
2859 	hdr->cmd.flags = htole32(WPI_TX_AUTO_SEQ);
2860 	hdr->cmd.id = WPI_ID_BROADCAST;
2861 	hdr->cmd.lifetime = htole32(WPI_LIFETIME_INFINITE);
2862 	/*
2863 	 * Move to the next channel if no packets are received within 5 msecs
2864 	 * after sending the probe request (this helps to reduce the duration
2865 	 * of active scans).
2866 	 */
2867 	hdr->quiet = htole16(5);	/* timeout in milliseconds */
2868 	hdr->plcp_threshold = htole16(1);	/* min # of packets */
2869 
2870 	if (ic->ic_curchan->ic_flags & IEEE80211_CHAN_5GHZ) {
2871 		hdr->crc_threshold = htole16(1);
2872 		/* send probe requests at 6Mbps */
2873 		hdr->cmd.rate = wpi_plcp_signal(12);
2874 		rs = &ic->ic_sup_rates[IEEE80211_MODE_11A];
2875 	} else {
2876 		hdr->flags = htole32(WPI_CONFIG_24GHZ | WPI_CONFIG_AUTO);
2877 		/* send probe requests at 1Mbps */
2878 		hdr->cmd.rate = wpi_plcp_signal(2);
2879 		rs = &ic->ic_sup_rates[IEEE80211_MODE_11G];
2880 	}
2881 
2882 	/* for directed scans, firmware inserts the essid IE itself */
2883 	if (ic->ic_des_esslen != 0) {
2884 		hdr->essid[0].id  = IEEE80211_ELEMID_SSID;
2885 		hdr->essid[0].len = ic->ic_des_esslen;
2886 		memcpy(hdr->essid[0].data, ic->ic_des_essid, ic->ic_des_esslen);
2887 	}
2888 
2889 	/*
2890 	 * Build a probe request frame.  Most of the following code is a
2891 	 * copy & paste of what is done in net80211.
2892 	 */
2893 	wh = (struct ieee80211_frame *)(hdr + 1);
2894 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
2895 	    IEEE80211_FC0_SUBTYPE_PROBE_REQ;
2896 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
2897 	IEEE80211_ADDR_COPY(wh->i_addr1, etherbroadcastaddr);
2898 	IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
2899 	IEEE80211_ADDR_COPY(wh->i_addr3, etherbroadcastaddr);
2900 	*(u_int16_t *)&wh->i_dur[0] = 0;	/* filled by h/w */
2901 	*(u_int16_t *)&wh->i_seq[0] = 0;	/* filled by h/w */
2902 
2903 	frm = (uint8_t *)(wh + 1);
2904 
2905 	/* add empty essid IE (firmware generates it for directed scans) */
2906 	*frm++ = IEEE80211_ELEMID_SSID;
2907 	*frm++ = 0;
2908 
2909 	/* add supported rates IE */
2910 	*frm++ = IEEE80211_ELEMID_RATES;
2911 	nrates = rs->rs_nrates;
2912 	if (nrates > IEEE80211_RATE_SIZE)
2913 		nrates = IEEE80211_RATE_SIZE;
2914 	*frm++ = nrates;
2915 	memcpy(frm, rs->rs_rates, nrates);
2916 	frm += nrates;
2917 
2918 	/* add supported xrates IE */
2919 	if (rs->rs_nrates > IEEE80211_RATE_SIZE) {
2920 		nrates = rs->rs_nrates - IEEE80211_RATE_SIZE;
2921 		*frm++ = IEEE80211_ELEMID_XRATES;
2922 		*frm++ = nrates;
2923 		memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates);
2924 		frm += nrates;
2925 	}
2926 
2927 	/* setup length of probe request */
2928 	hdr->cmd.len = htole16(frm - (uint8_t *)wh);
2929 
2930 	chan = (struct wpi_scan_chan *)frm;
2931 	c = ic->ic_curchan;
2932 
2933 	chan->chan = ieee80211_chan2ieee(ic, c);
2934 	chan->flags = 0;
2935 	if (!(c->ic_flags & IEEE80211_CHAN_PASSIVE)) {
2936 		chan->flags |= WPI_CHAN_ACTIVE;
2937 		if (ic->ic_des_esslen != 0)
2938 			chan->flags |= WPI_CHAN_DIRECT;
2939 	}
2940 	chan->dsp_gain = 0x6e;
2941 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
2942 		chan->rf_gain = 0x3b;
2943 		chan->active  = htole16(10);
2944 		chan->passive = htole16(110);
2945 	} else {
2946 		chan->rf_gain = 0x28;
2947 		chan->active  = htole16(20);
2948 		chan->passive = htole16(120);
2949 	}
2950 	hdr->nchan++;
2951 	chan++;
2952 
2953 	frm += sizeof (struct wpi_scan_chan);
2954 
2955 	hdr->len = htole16(frm - (uint8_t *)hdr);
2956 	pktlen = frm - (uint8_t *)cmd;
2957 
2958 	error = bus_dmamap_load(sc->sc_dmat, data->map, cmd, pktlen, NULL,
2959 	    BUS_DMA_NOWAIT);
2960 	if (error != 0) {
2961 		aprint_error_dev(sc->sc_dev, "could not map scan command\n");
2962 		m_freem(data->m);
2963 		data->m = NULL;
2964 		return error;
2965 	}
2966 
2967 	desc->flags = htole32(WPI_PAD32(pktlen) << 28 | 1 << 24);
2968 	desc->segs[0].addr = htole32(data->map->dm_segs[0].ds_addr);
2969 	desc->segs[0].len  = htole32(data->map->dm_segs[0].ds_len);
2970 
2971 	bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map, 0,
2972 	    ring->desc_dma.map->dm_mapsize, BUS_DMASYNC_PREWRITE);
2973 	bus_dmamap_sync(sc->sc_dmat, data->map, 0, data->map->dm_mapsize,
2974 	    BUS_DMASYNC_PREWRITE);
2975 
2976 	/* kick cmd ring */
2977 	ring->cur = (ring->cur + 1) % WPI_CMD_RING_COUNT;
2978 	WPI_WRITE(sc, WPI_TX_WIDX, ring->qid << 8 | ring->cur);
2979 
2980 	return 0;	/* will be notified async. of failure/success */
2981 }
2982 
2983 static int
2984 wpi_config(struct wpi_softc *sc)
2985 {
2986 	struct ieee80211com *ic = &sc->sc_ic;
2987 	struct ifnet *ifp = ic->ic_ifp;
2988 	struct wpi_power power;
2989 	struct wpi_bluetooth bluetooth;
2990 	struct wpi_node_info node;
2991 	int error;
2992 
2993 	memset(&power, 0, sizeof power);
2994 	power.flags = htole32(WPI_POWER_CAM | 0x8);
2995 	error = wpi_cmd(sc, WPI_CMD_SET_POWER_MODE, &power, sizeof power, 0);
2996 	if (error != 0) {
2997 		aprint_error_dev(sc->sc_dev, "could not set power mode\n");
2998 		return error;
2999 	}
3000 
3001 	/* configure bluetooth coexistence */
3002 	memset(&bluetooth, 0, sizeof bluetooth);
3003 	bluetooth.flags = 3;
3004 	bluetooth.lead = 0xaa;
3005 	bluetooth.kill = 1;
3006 	error = wpi_cmd(sc, WPI_CMD_BLUETOOTH, &bluetooth, sizeof bluetooth,
3007 	    0);
3008 	if (error != 0) {
3009 		aprint_error_dev(sc->sc_dev,
3010 			"could not configure bluetooth coexistence\n");
3011 		return error;
3012 	}
3013 
3014 	/* configure adapter */
3015 	memset(&sc->config, 0, sizeof (struct wpi_config));
3016 	IEEE80211_ADDR_COPY(ic->ic_myaddr, CLLADDR(ifp->if_sadl));
3017 	IEEE80211_ADDR_COPY(sc->config.myaddr, ic->ic_myaddr);
3018 	/* set default channel */
3019 	sc->config.chan = ieee80211_chan2ieee(ic, ic->ic_curchan);
3020 	sc->config.flags = htole32(WPI_CONFIG_TSF);
3021 	if (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan)) {
3022 		sc->config.flags |= htole32(WPI_CONFIG_AUTO |
3023 		    WPI_CONFIG_24GHZ);
3024 	}
3025 	sc->config.filter = 0;
3026 	switch (ic->ic_opmode) {
3027 	case IEEE80211_M_STA:
3028 		sc->config.mode = WPI_MODE_STA;
3029 		sc->config.filter |= htole32(WPI_FILTER_MULTICAST);
3030 		break;
3031 	case IEEE80211_M_IBSS:
3032 	case IEEE80211_M_AHDEMO:
3033 		sc->config.mode = WPI_MODE_IBSS;
3034 		break;
3035 	case IEEE80211_M_HOSTAP:
3036 		sc->config.mode = WPI_MODE_HOSTAP;
3037 		break;
3038 	case IEEE80211_M_MONITOR:
3039 		sc->config.mode = WPI_MODE_MONITOR;
3040 		sc->config.filter |= htole32(WPI_FILTER_MULTICAST |
3041 		    WPI_FILTER_CTL | WPI_FILTER_PROMISC);
3042 		break;
3043 	}
3044 	sc->config.cck_mask  = 0x0f;	/* not yet negotiated */
3045 	sc->config.ofdm_mask = 0xff;	/* not yet negotiated */
3046 	error = wpi_cmd(sc, WPI_CMD_CONFIGURE, &sc->config,
3047 	    sizeof (struct wpi_config), 0);
3048 	if (error != 0) {
3049 		aprint_error_dev(sc->sc_dev, "configure command failed\n");
3050 		return error;
3051 	}
3052 
3053 	/* configuration has changed, set Tx power accordingly */
3054 	if ((error = wpi_set_txpower(sc, ic->ic_curchan, 0)) != 0) {
3055 		aprint_error_dev(sc->sc_dev, "could not set Tx power\n");
3056 		return error;
3057 	}
3058 
3059 	/* add broadcast node */
3060 	memset(&node, 0, sizeof node);
3061 	IEEE80211_ADDR_COPY(node.bssid, etherbroadcastaddr);
3062 	node.id = WPI_ID_BROADCAST;
3063 	node.rate = wpi_plcp_signal(2);
3064 	node.action = htole32(WPI_ACTION_SET_RATE);
3065 	node.antenna = WPI_ANTENNA_BOTH;
3066 	error = wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, 0);
3067 	if (error != 0) {
3068 		aprint_error_dev(sc->sc_dev, "could not add broadcast node\n");
3069 		return error;
3070 	}
3071 
3072 	if ((error = wpi_mrr_setup(sc)) != 0) {
3073 		aprint_error_dev(sc->sc_dev, "could not setup MRR\n");
3074 		return error;
3075 	}
3076 
3077 	return 0;
3078 }
3079 
3080 static void
3081 wpi_stop_master(struct wpi_softc *sc)
3082 {
3083 	uint32_t tmp;
3084 	int ntries;
3085 
3086 	tmp = WPI_READ(sc, WPI_RESET);
3087 	WPI_WRITE(sc, WPI_RESET, tmp | WPI_STOP_MASTER);
3088 
3089 	tmp = WPI_READ(sc, WPI_GPIO_CTL);
3090 	if ((tmp & WPI_GPIO_PWR_STATUS) == WPI_GPIO_PWR_SLEEP)
3091 		return;	/* already asleep */
3092 
3093 	for (ntries = 0; ntries < 100; ntries++) {
3094 		if (WPI_READ(sc, WPI_RESET) & WPI_MASTER_DISABLED)
3095 			break;
3096 		DELAY(10);
3097 	}
3098 	if (ntries == 100) {
3099 		aprint_error_dev(sc->sc_dev, "timeout waiting for master\n");
3100 	}
3101 }
3102 
3103 static int
3104 wpi_power_up(struct wpi_softc *sc)
3105 {
3106 	uint32_t tmp;
3107 	int ntries;
3108 
3109 	wpi_mem_lock(sc);
3110 	tmp = wpi_mem_read(sc, WPI_MEM_POWER);
3111 	wpi_mem_write(sc, WPI_MEM_POWER, tmp & ~0x03000000);
3112 	wpi_mem_unlock(sc);
3113 
3114 	for (ntries = 0; ntries < 5000; ntries++) {
3115 		if (WPI_READ(sc, WPI_GPIO_STATUS) & WPI_POWERED)
3116 			break;
3117 		DELAY(10);
3118 	}
3119 	if (ntries == 5000) {
3120 		aprint_error_dev(sc->sc_dev,
3121 		    "timeout waiting for NIC to power up\n");
3122 		return ETIMEDOUT;
3123 	}
3124 	return 0;
3125 }
3126 
3127 static int
3128 wpi_reset(struct wpi_softc *sc)
3129 {
3130 	uint32_t tmp;
3131 	int ntries;
3132 
3133 	/* clear any pending interrupts */
3134 	WPI_WRITE(sc, WPI_INTR, 0xffffffff);
3135 
3136 	tmp = WPI_READ(sc, WPI_PLL_CTL);
3137 	WPI_WRITE(sc, WPI_PLL_CTL, tmp | WPI_PLL_INIT);
3138 
3139 	tmp = WPI_READ(sc, WPI_CHICKEN);
3140 	WPI_WRITE(sc, WPI_CHICKEN, tmp | WPI_CHICKEN_RXNOLOS);
3141 
3142 	tmp = WPI_READ(sc, WPI_GPIO_CTL);
3143 	WPI_WRITE(sc, WPI_GPIO_CTL, tmp | WPI_GPIO_INIT);
3144 
3145 	/* wait for clock stabilization */
3146 	for (ntries = 0; ntries < 1000; ntries++) {
3147 		if (WPI_READ(sc, WPI_GPIO_CTL) & WPI_GPIO_CLOCK)
3148 			break;
3149 		DELAY(10);
3150 	}
3151 	if (ntries == 1000) {
3152 		aprint_error_dev(sc->sc_dev,
3153 		    "timeout waiting for clock stabilization\n");
3154 		return ETIMEDOUT;
3155 	}
3156 
3157 	/* initialize EEPROM */
3158 	tmp = WPI_READ(sc, WPI_EEPROM_STATUS);
3159 	if ((tmp & WPI_EEPROM_VERSION) == 0) {
3160 		aprint_error_dev(sc->sc_dev, "EEPROM not found\n");
3161 		return EIO;
3162 	}
3163 	WPI_WRITE(sc, WPI_EEPROM_STATUS, tmp & ~WPI_EEPROM_LOCKED);
3164 
3165 	return 0;
3166 }
3167 
3168 static void
3169 wpi_hw_config(struct wpi_softc *sc)
3170 {
3171 	uint32_t rev, hw;
3172 
3173 	/* voodoo from the reference driver */
3174 	hw = WPI_READ(sc, WPI_HWCONFIG);
3175 
3176 	rev = pci_conf_read(sc->sc_pct, sc->sc_pcitag, PCI_CLASS_REG);
3177 	rev = PCI_REVISION(rev);
3178 	if ((rev & 0xc0) == 0x40)
3179 		hw |= WPI_HW_ALM_MB;
3180 	else if (!(rev & 0x80))
3181 		hw |= WPI_HW_ALM_MM;
3182 
3183 	if (sc->cap == 0x80)
3184 		hw |= WPI_HW_SKU_MRC;
3185 
3186 	hw &= ~WPI_HW_REV_D;
3187 	if ((le16toh(sc->rev) & 0xf0) == 0xd0)
3188 		hw |= WPI_HW_REV_D;
3189 
3190 	if (sc->type > 1)
3191 		hw |= WPI_HW_TYPE_B;
3192 
3193 	DPRINTF(("setting h/w config %x\n", hw));
3194 	WPI_WRITE(sc, WPI_HWCONFIG, hw);
3195 }
3196 
3197 static int
3198 wpi_init(struct ifnet *ifp)
3199 {
3200 	struct wpi_softc *sc = ifp->if_softc;
3201 	struct ieee80211com *ic = &sc->sc_ic;
3202 	uint32_t tmp;
3203 	int qid, ntries, error;
3204 
3205 	wpi_stop(ifp, 1);
3206 	(void)wpi_reset(sc);
3207 
3208 	wpi_mem_lock(sc);
3209 	wpi_mem_write(sc, WPI_MEM_CLOCK1, 0xa00);
3210 	DELAY(20);
3211 	tmp = wpi_mem_read(sc, WPI_MEM_PCIDEV);
3212 	wpi_mem_write(sc, WPI_MEM_PCIDEV, tmp | 0x800);
3213 	wpi_mem_unlock(sc);
3214 
3215 	(void)wpi_power_up(sc);
3216 	wpi_hw_config(sc);
3217 
3218 	/* init Rx ring */
3219 	wpi_mem_lock(sc);
3220 	WPI_WRITE(sc, WPI_RX_BASE, sc->rxq.desc_dma.paddr);
3221 	WPI_WRITE(sc, WPI_RX_RIDX_PTR, sc->shared_dma.paddr +
3222 	    offsetof(struct wpi_shared, next));
3223 	WPI_WRITE(sc, WPI_RX_WIDX, (WPI_RX_RING_COUNT - 1) & ~7);
3224 	WPI_WRITE(sc, WPI_RX_CONFIG, 0xa9601010);
3225 	wpi_mem_unlock(sc);
3226 
3227 	/* init Tx rings */
3228 	wpi_mem_lock(sc);
3229 	wpi_mem_write(sc, WPI_MEM_MODE, 2);	/* bypass mode */
3230 	wpi_mem_write(sc, WPI_MEM_RA, 1);	/* enable RA0 */
3231 	wpi_mem_write(sc, WPI_MEM_TXCFG, 0x3f);	/* enable all 6 Tx rings */
3232 	wpi_mem_write(sc, WPI_MEM_BYPASS1, 0x10000);
3233 	wpi_mem_write(sc, WPI_MEM_BYPASS2, 0x30002);
3234 	wpi_mem_write(sc, WPI_MEM_MAGIC4, 4);
3235 	wpi_mem_write(sc, WPI_MEM_MAGIC5, 5);
3236 
3237 	WPI_WRITE(sc, WPI_TX_BASE_PTR, sc->shared_dma.paddr);
3238 	WPI_WRITE(sc, WPI_MSG_CONFIG, 0xffff05a5);
3239 
3240 	for (qid = 0; qid < 6; qid++) {
3241 		WPI_WRITE(sc, WPI_TX_CTL(qid), 0);
3242 		WPI_WRITE(sc, WPI_TX_BASE(qid), 0);
3243 		WPI_WRITE(sc, WPI_TX_CONFIG(qid), 0x80200008);
3244 	}
3245 	wpi_mem_unlock(sc);
3246 
3247 	/* clear "radio off" and "disable command" bits (reversed logic) */
3248 	WPI_WRITE(sc, WPI_UCODE_CLR, WPI_RADIO_OFF);
3249 	WPI_WRITE(sc, WPI_UCODE_CLR, WPI_DISABLE_CMD);
3250 
3251 	/* clear any pending interrupts */
3252 	WPI_WRITE(sc, WPI_INTR, 0xffffffff);
3253 	/* enable interrupts */
3254 	WPI_WRITE(sc, WPI_MASK, WPI_INTR_MASK);
3255 
3256 	/* not sure why/if this is necessary... */
3257 	WPI_WRITE(sc, WPI_UCODE_CLR, WPI_RADIO_OFF);
3258 	WPI_WRITE(sc, WPI_UCODE_CLR, WPI_RADIO_OFF);
3259 
3260 	if ((error = wpi_load_firmware(sc)) != 0)
3261 		/* wpi_load_firmware prints error messages for us.  */
3262 		goto fail1;
3263 
3264 	/* Check the status of the radio switch */
3265 	mutex_enter(&sc->sc_rsw_mtx);
3266 	if (wpi_getrfkill(sc)) {
3267 		mutex_exit(&sc->sc_rsw_mtx);
3268 		aprint_error_dev(sc->sc_dev,
3269 		    "radio is disabled by hardware switch\n");
3270 		ifp->if_flags &= ~IFF_UP;
3271 		error = EBUSY;
3272 		goto fail1;
3273 	}
3274 	sc->sc_rsw_suspend = false;
3275 	cv_broadcast(&sc->sc_rsw_cv);
3276 	while (sc->sc_rsw_suspend)
3277 		cv_wait(&sc->sc_rsw_cv, &sc->sc_rsw_mtx);
3278 	mutex_exit(&sc->sc_rsw_mtx);
3279 
3280 	/* wait for thermal sensors to calibrate */
3281 	for (ntries = 0; ntries < 1000; ntries++) {
3282 		if ((sc->temp = (int)WPI_READ(sc, WPI_TEMPERATURE)) != 0)
3283 			break;
3284 		DELAY(10);
3285 	}
3286 	if (ntries == 1000) {
3287 		aprint_error_dev(sc->sc_dev,
3288 		    "timeout waiting for thermal sensors calibration\n");
3289 		error = ETIMEDOUT;
3290 		goto fail1;
3291 	}
3292 	DPRINTF(("temperature %d\n", sc->temp));
3293 
3294 	if ((error = wpi_config(sc)) != 0) {
3295 		aprint_error_dev(sc->sc_dev, "could not configure device\n");
3296 		goto fail1;
3297 	}
3298 
3299 	ifp->if_flags &= ~IFF_OACTIVE;
3300 	ifp->if_flags |= IFF_RUNNING;
3301 
3302 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
3303 		if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
3304 			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
3305 	}
3306 	else
3307 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
3308 
3309 	return 0;
3310 
3311 fail1:	wpi_stop(ifp, 1);
3312 	return error;
3313 }
3314 
3315 static void
3316 wpi_stop1(struct ifnet *ifp, int disable, bool fromintr)
3317 {
3318 	struct wpi_softc *sc = ifp->if_softc;
3319 	struct ieee80211com *ic = &sc->sc_ic;
3320 	uint32_t tmp;
3321 	int ac;
3322 
3323 	ifp->if_timer = sc->sc_tx_timer = 0;
3324 	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
3325 
3326 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
3327 
3328 	if (fromintr) {
3329 		sc->sc_rsw_suspend = true; // XXX: without mutex or wait
3330 	} else {
3331 		wpi_rsw_suspend(sc);
3332 	}
3333 
3334 	/* disable interrupts */
3335 	WPI_WRITE(sc, WPI_MASK, 0);
3336 	WPI_WRITE(sc, WPI_INTR, WPI_INTR_MASK);
3337 	WPI_WRITE(sc, WPI_INTR_STATUS, 0xff);
3338 	WPI_WRITE(sc, WPI_INTR_STATUS, 0x00070000);
3339 
3340 	wpi_mem_lock(sc);
3341 	wpi_mem_write(sc, WPI_MEM_MODE, 0);
3342 	wpi_mem_unlock(sc);
3343 
3344 	/* reset all Tx rings */
3345 	for (ac = 0; ac < 4; ac++)
3346 		wpi_reset_tx_ring(sc, &sc->txq[ac]);
3347 	wpi_reset_tx_ring(sc, &sc->cmdq);
3348 
3349 	/* reset Rx ring */
3350 	wpi_reset_rx_ring(sc, &sc->rxq);
3351 
3352 	wpi_mem_lock(sc);
3353 	wpi_mem_write(sc, WPI_MEM_CLOCK2, 0x200);
3354 	wpi_mem_unlock(sc);
3355 
3356 	DELAY(5);
3357 
3358 	wpi_stop_master(sc);
3359 
3360 	tmp = WPI_READ(sc, WPI_RESET);
3361 	WPI_WRITE(sc, WPI_RESET, tmp | WPI_SW_RESET);
3362 }
3363 
3364 static void
3365 wpi_stop(struct ifnet *ifp, int disable)
3366 {
3367 	wpi_stop1(ifp, disable, false);
3368 }
3369 
3370 static void
3371 wpi_stop_intr(struct ifnet *ifp, int disable)
3372 {
3373 	wpi_stop1(ifp, disable, true);
3374 }
3375 
3376 static bool
3377 wpi_resume(device_t dv, const pmf_qual_t *qual)
3378 {
3379 	struct wpi_softc *sc = device_private(dv);
3380 
3381 	(void)wpi_reset(sc);
3382 
3383 	return true;
3384 }
3385 
3386 /*
3387  * Return whether or not the radio is enabled in hardware
3388  * (i.e. the rfkill switch is "off").
3389  */
3390 static int
3391 wpi_getrfkill(struct wpi_softc *sc)
3392 {
3393 	uint32_t tmp;
3394 
3395 	wpi_mem_lock(sc);
3396 	tmp = wpi_mem_read(sc, WPI_MEM_RFKILL);
3397 	wpi_mem_unlock(sc);
3398 
3399 	KASSERT(mutex_owned(&sc->sc_rsw_mtx));
3400 	if (tmp & 0x01) {
3401 		/* switch is on */
3402 		if (sc->sc_rsw_status != WPI_RSW_ON) {
3403 			sc->sc_rsw_status = WPI_RSW_ON;
3404 			sysmon_pswitch_event(&sc->sc_rsw,
3405 			    PSWITCH_EVENT_PRESSED);
3406 		}
3407 	} else {
3408 		/* switch is off */
3409 		if (sc->sc_rsw_status != WPI_RSW_OFF) {
3410 			sc->sc_rsw_status = WPI_RSW_OFF;
3411 			sysmon_pswitch_event(&sc->sc_rsw,
3412 			    PSWITCH_EVENT_RELEASED);
3413 		}
3414 	}
3415 
3416 	return !(tmp & 0x01);
3417 }
3418 
3419 static int
3420 wpi_sysctl_radio(SYSCTLFN_ARGS)
3421 {
3422 	struct sysctlnode node;
3423 	struct wpi_softc *sc;
3424 	int val, error;
3425 
3426 	node = *rnode;
3427 	sc = (struct wpi_softc *)node.sysctl_data;
3428 
3429 	mutex_enter(&sc->sc_rsw_mtx);
3430 	val = !wpi_getrfkill(sc);
3431 	mutex_exit(&sc->sc_rsw_mtx);
3432 
3433 	node.sysctl_data = &val;
3434 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
3435 
3436 	if (error || newp == NULL)
3437 		return error;
3438 
3439 	return 0;
3440 }
3441 
3442 static void
3443 wpi_sysctlattach(struct wpi_softc *sc)
3444 {
3445 	int rc;
3446 	const struct sysctlnode *rnode;
3447 	const struct sysctlnode *cnode;
3448 
3449 	struct sysctllog **clog = &sc->sc_sysctllog;
3450 
3451 	if ((rc = sysctl_createv(clog, 0, NULL, &rnode,
3452 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, device_xname(sc->sc_dev),
3453 	    SYSCTL_DESCR("wpi controls and statistics"),
3454 	    NULL, 0, NULL, 0, CTL_HW, CTL_CREATE, CTL_EOL)) != 0)
3455 		goto err;
3456 
3457 	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
3458 	    CTLFLAG_PERMANENT, CTLTYPE_INT, "radio",
3459 	    SYSCTL_DESCR("radio transmitter switch state (0=off, 1=on)"),
3460 	    wpi_sysctl_radio, 0, (void *)sc, 0, CTL_CREATE, CTL_EOL)) != 0)
3461 		goto err;
3462 
3463 #ifdef WPI_DEBUG
3464 	/* control debugging printfs */
3465 	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
3466 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
3467 	    "debug", SYSCTL_DESCR("Enable debugging output"),
3468 	    NULL, 0, &wpi_debug, 0, CTL_CREATE, CTL_EOL)) != 0)
3469 		goto err;
3470 #endif
3471 
3472 	return;
3473 err:
3474 	aprint_error("%s: sysctl_createv failed (rc = %d)\n", __func__, rc);
3475 }
3476 
3477 static void
3478 wpi_rsw_suspend(struct wpi_softc *sc)
3479 {
3480 	/* suspend rfkill test thread */
3481 	mutex_enter(&sc->sc_rsw_mtx);
3482 	sc->sc_rsw_suspend = true;
3483 	cv_broadcast(&sc->sc_rsw_cv);
3484 	while (!sc->sc_rsw_suspended)
3485 		cv_wait(&sc->sc_rsw_cv, &sc->sc_rsw_mtx);
3486 	mutex_exit(&sc->sc_rsw_mtx);
3487 }
3488 
3489 static void
3490 wpi_rsw_thread(void *arg)
3491 {
3492 	struct wpi_softc *sc = (struct wpi_softc *)arg;
3493 
3494 	mutex_enter(&sc->sc_rsw_mtx);
3495 	for (;;) {
3496 		cv_timedwait(&sc->sc_rsw_cv, &sc->sc_rsw_mtx, hz);
3497 		if (sc->sc_dying) {
3498 			sc->sc_rsw_lwp = NULL;
3499 			cv_broadcast(&sc->sc_rsw_cv);
3500 			mutex_exit(&sc->sc_rsw_mtx);
3501 			kthread_exit(0);
3502 		}
3503 		if (sc->sc_rsw_suspend) {
3504 			sc->sc_rsw_suspended = true;
3505 			cv_broadcast(&sc->sc_rsw_cv);
3506 			while (sc->sc_rsw_suspend || sc->sc_dying)
3507 				cv_wait(&sc->sc_rsw_cv, &sc->sc_rsw_mtx);
3508 			sc->sc_rsw_suspended = false;
3509 			cv_broadcast(&sc->sc_rsw_cv);
3510 		}
3511 		wpi_getrfkill(sc);
3512 	}
3513 }
3514