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