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