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