atw.c revision 1.39
1/*	$NetBSD: atw.c,v 1.39 2004/07/15 05:54:13 dyoung Exp $	*/
2
3/*-
4 * Copyright (c) 1998, 1999, 2000, 2002, 2003, 2004 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by David Young, by Jason R. Thorpe, and by Charles M. Hannum.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 *    must display the following acknowledgement:
20 *	This product includes software developed by the NetBSD
21 *	Foundation, Inc. and its contributors.
22 * 4. Neither the name of The NetBSD Foundation nor the names of its
23 *    contributors may be used to endorse or promote products derived
24 *    from this software without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
37 */
38
39/*
40 * Device driver for the ADMtek ADM8211 802.11 MAC/BBP.
41 */
42
43#include <sys/cdefs.h>
44__KERNEL_RCSID(0, "$NetBSD: atw.c,v 1.39 2004/07/15 05:54:13 dyoung Exp $");
45
46#include "bpfilter.h"
47
48#include <sys/param.h>
49#include <sys/systm.h>
50#include <sys/callout.h>
51#include <sys/mbuf.h>
52#include <sys/malloc.h>
53#include <sys/kernel.h>
54#include <sys/socket.h>
55#include <sys/ioctl.h>
56#include <sys/errno.h>
57#include <sys/device.h>
58#include <sys/time.h>
59
60#include <machine/endian.h>
61
62#include <uvm/uvm_extern.h>
63
64#include <net/if.h>
65#include <net/if_dl.h>
66#include <net/if_media.h>
67#include <net/if_ether.h>
68
69#include <net80211/ieee80211_var.h>
70#include <net80211/ieee80211_compat.h>
71#include <net80211/ieee80211_radiotap.h>
72
73#if NBPFILTER > 0
74#include <net/bpf.h>
75#endif
76
77#include <machine/bus.h>
78#include <machine/intr.h>
79
80#include <dev/ic/atwreg.h>
81#include <dev/ic/rf3000reg.h>
82#include <dev/ic/si4136reg.h>
83#include <dev/ic/atwvar.h>
84#include <dev/ic/smc93cx6var.h>
85
86/* XXX TBD open questions
87 *
88 *
89 * When should I set DSSS PAD in reg 0x15 of RF3000? In 1-2Mbps
90 * modes only, or all modes (5.5-11 Mbps CCK modes, too?) Does the MAC
91 * handle this for me?
92 *
93 */
94/* device attachment
95 *
96 *    print TOFS[012]
97 *
98 * device initialization
99 *
100 *    clear ATW_FRCTL_MAXPSP to disable max power saving
101 *    set ATW_TXBR_ALCUPDATE to enable ALC
102 *    set TOFS[012]? (hope not)
103 *    disable rx/tx
104 *    set ATW_PAR_SWR (software reset)
105 *    wait for ATW_PAR_SWR clear
106 *    disable interrupts
107 *    ack status register
108 *    enable interrupts
109 *
110 * rx/tx initialization
111 *
112 *    disable rx/tx w/ ATW_NAR_SR, ATW_NAR_ST
113 *    allocate and init descriptor rings
114 *    write ATW_PAR_DSL (descriptor skip length)
115 *    write descriptor base addrs: ATW_TDBD, ATW_TDBP, write ATW_RDB
116 *    write ATW_NAR_SQ for one/both transmit descriptor rings
117 *    write ATW_NAR_SQ for one/both transmit descriptor rings
118 *    enable rx/tx w/ ATW_NAR_SR, ATW_NAR_ST
119 *
120 * rx/tx end
121 *
122 *    stop DMA
123 *    disable rx/tx w/ ATW_NAR_SR, ATW_NAR_ST
124 *    flush tx w/ ATW_NAR_HF
125 *
126 * scan
127 *
128 *    initialize rx/tx
129 *
130 * BSS join: (re)association response
131 *
132 *    set ATW_FRCTL_AID
133 *
134 * optimizations ???
135 *
136 */
137
138#define	VOODOO_DUR_11_ROUNDING		0x01 /* necessary */
139#define	VOODOO_DUR_2_4_SPECIALCASE	0x02 /* NOT necessary */
140int atw_voodoo = VOODOO_DUR_11_ROUNDING;
141
142int atw_rfio_enable_delay = 20 * 1000;
143int atw_rfio_disable_delay = 2 * 1000;
144int atw_writewep_delay = 5;
145int atw_beacon_len_adjust = 4;
146int atw_dwelltime = 200;
147
148#ifdef ATW_DEBUG
149int atw_debug = 0;
150
151#define ATW_DPRINTF(x)	if (atw_debug > 0) printf x
152#define ATW_DPRINTF2(x)	if (atw_debug > 1) printf x
153#define ATW_DPRINTF3(x)	if (atw_debug > 2) printf x
154#define	DPRINTF(sc, x)	if ((sc)->sc_ic.ic_if.if_flags & IFF_DEBUG) printf x
155#define	DPRINTF2(sc, x)	if ((sc)->sc_ic.ic_if.if_flags & IFF_DEBUG) ATW_DPRINTF2(x)
156#define	DPRINTF3(sc, x)	if ((sc)->sc_ic.ic_if.if_flags & IFF_DEBUG) ATW_DPRINTF3(x)
157
158static void atw_print_regs(struct atw_softc *, const char *);
159static void atw_dump_pkt(struct ifnet *, struct mbuf *);
160
161/* Note well: I never got atw_rf3000_read or atw_si4126_read to work. */
162#	ifdef ATW_BBPDEBUG
163static int atw_rf3000_read(struct atw_softc *sc, u_int, u_int *);
164static void atw_rf3000_print(struct atw_softc *);
165#	endif /* ATW_BBPDEBUG */
166
167#	ifdef ATW_SYNDEBUG
168static int atw_si4126_read(struct atw_softc *, u_int, u_int *);
169static void atw_si4126_print(struct atw_softc *);
170#	endif /* ATW_SYNDEBUG */
171
172#else
173#define ATW_DPRINTF(x)
174#define ATW_DPRINTF2(x)
175#define ATW_DPRINTF3(x)
176#define	DPRINTF(sc, x)	/* nothing */
177#define	DPRINTF2(sc, x)	/* nothing */
178#define	DPRINTF3(sc, x)	/* nothing */
179#endif
180
181#ifdef ATW_STATS
182void	atw_print_stats(struct atw_softc *);
183#endif
184
185void	atw_start(struct ifnet *);
186void	atw_watchdog(struct ifnet *);
187int	atw_ioctl(struct ifnet *, u_long, caddr_t);
188int	atw_init(struct ifnet *);
189void	atw_txdrain(struct atw_softc *);
190void	atw_stop(struct ifnet *, int);
191
192void	atw_reset(struct atw_softc *);
193int	atw_read_srom(struct atw_softc *);
194
195void	atw_shutdown(void *);
196
197void	atw_rxdrain(struct atw_softc *);
198int	atw_add_rxbuf(struct atw_softc *, int);
199void	atw_idle(struct atw_softc *, u_int32_t);
200
201int	atw_enable(struct atw_softc *);
202void	atw_disable(struct atw_softc *);
203void	atw_power(int, void *);
204
205void	atw_rxintr(struct atw_softc *);
206void	atw_txintr(struct atw_softc *);
207void	atw_linkintr(struct atw_softc *, u_int32_t);
208
209static int atw_newstate(struct ieee80211com *, enum ieee80211_state, int);
210static void atw_tsf(struct atw_softc *);
211static void atw_start_beacon(struct atw_softc *, int);
212static void atw_write_wep(struct atw_softc *);
213static void atw_write_bssid(struct atw_softc *);
214static void atw_write_bcn_thresh(struct atw_softc *);
215static void atw_write_ssid(struct atw_softc *);
216static void atw_write_sup_rates(struct atw_softc *);
217static void atw_clear_sram(struct atw_softc *);
218static void atw_write_sram(struct atw_softc *, u_int, u_int8_t *, u_int);
219static int atw_media_change(struct ifnet *);
220static void atw_media_status(struct ifnet *, struct ifmediareq *);
221static void atw_filter_setup(struct atw_softc *);
222static void atw_frame_setdurs(struct atw_softc *, struct atw_frame *, int, int);
223static __inline u_int64_t atw_predict_beacon(u_int64_t, u_int32_t);
224static void atw_recv_beacon(struct ieee80211com *, struct mbuf *,
225    struct ieee80211_node *, int, int, u_int32_t);
226static void atw_recv_mgmt(struct ieee80211com *, struct mbuf *,
227    struct ieee80211_node *, int, int, u_int32_t);
228static void atw_node_free(struct ieee80211com *, struct ieee80211_node *);
229static struct ieee80211_node *atw_node_alloc(struct ieee80211com *);
230
231static int atw_tune(struct atw_softc *);
232
233static void atw_rfio_enable(struct atw_softc *, int);
234
235/* RFMD RF3000 Baseband Processor */
236static int atw_rf3000_init(struct atw_softc *);
237static int atw_rf3000_tune(struct atw_softc *, u_int8_t);
238static int atw_rf3000_write(struct atw_softc *, u_int, u_int);
239#ifdef ATW_DEBUG
240static int atw_rf3000_read(struct atw_softc *sc, u_int, u_int *);
241#endif /* ATW_DEBUG */
242
243/* Silicon Laboratories Si4126 RF/IF Synthesizer */
244static int atw_si4126_tune(struct atw_softc *, u_int8_t);
245static int atw_si4126_write(struct atw_softc *, u_int, u_int);
246#ifdef ATW_DEBUG
247static int atw_si4126_read(struct atw_softc *, u_int, u_int *);
248#endif /* ATW_DEBUG */
249
250const struct atw_txthresh_tab atw_txthresh_tab_lo[] = ATW_TXTHRESH_TAB_LO_RATE;
251const struct atw_txthresh_tab atw_txthresh_tab_hi[] = ATW_TXTHRESH_TAB_HI_RATE;
252
253const char *atw_tx_state[] = {
254	"STOPPED",
255	"RUNNING - read descriptor",
256	"RUNNING - transmitting",
257	"RUNNING - filling fifo",	/* XXX */
258	"SUSPENDED",
259	"RUNNING -- write descriptor",
260	"RUNNING -- write last descriptor",
261	"RUNNING - fifo full"
262};
263
264const char *atw_rx_state[] = {
265	"STOPPED",
266	"RUNNING - read descriptor",
267	"RUNNING - check this packet, pre-fetch next",
268	"RUNNING - wait for reception",
269	"SUSPENDED",
270	"RUNNING - write descriptor",
271	"RUNNING - flush fifo",
272	"RUNNING - fifo drain"
273};
274
275int
276atw_activate(struct device *self, enum devact act)
277{
278	struct atw_softc *sc = (struct atw_softc *)self;
279	int rv = 0, s;
280
281	s = splnet();
282	switch (act) {
283	case DVACT_ACTIVATE:
284		rv = EOPNOTSUPP;
285		break;
286
287	case DVACT_DEACTIVATE:
288		if_deactivate(&sc->sc_ic.ic_if);
289		break;
290	}
291	splx(s);
292	return rv;
293}
294
295/*
296 * atw_enable:
297 *
298 *	Enable the ADM8211 chip.
299 */
300int
301atw_enable(struct atw_softc *sc)
302{
303
304	if (ATW_IS_ENABLED(sc) == 0) {
305		if (sc->sc_enable != NULL && (*sc->sc_enable)(sc) != 0) {
306			printf("%s: device enable failed\n",
307			    sc->sc_dev.dv_xname);
308			return (EIO);
309		}
310		sc->sc_flags |= ATWF_ENABLED;
311	}
312	return (0);
313}
314
315/*
316 * atw_disable:
317 *
318 *	Disable the ADM8211 chip.
319 */
320void
321atw_disable(struct atw_softc *sc)
322{
323	if (!ATW_IS_ENABLED(sc))
324		return;
325	if (sc->sc_disable != NULL)
326		(*sc->sc_disable)(sc);
327	sc->sc_flags &= ~ATWF_ENABLED;
328}
329
330/* Returns -1 on failure. */
331int
332atw_read_srom(struct atw_softc *sc)
333{
334	struct seeprom_descriptor sd;
335	u_int32_t reg;
336
337	(void)memset(&sd, 0, sizeof(sd));
338
339	reg = ATW_READ(sc, ATW_TEST0);
340
341	if ((reg & (ATW_TEST0_EPNE|ATW_TEST0_EPSNM)) != 0) {
342		printf("%s: bad or missing/bad SROM\n", sc->sc_dev.dv_xname);
343		return -1;
344	}
345
346	switch (reg & ATW_TEST0_EPTYP_MASK) {
347	case ATW_TEST0_EPTYP_93c66:
348		ATW_DPRINTF(("%s: 93c66 SROM\n", sc->sc_dev.dv_xname));
349		sc->sc_sromsz = 512;
350		sd.sd_chip = C56_66;
351		break;
352	case ATW_TEST0_EPTYP_93c46:
353		ATW_DPRINTF(("%s: 93c46 SROM\n", sc->sc_dev.dv_xname));
354		sc->sc_sromsz = 128;
355		sd.sd_chip = C46;
356		break;
357	default:
358		printf("%s: unknown SROM type %d\n", sc->sc_dev.dv_xname,
359		    MASK_AND_RSHIFT(reg, ATW_TEST0_EPTYP_MASK));
360		return -1;
361	}
362
363	sc->sc_srom = malloc(sc->sc_sromsz, M_DEVBUF, M_NOWAIT);
364
365	if (sc->sc_srom == NULL) {
366		printf("%s: unable to allocate SROM buffer\n",
367		    sc->sc_dev.dv_xname);
368		return -1;
369	}
370
371	(void)memset(sc->sc_srom, 0, sc->sc_sromsz);
372
373	/* ADM8211 has a single 32-bit register for controlling the
374	 * 93cx6 SROM.  Bit SRS enables the serial port. There is no
375	 * "ready" bit. The ADM8211 input/output sense is the reverse
376	 * of read_seeprom's.
377	 */
378	sd.sd_tag = sc->sc_st;
379	sd.sd_bsh = sc->sc_sh;
380	sd.sd_regsize = 4;
381	sd.sd_control_offset = ATW_SPR;
382	sd.sd_status_offset = ATW_SPR;
383	sd.sd_dataout_offset = ATW_SPR;
384	sd.sd_CK = ATW_SPR_SCLK;
385	sd.sd_CS = ATW_SPR_SCS;
386	sd.sd_DI = ATW_SPR_SDO;
387	sd.sd_DO = ATW_SPR_SDI;
388	sd.sd_MS = ATW_SPR_SRS;
389	sd.sd_RDY = 0;
390
391	if (!read_seeprom(&sd, sc->sc_srom, 0, sc->sc_sromsz/2)) {
392		printf("%s: could not read SROM\n", sc->sc_dev.dv_xname);
393		free(sc->sc_srom, M_DEVBUF);
394		return -1;
395	}
396#ifdef ATW_DEBUG
397	{
398		int i;
399		ATW_DPRINTF(("\nSerial EEPROM:\n\t"));
400		for (i = 0; i < sc->sc_sromsz/2; i = i + 1) {
401			if (((i % 8) == 0) && (i != 0)) {
402				ATW_DPRINTF(("\n\t"));
403			}
404			ATW_DPRINTF((" 0x%x", sc->sc_srom[i]));
405		}
406		ATW_DPRINTF(("\n"));
407	}
408#endif /* ATW_DEBUG */
409	return 0;
410}
411
412#ifdef ATW_DEBUG
413static void
414atw_print_regs(struct atw_softc *sc, const char *where)
415{
416#define PRINTREG(sc, reg) \
417	ATW_DPRINTF2(("%s: reg[ " #reg " / %03x ] = %08x\n", \
418	    sc->sc_dev.dv_xname, reg, ATW_READ(sc, reg)))
419
420	ATW_DPRINTF2(("%s: %s\n", sc->sc_dev.dv_xname, where));
421
422	PRINTREG(sc, ATW_PAR);
423	PRINTREG(sc, ATW_FRCTL);
424	PRINTREG(sc, ATW_TDR);
425	PRINTREG(sc, ATW_WTDP);
426	PRINTREG(sc, ATW_RDR);
427	PRINTREG(sc, ATW_WRDP);
428	PRINTREG(sc, ATW_RDB);
429	PRINTREG(sc, ATW_CSR3A);
430	PRINTREG(sc, ATW_TDBD);
431	PRINTREG(sc, ATW_TDBP);
432	PRINTREG(sc, ATW_STSR);
433	PRINTREG(sc, ATW_CSR5A);
434	PRINTREG(sc, ATW_NAR);
435	PRINTREG(sc, ATW_CSR6A);
436	PRINTREG(sc, ATW_IER);
437	PRINTREG(sc, ATW_CSR7A);
438	PRINTREG(sc, ATW_LPC);
439	PRINTREG(sc, ATW_TEST1);
440	PRINTREG(sc, ATW_SPR);
441	PRINTREG(sc, ATW_TEST0);
442	PRINTREG(sc, ATW_WCSR);
443	PRINTREG(sc, ATW_WPDR);
444	PRINTREG(sc, ATW_GPTMR);
445	PRINTREG(sc, ATW_GPIO);
446	PRINTREG(sc, ATW_BBPCTL);
447	PRINTREG(sc, ATW_SYNCTL);
448	PRINTREG(sc, ATW_PLCPHD);
449	PRINTREG(sc, ATW_MMIWADDR);
450	PRINTREG(sc, ATW_MMIRADDR1);
451	PRINTREG(sc, ATW_MMIRADDR2);
452	PRINTREG(sc, ATW_TXBR);
453	PRINTREG(sc, ATW_CSR15A);
454	PRINTREG(sc, ATW_ALCSTAT);
455	PRINTREG(sc, ATW_TOFS2);
456	PRINTREG(sc, ATW_CMDR);
457	PRINTREG(sc, ATW_PCIC);
458	PRINTREG(sc, ATW_PMCSR);
459	PRINTREG(sc, ATW_PAR0);
460	PRINTREG(sc, ATW_PAR1);
461	PRINTREG(sc, ATW_MAR0);
462	PRINTREG(sc, ATW_MAR1);
463	PRINTREG(sc, ATW_ATIMDA0);
464	PRINTREG(sc, ATW_ABDA1);
465	PRINTREG(sc, ATW_BSSID0);
466	PRINTREG(sc, ATW_TXLMT);
467	PRINTREG(sc, ATW_MIBCNT);
468	PRINTREG(sc, ATW_BCNT);
469	PRINTREG(sc, ATW_TSFTH);
470	PRINTREG(sc, ATW_TSC);
471	PRINTREG(sc, ATW_SYNRF);
472	PRINTREG(sc, ATW_BPLI);
473	PRINTREG(sc, ATW_CAP0);
474	PRINTREG(sc, ATW_CAP1);
475	PRINTREG(sc, ATW_RMD);
476	PRINTREG(sc, ATW_CFPP);
477	PRINTREG(sc, ATW_TOFS0);
478	PRINTREG(sc, ATW_TOFS1);
479	PRINTREG(sc, ATW_IFST);
480	PRINTREG(sc, ATW_RSPT);
481	PRINTREG(sc, ATW_TSFTL);
482	PRINTREG(sc, ATW_WEPCTL);
483	PRINTREG(sc, ATW_WESK);
484	PRINTREG(sc, ATW_WEPCNT);
485	PRINTREG(sc, ATW_MACTEST);
486	PRINTREG(sc, ATW_FER);
487	PRINTREG(sc, ATW_FEMR);
488	PRINTREG(sc, ATW_FPSR);
489	PRINTREG(sc, ATW_FFER);
490#undef PRINTREG
491}
492#endif /* ATW_DEBUG */
493
494/*
495 * Finish attaching an ADMtek ADM8211 MAC.  Called by bus-specific front-end.
496 */
497void
498atw_attach(struct atw_softc *sc)
499{
500	static const u_int8_t empty_macaddr[IEEE80211_ADDR_LEN] = {
501		0x00, 0x00, 0x00, 0x00, 0x00, 0x00
502	};
503	struct ieee80211com *ic = &sc->sc_ic;
504	struct ifnet *ifp = &ic->ic_if;
505	int country_code, error, i, nrate;
506	u_int32_t reg;
507	static const char *type_strings[] = {"Intersil (not supported)",
508	    "RFMD", "Marvel (not supported)"};
509
510	sc->sc_txth = atw_txthresh_tab_lo;
511
512	SIMPLEQ_INIT(&sc->sc_txfreeq);
513	SIMPLEQ_INIT(&sc->sc_txdirtyq);
514
515#ifdef ATW_DEBUG
516	atw_print_regs(sc, "atw_attach");
517#endif /* ATW_DEBUG */
518
519	/*
520	 * Allocate the control data structures, and create and load the
521	 * DMA map for it.
522	 */
523	if ((error = bus_dmamem_alloc(sc->sc_dmat,
524	    sizeof(struct atw_control_data), PAGE_SIZE, 0, &sc->sc_cdseg,
525	    1, &sc->sc_cdnseg, 0)) != 0) {
526		printf("%s: unable to allocate control data, error = %d\n",
527		    sc->sc_dev.dv_xname, error);
528		goto fail_0;
529	}
530
531	if ((error = bus_dmamem_map(sc->sc_dmat, &sc->sc_cdseg, sc->sc_cdnseg,
532	    sizeof(struct atw_control_data), (caddr_t *)&sc->sc_control_data,
533	    BUS_DMA_COHERENT)) != 0) {
534		printf("%s: unable to map control data, error = %d\n",
535		    sc->sc_dev.dv_xname, error);
536		goto fail_1;
537	}
538
539	if ((error = bus_dmamap_create(sc->sc_dmat,
540	    sizeof(struct atw_control_data), 1,
541	    sizeof(struct atw_control_data), 0, 0, &sc->sc_cddmamap)) != 0) {
542		printf("%s: unable to create control data DMA map, "
543		    "error = %d\n", sc->sc_dev.dv_xname, error);
544		goto fail_2;
545	}
546
547	if ((error = bus_dmamap_load(sc->sc_dmat, sc->sc_cddmamap,
548	    sc->sc_control_data, sizeof(struct atw_control_data), NULL,
549	    0)) != 0) {
550		printf("%s: unable to load control data DMA map, error = %d\n",
551		    sc->sc_dev.dv_xname, error);
552		goto fail_3;
553	}
554
555	/*
556	 * Create the transmit buffer DMA maps.
557	 */
558	sc->sc_ntxsegs = ATW_NTXSEGS;
559	for (i = 0; i < ATW_TXQUEUELEN; i++) {
560		if ((error = bus_dmamap_create(sc->sc_dmat, MCLBYTES,
561		    sc->sc_ntxsegs, MCLBYTES, 0, 0,
562		    &sc->sc_txsoft[i].txs_dmamap)) != 0) {
563			printf("%s: unable to create tx DMA map %d, "
564			    "error = %d\n", sc->sc_dev.dv_xname, i, error);
565			goto fail_4;
566		}
567	}
568
569	/*
570	 * Create the receive buffer DMA maps.
571	 */
572	for (i = 0; i < ATW_NRXDESC; i++) {
573		if ((error = bus_dmamap_create(sc->sc_dmat, MCLBYTES, 1,
574		    MCLBYTES, 0, 0, &sc->sc_rxsoft[i].rxs_dmamap)) != 0) {
575			printf("%s: unable to create rx DMA map %d, "
576			    "error = %d\n", sc->sc_dev.dv_xname, i, error);
577			goto fail_5;
578		}
579	}
580	for (i = 0; i < ATW_NRXDESC; i++) {
581		sc->sc_rxsoft[i].rxs_mbuf = NULL;
582	}
583
584	/* Reset the chip to a known state. */
585	atw_reset(sc);
586
587	if (atw_read_srom(sc) == -1)
588		return;
589
590	sc->sc_rftype = MASK_AND_RSHIFT(sc->sc_srom[ATW_SR_CSR20],
591	    ATW_SR_RFTYPE_MASK);
592
593	sc->sc_bbptype = MASK_AND_RSHIFT(sc->sc_srom[ATW_SR_CSR20],
594	    ATW_SR_BBPTYPE_MASK);
595
596	if (sc->sc_rftype > sizeof(type_strings)/sizeof(type_strings[0])) {
597		printf("%s: unknown RF\n", sc->sc_dev.dv_xname);
598		return;
599	}
600	if (sc->sc_bbptype > sizeof(type_strings)/sizeof(type_strings[0])) {
601		printf("%s: unknown BBP\n", sc->sc_dev.dv_xname);
602		return;
603	}
604
605	printf("%s: %s RF, %s BBP", sc->sc_dev.dv_xname,
606	    type_strings[sc->sc_rftype], type_strings[sc->sc_bbptype]);
607
608	/* XXX There exists a Linux driver which seems to use RFType = 0 for
609	 * MARVEL. My bug, or theirs?
610	 */
611
612	reg = LSHIFT(sc->sc_rftype, ATW_SYNCTL_RFTYPE_MASK);
613
614	switch (sc->sc_rftype) {
615	case ATW_RFTYPE_INTERSIL:
616		reg |= ATW_SYNCTL_CS1;
617		break;
618	case ATW_RFTYPE_RFMD:
619		reg |= ATW_SYNCTL_CS0;
620		break;
621	case ATW_RFTYPE_MARVEL:
622		break;
623	}
624
625	sc->sc_synctl_rd = reg | ATW_SYNCTL_RD;
626	sc->sc_synctl_wr = reg | ATW_SYNCTL_WR;
627
628	reg = LSHIFT(sc->sc_bbptype, ATW_BBPCTL_TYPE_MASK);
629
630	switch (sc->sc_bbptype) {
631	case ATW_BBPTYPE_INTERSIL:
632		reg |= ATW_BBPCTL_TWI;
633		break;
634	case ATW_BBPTYPE_RFMD:
635		reg |= ATW_BBPCTL_RF3KADDR_ADDR | ATW_BBPCTL_NEGEDGE_DO |
636		    ATW_BBPCTL_CCA_ACTLO;
637		break;
638	case ATW_BBPTYPE_MARVEL:
639		break;
640	case ATW_C_BBPTYPE_RFMD:
641		printf("%s: ADM8211C MAC/RFMD BBP not supported yet.\n",
642		    sc->sc_dev.dv_xname);
643		break;
644	}
645
646	sc->sc_bbpctl_wr = reg | ATW_BBPCTL_WR;
647	sc->sc_bbpctl_rd = reg | ATW_BBPCTL_RD;
648
649	/*
650	 * From this point forward, the attachment cannot fail.  A failure
651	 * before this point releases all resources that may have been
652	 * allocated.
653	 */
654	sc->sc_flags |= ATWF_ATTACHED /* | ATWF_RTSCTS */;
655
656	ATW_DPRINTF((" SROM MAC %04x%04x%04x",
657	    htole16(sc->sc_srom[ATW_SR_MAC00]),
658	    htole16(sc->sc_srom[ATW_SR_MAC01]),
659	    htole16(sc->sc_srom[ATW_SR_MAC10])));
660
661	country_code = MASK_AND_RSHIFT(sc->sc_srom[ATW_SR_CTRY_CR29],
662	    ATW_SR_CTRY_MASK);
663
664#define ADD_CHANNEL(_ic, _chan) do {					\
665	_ic->ic_channels[_chan].ic_flags = IEEE80211_CHAN_B;		\
666	_ic->ic_channels[_chan].ic_freq =				\
667	    ieee80211_ieee2mhz(_chan, _ic->ic_channels[_chan].ic_flags);\
668} while (0)
669
670	/* Find available channels */
671	switch (country_code) {
672	case COUNTRY_MMK2:	/* 1-14 */
673		ADD_CHANNEL(ic, 14);
674		/*FALLTHROUGH*/
675	case COUNTRY_ETSI:	/* 1-13 */
676		for (i = 1; i <= 13; i++)
677			ADD_CHANNEL(ic, i);
678		break;
679	case COUNTRY_FCC:	/* 1-11 */
680	case COUNTRY_IC:	/* 1-11 */
681		for (i = 1; i <= 11; i++)
682			ADD_CHANNEL(ic, i);
683		break;
684	case COUNTRY_MMK:	/* 14 */
685		ADD_CHANNEL(ic, 14);
686		break;
687	case COUNTRY_FRANCE:	/* 10-13 */
688		for (i = 10; i <= 13; i++)
689			ADD_CHANNEL(ic, i);
690		break;
691	default:	/* assume channels 10-11 */
692	case COUNTRY_SPAIN:	/* 10-11 */
693		for (i = 10; i <= 11; i++)
694			ADD_CHANNEL(ic, i);
695		break;
696	}
697
698	/* Read the MAC address. */
699	reg = ATW_READ(sc, ATW_PAR0);
700	ic->ic_myaddr[0] = MASK_AND_RSHIFT(reg, ATW_PAR0_PAB0_MASK);
701	ic->ic_myaddr[1] = MASK_AND_RSHIFT(reg, ATW_PAR0_PAB1_MASK);
702	ic->ic_myaddr[2] = MASK_AND_RSHIFT(reg, ATW_PAR0_PAB2_MASK);
703	ic->ic_myaddr[3] = MASK_AND_RSHIFT(reg, ATW_PAR0_PAB3_MASK);
704	reg = ATW_READ(sc, ATW_PAR1);
705	ic->ic_myaddr[4] = MASK_AND_RSHIFT(reg, ATW_PAR1_PAB4_MASK);
706	ic->ic_myaddr[5] = MASK_AND_RSHIFT(reg, ATW_PAR1_PAB5_MASK);
707
708	if (IEEE80211_ADDR_EQ(ic->ic_myaddr, empty_macaddr)) {
709		printf(" could not get mac address, attach failed\n");
710		return;
711	}
712
713	printf(" 802.11 address %s\n", ether_sprintf(ic->ic_myaddr));
714
715	memcpy(ifp->if_xname, sc->sc_dev.dv_xname, IFNAMSIZ);
716	ifp->if_softc = sc;
717	ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST |
718	    IFF_NOTRAILERS;
719	ifp->if_ioctl = atw_ioctl;
720	ifp->if_start = atw_start;
721	ifp->if_watchdog = atw_watchdog;
722	ifp->if_init = atw_init;
723	ifp->if_stop = atw_stop;
724	IFQ_SET_READY(&ifp->if_snd);
725
726	ic->ic_phytype = IEEE80211_T_DS;
727	ic->ic_opmode = IEEE80211_M_STA;
728	ic->ic_caps = IEEE80211_C_PMGT | IEEE80211_C_IBSS |
729	    IEEE80211_C_HOSTAP | IEEE80211_C_MONITOR | IEEE80211_C_WEP;
730
731	nrate = 0;
732	ic->ic_sup_rates[IEEE80211_MODE_11B].rs_rates[nrate++] = 2;
733	ic->ic_sup_rates[IEEE80211_MODE_11B].rs_rates[nrate++] = 4;
734	ic->ic_sup_rates[IEEE80211_MODE_11B].rs_rates[nrate++] = 11;
735	ic->ic_sup_rates[IEEE80211_MODE_11B].rs_rates[nrate++] = 22;
736	ic->ic_sup_rates[IEEE80211_MODE_11B].rs_nrates = nrate;
737
738	/*
739	 * Call MI attach routines.
740	 */
741
742	if_attach(ifp);
743	ieee80211_ifattach(ifp);
744
745	sc->sc_newstate = ic->ic_newstate;
746	ic->ic_newstate = atw_newstate;
747
748	sc->sc_recv_mgmt = ic->ic_recv_mgmt;
749	ic->ic_recv_mgmt = atw_recv_mgmt;
750
751	sc->sc_node_free = ic->ic_node_free;
752	ic->ic_node_free = atw_node_free;
753
754	sc->sc_node_alloc = ic->ic_node_alloc;
755	ic->ic_node_alloc = atw_node_alloc;
756
757	/* possibly we should fill in our own sc_send_prresp, since
758	 * the ADM8211 is probably sending probe responses in ad hoc
759	 * mode.
760	 */
761
762	/* complete initialization */
763	ieee80211_media_init(ifp, atw_media_change, atw_media_status);
764	callout_init(&sc->sc_scan_ch);
765
766#if NBPFILTER > 0
767	bpfattach2(ifp, DLT_IEEE802_11_RADIO,
768	    sizeof(struct ieee80211_frame) + 64, &sc->sc_radiobpf);
769#endif
770
771	/*
772	 * Make sure the interface is shutdown during reboot.
773	 */
774	sc->sc_sdhook = shutdownhook_establish(atw_shutdown, sc);
775	if (sc->sc_sdhook == NULL)
776		printf("%s: WARNING: unable to establish shutdown hook\n",
777		    sc->sc_dev.dv_xname);
778
779	/*
780	 * Add a suspend hook to make sure we come back up after a
781	 * resume.
782	 */
783	sc->sc_powerhook = powerhook_establish(atw_power, sc);
784	if (sc->sc_powerhook == NULL)
785		printf("%s: WARNING: unable to establish power hook\n",
786		    sc->sc_dev.dv_xname);
787
788	memset(&sc->sc_rxtapu, 0, sizeof(sc->sc_rxtapu));
789	sc->sc_rxtap.ar_ihdr.it_len = sizeof(sc->sc_rxtapu);
790	sc->sc_rxtap.ar_ihdr.it_present = ATW_RX_RADIOTAP_PRESENT;
791
792	memset(&sc->sc_txtapu, 0, sizeof(sc->sc_txtapu));
793	sc->sc_txtap.at_ihdr.it_len = sizeof(sc->sc_txtapu);
794	sc->sc_txtap.at_ihdr.it_present = ATW_TX_RADIOTAP_PRESENT;
795
796	return;
797
798	/*
799	 * Free any resources we've allocated during the failed attach
800	 * attempt.  Do this in reverse order and fall through.
801	 */
802 fail_5:
803	for (i = 0; i < ATW_NRXDESC; i++) {
804		if (sc->sc_rxsoft[i].rxs_dmamap == NULL)
805			continue;
806		bus_dmamap_destroy(sc->sc_dmat, sc->sc_rxsoft[i].rxs_dmamap);
807	}
808 fail_4:
809	for (i = 0; i < ATW_TXQUEUELEN; i++) {
810		if (sc->sc_txsoft[i].txs_dmamap == NULL)
811			continue;
812		bus_dmamap_destroy(sc->sc_dmat, sc->sc_txsoft[i].txs_dmamap);
813	}
814	bus_dmamap_unload(sc->sc_dmat, sc->sc_cddmamap);
815 fail_3:
816	bus_dmamap_destroy(sc->sc_dmat, sc->sc_cddmamap);
817 fail_2:
818	bus_dmamem_unmap(sc->sc_dmat, (caddr_t)sc->sc_control_data,
819	    sizeof(struct atw_control_data));
820 fail_1:
821	bus_dmamem_free(sc->sc_dmat, &sc->sc_cdseg, sc->sc_cdnseg);
822 fail_0:
823	return;
824}
825
826static struct ieee80211_node *
827atw_node_alloc(struct ieee80211com *ic)
828{
829	struct atw_softc *sc = (struct atw_softc *)ic->ic_if.if_softc;
830	struct ieee80211_node *ni = (*sc->sc_node_alloc)(ic);
831
832	DPRINTF(sc, ("%s: alloc node %p\n", sc->sc_dev.dv_xname, ni));
833	return ni;
834}
835
836static void
837atw_node_free(struct ieee80211com *ic, struct ieee80211_node *ni)
838{
839	struct atw_softc *sc = (struct atw_softc *)ic->ic_if.if_softc;
840
841	DPRINTF(sc, ("%s: freeing node %p %s\n", sc->sc_dev.dv_xname, ni,
842	    ether_sprintf(ni->ni_bssid)));
843	(*sc->sc_node_free)(ic, ni);
844}
845
846/*
847 * atw_reset:
848 *
849 *	Perform a soft reset on the ADM8211.
850 */
851void
852atw_reset(struct atw_softc *sc)
853{
854	int i;
855
856	ATW_WRITE(sc, ATW_PAR, ATW_PAR_SWR);
857
858	for (i = 0; i < 10000; i++) {
859		if (ATW_ISSET(sc, ATW_PAR, ATW_PAR_SWR) == 0)
860			break;
861		DELAY(1);
862	}
863
864	DPRINTF2(sc, ("%s: atw_reset %d iterations\n", sc->sc_dev.dv_xname, i));
865
866	if (ATW_ISSET(sc, ATW_PAR, ATW_PAR_SWR))
867		printf("%s: reset failed to complete\n", sc->sc_dev.dv_xname);
868
869	/* Turn off maximum power saving. */
870	ATW_CLR(sc, ATW_FRCTL, ATW_FRCTL_MAXPSP);
871
872	/* Recall EEPROM. */
873	ATW_SET(sc, ATW_TEST0, ATW_TEST0_EPRLD);
874
875	DELAY(10 * 1000);
876
877	/* A reset seems to affect the SRAM contents, so put them into
878	 * a known state.
879	 */
880	atw_clear_sram(sc);
881
882	memset(sc->sc_bssid, 0, sizeof(sc->sc_bssid));
883
884	sc->sc_lost_bcn_thresh = 0;
885}
886
887static void
888atw_clear_sram(struct atw_softc *sc)
889{
890#if 0
891	for (addr = 0; addr < 448; addr++) {
892		ATW_WRITE(sc, ATW_WEPCTL,
893		    ATW_WEPCTL_WR | ATW_WEPCTL_UNKNOWN0	| addr);
894		DELAY(1000);
895		ATW_WRITE(sc, ATW_WESK, 0);
896		DELAY(1000); /* paranoia */
897	}
898	return;
899#endif
900	memset(sc->sc_sram, 0, sizeof(sc->sc_sram));
901	/* XXX not for revision 0x20. */
902	atw_write_sram(sc, 0, sc->sc_sram, sizeof(sc->sc_sram));
903}
904
905/* TBD atw_init
906 *
907 * set MAC based on ic->ic_bss->myaddr
908 * write WEP keys
909 * set TX rate
910 */
911
912/*
913 * atw_init:		[ ifnet interface function ]
914 *
915 *	Initialize the interface.  Must be called at splnet().
916 */
917int
918atw_init(struct ifnet *ifp)
919{
920	struct atw_softc *sc = ifp->if_softc;
921	struct ieee80211com *ic = &sc->sc_ic;
922	struct atw_txsoft *txs;
923	struct atw_rxsoft *rxs;
924	u_int32_t reg;
925	int i, error = 0;
926
927	if ((error = atw_enable(sc)) != 0)
928		goto out;
929
930	/*
931	 * Cancel any pending I/O. This also resets.
932	 */
933	atw_stop(ifp, 0);
934
935	ic->ic_bss->ni_chan = ic->ic_ibss_chan;
936	DPRINTF(sc, ("%s: channel %d freq %d flags 0x%04x\n",
937	    __func__, ieee80211_chan2ieee(ic, ic->ic_bss->ni_chan),
938	    ic->ic_bss->ni_chan->ic_freq, ic->ic_bss->ni_chan->ic_flags));
939
940	/* Turn off APM??? (A binary-only driver does this.)
941	 *
942	 * Set Rx store-and-forward mode.
943	 */
944	reg = ATW_READ(sc, ATW_CMDR);
945	reg &= ~ATW_CMDR_APM;
946	reg &= ~ATW_CMDR_DRT_MASK;
947	reg |= ATW_CMDR_RTE | LSHIFT(0x2, ATW_CMDR_DRT_MASK);
948
949	ATW_WRITE(sc, ATW_CMDR, reg);
950
951	/* Set data rate for PLCP Signal field, 1Mbps = 10 x 100Kb/s.
952	 *
953	 * XXX a binary-only driver sets a different service field than
954	 * 0. why?
955	 */
956	reg = ATW_READ(sc, ATW_PLCPHD);
957	reg &= ~(ATW_PLCPHD_SERVICE_MASK|ATW_PLCPHD_SIGNAL_MASK);
958	reg |= LSHIFT(10, ATW_PLCPHD_SIGNAL_MASK) |
959	    LSHIFT(0xb0, ATW_PLCPHD_SERVICE_MASK);
960	ATW_WRITE(sc, ATW_PLCPHD, reg);
961
962	/* XXX this magic can probably be figured out from the RFMD docs */
963	reg = LSHIFT(4, ATW_TOFS2_PWR1UP_MASK)    | /* 8 ms = 4 * 2 ms */
964	      LSHIFT(13, ATW_TOFS2_PWR0PAPE_MASK) | /* 13 us */
965	      LSHIFT(8, ATW_TOFS2_PWR1PAPE_MASK)  | /* 8 us */
966	      LSHIFT(5, ATW_TOFS2_PWR0TRSW_MASK)  | /* 5 us */
967	      LSHIFT(12, ATW_TOFS2_PWR1TRSW_MASK) | /* 12 us */
968	      LSHIFT(13, ATW_TOFS2_PWR0PE2_MASK)  | /* 13 us */
969	      LSHIFT(4, ATW_TOFS2_PWR1PE2_MASK)   | /* 4 us */
970	      LSHIFT(5, ATW_TOFS2_PWR0TXPE_MASK);  /* 5 us */
971	ATW_WRITE(sc, ATW_TOFS2, reg);
972
973	ATW_WRITE(sc, ATW_TXLMT, LSHIFT(512, ATW_TXLMT_MTMLT_MASK) |
974	                         LSHIFT(224, ATW_TXLMT_SRTYLIM_MASK));
975
976	/* XXX this resets an Intersil RF front-end? */
977	/* TBD condition on Intersil RFType? */
978	ATW_WRITE(sc, ATW_SYNRF, ATW_SYNRF_INTERSIL_EN);
979	DELAY(10 * 1000);
980	ATW_WRITE(sc, ATW_SYNRF, 0);
981	DELAY(5 * 1000);
982
983	/* 16 TU max duration for contention-free period */
984	reg = ATW_READ(sc, ATW_CFPP) & ~ATW_CFPP_CFPMD;
985	ATW_WRITE(sc, ATW_CFPP, reg | LSHIFT(16, ATW_CFPP_CFPMD));
986
987	/* XXX I guess that the Cardbus clock is 22MHz?
988	 * I am assuming that the role of ATW_TOFS0_USCNT is
989	 * to divide the bus clock to get a 1MHz clock---the datasheet is not
990	 * very clear on this point. It says in the datasheet that it is
991	 * possible for the ADM8211 to accomodate bus speeds between 22MHz
992	 * and 33MHz; maybe this is the way? I see a binary-only driver write
993	 * these values. These values are also the power-on default.
994	 */
995	ATW_WRITE(sc, ATW_TOFS0,
996	    LSHIFT(22, ATW_TOFS0_USCNT_MASK) |
997	    ATW_TOFS0_TUCNT_MASK /* set all bits in TUCNT */);
998
999	/* Initialize interframe spacing.  EIFS=0x64 is used by a binary-only
1000	 * driver. Go figure.
1001	 */
1002	reg = LSHIFT(IEEE80211_DUR_DS_SLOT, ATW_IFST_SLOT_MASK) |
1003	      LSHIFT(22 * IEEE80211_DUR_DS_SIFS /* # of 22MHz cycles */,
1004	             ATW_IFST_SIFS_MASK) |
1005	      LSHIFT(IEEE80211_DUR_DS_DIFS, ATW_IFST_DIFS_MASK) |
1006	      LSHIFT(0x64 /* IEEE80211_DUR_DS_EIFS */, ATW_IFST_EIFS_MASK);
1007
1008	ATW_WRITE(sc, ATW_IFST, reg);
1009
1010	/* XXX More magic. Might relate to ACK timing. */
1011	ATW_WRITE(sc, ATW_RSPT, LSHIFT(0xffff, ATW_RSPT_MART_MASK) |
1012	    LSHIFT(0xff, ATW_RSPT_MIRT_MASK));
1013
1014	/* Set up the MMI read/write addresses for the BBP.
1015	 *
1016	 * TBD find out the Marvel settings.
1017	 */
1018	switch (sc->sc_bbptype) {
1019	case ATW_BBPTYPE_INTERSIL:
1020		ATW_WRITE(sc, ATW_MMIWADDR, ATW_MMIWADDR_INTERSIL);
1021		ATW_WRITE(sc, ATW_MMIRADDR1, ATW_MMIRADDR1_INTERSIL);
1022		ATW_WRITE(sc, ATW_MMIRADDR2, ATW_MMIRADDR2_INTERSIL);
1023		break;
1024	case ATW_BBPTYPE_MARVEL:
1025		break;
1026	case ATW_BBPTYPE_RFMD:
1027		ATW_WRITE(sc, ATW_MMIWADDR, ATW_MMIWADDR_RFMD);
1028		ATW_WRITE(sc, ATW_MMIRADDR1, ATW_MMIRADDR1_RFMD);
1029		ATW_WRITE(sc, ATW_MMIRADDR2, ATW_MMIRADDR2_RFMD);
1030	default:
1031		break;
1032	}
1033
1034	sc->sc_wepctl = 0;
1035	ATW_WRITE(sc, ATW_MACTEST, ATW_MACTEST_MMI_USETXCLK);
1036
1037	if ((error = atw_rf3000_init(sc)) != 0)
1038		goto out;
1039
1040	/*
1041	 * Initialize the PCI Access Register.
1042	 */
1043	sc->sc_busmode = ATW_PAR_BAR;	/* XXX what is this? */
1044
1045	/*
1046	 * If we're allowed to do so, use Memory Read Line
1047	 * and Memory Read Multiple.
1048	 *
1049	 * XXX Should we use Memory Write and Invalidate?
1050	 */
1051	if (sc->sc_flags & ATWF_MRL)
1052		sc->sc_busmode |= ATW_PAR_MRLE;
1053	if (sc->sc_flags & ATWF_MRM)
1054		sc->sc_busmode |= ATW_PAR_MRME;
1055	if (sc->sc_flags & ATWF_MWI)
1056		sc->sc_busmode |= ATW_PAR_MWIE;
1057	if (sc->sc_maxburst == 0)
1058		sc->sc_maxburst = 8;	/* ADM8211 default */
1059
1060	switch (sc->sc_cacheline) {
1061	default:
1062		/* Use burst length. */
1063		break;
1064	case 8:
1065		sc->sc_busmode |= ATW_PAR_CAL_8DW;
1066		break;
1067	case 16:
1068		sc->sc_busmode |= ATW_PAR_CAL_16DW;
1069		break;
1070	case 32:
1071		sc->sc_busmode |= ATW_PAR_CAL_32DW;
1072		break;
1073	}
1074	switch (sc->sc_maxburst) {
1075	case 1:
1076		sc->sc_busmode |= ATW_PAR_PBL_1DW;
1077		break;
1078	case 2:
1079		sc->sc_busmode |= ATW_PAR_PBL_2DW;
1080		break;
1081	case 4:
1082		sc->sc_busmode |= ATW_PAR_PBL_4DW;
1083		break;
1084	case 8:
1085		sc->sc_busmode |= ATW_PAR_PBL_8DW;
1086		break;
1087	case 16:
1088		sc->sc_busmode |= ATW_PAR_PBL_16DW;
1089		break;
1090	case 32:
1091		sc->sc_busmode |= ATW_PAR_PBL_32DW;
1092		break;
1093	default:
1094		sc->sc_busmode |= ATW_PAR_PBL_8DW;
1095		break;
1096	}
1097
1098	ATW_WRITE(sc, ATW_PAR, sc->sc_busmode);
1099	DPRINTF(sc, ("%s: ATW_PAR %08x busmode %08x\n", sc->sc_dev.dv_xname,
1100	    ATW_READ(sc, ATW_PAR), sc->sc_busmode));
1101
1102	/*
1103	 * Initialize the OPMODE register.  We don't write it until
1104	 * we're ready to begin the transmit and receive processes.
1105	 */
1106	sc->sc_opmode = ATW_NAR_SR | ATW_NAR_ST |
1107	    sc->sc_txth[sc->sc_txthresh].txth_opmode;
1108
1109	/*
1110	 * Initialize the transmit descriptor ring.
1111	 */
1112	memset(sc->sc_txdescs, 0, sizeof(sc->sc_txdescs));
1113	for (i = 0; i < ATW_NTXDESC; i++) {
1114		/* no transmit chaining */
1115		sc->sc_txdescs[i].at_ctl = 0 /* ATW_TXFLAG_TCH */;
1116		sc->sc_txdescs[i].at_buf2 =
1117		    htole32(ATW_CDTXADDR(sc, ATW_NEXTTX(i)));
1118	}
1119	/* use ring mode */
1120	sc->sc_txdescs[ATW_NTXDESC - 1].at_ctl |= ATW_TXFLAG_TER;
1121	ATW_CDTXSYNC(sc, 0, ATW_NTXDESC,
1122	    BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
1123	sc->sc_txfree = ATW_NTXDESC;
1124	sc->sc_txnext = 0;
1125
1126	/*
1127	 * Initialize the transmit job descriptors.
1128	 */
1129	SIMPLEQ_INIT(&sc->sc_txfreeq);
1130	SIMPLEQ_INIT(&sc->sc_txdirtyq);
1131	for (i = 0; i < ATW_TXQUEUELEN; i++) {
1132		txs = &sc->sc_txsoft[i];
1133		txs->txs_mbuf = NULL;
1134		SIMPLEQ_INSERT_TAIL(&sc->sc_txfreeq, txs, txs_q);
1135	}
1136
1137	/*
1138	 * Initialize the receive descriptor and receive job
1139	 * descriptor rings.
1140	 */
1141	for (i = 0; i < ATW_NRXDESC; i++) {
1142		rxs = &sc->sc_rxsoft[i];
1143		if (rxs->rxs_mbuf == NULL) {
1144			if ((error = atw_add_rxbuf(sc, i)) != 0) {
1145				printf("%s: unable to allocate or map rx "
1146				    "buffer %d, error = %d\n",
1147				    sc->sc_dev.dv_xname, i, error);
1148				/*
1149				 * XXX Should attempt to run with fewer receive
1150				 * XXX buffers instead of just failing.
1151				 */
1152				atw_rxdrain(sc);
1153				goto out;
1154			}
1155		} else
1156			ATW_INIT_RXDESC(sc, i);
1157	}
1158	sc->sc_rxptr = 0;
1159
1160	/* disable all wake-up events */
1161	ATW_CLR(sc, ATW_WCSR, ATW_WCSR_WP1E|ATW_WCSR_WP2E|ATW_WCSR_WP3E|
1162	                      ATW_WCSR_WP4E|ATW_WCSR_WP5E|ATW_WCSR_TSFTWE|
1163			      ATW_WCSR_TIMWE|ATW_WCSR_ATIMWE|ATW_WCSR_KEYWE|
1164			      ATW_WCSR_WFRE|ATW_WCSR_MPRE|ATW_WCSR_LSOE);
1165
1166	/* ack all wake-up events */
1167	ATW_SET(sc, ATW_WCSR, 0);
1168
1169	/*
1170	 * Initialize the interrupt mask and enable interrupts.
1171	 */
1172	/* normal interrupts */
1173	sc->sc_inten =  ATW_INTR_TCI | ATW_INTR_TDU | ATW_INTR_RCI |
1174	    ATW_INTR_NISS | ATW_INTR_LINKON | ATW_INTR_BCNTC;
1175
1176	/* abnormal interrupts */
1177	sc->sc_inten |= ATW_INTR_TPS | ATW_INTR_TLT | ATW_INTR_TRT |
1178	    ATW_INTR_TUF | ATW_INTR_RDU | ATW_INTR_RPS | ATW_INTR_AISS |
1179	    ATW_INTR_FBE | ATW_INTR_LINKOFF | ATW_INTR_TSFTF | ATW_INTR_TSCZ;
1180
1181	sc->sc_linkint_mask = ATW_INTR_LINKON | ATW_INTR_LINKOFF |
1182	    ATW_INTR_BCNTC | ATW_INTR_TSFTF | ATW_INTR_TSCZ;
1183	sc->sc_rxint_mask = ATW_INTR_RCI | ATW_INTR_RDU;
1184	sc->sc_txint_mask = ATW_INTR_TCI | ATW_INTR_TUF | ATW_INTR_TLT |
1185	    ATW_INTR_TRT;
1186
1187	sc->sc_linkint_mask &= sc->sc_inten;
1188	sc->sc_rxint_mask &= sc->sc_inten;
1189	sc->sc_txint_mask &= sc->sc_inten;
1190
1191	ATW_WRITE(sc, ATW_IER, sc->sc_inten);
1192	ATW_WRITE(sc, ATW_STSR, 0xffffffff);
1193	if (sc->sc_intr_ack != NULL)
1194		(*sc->sc_intr_ack)(sc);
1195
1196	DPRINTF(sc, ("%s: ATW_IER %08x, inten %08x\n",
1197	    sc->sc_dev.dv_xname, ATW_READ(sc, ATW_IER), sc->sc_inten));
1198
1199	/*
1200	 * Give the transmit and receive rings to the ADM8211.
1201	 */
1202	ATW_WRITE(sc, ATW_TDBD, ATW_CDTXADDR(sc, sc->sc_txnext));
1203	ATW_WRITE(sc, ATW_RDB, ATW_CDRXADDR(sc, sc->sc_rxptr));
1204
1205	/* common 802.11 configuration */
1206	ic->ic_flags &= ~IEEE80211_F_IBSSON;
1207	switch (ic->ic_opmode) {
1208	case IEEE80211_M_STA:
1209		break;
1210	case IEEE80211_M_AHDEMO: /* XXX */
1211	case IEEE80211_M_IBSS:
1212		ic->ic_flags |= IEEE80211_F_IBSSON;
1213		/*FALLTHROUGH*/
1214	case IEEE80211_M_HOSTAP: /* XXX */
1215		break;
1216	case IEEE80211_M_MONITOR: /* XXX */
1217		break;
1218	}
1219
1220	atw_start_beacon(sc, 0);
1221
1222	switch (ic->ic_opmode) {
1223	case IEEE80211_M_AHDEMO:
1224	case IEEE80211_M_HOSTAP:
1225		ic->ic_bss->ni_intval = ic->ic_lintval;
1226		ic->ic_bss->ni_rssi = 0;
1227		ic->ic_bss->ni_rstamp = 0;
1228		break;
1229	default:					/* XXX */
1230		break;
1231	}
1232
1233	atw_write_ssid(sc);
1234	atw_write_sup_rates(sc);
1235	if (ic->ic_caps & IEEE80211_C_WEP)
1236		atw_write_wep(sc);
1237
1238	/*
1239	 * Set the receive filter.  This will start the transmit and
1240	 * receive processes.
1241	 */
1242	atw_filter_setup(sc);
1243
1244	/*
1245	 * Start the receive process.
1246	 */
1247	ATW_WRITE(sc, ATW_RDR, 0x1);
1248
1249	/*
1250	 * Note that the interface is now running.
1251	 */
1252	ifp->if_flags |= IFF_RUNNING;
1253	ifp->if_flags &= ~IFF_OACTIVE;
1254	ic->ic_state = IEEE80211_S_INIT;
1255
1256	if (ic->ic_opmode != IEEE80211_M_MONITOR)
1257		error = ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
1258	else
1259		error = ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
1260 out:
1261	if (error) {
1262		ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
1263		ifp->if_timer = 0;
1264		printf("%s: interface not running\n", sc->sc_dev.dv_xname);
1265	}
1266#ifdef ATW_DEBUG
1267	atw_print_regs(sc, "end of init");
1268#endif /* ATW_DEBUG */
1269
1270	return (error);
1271}
1272
1273/* enable == 1: host control of RF3000/Si4126 through ATW_SYNCTL.
1274 *           0: MAC control of RF3000/Si4126.
1275 *
1276 * Applies power, or selects RF front-end? Sets reset condition.
1277 *
1278 * TBD support non-RFMD BBP, non-SiLabs synth.
1279 */
1280static void
1281atw_rfio_enable(struct atw_softc *sc, int enable)
1282{
1283	if (enable) {
1284		ATW_WRITE(sc, ATW_SYNRF,
1285		    ATW_SYNRF_SELRF|ATW_SYNRF_PE1|ATW_SYNRF_PHYRST);
1286		DELAY(atw_rfio_enable_delay);
1287	} else {
1288		ATW_WRITE(sc, ATW_SYNRF, 0);
1289		DELAY(atw_rfio_disable_delay); /* shorter for some reason */
1290	}
1291}
1292
1293static int
1294atw_tune(struct atw_softc *sc)
1295{
1296	int rc;
1297	u_int32_t reg;
1298	int chan;
1299	struct ieee80211com *ic = &sc->sc_ic;
1300
1301	chan = ieee80211_chan2ieee(ic, ic->ic_bss->ni_chan);
1302	if (chan == IEEE80211_CHAN_ANY)
1303		panic("%s: chan == IEEE80211_CHAN_ANY\n", __func__);
1304
1305	if (chan == sc->sc_cur_chan)
1306		return 0;
1307
1308	DPRINTF(sc, ("%s: chan %d -> %d\n", sc->sc_dev.dv_xname,
1309	    sc->sc_cur_chan, chan));
1310
1311	atw_idle(sc, ATW_NAR_SR|ATW_NAR_ST);
1312
1313	if ((rc = atw_si4126_tune(sc, chan)) != 0 ||
1314	    (rc = atw_rf3000_tune(sc, chan)) != 0)
1315		printf("%s: failed to tune channel %d\n", sc->sc_dev.dv_xname,
1316		    chan);
1317
1318	reg = ATW_READ(sc, ATW_CAP0) & ~ATW_CAP0_CHN_MASK;
1319	ATW_WRITE(sc, ATW_CAP0,
1320	    reg | LSHIFT(chan, ATW_CAP0_CHN_MASK));
1321
1322	ATW_WRITE(sc, ATW_NAR, sc->sc_opmode);
1323
1324	if (rc == 0)
1325		sc->sc_cur_chan = chan;
1326
1327	return rc;
1328}
1329
1330#ifdef ATW_DEBUG
1331static void
1332atw_si4126_print(struct atw_softc *sc)
1333{
1334	struct ifnet *ifp = &sc->sc_ic.ic_if;
1335	u_int addr, val;
1336
1337	if (atw_debug < 3 || (ifp->if_flags & IFF_DEBUG) == 0)
1338		return;
1339
1340	for (addr = 0; addr <= 8; addr++) {
1341		printf("%s: synth[%d] = ", sc->sc_dev.dv_xname, addr);
1342		if (atw_si4126_read(sc, addr, &val) == 0) {
1343			printf("<unknown> (quitting print-out)\n");
1344			break;
1345		}
1346		printf("%05x\n", val);
1347	}
1348}
1349#endif /* ATW_DEBUG */
1350
1351/* Tune to channel chan by adjusting the Si4126 RF/IF synthesizer.
1352 *
1353 * The RF/IF synthesizer produces two reference frequencies for
1354 * the RF2948B transceiver.  The first frequency the RF2948B requires
1355 * is two times the so-called "intermediate frequency" (IF). Since
1356 * a SAW filter on the radio fixes the IF at 374MHz, I program the
1357 * Si4126 to generate IF LO = 374MHz x 2 = 748MHz.  The second
1358 * frequency required by the transceiver is the radio frequency
1359 * (RF). This is a superheterodyne transceiver; for f(chan) the
1360 * center frequency of the channel we are tuning, RF = f(chan) -
1361 * IF.
1362 *
1363 * XXX I am told by SiLabs that the Si4126 will accept a broader range
1364 * of XIN than the 2-25MHz mentioned by the datasheet, even *without*
1365 * XINDIV2 = 1.  I've tried this (it is necessary to double R) and it
1366 * works, but I have still programmed for XINDIV2 = 1 to be safe.
1367 */
1368static int
1369atw_si4126_tune(struct atw_softc *sc, u_int8_t chan)
1370{
1371	int rc = 0;
1372	u_int mhz;
1373	u_int R;
1374	u_int32_t reg;
1375	u_int16_t gain;
1376
1377#ifdef ATW_DEBUG
1378	atw_si4126_print(sc);
1379#endif /* ATW_DEBUG */
1380
1381	if (chan == 14)
1382		mhz = 2484;
1383	else
1384		mhz = 2412 + 5 * (chan - 1);
1385
1386	/* Tune IF to 748MHz to suit the IF LO input of the
1387	 * RF2494B, which is 2 x IF. No need to set an IF divider
1388         * because an IF in 526MHz - 952MHz is allowed.
1389	 *
1390	 * XIN is 44.000MHz, so divide it by two to get allowable
1391	 * range of 2-25MHz. SiLabs tells me that this is not
1392	 * strictly necessary.
1393	 */
1394
1395	R = 44;
1396
1397	atw_rfio_enable(sc, 1);
1398
1399	/* Power-up RF, IF synthesizers. */
1400	if ((rc = atw_si4126_write(sc, SI4126_POWER,
1401	    SI4126_POWER_PDIB|SI4126_POWER_PDRB)) != 0)
1402		goto out;
1403
1404	/* If RF2 N > 2047, then set KP2 to 1. */
1405	gain = LSHIFT(((mhz - 374) > 2047) ? 1 : 0, SI4126_GAIN_KP2_MASK);
1406
1407	if ((rc = atw_si4126_write(sc, SI4126_GAIN, gain)) != 0)
1408		goto out;
1409
1410	/* set LPWR, too? */
1411	if ((rc = atw_si4126_write(sc, SI4126_MAIN,
1412	    SI4126_MAIN_XINDIV2)) != 0)
1413		goto out;
1414
1415	/* We set XINDIV2 = 1, so IF = N/(2 * R) * XIN.  XIN = 44MHz.
1416	 * I choose N = 1496, R = 44 so that 1496/(2 * 44) * 44MHz = 748MHz.
1417	 */
1418	if ((rc = atw_si4126_write(sc, SI4126_IFN, 1496)) != 0)
1419		goto out;
1420
1421	if ((rc = atw_si4126_write(sc, SI4126_IFR, R)) != 0)
1422		goto out;
1423
1424	/* Set RF1 arbitrarily. DO NOT configure RF1 after RF2, because
1425	 * then RF1 becomes the active RF synthesizer, even on the Si4126,
1426	 * which has no RF1!
1427	 */
1428	if ((rc = atw_si4126_write(sc, SI4126_RF1R, R)) != 0)
1429		goto out;
1430
1431	if ((rc = atw_si4126_write(sc, SI4126_RF1N, mhz - 374)) != 0)
1432		goto out;
1433
1434	/* N/R * XIN = RF. XIN = 44MHz. We desire RF = mhz - IF,
1435	 * where IF = 374MHz.  Let's divide XIN to 1MHz. So R = 44.
1436	 * Now let's multiply it to mhz. So mhz - IF = N.
1437	 */
1438	if ((rc = atw_si4126_write(sc, SI4126_RF2R, R)) != 0)
1439		goto out;
1440
1441	if ((rc = atw_si4126_write(sc, SI4126_RF2N, mhz - 374)) != 0)
1442		goto out;
1443
1444	/* wait 100us from power-up for RF, IF to settle */
1445	DELAY(100);
1446
1447	if ((sc->sc_if.if_flags & IFF_LINK1) == 0 || chan == 14) {
1448		/* XXX there is a binary driver which sends
1449		 * ATW_GPIO_EN_MASK = 1, ATW_GPIO_O_MASK = 1. I had speculated
1450		 * that this enables the Si4126 by raising its PWDN#, but I
1451		 * think that it actually sets the Prism RF front-end
1452		 * to a special mode for channel 14.
1453		 */
1454		reg = ATW_READ(sc, ATW_GPIO);
1455		reg &= ~(ATW_GPIO_EN_MASK|ATW_GPIO_O_MASK|ATW_GPIO_I_MASK);
1456		reg |= LSHIFT(1, ATW_GPIO_EN_MASK) | LSHIFT(1, ATW_GPIO_O_MASK);
1457		ATW_WRITE(sc, ATW_GPIO, reg);
1458	}
1459
1460#ifdef ATW_DEBUG
1461	atw_si4126_print(sc);
1462#endif /* ATW_DEBUG */
1463
1464out:
1465	atw_rfio_enable(sc, 0);
1466
1467	return rc;
1468}
1469
1470/* Baseline initialization of RF3000 BBP: set CCA mode and enable antenna
1471 * diversity.
1472 *
1473 * Call this w/ Tx/Rx suspended.
1474 */
1475static int
1476atw_rf3000_init(struct atw_softc *sc)
1477{
1478	int rc = 0;
1479
1480	atw_idle(sc, ATW_NAR_SR|ATW_NAR_ST);
1481
1482	atw_rfio_enable(sc, 1);
1483
1484	/* enable diversity */
1485	rc = atw_rf3000_write(sc, RF3000_DIVCTL, RF3000_DIVCTL_ENABLE);
1486
1487	if (rc != 0)
1488		goto out;
1489
1490	/* sensible setting from a binary-only driver */
1491	rc = atw_rf3000_write(sc, RF3000_GAINCTL,
1492	    LSHIFT(0x1d, RF3000_GAINCTL_TXVGC_MASK));
1493
1494	if (rc != 0)
1495		goto out;
1496
1497	/* magic from a binary-only driver */
1498	rc = atw_rf3000_write(sc, RF3000_LOGAINCAL,
1499	    LSHIFT(0x38, RF3000_LOGAINCAL_CAL_MASK));
1500
1501	if (rc != 0)
1502		goto out;
1503
1504	rc = atw_rf3000_write(sc, RF3000_HIGAINCAL, RF3000_HIGAINCAL_DSSSPAD);
1505
1506	if (rc != 0)
1507		goto out;
1508
1509	rc = atw_rf3000_write(sc, RF3000_OPTIONS1, 0x0);
1510
1511	if (rc != 0)
1512		goto out;
1513
1514	rc = atw_rf3000_write(sc, RF3000_OPTIONS2, RF3000_OPTIONS2_LNAGS_DELAY);
1515
1516	if (rc != 0)
1517		goto out;
1518
1519	/* CCA is acquisition sensitive */
1520	rc = atw_rf3000_write(sc, RF3000_CCACTL,
1521	    LSHIFT(RF3000_CCACTL_MODE_ACQ, RF3000_CCACTL_MODE_MASK));
1522
1523	if (rc != 0)
1524		goto out;
1525
1526out:
1527	atw_rfio_enable(sc, 0);
1528	ATW_WRITE(sc, ATW_NAR, sc->sc_opmode);
1529	return rc;
1530}
1531
1532#ifdef ATW_DEBUG
1533static void
1534atw_rf3000_print(struct atw_softc *sc)
1535{
1536	struct ifnet *ifp = &sc->sc_ic.ic_if;
1537	u_int addr, val;
1538
1539	if (atw_debug < 3 || (ifp->if_flags & IFF_DEBUG) == 0)
1540		return;
1541
1542	for (addr = 0x01; addr <= 0x15; addr++) {
1543		printf("%s: bbp[%d] = \n", sc->sc_dev.dv_xname, addr);
1544		if (atw_rf3000_read(sc, addr, &val) != 0) {
1545			printf("<unknown> (quitting print-out)\n");
1546			break;
1547		}
1548		printf("%08x\n", val);
1549	}
1550}
1551#endif /* ATW_DEBUG */
1552
1553/* Set the power settings on the BBP for channel `chan'. */
1554static int
1555atw_rf3000_tune(struct atw_softc *sc, u_int8_t chan)
1556{
1557	int rc = 0;
1558	u_int32_t reg;
1559	u_int16_t txpower, lpf_cutoff, lna_gs_thresh;
1560
1561	txpower = sc->sc_srom[ATW_SR_TXPOWER(chan)];
1562	lpf_cutoff = sc->sc_srom[ATW_SR_LPF_CUTOFF(chan)];
1563	lna_gs_thresh = sc->sc_srom[ATW_SR_LNA_GS_THRESH(chan)];
1564
1565	/* odd channels: LSB, even channels: MSB */
1566	if (chan % 2 == 1) {
1567		txpower &= 0xFF;
1568		lpf_cutoff &= 0xFF;
1569		lna_gs_thresh &= 0xFF;
1570	} else {
1571		txpower >>= 8;
1572		lpf_cutoff >>= 8;
1573		lna_gs_thresh >>= 8;
1574	}
1575
1576#ifdef ATW_DEBUG
1577	atw_rf3000_print(sc);
1578#endif /* ATW_DEBUG */
1579
1580	DPRINTF(sc, ("%s: chan %d txpower %02x, lpf_cutoff %02x, "
1581	    "lna_gs_thresh %02x\n",
1582	    sc->sc_dev.dv_xname, chan, txpower, lpf_cutoff, lna_gs_thresh));
1583
1584	atw_rfio_enable(sc, 1);
1585
1586	if ((rc = atw_rf3000_write(sc, RF3000_GAINCTL,
1587	    LSHIFT(txpower, RF3000_GAINCTL_TXVGC_MASK))) != 0)
1588		goto out;
1589
1590	if ((rc = atw_rf3000_write(sc, RF3000_LOGAINCAL, lpf_cutoff)) != 0)
1591		goto out;
1592
1593	if ((rc = atw_rf3000_write(sc, RF3000_HIGAINCAL, lna_gs_thresh)) != 0)
1594		goto out;
1595
1596	/* from a binary-only driver. */
1597	reg = ATW_READ(sc, ATW_PLCPHD);
1598	reg &= ~ATW_PLCPHD_SERVICE_MASK;
1599	reg |= LSHIFT(LSHIFT(txpower, RF3000_GAINCTL_TXVGC_MASK),
1600	    ATW_PLCPHD_SERVICE_MASK);
1601	ATW_WRITE(sc, ATW_PLCPHD, reg);
1602
1603#ifdef ATW_DEBUG
1604	atw_rf3000_print(sc);
1605#endif /* ATW_DEBUG */
1606
1607out:
1608	atw_rfio_enable(sc, 0);
1609
1610	return rc;
1611}
1612
1613/* Write a register on the RF3000 baseband processor using the
1614 * registers provided by the ADM8211 for this purpose.
1615 *
1616 * Return 0 on success.
1617 */
1618static int
1619atw_rf3000_write(struct atw_softc *sc, u_int addr, u_int val)
1620{
1621	u_int32_t reg;
1622	int i;
1623
1624	for (i = 1000; --i >= 0; ) {
1625		if (ATW_ISSET(sc, ATW_BBPCTL, ATW_BBPCTL_RD|ATW_BBPCTL_WR) == 0)
1626			break;
1627		DELAY(100);
1628	}
1629
1630	if (i < 0) {
1631		printf("%s: BBPCTL busy (pre-write)\n", sc->sc_dev.dv_xname);
1632		return ETIMEDOUT;
1633	}
1634
1635	reg = sc->sc_bbpctl_wr |
1636	     LSHIFT(val & 0xff, ATW_BBPCTL_DATA_MASK) |
1637	     LSHIFT(addr & 0x7f, ATW_BBPCTL_ADDR_MASK);
1638
1639	ATW_WRITE(sc, ATW_BBPCTL, reg);
1640
1641	for (i = 1000; --i >= 0; ) {
1642		DELAY(100);
1643		if (ATW_ISSET(sc, ATW_BBPCTL, ATW_BBPCTL_WR) == 0)
1644			break;
1645	}
1646
1647	ATW_CLR(sc, ATW_BBPCTL, ATW_BBPCTL_WR);
1648
1649	if (i < 0) {
1650		printf("%s: BBPCTL busy (post-write)\n", sc->sc_dev.dv_xname);
1651		return ETIMEDOUT;
1652	}
1653	return 0;
1654}
1655
1656/* Read a register on the RF3000 baseband processor using the registers
1657 * the ADM8211 provides for this purpose.
1658 *
1659 * The 7-bit register address is addr.  Record the 8-bit data in the register
1660 * in *val.
1661 *
1662 * Return 0 on success.
1663 *
1664 * XXX This does not seem to work. The ADM8211 must require more or
1665 * different magic to read the chip than to write it. Possibly some
1666 * of the magic I have derived from a binary-only driver concerns
1667 * the "chip address" (see the RF3000 manual).
1668 */
1669#ifdef ATW_DEBUG
1670static int
1671atw_rf3000_read(struct atw_softc *sc, u_int addr, u_int *val)
1672{
1673	u_int32_t reg;
1674	int i;
1675
1676	for (i = 1000; --i >= 0; ) {
1677		if (ATW_ISSET(sc, ATW_BBPCTL, ATW_BBPCTL_RD|ATW_BBPCTL_WR) == 0)
1678			break;
1679		DELAY(100);
1680	}
1681
1682	if (i < 0) {
1683		printf("%s: start atw_rf3000_read, BBPCTL busy\n",
1684		    sc->sc_dev.dv_xname);
1685		return ETIMEDOUT;
1686	}
1687
1688	reg = sc->sc_bbpctl_rd | LSHIFT(addr & 0x7f, ATW_BBPCTL_ADDR_MASK);
1689
1690	ATW_WRITE(sc, ATW_BBPCTL, reg);
1691
1692	for (i = 1000; --i >= 0; ) {
1693		DELAY(100);
1694		if (ATW_ISSET(sc, ATW_BBPCTL, ATW_BBPCTL_RD) == 0)
1695			break;
1696	}
1697
1698	ATW_CLR(sc, ATW_BBPCTL, ATW_BBPCTL_RD);
1699
1700	if (i < 0) {
1701		printf("%s: atw_rf3000_read wrote %08x; BBPCTL still busy\n",
1702		    sc->sc_dev.dv_xname, reg);
1703		return ETIMEDOUT;
1704	}
1705	if (val != NULL)
1706		*val = MASK_AND_RSHIFT(reg, ATW_BBPCTL_DATA_MASK);
1707	return 0;
1708}
1709#endif /* ATW_DEBUG */
1710
1711/* Write a register on the Si4126 RF/IF synthesizer using the registers
1712 * provided by the ADM8211 for that purpose.
1713 *
1714 * val is 18 bits of data, and val is the 4-bit address of the register.
1715 *
1716 * Return 0 on success.
1717 */
1718static int
1719atw_si4126_write(struct atw_softc *sc, u_int addr, u_int val)
1720{
1721	u_int32_t bits, reg;
1722	int i;
1723
1724	KASSERT((addr & ~PRESHIFT(SI4126_TWI_ADDR_MASK)) == 0);
1725	KASSERT((val & ~PRESHIFT(SI4126_TWI_DATA_MASK)) == 0);
1726
1727	for (i = 1000; --i >= 0; ) {
1728		if (ATW_ISSET(sc, ATW_SYNCTL, ATW_SYNCTL_RD|ATW_SYNCTL_WR) == 0)
1729			break;
1730		DELAY(100);
1731	}
1732
1733	if (i < 0) {
1734		printf("%s: start atw_si4126_write, SYNCTL busy\n",
1735		    sc->sc_dev.dv_xname);
1736		return ETIMEDOUT;
1737	}
1738
1739	bits = LSHIFT(val, SI4126_TWI_DATA_MASK) |
1740	       LSHIFT(addr, SI4126_TWI_ADDR_MASK);
1741
1742	reg = sc->sc_synctl_wr | LSHIFT(bits, ATW_SYNCTL_DATA_MASK);
1743
1744	ATW_WRITE(sc, ATW_SYNCTL, reg);
1745
1746	for (i = 1000; --i >= 0; ) {
1747		DELAY(100);
1748		if (ATW_ISSET(sc, ATW_SYNCTL, ATW_SYNCTL_WR) == 0)
1749			break;
1750	}
1751
1752	/* restore to acceptable starting condition */
1753	ATW_CLR(sc, ATW_SYNCTL, ATW_SYNCTL_WR);
1754
1755	if (i < 0) {
1756		printf("%s: atw_si4126_write wrote %08x, SYNCTL still busy\n",
1757		    sc->sc_dev.dv_xname, reg);
1758		return ETIMEDOUT;
1759	}
1760	return 0;
1761}
1762
1763/* Read 18-bit data from the 4-bit address addr in Si4126
1764 * RF synthesizer and write the data to *val. Return 0 on success.
1765 *
1766 * XXX This does not seem to work. The ADM8211 must require more or
1767 * different magic to read the chip than to write it.
1768 */
1769#ifdef ATW_DEBUG
1770static int
1771atw_si4126_read(struct atw_softc *sc, u_int addr, u_int *val)
1772{
1773	u_int32_t reg;
1774	int i;
1775
1776	KASSERT((addr & ~PRESHIFT(SI4126_TWI_ADDR_MASK)) == 0);
1777
1778	for (i = 1000; --i >= 0; ) {
1779		if (ATW_ISSET(sc, ATW_SYNCTL, ATW_SYNCTL_RD|ATW_SYNCTL_WR) == 0)
1780			break;
1781		DELAY(100);
1782	}
1783
1784	if (i < 0) {
1785		printf("%s: start atw_si4126_read, SYNCTL busy\n",
1786		    sc->sc_dev.dv_xname);
1787		return ETIMEDOUT;
1788	}
1789
1790	reg = sc->sc_synctl_rd | LSHIFT(addr, ATW_SYNCTL_DATA_MASK);
1791
1792	ATW_WRITE(sc, ATW_SYNCTL, reg);
1793
1794	for (i = 1000; --i >= 0; ) {
1795		DELAY(100);
1796		if (ATW_ISSET(sc, ATW_SYNCTL, ATW_SYNCTL_RD) == 0)
1797			break;
1798	}
1799
1800	ATW_CLR(sc, ATW_SYNCTL, ATW_SYNCTL_RD);
1801
1802	if (i < 0) {
1803		printf("%s: atw_si4126_read wrote %08x, SYNCTL still busy\n",
1804		    sc->sc_dev.dv_xname, reg);
1805		return ETIMEDOUT;
1806	}
1807	if (val != NULL)
1808		*val = MASK_AND_RSHIFT(ATW_READ(sc, ATW_SYNCTL),
1809		                       ATW_SYNCTL_DATA_MASK);
1810	return 0;
1811}
1812#endif /* ATW_DEBUG */
1813
1814/* XXX is the endianness correct? test. */
1815#define	atw_calchash(addr) \
1816	(ether_crc32_le((addr), IEEE80211_ADDR_LEN) & BITS(5, 0))
1817
1818/*
1819 * atw_filter_setup:
1820 *
1821 *	Set the ADM8211's receive filter.
1822 */
1823static void
1824atw_filter_setup(struct atw_softc *sc)
1825{
1826	struct ieee80211com *ic = &sc->sc_ic;
1827	struct ethercom *ec = &ic->ic_ec;
1828	struct ifnet *ifp = &sc->sc_ic.ic_if;
1829	int hash;
1830	u_int32_t hashes[2] = { 0, 0 };
1831	struct ether_multi *enm;
1832	struct ether_multistep step;
1833
1834	DPRINTF(sc, ("%s: atw_filter_setup: sc_flags 0x%08x\n",
1835	    sc->sc_dev.dv_xname, sc->sc_flags));
1836
1837	/*
1838	 * If we're running, idle the receive engine.  If we're NOT running,
1839	 * we're being called from atw_init(), and our writing ATW_NAR will
1840	 * start the transmit and receive processes in motion.
1841	 */
1842	if (ifp->if_flags & IFF_RUNNING)
1843		atw_idle(sc, ATW_NAR_SR);
1844
1845	sc->sc_opmode &= ~(ATW_NAR_PR|ATW_NAR_MM);
1846
1847	ifp->if_flags &= ~IFF_ALLMULTI;
1848
1849	if (ifp->if_flags & IFF_PROMISC) {
1850		sc->sc_opmode |= ATW_NAR_PR;
1851allmulti:
1852		ifp->if_flags |= IFF_ALLMULTI;
1853		goto setit;
1854	}
1855
1856	/*
1857	 * Program the 64-bit multicast hash filter.
1858	 */
1859	ETHER_FIRST_MULTI(step, ec, enm);
1860	while (enm != NULL) {
1861		/* XXX */
1862		if (memcmp(enm->enm_addrlo, enm->enm_addrhi,
1863		    ETHER_ADDR_LEN) != 0)
1864			goto allmulti;
1865
1866		hash = atw_calchash(enm->enm_addrlo);
1867		hashes[hash >> 5] |= 1 << (hash & 0x1f);
1868		ETHER_NEXT_MULTI(step, enm);
1869	}
1870
1871	if (ifp->if_flags & IFF_BROADCAST) {
1872		hash = atw_calchash(etherbroadcastaddr);
1873		hashes[hash >> 5] |= 1 << (hash & 0x1f);
1874	}
1875
1876	/* all bits set => hash is useless */
1877	if (~(hashes[0] & hashes[1]) == 0)
1878		goto allmulti;
1879
1880 setit:
1881	if (ifp->if_flags & IFF_ALLMULTI)
1882		sc->sc_opmode |= ATW_NAR_MM;
1883
1884	/* XXX in scan mode, do not filter packets. maybe this is
1885	 * unnecessary.
1886	 */
1887	if (ic->ic_state == IEEE80211_S_SCAN)
1888		sc->sc_opmode |= ATW_NAR_PR;
1889
1890	ATW_WRITE(sc, ATW_MAR0, hashes[0]);
1891	ATW_WRITE(sc, ATW_MAR1, hashes[1]);
1892	ATW_WRITE(sc, ATW_NAR, sc->sc_opmode);
1893	DPRINTF(sc, ("%s: ATW_NAR %08x opmode %08x\n", sc->sc_dev.dv_xname,
1894	    ATW_READ(sc, ATW_NAR), sc->sc_opmode));
1895
1896	DPRINTF(sc, ("%s: atw_filter_setup: returning\n", sc->sc_dev.dv_xname));
1897}
1898
1899/* Tell the ADM8211 our preferred BSSID. The ADM8211 must match
1900 * a beacon's BSSID and SSID against the preferred BSSID and SSID
1901 * before it will raise ATW_INTR_LINKON. When the ADM8211 receives
1902 * no beacon with the preferred BSSID and SSID in the number of
1903 * beacon intervals given in ATW_BPLI, then it raises ATW_INTR_LINKOFF.
1904 */
1905static void
1906atw_write_bssid(struct atw_softc *sc)
1907{
1908	struct ieee80211com *ic = &sc->sc_ic;
1909	u_int8_t *bssid;
1910
1911	bssid = ic->ic_bss->ni_bssid;
1912
1913	ATW_WRITE(sc, ATW_ABDA1,
1914	    (ATW_READ(sc, ATW_ABDA1) &
1915	    ~(ATW_ABDA1_BSSIDB4_MASK|ATW_ABDA1_BSSIDB5_MASK)) |
1916	    LSHIFT(bssid[4], ATW_ABDA1_BSSIDB4_MASK) |
1917	    LSHIFT(bssid[5], ATW_ABDA1_BSSIDB5_MASK));
1918
1919	ATW_WRITE(sc, ATW_BSSID0,
1920	    LSHIFT(bssid[0], ATW_BSSID0_BSSIDB0_MASK) |
1921	    LSHIFT(bssid[1], ATW_BSSID0_BSSIDB1_MASK) |
1922	    LSHIFT(bssid[2], ATW_BSSID0_BSSIDB2_MASK) |
1923	    LSHIFT(bssid[3], ATW_BSSID0_BSSIDB3_MASK));
1924
1925	DPRINTF(sc, ("%s: BSSID %s -> ", sc->sc_dev.dv_xname,
1926	    ether_sprintf(sc->sc_bssid)));
1927	DPRINTF(sc, ("%s\n", ether_sprintf(bssid)));
1928
1929	memcpy(sc->sc_bssid, bssid, sizeof(sc->sc_bssid));
1930}
1931
1932/* Tell the ADM8211 how many beacon intervals must pass without
1933 * receiving a beacon with the preferred BSSID & SSID set by
1934 * atw_write_bssid and atw_write_ssid before ATW_INTR_LINKOFF
1935 * raised.
1936 */
1937static void
1938atw_write_bcn_thresh(struct atw_softc *sc)
1939{
1940	struct ieee80211com *ic = &sc->sc_ic;
1941	int lost_bcn_thresh;
1942
1943	/* Lose link after one second or 7 beacons, whichever comes
1944	 * first, but do not lose link before 2 beacons are lost.
1945	 *
1946	 * In host AP mode, set the lost-beacon threshold to 0.
1947	 */
1948	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1949		lost_bcn_thresh = 0;
1950	else {
1951		int beacons_per_second =
1952		    1000000 / (IEEE80211_DUR_TU * MAX(1,ic->ic_bss->ni_intval));
1953		lost_bcn_thresh = MAX(2, MIN(7, beacons_per_second));
1954	}
1955
1956	/* XXX resets wake-up status bits */
1957	ATW_WRITE(sc, ATW_WCSR,
1958	    (ATW_READ(sc, ATW_WCSR) & ~ATW_WCSR_BLN_MASK) |
1959	    (LSHIFT(lost_bcn_thresh, ATW_WCSR_BLN_MASK) & ATW_WCSR_BLN_MASK));
1960
1961	DPRINTF(sc, ("%s: lost-beacon threshold %d -> %d\n",
1962	    sc->sc_dev.dv_xname, sc->sc_lost_bcn_thresh, lost_bcn_thresh));
1963
1964	sc->sc_lost_bcn_thresh = lost_bcn_thresh;
1965
1966	DPRINTF(sc, ("%s: atw_write_bcn_thresh reg[WCSR] = %08x\n",
1967	    sc->sc_dev.dv_xname, ATW_READ(sc, ATW_WCSR)));
1968}
1969
1970/* Write buflen bytes from buf to SRAM starting at the SRAM's ofs'th
1971 * 16-bit word.
1972 */
1973static void
1974atw_write_sram(struct atw_softc *sc, u_int ofs, u_int8_t *buf, u_int buflen)
1975{
1976	u_int i;
1977	u_int8_t *ptr;
1978
1979	memcpy(&sc->sc_sram[ofs], buf, buflen);
1980
1981	if (ofs % 2 != 0) {
1982		ofs--;
1983		buflen++;
1984	}
1985
1986	if (buflen % 2 != 0)
1987		buflen++;
1988
1989	assert(buflen + ofs <= ATW_SRAM_SIZE);
1990
1991	ptr = &sc->sc_sram[ofs];
1992
1993	for (i = 0; i < buflen; i += 2) {
1994		ATW_WRITE(sc, ATW_WEPCTL, ATW_WEPCTL_WR |
1995		    LSHIFT((ofs + i) / 2, ATW_WEPCTL_TBLADD_MASK));
1996		DELAY(atw_writewep_delay);
1997
1998		ATW_WRITE(sc, ATW_WESK,
1999		    LSHIFT((ptr[i + 1] << 8) | ptr[i], ATW_WESK_DATA_MASK));
2000		DELAY(atw_writewep_delay);
2001	}
2002	ATW_WRITE(sc, ATW_WEPCTL, sc->sc_wepctl); /* restore WEP condition */
2003
2004	if (sc->sc_if.if_flags & IFF_DEBUG) {
2005		int n_octets = 0;
2006		printf("%s: wrote %d bytes at 0x%x wepctl 0x%08x\n",
2007		    sc->sc_dev.dv_xname, buflen, ofs, sc->sc_wepctl);
2008		for (i = 0; i < buflen; i++) {
2009			printf(" %02x", ptr[i]);
2010			if (++n_octets % 24 == 0)
2011				printf("\n");
2012		}
2013		if (n_octets % 24 != 0)
2014			printf("\n");
2015	}
2016}
2017
2018/* Write WEP keys from the ieee80211com to the ADM8211's SRAM. */
2019static void
2020atw_write_wep(struct atw_softc *sc)
2021{
2022	struct ieee80211com *ic = &sc->sc_ic;
2023	/* SRAM shared-key record format: key0 flags key1 ... key12 */
2024	u_int8_t buf[IEEE80211_WEP_NKID]
2025	            [1 /* key[0] */ + 1 /* flags */ + 12 /* key[1 .. 12] */];
2026	u_int32_t reg;
2027	int i;
2028
2029	sc->sc_wepctl = 0;
2030	ATW_WRITE(sc, ATW_WEPCTL, sc->sc_wepctl);
2031
2032	if ((ic->ic_flags & IEEE80211_F_WEPON) == 0)
2033		return;
2034
2035	memset(&buf[0][0], 0, sizeof(buf));
2036
2037	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
2038		if (ic->ic_nw_keys[i].wk_len > 5) {
2039			buf[i][1] = ATW_WEP_ENABLED | ATW_WEP_104BIT;
2040		} else if (ic->ic_nw_keys[i].wk_len != 0) {
2041			buf[i][1] = ATW_WEP_ENABLED;
2042		} else {
2043			buf[i][1] = 0;
2044			continue;
2045		}
2046		buf[i][0] = ic->ic_nw_keys[i].wk_key[0];
2047		memcpy(&buf[i][2], &ic->ic_nw_keys[i].wk_key[1],
2048		    ic->ic_nw_keys[i].wk_len - 1);
2049	}
2050
2051	reg = ATW_READ(sc, ATW_MACTEST);
2052	reg |= ATW_MACTEST_MMI_USETXCLK | ATW_MACTEST_FORCE_KEYID;
2053	reg &= ~ATW_MACTEST_KEYID_MASK;
2054	reg |= LSHIFT(ic->ic_wep_txkey, ATW_MACTEST_KEYID_MASK);
2055	ATW_WRITE(sc, ATW_MACTEST, reg);
2056
2057	/* RX bypass WEP if revision != 0x20. (I assume revision != 0x20
2058	 * throughout.)
2059	 */
2060	sc->sc_wepctl = ATW_WEPCTL_WEPENABLE | ATW_WEPCTL_WEPRXBYP;
2061	if (sc->sc_if.if_flags & IFF_LINK2)
2062		sc->sc_wepctl &= ~ATW_WEPCTL_WEPRXBYP;
2063
2064	atw_write_sram(sc, ATW_SRAM_ADDR_SHARED_KEY, (u_int8_t*)&buf[0][0],
2065	    sizeof(buf));
2066}
2067
2068const struct timeval atw_beacon_mininterval = {1, 0}; /* 1s */
2069
2070static void
2071atw_recv_mgmt(struct ieee80211com *ic, struct mbuf *m,
2072    struct ieee80211_node *ni, int subtype, int rssi, u_int32_t rstamp)
2073{
2074	struct atw_softc *sc = (struct atw_softc*)ic->ic_softc;
2075
2076	switch (subtype) {
2077	case IEEE80211_FC0_SUBTYPE_PROBE_REQ:
2078		/* do nothing: hardware answers probe request */
2079		break;
2080	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
2081	case IEEE80211_FC0_SUBTYPE_BEACON:
2082		atw_recv_beacon(ic, m, ni, subtype, rssi, rstamp);
2083		break;
2084	default:
2085		(*sc->sc_recv_mgmt)(ic, m, ni, subtype, rssi, rstamp);
2086		break;
2087	}
2088	return;
2089}
2090
2091/* In ad hoc mode, atw_recv_beacon is responsible for the coalescence
2092 * of IBSSs with like SSID/channel but different BSSID. It joins the
2093 * oldest IBSS (i.e., with greatest TSF time), since that is the WECA
2094 * convention. Possibly the ADMtek chip does this for us; I will have
2095 * to test to find out.
2096 *
2097 * XXX we should add the duration field of the received beacon to
2098 * the TSF time it contains before comparing it with the ADM8211's
2099 * TSF.
2100 */
2101static void
2102atw_recv_beacon(struct ieee80211com *ic, struct mbuf *m0,
2103    struct ieee80211_node *ni, int subtype, int rssi, u_int32_t rstamp)
2104{
2105	struct atw_softc *sc;
2106	struct ieee80211_frame *wh;
2107	u_int64_t tsft, bcn_tsft;
2108	u_int32_t tsftl, tsfth;
2109	int do_print = 0;
2110
2111	sc = (struct atw_softc*)ic->ic_if.if_softc;
2112
2113	if (ic->ic_if.if_flags & IFF_DEBUG)
2114		do_print = (ic->ic_if.if_flags & IFF_LINK0)
2115		    ? 1 : ratecheck(&sc->sc_last_beacon,
2116		    &atw_beacon_mininterval);
2117
2118	wh = mtod(m0, struct ieee80211_frame *);
2119
2120	(*sc->sc_recv_mgmt)(ic, m0, ni, subtype, rssi, rstamp);
2121
2122	if (ic->ic_state != IEEE80211_S_RUN) {
2123		if (do_print)
2124			printf("%s: atw_recv_beacon: not running\n",
2125			    sc->sc_dev.dv_xname);
2126		return;
2127	}
2128
2129	if ((ni = ieee80211_lookup_node(ic, wh->i_addr2,
2130	    ic->ic_bss->ni_chan)) == NULL) {
2131		if (do_print)
2132			printf("%s: atw_recv_beacon: no node %s\n",
2133			    sc->sc_dev.dv_xname, ether_sprintf(wh->i_addr2));
2134		return;
2135	}
2136
2137	if (ieee80211_match_bss(ic, ni) != 0) {
2138		if (do_print)
2139			printf("%s: atw_recv_beacon: ssid mismatch %s\n",
2140			    sc->sc_dev.dv_xname, ether_sprintf(wh->i_addr2));
2141		return;
2142	}
2143
2144	if (memcmp(ni->ni_bssid, ic->ic_bss->ni_bssid, IEEE80211_ADDR_LEN) == 0)
2145		return;
2146
2147	if (do_print)
2148		printf("%s: atw_recv_beacon: bssid mismatch %s\n",
2149		    sc->sc_dev.dv_xname, ether_sprintf(ni->ni_bssid));
2150
2151	if (ic->ic_opmode != IEEE80211_M_IBSS)
2152		return;
2153
2154	/* If we read TSFTL right before rollover, we read a TSF timer
2155	 * that is too high rather than too low. This prevents a spurious
2156	 * synchronization down the line, however, our IBSS could suffer
2157	 * from a creeping TSF....
2158	 */
2159	tsftl = ATW_READ(sc, ATW_TSFTL);
2160	tsfth = ATW_READ(sc, ATW_TSFTH);
2161
2162	tsft = (u_int64_t)tsfth << 32 | tsftl;
2163	bcn_tsft = le64toh(*(u_int64_t*)ni->ni_tstamp);
2164
2165	if (do_print)
2166		printf("%s: my tsft %" PRIu64 " beacon tsft %" PRIu64 "\n",
2167		    sc->sc_dev.dv_xname, tsft, bcn_tsft);
2168
2169	/* we are faster, let the other guy catch up */
2170	if (bcn_tsft < tsft)
2171		return;
2172
2173	if (do_print)
2174		printf("%s: sync TSF with %s\n", sc->sc_dev.dv_xname,
2175		    ether_sprintf(wh->i_addr2));
2176
2177	ic->ic_flags &= ~IEEE80211_F_SIBSS;
2178
2179#if 0
2180	atw_tsf(sc);
2181#endif
2182
2183	/* negotiate rates with new IBSS */
2184	ieee80211_fix_rate(ic, ni, IEEE80211_F_DOFRATE |
2185	    IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
2186	if (ni->ni_rates.rs_nrates == 0) {
2187		printf("%s: rates mismatch, BSSID %s\n", sc->sc_dev.dv_xname,
2188			ether_sprintf(ni->ni_bssid));
2189		return;
2190	}
2191
2192	if (do_print) {
2193		printf("%s: sync BSSID %s -> ", sc->sc_dev.dv_xname,
2194		    ether_sprintf(ic->ic_bss->ni_bssid));
2195		printf("%s ", ether_sprintf(ni->ni_bssid));
2196		printf("(from %s)\n", ether_sprintf(wh->i_addr2));
2197	}
2198
2199	(*ic->ic_node_copy)(ic, ic->ic_bss, ni);
2200
2201	atw_write_bssid(sc);
2202	atw_write_bcn_thresh(sc);
2203	atw_start_beacon(sc, 1);
2204}
2205
2206/* Write the SSID in the ieee80211com to the SRAM on the ADM8211.
2207 * In ad hoc mode, the SSID is written to the beacons sent by the
2208 * ADM8211. In both ad hoc and infrastructure mode, beacons received
2209 * with matching SSID affect ATW_INTR_LINKON/ATW_INTR_LINKOFF
2210 * indications.
2211 */
2212static void
2213atw_write_ssid(struct atw_softc *sc)
2214{
2215	struct ieee80211com *ic = &sc->sc_ic;
2216	/* 34 bytes are reserved in ADM8211 SRAM for the SSID */
2217	u_int8_t buf[roundup(1 /* length */ + IEEE80211_NWID_LEN, 2)];
2218
2219	memset(buf, 0, sizeof(buf));
2220	buf[0] = ic->ic_bss->ni_esslen;
2221	memcpy(&buf[1], ic->ic_bss->ni_essid, ic->ic_bss->ni_esslen);
2222
2223	atw_write_sram(sc, ATW_SRAM_ADDR_SSID, buf, sizeof(buf));
2224}
2225
2226/* Write the supported rates in the ieee80211com to the SRAM of the ADM8211.
2227 * In ad hoc mode, the supported rates are written to beacons sent by the
2228 * ADM8211.
2229 */
2230static void
2231atw_write_sup_rates(struct atw_softc *sc)
2232{
2233	struct ieee80211com *ic = &sc->sc_ic;
2234	/* 14 bytes are probably (XXX) reserved in the ADM8211 SRAM for
2235	 * supported rates
2236	 */
2237	u_int8_t buf[roundup(1 /* length */ + IEEE80211_RATE_SIZE, 2)];
2238
2239	memset(buf, 0, sizeof(buf));
2240
2241	buf[0] = ic->ic_bss->ni_rates.rs_nrates;
2242
2243	memcpy(&buf[1], ic->ic_bss->ni_rates.rs_rates,
2244	    ic->ic_bss->ni_rates.rs_nrates);
2245
2246	atw_write_sram(sc, ATW_SRAM_ADDR_SUPRATES, buf, sizeof(buf));
2247}
2248
2249/* Start/stop sending beacons. */
2250void
2251atw_start_beacon(struct atw_softc *sc, int start)
2252{
2253	struct ieee80211com *ic = &sc->sc_ic;
2254	u_int32_t len, capinfo, reg_bcnt, reg_cap1;
2255
2256	if (ATW_IS_ENABLED(sc) == 0)
2257		return;
2258
2259	len = capinfo = 0;
2260
2261	/* start beacons */
2262	len = sizeof(struct ieee80211_frame) +
2263	    8 /* timestamp */ + 2 /* beacon interval */ +
2264	    2 /* capability info */ +
2265	    2 + ic->ic_bss->ni_esslen /* SSID element */ +
2266	    2 + ic->ic_bss->ni_rates.rs_nrates /* rates element */ +
2267	    3 /* DS parameters */ +
2268	    IEEE80211_CRC_LEN;
2269
2270	reg_bcnt = ATW_READ(sc, ATW_BCNT) & ~ATW_BCNT_BCNT_MASK;
2271
2272	reg_cap1 = ATW_READ(sc, ATW_CAP1) & ~ATW_CAP1_CAPI_MASK;
2273
2274	ATW_WRITE(sc, ATW_BCNT, reg_bcnt);
2275	ATW_WRITE(sc, ATW_CAP1, reg_cap1);
2276
2277	if (!start)
2278		return;
2279
2280	/* TBD use ni_capinfo */
2281
2282	if (sc->sc_flags & ATWF_SHORT_PREAMBLE)
2283		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
2284	if (ic->ic_flags & IEEE80211_F_WEPON)
2285		capinfo |= IEEE80211_CAPINFO_PRIVACY;
2286
2287	switch (ic->ic_opmode) {
2288	case IEEE80211_M_IBSS:
2289		len += 4; /* IBSS parameters */
2290		capinfo |= IEEE80211_CAPINFO_IBSS;
2291		break;
2292	case IEEE80211_M_HOSTAP:
2293		/* XXX 6-byte minimum TIM */
2294		len += atw_beacon_len_adjust;
2295		capinfo |= IEEE80211_CAPINFO_ESS;
2296		break;
2297	default:
2298		return;
2299	}
2300
2301	reg_bcnt |= LSHIFT(len, ATW_BCNT_BCNT_MASK);
2302	reg_cap1 |= LSHIFT(capinfo, ATW_CAP1_CAPI_MASK);
2303
2304	ATW_WRITE(sc, ATW_BCNT, reg_bcnt);
2305	ATW_WRITE(sc, ATW_CAP1, reg_cap1);
2306
2307	DPRINTF(sc, ("%s: atw_start_beacon reg[ATW_BCNT] = %08x\n",
2308	    sc->sc_dev.dv_xname, reg_bcnt));
2309
2310	DPRINTF(sc, ("%s: atw_start_beacon reg[ATW_CAP1] = %08x\n",
2311	    sc->sc_dev.dv_xname, reg_cap1));
2312}
2313
2314/* First beacon was sent at time 0 microseconds, current time is
2315 * tsfth << 32 | tsftl microseconds, and beacon interval is tbtt
2316 * microseconds.  Return the expected time in microseconds for the
2317 * beacon after next.
2318 */
2319static __inline u_int64_t
2320atw_predict_beacon(u_int64_t tsft, u_int32_t tbtt)
2321{
2322	return tsft + (tbtt - tsft % tbtt);
2323}
2324
2325/* If we've created an IBSS, write the TSF time in the ADM8211 to
2326 * the ieee80211com.
2327 *
2328 * Predict the next target beacon transmission time (TBTT) and
2329 * write it to the ADM8211.
2330 */
2331static void
2332atw_tsf(struct atw_softc *sc)
2333{
2334#define TBTTOFS 20 /* TU */
2335
2336	struct ieee80211com *ic = &sc->sc_ic;
2337	u_int64_t tsft, tbtt;
2338
2339	if ((ic->ic_opmode == IEEE80211_M_HOSTAP) ||
2340	    ((ic->ic_opmode == IEEE80211_M_IBSS) &&
2341	     (ic->ic_flags & IEEE80211_F_SIBSS))) {
2342		tsft = ATW_READ(sc, ATW_TSFTH);
2343		tsft <<= 32;
2344		tsft |= ATW_READ(sc, ATW_TSFTL);
2345		*(u_int64_t*)&ic->ic_bss->ni_tstamp[0] = htole64(tsft);
2346	} else
2347		tsft = le64toh(*(u_int64_t*)&ic->ic_bss->ni_tstamp[0]);
2348
2349	tbtt = atw_predict_beacon(tsft,
2350	    ic->ic_bss->ni_intval * IEEE80211_DUR_TU);
2351
2352	/* skip one more beacon so that the TBTT cannot pass before
2353	 * we've programmed it, and also so that we can subtract a
2354	 * few TU so that we wake a little before TBTT.
2355	 */
2356	tbtt += ic->ic_bss->ni_intval * IEEE80211_DUR_TU;
2357
2358	/* wake up a little early */
2359	tbtt -= TBTTOFS * IEEE80211_DUR_TU;
2360
2361	DPRINTF(sc, ("%s: tsft %" PRIu64 " tbtt %" PRIu64 "\n",
2362	    sc->sc_dev.dv_xname, tsft, tbtt));
2363
2364	ATW_WRITE(sc, ATW_TOFS1,
2365	    LSHIFT(1, ATW_TOFS1_TSFTOFSR_MASK) |
2366	    LSHIFT(TBTTOFS, ATW_TOFS1_TBTTOFS_MASK) |
2367	    LSHIFT(
2368		MASK_AND_RSHIFT((u_int32_t)tbtt, BITS(25, 10)),
2369		ATW_TOFS1_TBTTPRE_MASK));
2370#undef TBTTOFS
2371}
2372
2373static void
2374atw_next_scan(void *arg)
2375{
2376	struct atw_softc *sc = arg;
2377	struct ieee80211com *ic = &sc->sc_ic;
2378	struct ifnet *ifp = &ic->ic_if;
2379	int s;
2380
2381	/* don't call atw_start w/o network interrupts blocked */
2382	s = splnet();
2383	if (ic->ic_state == IEEE80211_S_SCAN)
2384		ieee80211_next_scan(ifp);
2385	splx(s);
2386}
2387
2388/* Synchronize the hardware state with the software state. */
2389static int
2390atw_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
2391{
2392	struct ifnet *ifp = &ic->ic_if;
2393	struct atw_softc *sc = ifp->if_softc;
2394	enum ieee80211_state ostate;
2395	int error;
2396
2397	ostate = ic->ic_state;
2398
2399	if (nstate == IEEE80211_S_INIT) {
2400		callout_stop(&sc->sc_scan_ch);
2401		sc->sc_cur_chan = IEEE80211_CHAN_ANY;
2402		atw_start_beacon(sc, 0);
2403		return (*sc->sc_newstate)(ic, nstate, arg);
2404	}
2405
2406	if ((error = atw_tune(sc)) != 0)
2407		return error;
2408
2409	switch (nstate) {
2410	case IEEE80211_S_ASSOC:
2411		break;
2412	case IEEE80211_S_INIT:
2413		panic("%s: unexpected state IEEE80211_S_INIT\n", __func__);
2414		break;
2415	case IEEE80211_S_SCAN:
2416		memset(sc->sc_bssid, 0, IEEE80211_ADDR_LEN);
2417		atw_write_bssid(sc);
2418
2419		callout_reset(&sc->sc_scan_ch, atw_dwelltime * hz / 1000,
2420		    atw_next_scan, sc);
2421
2422		break;
2423	case IEEE80211_S_RUN:
2424		if (ic->ic_opmode == IEEE80211_M_STA)
2425			break;
2426		/*FALLTHROUGH*/
2427	case IEEE80211_S_AUTH:
2428		atw_write_bssid(sc);
2429		atw_write_bcn_thresh(sc);
2430		atw_write_ssid(sc);
2431		atw_write_sup_rates(sc);
2432
2433		if (ic->ic_opmode == IEEE80211_M_AHDEMO ||
2434		    ic->ic_opmode == IEEE80211_M_MONITOR)
2435			break;
2436
2437		/* set listen interval
2438		 * XXX do software units agree w/ hardware?
2439		 */
2440		ATW_WRITE(sc, ATW_BPLI,
2441		    LSHIFT(ic->ic_bss->ni_intval, ATW_BPLI_BP_MASK) |
2442		    LSHIFT(ic->ic_lintval / ic->ic_bss->ni_intval,
2443			   ATW_BPLI_LI_MASK));
2444
2445		DPRINTF(sc, ("%s: reg[ATW_BPLI] = %08x\n",
2446		    sc->sc_dev.dv_xname, ATW_READ(sc, ATW_BPLI)));
2447
2448		atw_tsf(sc);
2449		break;
2450	}
2451
2452	if (nstate != IEEE80211_S_SCAN)
2453		callout_stop(&sc->sc_scan_ch);
2454
2455	if (nstate == IEEE80211_S_RUN &&
2456	    (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2457	     ic->ic_opmode == IEEE80211_M_IBSS))
2458		atw_start_beacon(sc, 1);
2459	else
2460		atw_start_beacon(sc, 0);
2461
2462	return (*sc->sc_newstate)(ic, nstate, arg);
2463}
2464
2465/*
2466 * atw_add_rxbuf:
2467 *
2468 *	Add a receive buffer to the indicated descriptor.
2469 */
2470int
2471atw_add_rxbuf(struct atw_softc *sc, int idx)
2472{
2473	struct atw_rxsoft *rxs = &sc->sc_rxsoft[idx];
2474	struct mbuf *m;
2475	int error;
2476
2477	MGETHDR(m, M_DONTWAIT, MT_DATA);
2478	if (m == NULL)
2479		return (ENOBUFS);
2480
2481	MCLGET(m, M_DONTWAIT);
2482	if ((m->m_flags & M_EXT) == 0) {
2483		m_freem(m);
2484		return (ENOBUFS);
2485	}
2486
2487	if (rxs->rxs_mbuf != NULL)
2488		bus_dmamap_unload(sc->sc_dmat, rxs->rxs_dmamap);
2489
2490	rxs->rxs_mbuf = m;
2491
2492	error = bus_dmamap_load(sc->sc_dmat, rxs->rxs_dmamap,
2493	    m->m_ext.ext_buf, m->m_ext.ext_size, NULL,
2494	    BUS_DMA_READ|BUS_DMA_NOWAIT);
2495	if (error) {
2496		printf("%s: can't load rx DMA map %d, error = %d\n",
2497		    sc->sc_dev.dv_xname, idx, error);
2498		panic("atw_add_rxbuf");	/* XXX */
2499	}
2500
2501	bus_dmamap_sync(sc->sc_dmat, rxs->rxs_dmamap, 0,
2502	    rxs->rxs_dmamap->dm_mapsize, BUS_DMASYNC_PREREAD);
2503
2504	ATW_INIT_RXDESC(sc, idx);
2505
2506	return (0);
2507}
2508
2509/*
2510 * Release any queued transmit buffers.
2511 */
2512void
2513atw_txdrain(struct atw_softc *sc)
2514{
2515	struct atw_txsoft *txs;
2516
2517	while ((txs = SIMPLEQ_FIRST(&sc->sc_txdirtyq)) != NULL) {
2518		SIMPLEQ_REMOVE_HEAD(&sc->sc_txdirtyq, txs_q);
2519		if (txs->txs_mbuf != NULL) {
2520			bus_dmamap_unload(sc->sc_dmat, txs->txs_dmamap);
2521			m_freem(txs->txs_mbuf);
2522			txs->txs_mbuf = NULL;
2523		}
2524		SIMPLEQ_INSERT_TAIL(&sc->sc_txfreeq, txs, txs_q);
2525	}
2526	sc->sc_tx_timer = 0;
2527}
2528
2529/*
2530 * atw_stop:		[ ifnet interface function ]
2531 *
2532 *	Stop transmission on the interface.
2533 */
2534void
2535atw_stop(struct ifnet *ifp, int disable)
2536{
2537	struct atw_softc *sc = ifp->if_softc;
2538	struct ieee80211com *ic = &sc->sc_ic;
2539
2540	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
2541
2542	/* Disable interrupts. */
2543	ATW_WRITE(sc, ATW_IER, 0);
2544
2545	/* Stop the transmit and receive processes. */
2546	sc->sc_opmode = 0;
2547	ATW_WRITE(sc, ATW_NAR, 0);
2548	ATW_WRITE(sc, ATW_TDBD, 0);
2549	ATW_WRITE(sc, ATW_TDBP, 0);
2550	ATW_WRITE(sc, ATW_RDB, 0);
2551
2552	atw_txdrain(sc);
2553
2554	if (disable) {
2555		atw_rxdrain(sc);
2556		atw_disable(sc);
2557	}
2558
2559	/*
2560	 * Mark the interface down and cancel the watchdog timer.
2561	 */
2562	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2563	ifp->if_timer = 0;
2564
2565	if (!disable)
2566		atw_reset(sc);
2567}
2568
2569/*
2570 * atw_rxdrain:
2571 *
2572 *	Drain the receive queue.
2573 */
2574void
2575atw_rxdrain(struct atw_softc *sc)
2576{
2577	struct atw_rxsoft *rxs;
2578	int i;
2579
2580	for (i = 0; i < ATW_NRXDESC; i++) {
2581		rxs = &sc->sc_rxsoft[i];
2582		if (rxs->rxs_mbuf == NULL)
2583			continue;
2584		bus_dmamap_unload(sc->sc_dmat, rxs->rxs_dmamap);
2585		m_freem(rxs->rxs_mbuf);
2586		rxs->rxs_mbuf = NULL;
2587	}
2588}
2589
2590/*
2591 * atw_detach:
2592 *
2593 *	Detach an ADM8211 interface.
2594 */
2595int
2596atw_detach(struct atw_softc *sc)
2597{
2598	struct ifnet *ifp = &sc->sc_ic.ic_if;
2599	struct atw_rxsoft *rxs;
2600	struct atw_txsoft *txs;
2601	int i;
2602
2603	/*
2604	 * Succeed now if there isn't any work to do.
2605	 */
2606	if ((sc->sc_flags & ATWF_ATTACHED) == 0)
2607		return (0);
2608
2609	ieee80211_ifdetach(ifp);
2610	if_detach(ifp);
2611
2612	for (i = 0; i < ATW_NRXDESC; i++) {
2613		rxs = &sc->sc_rxsoft[i];
2614		if (rxs->rxs_mbuf != NULL) {
2615			bus_dmamap_unload(sc->sc_dmat, rxs->rxs_dmamap);
2616			m_freem(rxs->rxs_mbuf);
2617			rxs->rxs_mbuf = NULL;
2618		}
2619		bus_dmamap_destroy(sc->sc_dmat, rxs->rxs_dmamap);
2620	}
2621	for (i = 0; i < ATW_TXQUEUELEN; i++) {
2622		txs = &sc->sc_txsoft[i];
2623		if (txs->txs_mbuf != NULL) {
2624			bus_dmamap_unload(sc->sc_dmat, txs->txs_dmamap);
2625			m_freem(txs->txs_mbuf);
2626			txs->txs_mbuf = NULL;
2627		}
2628		bus_dmamap_destroy(sc->sc_dmat, txs->txs_dmamap);
2629	}
2630	bus_dmamap_unload(sc->sc_dmat, sc->sc_cddmamap);
2631	bus_dmamap_destroy(sc->sc_dmat, sc->sc_cddmamap);
2632	bus_dmamem_unmap(sc->sc_dmat, (caddr_t)sc->sc_control_data,
2633	    sizeof(struct atw_control_data));
2634	bus_dmamem_free(sc->sc_dmat, &sc->sc_cdseg, sc->sc_cdnseg);
2635
2636	shutdownhook_disestablish(sc->sc_sdhook);
2637	powerhook_disestablish(sc->sc_powerhook);
2638
2639	if (sc->sc_srom)
2640		free(sc->sc_srom, M_DEVBUF);
2641
2642	return (0);
2643}
2644
2645/* atw_shutdown: make sure the interface is stopped at reboot time. */
2646void
2647atw_shutdown(void *arg)
2648{
2649	struct atw_softc *sc = arg;
2650
2651	atw_stop(&sc->sc_ic.ic_if, 1);
2652}
2653
2654int
2655atw_intr(void *arg)
2656{
2657	struct atw_softc *sc = arg;
2658	struct ifnet *ifp = &sc->sc_ic.ic_if;
2659	u_int32_t status, rxstatus, txstatus, linkstatus;
2660	int handled = 0, txthresh;
2661
2662#ifdef DEBUG
2663	if (ATW_IS_ENABLED(sc) == 0)
2664		panic("%s: atw_intr: not enabled", sc->sc_dev.dv_xname);
2665#endif
2666
2667	/*
2668	 * If the interface isn't running, the interrupt couldn't
2669	 * possibly have come from us.
2670	 */
2671	if ((ifp->if_flags & IFF_RUNNING) == 0 ||
2672	    (sc->sc_dev.dv_flags & DVF_ACTIVE) == 0)
2673		return (0);
2674
2675	for (;;) {
2676		status = ATW_READ(sc, ATW_STSR);
2677
2678		if (status)
2679			ATW_WRITE(sc, ATW_STSR, status);
2680
2681		if (sc->sc_intr_ack != NULL)
2682			(*sc->sc_intr_ack)(sc);
2683
2684#ifdef ATW_DEBUG
2685#define PRINTINTR(flag) do { \
2686	if ((status & flag) != 0) { \
2687		printf("%s" #flag, delim); \
2688		delim = ","; \
2689	} \
2690} while (0)
2691
2692		if (atw_debug > 1 && status) {
2693			const char *delim = "<";
2694
2695			printf("%s: reg[STSR] = %x",
2696			    sc->sc_dev.dv_xname, status);
2697
2698			PRINTINTR(ATW_INTR_FBE);
2699			PRINTINTR(ATW_INTR_LINKOFF);
2700			PRINTINTR(ATW_INTR_LINKON);
2701			PRINTINTR(ATW_INTR_RCI);
2702			PRINTINTR(ATW_INTR_RDU);
2703			PRINTINTR(ATW_INTR_REIS);
2704			PRINTINTR(ATW_INTR_RPS);
2705			PRINTINTR(ATW_INTR_TCI);
2706			PRINTINTR(ATW_INTR_TDU);
2707			PRINTINTR(ATW_INTR_TLT);
2708			PRINTINTR(ATW_INTR_TPS);
2709			PRINTINTR(ATW_INTR_TRT);
2710			PRINTINTR(ATW_INTR_TUF);
2711			PRINTINTR(ATW_INTR_BCNTC);
2712			PRINTINTR(ATW_INTR_ATIME);
2713			PRINTINTR(ATW_INTR_TBTT);
2714			PRINTINTR(ATW_INTR_TSCZ);
2715			PRINTINTR(ATW_INTR_TSFTF);
2716			printf(">\n");
2717		}
2718#undef PRINTINTR
2719#endif /* ATW_DEBUG */
2720
2721		if ((status & sc->sc_inten) == 0)
2722			break;
2723
2724		handled = 1;
2725
2726		rxstatus = status & sc->sc_rxint_mask;
2727		txstatus = status & sc->sc_txint_mask;
2728		linkstatus = status & sc->sc_linkint_mask;
2729
2730		if (linkstatus) {
2731			atw_linkintr(sc, linkstatus);
2732		}
2733
2734		if (rxstatus) {
2735			/* Grab any new packets. */
2736			atw_rxintr(sc);
2737
2738			if (rxstatus & ATW_INTR_RDU) {
2739				printf("%s: receive ring overrun\n",
2740				    sc->sc_dev.dv_xname);
2741				/* Get the receive process going again. */
2742				ATW_WRITE(sc, ATW_RDR, 0x1);
2743				break;
2744			}
2745		}
2746
2747		if (txstatus) {
2748			/* Sweep up transmit descriptors. */
2749			atw_txintr(sc);
2750
2751			if (txstatus & ATW_INTR_TLT)
2752				DPRINTF(sc, ("%s: tx lifetime exceeded\n",
2753				    sc->sc_dev.dv_xname));
2754
2755			if (txstatus & ATW_INTR_TRT)
2756				DPRINTF(sc, ("%s: tx retry limit exceeded\n",
2757				    sc->sc_dev.dv_xname));
2758
2759			/* If Tx under-run, increase our transmit threshold
2760			 * if another is available.
2761			 */
2762			txthresh = sc->sc_txthresh + 1;
2763			if ((txstatus & ATW_INTR_TUF) &&
2764			    sc->sc_txth[txthresh].txth_name != NULL) {
2765				/* Idle the transmit process. */
2766				atw_idle(sc, ATW_NAR_ST);
2767
2768				sc->sc_txthresh = txthresh;
2769				sc->sc_opmode &= ~(ATW_NAR_TR_MASK|ATW_NAR_SF);
2770				sc->sc_opmode |=
2771				    sc->sc_txth[txthresh].txth_opmode;
2772				printf("%s: transmit underrun; new "
2773				    "threshold: %s\n", sc->sc_dev.dv_xname,
2774				    sc->sc_txth[txthresh].txth_name);
2775
2776				/* Set the new threshold and restart
2777				 * the transmit process.
2778				 */
2779				ATW_WRITE(sc, ATW_NAR, sc->sc_opmode);
2780				/* XXX Log every Nth underrun from
2781				 * XXX now on?
2782				 */
2783			}
2784		}
2785
2786		if (status & (ATW_INTR_TPS|ATW_INTR_RPS)) {
2787			if (status & ATW_INTR_TPS)
2788				printf("%s: transmit process stopped\n",
2789				    sc->sc_dev.dv_xname);
2790			if (status & ATW_INTR_RPS)
2791				printf("%s: receive process stopped\n",
2792				    sc->sc_dev.dv_xname);
2793			(void)atw_init(ifp);
2794			break;
2795		}
2796
2797		if (status & ATW_INTR_FBE) {
2798			printf("%s: fatal bus error\n", sc->sc_dev.dv_xname);
2799			(void)atw_init(ifp);
2800			break;
2801		}
2802
2803		/*
2804		 * Not handled:
2805		 *
2806		 *	Transmit buffer unavailable -- normal
2807		 *	condition, nothing to do, really.
2808		 *
2809		 *	Early receive interrupt -- not available on
2810		 *	all chips, we just use RI.  We also only
2811		 *	use single-segment receive DMA, so this
2812		 *	is mostly useless.
2813		 *
2814		 *      TBD others
2815		 */
2816	}
2817
2818	/* Try to get more packets going. */
2819	atw_start(ifp);
2820
2821	return (handled);
2822}
2823
2824/*
2825 * atw_idle:
2826 *
2827 *	Cause the transmit and/or receive processes to go idle.
2828 *
2829 *      XXX It seems that the ADM8211 will not signal the end of the Rx/Tx
2830 *	process in STSR if I clear SR or ST after the process has already
2831 *	ceased. Fair enough. But the Rx process status bits in ATW_TEST0
2832 *      do not seem to be too reliable. Perhaps I have the sense of the
2833 *	Rx bits switched with the Tx bits?
2834 */
2835void
2836atw_idle(struct atw_softc *sc, u_int32_t bits)
2837{
2838	u_int32_t ackmask = 0, opmode, stsr, test0;
2839	int i, s;
2840
2841	/* without this, somehow we run concurrently w/ interrupt handler */
2842	s = splnet();
2843
2844	opmode = sc->sc_opmode & ~bits;
2845
2846	if (bits & ATW_NAR_SR)
2847		ackmask |= ATW_INTR_RPS;
2848
2849	if (bits & ATW_NAR_ST) {
2850		ackmask |= ATW_INTR_TPS;
2851		/* set ATW_NAR_HF to flush TX FIFO. */
2852		opmode |= ATW_NAR_HF;
2853	}
2854
2855	ATW_WRITE(sc, ATW_NAR, opmode);
2856
2857	for (i = 0; i < 1000; i++) {
2858		stsr = ATW_READ(sc, ATW_STSR);
2859		if ((stsr & ackmask) == ackmask)
2860			break;
2861		DELAY(10);
2862	}
2863
2864	ATW_WRITE(sc, ATW_STSR, stsr & ackmask);
2865
2866	if ((stsr & ackmask) == ackmask)
2867		goto out;
2868
2869	test0 = ATW_READ(sc, ATW_TEST0);
2870
2871	if ((bits & ATW_NAR_ST) != 0 && (stsr & ATW_INTR_TPS) == 0 &&
2872	    (test0 & ATW_TEST0_TS_MASK) != ATW_TEST0_TS_STOPPED) {
2873		printf("%s: transmit process not idle [%s]\n",
2874		    sc->sc_dev.dv_xname,
2875		    atw_tx_state[MASK_AND_RSHIFT(test0, ATW_TEST0_TS_MASK)]);
2876		printf("%s: bits %08x test0 %08x stsr %08x\n",
2877		    sc->sc_dev.dv_xname, bits, test0, stsr);
2878	}
2879
2880	if ((bits & ATW_NAR_SR) != 0 && (stsr & ATW_INTR_RPS) == 0 &&
2881	    (test0 & ATW_TEST0_RS_MASK) != ATW_TEST0_RS_STOPPED) {
2882		DPRINTF2(sc, ("%s: receive process not idle [%s]\n",
2883		    sc->sc_dev.dv_xname,
2884		    atw_rx_state[MASK_AND_RSHIFT(test0, ATW_TEST0_RS_MASK)]));
2885		DPRINTF2(sc, ("%s: bits %08x test0 %08x stsr %08x\n",
2886		    sc->sc_dev.dv_xname, bits, test0, stsr));
2887	}
2888out:
2889	if ((bits & ATW_NAR_ST) != 0)
2890		atw_txdrain(sc);
2891	splx(s);
2892	return;
2893}
2894
2895/*
2896 * atw_linkintr:
2897 *
2898 *	Helper; handle link-status interrupts.
2899 */
2900void
2901atw_linkintr(struct atw_softc *sc, u_int32_t linkstatus)
2902{
2903	struct ieee80211com *ic = &sc->sc_ic;
2904
2905	if (ic->ic_state != IEEE80211_S_RUN)
2906		return;
2907
2908	if (linkstatus & ATW_INTR_LINKON) {
2909		DPRINTF(sc, ("%s: link on\n", sc->sc_dev.dv_xname));
2910		sc->sc_rescan_timer = 0;
2911	} else if (linkstatus & ATW_INTR_LINKOFF) {
2912		DPRINTF(sc, ("%s: link off\n", sc->sc_dev.dv_xname));
2913		if (ic->ic_opmode != IEEE80211_M_STA)
2914			return;
2915		sc->sc_rescan_timer = 3;
2916		ic->ic_if.if_timer = 1;
2917	}
2918}
2919
2920/*
2921 * atw_rxintr:
2922 *
2923 *	Helper; handle receive interrupts.
2924 */
2925void
2926atw_rxintr(struct atw_softc *sc)
2927{
2928	static int rate_tbl[] = {2, 4, 11, 22, 44};
2929	struct ieee80211com *ic = &sc->sc_ic;
2930	struct ieee80211_node *ni;
2931	struct ieee80211_frame *wh;
2932	struct ifnet *ifp = &ic->ic_if;
2933	struct atw_rxsoft *rxs;
2934	struct mbuf *m;
2935	u_int32_t rxstat;
2936	int i, len, rate, rate0;
2937	u_int32_t rssi;
2938
2939	for (i = sc->sc_rxptr;; i = ATW_NEXTRX(i)) {
2940		rxs = &sc->sc_rxsoft[i];
2941
2942		ATW_CDRXSYNC(sc, i, BUS_DMASYNC_POSTREAD|BUS_DMASYNC_POSTWRITE);
2943
2944		rxstat = le32toh(sc->sc_rxdescs[i].ar_stat);
2945		rssi = le32toh(sc->sc_rxdescs[i].ar_rssi);
2946		rate0 = MASK_AND_RSHIFT(rxstat, ATW_RXSTAT_RXDR_MASK);
2947
2948		if (rxstat & ATW_RXSTAT_OWN)
2949			break; /* We have processed all receive buffers. */
2950
2951		DPRINTF3(sc,
2952		    ("%s: rx stat %08x rssi %08x buf1 %08x buf2 %08x\n",
2953		    sc->sc_dev.dv_xname,
2954		    sc->sc_rxdescs[i].ar_stat,
2955		    sc->sc_rxdescs[i].ar_rssi,
2956		    sc->sc_rxdescs[i].ar_buf1,
2957		    sc->sc_rxdescs[i].ar_buf2));
2958
2959		/*
2960		 * Make sure the packet fits in one buffer.  This should
2961		 * always be the case.
2962		 */
2963		if ((rxstat & (ATW_RXSTAT_FS|ATW_RXSTAT_LS)) !=
2964		    (ATW_RXSTAT_FS|ATW_RXSTAT_LS)) {
2965			printf("%s: incoming packet spilled, resetting\n",
2966			    sc->sc_dev.dv_xname);
2967			(void)atw_init(ifp);
2968			return;
2969		}
2970
2971		/*
2972		 * If an error occurred, update stats, clear the status
2973		 * word, and leave the packet buffer in place.  It will
2974		 * simply be reused the next time the ring comes around.
2975	 	 * If 802.1Q VLAN MTU is enabled, ignore the Frame Too Long
2976		 * error.
2977		 */
2978
2979		if ((rxstat & ATW_RXSTAT_ES) != 0 &&
2980		    ((sc->sc_ic.ic_ec.ec_capenable & ETHERCAP_VLAN_MTU) == 0 ||
2981		     (rxstat & (ATW_RXSTAT_DE | ATW_RXSTAT_SFDE |
2982		                ATW_RXSTAT_SIGE | ATW_RXSTAT_CRC16E |
2983				ATW_RXSTAT_RXTOE | ATW_RXSTAT_CRC32E |
2984				ATW_RXSTAT_ICVE)) != 0)) {
2985#define	PRINTERR(bit, str)						\
2986			if (rxstat & (bit))				\
2987				printf("%s: receive error: %s\n",	\
2988				    sc->sc_dev.dv_xname, str)
2989			ifp->if_ierrors++;
2990			PRINTERR(ATW_RXSTAT_DE, "descriptor error");
2991			PRINTERR(ATW_RXSTAT_SFDE, "PLCP SFD error");
2992			PRINTERR(ATW_RXSTAT_SIGE, "PLCP signal error");
2993			PRINTERR(ATW_RXSTAT_CRC16E, "PLCP CRC16 error");
2994			PRINTERR(ATW_RXSTAT_RXTOE, "time-out");
2995			PRINTERR(ATW_RXSTAT_CRC32E, "FCS error");
2996			PRINTERR(ATW_RXSTAT_ICVE, "WEP ICV error");
2997#undef PRINTERR
2998			ATW_INIT_RXDESC(sc, i);
2999			continue;
3000		}
3001
3002		bus_dmamap_sync(sc->sc_dmat, rxs->rxs_dmamap, 0,
3003		    rxs->rxs_dmamap->dm_mapsize, BUS_DMASYNC_POSTREAD);
3004
3005		/*
3006		 * No errors; receive the packet.  Note the ADM8211
3007		 * includes the CRC in promiscuous mode.
3008		 */
3009		len = MASK_AND_RSHIFT(rxstat, ATW_RXSTAT_FL_MASK);
3010
3011		/*
3012		 * Allocate a new mbuf cluster.  If that fails, we are
3013		 * out of memory, and must drop the packet and recycle
3014		 * the buffer that's already attached to this descriptor.
3015		 */
3016		m = rxs->rxs_mbuf;
3017		if (atw_add_rxbuf(sc, i) != 0) {
3018			ifp->if_ierrors++;
3019			ATW_INIT_RXDESC(sc, i);
3020			bus_dmamap_sync(sc->sc_dmat, rxs->rxs_dmamap, 0,
3021			    rxs->rxs_dmamap->dm_mapsize, BUS_DMASYNC_PREREAD);
3022			continue;
3023		}
3024
3025		ifp->if_ipackets++;
3026		if (sc->sc_opmode & ATW_NAR_PR)
3027			m->m_flags |= M_HASFCS;
3028		m->m_pkthdr.rcvif = ifp;
3029		m->m_pkthdr.len = m->m_len = len;
3030
3031		if (rate0 >= sizeof(rate_tbl) / sizeof(rate_tbl[0]))
3032			rate = 0;
3033		else
3034			rate = rate_tbl[rate0];
3035
3036 #if NBPFILTER > 0
3037		/* Pass this up to any BPF listeners. */
3038		if (sc->sc_radiobpf != NULL) {
3039			struct atw_rx_radiotap_header *tap = &sc->sc_rxtap;
3040
3041			tap->ar_rate = rate;
3042			tap->ar_chan_freq = ic->ic_bss->ni_chan->ic_freq;
3043			tap->ar_chan_flags = ic->ic_bss->ni_chan->ic_flags;
3044
3045			/* TBD verify units are dB */
3046			tap->ar_antsignal = (int)rssi;
3047			/* TBD tap->ar_flags */
3048
3049			bpf_mtap2(sc->sc_radiobpf, (caddr_t)tap,
3050			    tap->ar_ihdr.it_len, m);
3051 		}
3052 #endif /* NPBFILTER > 0 */
3053
3054		wh = mtod(m, struct ieee80211_frame *);
3055		ni = ieee80211_find_rxnode(ic, wh);
3056		ieee80211_input(ifp, m, ni, (int)rssi, 0);
3057		/*
3058		 * The frame may have caused the node to be marked for
3059		 * reclamation (e.g. in response to a DEAUTH message)
3060		 * so use free_node here instead of unref_node.
3061		 */
3062		if (ni == ic->ic_bss)
3063			ieee80211_unref_node(&ni);
3064		else
3065			ieee80211_free_node(ic, ni);
3066	}
3067
3068	/* Update the receive pointer. */
3069	sc->sc_rxptr = i;
3070}
3071
3072/*
3073 * atw_txintr:
3074 *
3075 *	Helper; handle transmit interrupts.
3076 */
3077void
3078atw_txintr(struct atw_softc *sc)
3079{
3080#define TXSTAT_ERRMASK (ATW_TXSTAT_TUF | ATW_TXSTAT_TLT | ATW_TXSTAT_TRT | \
3081    ATW_TXSTAT_TRO | ATW_TXSTAT_SOFBR)
3082#define TXSTAT_FMT "\20\31ATW_TXSTAT_SOFBR\32ATW_TXSTAT_TRO\33ATW_TXSTAT_TUF" \
3083    "\34ATW_TXSTAT_TRT\35ATW_TXSTAT_TLT"
3084
3085	static char txstat_buf[sizeof("ffffffff<>" TXSTAT_FMT)];
3086	struct ifnet *ifp = &sc->sc_ic.ic_if;
3087	struct atw_txsoft *txs;
3088	u_int32_t txstat;
3089
3090	DPRINTF3(sc, ("%s: atw_txintr: sc_flags 0x%08x\n",
3091	    sc->sc_dev.dv_xname, sc->sc_flags));
3092
3093	ifp->if_flags &= ~IFF_OACTIVE;
3094
3095	/*
3096	 * Go through our Tx list and free mbufs for those
3097	 * frames that have been transmitted.
3098	 */
3099	while ((txs = SIMPLEQ_FIRST(&sc->sc_txdirtyq)) != NULL) {
3100		ATW_CDTXSYNC(sc, txs->txs_lastdesc,
3101		    txs->txs_ndescs,
3102		    BUS_DMASYNC_POSTREAD|BUS_DMASYNC_POSTWRITE);
3103
3104#ifdef ATW_DEBUG
3105		if ((ifp->if_flags & IFF_DEBUG) != 0 && atw_debug > 2) {
3106			int i;
3107			printf("    txsoft %p transmit chain:\n", txs);
3108			for (i = txs->txs_firstdesc;; i = ATW_NEXTTX(i)) {
3109				printf("     descriptor %d:\n", i);
3110				printf("       at_status:   0x%08x\n",
3111				    le32toh(sc->sc_txdescs[i].at_stat));
3112				printf("       at_flags:      0x%08x\n",
3113				    le32toh(sc->sc_txdescs[i].at_flags));
3114				printf("       at_buf1: 0x%08x\n",
3115				    le32toh(sc->sc_txdescs[i].at_buf1));
3116				printf("       at_buf2: 0x%08x\n",
3117				    le32toh(sc->sc_txdescs[i].at_buf2));
3118				if (i == txs->txs_lastdesc)
3119					break;
3120			}
3121		}
3122#endif
3123
3124		txstat = le32toh(sc->sc_txdescs[txs->txs_lastdesc].at_stat);
3125		if (txstat & ATW_TXSTAT_OWN)
3126			break;
3127
3128		SIMPLEQ_REMOVE_HEAD(&sc->sc_txdirtyq, txs_q);
3129
3130		sc->sc_txfree += txs->txs_ndescs;
3131
3132		bus_dmamap_sync(sc->sc_dmat, txs->txs_dmamap,
3133		    0, txs->txs_dmamap->dm_mapsize,
3134		    BUS_DMASYNC_POSTWRITE);
3135		bus_dmamap_unload(sc->sc_dmat, txs->txs_dmamap);
3136		m_freem(txs->txs_mbuf);
3137		txs->txs_mbuf = NULL;
3138
3139		SIMPLEQ_INSERT_TAIL(&sc->sc_txfreeq, txs, txs_q);
3140
3141		if ((ifp->if_flags & IFF_DEBUG) != 0 &&
3142		    (txstat & TXSTAT_ERRMASK) != 0) {
3143			bitmask_snprintf(txstat & TXSTAT_ERRMASK, TXSTAT_FMT,
3144			    txstat_buf, sizeof(txstat_buf));
3145			printf("%s: txstat %s %d\n", sc->sc_dev.dv_xname,
3146			    txstat_buf,
3147			    MASK_AND_RSHIFT(txstat, ATW_TXSTAT_ARC_MASK));
3148		}
3149
3150		/*
3151		 * Check for errors and collisions.
3152		 */
3153		if (txstat & ATW_TXSTAT_TUF)
3154			sc->sc_stats.ts_tx_tuf++;
3155		if (txstat & ATW_TXSTAT_TLT)
3156			sc->sc_stats.ts_tx_tlt++;
3157		if (txstat & ATW_TXSTAT_TRT)
3158			sc->sc_stats.ts_tx_trt++;
3159		if (txstat & ATW_TXSTAT_TRO)
3160			sc->sc_stats.ts_tx_tro++;
3161		if (txstat & ATW_TXSTAT_SOFBR) {
3162			sc->sc_stats.ts_tx_sofbr++;
3163		}
3164
3165		if ((txstat & ATW_TXSTAT_ES) == 0)
3166			ifp->if_collisions +=
3167			    MASK_AND_RSHIFT(txstat, ATW_TXSTAT_ARC_MASK);
3168		else
3169			ifp->if_oerrors++;
3170
3171		ifp->if_opackets++;
3172	}
3173
3174	/*
3175	 * If there are no more pending transmissions, cancel the watchdog
3176	 * timer.
3177	 */
3178	if (txs == NULL)
3179		sc->sc_tx_timer = 0;
3180#undef TXSTAT_ERRMASK
3181#undef TXSTAT_FMT
3182}
3183
3184/*
3185 * atw_watchdog:	[ifnet interface function]
3186 *
3187 *	Watchdog timer handler.
3188 */
3189void
3190atw_watchdog(struct ifnet *ifp)
3191{
3192	struct atw_softc *sc = ifp->if_softc;
3193	struct ieee80211com *ic = &sc->sc_ic;
3194
3195	ifp->if_timer = 0;
3196	if (ATW_IS_ENABLED(sc) == 0)
3197		return;
3198
3199	if (sc->sc_rescan_timer) {
3200		if (--sc->sc_rescan_timer == 0)
3201			(void)ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
3202	}
3203	if (sc->sc_tx_timer) {
3204		if (--sc->sc_tx_timer == 0 &&
3205		    !SIMPLEQ_EMPTY(&sc->sc_txdirtyq)) {
3206			printf("%s: transmit timeout\n", ifp->if_xname);
3207			ifp->if_oerrors++;
3208			(void)atw_init(ifp);
3209			atw_start(ifp);
3210		}
3211	}
3212	if (sc->sc_tx_timer != 0 || sc->sc_rescan_timer != 0)
3213		ifp->if_timer = 1;
3214	ieee80211_watchdog(ifp);
3215}
3216
3217/* Compute the 802.11 Duration field and the PLCP Length fields for
3218 * a len-byte frame (HEADER + PAYLOAD + FCS) sent at rate * 500Kbps.
3219 * Write the fields to the ADM8211 Tx header, frm.
3220 *
3221 * TBD use the fragmentation threshold to find the right duration for
3222 * the first & last fragments.
3223 *
3224 * TBD make certain of the duration fields applied by the ADM8211 to each
3225 * fragment. I think that the ADM8211 knows how to subtract the CTS
3226 * duration when ATW_HDRCTL_RTSCTS is clear; that is why I add it regardless.
3227 * I also think that the ADM8211 does *some* arithmetic for us, because
3228 * otherwise I think we would have to set a first duration for CTS/first
3229 * fragment, a second duration for fragments between the first and the
3230 * last, and a third duration for the last fragment.
3231 *
3232 * TBD make certain that duration fields reflect addition of FCS/WEP
3233 * and correct duration arithmetic as necessary.
3234 */
3235static void
3236atw_frame_setdurs(struct atw_softc *sc, struct atw_frame *frm, int rate,
3237    int len)
3238{
3239	int remainder;
3240
3241	/* deal also with encrypted fragments */
3242	if (frm->atw_hdrctl & htole16(ATW_HDRCTL_WEP)) {
3243		DPRINTF2(sc, ("%s: atw_frame_setdurs len += 8\n",
3244		    sc->sc_dev.dv_xname));
3245		len += IEEE80211_WEP_IVLEN + IEEE80211_WEP_KIDLEN +
3246		       IEEE80211_WEP_CRCLEN;
3247	}
3248
3249	/* 802.11 Duration Field for CTS/Data/ACK sequence minus FCS & WEP
3250	 * duration (XXX added by MAC?).
3251	 */
3252	frm->atw_head_dur = (16 * (len - IEEE80211_CRC_LEN)) / rate;
3253	remainder = (16 * (len - IEEE80211_CRC_LEN)) % rate;
3254
3255	if (rate <= 4)
3256		/* 1-2Mbps WLAN: send ACK/CTS at 1Mbps */
3257		frm->atw_head_dur += 3 * (IEEE80211_DUR_DS_SIFS +
3258		    IEEE80211_DUR_DS_SHORT_PREAMBLE +
3259		    IEEE80211_DUR_DS_FAST_PLCPHDR) +
3260		    IEEE80211_DUR_DS_SLOW_CTS + IEEE80211_DUR_DS_SLOW_ACK;
3261	else
3262		/* 5-11Mbps WLAN: send ACK/CTS at 2Mbps */
3263		frm->atw_head_dur += 3 * (IEEE80211_DUR_DS_SIFS +
3264		    IEEE80211_DUR_DS_SHORT_PREAMBLE +
3265		    IEEE80211_DUR_DS_FAST_PLCPHDR) +
3266		    IEEE80211_DUR_DS_FAST_CTS + IEEE80211_DUR_DS_FAST_ACK;
3267
3268	/* lengthen duration if long preamble */
3269	if ((sc->sc_flags & ATWF_SHORT_PREAMBLE) == 0)
3270		frm->atw_head_dur +=
3271		    3 * (IEEE80211_DUR_DS_LONG_PREAMBLE -
3272		         IEEE80211_DUR_DS_SHORT_PREAMBLE) +
3273		    3 * (IEEE80211_DUR_DS_SLOW_PLCPHDR -
3274		         IEEE80211_DUR_DS_FAST_PLCPHDR);
3275
3276	if (remainder != 0)
3277		frm->atw_head_dur++;
3278
3279	if ((atw_voodoo & VOODOO_DUR_2_4_SPECIALCASE) &&
3280	    (rate == 2 || rate == 4)) {
3281		/* derived from Linux: how could this be right? */
3282		frm->atw_head_plcplen = frm->atw_head_dur;
3283	} else {
3284		frm->atw_head_plcplen = (16 * len) / rate;
3285		remainder = (80 * len) % (rate * 5);
3286
3287		if (remainder != 0) {
3288			frm->atw_head_plcplen++;
3289
3290			/* XXX magic */
3291			if ((atw_voodoo & VOODOO_DUR_11_ROUNDING) &&
3292			    rate == 22 && remainder <= 30)
3293				frm->atw_head_plcplen |= 0x8000;
3294		}
3295	}
3296	frm->atw_tail_plcplen = frm->atw_head_plcplen =
3297	    htole16(frm->atw_head_plcplen);
3298	frm->atw_tail_dur = frm->atw_head_dur = htole16(frm->atw_head_dur);
3299}
3300
3301#ifdef ATW_DEBUG
3302static void
3303atw_dump_pkt(struct ifnet *ifp, struct mbuf *m0)
3304{
3305	struct atw_softc *sc = ifp->if_softc;
3306	struct mbuf *m;
3307	int i, noctets = 0;
3308
3309	printf("%s: %d-byte packet\n", sc->sc_dev.dv_xname,
3310	    m0->m_pkthdr.len);
3311
3312	for (m = m0; m; m = m->m_next) {
3313		if (m->m_len == 0)
3314			continue;
3315		for (i = 0; i < m->m_len; i++) {
3316			printf(" %02x", ((u_int8_t*)m->m_data)[i]);
3317			if (++noctets % 24 == 0)
3318				printf("\n");
3319		}
3320	}
3321	printf("%s%s: %d bytes emitted\n",
3322	    (noctets % 24 != 0) ? "\n" : "", sc->sc_dev.dv_xname, noctets);
3323}
3324#endif /* ATW_DEBUG */
3325
3326/*
3327 * atw_start:		[ifnet interface function]
3328 *
3329 *	Start packet transmission on the interface.
3330 */
3331void
3332atw_start(struct ifnet *ifp)
3333{
3334	struct atw_softc *sc = ifp->if_softc;
3335	struct ieee80211com *ic = &sc->sc_ic;
3336	struct ieee80211_node *ni;
3337	struct ieee80211_frame *wh;
3338	struct atw_frame *hh;
3339	struct mbuf *m0, *m;
3340	struct atw_txsoft *txs, *last_txs;
3341	struct atw_txdesc *txd;
3342	int do_encrypt, rate;
3343	bus_dmamap_t dmamap;
3344	int ctl, error, firsttx, nexttx, lasttx = -1, first, ofree, seg;
3345
3346	DPRINTF2(sc, ("%s: atw_start: sc_flags 0x%08x, if_flags 0x%08x\n",
3347	    sc->sc_dev.dv_xname, sc->sc_flags, ifp->if_flags));
3348
3349	if ((ifp->if_flags & (IFF_RUNNING|IFF_OACTIVE)) != IFF_RUNNING)
3350		return;
3351
3352#if 0 /* TBD ??? */
3353	if ((sc->sc_flags & ATWF_LINK_UP) == 0 && ifp->if_snd.ifq_len < 10)
3354		return;
3355#endif
3356
3357	/*
3358	 * Remember the previous number of free descriptors and
3359	 * the first descriptor we'll use.
3360	 */
3361	ofree = sc->sc_txfree;
3362	firsttx = sc->sc_txnext;
3363
3364	DPRINTF2(sc, ("%s: atw_start: txfree %d, txnext %d\n",
3365	    sc->sc_dev.dv_xname, ofree, firsttx));
3366
3367	/*
3368	 * Loop through the send queue, setting up transmit descriptors
3369	 * until we drain the queue, or use up all available transmit
3370	 * descriptors.
3371	 */
3372	while ((txs = SIMPLEQ_FIRST(&sc->sc_txfreeq)) != NULL &&
3373	       sc->sc_txfree != 0) {
3374
3375		/*
3376		 * Grab a packet off the management queue, if it
3377		 * is not empty. Otherwise, from the data queue.
3378		 */
3379		IF_DEQUEUE(&ic->ic_mgtq, m0);
3380		if (m0 != NULL) {
3381			ni = (struct ieee80211_node *)m0->m_pkthdr.rcvif;
3382			m0->m_pkthdr.rcvif = NULL;
3383		} else {
3384			IFQ_DEQUEUE(&ifp->if_snd, m0);
3385			if (m0 == NULL)
3386				break;
3387#if NBPFILTER > 0
3388			if (ifp->if_bpf != NULL)
3389				bpf_mtap(ifp->if_bpf, m0);
3390#endif /* NBPFILTER > 0 */
3391			if ((m0 = ieee80211_encap(ifp, m0, &ni)) == NULL) {
3392				ifp->if_oerrors++;
3393				break;
3394			}
3395		}
3396
3397		rate = MAX(ieee80211_get_rate(ic), 2);
3398
3399#if NBPFILTER > 0
3400		/*
3401		 * Pass the packet to any BPF listeners.
3402		 */
3403		if (ic->ic_rawbpf != NULL)
3404			bpf_mtap((caddr_t)ic->ic_rawbpf, m0);
3405
3406		if (sc->sc_radiobpf != NULL) {
3407			struct atw_tx_radiotap_header *tap = &sc->sc_txtap;
3408
3409			tap->at_rate = rate;
3410			tap->at_chan_freq = ic->ic_bss->ni_chan->ic_freq;
3411			tap->at_chan_flags = ic->ic_bss->ni_chan->ic_flags;
3412
3413			/* TBD tap->at_flags */
3414
3415			bpf_mtap2(sc->sc_radiobpf, (caddr_t)tap,
3416			    tap->at_ihdr.it_len, m0);
3417		}
3418#endif /* NBPFILTER > 0 */
3419
3420		M_PREPEND(m0, offsetof(struct atw_frame, atw_ihdr), M_DONTWAIT);
3421
3422		if (ni != NULL && ni != ic->ic_bss)
3423			ieee80211_free_node(ic, ni);
3424
3425		if (m0 == NULL) {
3426			ifp->if_oerrors++;
3427			break;
3428		}
3429
3430		/* just to make sure. */
3431		m0 = m_pullup(m0, sizeof(struct atw_frame));
3432
3433		if (m0 == NULL) {
3434			ifp->if_oerrors++;
3435			break;
3436		}
3437
3438		hh = mtod(m0, struct atw_frame *);
3439		wh = &hh->atw_ihdr;
3440
3441		do_encrypt = ((wh->i_fc[1] & IEEE80211_FC1_WEP) != 0) ? 1 : 0;
3442
3443		/* Copy everything we need from the 802.11 header:
3444		 * Frame Control; address 1, address 3, or addresses
3445		 * 3 and 4. NIC fills in BSSID, SA.
3446		 */
3447		if (wh->i_fc[1] & IEEE80211_FC1_DIR_TODS) {
3448			if (wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS)
3449				panic("%s: illegal WDS frame",
3450				    sc->sc_dev.dv_xname);
3451			memcpy(hh->atw_dst, wh->i_addr3, IEEE80211_ADDR_LEN);
3452		} else
3453			memcpy(hh->atw_dst, wh->i_addr1, IEEE80211_ADDR_LEN);
3454
3455		*(u_int16_t*)hh->atw_fc = *(u_int16_t*)wh->i_fc;
3456
3457		/* initialize remaining Tx parameters */
3458		memset(&hh->u, 0, sizeof(hh->u));
3459
3460		hh->atw_rate = rate * 5;
3461		/* XXX this could be incorrect if M_FCS. _encap should
3462		 * probably strip FCS just in case it sticks around in
3463		 * bridged packets.
3464		 */
3465		hh->atw_service = IEEE80211_PLCP_SERVICE; /* XXX guess */
3466		hh->atw_paylen = htole16(m0->m_pkthdr.len -
3467		    sizeof(struct atw_frame));
3468
3469		hh->atw_fragthr = htole16(ATW_FRAGTHR_FRAGTHR_MASK);
3470		hh->atw_rtylmt = 3;
3471		hh->atw_hdrctl = htole16(ATW_HDRCTL_UNKNOWN1);
3472		if (do_encrypt) {
3473			hh->atw_hdrctl |= htole16(ATW_HDRCTL_WEP);
3474			hh->atw_keyid = ic->ic_wep_txkey;
3475		}
3476
3477		/* TBD 4-addr frames */
3478		atw_frame_setdurs(sc, hh, rate,
3479		    m0->m_pkthdr.len - sizeof(struct atw_frame) +
3480		    sizeof(struct ieee80211_frame) + IEEE80211_CRC_LEN);
3481
3482		/* never fragment multicast frames */
3483		if (IEEE80211_IS_MULTICAST(hh->atw_dst)) {
3484			hh->atw_fragthr = htole16(ATW_FRAGTHR_FRAGTHR_MASK);
3485		} else if (sc->sc_flags & ATWF_RTSCTS) {
3486			hh->atw_hdrctl |= htole16(ATW_HDRCTL_RTSCTS);
3487		}
3488
3489#ifdef ATW_DEBUG
3490		hh->atw_fragnum = 0;
3491
3492		if ((ifp->if_flags & IFF_DEBUG) != 0 && atw_debug > 2) {
3493			printf("%s: dst = %s, rate = 0x%02x, "
3494			    "service = 0x%02x, paylen = 0x%04x\n",
3495			    sc->sc_dev.dv_xname, ether_sprintf(hh->atw_dst),
3496			    hh->atw_rate, hh->atw_service, hh->atw_paylen);
3497
3498			printf("%s: fc[0] = 0x%02x, fc[1] = 0x%02x, "
3499			    "dur1 = 0x%04x, dur2 = 0x%04x, "
3500			    "dur3 = 0x%04x, rts_dur = 0x%04x\n",
3501			    sc->sc_dev.dv_xname, hh->atw_fc[0], hh->atw_fc[1],
3502			    hh->atw_tail_plcplen, hh->atw_head_plcplen,
3503			    hh->atw_tail_dur, hh->atw_head_dur);
3504
3505			printf("%s: hdrctl = 0x%04x, fragthr = 0x%04x, "
3506			    "fragnum = 0x%02x, rtylmt = 0x%04x\n",
3507			    sc->sc_dev.dv_xname, hh->atw_hdrctl,
3508			    hh->atw_fragthr, hh->atw_fragnum, hh->atw_rtylmt);
3509
3510			printf("%s: keyid = %d\n",
3511			    sc->sc_dev.dv_xname, hh->atw_keyid);
3512
3513			atw_dump_pkt(ifp, m0);
3514		}
3515#endif /* ATW_DEBUG */
3516
3517		dmamap = txs->txs_dmamap;
3518
3519		/*
3520		 * Load the DMA map.  Copy and try (once) again if the packet
3521		 * didn't fit in the alloted number of segments.
3522		 */
3523		for (first = 1;
3524		     (error = bus_dmamap_load_mbuf(sc->sc_dmat, dmamap, m0,
3525		                  BUS_DMA_WRITE|BUS_DMA_NOWAIT)) != 0 && first;
3526		     first = 0) {
3527			MGETHDR(m, M_DONTWAIT, MT_DATA);
3528			if (m == NULL) {
3529				printf("%s: unable to allocate Tx mbuf\n",
3530				    sc->sc_dev.dv_xname);
3531				break;
3532			}
3533			if (m0->m_pkthdr.len > MHLEN) {
3534				MCLGET(m, M_DONTWAIT);
3535				if ((m->m_flags & M_EXT) == 0) {
3536					printf("%s: unable to allocate Tx "
3537					    "cluster\n", sc->sc_dev.dv_xname);
3538					m_freem(m);
3539					break;
3540				}
3541			}
3542			m_copydata(m0, 0, m0->m_pkthdr.len, mtod(m, caddr_t));
3543			m->m_pkthdr.len = m->m_len = m0->m_pkthdr.len;
3544			m_freem(m0);
3545			m0 = m;
3546			m = NULL;
3547		}
3548		if (error != 0) {
3549			printf("%s: unable to load Tx buffer, "
3550			    "error = %d\n", sc->sc_dev.dv_xname, error);
3551			m_freem(m0);
3552			break;
3553		}
3554
3555		/*
3556		 * Ensure we have enough descriptors free to describe
3557		 * the packet.
3558		 */
3559		if (dmamap->dm_nsegs > sc->sc_txfree) {
3560			/*
3561			 * Not enough free descriptors to transmit
3562			 * this packet.  Unload the DMA map and
3563			 * drop the packet.  Notify the upper layer
3564			 * that there are no more slots left.
3565			 *
3566			 * XXX We could allocate an mbuf and copy, but
3567			 * XXX it is worth it?
3568			 */
3569			ifp->if_flags |= IFF_OACTIVE;
3570			bus_dmamap_unload(sc->sc_dmat, dmamap);
3571			m_freem(m0);
3572			break;
3573		}
3574
3575		/*
3576		 * WE ARE NOW COMMITTED TO TRANSMITTING THE PACKET.
3577		 */
3578
3579		/* Sync the DMA map. */
3580		bus_dmamap_sync(sc->sc_dmat, dmamap, 0, dmamap->dm_mapsize,
3581		    BUS_DMASYNC_PREWRITE);
3582
3583		/* XXX arbitrary retry limit; 8 because I have seen it in
3584		 * use already and maybe 0 means "no tries" !
3585		 */
3586		ctl = htole32(LSHIFT(8, ATW_TXCTL_TL_MASK));
3587
3588		DPRINTF2(sc, ("%s: TXDR <- max(10, %d)\n",
3589		    sc->sc_dev.dv_xname, rate * 5));
3590		ctl |= htole32(LSHIFT(MAX(10, rate * 5), ATW_TXCTL_TXDR_MASK));
3591
3592		/*
3593		 * Initialize the transmit descriptors.
3594		 */
3595		for (nexttx = sc->sc_txnext, seg = 0;
3596		     seg < dmamap->dm_nsegs;
3597		     seg++, nexttx = ATW_NEXTTX(nexttx)) {
3598			/*
3599			 * If this is the first descriptor we're
3600			 * enqueueing, don't set the OWN bit just
3601			 * yet.  That could cause a race condition.
3602			 * We'll do it below.
3603			 */
3604			txd = &sc->sc_txdescs[nexttx];
3605			txd->at_ctl = ctl |
3606			    ((nexttx == firsttx) ? 0 : htole32(ATW_TXCTL_OWN));
3607
3608			txd->at_buf1 = htole32(dmamap->dm_segs[seg].ds_addr);
3609			txd->at_flags =
3610			    htole32(LSHIFT(dmamap->dm_segs[seg].ds_len,
3611			                   ATW_TXFLAG_TBS1_MASK)) |
3612			    ((nexttx == (ATW_NTXDESC - 1))
3613			        ? htole32(ATW_TXFLAG_TER) : 0);
3614			lasttx = nexttx;
3615		}
3616
3617		IASSERT(lasttx != -1, ("bad lastx"));
3618		/* Set `first segment' and `last segment' appropriately. */
3619		sc->sc_txdescs[sc->sc_txnext].at_flags |=
3620		    htole32(ATW_TXFLAG_FS);
3621		sc->sc_txdescs[lasttx].at_flags |= htole32(ATW_TXFLAG_LS);
3622
3623#ifdef ATW_DEBUG
3624		if ((ifp->if_flags & IFF_DEBUG) != 0 && atw_debug > 2) {
3625			printf("     txsoft %p transmit chain:\n", txs);
3626			for (seg = sc->sc_txnext;; seg = ATW_NEXTTX(seg)) {
3627				printf("     descriptor %d:\n", seg);
3628				printf("       at_ctl:   0x%08x\n",
3629				    le32toh(sc->sc_txdescs[seg].at_ctl));
3630				printf("       at_flags:      0x%08x\n",
3631				    le32toh(sc->sc_txdescs[seg].at_flags));
3632				printf("       at_buf1: 0x%08x\n",
3633				    le32toh(sc->sc_txdescs[seg].at_buf1));
3634				printf("       at_buf2: 0x%08x\n",
3635				    le32toh(sc->sc_txdescs[seg].at_buf2));
3636				if (seg == lasttx)
3637					break;
3638			}
3639		}
3640#endif
3641
3642		/* Sync the descriptors we're using. */
3643		ATW_CDTXSYNC(sc, sc->sc_txnext, dmamap->dm_nsegs,
3644		    BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
3645
3646		/*
3647		 * Store a pointer to the packet so we can free it later,
3648		 * and remember what txdirty will be once the packet is
3649		 * done.
3650		 */
3651		txs->txs_mbuf = m0;
3652		txs->txs_firstdesc = sc->sc_txnext;
3653		txs->txs_lastdesc = lasttx;
3654		txs->txs_ndescs = dmamap->dm_nsegs;
3655
3656		/* Advance the tx pointer. */
3657		sc->sc_txfree -= dmamap->dm_nsegs;
3658		sc->sc_txnext = nexttx;
3659
3660		SIMPLEQ_REMOVE_HEAD(&sc->sc_txfreeq, txs_q);
3661		SIMPLEQ_INSERT_TAIL(&sc->sc_txdirtyq, txs, txs_q);
3662
3663		last_txs = txs;
3664	}
3665
3666	if (txs == NULL || sc->sc_txfree == 0) {
3667		/* No more slots left; notify upper layer. */
3668		ifp->if_flags |= IFF_OACTIVE;
3669	}
3670
3671	if (sc->sc_txfree != ofree) {
3672		DPRINTF2(sc, ("%s: packets enqueued, IC on %d, OWN on %d\n",
3673		    sc->sc_dev.dv_xname, lasttx, firsttx));
3674		/*
3675		 * Cause a transmit interrupt to happen on the
3676		 * last packet we enqueued.
3677		 */
3678		sc->sc_txdescs[lasttx].at_flags |= htole32(ATW_TXFLAG_IC);
3679		ATW_CDTXSYNC(sc, lasttx, 1,
3680		    BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
3681
3682		/*
3683		 * The entire packet chain is set up.  Give the
3684		 * first descriptor to the chip now.
3685		 */
3686		sc->sc_txdescs[firsttx].at_ctl |= htole32(ATW_TXCTL_OWN);
3687		ATW_CDTXSYNC(sc, firsttx, 1,
3688		    BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
3689
3690		/* Wake up the transmitter. */
3691		ATW_WRITE(sc, ATW_TDR, 0x1);
3692
3693		/* Set a watchdog timer in case the chip flakes out. */
3694		sc->sc_tx_timer = 5;
3695		ifp->if_timer = 1;
3696	}
3697}
3698
3699/*
3700 * atw_power:
3701 *
3702 *	Power management (suspend/resume) hook.
3703 */
3704void
3705atw_power(int why, void *arg)
3706{
3707	struct atw_softc *sc = arg;
3708	struct ifnet *ifp = &sc->sc_ic.ic_if;
3709	int s;
3710
3711	DPRINTF(sc, ("%s: atw_power(%d,)\n", sc->sc_dev.dv_xname, why));
3712
3713	s = splnet();
3714	switch (why) {
3715	case PWR_STANDBY:
3716		/* XXX do nothing. */
3717		break;
3718	case PWR_SUSPEND:
3719		atw_stop(ifp, 0);
3720		if (sc->sc_power != NULL)
3721			(*sc->sc_power)(sc, why);
3722		break;
3723	case PWR_RESUME:
3724		if (ifp->if_flags & IFF_UP) {
3725			if (sc->sc_power != NULL)
3726				(*sc->sc_power)(sc, why);
3727			atw_init(ifp);
3728		}
3729		break;
3730	case PWR_SOFTSUSPEND:
3731	case PWR_SOFTSTANDBY:
3732	case PWR_SOFTRESUME:
3733		break;
3734	}
3735	splx(s);
3736}
3737
3738/*
3739 * atw_ioctl:		[ifnet interface function]
3740 *
3741 *	Handle control requests from the operator.
3742 */
3743int
3744atw_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
3745{
3746	struct atw_softc *sc = ifp->if_softc;
3747	struct ifreq *ifr = (struct ifreq *)data;
3748	int s, error = 0;
3749
3750	/* XXX monkey see, monkey do. comes from wi_ioctl. */
3751	if ((sc->sc_dev.dv_flags & DVF_ACTIVE) == 0)
3752		return ENXIO;
3753
3754	s = splnet();
3755
3756	switch (cmd) {
3757	case SIOCSIFFLAGS:
3758		if (ifp->if_flags & IFF_UP) {
3759			if (ATW_IS_ENABLED(sc)) {
3760				/*
3761				 * To avoid rescanning another access point,
3762				 * do not call atw_init() here.  Instead,
3763				 * only reflect media settings.
3764				 */
3765				atw_filter_setup(sc);
3766			} else
3767				error = atw_init(ifp);
3768		} else if (ATW_IS_ENABLED(sc))
3769			atw_stop(ifp, 1);
3770		break;
3771	case SIOCADDMULTI:
3772	case SIOCDELMULTI:
3773		error = (cmd == SIOCADDMULTI) ?
3774		    ether_addmulti(ifr, &sc->sc_ic.ic_ec) :
3775		    ether_delmulti(ifr, &sc->sc_ic.ic_ec);
3776		if (error == ENETRESET) {
3777			if (ATW_IS_ENABLED(sc))
3778				atw_filter_setup(sc); /* do not rescan */
3779			error = 0;
3780		}
3781		break;
3782	default:
3783		error = ieee80211_ioctl(ifp, cmd, data);
3784		if (error == ENETRESET) {
3785			if (ATW_IS_ENABLED(sc))
3786				error = atw_init(ifp);
3787			else
3788				error = 0;
3789		}
3790		break;
3791	}
3792
3793	/* Try to get more packets going. */
3794	if (ATW_IS_ENABLED(sc))
3795		atw_start(ifp);
3796
3797	splx(s);
3798	return (error);
3799}
3800
3801static int
3802atw_media_change(struct ifnet *ifp)
3803{
3804	int error;
3805
3806	error = ieee80211_media_change(ifp);
3807	if (error == ENETRESET) {
3808		if ((ifp->if_flags & (IFF_RUNNING|IFF_UP)) ==
3809		    (IFF_RUNNING|IFF_UP))
3810			atw_init(ifp);		/* XXX lose error */
3811		error = 0;
3812	}
3813	return error;
3814}
3815
3816static void
3817atw_media_status(struct ifnet *ifp, struct ifmediareq *imr)
3818{
3819	struct atw_softc *sc = ifp->if_softc;
3820
3821	if (ATW_IS_ENABLED(sc) == 0) {
3822		imr->ifm_active = IFM_IEEE80211 | IFM_NONE;
3823		imr->ifm_status = 0;
3824		return;
3825	}
3826	ieee80211_media_status(ifp, imr);
3827}
3828