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