if_wpi.c revision 1.53
1/*  $NetBSD: if_wpi.c,v 1.53 2012/08/04 03:52:46 riastradh 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.53 2012/08/04 03:52:46 riastradh Exp $");
22
23/*
24 * Driver for Intel PRO/Wireless 3945ABG 802.11 network adapters.
25 */
26
27
28#include <sys/param.h>
29#include <sys/sockio.h>
30#include <sys/sysctl.h>
31#include <sys/mbuf.h>
32#include <sys/kernel.h>
33#include <sys/socket.h>
34#include <sys/systm.h>
35#include <sys/malloc.h>
36#include <sys/mutex.h>
37#include <sys/once.h>
38#include <sys/conf.h>
39#include <sys/kauth.h>
40#include <sys/callout.h>
41#include <sys/proc.h>
42
43#include <sys/bus.h>
44#include <machine/endian.h>
45#include <sys/intr.h>
46
47#include <dev/pci/pcireg.h>
48#include <dev/pci/pcivar.h>
49#include <dev/pci/pcidevs.h>
50
51#include <net/bpf.h>
52#include <net/if.h>
53#include <net/if_arp.h>
54#include <net/if_dl.h>
55#include <net/if_ether.h>
56#include <net/if_media.h>
57#include <net/if_types.h>
58
59#include <net80211/ieee80211_var.h>
60#include <net80211/ieee80211_amrr.h>
61#include <net80211/ieee80211_radiotap.h>
62
63#include <netinet/in.h>
64#include <netinet/in_systm.h>
65#include <netinet/in_var.h>
66#include <netinet/ip.h>
67
68#include <dev/firmload.h>
69
70#include <dev/pci/if_wpireg.h>
71#include <dev/pci/if_wpivar.h>
72
73#ifdef WPI_DEBUG
74#define DPRINTF(x)	if (wpi_debug > 0) printf x
75#define DPRINTFN(n, x)	if (wpi_debug >= (n)) printf x
76int wpi_debug = 1;
77#else
78#define DPRINTF(x)
79#define DPRINTFN(n, x)
80#endif
81
82/*
83 * Supported rates for 802.11a/b/g modes (in 500Kbps unit).
84 */
85static const struct ieee80211_rateset wpi_rateset_11a =
86	{ 8, { 12, 18, 24, 36, 48, 72, 96, 108 } };
87
88static const struct ieee80211_rateset wpi_rateset_11b =
89	{ 4, { 2, 4, 11, 22 } };
90
91static const struct ieee80211_rateset wpi_rateset_11g =
92	{ 12, { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 } };
93
94static once_t wpi_firmware_init;
95static kmutex_t wpi_firmware_mutex;
96static size_t wpi_firmware_users;
97static uint8_t *wpi_firmware_image;
98static size_t wpi_firmware_size;
99
100static int  wpi_match(device_t, cfdata_t, void *);
101static void wpi_attach(device_t, device_t, void *);
102static int  wpi_detach(device_t , int);
103static int  wpi_dma_contig_alloc(bus_dma_tag_t, struct wpi_dma_info *,
104	void **, bus_size_t, bus_size_t, int);
105static void wpi_dma_contig_free(struct wpi_dma_info *);
106static int  wpi_alloc_shared(struct wpi_softc *);
107static void wpi_free_shared(struct wpi_softc *);
108static int  wpi_alloc_fwmem(struct wpi_softc *);
109static void wpi_free_fwmem(struct wpi_softc *);
110static struct wpi_rbuf *wpi_alloc_rbuf(struct wpi_softc *);
111static void wpi_free_rbuf(struct mbuf *, void *, size_t, void *);
112static int  wpi_alloc_rpool(struct wpi_softc *);
113static void wpi_free_rpool(struct wpi_softc *);
114static int  wpi_alloc_rx_ring(struct wpi_softc *, struct wpi_rx_ring *);
115static void wpi_reset_rx_ring(struct wpi_softc *, struct wpi_rx_ring *);
116static void wpi_free_rx_ring(struct wpi_softc *, struct wpi_rx_ring *);
117static int  wpi_alloc_tx_ring(struct wpi_softc *, struct wpi_tx_ring *, int,
118	int);
119static void wpi_reset_tx_ring(struct wpi_softc *, struct wpi_tx_ring *);
120static void wpi_free_tx_ring(struct wpi_softc *, struct wpi_tx_ring *);
121static struct ieee80211_node * wpi_node_alloc(struct ieee80211_node_table *);
122static void wpi_newassoc(struct ieee80211_node *, int);
123static int  wpi_media_change(struct ifnet *);
124static int  wpi_newstate(struct ieee80211com *, enum ieee80211_state, int);
125static void	wpi_fix_channel(struct ieee80211com *, struct mbuf *);
126static void wpi_mem_lock(struct wpi_softc *);
127static void wpi_mem_unlock(struct wpi_softc *);
128static uint32_t wpi_mem_read(struct wpi_softc *, uint16_t);
129static void wpi_mem_write(struct wpi_softc *, uint16_t, uint32_t);
130static void wpi_mem_write_region_4(struct wpi_softc *, uint16_t,
131								   const uint32_t *, int);
132static int  wpi_read_prom_data(struct wpi_softc *, uint32_t, void *, int);
133static int  wpi_load_microcode(struct wpi_softc *,  const uint8_t *, int);
134static int  wpi_load_firmware(struct wpi_softc *);
135static void wpi_calib_timeout(void *);
136static void wpi_iter_func(void *, struct ieee80211_node *);
137static void wpi_power_calibration(struct wpi_softc *, int);
138static void wpi_rx_intr(struct wpi_softc *, struct wpi_rx_desc *,
139	struct wpi_rx_data *);
140static void wpi_tx_intr(struct wpi_softc *, struct wpi_rx_desc *);
141static void wpi_cmd_intr(struct wpi_softc *, struct wpi_rx_desc *);
142static void wpi_notif_intr(struct wpi_softc *);
143static int  wpi_intr(void *);
144static void wpi_read_eeprom(struct wpi_softc *);
145static void wpi_read_eeprom_channels(struct wpi_softc *, int);
146static void wpi_read_eeprom_group(struct wpi_softc *, int);
147static uint8_t wpi_plcp_signal(int);
148static int  wpi_tx_data(struct wpi_softc *, struct mbuf *,
149	struct ieee80211_node *, int);
150static void wpi_start(struct ifnet *);
151static void wpi_watchdog(struct ifnet *);
152static int  wpi_ioctl(struct ifnet *, u_long, void *);
153static int  wpi_cmd(struct wpi_softc *, int, const void *, int, int);
154static int  wpi_wme_update(struct ieee80211com *);
155static int  wpi_mrr_setup(struct wpi_softc *);
156static void wpi_set_led(struct wpi_softc *, uint8_t, uint8_t, uint8_t);
157static void wpi_enable_tsf(struct wpi_softc *, struct ieee80211_node *);
158static int  wpi_set_txpower(struct wpi_softc *,
159			    struct ieee80211_channel *, int);
160static int  wpi_get_power_index(struct wpi_softc *,
161		struct wpi_power_group *, struct ieee80211_channel *, int);
162static int  wpi_setup_beacon(struct wpi_softc *, struct ieee80211_node *);
163static int  wpi_auth(struct wpi_softc *);
164static int  wpi_scan(struct wpi_softc *, uint16_t);
165static int  wpi_config(struct wpi_softc *);
166static void wpi_stop_master(struct wpi_softc *);
167static int  wpi_power_up(struct wpi_softc *);
168static int  wpi_reset(struct wpi_softc *);
169static void wpi_hw_config(struct wpi_softc *);
170static int  wpi_init(struct ifnet *);
171static void wpi_stop(struct ifnet *, int);
172static bool wpi_resume(device_t, const pmf_qual_t *);
173static int	wpi_getrfkill(struct wpi_softc *);
174static void wpi_sysctlattach(struct wpi_softc *);
175
176CFATTACH_DECL_NEW(wpi, sizeof (struct wpi_softc), wpi_match, wpi_attach,
177	wpi_detach, NULL);
178
179static int
180wpi_match(device_t parent, cfdata_t match __unused, void *aux)
181{
182	struct pci_attach_args *pa = aux;
183
184	if (PCI_VENDOR(pa->pa_id) != PCI_VENDOR_INTEL)
185		return 0;
186
187	if (PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_INTEL_PRO_WL_3945ABG_1 ||
188	    PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_INTEL_PRO_WL_3945ABG_2)
189		return 1;
190
191	return 0;
192}
193
194/* Base Address Register */
195#define WPI_PCI_BAR0	0x10
196
197static int
198wpi_attach_once(void)
199{
200	mutex_init(&wpi_firmware_mutex, MUTEX_DEFAULT, IPL_NONE);
201	return 0;
202}
203
204static void
205wpi_attach(device_t parent __unused, device_t self, void *aux)
206{
207	struct wpi_softc *sc = device_private(self);
208	struct ieee80211com *ic = &sc->sc_ic;
209	struct ifnet *ifp = &sc->sc_ec.ec_if;
210	struct pci_attach_args *pa = aux;
211	const char *intrstr;
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;
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_aprint_devinfo(pa, NULL);
229
230	/* enable bus-mastering */
231	data = pci_conf_read(sc->sc_pct, sc->sc_pcitag, PCI_COMMAND_STATUS_REG);
232	data |= PCI_COMMAND_MASTER_ENABLE;
233	pci_conf_write(sc->sc_pct, sc->sc_pcitag, PCI_COMMAND_STATUS_REG, data);
234
235	/* map the register window */
236	error = pci_mapreg_map(pa, WPI_PCI_BAR0, PCI_MAPREG_TYPE_MEM |
237		PCI_MAPREG_MEM_TYPE_32BIT, 0, &memt, &memh, NULL, &sc->sc_sz);
238	if (error != 0) {
239		aprint_error_dev(self, "could not map memory space\n");
240		return;
241	}
242
243	sc->sc_st = memt;
244	sc->sc_sh = memh;
245	sc->sc_dmat = pa->pa_dmat;
246
247	if (pci_intr_map(pa, &ih) != 0) {
248		aprint_error_dev(self, "could not map interrupt\n");
249		return;
250	}
251
252	intrstr = pci_intr_string(sc->sc_pct, ih);
253	sc->sc_ih = pci_intr_establish(sc->sc_pct, ih, IPL_NET, wpi_intr, sc);
254	if (sc->sc_ih == NULL) {
255		aprint_error_dev(self, "could not establish interrupt");
256		if (intrstr != NULL)
257			aprint_error(" at %s", intrstr);
258		aprint_error("\n");
259		return;
260	}
261	aprint_normal_dev(self, "interrupting at %s\n", intrstr);
262
263	if (wpi_reset(sc) != 0) {
264		aprint_error_dev(self, "could not reset adapter\n");
265		return;
266	}
267
268 	/*
269	 * Allocate DMA memory for firmware transfers.
270	 */
271	if ((error = wpi_alloc_fwmem(sc)) != 0)
272		return;
273
274	/*
275	 * Allocate shared page and Tx/Rx rings.
276	 */
277	if ((error = wpi_alloc_shared(sc)) != 0) {
278		aprint_error_dev(self, "could not allocate shared area\n");
279		goto fail1;
280	}
281
282	if ((error = wpi_alloc_rpool(sc)) != 0) {
283		aprint_error_dev(self, "could not allocate Rx buffers\n");
284		goto fail2;
285	}
286
287	for (ac = 0; ac < 4; ac++) {
288		error = wpi_alloc_tx_ring(sc, &sc->txq[ac], WPI_TX_RING_COUNT, ac);
289		if (error != 0) {
290			aprint_error_dev(self, "could not allocate Tx ring %d\n", ac);
291			goto fail3;
292		}
293	}
294
295	error = wpi_alloc_tx_ring(sc, &sc->cmdq, WPI_CMD_RING_COUNT, 4);
296	if (error != 0) {
297		aprint_error_dev(self, "could not allocate command ring\n");
298		goto fail3;
299	}
300
301	if (wpi_alloc_rx_ring(sc, &sc->rxq) != 0) {
302		aprint_error_dev(self, "could not allocate Rx ring\n");
303		goto fail4;
304	}
305
306	ic->ic_ifp = ifp;
307	ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
308	ic->ic_opmode = IEEE80211_M_STA; /* default to BSS mode */
309	ic->ic_state = IEEE80211_S_INIT;
310
311	/* set device capabilities */
312	ic->ic_caps =
313#ifdef netyet
314		IEEE80211_C_IBSS |       /* IBSS mode support */
315#endif
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
381fail4:  wpi_free_tx_ring(sc, &sc->cmdq);
382fail3:  while (--ac >= 0)
383			wpi_free_tx_ring(sc, &sc->txq[ac]);
384	wpi_free_rpool(sc);
385fail2:	wpi_free_shared(sc);
386fail1:	wpi_free_fwmem(sc);
387}
388
389static int
390wpi_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
428static int
429wpi_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
462fail:   wpi_dma_contig_free(dma);
463	return error;
464}
465
466static void
467wpi_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 */
484static int
485wpi_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
499static void
500wpi_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 */
508static int
509wpi_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
524static void
525wpi_free_fwmem(struct wpi_softc *sc)
526{
527	wpi_dma_contig_free(&sc->fw_dma);
528}
529
530
531static struct wpi_rbuf *
532wpi_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 */
551static void
552wpi_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
569static int
570wpi_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
601static void
602wpi_free_rpool(struct wpi_softc *sc)
603{
604	wpi_dma_contig_free(&sc->rxq.buf_dma);
605}
606
607static int
608wpi_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
654fail:	wpi_free_rx_ring(sc, ring);
655	return error;
656}
657
658static void
659wpi_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
680static void
681wpi_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
693static int
694wpi_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
747fail:	wpi_free_tx_ring(sc, ring);
748	return error;
749}
750
751static void
752wpi_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
787static void
788wpi_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*/
810static struct ieee80211_node *
811wpi_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
820static void
821wpi_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
835static int
836wpi_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
850static int
851wpi_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 */
968static void
969wpi_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 */
1004static void
1005wpi_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 */
1027static void
1028wpi_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
1034static uint32_t
1035wpi_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
1041static void
1042wpi_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
1048static void
1049wpi_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 */
1061static int
1062wpi_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 */
1095int
1096wpi_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
1133static int
1134wpi_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 fail0;
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
1191fail2:
1192	firmware_free(wpi_firmware_image, wpi_firmware_size);
1193fail1:
1194	firmware_close(fw);
1195fail0:
1196	wpi_firmware_users--;
1197	KASSERT(wpi_firmware_users == 0);
1198	mutex_exit(&wpi_firmware_mutex);
1199	return error;
1200}
1201
1202static int
1203wpi_load_firmware(struct wpi_softc *sc)
1204{
1205	struct wpi_dma_info *dma = &sc->fw_dma;
1206	struct wpi_firmware_hdr hdr;
1207	const uint8_t *init_text, *init_data, *main_text, *main_data;
1208	const uint8_t *boot_text;
1209	uint32_t init_textsz, init_datasz, main_textsz, main_datasz;
1210	uint32_t boot_textsz;
1211	int error;
1212
1213	if ((error = wpi_cache_firmware(sc)) != 0)
1214		return error;
1215
1216	memcpy(&hdr, wpi_firmware_image, sizeof(hdr));
1217
1218	main_textsz = le32toh(hdr.main_textsz);
1219	main_datasz = le32toh(hdr.main_datasz);
1220	init_textsz = le32toh(hdr.init_textsz);
1221	init_datasz = le32toh(hdr.init_datasz);
1222	boot_textsz = le32toh(hdr.boot_textsz);
1223
1224	/* sanity-check firmware segments sizes */
1225	if (main_textsz > WPI_FW_MAIN_TEXT_MAXSZ ||
1226	    main_datasz > WPI_FW_MAIN_DATA_MAXSZ ||
1227	    init_textsz > WPI_FW_INIT_TEXT_MAXSZ ||
1228	    init_datasz > WPI_FW_INIT_DATA_MAXSZ ||
1229	    boot_textsz > WPI_FW_BOOT_TEXT_MAXSZ ||
1230	    (boot_textsz & 3) != 0) {
1231		aprint_error_dev(sc->sc_dev, "invalid firmware header\n");
1232		error = EINVAL;
1233		goto free_firmware;
1234	}
1235
1236	/* check that all firmware segments are present */
1237	if (wpi_firmware_size <
1238	    sizeof (struct wpi_firmware_hdr) + main_textsz +
1239	    main_datasz + init_textsz + init_datasz + boot_textsz) {
1240		aprint_error_dev(sc->sc_dev,
1241		    "firmware file too short: %zu bytes\n", wpi_firmware_size);
1242		error = EINVAL;
1243		goto free_firmware;
1244	}
1245
1246	/* get pointers to firmware segments */
1247	main_text = wpi_firmware_image + sizeof (struct wpi_firmware_hdr);
1248	main_data = main_text + main_textsz;
1249	init_text = main_data + main_datasz;
1250	init_data = init_text + init_textsz;
1251	boot_text = init_data + init_datasz;
1252
1253	/* copy initialization images into pre-allocated DMA-safe memory */
1254	memcpy(dma->vaddr, init_data, init_datasz);
1255	memcpy((char*)dma->vaddr + WPI_FW_INIT_DATA_MAXSZ, init_text, init_textsz);
1256
1257	/* tell adapter where to find initialization images */
1258	wpi_mem_lock(sc);
1259	wpi_mem_write(sc, WPI_MEM_DATA_BASE, dma->paddr);
1260	wpi_mem_write(sc, WPI_MEM_DATA_SIZE, init_datasz);
1261	wpi_mem_write(sc, WPI_MEM_TEXT_BASE,
1262	    dma->paddr + WPI_FW_INIT_DATA_MAXSZ);
1263	wpi_mem_write(sc, WPI_MEM_TEXT_SIZE, init_textsz);
1264	wpi_mem_unlock(sc);
1265
1266	/* load firmware boot code */
1267	if ((error = wpi_load_microcode(sc, boot_text, boot_textsz)) != 0) {
1268		aprint_error_dev(sc->sc_dev, "could not load boot firmware\n");
1269		return error;
1270	}
1271
1272	/* now press "execute" ;-) */
1273	WPI_WRITE(sc, WPI_RESET, 0);
1274
1275	/* ..and wait at most one second for adapter to initialize */
1276	if ((error = tsleep(sc, PCATCH, "wpiinit", hz)) != 0) {
1277		/* this isn't what was supposed to happen.. */
1278		aprint_error_dev(sc->sc_dev,
1279		    "timeout waiting for adapter to initialize\n");
1280	}
1281
1282	/* copy runtime images into pre-allocated DMA-safe memory */
1283	memcpy(dma->vaddr, main_data, main_datasz);
1284	memcpy((char*)dma->vaddr + WPI_FW_MAIN_DATA_MAXSZ, main_text, main_textsz);
1285
1286	/* tell adapter where to find runtime images */
1287	wpi_mem_lock(sc);
1288	wpi_mem_write(sc, WPI_MEM_DATA_BASE, dma->paddr);
1289	wpi_mem_write(sc, WPI_MEM_DATA_SIZE, main_datasz);
1290	wpi_mem_write(sc, WPI_MEM_TEXT_BASE,
1291	    dma->paddr + WPI_FW_MAIN_DATA_MAXSZ);
1292	wpi_mem_write(sc, WPI_MEM_TEXT_SIZE, WPI_FW_UPDATED | main_textsz);
1293	wpi_mem_unlock(sc);
1294
1295	/* wait at most one second for second alive notification */
1296	if ((error = tsleep(sc, PCATCH, "wpiinit", hz)) != 0) {
1297		/* this isn't what was supposed to happen.. */
1298		aprint_error_dev(sc->sc_dev,
1299		    "timeout waiting for adapter to initialize\n");
1300	}
1301
1302	return error;
1303
1304free_firmware:
1305	mutex_enter(&wpi_firmware_mutex);
1306	sc->fw_used = false;
1307	--wpi_firmware_users;
1308	mutex_exit(&wpi_firmware_mutex);
1309	return error;
1310}
1311
1312static void
1313wpi_calib_timeout(void *arg)
1314{
1315	struct wpi_softc *sc = arg;
1316	struct ieee80211com *ic = &sc->sc_ic;
1317	int temp, s;
1318
1319	/* automatic rate control triggered every 500ms */
1320	if (ic->ic_fixed_rate == -1) {
1321		s = splnet();
1322		if (ic->ic_opmode == IEEE80211_M_STA)
1323			wpi_iter_func(sc, ic->ic_bss);
1324		else
1325                	ieee80211_iterate_nodes(&ic->ic_sta, wpi_iter_func, sc);
1326		splx(s);
1327	}
1328
1329	/* update sensor data */
1330	temp = (int)WPI_READ(sc, WPI_TEMPERATURE);
1331
1332	/* automatic power calibration every 60s */
1333	if (++sc->calib_cnt >= 120) {
1334		wpi_power_calibration(sc, temp);
1335		sc->calib_cnt = 0;
1336	}
1337
1338	callout_schedule(&sc->calib_to, hz/2);
1339}
1340
1341static void
1342wpi_iter_func(void *arg, struct ieee80211_node *ni)
1343{
1344	struct wpi_softc *sc = arg;
1345	struct wpi_node *wn = (struct wpi_node *)ni;
1346
1347	ieee80211_amrr_choose(&sc->amrr, ni, &wn->amn);
1348}
1349
1350/*
1351 * This function is called periodically (every 60 seconds) to adjust output
1352 * power to temperature changes.
1353 */
1354void
1355wpi_power_calibration(struct wpi_softc *sc, int temp)
1356{
1357	/* sanity-check read value */
1358	if (temp < -260 || temp > 25) {
1359		/* this can't be correct, ignore */
1360		DPRINTF(("out-of-range temperature reported: %d\n", temp));
1361		return;
1362	}
1363
1364	DPRINTF(("temperature %d->%d\n", sc->temp, temp));
1365
1366	/* adjust Tx power if need be */
1367	if (abs(temp - sc->temp) <= 6)
1368		return;
1369
1370	sc->temp = temp;
1371
1372	if (wpi_set_txpower(sc, sc->sc_ic.ic_bss->ni_chan, 1) != 0) {
1373		/* just warn, too bad for the automatic calibration... */
1374		aprint_error_dev(sc->sc_dev, "could not adjust Tx power\n");
1375	}
1376}
1377
1378static void
1379wpi_rx_intr(struct wpi_softc *sc, struct wpi_rx_desc *desc,
1380	struct wpi_rx_data *data)
1381{
1382	struct ieee80211com *ic = &sc->sc_ic;
1383	struct ifnet *ifp = ic->ic_ifp;
1384	struct wpi_rx_ring *ring = &sc->rxq;
1385	struct wpi_rx_stat *stat;
1386	struct wpi_rx_head *head;
1387	struct wpi_rx_tail *tail;
1388	struct wpi_rbuf *rbuf;
1389	struct ieee80211_frame *wh;
1390	struct ieee80211_node *ni;
1391	struct mbuf *m, *mnew;
1392	int data_off ;
1393
1394	stat = (struct wpi_rx_stat *)(desc + 1);
1395
1396	if (stat->len > WPI_STAT_MAXLEN) {
1397		aprint_error_dev(sc->sc_dev, "invalid rx statistic header\n");
1398		ifp->if_ierrors++;
1399		return;
1400	}
1401
1402	head = (struct wpi_rx_head *)((char *)(stat + 1) + stat->len);
1403	tail = (struct wpi_rx_tail *)((char *)(head + 1) + le16toh(head->len));
1404
1405	DPRINTFN(4, ("rx intr: idx=%d len=%d stat len=%d rssi=%d rate=%x "
1406		"chan=%d tstamp=%" PRId64 "\n", ring->cur, le32toh(desc->len),
1407		le16toh(head->len), (int8_t)stat->rssi, head->rate, head->chan,
1408		le64toh(tail->tstamp)));
1409
1410	/*
1411	 * Discard Rx frames with bad CRC early (XXX we may want to pass them
1412	 * to radiotap in monitor mode).
1413	 */
1414	if ((le32toh(tail->flags) & WPI_RX_NOERROR) != WPI_RX_NOERROR) {
1415		DPRINTF(("rx tail flags error %x\n", le32toh(tail->flags)));
1416		ifp->if_ierrors++;
1417		return;
1418	}
1419
1420	/* Compute where are the useful datas */
1421	data_off = (char*)(head + 1) - mtod(data->m, char*);
1422
1423	/*
1424	 * If the number of free entry is too low
1425	 * just dup the data->m socket and reuse the same rbuf entry
1426	 * Note that thi test is not protected by a mutex because the
1427	 * only path that causes nb_free_entries to decrease is through
1428	 * this interrupt routine, which is not re-entrent.
1429	 * What may not be obvious is that the safe path is if that test
1430	 * evaluates as true, so nb_free_entries can grow any time.
1431	 */
1432	if (sc->rxq.nb_free_entries <= WPI_RBUF_LOW_LIMIT) {
1433
1434		/* Prepare the mbuf for the m_dup */
1435		data->m->m_pkthdr.len = data->m->m_len = le16toh(head->len);
1436		data->m->m_data = (char*) data->m->m_data + data_off;
1437
1438		m = m_dup(data->m,0,M_COPYALL,M_DONTWAIT);
1439
1440		/* Restore the m_data pointer for future use */
1441		data->m->m_data = (char*) data->m->m_data - data_off;
1442
1443		if (m == NULL) {
1444			ifp->if_ierrors++;
1445			return;
1446		}
1447	} else {
1448
1449		MGETHDR(mnew, M_DONTWAIT, MT_DATA);
1450		if (mnew == NULL) {
1451			ifp->if_ierrors++;
1452			return;
1453		}
1454
1455		rbuf = wpi_alloc_rbuf(sc);
1456		KASSERT(rbuf != NULL);
1457
1458 		/* attach Rx buffer to mbuf */
1459		MEXTADD(mnew, rbuf->vaddr, WPI_RBUF_SIZE, 0, wpi_free_rbuf,
1460		 	rbuf);
1461		mnew->m_flags |= M_EXT_RW;
1462
1463		m = data->m;
1464		data->m = mnew;
1465
1466		/* update Rx descriptor */
1467		ring->desc[ring->cur] = htole32(rbuf->paddr);
1468
1469		m->m_data = (char*)m->m_data + data_off;
1470		m->m_pkthdr.len = m->m_len = le16toh(head->len);
1471	}
1472
1473	/* finalize mbuf */
1474	m->m_pkthdr.rcvif = ifp;
1475
1476	if (ic->ic_state == IEEE80211_S_SCAN)
1477		wpi_fix_channel(ic, m);
1478
1479	if (sc->sc_drvbpf != NULL) {
1480		struct wpi_rx_radiotap_header *tap = &sc->sc_rxtap;
1481
1482		tap->wr_flags = 0;
1483		tap->wr_chan_freq =
1484			htole16(ic->ic_channels[head->chan].ic_freq);
1485		tap->wr_chan_flags =
1486			htole16(ic->ic_channels[head->chan].ic_flags);
1487		tap->wr_dbm_antsignal = (int8_t)(stat->rssi - WPI_RSSI_OFFSET);
1488		tap->wr_dbm_antnoise = (int8_t)le16toh(stat->noise);
1489		tap->wr_tsft = tail->tstamp;
1490		tap->wr_antenna = (le16toh(head->flags) >> 4) & 0xf;
1491		switch (head->rate) {
1492		/* CCK rates */
1493		case  10: tap->wr_rate =   2; break;
1494		case  20: tap->wr_rate =   4; break;
1495		case  55: tap->wr_rate =  11; break;
1496		case 110: tap->wr_rate =  22; break;
1497		/* OFDM rates */
1498		case 0xd: tap->wr_rate =  12; break;
1499		case 0xf: tap->wr_rate =  18; break;
1500		case 0x5: tap->wr_rate =  24; break;
1501		case 0x7: tap->wr_rate =  36; break;
1502		case 0x9: tap->wr_rate =  48; break;
1503		case 0xb: tap->wr_rate =  72; break;
1504		case 0x1: tap->wr_rate =  96; break;
1505		case 0x3: tap->wr_rate = 108; break;
1506		/* unknown rate: should not happen */
1507		default:  tap->wr_rate =   0;
1508		}
1509		if (le16toh(head->flags) & 0x4)
1510			tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
1511
1512		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_rxtap_len, m);
1513	}
1514
1515	/* grab a reference to the source node */
1516	wh = mtod(m, struct ieee80211_frame *);
1517	ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
1518
1519	/* send the frame to the 802.11 layer */
1520	ieee80211_input(ic, m, ni, stat->rssi, 0);
1521
1522	/* release node reference */
1523	ieee80211_free_node(ni);
1524}
1525
1526static void
1527wpi_tx_intr(struct wpi_softc *sc, struct wpi_rx_desc *desc)
1528{
1529	struct ifnet *ifp = sc->sc_ic.ic_ifp;
1530	struct wpi_tx_ring *ring = &sc->txq[desc->qid & 0x3];
1531	struct wpi_tx_data *txdata = &ring->data[desc->idx];
1532	struct wpi_tx_stat *stat = (struct wpi_tx_stat *)(desc + 1);
1533	struct wpi_node *wn = (struct wpi_node *)txdata->ni;
1534
1535	DPRINTFN(4, ("tx done: qid=%d idx=%d retries=%d nkill=%d rate=%x "
1536		"duration=%d status=%x\n", desc->qid, desc->idx, stat->ntries,
1537		stat->nkill, stat->rate, le32toh(stat->duration),
1538		le32toh(stat->status)));
1539
1540	/*
1541	 * Update rate control statistics for the node.
1542	 * XXX we should not count mgmt frames since they're always sent at
1543	 * the lowest available bit-rate.
1544	 */
1545	wn->amn.amn_txcnt++;
1546	if (stat->ntries > 0) {
1547		DPRINTFN(3, ("tx intr ntries %d\n", stat->ntries));
1548		wn->amn.amn_retrycnt++;
1549	}
1550
1551	if ((le32toh(stat->status) & 0xff) != 1)
1552		ifp->if_oerrors++;
1553	else
1554		ifp->if_opackets++;
1555
1556	bus_dmamap_unload(sc->sc_dmat, txdata->map);
1557	m_freem(txdata->m);
1558	txdata->m = NULL;
1559	ieee80211_free_node(txdata->ni);
1560	txdata->ni = NULL;
1561
1562	ring->queued--;
1563
1564	sc->sc_tx_timer = 0;
1565	ifp->if_flags &= ~IFF_OACTIVE;
1566	wpi_start(ifp);
1567}
1568
1569static void
1570wpi_cmd_intr(struct wpi_softc *sc, struct wpi_rx_desc *desc)
1571{
1572	struct wpi_tx_ring *ring = &sc->cmdq;
1573	struct wpi_tx_data *data;
1574
1575	if ((desc->qid & 7) != 4)
1576		return;	/* not a command ack */
1577
1578	data = &ring->data[desc->idx];
1579
1580	/* if the command was mapped in a mbuf, free it */
1581	if (data->m != NULL) {
1582		bus_dmamap_unload(sc->sc_dmat, data->map);
1583		m_freem(data->m);
1584		data->m = NULL;
1585	}
1586
1587	wakeup(&ring->cmd[desc->idx]);
1588}
1589
1590static void
1591wpi_notif_intr(struct wpi_softc *sc)
1592{
1593	struct ieee80211com *ic = &sc->sc_ic;
1594	struct ifnet *ifp =  ic->ic_ifp;
1595	struct wpi_rx_desc *desc;
1596	struct wpi_rx_data *data;
1597	uint32_t hw;
1598
1599	hw = le32toh(sc->shared->next);
1600	while (sc->rxq.cur != hw) {
1601		data = &sc->rxq.data[sc->rxq.cur];
1602
1603		desc = mtod(data->m, struct wpi_rx_desc *);
1604
1605		DPRINTFN(4, ("rx notification qid=%x idx=%d flags=%x type=%d "
1606			"len=%d\n", desc->qid, desc->idx, desc->flags,
1607			desc->type, le32toh(desc->len)));
1608
1609		if (!(desc->qid & 0x80))	/* reply to a command */
1610			wpi_cmd_intr(sc, desc);
1611
1612		switch (desc->type) {
1613		case WPI_RX_DONE:
1614			/* a 802.11 frame was received */
1615			wpi_rx_intr(sc, desc, data);
1616			break;
1617
1618		case WPI_TX_DONE:
1619			/* a 802.11 frame has been transmitted */
1620			wpi_tx_intr(sc, desc);
1621			break;
1622
1623		case WPI_UC_READY:
1624		{
1625			struct wpi_ucode_info *uc =
1626				(struct wpi_ucode_info *)(desc + 1);
1627
1628			/* the microcontroller is ready */
1629			DPRINTF(("microcode alive notification version %x "
1630				"alive %x\n", le32toh(uc->version),
1631				le32toh(uc->valid)));
1632
1633			if (le32toh(uc->valid) != 1) {
1634				aprint_error_dev(sc->sc_dev,
1635					"microcontroller initialization failed\n");
1636			}
1637			break;
1638		}
1639		case WPI_STATE_CHANGED:
1640		{
1641			uint32_t *status = (uint32_t *)(desc + 1);
1642
1643			/* enabled/disabled notification */
1644			DPRINTF(("state changed to %x\n", le32toh(*status)));
1645
1646			if (le32toh(*status) & 1) {
1647				/* the radio button has to be pushed */
1648				aprint_error_dev(sc->sc_dev, "Radio transmitter is off\n");
1649				/* turn the interface down */
1650				ifp->if_flags &= ~IFF_UP;
1651				wpi_stop(ifp, 1);
1652				return;	/* no further processing */
1653			}
1654			break;
1655		}
1656		case WPI_START_SCAN:
1657		{
1658			struct wpi_start_scan *scan =
1659				(struct wpi_start_scan *)(desc + 1);
1660
1661			DPRINTFN(2, ("scanning channel %d status %x\n",
1662				scan->chan, le32toh(scan->status)));
1663
1664			/* fix current channel */
1665			ic->ic_bss->ni_chan = &ic->ic_channels[scan->chan];
1666			break;
1667		}
1668		case WPI_STOP_SCAN:
1669		{
1670			struct wpi_stop_scan *scan =
1671				(struct wpi_stop_scan *)(desc + 1);
1672
1673			DPRINTF(("scan finished nchan=%d status=%d chan=%d\n",
1674				scan->nchan, scan->status, scan->chan));
1675
1676			if (scan->status == 1 && scan->chan <= 14) {
1677				/*
1678				 * We just finished scanning 802.11g channels,
1679				 * start scanning 802.11a ones.
1680				 */
1681				if (wpi_scan(sc, IEEE80211_CHAN_A) == 0)
1682					break;
1683			}
1684			sc->is_scanning = false;
1685			ieee80211_end_scan(ic);
1686			break;
1687		}
1688		}
1689
1690		sc->rxq.cur = (sc->rxq.cur + 1) % WPI_RX_RING_COUNT;
1691	}
1692
1693	/* tell the firmware what we have processed */
1694	hw = (hw == 0) ? WPI_RX_RING_COUNT - 1 : hw - 1;
1695	WPI_WRITE(sc, WPI_RX_WIDX, hw & ~7);
1696}
1697
1698static int
1699wpi_intr(void *arg)
1700{
1701	struct wpi_softc *sc = arg;
1702	struct ifnet *ifp = sc->sc_ic.ic_ifp;
1703	uint32_t r;
1704
1705	r = WPI_READ(sc, WPI_INTR);
1706	if (r == 0 || r == 0xffffffff)
1707		return 0;	/* not for us */
1708
1709	DPRINTFN(5, ("interrupt reg %x\n", r));
1710
1711	/* disable interrupts */
1712	WPI_WRITE(sc, WPI_MASK, 0);
1713	/* ack interrupts */
1714	WPI_WRITE(sc, WPI_INTR, r);
1715
1716	if (r & (WPI_SW_ERROR | WPI_HW_ERROR)) {
1717		aprint_error_dev(sc->sc_dev, "fatal firmware error\n");
1718		sc->sc_ic.ic_ifp->if_flags &= ~IFF_UP;
1719		wpi_stop(sc->sc_ic.ic_ifp, 1);
1720		return 1;
1721	}
1722
1723	if (r & WPI_RX_INTR)
1724		wpi_notif_intr(sc);
1725
1726	if (r & WPI_ALIVE_INTR)	/* firmware initialized */
1727		wakeup(sc);
1728
1729	/* re-enable interrupts */
1730	if (ifp->if_flags & IFF_UP)
1731		WPI_WRITE(sc, WPI_MASK, WPI_INTR_MASK);
1732
1733	return 1;
1734}
1735
1736static uint8_t
1737wpi_plcp_signal(int rate)
1738{
1739	switch (rate) {
1740	/* CCK rates (returned values are device-dependent) */
1741	case 2:		return 10;
1742	case 4:		return 20;
1743	case 11:	return 55;
1744	case 22:	return 110;
1745
1746	/* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
1747	/* R1-R4, (u)ral is R4-R1 */
1748	case 12:	return 0xd;
1749	case 18:	return 0xf;
1750	case 24:	return 0x5;
1751	case 36:	return 0x7;
1752	case 48:	return 0x9;
1753	case 72:	return 0xb;
1754	case 96:	return 0x1;
1755	case 108:	return 0x3;
1756
1757	/* unsupported rates (should not get there) */
1758	default:	return 0;
1759	}
1760}
1761
1762/* quickly determine if a given rate is CCK or OFDM */
1763#define WPI_RATE_IS_OFDM(rate) ((rate) >= 12 && (rate) != 22)
1764
1765static int
1766wpi_tx_data(struct wpi_softc *sc, struct mbuf *m0, struct ieee80211_node *ni,
1767	int ac)
1768{
1769	struct ieee80211com *ic = &sc->sc_ic;
1770	struct wpi_tx_ring *ring = &sc->txq[ac];
1771	struct wpi_tx_desc *desc;
1772	struct wpi_tx_data *data;
1773	struct wpi_tx_cmd *cmd;
1774	struct wpi_cmd_data *tx;
1775	struct ieee80211_frame *wh;
1776	struct ieee80211_key *k;
1777	const struct chanAccParams *cap;
1778	struct mbuf *mnew;
1779	int i, error, rate, hdrlen, noack = 0;
1780
1781	desc = &ring->desc[ring->cur];
1782	data = &ring->data[ring->cur];
1783
1784	wh = mtod(m0, struct ieee80211_frame *);
1785
1786	if (IEEE80211_QOS_HAS_SEQ(wh)) {
1787		cap = &ic->ic_wme.wme_chanParams;
1788		noack = cap->cap_wmeParams[ac].wmep_noackPolicy;
1789	}
1790
1791	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1792		k = ieee80211_crypto_encap(ic, ni, m0);
1793		if (k == NULL) {
1794			m_freem(m0);
1795			return ENOBUFS;
1796		}
1797
1798		/* packet header may have moved, reset our local pointer */
1799		wh = mtod(m0, struct ieee80211_frame *);
1800	}
1801
1802	hdrlen = ieee80211_anyhdrsize(wh);
1803
1804	/* pickup a rate */
1805	if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
1806		IEEE80211_FC0_TYPE_MGT) {
1807		/* mgmt frames are sent at the lowest available bit-rate */
1808		rate = ni->ni_rates.rs_rates[0];
1809	} else {
1810		if (ic->ic_fixed_rate != -1) {
1811			rate = ic->ic_sup_rates[ic->ic_curmode].
1812				rs_rates[ic->ic_fixed_rate];
1813		} else
1814			rate = ni->ni_rates.rs_rates[ni->ni_txrate];
1815	}
1816	rate &= IEEE80211_RATE_VAL;
1817
1818
1819	if (sc->sc_drvbpf != NULL) {
1820		struct wpi_tx_radiotap_header *tap = &sc->sc_txtap;
1821
1822		tap->wt_flags = 0;
1823		tap->wt_chan_freq = htole16(ni->ni_chan->ic_freq);
1824		tap->wt_chan_flags = htole16(ni->ni_chan->ic_flags);
1825		tap->wt_rate = rate;
1826		tap->wt_hwqueue = ac;
1827		if (wh->i_fc[1] & IEEE80211_FC1_WEP)
1828			tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
1829
1830		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m0);
1831	}
1832
1833	cmd = &ring->cmd[ring->cur];
1834	cmd->code = WPI_CMD_TX_DATA;
1835	cmd->flags = 0;
1836	cmd->qid = ring->qid;
1837	cmd->idx = ring->cur;
1838
1839	tx = (struct wpi_cmd_data *)cmd->data;
1840	tx->flags = 0;
1841
1842	if (!noack && !IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1843		tx->flags |= htole32(WPI_TX_NEED_ACK);
1844	} else if (m0->m_pkthdr.len + IEEE80211_CRC_LEN > ic->ic_rtsthreshold)
1845		tx->flags |= htole32(WPI_TX_NEED_RTS | WPI_TX_FULL_TXOP);
1846
1847	tx->flags |= htole32(WPI_TX_AUTO_SEQ);
1848
1849	/* retrieve destination node's id */
1850	tx->id = IEEE80211_IS_MULTICAST(wh->i_addr1) ? WPI_ID_BROADCAST :
1851		WPI_ID_BSS;
1852
1853	if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
1854		IEEE80211_FC0_TYPE_MGT) {
1855		/* tell h/w to set timestamp in probe responses */
1856		if ((wh->i_fc[0] &
1857		    (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
1858		    (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP))
1859			tx->flags |= htole32(WPI_TX_INSERT_TSTAMP);
1860
1861		if (((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
1862			 IEEE80211_FC0_SUBTYPE_ASSOC_REQ) ||
1863			((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
1864			 IEEE80211_FC0_SUBTYPE_REASSOC_REQ))
1865			tx->timeout = htole16(3);
1866		else
1867			tx->timeout = htole16(2);
1868	} else
1869		tx->timeout = htole16(0);
1870
1871	tx->rate = wpi_plcp_signal(rate);
1872
1873	/* be very persistant at sending frames out */
1874	tx->rts_ntries = 7;
1875	tx->data_ntries = 15;
1876
1877	tx->ofdm_mask = 0xff;
1878	tx->cck_mask = 0xf;
1879	tx->lifetime = htole32(WPI_LIFETIME_INFINITE);
1880
1881	tx->len = htole16(m0->m_pkthdr.len);
1882
1883	/* save and trim IEEE802.11 header */
1884	memcpy((uint8_t *)(tx + 1), wh, hdrlen);
1885	m_adj(m0, hdrlen);
1886
1887	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
1888		BUS_DMA_WRITE | BUS_DMA_NOWAIT);
1889	if (error != 0 && error != EFBIG) {
1890		aprint_error_dev(sc->sc_dev, "could not map mbuf (error %d)\n", error);
1891		m_freem(m0);
1892		return error;
1893	}
1894	if (error != 0) {
1895		/* too many fragments, linearize */
1896		MGETHDR(mnew, M_DONTWAIT, MT_DATA);
1897		if (mnew == NULL) {
1898			m_freem(m0);
1899			return ENOMEM;
1900		}
1901
1902		M_COPY_PKTHDR(mnew, m0);
1903		if (m0->m_pkthdr.len > MHLEN) {
1904			MCLGET(mnew, M_DONTWAIT);
1905			if (!(mnew->m_flags & M_EXT)) {
1906				m_freem(m0);
1907				m_freem(mnew);
1908				return ENOMEM;
1909			}
1910		}
1911
1912		m_copydata(m0, 0, m0->m_pkthdr.len, mtod(mnew, void *));
1913		m_freem(m0);
1914		mnew->m_len = mnew->m_pkthdr.len;
1915		m0 = mnew;
1916
1917		error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
1918			BUS_DMA_WRITE | BUS_DMA_NOWAIT);
1919		if (error != 0) {
1920			aprint_error_dev(sc->sc_dev, "could not map mbuf (error %d)\n",
1921							 error);
1922			m_freem(m0);
1923			return error;
1924		}
1925	}
1926
1927	data->m = m0;
1928	data->ni = ni;
1929
1930	DPRINTFN(4, ("sending data: qid=%d idx=%d len=%d nsegs=%d\n",
1931		ring->qid, ring->cur, m0->m_pkthdr.len, data->map->dm_nsegs));
1932
1933	/* first scatter/gather segment is used by the tx data command */
1934	desc->flags = htole32(WPI_PAD32(m0->m_pkthdr.len) << 28 |
1935		(1 + data->map->dm_nsegs) << 24);
1936	desc->segs[0].addr = htole32(ring->cmd_dma.paddr +
1937		ring->cur * sizeof (struct wpi_tx_cmd));
1938	desc->segs[0].len  = htole32(4 + sizeof (struct wpi_cmd_data) +
1939						 ((hdrlen + 3) & ~3));
1940
1941	for (i = 1; i <= data->map->dm_nsegs; i++) {
1942		desc->segs[i].addr =
1943			htole32(data->map->dm_segs[i - 1].ds_addr);
1944		desc->segs[i].len  =
1945			htole32(data->map->dm_segs[i - 1].ds_len);
1946	}
1947
1948	ring->queued++;
1949
1950	/* kick ring */
1951	ring->cur = (ring->cur + 1) % WPI_TX_RING_COUNT;
1952	WPI_WRITE(sc, WPI_TX_WIDX, ring->qid << 8 | ring->cur);
1953
1954	return 0;
1955}
1956
1957static void
1958wpi_start(struct ifnet *ifp)
1959{
1960	struct wpi_softc *sc = ifp->if_softc;
1961	struct ieee80211com *ic = &sc->sc_ic;
1962	struct ieee80211_node *ni;
1963	struct ether_header *eh;
1964	struct mbuf *m0;
1965	int ac;
1966
1967	/*
1968	 * net80211 may still try to send management frames even if the
1969	 * IFF_RUNNING flag is not set...
1970	 */
1971	if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
1972		return;
1973
1974	for (;;) {
1975		IF_DEQUEUE(&ic->ic_mgtq, m0);
1976		if (m0 != NULL) {
1977
1978			ni = (struct ieee80211_node *)m0->m_pkthdr.rcvif;
1979			m0->m_pkthdr.rcvif = NULL;
1980
1981			/* management frames go into ring 0 */
1982			if (sc->txq[0].queued > sc->txq[0].count - 8) {
1983				ifp->if_oerrors++;
1984				continue;
1985			}
1986			bpf_mtap3(ic->ic_rawbpf, m0);
1987			if (wpi_tx_data(sc, m0, ni, 0) != 0) {
1988				ifp->if_oerrors++;
1989				break;
1990			}
1991		} else {
1992			if (ic->ic_state != IEEE80211_S_RUN)
1993				break;
1994			IFQ_POLL(&ifp->if_snd, m0);
1995			if (m0 == NULL)
1996				break;
1997
1998			if (m0->m_len < sizeof (*eh) &&
1999			    (m0 = m_pullup(m0, sizeof (*eh))) == NULL) {
2000				ifp->if_oerrors++;
2001				continue;
2002			}
2003			eh = mtod(m0, struct ether_header *);
2004			ni = ieee80211_find_txnode(ic, eh->ether_dhost);
2005			if (ni == NULL) {
2006				m_freem(m0);
2007				ifp->if_oerrors++;
2008				continue;
2009			}
2010
2011			/* classify mbuf so we can find which tx ring to use */
2012			if (ieee80211_classify(ic, m0, ni) != 0) {
2013				m_freem(m0);
2014				ieee80211_free_node(ni);
2015				ifp->if_oerrors++;
2016				continue;
2017			}
2018
2019			/* no QoS encapsulation for EAPOL frames */
2020			ac = (eh->ether_type != htons(ETHERTYPE_PAE)) ?
2021			    M_WME_GETAC(m0) : WME_AC_BE;
2022
2023			if (sc->txq[ac].queued > sc->txq[ac].count - 8) {
2024				/* there is no place left in this ring */
2025				ifp->if_flags |= IFF_OACTIVE;
2026				break;
2027			}
2028			IFQ_DEQUEUE(&ifp->if_snd, m0);
2029			bpf_mtap(ifp, m0);
2030			m0 = ieee80211_encap(ic, m0, ni);
2031			if (m0 == NULL) {
2032				ieee80211_free_node(ni);
2033				ifp->if_oerrors++;
2034				continue;
2035			}
2036			bpf_mtap3(ic->ic_rawbpf, m0);
2037			if (wpi_tx_data(sc, m0, ni, ac) != 0) {
2038				ieee80211_free_node(ni);
2039				ifp->if_oerrors++;
2040				break;
2041			}
2042		}
2043
2044		sc->sc_tx_timer = 5;
2045		ifp->if_timer = 1;
2046	}
2047}
2048
2049static void
2050wpi_watchdog(struct ifnet *ifp)
2051{
2052	struct wpi_softc *sc = ifp->if_softc;
2053
2054	ifp->if_timer = 0;
2055
2056	if (sc->sc_tx_timer > 0) {
2057		if (--sc->sc_tx_timer == 0) {
2058			aprint_error_dev(sc->sc_dev, "device timeout\n");
2059			ifp->if_oerrors++;
2060			ifp->if_flags &= ~IFF_UP;
2061			wpi_stop(ifp, 1);
2062			return;
2063		}
2064		ifp->if_timer = 1;
2065	}
2066
2067	ieee80211_watchdog(&sc->sc_ic);
2068}
2069
2070static int
2071wpi_ioctl(struct ifnet *ifp, u_long cmd, void *data)
2072{
2073#define IS_RUNNING(ifp) \
2074	((ifp->if_flags & IFF_UP) && (ifp->if_flags & IFF_RUNNING))
2075
2076	struct wpi_softc *sc = ifp->if_softc;
2077	struct ieee80211com *ic = &sc->sc_ic;
2078	int s, error = 0;
2079
2080	s = splnet();
2081
2082	switch (cmd) {
2083	case SIOCSIFFLAGS:
2084		if ((error = ifioctl_common(ifp, cmd, data)) != 0)
2085			break;
2086		if (ifp->if_flags & IFF_UP) {
2087			if (!(ifp->if_flags & IFF_RUNNING))
2088				wpi_init(ifp);
2089		} else {
2090			if (ifp->if_flags & IFF_RUNNING)
2091				wpi_stop(ifp, 1);
2092		}
2093		break;
2094
2095	case SIOCADDMULTI:
2096	case SIOCDELMULTI:
2097		/* XXX no h/w multicast filter? --dyoung */
2098		if ((error = ether_ioctl(ifp, cmd, data)) == ENETRESET) {
2099			/* setup multicast filter, etc */
2100			error = 0;
2101		}
2102		break;
2103
2104	default:
2105		error = ieee80211_ioctl(ic, cmd, data);
2106	}
2107
2108	if (error == ENETRESET) {
2109		if (IS_RUNNING(ifp) &&
2110			(ic->ic_roaming != IEEE80211_ROAMING_MANUAL))
2111			wpi_init(ifp);
2112		error = 0;
2113	}
2114
2115	splx(s);
2116	return error;
2117
2118#undef IS_RUNNING
2119}
2120
2121/*
2122 * Extract various information from EEPROM.
2123 */
2124static void
2125wpi_read_eeprom(struct wpi_softc *sc)
2126{
2127	struct ieee80211com *ic = &sc->sc_ic;
2128	char domain[4];
2129	int i;
2130
2131	wpi_read_prom_data(sc, WPI_EEPROM_CAPABILITIES, &sc->cap, 1);
2132	wpi_read_prom_data(sc, WPI_EEPROM_REVISION, &sc->rev, 2);
2133	wpi_read_prom_data(sc, WPI_EEPROM_TYPE, &sc->type, 1);
2134
2135	DPRINTF(("cap=%x rev=%x type=%x\n", sc->cap, le16toh(sc->rev),
2136	    sc->type));
2137
2138	/* read and print regulatory domain */
2139	wpi_read_prom_data(sc, WPI_EEPROM_DOMAIN, domain, 4);
2140	aprint_normal_dev(sc->sc_dev, "%.4s", domain);
2141
2142	/* read and print MAC address */
2143	wpi_read_prom_data(sc, WPI_EEPROM_MAC, ic->ic_myaddr, 6);
2144	aprint_normal(", address %s\n", ether_sprintf(ic->ic_myaddr));
2145
2146	/* read the list of authorized channels */
2147	for (i = 0; i < WPI_CHAN_BANDS_COUNT; i++)
2148		wpi_read_eeprom_channels(sc, i);
2149
2150	/* read the list of power groups */
2151	for (i = 0; i < WPI_POWER_GROUPS_COUNT; i++)
2152		wpi_read_eeprom_group(sc, i);
2153}
2154
2155static void
2156wpi_read_eeprom_channels(struct wpi_softc *sc, int n)
2157{
2158	struct ieee80211com *ic = &sc->sc_ic;
2159	const struct wpi_chan_band *band = &wpi_bands[n];
2160	struct wpi_eeprom_chan channels[WPI_MAX_CHAN_PER_BAND];
2161	int chan, i;
2162
2163	wpi_read_prom_data(sc, band->addr, channels,
2164	    band->nchan * sizeof (struct wpi_eeprom_chan));
2165
2166	for (i = 0; i < band->nchan; i++) {
2167		if (!(channels[i].flags & WPI_EEPROM_CHAN_VALID))
2168			continue;
2169
2170		chan = band->chan[i];
2171
2172		if (n == 0) {	/* 2GHz band */
2173			ic->ic_channels[chan].ic_freq =
2174			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_2GHZ);
2175			ic->ic_channels[chan].ic_flags =
2176			    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
2177			    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
2178
2179		} else {	/* 5GHz band */
2180			/*
2181			 * Some 3945abg adapters support channels 7, 8, 11
2182			 * and 12 in the 2GHz *and* 5GHz bands.
2183			 * Because of limitations in our net80211(9) stack,
2184			 * we can't support these channels in 5GHz band.
2185			 */
2186			if (chan <= 14)
2187				continue;
2188
2189			ic->ic_channels[chan].ic_freq =
2190			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_5GHZ);
2191			ic->ic_channels[chan].ic_flags = IEEE80211_CHAN_A;
2192		}
2193
2194		/* is active scan allowed on this channel? */
2195		if (!(channels[i].flags & WPI_EEPROM_CHAN_ACTIVE)) {
2196			ic->ic_channels[chan].ic_flags |=
2197			    IEEE80211_CHAN_PASSIVE;
2198		}
2199
2200		/* save maximum allowed power for this channel */
2201		sc->maxpwr[chan] = channels[i].maxpwr;
2202
2203		DPRINTF(("adding chan %d flags=0x%x maxpwr=%d\n",
2204		    chan, channels[i].flags, sc->maxpwr[chan]));
2205	}
2206}
2207
2208static void
2209wpi_read_eeprom_group(struct wpi_softc *sc, int n)
2210{
2211	struct wpi_power_group *group = &sc->groups[n];
2212	struct wpi_eeprom_group rgroup;
2213	int i;
2214
2215	wpi_read_prom_data(sc, WPI_EEPROM_POWER_GRP + n * 32, &rgroup,
2216	    sizeof rgroup);
2217
2218	/* save power group information */
2219	group->chan   = rgroup.chan;
2220	group->maxpwr = rgroup.maxpwr;
2221	/* temperature at which the samples were taken */
2222	group->temp   = (int16_t)le16toh(rgroup.temp);
2223
2224	DPRINTF(("power group %d: chan=%d maxpwr=%d temp=%d\n", n,
2225	    group->chan, group->maxpwr, group->temp));
2226
2227	for (i = 0; i < WPI_SAMPLES_COUNT; i++) {
2228		group->samples[i].index = rgroup.samples[i].index;
2229		group->samples[i].power = rgroup.samples[i].power;
2230
2231		DPRINTF(("\tsample %d: index=%d power=%d\n", i,
2232		    group->samples[i].index, group->samples[i].power));
2233	}
2234}
2235
2236/*
2237 * Send a command to the firmware.
2238 */
2239static int
2240wpi_cmd(struct wpi_softc *sc, int code, const void *buf, int size, int async)
2241{
2242	struct wpi_tx_ring *ring = &sc->cmdq;
2243	struct wpi_tx_desc *desc;
2244	struct wpi_tx_cmd *cmd;
2245
2246	KASSERT(size <= sizeof cmd->data);
2247
2248	desc = &ring->desc[ring->cur];
2249	cmd = &ring->cmd[ring->cur];
2250
2251	cmd->code = code;
2252	cmd->flags = 0;
2253	cmd->qid = ring->qid;
2254	cmd->idx = ring->cur;
2255	memcpy(cmd->data, buf, size);
2256
2257	desc->flags = htole32(WPI_PAD32(size) << 28 | 1 << 24);
2258	desc->segs[0].addr = htole32(ring->cmd_dma.paddr +
2259		ring->cur * sizeof (struct wpi_tx_cmd));
2260	desc->segs[0].len  = htole32(4 + size);
2261
2262	/* kick cmd ring */
2263	ring->cur = (ring->cur + 1) % WPI_CMD_RING_COUNT;
2264	WPI_WRITE(sc, WPI_TX_WIDX, ring->qid << 8 | ring->cur);
2265
2266	return async ? 0 : tsleep(cmd, PCATCH, "wpicmd", hz);
2267}
2268
2269static int
2270wpi_wme_update(struct ieee80211com *ic)
2271{
2272#define WPI_EXP2(v)	htole16((1 << (v)) - 1)
2273#define WPI_USEC(v)	htole16(IEEE80211_TXOP_TO_US(v))
2274	struct wpi_softc *sc = ic->ic_ifp->if_softc;
2275	const struct wmeParams *wmep;
2276	struct wpi_wme_setup wme;
2277	int ac;
2278
2279	/* don't override default WME values if WME is not actually enabled */
2280	if (!(ic->ic_flags & IEEE80211_F_WME))
2281		return 0;
2282
2283	wme.flags = 0;
2284	for (ac = 0; ac < WME_NUM_AC; ac++) {
2285		wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
2286		wme.ac[ac].aifsn = wmep->wmep_aifsn;
2287		wme.ac[ac].cwmin = WPI_EXP2(wmep->wmep_logcwmin);
2288		wme.ac[ac].cwmax = WPI_EXP2(wmep->wmep_logcwmax);
2289		wme.ac[ac].txop  = WPI_USEC(wmep->wmep_txopLimit);
2290
2291		DPRINTF(("setting WME for queue %d aifsn=%d cwmin=%d cwmax=%d "
2292		    "txop=%d\n", ac, wme.ac[ac].aifsn, wme.ac[ac].cwmin,
2293		    wme.ac[ac].cwmax, wme.ac[ac].txop));
2294	}
2295
2296	return wpi_cmd(sc, WPI_CMD_SET_WME, &wme, sizeof wme, 1);
2297#undef WPI_USEC
2298#undef WPI_EXP2
2299}
2300
2301/*
2302 * Configure h/w multi-rate retries.
2303 */
2304static int
2305wpi_mrr_setup(struct wpi_softc *sc)
2306{
2307	struct ieee80211com *ic = &sc->sc_ic;
2308	struct wpi_mrr_setup mrr;
2309	int i, error;
2310
2311	/* CCK rates (not used with 802.11a) */
2312	for (i = WPI_CCK1; i <= WPI_CCK11; i++) {
2313		mrr.rates[i].flags = 0;
2314		mrr.rates[i].plcp = wpi_ridx_to_plcp[i];
2315		/* fallback to the immediate lower CCK rate (if any) */
2316		mrr.rates[i].next = (i == WPI_CCK1) ? WPI_CCK1 : i - 1;
2317		/* try one time at this rate before falling back to "next" */
2318		mrr.rates[i].ntries = 1;
2319	}
2320
2321	/* OFDM rates (not used with 802.11b) */
2322	for (i = WPI_OFDM6; i <= WPI_OFDM54; i++) {
2323		mrr.rates[i].flags = 0;
2324		mrr.rates[i].plcp = wpi_ridx_to_plcp[i];
2325		/* fallback to the immediate lower rate (if any) */
2326		/* we allow fallback from OFDM/6 to CCK/2 in 11b/g mode */
2327		mrr.rates[i].next = (i == WPI_OFDM6) ?
2328		    ((ic->ic_curmode == IEEE80211_MODE_11A) ?
2329			WPI_OFDM6 : WPI_CCK2) :
2330		    i - 1;
2331		/* try one time at this rate before falling back to "next" */
2332		mrr.rates[i].ntries = 1;
2333	}
2334
2335	/* setup MRR for control frames */
2336	mrr.which = htole32(WPI_MRR_CTL);
2337	error = wpi_cmd(sc, WPI_CMD_MRR_SETUP, &mrr, sizeof mrr, 0);
2338	if (error != 0) {
2339		aprint_error_dev(sc->sc_dev, "could not setup MRR for control frames\n");
2340		return error;
2341	}
2342
2343	/* setup MRR for data frames */
2344	mrr.which = htole32(WPI_MRR_DATA);
2345	error = wpi_cmd(sc, WPI_CMD_MRR_SETUP, &mrr, sizeof mrr, 0);
2346	if (error != 0) {
2347		aprint_error_dev(sc->sc_dev, "could not setup MRR for data frames\n");
2348		return error;
2349	}
2350
2351	return 0;
2352}
2353
2354static void
2355wpi_set_led(struct wpi_softc *sc, uint8_t which, uint8_t off, uint8_t on)
2356{
2357	struct wpi_cmd_led led;
2358
2359	led.which = which;
2360	led.unit = htole32(100000);	/* on/off in unit of 100ms */
2361	led.off = off;
2362	led.on = on;
2363
2364	(void)wpi_cmd(sc, WPI_CMD_SET_LED, &led, sizeof led, 1);
2365}
2366
2367static void
2368wpi_enable_tsf(struct wpi_softc *sc, struct ieee80211_node *ni)
2369{
2370	struct wpi_cmd_tsf tsf;
2371	uint64_t val, mod;
2372
2373	memset(&tsf, 0, sizeof tsf);
2374	memcpy(&tsf.tstamp, ni->ni_tstamp.data, 8);
2375	tsf.bintval = htole16(ni->ni_intval);
2376	tsf.lintval = htole16(10);
2377
2378	/* compute remaining time until next beacon */
2379	val = (uint64_t)ni->ni_intval  * 1024;	/* msecs -> usecs */
2380	mod = le64toh(tsf.tstamp) % val;
2381	tsf.binitval = htole32((uint32_t)(val - mod));
2382
2383	DPRINTF(("TSF bintval=%u tstamp=%" PRId64 ", init=%u\n",
2384	    ni->ni_intval, le64toh(tsf.tstamp), (uint32_t)(val - mod)));
2385
2386	if (wpi_cmd(sc, WPI_CMD_TSF, &tsf, sizeof tsf, 1) != 0)
2387		aprint_error_dev(sc->sc_dev, "could not enable TSF\n");
2388}
2389
2390/*
2391 * Update Tx power to match what is defined for channel `c'.
2392 */
2393static int
2394wpi_set_txpower(struct wpi_softc *sc, struct ieee80211_channel *c, int async)
2395{
2396	struct ieee80211com *ic = &sc->sc_ic;
2397	struct wpi_power_group *group;
2398	struct wpi_cmd_txpower txpower;
2399	u_int chan;
2400	int i;
2401
2402	/* get channel number */
2403	chan = ieee80211_chan2ieee(ic, c);
2404
2405	/* find the power group to which this channel belongs */
2406	if (IEEE80211_IS_CHAN_5GHZ(c)) {
2407		for (group = &sc->groups[1]; group < &sc->groups[4]; group++)
2408			if (chan <= group->chan)
2409				break;
2410	} else
2411		group = &sc->groups[0];
2412
2413	memset(&txpower, 0, sizeof txpower);
2414	txpower.band = IEEE80211_IS_CHAN_5GHZ(c) ? 0 : 1;
2415	txpower.chan = htole16(chan);
2416
2417	/* set Tx power for all OFDM and CCK rates */
2418	for (i = 0; i <= 11 ; i++) {
2419		/* retrieve Tx power for this channel/rate combination */
2420		int idx = wpi_get_power_index(sc, group, c,
2421		    wpi_ridx_to_rate[i]);
2422
2423		txpower.rates[i].plcp = wpi_ridx_to_plcp[i];
2424
2425		if (IEEE80211_IS_CHAN_5GHZ(c)) {
2426			txpower.rates[i].rf_gain = wpi_rf_gain_5ghz[idx];
2427			txpower.rates[i].dsp_gain = wpi_dsp_gain_5ghz[idx];
2428		} else {
2429			txpower.rates[i].rf_gain = wpi_rf_gain_2ghz[idx];
2430			txpower.rates[i].dsp_gain = wpi_dsp_gain_2ghz[idx];
2431		}
2432		DPRINTF(("chan %d/rate %d: power index %d\n", chan,
2433		    wpi_ridx_to_rate[i], idx));
2434	}
2435
2436	return wpi_cmd(sc, WPI_CMD_TXPOWER, &txpower, sizeof txpower, async);
2437}
2438
2439/*
2440 * Determine Tx power index for a given channel/rate combination.
2441 * This takes into account the regulatory information from EEPROM and the
2442 * current temperature.
2443 */
2444static int
2445wpi_get_power_index(struct wpi_softc *sc, struct wpi_power_group *group,
2446    struct ieee80211_channel *c, int rate)
2447{
2448/* fixed-point arithmetic division using a n-bit fractional part */
2449#define fdivround(a, b, n)	\
2450	((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
2451
2452/* linear interpolation */
2453#define interpolate(x, x1, y1, x2, y2, n)	\
2454	((y1) + fdivround(((x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
2455
2456	struct ieee80211com *ic = &sc->sc_ic;
2457	struct wpi_power_sample *sample;
2458	int pwr, idx;
2459	u_int chan;
2460
2461	/* get channel number */
2462	chan = ieee80211_chan2ieee(ic, c);
2463
2464	/* default power is group's maximum power - 3dB */
2465	pwr = group->maxpwr / 2;
2466
2467	/* decrease power for highest OFDM rates to reduce distortion */
2468	switch (rate) {
2469	case 72:	/* 36Mb/s */
2470		pwr -= IEEE80211_IS_CHAN_2GHZ(c) ? 0 :  5;
2471		break;
2472	case 96:	/* 48Mb/s */
2473		pwr -= IEEE80211_IS_CHAN_2GHZ(c) ? 7 : 10;
2474		break;
2475	case 108:	/* 54Mb/s */
2476		pwr -= IEEE80211_IS_CHAN_2GHZ(c) ? 9 : 12;
2477		break;
2478	}
2479
2480	/* never exceed channel's maximum allowed Tx power */
2481	pwr = min(pwr, sc->maxpwr[chan]);
2482
2483	/* retrieve power index into gain tables from samples */
2484	for (sample = group->samples; sample < &group->samples[3]; sample++)
2485		if (pwr > sample[1].power)
2486			break;
2487	/* fixed-point linear interpolation using a 19-bit fractional part */
2488	idx = interpolate(pwr, sample[0].power, sample[0].index,
2489	    sample[1].power, sample[1].index, 19);
2490
2491	/*
2492	 * Adjust power index based on current temperature:
2493	 * - if cooler than factory-calibrated: decrease output power
2494	 * - if warmer than factory-calibrated: increase output power
2495	 */
2496	idx -= (sc->temp - group->temp) * 11 / 100;
2497
2498	/* decrease power for CCK rates (-5dB) */
2499	if (!WPI_RATE_IS_OFDM(rate))
2500		idx += 10;
2501
2502	/* keep power index in a valid range */
2503	if (idx < 0)
2504		return 0;
2505	if (idx > WPI_MAX_PWR_INDEX)
2506		return WPI_MAX_PWR_INDEX;
2507	return idx;
2508
2509#undef interpolate
2510#undef fdivround
2511}
2512
2513/*
2514 * Build a beacon frame that the firmware will broadcast periodically in
2515 * IBSS or HostAP modes.
2516 */
2517static int
2518wpi_setup_beacon(struct wpi_softc *sc, struct ieee80211_node *ni)
2519{
2520	struct ieee80211com *ic = &sc->sc_ic;
2521	struct wpi_tx_ring *ring = &sc->cmdq;
2522	struct wpi_tx_desc *desc;
2523	struct wpi_tx_data *data;
2524	struct wpi_tx_cmd *cmd;
2525	struct wpi_cmd_beacon *bcn;
2526	struct ieee80211_beacon_offsets bo;
2527	struct mbuf *m0;
2528	int error;
2529
2530	desc = &ring->desc[ring->cur];
2531	data = &ring->data[ring->cur];
2532
2533	m0 = ieee80211_beacon_alloc(ic, ni, &bo);
2534	if (m0 == NULL) {
2535		aprint_error_dev(sc->sc_dev, "could not allocate beacon frame\n");
2536		return ENOMEM;
2537	}
2538
2539	cmd = &ring->cmd[ring->cur];
2540	cmd->code = WPI_CMD_SET_BEACON;
2541	cmd->flags = 0;
2542	cmd->qid = ring->qid;
2543	cmd->idx = ring->cur;
2544
2545	bcn = (struct wpi_cmd_beacon *)cmd->data;
2546	memset(bcn, 0, sizeof (struct wpi_cmd_beacon));
2547	bcn->id = WPI_ID_BROADCAST;
2548	bcn->ofdm_mask = 0xff;
2549	bcn->cck_mask = 0x0f;
2550	bcn->lifetime = htole32(WPI_LIFETIME_INFINITE);
2551	bcn->len = htole16(m0->m_pkthdr.len);
2552	bcn->rate = (ic->ic_curmode == IEEE80211_MODE_11A) ?
2553		wpi_plcp_signal(12) : wpi_plcp_signal(2);
2554	bcn->flags = htole32(WPI_TX_AUTO_SEQ | WPI_TX_INSERT_TSTAMP);
2555
2556	/* save and trim IEEE802.11 header */
2557	m_copydata(m0, 0, sizeof (struct ieee80211_frame), (void *)&bcn->wh);
2558	m_adj(m0, sizeof (struct ieee80211_frame));
2559
2560	/* assume beacon frame is contiguous */
2561	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
2562		BUS_DMA_READ | BUS_DMA_NOWAIT);
2563	if (error) {
2564		aprint_error_dev(sc->sc_dev, "could not map beacon\n");
2565		m_freem(m0);
2566		return error;
2567	}
2568
2569	data->m = m0;
2570
2571	/* first scatter/gather segment is used by the beacon command */
2572	desc->flags = htole32(WPI_PAD32(m0->m_pkthdr.len) << 28 | 2 << 24);
2573	desc->segs[0].addr = htole32(ring->cmd_dma.paddr +
2574		ring->cur * sizeof (struct wpi_tx_cmd));
2575	desc->segs[0].len  = htole32(4 + sizeof (struct wpi_cmd_beacon));
2576	desc->segs[1].addr = htole32(data->map->dm_segs[0].ds_addr);
2577	desc->segs[1].len  = htole32(data->map->dm_segs[0].ds_len);
2578
2579	/* kick cmd ring */
2580	ring->cur = (ring->cur + 1) % WPI_CMD_RING_COUNT;
2581	WPI_WRITE(sc, WPI_TX_WIDX, ring->qid << 8 | ring->cur);
2582
2583	return 0;
2584}
2585
2586static int
2587wpi_auth(struct wpi_softc *sc)
2588{
2589	struct ieee80211com *ic = &sc->sc_ic;
2590	struct ieee80211_node *ni = ic->ic_bss;
2591	struct wpi_node_info node;
2592	int error;
2593
2594	/* update adapter's configuration */
2595	IEEE80211_ADDR_COPY(sc->config.bssid, ni->ni_bssid);
2596	sc->config.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
2597	sc->config.flags = htole32(WPI_CONFIG_TSF);
2598	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) {
2599		sc->config.flags |= htole32(WPI_CONFIG_AUTO |
2600		    WPI_CONFIG_24GHZ);
2601	}
2602	switch (ic->ic_curmode) {
2603	case IEEE80211_MODE_11A:
2604		sc->config.cck_mask  = 0;
2605		sc->config.ofdm_mask = 0x15;
2606		break;
2607	case IEEE80211_MODE_11B:
2608		sc->config.cck_mask  = 0x03;
2609		sc->config.ofdm_mask = 0;
2610		break;
2611	default:	/* assume 802.11b/g */
2612		sc->config.cck_mask  = 0x0f;
2613		sc->config.ofdm_mask = 0x15;
2614	}
2615
2616	DPRINTF(("config chan %d flags %x cck %x ofdm %x\n", sc->config.chan,
2617		sc->config.flags, sc->config.cck_mask, sc->config.ofdm_mask));
2618	error = wpi_cmd(sc, WPI_CMD_CONFIGURE, &sc->config,
2619		sizeof (struct wpi_config), 1);
2620	if (error != 0) {
2621		aprint_error_dev(sc->sc_dev, "could not configure\n");
2622		return error;
2623	}
2624
2625	/* configuration has changed, set Tx power accordingly */
2626	if ((error = wpi_set_txpower(sc, ni->ni_chan, 1)) != 0) {
2627		aprint_error_dev(sc->sc_dev, "could not set Tx power\n");
2628		return error;
2629	}
2630
2631	/* add default node */
2632	memset(&node, 0, sizeof node);
2633	IEEE80211_ADDR_COPY(node.bssid, ni->ni_bssid);
2634	node.id = WPI_ID_BSS;
2635	node.rate = (ic->ic_curmode == IEEE80211_MODE_11A) ?
2636	    wpi_plcp_signal(12) : wpi_plcp_signal(2);
2637	node.action = htole32(WPI_ACTION_SET_RATE);
2638	node.antenna = WPI_ANTENNA_BOTH;
2639	error = wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, 1);
2640	if (error != 0) {
2641		aprint_error_dev(sc->sc_dev, "could not add BSS node\n");
2642		return error;
2643	}
2644
2645	return 0;
2646}
2647
2648/*
2649 * Send a scan request to the firmware.  Since this command is huge, we map it
2650 * into a mbuf instead of using the pre-allocated set of commands.
2651 */
2652static int
2653wpi_scan(struct wpi_softc *sc, uint16_t flags)
2654{
2655	struct ieee80211com *ic = &sc->sc_ic;
2656	struct wpi_tx_ring *ring = &sc->cmdq;
2657	struct wpi_tx_desc *desc;
2658	struct wpi_tx_data *data;
2659	struct wpi_tx_cmd *cmd;
2660	struct wpi_scan_hdr *hdr;
2661	struct wpi_scan_chan *chan;
2662	struct ieee80211_frame *wh;
2663	struct ieee80211_rateset *rs;
2664	struct ieee80211_channel *c;
2665	enum ieee80211_phymode mode;
2666	uint8_t *frm;
2667	int nrates, pktlen, error;
2668
2669	desc = &ring->desc[ring->cur];
2670	data = &ring->data[ring->cur];
2671
2672	MGETHDR(data->m, M_DONTWAIT, MT_DATA);
2673	if (data->m == NULL) {
2674		aprint_error_dev(sc->sc_dev,
2675						"could not allocate mbuf for scan command\n");
2676		return ENOMEM;
2677	}
2678
2679	MCLGET(data->m, M_DONTWAIT);
2680	if (!(data->m->m_flags & M_EXT)) {
2681		m_freem(data->m);
2682		data->m = NULL;
2683		aprint_error_dev(sc->sc_dev,
2684						 "could not allocate mbuf for scan command\n");
2685		return ENOMEM;
2686	}
2687
2688	cmd = mtod(data->m, struct wpi_tx_cmd *);
2689	cmd->code = WPI_CMD_SCAN;
2690	cmd->flags = 0;
2691	cmd->qid = ring->qid;
2692	cmd->idx = ring->cur;
2693
2694	hdr = (struct wpi_scan_hdr *)cmd->data;
2695	memset(hdr, 0, sizeof (struct wpi_scan_hdr));
2696	hdr->txflags = htole32(WPI_TX_AUTO_SEQ);
2697	hdr->id = WPI_ID_BROADCAST;
2698	hdr->lifetime = htole32(WPI_LIFETIME_INFINITE);
2699
2700	/*
2701	 * Move to the next channel if no packets are received within 5 msecs
2702	 * after sending the probe request (this helps to reduce the duration
2703	 * of active scans).
2704	 */
2705	hdr->quiet = htole16(5);        /* timeout in milliseconds */
2706	hdr->plcp_threshold = htole16(1);	/* min # of packets */
2707
2708	if (flags & IEEE80211_CHAN_A) {
2709		hdr->crc_threshold = htole16(1);
2710		/* send probe requests at 6Mbps */
2711		hdr->rate = wpi_plcp_signal(12);
2712	} else {
2713		hdr->flags = htole32(WPI_CONFIG_24GHZ | WPI_CONFIG_AUTO);
2714		/* send probe requests at 1Mbps */
2715		hdr->rate = wpi_plcp_signal(2);
2716	}
2717
2718	/* for directed scans, firmware inserts the essid IE itself */
2719	hdr->essid[0].id  = IEEE80211_ELEMID_SSID;
2720	hdr->essid[0].len = ic->ic_des_esslen;
2721	memcpy(hdr->essid[0].data, ic->ic_des_essid, ic->ic_des_esslen);
2722
2723	/*
2724	 * Build a probe request frame.  Most of the following code is a
2725	 * copy & paste of what is done in net80211.
2726	 */
2727	wh = (struct ieee80211_frame *)(hdr + 1);
2728	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
2729		IEEE80211_FC0_SUBTYPE_PROBE_REQ;
2730	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
2731	IEEE80211_ADDR_COPY(wh->i_addr1, etherbroadcastaddr);
2732	IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
2733	IEEE80211_ADDR_COPY(wh->i_addr3, etherbroadcastaddr);
2734	*(u_int16_t *)&wh->i_dur[0] = 0;	/* filled by h/w */
2735	*(u_int16_t *)&wh->i_seq[0] = 0;	/* filled by h/w */
2736
2737	frm = (uint8_t *)(wh + 1);
2738
2739	/* add empty essid IE (firmware generates it for directed scans) */
2740	*frm++ = IEEE80211_ELEMID_SSID;
2741	*frm++ = 0;
2742
2743	mode = ieee80211_chan2mode(ic, ic->ic_ibss_chan);
2744	rs = &ic->ic_sup_rates[mode];
2745
2746	/* add supported rates IE */
2747	*frm++ = IEEE80211_ELEMID_RATES;
2748	nrates = rs->rs_nrates;
2749	if (nrates > IEEE80211_RATE_SIZE)
2750		nrates = IEEE80211_RATE_SIZE;
2751	*frm++ = nrates;
2752	memcpy(frm, rs->rs_rates, nrates);
2753	frm += nrates;
2754
2755	/* add supported xrates IE */
2756	if (rs->rs_nrates > IEEE80211_RATE_SIZE) {
2757		nrates = rs->rs_nrates - IEEE80211_RATE_SIZE;
2758		*frm++ = IEEE80211_ELEMID_XRATES;
2759		*frm++ = nrates;
2760		memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates);
2761		frm += nrates;
2762	}
2763
2764	/* setup length of probe request */
2765	hdr->paylen = htole16(frm - (uint8_t *)wh);
2766
2767	chan = (struct wpi_scan_chan *)frm;
2768	for (c  = &ic->ic_channels[1];
2769	     c <= &ic->ic_channels[IEEE80211_CHAN_MAX]; c++) {
2770		if ((c->ic_flags & flags) != flags)
2771			continue;
2772
2773		chan->chan = ieee80211_chan2ieee(ic, c);
2774		chan->flags = 0;
2775		if (!(c->ic_flags & IEEE80211_CHAN_PASSIVE)) {
2776			chan->flags |= WPI_CHAN_ACTIVE;
2777			if (ic->ic_des_esslen != 0)
2778				chan->flags |= WPI_CHAN_DIRECT;
2779		}
2780		chan->dsp_gain = 0x6e;
2781		if (IEEE80211_IS_CHAN_5GHZ(c)) {
2782			chan->rf_gain = 0x3b;
2783			chan->active = htole16(10);
2784			chan->passive = htole16(110);
2785		} else {
2786			chan->rf_gain = 0x28;
2787			chan->active = htole16(20);
2788			chan->passive = htole16(120);
2789		}
2790		hdr->nchan++;
2791		chan++;
2792
2793		frm += sizeof (struct wpi_scan_chan);
2794	}
2795	hdr->len = htole16(frm - (uint8_t *)hdr);
2796	pktlen = frm - (uint8_t *)cmd;
2797
2798	error = bus_dmamap_load(sc->sc_dmat, data->map, cmd, pktlen,
2799		NULL, BUS_DMA_NOWAIT);
2800	if (error) {
2801		aprint_error_dev(sc->sc_dev, "could not map scan command\n");
2802		m_freem(data->m);
2803		data->m = NULL;
2804		return error;
2805	}
2806
2807	desc->flags = htole32(WPI_PAD32(pktlen) << 28 | 1 << 24);
2808	desc->segs[0].addr = htole32(data->map->dm_segs[0].ds_addr);
2809	desc->segs[0].len  = htole32(data->map->dm_segs[0].ds_len);
2810
2811	/* kick cmd ring */
2812	ring->cur = (ring->cur + 1) % WPI_CMD_RING_COUNT;
2813	WPI_WRITE(sc, WPI_TX_WIDX, ring->qid << 8 | ring->cur);
2814
2815	return 0;	/* will be notified async. of failure/success */
2816}
2817
2818static int
2819wpi_config(struct wpi_softc *sc)
2820{
2821	struct ieee80211com *ic = &sc->sc_ic;
2822	struct ifnet *ifp = ic->ic_ifp;
2823	struct wpi_power power;
2824	struct wpi_bluetooth bluetooth;
2825	struct wpi_node_info node;
2826	int error;
2827
2828	memset(&power, 0, sizeof power);
2829	power.flags = htole32(WPI_POWER_CAM | 0x8);
2830	error = wpi_cmd(sc, WPI_CMD_SET_POWER_MODE, &power, sizeof power, 0);
2831	if (error != 0) {
2832		aprint_error_dev(sc->sc_dev, "could not set power mode\n");
2833		return error;
2834	}
2835
2836	/* configure bluetooth coexistence */
2837	memset(&bluetooth, 0, sizeof bluetooth);
2838	bluetooth.flags = 3;
2839	bluetooth.lead = 0xaa;
2840	bluetooth.kill = 1;
2841	error = wpi_cmd(sc, WPI_CMD_BLUETOOTH, &bluetooth, sizeof bluetooth,
2842		0);
2843	if (error != 0) {
2844		aprint_error_dev(sc->sc_dev,
2845			"could not configure bluetooth coexistence\n");
2846		return error;
2847	}
2848
2849	/* configure adapter */
2850	memset(&sc->config, 0, sizeof (struct wpi_config));
2851	IEEE80211_ADDR_COPY(ic->ic_myaddr, CLLADDR(ifp->if_sadl));
2852	IEEE80211_ADDR_COPY(sc->config.myaddr, ic->ic_myaddr);
2853	/*set default channel*/
2854	sc->config.chan = ieee80211_chan2ieee(ic, ic->ic_ibss_chan);
2855	sc->config.flags = htole32(WPI_CONFIG_TSF);
2856	if (IEEE80211_IS_CHAN_2GHZ(ic->ic_ibss_chan)) {
2857		sc->config.flags |= htole32(WPI_CONFIG_AUTO |
2858		    WPI_CONFIG_24GHZ);
2859	}
2860	sc->config.filter = 0;
2861	switch (ic->ic_opmode) {
2862	case IEEE80211_M_STA:
2863		sc->config.mode = WPI_MODE_STA;
2864		sc->config.filter |= htole32(WPI_FILTER_MULTICAST);
2865		break;
2866	case IEEE80211_M_IBSS:
2867	case IEEE80211_M_AHDEMO:
2868		sc->config.mode = WPI_MODE_IBSS;
2869		break;
2870	case IEEE80211_M_HOSTAP:
2871		sc->config.mode = WPI_MODE_HOSTAP;
2872		break;
2873	case IEEE80211_M_MONITOR:
2874		sc->config.mode = WPI_MODE_MONITOR;
2875		sc->config.filter |= htole32(WPI_FILTER_MULTICAST |
2876			WPI_FILTER_CTL | WPI_FILTER_PROMISC);
2877		break;
2878	}
2879	sc->config.cck_mask  = 0x0f;	/* not yet negotiated */
2880	sc->config.ofdm_mask = 0xff;	/* not yet negotiated */
2881	error = wpi_cmd(sc, WPI_CMD_CONFIGURE, &sc->config,
2882		sizeof (struct wpi_config), 0);
2883	if (error != 0) {
2884		aprint_error_dev(sc->sc_dev, "configure command failed\n");
2885		return error;
2886	}
2887
2888	/* configuration has changed, set Tx power accordingly */
2889	if ((error = wpi_set_txpower(sc, ic->ic_ibss_chan, 0)) != 0) {
2890		aprint_error_dev(sc->sc_dev, "could not set Tx power\n");
2891		return error;
2892	}
2893
2894	/* add broadcast node */
2895	memset(&node, 0, sizeof node);
2896	IEEE80211_ADDR_COPY(node.bssid, etherbroadcastaddr);
2897	node.id = WPI_ID_BROADCAST;
2898	node.rate = wpi_plcp_signal(2);
2899	node.action = htole32(WPI_ACTION_SET_RATE);
2900	node.antenna = WPI_ANTENNA_BOTH;
2901	error = wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, 0);
2902	if (error != 0) {
2903		aprint_error_dev(sc->sc_dev, "could not add broadcast node\n");
2904		return error;
2905	}
2906
2907	if ((error = wpi_mrr_setup(sc)) != 0) {
2908		aprint_error_dev(sc->sc_dev, "could not setup MRR\n");
2909		return error;
2910	}
2911
2912	return 0;
2913}
2914
2915static void
2916wpi_stop_master(struct wpi_softc *sc)
2917{
2918	uint32_t tmp;
2919	int ntries;
2920
2921	tmp = WPI_READ(sc, WPI_RESET);
2922	WPI_WRITE(sc, WPI_RESET, tmp | WPI_STOP_MASTER);
2923
2924	tmp = WPI_READ(sc, WPI_GPIO_CTL);
2925	if ((tmp & WPI_GPIO_PWR_STATUS) == WPI_GPIO_PWR_SLEEP)
2926		return;	/* already asleep */
2927
2928	for (ntries = 0; ntries < 100; ntries++) {
2929		if (WPI_READ(sc, WPI_RESET) & WPI_MASTER_DISABLED)
2930			break;
2931		DELAY(10);
2932	}
2933	if (ntries == 100) {
2934		aprint_error_dev(sc->sc_dev, "timeout waiting for master\n");
2935	}
2936}
2937
2938static int
2939wpi_power_up(struct wpi_softc *sc)
2940{
2941	uint32_t tmp;
2942	int ntries;
2943
2944	wpi_mem_lock(sc);
2945	tmp = wpi_mem_read(sc, WPI_MEM_POWER);
2946	wpi_mem_write(sc, WPI_MEM_POWER, tmp & ~0x03000000);
2947	wpi_mem_unlock(sc);
2948
2949	for (ntries = 0; ntries < 5000; ntries++) {
2950		if (WPI_READ(sc, WPI_GPIO_STATUS) & WPI_POWERED)
2951			break;
2952		DELAY(10);
2953	}
2954	if (ntries == 5000) {
2955		aprint_error_dev(sc->sc_dev, "timeout waiting for NIC to power up\n");
2956		return ETIMEDOUT;
2957	}
2958	return 0;
2959}
2960
2961static int
2962wpi_reset(struct wpi_softc *sc)
2963{
2964	uint32_t tmp;
2965	int ntries;
2966
2967	/* clear any pending interrupts */
2968	WPI_WRITE(sc, WPI_INTR, 0xffffffff);
2969
2970	tmp = WPI_READ(sc, WPI_PLL_CTL);
2971	WPI_WRITE(sc, WPI_PLL_CTL, tmp | WPI_PLL_INIT);
2972
2973	tmp = WPI_READ(sc, WPI_CHICKEN);
2974	WPI_WRITE(sc, WPI_CHICKEN, tmp | WPI_CHICKEN_RXNOLOS);
2975
2976	tmp = WPI_READ(sc, WPI_GPIO_CTL);
2977	WPI_WRITE(sc, WPI_GPIO_CTL, tmp | WPI_GPIO_INIT);
2978
2979	/* wait for clock stabilization */
2980	for (ntries = 0; ntries < 1000; ntries++) {
2981		if (WPI_READ(sc, WPI_GPIO_CTL) & WPI_GPIO_CLOCK)
2982			break;
2983		DELAY(10);
2984	}
2985	if (ntries == 1000) {
2986		aprint_error_dev(sc->sc_dev,
2987						 "timeout waiting for clock stabilization\n");
2988		return ETIMEDOUT;
2989	}
2990
2991	/* initialize EEPROM */
2992	tmp = WPI_READ(sc, WPI_EEPROM_STATUS);
2993	if ((tmp & WPI_EEPROM_VERSION) == 0) {
2994		aprint_error_dev(sc->sc_dev, "EEPROM not found\n");
2995		return EIO;
2996	}
2997	WPI_WRITE(sc, WPI_EEPROM_STATUS, tmp & ~WPI_EEPROM_LOCKED);
2998
2999	return 0;
3000}
3001
3002static void
3003wpi_hw_config(struct wpi_softc *sc)
3004{
3005	uint32_t rev, hw;
3006
3007	/* voodoo from the reference driver */
3008	hw = WPI_READ(sc, WPI_HWCONFIG);
3009
3010	rev = pci_conf_read(sc->sc_pct, sc->sc_pcitag, PCI_CLASS_REG);
3011	rev = PCI_REVISION(rev);
3012	if ((rev & 0xc0) == 0x40)
3013		hw |= WPI_HW_ALM_MB;
3014	else if (!(rev & 0x80))
3015		hw |= WPI_HW_ALM_MM;
3016
3017	if (sc->cap == 0x80)
3018		hw |= WPI_HW_SKU_MRC;
3019
3020	hw &= ~WPI_HW_REV_D;
3021	if ((le16toh(sc->rev) & 0xf0) == 0xd0)
3022		hw |= WPI_HW_REV_D;
3023
3024	if (sc->type > 1)
3025		hw |= WPI_HW_TYPE_B;
3026
3027	DPRINTF(("setting h/w config %x\n", hw));
3028	WPI_WRITE(sc, WPI_HWCONFIG, hw);
3029}
3030
3031static int
3032wpi_init(struct ifnet *ifp)
3033{
3034	struct wpi_softc *sc = ifp->if_softc;
3035	struct ieee80211com *ic = &sc->sc_ic;
3036	uint32_t tmp;
3037	int qid, ntries, error;
3038
3039	wpi_stop(ifp,1);
3040	(void)wpi_reset(sc);
3041
3042	wpi_mem_lock(sc);
3043	wpi_mem_write(sc, WPI_MEM_CLOCK1, 0xa00);
3044	DELAY(20);
3045	tmp = wpi_mem_read(sc, WPI_MEM_PCIDEV);
3046	wpi_mem_write(sc, WPI_MEM_PCIDEV, tmp | 0x800);
3047	wpi_mem_unlock(sc);
3048
3049	(void)wpi_power_up(sc);
3050	wpi_hw_config(sc);
3051
3052	/* init Rx ring */
3053	wpi_mem_lock(sc);
3054	WPI_WRITE(sc, WPI_RX_BASE, sc->rxq.desc_dma.paddr);
3055	WPI_WRITE(sc, WPI_RX_RIDX_PTR, sc->shared_dma.paddr +
3056	    offsetof(struct wpi_shared, next));
3057	WPI_WRITE(sc, WPI_RX_WIDX, (WPI_RX_RING_COUNT - 1) & ~7);
3058	WPI_WRITE(sc, WPI_RX_CONFIG, 0xa9601010);
3059	wpi_mem_unlock(sc);
3060
3061	/* init Tx rings */
3062	wpi_mem_lock(sc);
3063	wpi_mem_write(sc, WPI_MEM_MODE, 2); /* bypass mode */
3064	wpi_mem_write(sc, WPI_MEM_RA, 1);   /* enable RA0 */
3065	wpi_mem_write(sc, WPI_MEM_TXCFG, 0x3f); /* enable all 6 Tx rings */
3066	wpi_mem_write(sc, WPI_MEM_BYPASS1, 0x10000);
3067	wpi_mem_write(sc, WPI_MEM_BYPASS2, 0x30002);
3068	wpi_mem_write(sc, WPI_MEM_MAGIC4, 4);
3069	wpi_mem_write(sc, WPI_MEM_MAGIC5, 5);
3070
3071	WPI_WRITE(sc, WPI_TX_BASE_PTR, sc->shared_dma.paddr);
3072	WPI_WRITE(sc, WPI_MSG_CONFIG, 0xffff05a5);
3073
3074	for (qid = 0; qid < 6; qid++) {
3075		WPI_WRITE(sc, WPI_TX_CTL(qid), 0);
3076		WPI_WRITE(sc, WPI_TX_BASE(qid), 0);
3077		WPI_WRITE(sc, WPI_TX_CONFIG(qid), 0x80200008);
3078	}
3079	wpi_mem_unlock(sc);
3080
3081	/* clear "radio off" and "disable command" bits (reversed logic) */
3082	WPI_WRITE(sc, WPI_UCODE_CLR, WPI_RADIO_OFF);
3083	WPI_WRITE(sc, WPI_UCODE_CLR, WPI_DISABLE_CMD);
3084
3085	/* clear any pending interrupts */
3086	WPI_WRITE(sc, WPI_INTR, 0xffffffff);
3087	/* enable interrupts */
3088	WPI_WRITE(sc, WPI_MASK, WPI_INTR_MASK);
3089
3090	/* not sure why/if this is necessary... */
3091	WPI_WRITE(sc, WPI_UCODE_CLR, WPI_RADIO_OFF);
3092	WPI_WRITE(sc, WPI_UCODE_CLR, WPI_RADIO_OFF);
3093
3094	if ((error = wpi_load_firmware(sc)) != 0) {
3095		aprint_error_dev(sc->sc_dev, "could not load firmware\n");
3096		goto fail1;
3097	}
3098
3099	/* Check the status of the radio switch */
3100	if (wpi_getrfkill(sc)) {
3101		aprint_error_dev(sc->sc_dev, "Radio is disabled by hardware switch\n");
3102		error = EBUSY;
3103		goto fail1;
3104	}
3105
3106	/* wait for thermal sensors to calibrate */
3107	for (ntries = 0; ntries < 1000; ntries++) {
3108		if ((sc->temp = (int)WPI_READ(sc, WPI_TEMPERATURE)) != 0)
3109			break;
3110		DELAY(10);
3111	}
3112	if (ntries == 1000) {
3113		aprint_error_dev(sc->sc_dev,
3114						 "timeout waiting for thermal sensors calibration\n");
3115		error = ETIMEDOUT;
3116		goto fail1;
3117	}
3118
3119	DPRINTF(("temperature %d\n", sc->temp));
3120
3121	if ((error = wpi_config(sc)) != 0) {
3122		aprint_error_dev(sc->sc_dev, "could not configure device\n");
3123		goto fail1;
3124	}
3125
3126	ifp->if_flags &= ~IFF_OACTIVE;
3127	ifp->if_flags |= IFF_RUNNING;
3128
3129	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
3130		if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
3131			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
3132	}
3133	else
3134		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
3135
3136	return 0;
3137
3138fail1:	wpi_stop(ifp, 1);
3139	return error;
3140}
3141
3142
3143static void
3144wpi_stop(struct ifnet *ifp, int disable)
3145{
3146	struct wpi_softc *sc = ifp->if_softc;
3147	struct ieee80211com *ic = &sc->sc_ic;
3148	uint32_t tmp;
3149	int ac;
3150
3151	ifp->if_timer = sc->sc_tx_timer = 0;
3152	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
3153
3154	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
3155
3156	/* disable interrupts */
3157	WPI_WRITE(sc, WPI_MASK, 0);
3158	WPI_WRITE(sc, WPI_INTR, WPI_INTR_MASK);
3159	WPI_WRITE(sc, WPI_INTR_STATUS, 0xff);
3160	WPI_WRITE(sc, WPI_INTR_STATUS, 0x00070000);
3161
3162	wpi_mem_lock(sc);
3163	wpi_mem_write(sc, WPI_MEM_MODE, 0);
3164	wpi_mem_unlock(sc);
3165
3166	/* reset all Tx rings */
3167	for (ac = 0; ac < 4; ac++)
3168		wpi_reset_tx_ring(sc, &sc->txq[ac]);
3169	wpi_reset_tx_ring(sc, &sc->cmdq);
3170
3171	/* reset Rx ring */
3172	wpi_reset_rx_ring(sc, &sc->rxq);
3173
3174	wpi_mem_lock(sc);
3175	wpi_mem_write(sc, WPI_MEM_CLOCK2, 0x200);
3176	wpi_mem_unlock(sc);
3177
3178	DELAY(5);
3179
3180	wpi_stop_master(sc);
3181
3182	tmp = WPI_READ(sc, WPI_RESET);
3183	WPI_WRITE(sc, WPI_RESET, tmp | WPI_SW_RESET);
3184}
3185
3186static bool
3187wpi_resume(device_t dv, const pmf_qual_t *qual)
3188{
3189	struct wpi_softc *sc = device_private(dv);
3190
3191	(void)wpi_reset(sc);
3192
3193	return true;
3194}
3195
3196/*
3197 * Return whether or not the radio is enabled in hardware
3198 * (i.e. the rfkill switch is "off").
3199 */
3200static int
3201wpi_getrfkill(struct wpi_softc *sc)
3202{
3203	uint32_t tmp;
3204
3205	wpi_mem_lock(sc);
3206	tmp = wpi_mem_read(sc, WPI_MEM_RFKILL);
3207	wpi_mem_unlock(sc);
3208
3209	return !(tmp & 0x01);
3210}
3211
3212static int
3213wpi_sysctl_radio(SYSCTLFN_ARGS)
3214{
3215	struct sysctlnode node;
3216	struct wpi_softc *sc;
3217	int val, error;
3218
3219	node = *rnode;
3220	sc = (struct wpi_softc *)node.sysctl_data;
3221
3222	val = !wpi_getrfkill(sc);
3223
3224	node.sysctl_data = &val;
3225	error = sysctl_lookup(SYSCTLFN_CALL(&node));
3226
3227	if (error || newp == NULL)
3228		return error;
3229
3230	return 0;
3231}
3232
3233static void
3234wpi_sysctlattach(struct wpi_softc *sc)
3235{
3236	int rc;
3237	const struct sysctlnode *rnode;
3238	const struct sysctlnode *cnode;
3239
3240	struct sysctllog **clog = &sc->sc_sysctllog;
3241
3242	if ((rc = sysctl_createv(clog, 0, NULL, &rnode,
3243	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "hw", NULL,
3244	    NULL, 0, NULL, 0, CTL_HW, CTL_EOL)) != 0)
3245		goto err;
3246
3247	if ((rc = sysctl_createv(clog, 0, &rnode, &rnode,
3248	    CTLFLAG_PERMANENT, CTLTYPE_NODE, device_xname(sc->sc_dev),
3249	    SYSCTL_DESCR("wpi controls and statistics"),
3250	    NULL, 0, NULL, 0, CTL_CREATE, CTL_EOL)) != 0)
3251		goto err;
3252
3253	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
3254	    CTLFLAG_PERMANENT, CTLTYPE_INT, "radio",
3255	    SYSCTL_DESCR("radio transmitter switch state (0=off, 1=on)"),
3256	    wpi_sysctl_radio, 0, (void *)sc, 0, CTL_CREATE, CTL_EOL)) != 0)
3257		goto err;
3258
3259#ifdef WPI_DEBUG
3260	/* control debugging printfs */
3261	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
3262	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
3263	    "debug", SYSCTL_DESCR("Enable debugging output"),
3264	    NULL, 0, &wpi_debug, 0, CTL_CREATE, CTL_EOL)) != 0)
3265		goto err;
3266#endif
3267
3268	return;
3269err:
3270	aprint_error("%s: sysctl_createv failed (rc = %d)\n", __func__, rc);
3271}
3272