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