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