if_bwi.c revision 260444
1/*
2 * Copyright (c) 2007 The DragonFly Project.  All rights reserved.
3 *
4 * This code is derived from software contributed to The DragonFly Project
5 * by Sepherosa Ziehau <sepherosa@gmail.com>
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in
15 *    the documentation and/or other materials provided with the
16 *    distribution.
17 * 3. Neither the name of The DragonFly Project nor the names of its
18 *    contributors may be used to endorse or promote products derived
19 *    from this software without specific, prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 *
34 * $DragonFly: src/sys/dev/netif/bwi/if_bwi.c,v 1.19 2008/02/15 11:15:38 sephe Exp $
35 */
36
37#include <sys/cdefs.h>
38__FBSDID("$FreeBSD: head/sys/dev/bwi/if_bwi.c 260444 2014-01-08 08:06:56Z kevlo $");
39
40#include "opt_inet.h"
41#include "opt_bwi.h"
42#include "opt_wlan.h"
43
44#include <sys/param.h>
45#include <sys/endian.h>
46#include <sys/kernel.h>
47#include <sys/bus.h>
48#include <sys/malloc.h>
49#include <sys/proc.h>
50#include <sys/rman.h>
51#include <sys/socket.h>
52#include <sys/sockio.h>
53#include <sys/sysctl.h>
54#include <sys/systm.h>
55#include <sys/taskqueue.h>
56
57#include <net/if.h>
58#include <net/if_var.h>
59#include <net/if_dl.h>
60#include <net/if_media.h>
61#include <net/if_types.h>
62#include <net/if_arp.h>
63#include <net/ethernet.h>
64#include <net/if_llc.h>
65
66#include <net80211/ieee80211_var.h>
67#include <net80211/ieee80211_radiotap.h>
68#include <net80211/ieee80211_regdomain.h>
69#include <net80211/ieee80211_phy.h>
70#include <net80211/ieee80211_ratectl.h>
71
72#include <net/bpf.h>
73
74#ifdef INET
75#include <netinet/in.h>
76#include <netinet/if_ether.h>
77#endif
78
79#include <machine/bus.h>
80
81#include <dev/pci/pcivar.h>
82#include <dev/pci/pcireg.h>
83
84#include <dev/bwi/bitops.h>
85#include <dev/bwi/if_bwireg.h>
86#include <dev/bwi/if_bwivar.h>
87#include <dev/bwi/bwimac.h>
88#include <dev/bwi/bwirf.h>
89
90struct bwi_clock_freq {
91	u_int		clkfreq_min;
92	u_int		clkfreq_max;
93};
94
95struct bwi_myaddr_bssid {
96	uint8_t		myaddr[IEEE80211_ADDR_LEN];
97	uint8_t		bssid[IEEE80211_ADDR_LEN];
98} __packed;
99
100static struct ieee80211vap *bwi_vap_create(struct ieee80211com *,
101		    const char [IFNAMSIZ], int, enum ieee80211_opmode, int,
102		    const uint8_t [IEEE80211_ADDR_LEN],
103		    const uint8_t [IEEE80211_ADDR_LEN]);
104static void	bwi_vap_delete(struct ieee80211vap *);
105static void	bwi_init(void *);
106static int	bwi_ioctl(struct ifnet *, u_long, caddr_t);
107static void	bwi_start(struct ifnet *);
108static void	bwi_start_locked(struct ifnet *);
109static int	bwi_raw_xmit(struct ieee80211_node *, struct mbuf *,
110			const struct ieee80211_bpf_params *);
111static void	bwi_watchdog(void *);
112static void	bwi_scan_start(struct ieee80211com *);
113static void	bwi_set_channel(struct ieee80211com *);
114static void	bwi_scan_end(struct ieee80211com *);
115static int	bwi_newstate(struct ieee80211vap *, enum ieee80211_state, int);
116static void	bwi_updateslot(struct ifnet *);
117static int	bwi_media_change(struct ifnet *);
118
119static void	bwi_calibrate(void *);
120
121static int	bwi_calc_rssi(struct bwi_softc *, const struct bwi_rxbuf_hdr *);
122static int	bwi_calc_noise(struct bwi_softc *);
123static __inline uint8_t bwi_plcp2rate(uint32_t, enum ieee80211_phytype);
124static void	bwi_rx_radiotap(struct bwi_softc *, struct mbuf *,
125			struct bwi_rxbuf_hdr *, const void *, int, int, int);
126
127static void	bwi_restart(void *, int);
128static void	bwi_init_statechg(struct bwi_softc *, int);
129static void	bwi_stop(struct bwi_softc *, int);
130static void	bwi_stop_locked(struct bwi_softc *, int);
131static int	bwi_newbuf(struct bwi_softc *, int, int);
132static int	bwi_encap(struct bwi_softc *, int, struct mbuf *,
133			  struct ieee80211_node *);
134static int	bwi_encap_raw(struct bwi_softc *, int, struct mbuf *,
135			  struct ieee80211_node *,
136			  const struct ieee80211_bpf_params *);
137
138static void	bwi_init_rxdesc_ring32(struct bwi_softc *, uint32_t,
139				       bus_addr_t, int, int);
140static void	bwi_reset_rx_ring32(struct bwi_softc *, uint32_t);
141
142static int	bwi_init_tx_ring32(struct bwi_softc *, int);
143static int	bwi_init_rx_ring32(struct bwi_softc *);
144static int	bwi_init_txstats32(struct bwi_softc *);
145static void	bwi_free_tx_ring32(struct bwi_softc *, int);
146static void	bwi_free_rx_ring32(struct bwi_softc *);
147static void	bwi_free_txstats32(struct bwi_softc *);
148static void	bwi_setup_rx_desc32(struct bwi_softc *, int, bus_addr_t, int);
149static void	bwi_setup_tx_desc32(struct bwi_softc *, struct bwi_ring_data *,
150				    int, bus_addr_t, int);
151static int	bwi_rxeof32(struct bwi_softc *);
152static void	bwi_start_tx32(struct bwi_softc *, uint32_t, int);
153static void	bwi_txeof_status32(struct bwi_softc *);
154
155static int	bwi_init_tx_ring64(struct bwi_softc *, int);
156static int	bwi_init_rx_ring64(struct bwi_softc *);
157static int	bwi_init_txstats64(struct bwi_softc *);
158static void	bwi_free_tx_ring64(struct bwi_softc *, int);
159static void	bwi_free_rx_ring64(struct bwi_softc *);
160static void	bwi_free_txstats64(struct bwi_softc *);
161static void	bwi_setup_rx_desc64(struct bwi_softc *, int, bus_addr_t, int);
162static void	bwi_setup_tx_desc64(struct bwi_softc *, struct bwi_ring_data *,
163				    int, bus_addr_t, int);
164static int	bwi_rxeof64(struct bwi_softc *);
165static void	bwi_start_tx64(struct bwi_softc *, uint32_t, int);
166static void	bwi_txeof_status64(struct bwi_softc *);
167
168static int	bwi_rxeof(struct bwi_softc *, int);
169static void	_bwi_txeof(struct bwi_softc *, uint16_t, int, int);
170static void	bwi_txeof(struct bwi_softc *);
171static void	bwi_txeof_status(struct bwi_softc *, int);
172static void	bwi_enable_intrs(struct bwi_softc *, uint32_t);
173static void	bwi_disable_intrs(struct bwi_softc *, uint32_t);
174
175static int	bwi_dma_alloc(struct bwi_softc *);
176static void	bwi_dma_free(struct bwi_softc *);
177static int	bwi_dma_ring_alloc(struct bwi_softc *, bus_dma_tag_t,
178				   struct bwi_ring_data *, bus_size_t,
179				   uint32_t);
180static int	bwi_dma_mbuf_create(struct bwi_softc *);
181static void	bwi_dma_mbuf_destroy(struct bwi_softc *, int, int);
182static int	bwi_dma_txstats_alloc(struct bwi_softc *, uint32_t, bus_size_t);
183static void	bwi_dma_txstats_free(struct bwi_softc *);
184static void	bwi_dma_ring_addr(void *, bus_dma_segment_t *, int, int);
185static void	bwi_dma_buf_addr(void *, bus_dma_segment_t *, int,
186				 bus_size_t, int);
187
188static void	bwi_power_on(struct bwi_softc *, int);
189static int	bwi_power_off(struct bwi_softc *, int);
190static int	bwi_set_clock_mode(struct bwi_softc *, enum bwi_clock_mode);
191static int	bwi_set_clock_delay(struct bwi_softc *);
192static void	bwi_get_clock_freq(struct bwi_softc *, struct bwi_clock_freq *);
193static int	bwi_get_pwron_delay(struct bwi_softc *sc);
194static void	bwi_set_addr_filter(struct bwi_softc *, uint16_t,
195				    const uint8_t *);
196static void	bwi_set_bssid(struct bwi_softc *, const uint8_t *);
197
198static void	bwi_get_card_flags(struct bwi_softc *);
199static void	bwi_get_eaddr(struct bwi_softc *, uint16_t, uint8_t *);
200
201static int	bwi_bus_attach(struct bwi_softc *);
202static int	bwi_bbp_attach(struct bwi_softc *);
203static int	bwi_bbp_power_on(struct bwi_softc *, enum bwi_clock_mode);
204static void	bwi_bbp_power_off(struct bwi_softc *);
205
206static const char *bwi_regwin_name(const struct bwi_regwin *);
207static uint32_t	bwi_regwin_disable_bits(struct bwi_softc *);
208static void	bwi_regwin_info(struct bwi_softc *, uint16_t *, uint8_t *);
209static int	bwi_regwin_select(struct bwi_softc *, int);
210
211static void	bwi_led_attach(struct bwi_softc *);
212static void	bwi_led_newstate(struct bwi_softc *, enum ieee80211_state);
213static void	bwi_led_event(struct bwi_softc *, int);
214static void	bwi_led_blink_start(struct bwi_softc *, int, int);
215static void	bwi_led_blink_next(void *);
216static void	bwi_led_blink_end(void *);
217
218static const struct {
219	uint16_t	did_min;
220	uint16_t	did_max;
221	uint16_t	bbp_id;
222} bwi_bbpid_map[] = {
223	{ 0x4301, 0x4301, 0x4301 },
224	{ 0x4305, 0x4307, 0x4307 },
225	{ 0x4402, 0x4403, 0x4402 },
226	{ 0x4610, 0x4615, 0x4610 },
227	{ 0x4710, 0x4715, 0x4710 },
228	{ 0x4720, 0x4725, 0x4309 }
229};
230
231static const struct {
232	uint16_t	bbp_id;
233	int		nregwin;
234} bwi_regwin_count[] = {
235	{ 0x4301, 5 },
236	{ 0x4306, 6 },
237	{ 0x4307, 5 },
238	{ 0x4310, 8 },
239	{ 0x4401, 3 },
240	{ 0x4402, 3 },
241	{ 0x4610, 9 },
242	{ 0x4704, 9 },
243	{ 0x4710, 9 },
244	{ 0x5365, 7 }
245};
246
247#define CLKSRC(src) 				\
248[BWI_CLKSRC_ ## src] = {			\
249	.freq_min = BWI_CLKSRC_ ##src## _FMIN,	\
250	.freq_max = BWI_CLKSRC_ ##src## _FMAX	\
251}
252
253static const struct {
254	u_int	freq_min;
255	u_int	freq_max;
256} bwi_clkfreq[BWI_CLKSRC_MAX] = {
257	CLKSRC(LP_OSC),
258	CLKSRC(CS_OSC),
259	CLKSRC(PCI)
260};
261
262#undef CLKSRC
263
264#define VENDOR_LED_ACT(vendor)				\
265{							\
266	.vid = PCI_VENDOR_##vendor,			\
267	.led_act = { BWI_VENDOR_LED_ACT_##vendor }	\
268}
269
270static const struct {
271#define	PCI_VENDOR_COMPAQ	0x0e11
272#define	PCI_VENDOR_LINKSYS	0x1737
273	uint16_t	vid;
274	uint8_t		led_act[BWI_LED_MAX];
275} bwi_vendor_led_act[] = {
276	VENDOR_LED_ACT(COMPAQ),
277	VENDOR_LED_ACT(LINKSYS)
278#undef PCI_VENDOR_LINKSYS
279#undef PCI_VENDOR_COMPAQ
280};
281
282static const uint8_t bwi_default_led_act[BWI_LED_MAX] =
283	{ BWI_VENDOR_LED_ACT_DEFAULT };
284
285#undef VENDOR_LED_ACT
286
287static const struct {
288	int	on_dur;
289	int	off_dur;
290} bwi_led_duration[109] = {
291	[0]	= { 400, 100 },
292	[2]	= { 150, 75 },
293	[4]	= { 90, 45 },
294	[11]	= { 66, 34 },
295	[12]	= { 53, 26 },
296	[18]	= { 42, 21 },
297	[22]	= { 35, 17 },
298	[24]	= { 32, 16 },
299	[36]	= { 21, 10 },
300	[48]	= { 16, 8 },
301	[72]	= { 11, 5 },
302	[96]	= { 9, 4 },
303	[108]	= { 7, 3 }
304};
305
306#ifdef BWI_DEBUG
307#ifdef BWI_DEBUG_VERBOSE
308static uint32_t bwi_debug = BWI_DBG_ATTACH | BWI_DBG_INIT | BWI_DBG_TXPOWER;
309#else
310static uint32_t	bwi_debug;
311#endif
312TUNABLE_INT("hw.bwi.debug", (int *)&bwi_debug);
313#endif	/* BWI_DEBUG */
314
315static const uint8_t bwi_zero_addr[IEEE80211_ADDR_LEN];
316
317uint16_t
318bwi_read_sprom(struct bwi_softc *sc, uint16_t ofs)
319{
320	return CSR_READ_2(sc, ofs + BWI_SPROM_START);
321}
322
323static __inline void
324bwi_setup_desc32(struct bwi_softc *sc, struct bwi_desc32 *desc_array,
325		 int ndesc, int desc_idx, bus_addr_t paddr, int buf_len,
326		 int tx)
327{
328	struct bwi_desc32 *desc = &desc_array[desc_idx];
329	uint32_t ctrl, addr, addr_hi, addr_lo;
330
331	addr_lo = __SHIFTOUT(paddr, BWI_DESC32_A_ADDR_MASK);
332	addr_hi = __SHIFTOUT(paddr, BWI_DESC32_A_FUNC_MASK);
333
334	addr = __SHIFTIN(addr_lo, BWI_DESC32_A_ADDR_MASK) |
335	       __SHIFTIN(BWI_DESC32_A_FUNC_TXRX, BWI_DESC32_A_FUNC_MASK);
336
337	ctrl = __SHIFTIN(buf_len, BWI_DESC32_C_BUFLEN_MASK) |
338	       __SHIFTIN(addr_hi, BWI_DESC32_C_ADDRHI_MASK);
339	if (desc_idx == ndesc - 1)
340		ctrl |= BWI_DESC32_C_EOR;
341	if (tx) {
342		/* XXX */
343		ctrl |= BWI_DESC32_C_FRAME_START |
344			BWI_DESC32_C_FRAME_END |
345			BWI_DESC32_C_INTR;
346	}
347
348	desc->addr = htole32(addr);
349	desc->ctrl = htole32(ctrl);
350}
351
352int
353bwi_attach(struct bwi_softc *sc)
354{
355	struct ieee80211com *ic;
356	device_t dev = sc->sc_dev;
357	struct ifnet *ifp;
358	struct bwi_mac *mac;
359	struct bwi_phy *phy;
360	int i, error;
361	uint8_t bands;
362	uint8_t macaddr[IEEE80211_ADDR_LEN];
363
364	BWI_LOCK_INIT(sc);
365
366	/*
367	 * Initialize taskq and various tasks
368	 */
369	sc->sc_tq = taskqueue_create("bwi_taskq", M_NOWAIT | M_ZERO,
370		taskqueue_thread_enqueue, &sc->sc_tq);
371	taskqueue_start_threads(&sc->sc_tq, 1, PI_NET, "%s taskq",
372		device_get_nameunit(dev));
373	TASK_INIT(&sc->sc_restart_task, 0, bwi_restart, sc);
374
375	callout_init_mtx(&sc->sc_calib_ch, &sc->sc_mtx, 0);
376
377	/*
378	 * Initialize sysctl variables
379	 */
380	sc->sc_fw_version = BWI_FW_VERSION3;
381	sc->sc_led_idle = (2350 * hz) / 1000;
382	sc->sc_led_blink = 1;
383	sc->sc_txpwr_calib = 1;
384#ifdef BWI_DEBUG
385	sc->sc_debug = bwi_debug;
386#endif
387	bwi_power_on(sc, 1);
388
389	error = bwi_bbp_attach(sc);
390	if (error)
391		goto fail;
392
393	error = bwi_bbp_power_on(sc, BWI_CLOCK_MODE_FAST);
394	if (error)
395		goto fail;
396
397	if (BWI_REGWIN_EXIST(&sc->sc_com_regwin)) {
398		error = bwi_set_clock_delay(sc);
399		if (error)
400			goto fail;
401
402		error = bwi_set_clock_mode(sc, BWI_CLOCK_MODE_FAST);
403		if (error)
404			goto fail;
405
406		error = bwi_get_pwron_delay(sc);
407		if (error)
408			goto fail;
409	}
410
411	error = bwi_bus_attach(sc);
412	if (error)
413		goto fail;
414
415	bwi_get_card_flags(sc);
416
417	bwi_led_attach(sc);
418
419	for (i = 0; i < sc->sc_nmac; ++i) {
420		struct bwi_regwin *old;
421
422		mac = &sc->sc_mac[i];
423		error = bwi_regwin_switch(sc, &mac->mac_regwin, &old);
424		if (error)
425			goto fail;
426
427		error = bwi_mac_lateattach(mac);
428		if (error)
429			goto fail;
430
431		error = bwi_regwin_switch(sc, old, NULL);
432		if (error)
433			goto fail;
434	}
435
436	/*
437	 * XXX First MAC is known to exist
438	 * TODO2
439	 */
440	mac = &sc->sc_mac[0];
441	phy = &mac->mac_phy;
442
443	bwi_bbp_power_off(sc);
444
445	error = bwi_dma_alloc(sc);
446	if (error)
447		goto fail;
448
449	ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
450	if (ifp == NULL) {
451		device_printf(dev, "can not if_alloc()\n");
452		error = ENOSPC;
453		goto fail;
454	}
455	ic = ifp->if_l2com;
456
457	/* set these up early for if_printf use */
458	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
459
460	ifp->if_softc = sc;
461	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
462	ifp->if_init = bwi_init;
463	ifp->if_ioctl = bwi_ioctl;
464	ifp->if_start = bwi_start;
465	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
466	ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
467	IFQ_SET_READY(&ifp->if_snd);
468	callout_init_mtx(&sc->sc_watchdog_timer, &sc->sc_mtx, 0);
469
470	/*
471	 * Setup ratesets, phytype, channels and get MAC address
472	 */
473	bands = 0;
474	if (phy->phy_mode == IEEE80211_MODE_11B ||
475	    phy->phy_mode == IEEE80211_MODE_11G) {
476		setbit(&bands, IEEE80211_MODE_11B);
477		if (phy->phy_mode == IEEE80211_MODE_11B) {
478			ic->ic_phytype = IEEE80211_T_DS;
479		} else {
480			ic->ic_phytype = IEEE80211_T_OFDM;
481			setbit(&bands, IEEE80211_MODE_11G);
482		}
483
484		bwi_get_eaddr(sc, BWI_SPROM_11BG_EADDR, macaddr);
485		if (IEEE80211_IS_MULTICAST(macaddr)) {
486			bwi_get_eaddr(sc, BWI_SPROM_11A_EADDR, macaddr);
487			if (IEEE80211_IS_MULTICAST(macaddr)) {
488				device_printf(dev,
489				    "invalid MAC address: %6D\n",
490				    macaddr, ":");
491			}
492		}
493	} else if (phy->phy_mode == IEEE80211_MODE_11A) {
494		/* TODO:11A */
495		setbit(&bands, IEEE80211_MODE_11A);
496		error = ENXIO;
497		goto fail;
498	} else {
499		panic("unknown phymode %d\n", phy->phy_mode);
500	}
501
502	/* Get locale */
503	sc->sc_locale = __SHIFTOUT(bwi_read_sprom(sc, BWI_SPROM_CARD_INFO),
504				   BWI_SPROM_CARD_INFO_LOCALE);
505	DPRINTF(sc, BWI_DBG_ATTACH, "locale: %d\n", sc->sc_locale);
506	/* XXX use locale */
507	ieee80211_init_channels(ic, NULL, &bands);
508
509	ic->ic_ifp = ifp;
510	ic->ic_caps = IEEE80211_C_STA |
511		      IEEE80211_C_SHSLOT |
512		      IEEE80211_C_SHPREAMBLE |
513		      IEEE80211_C_WPA |
514		      IEEE80211_C_BGSCAN |
515		      IEEE80211_C_MONITOR;
516	ic->ic_opmode = IEEE80211_M_STA;
517	ieee80211_ifattach(ic, macaddr);
518
519	ic->ic_headroom = sizeof(struct bwi_txbuf_hdr);
520
521	/* override default methods */
522	ic->ic_vap_create = bwi_vap_create;
523	ic->ic_vap_delete = bwi_vap_delete;
524	ic->ic_raw_xmit = bwi_raw_xmit;
525	ic->ic_updateslot = bwi_updateslot;
526	ic->ic_scan_start = bwi_scan_start;
527	ic->ic_scan_end = bwi_scan_end;
528	ic->ic_set_channel = bwi_set_channel;
529
530	sc->sc_rates = ieee80211_get_ratetable(ic->ic_curchan);
531
532	ieee80211_radiotap_attach(ic,
533	    &sc->sc_tx_th.wt_ihdr, sizeof(sc->sc_tx_th),
534		BWI_TX_RADIOTAP_PRESENT,
535	    &sc->sc_rx_th.wr_ihdr, sizeof(sc->sc_rx_th),
536		BWI_RX_RADIOTAP_PRESENT);
537
538	/*
539	 * Add sysctl nodes
540	 */
541	SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
542		        SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO,
543		        "fw_version", CTLFLAG_RD, &sc->sc_fw_version, 0,
544		        "Firmware version");
545	SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
546		        SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO,
547		        "led_idle", CTLFLAG_RW, &sc->sc_led_idle, 0,
548		        "# ticks before LED enters idle state");
549	SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
550		       SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO,
551		       "led_blink", CTLFLAG_RW, &sc->sc_led_blink, 0,
552		       "Allow LED to blink");
553	SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
554		       SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO,
555		       "txpwr_calib", CTLFLAG_RW, &sc->sc_txpwr_calib, 0,
556		       "Enable software TX power calibration");
557#ifdef BWI_DEBUG
558	SYSCTL_ADD_UINT(device_get_sysctl_ctx(dev),
559		        SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO,
560		        "debug", CTLFLAG_RW, &sc->sc_debug, 0, "Debug flags");
561#endif
562	if (bootverbose)
563		ieee80211_announce(ic);
564
565	return (0);
566fail:
567	BWI_LOCK_DESTROY(sc);
568	return (error);
569}
570
571int
572bwi_detach(struct bwi_softc *sc)
573{
574	struct ifnet *ifp = sc->sc_ifp;
575	struct ieee80211com *ic = ifp->if_l2com;
576	int i;
577
578	bwi_stop(sc, 1);
579	callout_drain(&sc->sc_led_blink_ch);
580	callout_drain(&sc->sc_calib_ch);
581	callout_drain(&sc->sc_watchdog_timer);
582	ieee80211_ifdetach(ic);
583
584	for (i = 0; i < sc->sc_nmac; ++i)
585		bwi_mac_detach(&sc->sc_mac[i]);
586	bwi_dma_free(sc);
587	if_free(ifp);
588	taskqueue_free(sc->sc_tq);
589
590	BWI_LOCK_DESTROY(sc);
591
592	return (0);
593}
594
595static struct ieee80211vap *
596bwi_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
597    enum ieee80211_opmode opmode, int flags,
598    const uint8_t bssid[IEEE80211_ADDR_LEN],
599    const uint8_t mac[IEEE80211_ADDR_LEN])
600{
601	struct bwi_vap *bvp;
602	struct ieee80211vap *vap;
603
604	if (!TAILQ_EMPTY(&ic->ic_vaps))		/* only one at a time */
605		return NULL;
606	bvp = (struct bwi_vap *) malloc(sizeof(struct bwi_vap),
607	    M_80211_VAP, M_WAITOK | M_ZERO);
608	if (bvp == NULL)
609		return NULL;
610	vap = &bvp->bv_vap;
611	/* enable s/w bmiss handling for sta mode */
612	ieee80211_vap_setup(ic, vap, name, unit, opmode,
613	    flags | IEEE80211_CLONE_NOBEACONS, bssid, mac);
614
615	/* override default methods */
616	bvp->bv_newstate = vap->iv_newstate;
617	vap->iv_newstate = bwi_newstate;
618#if 0
619	vap->iv_update_beacon = bwi_beacon_update;
620#endif
621	ieee80211_ratectl_init(vap);
622
623	/* complete setup */
624	ieee80211_vap_attach(vap, bwi_media_change, ieee80211_media_status);
625	ic->ic_opmode = opmode;
626	return vap;
627}
628
629static void
630bwi_vap_delete(struct ieee80211vap *vap)
631{
632	struct bwi_vap *bvp = BWI_VAP(vap);
633
634	ieee80211_ratectl_deinit(vap);
635	ieee80211_vap_detach(vap);
636	free(bvp, M_80211_VAP);
637}
638
639void
640bwi_suspend(struct bwi_softc *sc)
641{
642	bwi_stop(sc, 1);
643}
644
645void
646bwi_resume(struct bwi_softc *sc)
647{
648	struct ifnet *ifp = sc->sc_ifp;
649
650	if (ifp->if_flags & IFF_UP)
651		bwi_init(sc);
652}
653
654int
655bwi_shutdown(struct bwi_softc *sc)
656{
657	bwi_stop(sc, 1);
658	return 0;
659}
660
661static void
662bwi_power_on(struct bwi_softc *sc, int with_pll)
663{
664	uint32_t gpio_in, gpio_out, gpio_en;
665	uint16_t status;
666
667	gpio_in = pci_read_config(sc->sc_dev, BWI_PCIR_GPIO_IN, 4);
668	if (gpio_in & BWI_PCIM_GPIO_PWR_ON)
669		goto back;
670
671	gpio_out = pci_read_config(sc->sc_dev, BWI_PCIR_GPIO_OUT, 4);
672	gpio_en = pci_read_config(sc->sc_dev, BWI_PCIR_GPIO_ENABLE, 4);
673
674	gpio_out |= BWI_PCIM_GPIO_PWR_ON;
675	gpio_en |= BWI_PCIM_GPIO_PWR_ON;
676	if (with_pll) {
677		/* Turn off PLL first */
678		gpio_out |= BWI_PCIM_GPIO_PLL_PWR_OFF;
679		gpio_en |= BWI_PCIM_GPIO_PLL_PWR_OFF;
680	}
681
682	pci_write_config(sc->sc_dev, BWI_PCIR_GPIO_OUT, gpio_out, 4);
683	pci_write_config(sc->sc_dev, BWI_PCIR_GPIO_ENABLE, gpio_en, 4);
684	DELAY(1000);
685
686	if (with_pll) {
687		/* Turn on PLL */
688		gpio_out &= ~BWI_PCIM_GPIO_PLL_PWR_OFF;
689		pci_write_config(sc->sc_dev, BWI_PCIR_GPIO_OUT, gpio_out, 4);
690		DELAY(5000);
691	}
692
693back:
694	/* Clear "Signaled Target Abort" */
695	status = pci_read_config(sc->sc_dev, PCIR_STATUS, 2);
696	status &= ~PCIM_STATUS_STABORT;
697	pci_write_config(sc->sc_dev, PCIR_STATUS, status, 2);
698}
699
700static int
701bwi_power_off(struct bwi_softc *sc, int with_pll)
702{
703	uint32_t gpio_out, gpio_en;
704
705	pci_read_config(sc->sc_dev, BWI_PCIR_GPIO_IN, 4); /* dummy read */
706	gpio_out = pci_read_config(sc->sc_dev, BWI_PCIR_GPIO_OUT, 4);
707	gpio_en = pci_read_config(sc->sc_dev, BWI_PCIR_GPIO_ENABLE, 4);
708
709	gpio_out &= ~BWI_PCIM_GPIO_PWR_ON;
710	gpio_en |= BWI_PCIM_GPIO_PWR_ON;
711	if (with_pll) {
712		gpio_out |= BWI_PCIM_GPIO_PLL_PWR_OFF;
713		gpio_en |= BWI_PCIM_GPIO_PLL_PWR_OFF;
714	}
715
716	pci_write_config(sc->sc_dev, BWI_PCIR_GPIO_OUT, gpio_out, 4);
717	pci_write_config(sc->sc_dev, BWI_PCIR_GPIO_ENABLE, gpio_en, 4);
718	return 0;
719}
720
721int
722bwi_regwin_switch(struct bwi_softc *sc, struct bwi_regwin *rw,
723		  struct bwi_regwin **old_rw)
724{
725	int error;
726
727	if (old_rw != NULL)
728		*old_rw = NULL;
729
730	if (!BWI_REGWIN_EXIST(rw))
731		return EINVAL;
732
733	if (sc->sc_cur_regwin != rw) {
734		error = bwi_regwin_select(sc, rw->rw_id);
735		if (error) {
736			device_printf(sc->sc_dev, "can't select regwin %d\n",
737				  rw->rw_id);
738			return error;
739		}
740	}
741
742	if (old_rw != NULL)
743		*old_rw = sc->sc_cur_regwin;
744	sc->sc_cur_regwin = rw;
745	return 0;
746}
747
748static int
749bwi_regwin_select(struct bwi_softc *sc, int id)
750{
751	uint32_t win = BWI_PCIM_REGWIN(id);
752	int i;
753
754#define RETRY_MAX	50
755	for (i = 0; i < RETRY_MAX; ++i) {
756		pci_write_config(sc->sc_dev, BWI_PCIR_SEL_REGWIN, win, 4);
757		if (pci_read_config(sc->sc_dev, BWI_PCIR_SEL_REGWIN, 4) == win)
758			return 0;
759		DELAY(10);
760	}
761#undef RETRY_MAX
762
763	return ENXIO;
764}
765
766static void
767bwi_regwin_info(struct bwi_softc *sc, uint16_t *type, uint8_t *rev)
768{
769	uint32_t val;
770
771	val = CSR_READ_4(sc, BWI_ID_HI);
772	*type = BWI_ID_HI_REGWIN_TYPE(val);
773	*rev = BWI_ID_HI_REGWIN_REV(val);
774
775	DPRINTF(sc, BWI_DBG_ATTACH, "regwin: type 0x%03x, rev %d, "
776		"vendor 0x%04x\n", *type, *rev,
777		__SHIFTOUT(val, BWI_ID_HI_REGWIN_VENDOR_MASK));
778}
779
780static int
781bwi_bbp_attach(struct bwi_softc *sc)
782{
783#define N(arr)	(int)(sizeof(arr) / sizeof(arr[0]))
784	uint16_t bbp_id, rw_type;
785	uint8_t rw_rev;
786	uint32_t info;
787	int error, nregwin, i;
788
789	/*
790	 * Get 0th regwin information
791	 * NOTE: 0th regwin should exist
792	 */
793	error = bwi_regwin_select(sc, 0);
794	if (error) {
795		device_printf(sc->sc_dev, "can't select regwin 0\n");
796		return error;
797	}
798	bwi_regwin_info(sc, &rw_type, &rw_rev);
799
800	/*
801	 * Find out BBP id
802	 */
803	bbp_id = 0;
804	info = 0;
805	if (rw_type == BWI_REGWIN_T_COM) {
806		info = CSR_READ_4(sc, BWI_INFO);
807		bbp_id = __SHIFTOUT(info, BWI_INFO_BBPID_MASK);
808
809		BWI_CREATE_REGWIN(&sc->sc_com_regwin, 0, rw_type, rw_rev);
810
811		sc->sc_cap = CSR_READ_4(sc, BWI_CAPABILITY);
812	} else {
813		for (i = 0; i < N(bwi_bbpid_map); ++i) {
814			if (sc->sc_pci_did >= bwi_bbpid_map[i].did_min &&
815			    sc->sc_pci_did <= bwi_bbpid_map[i].did_max) {
816				bbp_id = bwi_bbpid_map[i].bbp_id;
817				break;
818			}
819		}
820		if (bbp_id == 0) {
821			device_printf(sc->sc_dev, "no BBP id for device id "
822				      "0x%04x\n", sc->sc_pci_did);
823			return ENXIO;
824		}
825
826		info = __SHIFTIN(sc->sc_pci_revid, BWI_INFO_BBPREV_MASK) |
827		       __SHIFTIN(0, BWI_INFO_BBPPKG_MASK);
828	}
829
830	/*
831	 * Find out number of regwins
832	 */
833	nregwin = 0;
834	if (rw_type == BWI_REGWIN_T_COM && rw_rev >= 4) {
835		nregwin = __SHIFTOUT(info, BWI_INFO_NREGWIN_MASK);
836	} else {
837		for (i = 0; i < N(bwi_regwin_count); ++i) {
838			if (bwi_regwin_count[i].bbp_id == bbp_id) {
839				nregwin = bwi_regwin_count[i].nregwin;
840				break;
841			}
842		}
843		if (nregwin == 0) {
844			device_printf(sc->sc_dev, "no number of win for "
845				      "BBP id 0x%04x\n", bbp_id);
846			return ENXIO;
847		}
848	}
849
850	/* Record BBP id/rev for later using */
851	sc->sc_bbp_id = bbp_id;
852	sc->sc_bbp_rev = __SHIFTOUT(info, BWI_INFO_BBPREV_MASK);
853	sc->sc_bbp_pkg = __SHIFTOUT(info, BWI_INFO_BBPPKG_MASK);
854	device_printf(sc->sc_dev, "BBP: id 0x%04x, rev 0x%x, pkg %d\n",
855		      sc->sc_bbp_id, sc->sc_bbp_rev, sc->sc_bbp_pkg);
856
857	DPRINTF(sc, BWI_DBG_ATTACH, "nregwin %d, cap 0x%08x\n",
858		nregwin, sc->sc_cap);
859
860	/*
861	 * Create rest of the regwins
862	 */
863
864	/* Don't re-create common regwin, if it is already created */
865	i = BWI_REGWIN_EXIST(&sc->sc_com_regwin) ? 1 : 0;
866
867	for (; i < nregwin; ++i) {
868		/*
869		 * Get regwin information
870		 */
871		error = bwi_regwin_select(sc, i);
872		if (error) {
873			device_printf(sc->sc_dev,
874				      "can't select regwin %d\n", i);
875			return error;
876		}
877		bwi_regwin_info(sc, &rw_type, &rw_rev);
878
879		/*
880		 * Try attach:
881		 * 1) Bus (PCI/PCIE) regwin
882		 * 2) MAC regwin
883		 * Ignore rest types of regwin
884		 */
885		if (rw_type == BWI_REGWIN_T_BUSPCI ||
886		    rw_type == BWI_REGWIN_T_BUSPCIE) {
887			if (BWI_REGWIN_EXIST(&sc->sc_bus_regwin)) {
888				device_printf(sc->sc_dev,
889					      "bus regwin already exists\n");
890			} else {
891				BWI_CREATE_REGWIN(&sc->sc_bus_regwin, i,
892						  rw_type, rw_rev);
893			}
894		} else if (rw_type == BWI_REGWIN_T_MAC) {
895			/* XXX ignore return value */
896			bwi_mac_attach(sc, i, rw_rev);
897		}
898	}
899
900	/* At least one MAC shold exist */
901	if (!BWI_REGWIN_EXIST(&sc->sc_mac[0].mac_regwin)) {
902		device_printf(sc->sc_dev, "no MAC was found\n");
903		return ENXIO;
904	}
905	KASSERT(sc->sc_nmac > 0, ("no mac's"));
906
907	/* Bus regwin must exist */
908	if (!BWI_REGWIN_EXIST(&sc->sc_bus_regwin)) {
909		device_printf(sc->sc_dev, "no bus regwin was found\n");
910		return ENXIO;
911	}
912
913	/* Start with first MAC */
914	error = bwi_regwin_switch(sc, &sc->sc_mac[0].mac_regwin, NULL);
915	if (error)
916		return error;
917
918	return 0;
919#undef N
920}
921
922int
923bwi_bus_init(struct bwi_softc *sc, struct bwi_mac *mac)
924{
925	struct bwi_regwin *old, *bus;
926	uint32_t val;
927	int error;
928
929	bus = &sc->sc_bus_regwin;
930	KASSERT(sc->sc_cur_regwin == &mac->mac_regwin, ("not cur regwin"));
931
932	/*
933	 * Tell bus to generate requested interrupts
934	 */
935	if (bus->rw_rev < 6 && bus->rw_type == BWI_REGWIN_T_BUSPCI) {
936		/*
937		 * NOTE: Read BWI_FLAGS from MAC regwin
938		 */
939		val = CSR_READ_4(sc, BWI_FLAGS);
940
941		error = bwi_regwin_switch(sc, bus, &old);
942		if (error)
943			return error;
944
945		CSR_SETBITS_4(sc, BWI_INTRVEC, (val & BWI_FLAGS_INTR_MASK));
946	} else {
947		uint32_t mac_mask;
948
949		mac_mask = 1 << mac->mac_id;
950
951		error = bwi_regwin_switch(sc, bus, &old);
952		if (error)
953			return error;
954
955		val = pci_read_config(sc->sc_dev, BWI_PCIR_INTCTL, 4);
956		val |= mac_mask << 8;
957		pci_write_config(sc->sc_dev, BWI_PCIR_INTCTL, val, 4);
958	}
959
960	if (sc->sc_flags & BWI_F_BUS_INITED)
961		goto back;
962
963	if (bus->rw_type == BWI_REGWIN_T_BUSPCI) {
964		/*
965		 * Enable prefetch and burst
966		 */
967		CSR_SETBITS_4(sc, BWI_BUS_CONFIG,
968			      BWI_BUS_CONFIG_PREFETCH | BWI_BUS_CONFIG_BURST);
969
970		if (bus->rw_rev < 5) {
971			struct bwi_regwin *com = &sc->sc_com_regwin;
972
973			/*
974			 * Configure timeouts for bus operation
975			 */
976
977			/*
978			 * Set service timeout and request timeout
979			 */
980			CSR_SETBITS_4(sc, BWI_CONF_LO,
981			__SHIFTIN(BWI_CONF_LO_SERVTO, BWI_CONF_LO_SERVTO_MASK) |
982			__SHIFTIN(BWI_CONF_LO_REQTO, BWI_CONF_LO_REQTO_MASK));
983
984			/*
985			 * If there is common regwin, we switch to that regwin
986			 * and switch back to bus regwin once we have done.
987			 */
988			if (BWI_REGWIN_EXIST(com)) {
989				error = bwi_regwin_switch(sc, com, NULL);
990				if (error)
991					return error;
992			}
993
994			/* Let bus know what we have changed */
995			CSR_WRITE_4(sc, BWI_BUS_ADDR, BWI_BUS_ADDR_MAGIC);
996			CSR_READ_4(sc, BWI_BUS_ADDR); /* Flush */
997			CSR_WRITE_4(sc, BWI_BUS_DATA, 0);
998			CSR_READ_4(sc, BWI_BUS_DATA); /* Flush */
999
1000			if (BWI_REGWIN_EXIST(com)) {
1001				error = bwi_regwin_switch(sc, bus, NULL);
1002				if (error)
1003					return error;
1004			}
1005		} else if (bus->rw_rev >= 11) {
1006			/*
1007			 * Enable memory read multiple
1008			 */
1009			CSR_SETBITS_4(sc, BWI_BUS_CONFIG, BWI_BUS_CONFIG_MRM);
1010		}
1011	} else {
1012		/* TODO:PCIE */
1013	}
1014
1015	sc->sc_flags |= BWI_F_BUS_INITED;
1016back:
1017	return bwi_regwin_switch(sc, old, NULL);
1018}
1019
1020static void
1021bwi_get_card_flags(struct bwi_softc *sc)
1022{
1023#define	PCI_VENDOR_APPLE 0x106b
1024#define	PCI_VENDOR_DELL  0x1028
1025	sc->sc_card_flags = bwi_read_sprom(sc, BWI_SPROM_CARD_FLAGS);
1026	if (sc->sc_card_flags == 0xffff)
1027		sc->sc_card_flags = 0;
1028
1029	if (sc->sc_pci_subvid == PCI_VENDOR_DELL &&
1030	    sc->sc_bbp_id == BWI_BBPID_BCM4301 &&
1031	    sc->sc_pci_revid == 0x74)
1032		sc->sc_card_flags |= BWI_CARD_F_BT_COEXIST;
1033
1034	if (sc->sc_pci_subvid == PCI_VENDOR_APPLE &&
1035	    sc->sc_pci_subdid == 0x4e && /* XXX */
1036	    sc->sc_pci_revid > 0x40)
1037		sc->sc_card_flags |= BWI_CARD_F_PA_GPIO9;
1038
1039	DPRINTF(sc, BWI_DBG_ATTACH, "card flags 0x%04x\n", sc->sc_card_flags);
1040#undef PCI_VENDOR_DELL
1041#undef PCI_VENDOR_APPLE
1042}
1043
1044static void
1045bwi_get_eaddr(struct bwi_softc *sc, uint16_t eaddr_ofs, uint8_t *eaddr)
1046{
1047	int i;
1048
1049	for (i = 0; i < 3; ++i) {
1050		*((uint16_t *)eaddr + i) =
1051			htobe16(bwi_read_sprom(sc, eaddr_ofs + 2 * i));
1052	}
1053}
1054
1055static void
1056bwi_get_clock_freq(struct bwi_softc *sc, struct bwi_clock_freq *freq)
1057{
1058	struct bwi_regwin *com;
1059	uint32_t val;
1060	u_int div;
1061	int src;
1062
1063	bzero(freq, sizeof(*freq));
1064	com = &sc->sc_com_regwin;
1065
1066	KASSERT(BWI_REGWIN_EXIST(com), ("regwin does not exist"));
1067	KASSERT(sc->sc_cur_regwin == com, ("wrong regwin"));
1068	KASSERT(sc->sc_cap & BWI_CAP_CLKMODE, ("wrong clock mode"));
1069
1070	/*
1071	 * Calculate clock frequency
1072	 */
1073	src = -1;
1074	div = 0;
1075	if (com->rw_rev < 6) {
1076		val = pci_read_config(sc->sc_dev, BWI_PCIR_GPIO_OUT, 4);
1077		if (val & BWI_PCIM_GPIO_OUT_CLKSRC) {
1078			src = BWI_CLKSRC_PCI;
1079			div = 64;
1080		} else {
1081			src = BWI_CLKSRC_CS_OSC;
1082			div = 32;
1083		}
1084	} else if (com->rw_rev < 10) {
1085		val = CSR_READ_4(sc, BWI_CLOCK_CTRL);
1086
1087		src = __SHIFTOUT(val, BWI_CLOCK_CTRL_CLKSRC);
1088		if (src == BWI_CLKSRC_LP_OSC) {
1089			div = 1;
1090		} else {
1091			div = (__SHIFTOUT(val, BWI_CLOCK_CTRL_FDIV) + 1) << 2;
1092
1093			/* Unknown source */
1094			if (src >= BWI_CLKSRC_MAX)
1095				src = BWI_CLKSRC_CS_OSC;
1096		}
1097	} else {
1098		val = CSR_READ_4(sc, BWI_CLOCK_INFO);
1099
1100		src = BWI_CLKSRC_CS_OSC;
1101		div = (__SHIFTOUT(val, BWI_CLOCK_INFO_FDIV) + 1) << 2;
1102	}
1103
1104	KASSERT(src >= 0 && src < BWI_CLKSRC_MAX, ("bad src %d", src));
1105	KASSERT(div != 0, ("div zero"));
1106
1107	DPRINTF(sc, BWI_DBG_ATTACH, "clksrc %s\n",
1108		src == BWI_CLKSRC_PCI ? "PCI" :
1109		(src == BWI_CLKSRC_LP_OSC ? "LP_OSC" : "CS_OSC"));
1110
1111	freq->clkfreq_min = bwi_clkfreq[src].freq_min / div;
1112	freq->clkfreq_max = bwi_clkfreq[src].freq_max / div;
1113
1114	DPRINTF(sc, BWI_DBG_ATTACH, "clkfreq min %u, max %u\n",
1115		freq->clkfreq_min, freq->clkfreq_max);
1116}
1117
1118static int
1119bwi_set_clock_mode(struct bwi_softc *sc, enum bwi_clock_mode clk_mode)
1120{
1121	struct bwi_regwin *old, *com;
1122	uint32_t clk_ctrl, clk_src;
1123	int error, pwr_off = 0;
1124
1125	com = &sc->sc_com_regwin;
1126	if (!BWI_REGWIN_EXIST(com))
1127		return 0;
1128
1129	if (com->rw_rev >= 10 || com->rw_rev < 6)
1130		return 0;
1131
1132	/*
1133	 * For common regwin whose rev is [6, 10), the chip
1134	 * must be capable to change clock mode.
1135	 */
1136	if ((sc->sc_cap & BWI_CAP_CLKMODE) == 0)
1137		return 0;
1138
1139	error = bwi_regwin_switch(sc, com, &old);
1140	if (error)
1141		return error;
1142
1143	if (clk_mode == BWI_CLOCK_MODE_FAST)
1144		bwi_power_on(sc, 0);	/* Don't turn on PLL */
1145
1146	clk_ctrl = CSR_READ_4(sc, BWI_CLOCK_CTRL);
1147	clk_src = __SHIFTOUT(clk_ctrl, BWI_CLOCK_CTRL_CLKSRC);
1148
1149	switch (clk_mode) {
1150	case BWI_CLOCK_MODE_FAST:
1151		clk_ctrl &= ~BWI_CLOCK_CTRL_SLOW;
1152		clk_ctrl |= BWI_CLOCK_CTRL_IGNPLL;
1153		break;
1154	case BWI_CLOCK_MODE_SLOW:
1155		clk_ctrl |= BWI_CLOCK_CTRL_SLOW;
1156		break;
1157	case BWI_CLOCK_MODE_DYN:
1158		clk_ctrl &= ~(BWI_CLOCK_CTRL_SLOW |
1159			      BWI_CLOCK_CTRL_IGNPLL |
1160			      BWI_CLOCK_CTRL_NODYN);
1161		if (clk_src != BWI_CLKSRC_CS_OSC) {
1162			clk_ctrl |= BWI_CLOCK_CTRL_NODYN;
1163			pwr_off = 1;
1164		}
1165		break;
1166	}
1167	CSR_WRITE_4(sc, BWI_CLOCK_CTRL, clk_ctrl);
1168
1169	if (pwr_off)
1170		bwi_power_off(sc, 0);	/* Leave PLL as it is */
1171
1172	return bwi_regwin_switch(sc, old, NULL);
1173}
1174
1175static int
1176bwi_set_clock_delay(struct bwi_softc *sc)
1177{
1178	struct bwi_regwin *old, *com;
1179	int error;
1180
1181	com = &sc->sc_com_regwin;
1182	if (!BWI_REGWIN_EXIST(com))
1183		return 0;
1184
1185	error = bwi_regwin_switch(sc, com, &old);
1186	if (error)
1187		return error;
1188
1189	if (sc->sc_bbp_id == BWI_BBPID_BCM4321) {
1190		if (sc->sc_bbp_rev == 0)
1191			CSR_WRITE_4(sc, BWI_CONTROL, BWI_CONTROL_MAGIC0);
1192		else if (sc->sc_bbp_rev == 1)
1193			CSR_WRITE_4(sc, BWI_CONTROL, BWI_CONTROL_MAGIC1);
1194	}
1195
1196	if (sc->sc_cap & BWI_CAP_CLKMODE) {
1197		if (com->rw_rev >= 10) {
1198			CSR_FILT_SETBITS_4(sc, BWI_CLOCK_INFO, 0xffff, 0x40000);
1199		} else {
1200			struct bwi_clock_freq freq;
1201
1202			bwi_get_clock_freq(sc, &freq);
1203			CSR_WRITE_4(sc, BWI_PLL_ON_DELAY,
1204				howmany(freq.clkfreq_max * 150, 1000000));
1205			CSR_WRITE_4(sc, BWI_FREQ_SEL_DELAY,
1206				howmany(freq.clkfreq_max * 15, 1000000));
1207		}
1208	}
1209
1210	return bwi_regwin_switch(sc, old, NULL);
1211}
1212
1213static void
1214bwi_init(void *xsc)
1215{
1216	struct bwi_softc *sc = xsc;
1217	struct ifnet *ifp = sc->sc_ifp;
1218	struct ieee80211com *ic = ifp->if_l2com;
1219
1220	BWI_LOCK(sc);
1221	bwi_init_statechg(sc, 1);
1222	BWI_UNLOCK(sc);
1223
1224	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1225		ieee80211_start_all(ic);		/* start all vap's */
1226}
1227
1228static void
1229bwi_init_statechg(struct bwi_softc *sc, int statechg)
1230{
1231	struct ifnet *ifp = sc->sc_ifp;
1232	struct bwi_mac *mac;
1233	int error;
1234
1235	bwi_stop_locked(sc, statechg);
1236
1237	bwi_bbp_power_on(sc, BWI_CLOCK_MODE_FAST);
1238
1239	/* TODO: 2 MAC */
1240
1241	mac = &sc->sc_mac[0];
1242	error = bwi_regwin_switch(sc, &mac->mac_regwin, NULL);
1243	if (error) {
1244		if_printf(ifp, "%s: error %d on regwin switch\n",
1245		    __func__, error);
1246		goto bad;
1247	}
1248	error = bwi_mac_init(mac);
1249	if (error) {
1250		if_printf(ifp, "%s: error %d on MAC init\n", __func__, error);
1251		goto bad;
1252	}
1253
1254	bwi_bbp_power_on(sc, BWI_CLOCK_MODE_DYN);
1255
1256	bwi_set_bssid(sc, bwi_zero_addr);	/* Clear BSSID */
1257	bwi_set_addr_filter(sc, BWI_ADDR_FILTER_MYADDR, IF_LLADDR(ifp));
1258
1259	bwi_mac_reset_hwkeys(mac);
1260
1261	if ((mac->mac_flags & BWI_MAC_F_HAS_TXSTATS) == 0) {
1262		int i;
1263
1264#define NRETRY	1000
1265		/*
1266		 * Drain any possible pending TX status
1267		 */
1268		for (i = 0; i < NRETRY; ++i) {
1269			if ((CSR_READ_4(sc, BWI_TXSTATUS0) &
1270			     BWI_TXSTATUS0_VALID) == 0)
1271				break;
1272			CSR_READ_4(sc, BWI_TXSTATUS1);
1273		}
1274		if (i == NRETRY)
1275			if_printf(ifp, "%s: can't drain TX status\n", __func__);
1276#undef NRETRY
1277	}
1278
1279	if (mac->mac_phy.phy_mode == IEEE80211_MODE_11G)
1280		bwi_mac_updateslot(mac, 1);
1281
1282	/* Start MAC */
1283	error = bwi_mac_start(mac);
1284	if (error) {
1285		if_printf(ifp, "%s: error %d starting MAC\n", __func__, error);
1286		goto bad;
1287	}
1288
1289	/* Clear stop flag before enabling interrupt */
1290	sc->sc_flags &= ~BWI_F_STOP;
1291
1292	ifp->if_drv_flags |= IFF_DRV_RUNNING;
1293	callout_reset(&sc->sc_watchdog_timer, hz, bwi_watchdog, sc);
1294
1295	/* Enable intrs */
1296	bwi_enable_intrs(sc, BWI_INIT_INTRS);
1297	return;
1298bad:
1299	bwi_stop_locked(sc, 1);
1300}
1301
1302static int
1303bwi_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1304{
1305#define	IS_RUNNING(ifp) \
1306	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
1307	struct bwi_softc *sc = ifp->if_softc;
1308	struct ieee80211com *ic = ifp->if_l2com;
1309	struct ifreq *ifr = (struct ifreq *) data;
1310	int error = 0, startall = 0;
1311
1312	switch (cmd) {
1313	case SIOCSIFFLAGS:
1314		BWI_LOCK(sc);
1315		if (IS_RUNNING(ifp)) {
1316			struct bwi_mac *mac;
1317			int promisc = -1;
1318
1319			KASSERT(sc->sc_cur_regwin->rw_type == BWI_REGWIN_T_MAC,
1320			    ("current regwin type %d",
1321			    sc->sc_cur_regwin->rw_type));
1322			mac = (struct bwi_mac *)sc->sc_cur_regwin;
1323
1324			if ((ifp->if_flags & IFF_PROMISC) &&
1325			    (sc->sc_flags & BWI_F_PROMISC) == 0) {
1326				promisc = 1;
1327				sc->sc_flags |= BWI_F_PROMISC;
1328			} else if ((ifp->if_flags & IFF_PROMISC) == 0 &&
1329				   (sc->sc_flags & BWI_F_PROMISC)) {
1330				promisc = 0;
1331				sc->sc_flags &= ~BWI_F_PROMISC;
1332			}
1333
1334			if (promisc >= 0)
1335				bwi_mac_set_promisc(mac, promisc);
1336		}
1337
1338		if (ifp->if_flags & IFF_UP) {
1339			if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1340				bwi_init_statechg(sc, 1);
1341				startall = 1;
1342			}
1343		} else {
1344			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1345				bwi_stop_locked(sc, 1);
1346		}
1347		BWI_UNLOCK(sc);
1348		if (startall)
1349			ieee80211_start_all(ic);
1350		break;
1351	case SIOCGIFMEDIA:
1352		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
1353		break;
1354	case SIOCGIFADDR:
1355		error = ether_ioctl(ifp, cmd, data);
1356		break;
1357	default:
1358		error = EINVAL;
1359		break;
1360	}
1361	return error;
1362#undef IS_RUNNING
1363}
1364
1365static void
1366bwi_start(struct ifnet *ifp)
1367{
1368	struct bwi_softc *sc = ifp->if_softc;
1369
1370	BWI_LOCK(sc);
1371	bwi_start_locked(ifp);
1372	BWI_UNLOCK(sc);
1373}
1374
1375static void
1376bwi_start_locked(struct ifnet *ifp)
1377{
1378	struct bwi_softc *sc = ifp->if_softc;
1379	struct bwi_txbuf_data *tbd = &sc->sc_tx_bdata[BWI_TX_DATA_RING];
1380	struct ieee80211_frame *wh;
1381	struct ieee80211_node *ni;
1382	struct ieee80211_key *k;
1383	struct mbuf *m;
1384	int trans, idx;
1385
1386	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
1387		return;
1388
1389	trans = 0;
1390	idx = tbd->tbd_idx;
1391
1392	while (tbd->tbd_buf[idx].tb_mbuf == NULL) {
1393		IFQ_DRV_DEQUEUE(&ifp->if_snd, m);	/* XXX: LOCK */
1394		if (m == NULL)
1395			break;
1396
1397		ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1398		wh = mtod(m, struct ieee80211_frame *);
1399		if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1400			k = ieee80211_crypto_encap(ni, m);
1401			if (k == NULL) {
1402				ieee80211_free_node(ni);
1403				m_freem(m);
1404				ifp->if_oerrors++;
1405				continue;
1406			}
1407		}
1408		wh = NULL;	/* Catch any invalid use */
1409
1410		if (bwi_encap(sc, idx, m, ni) != 0) {
1411			/* 'm' is freed in bwi_encap() if we reach here */
1412			if (ni != NULL)
1413				ieee80211_free_node(ni);
1414			ifp->if_oerrors++;
1415			continue;
1416		}
1417
1418		trans = 1;
1419		tbd->tbd_used++;
1420		idx = (idx + 1) % BWI_TX_NDESC;
1421
1422		ifp->if_opackets++;
1423
1424		if (tbd->tbd_used + BWI_TX_NSPRDESC >= BWI_TX_NDESC) {
1425			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1426			break;
1427		}
1428	}
1429	tbd->tbd_idx = idx;
1430
1431	if (trans)
1432		sc->sc_tx_timer = 5;
1433}
1434
1435static int
1436bwi_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
1437	const struct ieee80211_bpf_params *params)
1438{
1439	struct ieee80211com *ic = ni->ni_ic;
1440	struct ifnet *ifp = ic->ic_ifp;
1441	struct bwi_softc *sc = ifp->if_softc;
1442	/* XXX wme? */
1443	struct bwi_txbuf_data *tbd = &sc->sc_tx_bdata[BWI_TX_DATA_RING];
1444	int idx, error;
1445
1446	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1447		ieee80211_free_node(ni);
1448		m_freem(m);
1449		return ENETDOWN;
1450	}
1451
1452	BWI_LOCK(sc);
1453	idx = tbd->tbd_idx;
1454	KASSERT(tbd->tbd_buf[idx].tb_mbuf == NULL, ("slot %d not empty", idx));
1455	if (params == NULL) {
1456		/*
1457		 * Legacy path; interpret frame contents to decide
1458		 * precisely how to send the frame.
1459		 */
1460		error = bwi_encap(sc, idx, m, ni);
1461	} else {
1462		/*
1463		 * Caller supplied explicit parameters to use in
1464		 * sending the frame.
1465		 */
1466		error = bwi_encap_raw(sc, idx, m, ni, params);
1467	}
1468	if (error == 0) {
1469		ifp->if_opackets++;
1470		if (++tbd->tbd_used + BWI_TX_NSPRDESC >= BWI_TX_NDESC)
1471			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1472		tbd->tbd_idx = (idx + 1) % BWI_TX_NDESC;
1473		sc->sc_tx_timer = 5;
1474	} else {
1475		/* NB: m is reclaimed on encap failure */
1476		ieee80211_free_node(ni);
1477		ifp->if_oerrors++;
1478	}
1479	BWI_UNLOCK(sc);
1480	return error;
1481}
1482
1483static void
1484bwi_watchdog(void *arg)
1485{
1486	struct bwi_softc *sc;
1487	struct ifnet *ifp;
1488
1489	sc = arg;
1490	ifp = sc->sc_ifp;
1491	BWI_ASSERT_LOCKED(sc);
1492	if (sc->sc_tx_timer != 0 && --sc->sc_tx_timer == 0) {
1493		if_printf(ifp, "watchdog timeout\n");
1494		ifp->if_oerrors++;
1495		taskqueue_enqueue(sc->sc_tq, &sc->sc_restart_task);
1496	}
1497	callout_reset(&sc->sc_watchdog_timer, hz, bwi_watchdog, sc);
1498}
1499
1500static void
1501bwi_stop(struct bwi_softc *sc, int statechg)
1502{
1503	BWI_LOCK(sc);
1504	bwi_stop_locked(sc, statechg);
1505	BWI_UNLOCK(sc);
1506}
1507
1508static void
1509bwi_stop_locked(struct bwi_softc *sc, int statechg)
1510{
1511	struct ifnet *ifp = sc->sc_ifp;
1512	struct bwi_mac *mac;
1513	int i, error, pwr_off = 0;
1514
1515	BWI_ASSERT_LOCKED(sc);
1516
1517	callout_stop(&sc->sc_calib_ch);
1518	callout_stop(&sc->sc_led_blink_ch);
1519	sc->sc_led_blinking = 0;
1520	sc->sc_flags |= BWI_F_STOP;
1521
1522	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1523		KASSERT(sc->sc_cur_regwin->rw_type == BWI_REGWIN_T_MAC,
1524		    ("current regwin type %d", sc->sc_cur_regwin->rw_type));
1525		mac = (struct bwi_mac *)sc->sc_cur_regwin;
1526
1527		bwi_disable_intrs(sc, BWI_ALL_INTRS);
1528		CSR_READ_4(sc, BWI_MAC_INTR_MASK);
1529		bwi_mac_stop(mac);
1530	}
1531
1532	for (i = 0; i < sc->sc_nmac; ++i) {
1533		struct bwi_regwin *old_rw;
1534
1535		mac = &sc->sc_mac[i];
1536		if ((mac->mac_flags & BWI_MAC_F_INITED) == 0)
1537			continue;
1538
1539		error = bwi_regwin_switch(sc, &mac->mac_regwin, &old_rw);
1540		if (error)
1541			continue;
1542
1543		bwi_mac_shutdown(mac);
1544		pwr_off = 1;
1545
1546		bwi_regwin_switch(sc, old_rw, NULL);
1547	}
1548
1549	if (pwr_off)
1550		bwi_bbp_power_off(sc);
1551
1552	sc->sc_tx_timer = 0;
1553	callout_stop(&sc->sc_watchdog_timer);
1554	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
1555}
1556
1557void
1558bwi_intr(void *xsc)
1559{
1560	struct bwi_softc *sc = xsc;
1561	struct ifnet *ifp = sc->sc_ifp;
1562	struct bwi_mac *mac;
1563	uint32_t intr_status;
1564	uint32_t txrx_intr_status[BWI_TXRX_NRING];
1565	int i, txrx_error, tx = 0, rx_data = -1;
1566
1567	BWI_LOCK(sc);
1568
1569	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
1570	    (sc->sc_flags & BWI_F_STOP)) {
1571		BWI_UNLOCK(sc);
1572		return;
1573	}
1574	/*
1575	 * Get interrupt status
1576	 */
1577	intr_status = CSR_READ_4(sc, BWI_MAC_INTR_STATUS);
1578	if (intr_status == 0xffffffff) {	/* Not for us */
1579		BWI_UNLOCK(sc);
1580		return;
1581	}
1582
1583	DPRINTF(sc, BWI_DBG_INTR, "intr status 0x%08x\n", intr_status);
1584
1585	intr_status &= CSR_READ_4(sc, BWI_MAC_INTR_MASK);
1586	if (intr_status == 0) {		/* Nothing is interesting */
1587		BWI_UNLOCK(sc);
1588		return;
1589	}
1590
1591	KASSERT(sc->sc_cur_regwin->rw_type == BWI_REGWIN_T_MAC,
1592	    ("current regwin type %d", sc->sc_cur_regwin->rw_type));
1593	mac = (struct bwi_mac *)sc->sc_cur_regwin;
1594
1595	txrx_error = 0;
1596	DPRINTF(sc, BWI_DBG_INTR, "%s\n", "TX/RX intr");
1597	for (i = 0; i < BWI_TXRX_NRING; ++i) {
1598		uint32_t mask;
1599
1600		if (BWI_TXRX_IS_RX(i))
1601			mask = BWI_TXRX_RX_INTRS;
1602		else
1603			mask = BWI_TXRX_TX_INTRS;
1604
1605		txrx_intr_status[i] =
1606		CSR_READ_4(sc, BWI_TXRX_INTR_STATUS(i)) & mask;
1607
1608		_DPRINTF(sc, BWI_DBG_INTR, ", %d 0x%08x",
1609			 i, txrx_intr_status[i]);
1610
1611		if (txrx_intr_status[i] & BWI_TXRX_INTR_ERROR) {
1612			if_printf(ifp,
1613			    "%s: intr fatal TX/RX (%d) error 0x%08x\n",
1614			    __func__, i, txrx_intr_status[i]);
1615			txrx_error = 1;
1616		}
1617	}
1618	_DPRINTF(sc, BWI_DBG_INTR, "%s\n", "");
1619
1620	/*
1621	 * Acknowledge interrupt
1622	 */
1623	CSR_WRITE_4(sc, BWI_MAC_INTR_STATUS, intr_status);
1624
1625	for (i = 0; i < BWI_TXRX_NRING; ++i)
1626		CSR_WRITE_4(sc, BWI_TXRX_INTR_STATUS(i), txrx_intr_status[i]);
1627
1628	/* Disable all interrupts */
1629	bwi_disable_intrs(sc, BWI_ALL_INTRS);
1630
1631	/*
1632	 * http://bcm-specs.sipsolutions.net/Interrupts
1633	 * Says for this bit (0x800):
1634	 * "Fatal Error
1635	 *
1636	 * We got this one while testing things when by accident the
1637	 * template ram wasn't set to big endian when it should have
1638	 * been after writing the initial values. It keeps on being
1639	 * triggered, the only way to stop it seems to shut down the
1640	 * chip."
1641	 *
1642	 * Suggesting that we should never get it and if we do we're not
1643	 * feeding TX packets into the MAC correctly if we do...  Apparently,
1644	 * it is valid only on mac version 5 and higher, but I couldn't
1645	 * find a reference for that...  Since I see them from time to time
1646	 * on my card, this suggests an error in the tx path still...
1647	 */
1648	if (intr_status & BWI_INTR_PHY_TXERR) {
1649		if (mac->mac_flags & BWI_MAC_F_PHYE_RESET) {
1650			if_printf(ifp, "%s: intr PHY TX error\n", __func__);
1651			taskqueue_enqueue(sc->sc_tq, &sc->sc_restart_task);
1652			BWI_UNLOCK(sc);
1653			return;
1654		}
1655	}
1656
1657	if (txrx_error) {
1658		/* TODO: reset device */
1659	}
1660
1661	if (intr_status & BWI_INTR_TBTT)
1662		bwi_mac_config_ps(mac);
1663
1664	if (intr_status & BWI_INTR_EO_ATIM)
1665		if_printf(ifp, "EO_ATIM\n");
1666
1667	if (intr_status & BWI_INTR_PMQ) {
1668		for (;;) {
1669			if ((CSR_READ_4(sc, BWI_MAC_PS_STATUS) & 0x8) == 0)
1670				break;
1671		}
1672		CSR_WRITE_2(sc, BWI_MAC_PS_STATUS, 0x2);
1673	}
1674
1675	if (intr_status & BWI_INTR_NOISE)
1676		if_printf(ifp, "intr noise\n");
1677
1678	if (txrx_intr_status[0] & BWI_TXRX_INTR_RX) {
1679		rx_data = sc->sc_rxeof(sc);
1680		if (sc->sc_flags & BWI_F_STOP) {
1681			BWI_UNLOCK(sc);
1682			return;
1683		}
1684	}
1685
1686	if (txrx_intr_status[3] & BWI_TXRX_INTR_RX) {
1687		sc->sc_txeof_status(sc);
1688		tx = 1;
1689	}
1690
1691	if (intr_status & BWI_INTR_TX_DONE) {
1692		bwi_txeof(sc);
1693		tx = 1;
1694	}
1695
1696	/* Re-enable interrupts */
1697	bwi_enable_intrs(sc, BWI_INIT_INTRS);
1698
1699	if (sc->sc_blink_led != NULL && sc->sc_led_blink) {
1700		int evt = BWI_LED_EVENT_NONE;
1701
1702		if (tx && rx_data > 0) {
1703			if (sc->sc_rx_rate > sc->sc_tx_rate)
1704				evt = BWI_LED_EVENT_RX;
1705			else
1706				evt = BWI_LED_EVENT_TX;
1707		} else if (tx) {
1708			evt = BWI_LED_EVENT_TX;
1709		} else if (rx_data > 0) {
1710			evt = BWI_LED_EVENT_RX;
1711		} else if (rx_data == 0) {
1712			evt = BWI_LED_EVENT_POLL;
1713		}
1714
1715		if (evt != BWI_LED_EVENT_NONE)
1716			bwi_led_event(sc, evt);
1717	}
1718
1719	BWI_UNLOCK(sc);
1720}
1721
1722static void
1723bwi_scan_start(struct ieee80211com *ic)
1724{
1725	struct bwi_softc *sc = ic->ic_ifp->if_softc;
1726
1727	BWI_LOCK(sc);
1728	/* Enable MAC beacon promiscuity */
1729	CSR_SETBITS_4(sc, BWI_MAC_STATUS, BWI_MAC_STATUS_PASS_BCN);
1730	BWI_UNLOCK(sc);
1731}
1732
1733static void
1734bwi_set_channel(struct ieee80211com *ic)
1735{
1736	struct bwi_softc *sc = ic->ic_ifp->if_softc;
1737	struct ieee80211_channel *c = ic->ic_curchan;
1738	struct bwi_mac *mac;
1739
1740	BWI_LOCK(sc);
1741	KASSERT(sc->sc_cur_regwin->rw_type == BWI_REGWIN_T_MAC,
1742	    ("current regwin type %d", sc->sc_cur_regwin->rw_type));
1743	mac = (struct bwi_mac *)sc->sc_cur_regwin;
1744	bwi_rf_set_chan(mac, ieee80211_chan2ieee(ic, c), 0);
1745
1746	sc->sc_rates = ieee80211_get_ratetable(c);
1747
1748	/*
1749	 * Setup radio tap channel freq and flags
1750	 */
1751	sc->sc_tx_th.wt_chan_freq = sc->sc_rx_th.wr_chan_freq =
1752		htole16(c->ic_freq);
1753	sc->sc_tx_th.wt_chan_flags = sc->sc_rx_th.wr_chan_flags =
1754		htole16(c->ic_flags & 0xffff);
1755
1756	BWI_UNLOCK(sc);
1757}
1758
1759static void
1760bwi_scan_end(struct ieee80211com *ic)
1761{
1762	struct bwi_softc *sc = ic->ic_ifp->if_softc;
1763
1764	BWI_LOCK(sc);
1765	CSR_CLRBITS_4(sc, BWI_MAC_STATUS, BWI_MAC_STATUS_PASS_BCN);
1766	BWI_UNLOCK(sc);
1767}
1768
1769static int
1770bwi_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
1771{
1772	struct bwi_vap *bvp = BWI_VAP(vap);
1773	struct ieee80211com *ic= vap->iv_ic;
1774	struct ifnet *ifp = ic->ic_ifp;
1775	enum ieee80211_state ostate = vap->iv_state;
1776	struct bwi_softc *sc = ifp->if_softc;
1777	struct bwi_mac *mac;
1778	int error;
1779
1780	BWI_LOCK(sc);
1781
1782	callout_stop(&sc->sc_calib_ch);
1783
1784	if (nstate == IEEE80211_S_INIT)
1785		sc->sc_txpwrcb_type = BWI_TXPWR_INIT;
1786
1787	bwi_led_newstate(sc, nstate);
1788
1789	error = bvp->bv_newstate(vap, nstate, arg);
1790	if (error != 0)
1791		goto back;
1792
1793	/*
1794	 * Clear the BSSID when we stop a STA
1795	 */
1796	if (vap->iv_opmode == IEEE80211_M_STA) {
1797		if (ostate == IEEE80211_S_RUN && nstate != IEEE80211_S_RUN) {
1798			/*
1799			 * Clear out the BSSID.  If we reassociate to
1800			 * the same AP, this will reinialize things
1801			 * correctly...
1802			 */
1803			if (ic->ic_opmode == IEEE80211_M_STA &&
1804			    !(sc->sc_flags & BWI_F_STOP))
1805				bwi_set_bssid(sc, bwi_zero_addr);
1806		}
1807	}
1808
1809	if (vap->iv_opmode == IEEE80211_M_MONITOR) {
1810		/* Nothing to do */
1811	} else if (nstate == IEEE80211_S_RUN) {
1812		bwi_set_bssid(sc, vap->iv_bss->ni_bssid);
1813
1814		KASSERT(sc->sc_cur_regwin->rw_type == BWI_REGWIN_T_MAC,
1815		    ("current regwin type %d", sc->sc_cur_regwin->rw_type));
1816		mac = (struct bwi_mac *)sc->sc_cur_regwin;
1817
1818		/* Initial TX power calibration */
1819		bwi_mac_calibrate_txpower(mac, BWI_TXPWR_INIT);
1820#ifdef notyet
1821		sc->sc_txpwrcb_type = BWI_TXPWR_FORCE;
1822#else
1823		sc->sc_txpwrcb_type = BWI_TXPWR_CALIB;
1824#endif
1825
1826		callout_reset(&sc->sc_calib_ch, hz, bwi_calibrate, sc);
1827	}
1828back:
1829	BWI_UNLOCK(sc);
1830
1831	return error;
1832}
1833
1834static int
1835bwi_media_change(struct ifnet *ifp)
1836{
1837	int error = ieee80211_media_change(ifp);
1838	/* NB: only the fixed rate can change and that doesn't need a reset */
1839	return (error == ENETRESET ? 0 : error);
1840}
1841
1842static int
1843bwi_dma_alloc(struct bwi_softc *sc)
1844{
1845	int error, i, has_txstats;
1846	bus_addr_t lowaddr = 0;
1847	bus_size_t tx_ring_sz, rx_ring_sz, desc_sz = 0;
1848	uint32_t txrx_ctrl_step = 0;
1849
1850	has_txstats = 0;
1851	for (i = 0; i < sc->sc_nmac; ++i) {
1852		if (sc->sc_mac[i].mac_flags & BWI_MAC_F_HAS_TXSTATS) {
1853			has_txstats = 1;
1854			break;
1855		}
1856	}
1857
1858	switch (sc->sc_bus_space) {
1859	case BWI_BUS_SPACE_30BIT:
1860	case BWI_BUS_SPACE_32BIT:
1861		if (sc->sc_bus_space == BWI_BUS_SPACE_30BIT)
1862			lowaddr = BWI_BUS_SPACE_MAXADDR;
1863		else
1864			lowaddr = BUS_SPACE_MAXADDR_32BIT;
1865		desc_sz = sizeof(struct bwi_desc32);
1866		txrx_ctrl_step = 0x20;
1867
1868		sc->sc_init_tx_ring = bwi_init_tx_ring32;
1869		sc->sc_free_tx_ring = bwi_free_tx_ring32;
1870		sc->sc_init_rx_ring = bwi_init_rx_ring32;
1871		sc->sc_free_rx_ring = bwi_free_rx_ring32;
1872		sc->sc_setup_rxdesc = bwi_setup_rx_desc32;
1873		sc->sc_setup_txdesc = bwi_setup_tx_desc32;
1874		sc->sc_rxeof = bwi_rxeof32;
1875		sc->sc_start_tx = bwi_start_tx32;
1876		if (has_txstats) {
1877			sc->sc_init_txstats = bwi_init_txstats32;
1878			sc->sc_free_txstats = bwi_free_txstats32;
1879			sc->sc_txeof_status = bwi_txeof_status32;
1880		}
1881		break;
1882
1883	case BWI_BUS_SPACE_64BIT:
1884		lowaddr = BUS_SPACE_MAXADDR;	/* XXX */
1885		desc_sz = sizeof(struct bwi_desc64);
1886		txrx_ctrl_step = 0x40;
1887
1888		sc->sc_init_tx_ring = bwi_init_tx_ring64;
1889		sc->sc_free_tx_ring = bwi_free_tx_ring64;
1890		sc->sc_init_rx_ring = bwi_init_rx_ring64;
1891		sc->sc_free_rx_ring = bwi_free_rx_ring64;
1892		sc->sc_setup_rxdesc = bwi_setup_rx_desc64;
1893		sc->sc_setup_txdesc = bwi_setup_tx_desc64;
1894		sc->sc_rxeof = bwi_rxeof64;
1895		sc->sc_start_tx = bwi_start_tx64;
1896		if (has_txstats) {
1897			sc->sc_init_txstats = bwi_init_txstats64;
1898			sc->sc_free_txstats = bwi_free_txstats64;
1899			sc->sc_txeof_status = bwi_txeof_status64;
1900		}
1901		break;
1902	}
1903
1904	KASSERT(lowaddr != 0, ("lowaddr zero"));
1905	KASSERT(desc_sz != 0, ("desc_sz zero"));
1906	KASSERT(txrx_ctrl_step != 0, ("txrx_ctrl_step zero"));
1907
1908	tx_ring_sz = roundup(desc_sz * BWI_TX_NDESC, BWI_RING_ALIGN);
1909	rx_ring_sz = roundup(desc_sz * BWI_RX_NDESC, BWI_RING_ALIGN);
1910
1911	/*
1912	 * Create top level DMA tag
1913	 */
1914	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev),	/* parent */
1915			       BWI_ALIGN, 0,		/* alignment, bounds */
1916			       lowaddr,			/* lowaddr */
1917			       BUS_SPACE_MAXADDR,	/* highaddr */
1918			       NULL, NULL,		/* filter, filterarg */
1919			       MAXBSIZE,		/* maxsize */
1920			       BUS_SPACE_UNRESTRICTED,	/* nsegments */
1921			       BUS_SPACE_MAXSIZE_32BIT,	/* maxsegsize */
1922			       BUS_DMA_ALLOCNOW,	/* flags */
1923			       NULL, NULL,		/* lockfunc, lockarg */
1924			       &sc->sc_parent_dtag);
1925	if (error) {
1926		device_printf(sc->sc_dev, "can't create parent DMA tag\n");
1927		return error;
1928	}
1929
1930#define TXRX_CTRL(idx)	(BWI_TXRX_CTRL_BASE + (idx) * txrx_ctrl_step)
1931
1932	/*
1933	 * Create TX ring DMA stuffs
1934	 */
1935	error = bus_dma_tag_create(sc->sc_parent_dtag,
1936				BWI_RING_ALIGN, 0,
1937				BUS_SPACE_MAXADDR,
1938				BUS_SPACE_MAXADDR,
1939				NULL, NULL,
1940				tx_ring_sz,
1941				1,
1942				BUS_SPACE_MAXSIZE_32BIT,
1943				BUS_DMA_ALLOCNOW,
1944				NULL, NULL,
1945				&sc->sc_txring_dtag);
1946	if (error) {
1947		device_printf(sc->sc_dev, "can't create TX ring DMA tag\n");
1948		return error;
1949	}
1950
1951	for (i = 0; i < BWI_TX_NRING; ++i) {
1952		error = bwi_dma_ring_alloc(sc, sc->sc_txring_dtag,
1953					   &sc->sc_tx_rdata[i], tx_ring_sz,
1954					   TXRX_CTRL(i));
1955		if (error) {
1956			device_printf(sc->sc_dev, "%dth TX ring "
1957				      "DMA alloc failed\n", i);
1958			return error;
1959		}
1960	}
1961
1962	/*
1963	 * Create RX ring DMA stuffs
1964	 */
1965	error = bus_dma_tag_create(sc->sc_parent_dtag,
1966				BWI_RING_ALIGN, 0,
1967				BUS_SPACE_MAXADDR,
1968				BUS_SPACE_MAXADDR,
1969				NULL, NULL,
1970				rx_ring_sz,
1971				1,
1972				BUS_SPACE_MAXSIZE_32BIT,
1973				BUS_DMA_ALLOCNOW,
1974				NULL, NULL,
1975				&sc->sc_rxring_dtag);
1976	if (error) {
1977		device_printf(sc->sc_dev, "can't create RX ring DMA tag\n");
1978		return error;
1979	}
1980
1981	error = bwi_dma_ring_alloc(sc, sc->sc_rxring_dtag, &sc->sc_rx_rdata,
1982				   rx_ring_sz, TXRX_CTRL(0));
1983	if (error) {
1984		device_printf(sc->sc_dev, "RX ring DMA alloc failed\n");
1985		return error;
1986	}
1987
1988	if (has_txstats) {
1989		error = bwi_dma_txstats_alloc(sc, TXRX_CTRL(3), desc_sz);
1990		if (error) {
1991			device_printf(sc->sc_dev,
1992				      "TX stats DMA alloc failed\n");
1993			return error;
1994		}
1995	}
1996
1997#undef TXRX_CTRL
1998
1999	return bwi_dma_mbuf_create(sc);
2000}
2001
2002static void
2003bwi_dma_free(struct bwi_softc *sc)
2004{
2005	if (sc->sc_txring_dtag != NULL) {
2006		int i;
2007
2008		for (i = 0; i < BWI_TX_NRING; ++i) {
2009			struct bwi_ring_data *rd = &sc->sc_tx_rdata[i];
2010
2011			if (rd->rdata_desc != NULL) {
2012				bus_dmamap_unload(sc->sc_txring_dtag,
2013						  rd->rdata_dmap);
2014				bus_dmamem_free(sc->sc_txring_dtag,
2015						rd->rdata_desc,
2016						rd->rdata_dmap);
2017			}
2018		}
2019		bus_dma_tag_destroy(sc->sc_txring_dtag);
2020	}
2021
2022	if (sc->sc_rxring_dtag != NULL) {
2023		struct bwi_ring_data *rd = &sc->sc_rx_rdata;
2024
2025		if (rd->rdata_desc != NULL) {
2026			bus_dmamap_unload(sc->sc_rxring_dtag, rd->rdata_dmap);
2027			bus_dmamem_free(sc->sc_rxring_dtag, rd->rdata_desc,
2028					rd->rdata_dmap);
2029		}
2030		bus_dma_tag_destroy(sc->sc_rxring_dtag);
2031	}
2032
2033	bwi_dma_txstats_free(sc);
2034	bwi_dma_mbuf_destroy(sc, BWI_TX_NRING, 1);
2035
2036	if (sc->sc_parent_dtag != NULL)
2037		bus_dma_tag_destroy(sc->sc_parent_dtag);
2038}
2039
2040static int
2041bwi_dma_ring_alloc(struct bwi_softc *sc, bus_dma_tag_t dtag,
2042		   struct bwi_ring_data *rd, bus_size_t size,
2043		   uint32_t txrx_ctrl)
2044{
2045	int error;
2046
2047	error = bus_dmamem_alloc(dtag, &rd->rdata_desc,
2048				 BUS_DMA_WAITOK | BUS_DMA_ZERO,
2049				 &rd->rdata_dmap);
2050	if (error) {
2051		device_printf(sc->sc_dev, "can't allocate DMA mem\n");
2052		return error;
2053	}
2054
2055	error = bus_dmamap_load(dtag, rd->rdata_dmap, rd->rdata_desc, size,
2056				bwi_dma_ring_addr, &rd->rdata_paddr,
2057				BUS_DMA_NOWAIT);
2058	if (error) {
2059		device_printf(sc->sc_dev, "can't load DMA mem\n");
2060		bus_dmamem_free(dtag, rd->rdata_desc, rd->rdata_dmap);
2061		rd->rdata_desc = NULL;
2062		return error;
2063	}
2064
2065	rd->rdata_txrx_ctrl = txrx_ctrl;
2066	return 0;
2067}
2068
2069static int
2070bwi_dma_txstats_alloc(struct bwi_softc *sc, uint32_t ctrl_base,
2071		      bus_size_t desc_sz)
2072{
2073	struct bwi_txstats_data *st;
2074	bus_size_t dma_size;
2075	int error;
2076
2077	st = malloc(sizeof(*st), M_DEVBUF, M_NOWAIT | M_ZERO);
2078	if (st == NULL) {
2079		device_printf(sc->sc_dev, "can't allocate txstats data\n");
2080		return ENOMEM;
2081	}
2082	sc->sc_txstats = st;
2083
2084	/*
2085	 * Create TX stats descriptor DMA stuffs
2086	 */
2087	dma_size = roundup(desc_sz * BWI_TXSTATS_NDESC, BWI_RING_ALIGN);
2088
2089	error = bus_dma_tag_create(sc->sc_parent_dtag,
2090				BWI_RING_ALIGN,
2091				0,
2092				BUS_SPACE_MAXADDR,
2093				BUS_SPACE_MAXADDR,
2094				NULL, NULL,
2095				dma_size,
2096				1,
2097				BUS_SPACE_MAXSIZE_32BIT,
2098				BUS_DMA_ALLOCNOW,
2099				NULL, NULL,
2100				&st->stats_ring_dtag);
2101	if (error) {
2102		device_printf(sc->sc_dev, "can't create txstats ring "
2103			      "DMA tag\n");
2104		return error;
2105	}
2106
2107	error = bus_dmamem_alloc(st->stats_ring_dtag, &st->stats_ring,
2108				 BUS_DMA_WAITOK | BUS_DMA_ZERO,
2109				 &st->stats_ring_dmap);
2110	if (error) {
2111		device_printf(sc->sc_dev, "can't allocate txstats ring "
2112			      "DMA mem\n");
2113		bus_dma_tag_destroy(st->stats_ring_dtag);
2114		st->stats_ring_dtag = NULL;
2115		return error;
2116	}
2117
2118	error = bus_dmamap_load(st->stats_ring_dtag, st->stats_ring_dmap,
2119				st->stats_ring, dma_size,
2120				bwi_dma_ring_addr, &st->stats_ring_paddr,
2121				BUS_DMA_NOWAIT);
2122	if (error) {
2123		device_printf(sc->sc_dev, "can't load txstats ring DMA mem\n");
2124		bus_dmamem_free(st->stats_ring_dtag, st->stats_ring,
2125				st->stats_ring_dmap);
2126		bus_dma_tag_destroy(st->stats_ring_dtag);
2127		st->stats_ring_dtag = NULL;
2128		return error;
2129	}
2130
2131	/*
2132	 * Create TX stats DMA stuffs
2133	 */
2134	dma_size = roundup(sizeof(struct bwi_txstats) * BWI_TXSTATS_NDESC,
2135			   BWI_ALIGN);
2136
2137	error = bus_dma_tag_create(sc->sc_parent_dtag,
2138				BWI_ALIGN,
2139				0,
2140				BUS_SPACE_MAXADDR,
2141				BUS_SPACE_MAXADDR,
2142				NULL, NULL,
2143				dma_size,
2144				1,
2145				BUS_SPACE_MAXSIZE_32BIT,
2146				BUS_DMA_ALLOCNOW,
2147				NULL, NULL,
2148				&st->stats_dtag);
2149	if (error) {
2150		device_printf(sc->sc_dev, "can't create txstats DMA tag\n");
2151		return error;
2152	}
2153
2154	error = bus_dmamem_alloc(st->stats_dtag, (void **)&st->stats,
2155				 BUS_DMA_WAITOK | BUS_DMA_ZERO,
2156				 &st->stats_dmap);
2157	if (error) {
2158		device_printf(sc->sc_dev, "can't allocate txstats DMA mem\n");
2159		bus_dma_tag_destroy(st->stats_dtag);
2160		st->stats_dtag = NULL;
2161		return error;
2162	}
2163
2164	error = bus_dmamap_load(st->stats_dtag, st->stats_dmap, st->stats,
2165				dma_size, bwi_dma_ring_addr, &st->stats_paddr,
2166				BUS_DMA_NOWAIT);
2167	if (error) {
2168		device_printf(sc->sc_dev, "can't load txstats DMA mem\n");
2169		bus_dmamem_free(st->stats_dtag, st->stats, st->stats_dmap);
2170		bus_dma_tag_destroy(st->stats_dtag);
2171		st->stats_dtag = NULL;
2172		return error;
2173	}
2174
2175	st->stats_ctrl_base = ctrl_base;
2176	return 0;
2177}
2178
2179static void
2180bwi_dma_txstats_free(struct bwi_softc *sc)
2181{
2182	struct bwi_txstats_data *st;
2183
2184	if (sc->sc_txstats == NULL)
2185		return;
2186	st = sc->sc_txstats;
2187
2188	if (st->stats_ring_dtag != NULL) {
2189		bus_dmamap_unload(st->stats_ring_dtag, st->stats_ring_dmap);
2190		bus_dmamem_free(st->stats_ring_dtag, st->stats_ring,
2191				st->stats_ring_dmap);
2192		bus_dma_tag_destroy(st->stats_ring_dtag);
2193	}
2194
2195	if (st->stats_dtag != NULL) {
2196		bus_dmamap_unload(st->stats_dtag, st->stats_dmap);
2197		bus_dmamem_free(st->stats_dtag, st->stats, st->stats_dmap);
2198		bus_dma_tag_destroy(st->stats_dtag);
2199	}
2200
2201	free(st, M_DEVBUF);
2202}
2203
2204static void
2205bwi_dma_ring_addr(void *arg, bus_dma_segment_t *seg, int nseg, int error)
2206{
2207	KASSERT(nseg == 1, ("too many segments\n"));
2208	*((bus_addr_t *)arg) = seg->ds_addr;
2209}
2210
2211static int
2212bwi_dma_mbuf_create(struct bwi_softc *sc)
2213{
2214	struct bwi_rxbuf_data *rbd = &sc->sc_rx_bdata;
2215	int i, j, k, ntx, error;
2216
2217	/*
2218	 * Create TX/RX mbuf DMA tag
2219	 */
2220	error = bus_dma_tag_create(sc->sc_parent_dtag,
2221				1,
2222				0,
2223				BUS_SPACE_MAXADDR,
2224				BUS_SPACE_MAXADDR,
2225				NULL, NULL,
2226				MCLBYTES,
2227				1,
2228				BUS_SPACE_MAXSIZE_32BIT,
2229				BUS_DMA_ALLOCNOW,
2230				NULL, NULL,
2231				&sc->sc_buf_dtag);
2232	if (error) {
2233		device_printf(sc->sc_dev, "can't create mbuf DMA tag\n");
2234		return error;
2235	}
2236
2237	ntx = 0;
2238
2239	/*
2240	 * Create TX mbuf DMA map
2241	 */
2242	for (i = 0; i < BWI_TX_NRING; ++i) {
2243		struct bwi_txbuf_data *tbd = &sc->sc_tx_bdata[i];
2244
2245		for (j = 0; j < BWI_TX_NDESC; ++j) {
2246			error = bus_dmamap_create(sc->sc_buf_dtag, 0,
2247						  &tbd->tbd_buf[j].tb_dmap);
2248			if (error) {
2249				device_printf(sc->sc_dev, "can't create "
2250					      "%dth tbd, %dth DMA map\n", i, j);
2251
2252				ntx = i;
2253				for (k = 0; k < j; ++k) {
2254					bus_dmamap_destroy(sc->sc_buf_dtag,
2255						tbd->tbd_buf[k].tb_dmap);
2256				}
2257				goto fail;
2258			}
2259		}
2260	}
2261	ntx = BWI_TX_NRING;
2262
2263	/*
2264	 * Create RX mbuf DMA map and a spare DMA map
2265	 */
2266	error = bus_dmamap_create(sc->sc_buf_dtag, 0,
2267				  &rbd->rbd_tmp_dmap);
2268	if (error) {
2269		device_printf(sc->sc_dev,
2270			      "can't create spare RX buf DMA map\n");
2271		goto fail;
2272	}
2273
2274	for (j = 0; j < BWI_RX_NDESC; ++j) {
2275		error = bus_dmamap_create(sc->sc_buf_dtag, 0,
2276					  &rbd->rbd_buf[j].rb_dmap);
2277		if (error) {
2278			device_printf(sc->sc_dev, "can't create %dth "
2279				      "RX buf DMA map\n", j);
2280
2281			for (k = 0; k < j; ++k) {
2282				bus_dmamap_destroy(sc->sc_buf_dtag,
2283					rbd->rbd_buf[j].rb_dmap);
2284			}
2285			bus_dmamap_destroy(sc->sc_buf_dtag,
2286					   rbd->rbd_tmp_dmap);
2287			goto fail;
2288		}
2289	}
2290
2291	return 0;
2292fail:
2293	bwi_dma_mbuf_destroy(sc, ntx, 0);
2294	return error;
2295}
2296
2297static void
2298bwi_dma_mbuf_destroy(struct bwi_softc *sc, int ntx, int nrx)
2299{
2300	int i, j;
2301
2302	if (sc->sc_buf_dtag == NULL)
2303		return;
2304
2305	for (i = 0; i < ntx; ++i) {
2306		struct bwi_txbuf_data *tbd = &sc->sc_tx_bdata[i];
2307
2308		for (j = 0; j < BWI_TX_NDESC; ++j) {
2309			struct bwi_txbuf *tb = &tbd->tbd_buf[j];
2310
2311			if (tb->tb_mbuf != NULL) {
2312				bus_dmamap_unload(sc->sc_buf_dtag,
2313						  tb->tb_dmap);
2314				m_freem(tb->tb_mbuf);
2315			}
2316			if (tb->tb_ni != NULL)
2317				ieee80211_free_node(tb->tb_ni);
2318			bus_dmamap_destroy(sc->sc_buf_dtag, tb->tb_dmap);
2319		}
2320	}
2321
2322	if (nrx) {
2323		struct bwi_rxbuf_data *rbd = &sc->sc_rx_bdata;
2324
2325		bus_dmamap_destroy(sc->sc_buf_dtag, rbd->rbd_tmp_dmap);
2326		for (j = 0; j < BWI_RX_NDESC; ++j) {
2327			struct bwi_rxbuf *rb = &rbd->rbd_buf[j];
2328
2329			if (rb->rb_mbuf != NULL) {
2330				bus_dmamap_unload(sc->sc_buf_dtag,
2331						  rb->rb_dmap);
2332				m_freem(rb->rb_mbuf);
2333			}
2334			bus_dmamap_destroy(sc->sc_buf_dtag, rb->rb_dmap);
2335		}
2336	}
2337
2338	bus_dma_tag_destroy(sc->sc_buf_dtag);
2339	sc->sc_buf_dtag = NULL;
2340}
2341
2342static void
2343bwi_enable_intrs(struct bwi_softc *sc, uint32_t enable_intrs)
2344{
2345	CSR_SETBITS_4(sc, BWI_MAC_INTR_MASK, enable_intrs);
2346}
2347
2348static void
2349bwi_disable_intrs(struct bwi_softc *sc, uint32_t disable_intrs)
2350{
2351	CSR_CLRBITS_4(sc, BWI_MAC_INTR_MASK, disable_intrs);
2352}
2353
2354static int
2355bwi_init_tx_ring32(struct bwi_softc *sc, int ring_idx)
2356{
2357	struct bwi_ring_data *rd;
2358	struct bwi_txbuf_data *tbd;
2359	uint32_t val, addr_hi, addr_lo;
2360
2361	KASSERT(ring_idx < BWI_TX_NRING, ("ring_idx %d", ring_idx));
2362	rd = &sc->sc_tx_rdata[ring_idx];
2363	tbd = &sc->sc_tx_bdata[ring_idx];
2364
2365	tbd->tbd_idx = 0;
2366	tbd->tbd_used = 0;
2367
2368	bzero(rd->rdata_desc, sizeof(struct bwi_desc32) * BWI_TX_NDESC);
2369	bus_dmamap_sync(sc->sc_txring_dtag, rd->rdata_dmap,
2370			BUS_DMASYNC_PREWRITE);
2371
2372	addr_lo = __SHIFTOUT(rd->rdata_paddr, BWI_TXRX32_RINGINFO_ADDR_MASK);
2373	addr_hi = __SHIFTOUT(rd->rdata_paddr, BWI_TXRX32_RINGINFO_FUNC_MASK);
2374
2375	val = __SHIFTIN(addr_lo, BWI_TXRX32_RINGINFO_ADDR_MASK) |
2376	      __SHIFTIN(BWI_TXRX32_RINGINFO_FUNC_TXRX,
2377	      		BWI_TXRX32_RINGINFO_FUNC_MASK);
2378	CSR_WRITE_4(sc, rd->rdata_txrx_ctrl + BWI_TX32_RINGINFO, val);
2379
2380	val = __SHIFTIN(addr_hi, BWI_TXRX32_CTRL_ADDRHI_MASK) |
2381	      BWI_TXRX32_CTRL_ENABLE;
2382	CSR_WRITE_4(sc, rd->rdata_txrx_ctrl + BWI_TX32_CTRL, val);
2383
2384	return 0;
2385}
2386
2387static void
2388bwi_init_rxdesc_ring32(struct bwi_softc *sc, uint32_t ctrl_base,
2389		       bus_addr_t paddr, int hdr_size, int ndesc)
2390{
2391	uint32_t val, addr_hi, addr_lo;
2392
2393	addr_lo = __SHIFTOUT(paddr, BWI_TXRX32_RINGINFO_ADDR_MASK);
2394	addr_hi = __SHIFTOUT(paddr, BWI_TXRX32_RINGINFO_FUNC_MASK);
2395
2396	val = __SHIFTIN(addr_lo, BWI_TXRX32_RINGINFO_ADDR_MASK) |
2397	      __SHIFTIN(BWI_TXRX32_RINGINFO_FUNC_TXRX,
2398	      		BWI_TXRX32_RINGINFO_FUNC_MASK);
2399	CSR_WRITE_4(sc, ctrl_base + BWI_RX32_RINGINFO, val);
2400
2401	val = __SHIFTIN(hdr_size, BWI_RX32_CTRL_HDRSZ_MASK) |
2402	      __SHIFTIN(addr_hi, BWI_TXRX32_CTRL_ADDRHI_MASK) |
2403	      BWI_TXRX32_CTRL_ENABLE;
2404	CSR_WRITE_4(sc, ctrl_base + BWI_RX32_CTRL, val);
2405
2406	CSR_WRITE_4(sc, ctrl_base + BWI_RX32_INDEX,
2407		    (ndesc - 1) * sizeof(struct bwi_desc32));
2408}
2409
2410static int
2411bwi_init_rx_ring32(struct bwi_softc *sc)
2412{
2413	struct bwi_ring_data *rd = &sc->sc_rx_rdata;
2414	int i, error;
2415
2416	sc->sc_rx_bdata.rbd_idx = 0;
2417
2418	for (i = 0; i < BWI_RX_NDESC; ++i) {
2419		error = bwi_newbuf(sc, i, 1);
2420		if (error) {
2421			device_printf(sc->sc_dev,
2422				  "can't allocate %dth RX buffer\n", i);
2423			return error;
2424		}
2425	}
2426	bus_dmamap_sync(sc->sc_rxring_dtag, rd->rdata_dmap,
2427			BUS_DMASYNC_PREWRITE);
2428
2429	bwi_init_rxdesc_ring32(sc, rd->rdata_txrx_ctrl, rd->rdata_paddr,
2430			       sizeof(struct bwi_rxbuf_hdr), BWI_RX_NDESC);
2431	return 0;
2432}
2433
2434static int
2435bwi_init_txstats32(struct bwi_softc *sc)
2436{
2437	struct bwi_txstats_data *st = sc->sc_txstats;
2438	bus_addr_t stats_paddr;
2439	int i;
2440
2441	bzero(st->stats, BWI_TXSTATS_NDESC * sizeof(struct bwi_txstats));
2442	bus_dmamap_sync(st->stats_dtag, st->stats_dmap, BUS_DMASYNC_PREWRITE);
2443
2444	st->stats_idx = 0;
2445
2446	stats_paddr = st->stats_paddr;
2447	for (i = 0; i < BWI_TXSTATS_NDESC; ++i) {
2448		bwi_setup_desc32(sc, st->stats_ring, BWI_TXSTATS_NDESC, i,
2449				 stats_paddr, sizeof(struct bwi_txstats), 0);
2450		stats_paddr += sizeof(struct bwi_txstats);
2451	}
2452	bus_dmamap_sync(st->stats_ring_dtag, st->stats_ring_dmap,
2453			BUS_DMASYNC_PREWRITE);
2454
2455	bwi_init_rxdesc_ring32(sc, st->stats_ctrl_base,
2456			       st->stats_ring_paddr, 0, BWI_TXSTATS_NDESC);
2457	return 0;
2458}
2459
2460static void
2461bwi_setup_rx_desc32(struct bwi_softc *sc, int buf_idx, bus_addr_t paddr,
2462		    int buf_len)
2463{
2464	struct bwi_ring_data *rd = &sc->sc_rx_rdata;
2465
2466	KASSERT(buf_idx < BWI_RX_NDESC, ("buf_idx %d", buf_idx));
2467	bwi_setup_desc32(sc, rd->rdata_desc, BWI_RX_NDESC, buf_idx,
2468			 paddr, buf_len, 0);
2469}
2470
2471static void
2472bwi_setup_tx_desc32(struct bwi_softc *sc, struct bwi_ring_data *rd,
2473		    int buf_idx, bus_addr_t paddr, int buf_len)
2474{
2475	KASSERT(buf_idx < BWI_TX_NDESC, ("buf_idx %d", buf_idx));
2476	bwi_setup_desc32(sc, rd->rdata_desc, BWI_TX_NDESC, buf_idx,
2477			 paddr, buf_len, 1);
2478}
2479
2480static int
2481bwi_init_tx_ring64(struct bwi_softc *sc, int ring_idx)
2482{
2483	/* TODO:64 */
2484	return EOPNOTSUPP;
2485}
2486
2487static int
2488bwi_init_rx_ring64(struct bwi_softc *sc)
2489{
2490	/* TODO:64 */
2491	return EOPNOTSUPP;
2492}
2493
2494static int
2495bwi_init_txstats64(struct bwi_softc *sc)
2496{
2497	/* TODO:64 */
2498	return EOPNOTSUPP;
2499}
2500
2501static void
2502bwi_setup_rx_desc64(struct bwi_softc *sc, int buf_idx, bus_addr_t paddr,
2503		    int buf_len)
2504{
2505	/* TODO:64 */
2506}
2507
2508static void
2509bwi_setup_tx_desc64(struct bwi_softc *sc, struct bwi_ring_data *rd,
2510		    int buf_idx, bus_addr_t paddr, int buf_len)
2511{
2512	/* TODO:64 */
2513}
2514
2515static void
2516bwi_dma_buf_addr(void *arg, bus_dma_segment_t *seg, int nseg,
2517		 bus_size_t mapsz __unused, int error)
2518{
2519        if (!error) {
2520		KASSERT(nseg == 1, ("too many segments(%d)\n", nseg));
2521		*((bus_addr_t *)arg) = seg->ds_addr;
2522	}
2523}
2524
2525static int
2526bwi_newbuf(struct bwi_softc *sc, int buf_idx, int init)
2527{
2528	struct bwi_rxbuf_data *rbd = &sc->sc_rx_bdata;
2529	struct bwi_rxbuf *rxbuf = &rbd->rbd_buf[buf_idx];
2530	struct bwi_rxbuf_hdr *hdr;
2531	bus_dmamap_t map;
2532	bus_addr_t paddr;
2533	struct mbuf *m;
2534	int error;
2535
2536	KASSERT(buf_idx < BWI_RX_NDESC, ("buf_idx %d", buf_idx));
2537
2538	m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2539	if (m == NULL) {
2540		error = ENOBUFS;
2541
2542		/*
2543		 * If the NIC is up and running, we need to:
2544		 * - Clear RX buffer's header.
2545		 * - Restore RX descriptor settings.
2546		 */
2547		if (init)
2548			return error;
2549		else
2550			goto back;
2551	}
2552	m->m_len = m->m_pkthdr.len = MCLBYTES;
2553
2554	/*
2555	 * Try to load RX buf into temporary DMA map
2556	 */
2557	error = bus_dmamap_load_mbuf(sc->sc_buf_dtag, rbd->rbd_tmp_dmap, m,
2558				     bwi_dma_buf_addr, &paddr, BUS_DMA_NOWAIT);
2559	if (error) {
2560		m_freem(m);
2561
2562		/*
2563		 * See the comment above
2564		 */
2565		if (init)
2566			return error;
2567		else
2568			goto back;
2569	}
2570
2571	if (!init)
2572		bus_dmamap_unload(sc->sc_buf_dtag, rxbuf->rb_dmap);
2573	rxbuf->rb_mbuf = m;
2574	rxbuf->rb_paddr = paddr;
2575
2576	/*
2577	 * Swap RX buf's DMA map with the loaded temporary one
2578	 */
2579	map = rxbuf->rb_dmap;
2580	rxbuf->rb_dmap = rbd->rbd_tmp_dmap;
2581	rbd->rbd_tmp_dmap = map;
2582
2583back:
2584	/*
2585	 * Clear RX buf header
2586	 */
2587	hdr = mtod(rxbuf->rb_mbuf, struct bwi_rxbuf_hdr *);
2588	bzero(hdr, sizeof(*hdr));
2589	bus_dmamap_sync(sc->sc_buf_dtag, rxbuf->rb_dmap, BUS_DMASYNC_PREWRITE);
2590
2591	/*
2592	 * Setup RX buf descriptor
2593	 */
2594	sc->sc_setup_rxdesc(sc, buf_idx, rxbuf->rb_paddr,
2595			    rxbuf->rb_mbuf->m_len - sizeof(*hdr));
2596	return error;
2597}
2598
2599static void
2600bwi_set_addr_filter(struct bwi_softc *sc, uint16_t addr_ofs,
2601		    const uint8_t *addr)
2602{
2603	int i;
2604
2605	CSR_WRITE_2(sc, BWI_ADDR_FILTER_CTRL,
2606		    BWI_ADDR_FILTER_CTRL_SET | addr_ofs);
2607
2608	for (i = 0; i < (IEEE80211_ADDR_LEN / 2); ++i) {
2609		uint16_t addr_val;
2610
2611		addr_val = (uint16_t)addr[i * 2] |
2612			   (((uint16_t)addr[(i * 2) + 1]) << 8);
2613		CSR_WRITE_2(sc, BWI_ADDR_FILTER_DATA, addr_val);
2614	}
2615}
2616
2617static int
2618bwi_rxeof(struct bwi_softc *sc, int end_idx)
2619{
2620	struct bwi_ring_data *rd = &sc->sc_rx_rdata;
2621	struct bwi_rxbuf_data *rbd = &sc->sc_rx_bdata;
2622	struct ifnet *ifp = sc->sc_ifp;
2623	struct ieee80211com *ic = ifp->if_l2com;
2624	int idx, rx_data = 0;
2625
2626	idx = rbd->rbd_idx;
2627	while (idx != end_idx) {
2628		struct bwi_rxbuf *rb = &rbd->rbd_buf[idx];
2629		struct bwi_rxbuf_hdr *hdr;
2630		struct ieee80211_frame_min *wh;
2631		struct ieee80211_node *ni;
2632		struct mbuf *m;
2633		uint32_t plcp;
2634		uint16_t flags2;
2635		int buflen, wh_ofs, hdr_extra, rssi, noise, type, rate;
2636
2637		m = rb->rb_mbuf;
2638		bus_dmamap_sync(sc->sc_buf_dtag, rb->rb_dmap,
2639				BUS_DMASYNC_POSTREAD);
2640
2641		if (bwi_newbuf(sc, idx, 0)) {
2642			ifp->if_ierrors++;
2643			goto next;
2644		}
2645
2646		hdr = mtod(m, struct bwi_rxbuf_hdr *);
2647		flags2 = le16toh(hdr->rxh_flags2);
2648
2649		hdr_extra = 0;
2650		if (flags2 & BWI_RXH_F2_TYPE2FRAME)
2651			hdr_extra = 2;
2652		wh_ofs = hdr_extra + 6;	/* XXX magic number */
2653
2654		buflen = le16toh(hdr->rxh_buflen);
2655		if (buflen < BWI_FRAME_MIN_LEN(wh_ofs)) {
2656			if_printf(ifp, "%s: zero length data, hdr_extra %d\n",
2657				  __func__, hdr_extra);
2658			ifp->if_ierrors++;
2659			m_freem(m);
2660			goto next;
2661		}
2662
2663	        bcopy((uint8_t *)(hdr + 1) + hdr_extra, &plcp, sizeof(plcp));
2664		rssi = bwi_calc_rssi(sc, hdr);
2665		noise = bwi_calc_noise(sc);
2666
2667		m->m_pkthdr.rcvif = ifp;
2668		m->m_len = m->m_pkthdr.len = buflen + sizeof(*hdr);
2669		m_adj(m, sizeof(*hdr) + wh_ofs);
2670
2671		if (htole16(hdr->rxh_flags1) & BWI_RXH_F1_OFDM)
2672			rate = bwi_plcp2rate(plcp, IEEE80211_T_OFDM);
2673		else
2674			rate = bwi_plcp2rate(plcp, IEEE80211_T_CCK);
2675
2676		/* RX radio tap */
2677		if (ieee80211_radiotap_active(ic))
2678			bwi_rx_radiotap(sc, m, hdr, &plcp, rate, rssi, noise);
2679
2680		m_adj(m, -IEEE80211_CRC_LEN);
2681
2682		BWI_UNLOCK(sc);
2683
2684		wh = mtod(m, struct ieee80211_frame_min *);
2685		ni = ieee80211_find_rxnode(ic, wh);
2686		if (ni != NULL) {
2687			type = ieee80211_input(ni, m, rssi - noise, noise);
2688			ieee80211_free_node(ni);
2689		} else
2690			type = ieee80211_input_all(ic, m, rssi - noise, noise);
2691		if (type == IEEE80211_FC0_TYPE_DATA) {
2692			rx_data = 1;
2693			sc->sc_rx_rate = rate;
2694		}
2695
2696		BWI_LOCK(sc);
2697next:
2698		idx = (idx + 1) % BWI_RX_NDESC;
2699
2700		if (sc->sc_flags & BWI_F_STOP) {
2701			/*
2702			 * Take the fast lane, don't do
2703			 * any damage to softc
2704			 */
2705			return -1;
2706		}
2707	}
2708
2709	rbd->rbd_idx = idx;
2710	bus_dmamap_sync(sc->sc_rxring_dtag, rd->rdata_dmap,
2711			BUS_DMASYNC_PREWRITE);
2712
2713	return rx_data;
2714}
2715
2716static int
2717bwi_rxeof32(struct bwi_softc *sc)
2718{
2719	uint32_t val, rx_ctrl;
2720	int end_idx, rx_data;
2721
2722	rx_ctrl = sc->sc_rx_rdata.rdata_txrx_ctrl;
2723
2724	val = CSR_READ_4(sc, rx_ctrl + BWI_RX32_STATUS);
2725	end_idx = __SHIFTOUT(val, BWI_RX32_STATUS_INDEX_MASK) /
2726		  sizeof(struct bwi_desc32);
2727
2728	rx_data = bwi_rxeof(sc, end_idx);
2729	if (rx_data >= 0) {
2730		CSR_WRITE_4(sc, rx_ctrl + BWI_RX32_INDEX,
2731			    end_idx * sizeof(struct bwi_desc32));
2732	}
2733	return rx_data;
2734}
2735
2736static int
2737bwi_rxeof64(struct bwi_softc *sc)
2738{
2739	/* TODO:64 */
2740	return 0;
2741}
2742
2743static void
2744bwi_reset_rx_ring32(struct bwi_softc *sc, uint32_t rx_ctrl)
2745{
2746	int i;
2747
2748	CSR_WRITE_4(sc, rx_ctrl + BWI_RX32_CTRL, 0);
2749
2750#define NRETRY 10
2751
2752	for (i = 0; i < NRETRY; ++i) {
2753		uint32_t status;
2754
2755		status = CSR_READ_4(sc, rx_ctrl + BWI_RX32_STATUS);
2756		if (__SHIFTOUT(status, BWI_RX32_STATUS_STATE_MASK) ==
2757		    BWI_RX32_STATUS_STATE_DISABLED)
2758			break;
2759
2760		DELAY(1000);
2761	}
2762	if (i == NRETRY)
2763		device_printf(sc->sc_dev, "reset rx ring timedout\n");
2764
2765#undef NRETRY
2766
2767	CSR_WRITE_4(sc, rx_ctrl + BWI_RX32_RINGINFO, 0);
2768}
2769
2770static void
2771bwi_free_txstats32(struct bwi_softc *sc)
2772{
2773	bwi_reset_rx_ring32(sc, sc->sc_txstats->stats_ctrl_base);
2774}
2775
2776static void
2777bwi_free_rx_ring32(struct bwi_softc *sc)
2778{
2779	struct bwi_ring_data *rd = &sc->sc_rx_rdata;
2780	struct bwi_rxbuf_data *rbd = &sc->sc_rx_bdata;
2781	int i;
2782
2783	bwi_reset_rx_ring32(sc, rd->rdata_txrx_ctrl);
2784
2785	for (i = 0; i < BWI_RX_NDESC; ++i) {
2786		struct bwi_rxbuf *rb = &rbd->rbd_buf[i];
2787
2788		if (rb->rb_mbuf != NULL) {
2789			bus_dmamap_unload(sc->sc_buf_dtag, rb->rb_dmap);
2790			m_freem(rb->rb_mbuf);
2791			rb->rb_mbuf = NULL;
2792		}
2793	}
2794}
2795
2796static void
2797bwi_free_tx_ring32(struct bwi_softc *sc, int ring_idx)
2798{
2799	struct bwi_ring_data *rd;
2800	struct bwi_txbuf_data *tbd;
2801	struct ifnet *ifp = sc->sc_ifp;
2802	uint32_t state, val;
2803	int i;
2804
2805	KASSERT(ring_idx < BWI_TX_NRING, ("ring_idx %d", ring_idx));
2806	rd = &sc->sc_tx_rdata[ring_idx];
2807	tbd = &sc->sc_tx_bdata[ring_idx];
2808
2809#define NRETRY 10
2810
2811	for (i = 0; i < NRETRY; ++i) {
2812		val = CSR_READ_4(sc, rd->rdata_txrx_ctrl + BWI_TX32_STATUS);
2813		state = __SHIFTOUT(val, BWI_TX32_STATUS_STATE_MASK);
2814		if (state == BWI_TX32_STATUS_STATE_DISABLED ||
2815		    state == BWI_TX32_STATUS_STATE_IDLE ||
2816		    state == BWI_TX32_STATUS_STATE_STOPPED)
2817			break;
2818
2819		DELAY(1000);
2820	}
2821	if (i == NRETRY) {
2822		if_printf(ifp, "%s: wait for TX ring(%d) stable timed out\n",
2823			  __func__, ring_idx);
2824	}
2825
2826	CSR_WRITE_4(sc, rd->rdata_txrx_ctrl + BWI_TX32_CTRL, 0);
2827	for (i = 0; i < NRETRY; ++i) {
2828		val = CSR_READ_4(sc, rd->rdata_txrx_ctrl + BWI_TX32_STATUS);
2829		state = __SHIFTOUT(val, BWI_TX32_STATUS_STATE_MASK);
2830		if (state == BWI_TX32_STATUS_STATE_DISABLED)
2831			break;
2832
2833		DELAY(1000);
2834	}
2835	if (i == NRETRY)
2836		if_printf(ifp, "%s: reset TX ring (%d) timed out\n",
2837		     __func__, ring_idx);
2838
2839#undef NRETRY
2840
2841	DELAY(1000);
2842
2843	CSR_WRITE_4(sc, rd->rdata_txrx_ctrl + BWI_TX32_RINGINFO, 0);
2844
2845	for (i = 0; i < BWI_TX_NDESC; ++i) {
2846		struct bwi_txbuf *tb = &tbd->tbd_buf[i];
2847
2848		if (tb->tb_mbuf != NULL) {
2849			bus_dmamap_unload(sc->sc_buf_dtag, tb->tb_dmap);
2850			m_freem(tb->tb_mbuf);
2851			tb->tb_mbuf = NULL;
2852		}
2853		if (tb->tb_ni != NULL) {
2854			ieee80211_free_node(tb->tb_ni);
2855			tb->tb_ni = NULL;
2856		}
2857	}
2858}
2859
2860static void
2861bwi_free_txstats64(struct bwi_softc *sc)
2862{
2863	/* TODO:64 */
2864}
2865
2866static void
2867bwi_free_rx_ring64(struct bwi_softc *sc)
2868{
2869	/* TODO:64 */
2870}
2871
2872static void
2873bwi_free_tx_ring64(struct bwi_softc *sc, int ring_idx)
2874{
2875	/* TODO:64 */
2876}
2877
2878/* XXX does not belong here */
2879#define IEEE80211_OFDM_PLCP_RATE_MASK	__BITS(3, 0)
2880#define IEEE80211_OFDM_PLCP_LEN_MASK	__BITS(16, 5)
2881
2882static __inline void
2883bwi_ofdm_plcp_header(uint32_t *plcp0, int pkt_len, uint8_t rate)
2884{
2885	uint32_t plcp;
2886
2887	plcp = __SHIFTIN(ieee80211_rate2plcp(rate, IEEE80211_T_OFDM),
2888		    IEEE80211_OFDM_PLCP_RATE_MASK) |
2889	       __SHIFTIN(pkt_len, IEEE80211_OFDM_PLCP_LEN_MASK);
2890	*plcp0 = htole32(plcp);
2891}
2892
2893static __inline void
2894bwi_ds_plcp_header(struct ieee80211_ds_plcp_hdr *plcp, int pkt_len,
2895		   uint8_t rate)
2896{
2897	int len, service, pkt_bitlen;
2898
2899	pkt_bitlen = pkt_len * NBBY;
2900	len = howmany(pkt_bitlen * 2, rate);
2901
2902	service = IEEE80211_PLCP_SERVICE_LOCKED;
2903	if (rate == (11 * 2)) {
2904		int pkt_bitlen1;
2905
2906		/*
2907		 * PLCP service field needs to be adjusted,
2908		 * if TX rate is 11Mbytes/s
2909		 */
2910		pkt_bitlen1 = len * 11;
2911		if (pkt_bitlen1 - pkt_bitlen >= NBBY)
2912			service |= IEEE80211_PLCP_SERVICE_LENEXT7;
2913	}
2914
2915	plcp->i_signal = ieee80211_rate2plcp(rate, IEEE80211_T_CCK);
2916	plcp->i_service = service;
2917	plcp->i_length = htole16(len);
2918	/* NOTE: do NOT touch i_crc */
2919}
2920
2921static __inline void
2922bwi_plcp_header(const struct ieee80211_rate_table *rt,
2923	void *plcp, int pkt_len, uint8_t rate)
2924{
2925	enum ieee80211_phytype modtype;
2926
2927	/*
2928	 * Assume caller has zeroed 'plcp'
2929	 */
2930	modtype = ieee80211_rate2phytype(rt, rate);
2931	if (modtype == IEEE80211_T_OFDM)
2932		bwi_ofdm_plcp_header(plcp, pkt_len, rate);
2933	else if (modtype == IEEE80211_T_DS)
2934		bwi_ds_plcp_header(plcp, pkt_len, rate);
2935	else
2936		panic("unsupport modulation type %u\n", modtype);
2937}
2938
2939static int
2940bwi_encap(struct bwi_softc *sc, int idx, struct mbuf *m,
2941	  struct ieee80211_node *ni)
2942{
2943	struct ieee80211vap *vap = ni->ni_vap;
2944	struct ifnet *ifp = sc->sc_ifp;
2945	struct ieee80211com *ic = ifp->if_l2com;
2946	struct bwi_ring_data *rd = &sc->sc_tx_rdata[BWI_TX_DATA_RING];
2947	struct bwi_txbuf_data *tbd = &sc->sc_tx_bdata[BWI_TX_DATA_RING];
2948	struct bwi_txbuf *tb = &tbd->tbd_buf[idx];
2949	struct bwi_mac *mac;
2950	struct bwi_txbuf_hdr *hdr;
2951	struct ieee80211_frame *wh;
2952	const struct ieee80211_txparam *tp;
2953	uint8_t rate, rate_fb;
2954	uint32_t mac_ctrl;
2955	uint16_t phy_ctrl;
2956	bus_addr_t paddr;
2957	int type, ismcast, pkt_len, error, rix;
2958#if 0
2959	const uint8_t *p;
2960	int i;
2961#endif
2962
2963	KASSERT(sc->sc_cur_regwin->rw_type == BWI_REGWIN_T_MAC,
2964	    ("current regwin type %d", sc->sc_cur_regwin->rw_type));
2965	mac = (struct bwi_mac *)sc->sc_cur_regwin;
2966
2967	wh = mtod(m, struct ieee80211_frame *);
2968	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
2969	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
2970
2971	/* Get 802.11 frame len before prepending TX header */
2972	pkt_len = m->m_pkthdr.len + IEEE80211_CRC_LEN;
2973
2974	/*
2975	 * Find TX rate
2976	 */
2977	tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
2978	if (type != IEEE80211_FC0_TYPE_DATA || (m->m_flags & M_EAPOL)) {
2979		rate = rate_fb = tp->mgmtrate;
2980	} else if (ismcast) {
2981		rate = rate_fb = tp->mcastrate;
2982	} else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE) {
2983		rate = rate_fb = tp->ucastrate;
2984	} else {
2985		rix = ieee80211_ratectl_rate(ni, NULL, pkt_len);
2986		rate = ni->ni_txrate;
2987
2988		if (rix > 0) {
2989			rate_fb = ni->ni_rates.rs_rates[rix-1] &
2990				  IEEE80211_RATE_VAL;
2991		} else {
2992			rate_fb = rate;
2993		}
2994	}
2995	tb->tb_rate[0] = rate;
2996	tb->tb_rate[1] = rate_fb;
2997	sc->sc_tx_rate = rate;
2998
2999	/*
3000	 * TX radio tap
3001	 */
3002	if (ieee80211_radiotap_active_vap(vap)) {
3003		sc->sc_tx_th.wt_flags = 0;
3004		if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED)
3005			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
3006		if (ieee80211_rate2phytype(sc->sc_rates, rate) == IEEE80211_T_DS &&
3007		    (ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
3008		    rate != (1 * 2)) {
3009			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
3010		}
3011		sc->sc_tx_th.wt_rate = rate;
3012
3013		ieee80211_radiotap_tx(vap, m);
3014	}
3015
3016	/*
3017	 * Setup the embedded TX header
3018	 */
3019	M_PREPEND(m, sizeof(*hdr), M_NOWAIT);
3020	if (m == NULL) {
3021		if_printf(ifp, "%s: prepend TX header failed\n", __func__);
3022		return ENOBUFS;
3023	}
3024	hdr = mtod(m, struct bwi_txbuf_hdr *);
3025
3026	bzero(hdr, sizeof(*hdr));
3027
3028	bcopy(wh->i_fc, hdr->txh_fc, sizeof(hdr->txh_fc));
3029	bcopy(wh->i_addr1, hdr->txh_addr1, sizeof(hdr->txh_addr1));
3030
3031	if (!ismcast) {
3032		uint16_t dur;
3033
3034		dur = ieee80211_ack_duration(sc->sc_rates, rate,
3035		    ic->ic_flags & ~IEEE80211_F_SHPREAMBLE);
3036
3037		hdr->txh_fb_duration = htole16(dur);
3038	}
3039
3040	hdr->txh_id = __SHIFTIN(BWI_TX_DATA_RING, BWI_TXH_ID_RING_MASK) |
3041		      __SHIFTIN(idx, BWI_TXH_ID_IDX_MASK);
3042
3043	bwi_plcp_header(sc->sc_rates, hdr->txh_plcp, pkt_len, rate);
3044	bwi_plcp_header(sc->sc_rates, hdr->txh_fb_plcp, pkt_len, rate_fb);
3045
3046	phy_ctrl = __SHIFTIN(mac->mac_rf.rf_ant_mode,
3047			     BWI_TXH_PHY_C_ANTMODE_MASK);
3048	if (ieee80211_rate2phytype(sc->sc_rates, rate) == IEEE80211_T_OFDM)
3049		phy_ctrl |= BWI_TXH_PHY_C_OFDM;
3050	else if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) && rate != (2 * 1))
3051		phy_ctrl |= BWI_TXH_PHY_C_SHPREAMBLE;
3052
3053	mac_ctrl = BWI_TXH_MAC_C_HWSEQ | BWI_TXH_MAC_C_FIRST_FRAG;
3054	if (!ismcast)
3055		mac_ctrl |= BWI_TXH_MAC_C_ACK;
3056	if (ieee80211_rate2phytype(sc->sc_rates, rate_fb) == IEEE80211_T_OFDM)
3057		mac_ctrl |= BWI_TXH_MAC_C_FB_OFDM;
3058
3059	hdr->txh_mac_ctrl = htole32(mac_ctrl);
3060	hdr->txh_phy_ctrl = htole16(phy_ctrl);
3061
3062	/* Catch any further usage */
3063	hdr = NULL;
3064	wh = NULL;
3065
3066	/* DMA load */
3067	error = bus_dmamap_load_mbuf(sc->sc_buf_dtag, tb->tb_dmap, m,
3068				     bwi_dma_buf_addr, &paddr, BUS_DMA_NOWAIT);
3069	if (error && error != EFBIG) {
3070		if_printf(ifp, "%s: can't load TX buffer (1) %d\n",
3071		    __func__, error);
3072		goto back;
3073	}
3074
3075	if (error) {	/* error == EFBIG */
3076		struct mbuf *m_new;
3077
3078		m_new = m_defrag(m, M_NOWAIT);
3079		if (m_new == NULL) {
3080			if_printf(ifp, "%s: can't defrag TX buffer\n",
3081			    __func__);
3082			error = ENOBUFS;
3083			goto back;
3084		} else {
3085			m = m_new;
3086		}
3087
3088		error = bus_dmamap_load_mbuf(sc->sc_buf_dtag, tb->tb_dmap, m,
3089					     bwi_dma_buf_addr, &paddr,
3090					     BUS_DMA_NOWAIT);
3091		if (error) {
3092			if_printf(ifp, "%s: can't load TX buffer (2) %d\n",
3093			    __func__, error);
3094			goto back;
3095		}
3096	}
3097	error = 0;
3098
3099	bus_dmamap_sync(sc->sc_buf_dtag, tb->tb_dmap, BUS_DMASYNC_PREWRITE);
3100
3101	tb->tb_mbuf = m;
3102	tb->tb_ni = ni;
3103
3104#if 0
3105	p = mtod(m, const uint8_t *);
3106	for (i = 0; i < m->m_pkthdr.len; ++i) {
3107		if (i != 0 && i % 8 == 0)
3108			printf("\n");
3109		printf("%02x ", p[i]);
3110	}
3111	printf("\n");
3112#endif
3113	DPRINTF(sc, BWI_DBG_TX, "idx %d, pkt_len %d, buflen %d\n",
3114		idx, pkt_len, m->m_pkthdr.len);
3115
3116	/* Setup TX descriptor */
3117	sc->sc_setup_txdesc(sc, rd, idx, paddr, m->m_pkthdr.len);
3118	bus_dmamap_sync(sc->sc_txring_dtag, rd->rdata_dmap,
3119			BUS_DMASYNC_PREWRITE);
3120
3121	/* Kick start */
3122	sc->sc_start_tx(sc, rd->rdata_txrx_ctrl, idx);
3123
3124back:
3125	if (error)
3126		m_freem(m);
3127	return error;
3128}
3129
3130static int
3131bwi_encap_raw(struct bwi_softc *sc, int idx, struct mbuf *m,
3132	  struct ieee80211_node *ni, const struct ieee80211_bpf_params *params)
3133{
3134	struct ifnet *ifp = sc->sc_ifp;
3135	struct ieee80211vap *vap = ni->ni_vap;
3136	struct ieee80211com *ic = ni->ni_ic;
3137	struct bwi_ring_data *rd = &sc->sc_tx_rdata[BWI_TX_DATA_RING];
3138	struct bwi_txbuf_data *tbd = &sc->sc_tx_bdata[BWI_TX_DATA_RING];
3139	struct bwi_txbuf *tb = &tbd->tbd_buf[idx];
3140	struct bwi_mac *mac;
3141	struct bwi_txbuf_hdr *hdr;
3142	struct ieee80211_frame *wh;
3143	uint8_t rate, rate_fb;
3144	uint32_t mac_ctrl;
3145	uint16_t phy_ctrl;
3146	bus_addr_t paddr;
3147	int ismcast, pkt_len, error;
3148
3149	KASSERT(sc->sc_cur_regwin->rw_type == BWI_REGWIN_T_MAC,
3150	    ("current regwin type %d", sc->sc_cur_regwin->rw_type));
3151	mac = (struct bwi_mac *)sc->sc_cur_regwin;
3152
3153	wh = mtod(m, struct ieee80211_frame *);
3154	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
3155
3156	/* Get 802.11 frame len before prepending TX header */
3157	pkt_len = m->m_pkthdr.len + IEEE80211_CRC_LEN;
3158
3159	/*
3160	 * Find TX rate
3161	 */
3162	rate = params->ibp_rate0;
3163	if (!ieee80211_isratevalid(ic->ic_rt, rate)) {
3164		/* XXX fall back to mcast/mgmt rate? */
3165		m_freem(m);
3166		return EINVAL;
3167	}
3168	if (params->ibp_try1 != 0) {
3169		rate_fb = params->ibp_rate1;
3170		if (!ieee80211_isratevalid(ic->ic_rt, rate_fb)) {
3171			/* XXX fall back to rate0? */
3172			m_freem(m);
3173			return EINVAL;
3174		}
3175	} else
3176		rate_fb = rate;
3177	tb->tb_rate[0] = rate;
3178	tb->tb_rate[1] = rate_fb;
3179	sc->sc_tx_rate = rate;
3180
3181	/*
3182	 * TX radio tap
3183	 */
3184	if (ieee80211_radiotap_active_vap(vap)) {
3185		sc->sc_tx_th.wt_flags = 0;
3186		/* XXX IEEE80211_BPF_CRYPTO */
3187		if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED)
3188			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
3189		if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
3190			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
3191		sc->sc_tx_th.wt_rate = rate;
3192
3193		ieee80211_radiotap_tx(vap, m);
3194	}
3195
3196	/*
3197	 * Setup the embedded TX header
3198	 */
3199	M_PREPEND(m, sizeof(*hdr), M_NOWAIT);
3200	if (m == NULL) {
3201		if_printf(ifp, "%s: prepend TX header failed\n", __func__);
3202		return ENOBUFS;
3203	}
3204	hdr = mtod(m, struct bwi_txbuf_hdr *);
3205
3206	bzero(hdr, sizeof(*hdr));
3207
3208	bcopy(wh->i_fc, hdr->txh_fc, sizeof(hdr->txh_fc));
3209	bcopy(wh->i_addr1, hdr->txh_addr1, sizeof(hdr->txh_addr1));
3210
3211	mac_ctrl = BWI_TXH_MAC_C_HWSEQ | BWI_TXH_MAC_C_FIRST_FRAG;
3212	if (!ismcast && (params->ibp_flags & IEEE80211_BPF_NOACK) == 0) {
3213		uint16_t dur;
3214
3215		dur = ieee80211_ack_duration(sc->sc_rates, rate_fb, 0);
3216
3217		hdr->txh_fb_duration = htole16(dur);
3218		mac_ctrl |= BWI_TXH_MAC_C_ACK;
3219	}
3220
3221	hdr->txh_id = __SHIFTIN(BWI_TX_DATA_RING, BWI_TXH_ID_RING_MASK) |
3222		      __SHIFTIN(idx, BWI_TXH_ID_IDX_MASK);
3223
3224	bwi_plcp_header(sc->sc_rates, hdr->txh_plcp, pkt_len, rate);
3225	bwi_plcp_header(sc->sc_rates, hdr->txh_fb_plcp, pkt_len, rate_fb);
3226
3227	phy_ctrl = __SHIFTIN(mac->mac_rf.rf_ant_mode,
3228			     BWI_TXH_PHY_C_ANTMODE_MASK);
3229	if (ieee80211_rate2phytype(sc->sc_rates, rate) == IEEE80211_T_OFDM) {
3230		phy_ctrl |= BWI_TXH_PHY_C_OFDM;
3231		mac_ctrl |= BWI_TXH_MAC_C_FB_OFDM;
3232	} else if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
3233		phy_ctrl |= BWI_TXH_PHY_C_SHPREAMBLE;
3234
3235	hdr->txh_mac_ctrl = htole32(mac_ctrl);
3236	hdr->txh_phy_ctrl = htole16(phy_ctrl);
3237
3238	/* Catch any further usage */
3239	hdr = NULL;
3240	wh = NULL;
3241
3242	/* DMA load */
3243	error = bus_dmamap_load_mbuf(sc->sc_buf_dtag, tb->tb_dmap, m,
3244				     bwi_dma_buf_addr, &paddr, BUS_DMA_NOWAIT);
3245	if (error != 0) {
3246		struct mbuf *m_new;
3247
3248		if (error != EFBIG) {
3249			if_printf(ifp, "%s: can't load TX buffer (1) %d\n",
3250			    __func__, error);
3251			goto back;
3252		}
3253		m_new = m_defrag(m, M_NOWAIT);
3254		if (m_new == NULL) {
3255			if_printf(ifp, "%s: can't defrag TX buffer\n",
3256			    __func__);
3257			error = ENOBUFS;
3258			goto back;
3259		}
3260		m = m_new;
3261		error = bus_dmamap_load_mbuf(sc->sc_buf_dtag, tb->tb_dmap, m,
3262					     bwi_dma_buf_addr, &paddr,
3263					     BUS_DMA_NOWAIT);
3264		if (error) {
3265			if_printf(ifp, "%s: can't load TX buffer (2) %d\n",
3266			    __func__, error);
3267			goto back;
3268		}
3269	}
3270
3271	bus_dmamap_sync(sc->sc_buf_dtag, tb->tb_dmap, BUS_DMASYNC_PREWRITE);
3272
3273	tb->tb_mbuf = m;
3274	tb->tb_ni = ni;
3275
3276	DPRINTF(sc, BWI_DBG_TX, "idx %d, pkt_len %d, buflen %d\n",
3277		idx, pkt_len, m->m_pkthdr.len);
3278
3279	/* Setup TX descriptor */
3280	sc->sc_setup_txdesc(sc, rd, idx, paddr, m->m_pkthdr.len);
3281	bus_dmamap_sync(sc->sc_txring_dtag, rd->rdata_dmap,
3282			BUS_DMASYNC_PREWRITE);
3283
3284	/* Kick start */
3285	sc->sc_start_tx(sc, rd->rdata_txrx_ctrl, idx);
3286back:
3287	if (error)
3288		m_freem(m);
3289	return error;
3290}
3291
3292static void
3293bwi_start_tx32(struct bwi_softc *sc, uint32_t tx_ctrl, int idx)
3294{
3295	idx = (idx + 1) % BWI_TX_NDESC;
3296	CSR_WRITE_4(sc, tx_ctrl + BWI_TX32_INDEX,
3297		    idx * sizeof(struct bwi_desc32));
3298}
3299
3300static void
3301bwi_start_tx64(struct bwi_softc *sc, uint32_t tx_ctrl, int idx)
3302{
3303	/* TODO:64 */
3304}
3305
3306static void
3307bwi_txeof_status32(struct bwi_softc *sc)
3308{
3309	struct ifnet *ifp = sc->sc_ifp;
3310	uint32_t val, ctrl_base;
3311	int end_idx;
3312
3313	ctrl_base = sc->sc_txstats->stats_ctrl_base;
3314
3315	val = CSR_READ_4(sc, ctrl_base + BWI_RX32_STATUS);
3316	end_idx = __SHIFTOUT(val, BWI_RX32_STATUS_INDEX_MASK) /
3317		  sizeof(struct bwi_desc32);
3318
3319	bwi_txeof_status(sc, end_idx);
3320
3321	CSR_WRITE_4(sc, ctrl_base + BWI_RX32_INDEX,
3322		    end_idx * sizeof(struct bwi_desc32));
3323
3324	if ((ifp->if_drv_flags & IFF_DRV_OACTIVE) == 0)
3325		ifp->if_start(ifp);
3326}
3327
3328static void
3329bwi_txeof_status64(struct bwi_softc *sc)
3330{
3331	/* TODO:64 */
3332}
3333
3334static void
3335_bwi_txeof(struct bwi_softc *sc, uint16_t tx_id, int acked, int data_txcnt)
3336{
3337	struct ifnet *ifp = sc->sc_ifp;
3338	struct bwi_txbuf_data *tbd;
3339	struct bwi_txbuf *tb;
3340	int ring_idx, buf_idx;
3341	struct ieee80211_node *ni;
3342	struct ieee80211vap *vap;
3343
3344	if (tx_id == 0) {
3345		if_printf(ifp, "%s: zero tx id\n", __func__);
3346		return;
3347	}
3348
3349	ring_idx = __SHIFTOUT(tx_id, BWI_TXH_ID_RING_MASK);
3350	buf_idx = __SHIFTOUT(tx_id, BWI_TXH_ID_IDX_MASK);
3351
3352	KASSERT(ring_idx == BWI_TX_DATA_RING, ("ring_idx %d", ring_idx));
3353	KASSERT(buf_idx < BWI_TX_NDESC, ("buf_idx %d", buf_idx));
3354
3355	tbd = &sc->sc_tx_bdata[ring_idx];
3356	KASSERT(tbd->tbd_used > 0, ("tbd_used %d", tbd->tbd_used));
3357	tbd->tbd_used--;
3358
3359	tb = &tbd->tbd_buf[buf_idx];
3360	DPRINTF(sc, BWI_DBG_TXEOF, "txeof idx %d, "
3361		"acked %d, data_txcnt %d, ni %p\n",
3362		buf_idx, acked, data_txcnt, tb->tb_ni);
3363
3364	bus_dmamap_unload(sc->sc_buf_dtag, tb->tb_dmap);
3365
3366	ni = tb->tb_ni;
3367	if (tb->tb_ni != NULL) {
3368		const struct bwi_txbuf_hdr *hdr =
3369		    mtod(tb->tb_mbuf, const struct bwi_txbuf_hdr *);
3370		vap = ni->ni_vap;
3371
3372		/* NB: update rate control only for unicast frames */
3373		if (hdr->txh_mac_ctrl & htole32(BWI_TXH_MAC_C_ACK)) {
3374			/*
3375			 * Feed back 'acked and data_txcnt'.  Note that the
3376			 * generic AMRR code only understands one tx rate
3377			 * and the estimator doesn't handle real retry counts
3378			 * well so to avoid over-aggressive downshifting we
3379			 * treat any number of retries as "1".
3380			 */
3381			ieee80211_ratectl_tx_complete(vap, ni,
3382			    (data_txcnt > 1) ? IEEE80211_RATECTL_TX_SUCCESS :
3383			        IEEE80211_RATECTL_TX_FAILURE, &acked, NULL);
3384		}
3385
3386		/*
3387		 * Do any tx complete callback.  Note this must
3388		 * be done before releasing the node reference.
3389		 */
3390		if (tb->tb_mbuf->m_flags & M_TXCB)
3391			ieee80211_process_callback(ni, tb->tb_mbuf, !acked);
3392
3393		ieee80211_free_node(tb->tb_ni);
3394		tb->tb_ni = NULL;
3395	}
3396	m_freem(tb->tb_mbuf);
3397	tb->tb_mbuf = NULL;
3398
3399	if (tbd->tbd_used == 0)
3400		sc->sc_tx_timer = 0;
3401
3402	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3403}
3404
3405static void
3406bwi_txeof_status(struct bwi_softc *sc, int end_idx)
3407{
3408	struct bwi_txstats_data *st = sc->sc_txstats;
3409	int idx;
3410
3411	bus_dmamap_sync(st->stats_dtag, st->stats_dmap, BUS_DMASYNC_POSTREAD);
3412
3413	idx = st->stats_idx;
3414	while (idx != end_idx) {
3415		const struct bwi_txstats *stats = &st->stats[idx];
3416
3417		if ((stats->txs_flags & BWI_TXS_F_PENDING) == 0) {
3418			int data_txcnt;
3419
3420			data_txcnt = __SHIFTOUT(stats->txs_txcnt,
3421						BWI_TXS_TXCNT_DATA);
3422			_bwi_txeof(sc, le16toh(stats->txs_id),
3423				   stats->txs_flags & BWI_TXS_F_ACKED,
3424				   data_txcnt);
3425		}
3426		idx = (idx + 1) % BWI_TXSTATS_NDESC;
3427	}
3428	st->stats_idx = idx;
3429}
3430
3431static void
3432bwi_txeof(struct bwi_softc *sc)
3433{
3434	struct ifnet *ifp = sc->sc_ifp;
3435
3436	for (;;) {
3437		uint32_t tx_status0, tx_status1;
3438		uint16_t tx_id;
3439		int data_txcnt;
3440
3441		tx_status0 = CSR_READ_4(sc, BWI_TXSTATUS0);
3442		if ((tx_status0 & BWI_TXSTATUS0_VALID) == 0)
3443			break;
3444		tx_status1 = CSR_READ_4(sc, BWI_TXSTATUS1);
3445
3446		tx_id = __SHIFTOUT(tx_status0, BWI_TXSTATUS0_TXID_MASK);
3447		data_txcnt = __SHIFTOUT(tx_status0,
3448				BWI_TXSTATUS0_DATA_TXCNT_MASK);
3449
3450		if (tx_status0 & (BWI_TXSTATUS0_AMPDU | BWI_TXSTATUS0_PENDING))
3451			continue;
3452
3453		_bwi_txeof(sc, le16toh(tx_id), tx_status0 & BWI_TXSTATUS0_ACKED,
3454		    data_txcnt);
3455	}
3456
3457	if ((ifp->if_drv_flags & IFF_DRV_OACTIVE) == 0)
3458		ifp->if_start(ifp);
3459}
3460
3461static int
3462bwi_bbp_power_on(struct bwi_softc *sc, enum bwi_clock_mode clk_mode)
3463{
3464	bwi_power_on(sc, 1);
3465	return bwi_set_clock_mode(sc, clk_mode);
3466}
3467
3468static void
3469bwi_bbp_power_off(struct bwi_softc *sc)
3470{
3471	bwi_set_clock_mode(sc, BWI_CLOCK_MODE_SLOW);
3472	bwi_power_off(sc, 1);
3473}
3474
3475static int
3476bwi_get_pwron_delay(struct bwi_softc *sc)
3477{
3478	struct bwi_regwin *com, *old;
3479	struct bwi_clock_freq freq;
3480	uint32_t val;
3481	int error;
3482
3483	com = &sc->sc_com_regwin;
3484	KASSERT(BWI_REGWIN_EXIST(com), ("no regwin"));
3485
3486	if ((sc->sc_cap & BWI_CAP_CLKMODE) == 0)
3487		return 0;
3488
3489	error = bwi_regwin_switch(sc, com, &old);
3490	if (error)
3491		return error;
3492
3493	bwi_get_clock_freq(sc, &freq);
3494
3495	val = CSR_READ_4(sc, BWI_PLL_ON_DELAY);
3496	sc->sc_pwron_delay = howmany((val + 2) * 1000000, freq.clkfreq_min);
3497	DPRINTF(sc, BWI_DBG_ATTACH, "power on delay %u\n", sc->sc_pwron_delay);
3498
3499	return bwi_regwin_switch(sc, old, NULL);
3500}
3501
3502static int
3503bwi_bus_attach(struct bwi_softc *sc)
3504{
3505	struct bwi_regwin *bus, *old;
3506	int error;
3507
3508	bus = &sc->sc_bus_regwin;
3509
3510	error = bwi_regwin_switch(sc, bus, &old);
3511	if (error)
3512		return error;
3513
3514	if (!bwi_regwin_is_enabled(sc, bus))
3515		bwi_regwin_enable(sc, bus, 0);
3516
3517	/* Disable interripts */
3518	CSR_WRITE_4(sc, BWI_INTRVEC, 0);
3519
3520	return bwi_regwin_switch(sc, old, NULL);
3521}
3522
3523static const char *
3524bwi_regwin_name(const struct bwi_regwin *rw)
3525{
3526	switch (rw->rw_type) {
3527	case BWI_REGWIN_T_COM:
3528		return "COM";
3529	case BWI_REGWIN_T_BUSPCI:
3530		return "PCI";
3531	case BWI_REGWIN_T_MAC:
3532		return "MAC";
3533	case BWI_REGWIN_T_BUSPCIE:
3534		return "PCIE";
3535	}
3536	panic("unknown regwin type 0x%04x\n", rw->rw_type);
3537	return NULL;
3538}
3539
3540static uint32_t
3541bwi_regwin_disable_bits(struct bwi_softc *sc)
3542{
3543	uint32_t busrev;
3544
3545	/* XXX cache this */
3546	busrev = __SHIFTOUT(CSR_READ_4(sc, BWI_ID_LO), BWI_ID_LO_BUSREV_MASK);
3547	DPRINTF(sc, BWI_DBG_ATTACH | BWI_DBG_INIT | BWI_DBG_MISC,
3548		"bus rev %u\n", busrev);
3549
3550	if (busrev == BWI_BUSREV_0)
3551		return BWI_STATE_LO_DISABLE1;
3552	else if (busrev == BWI_BUSREV_1)
3553		return BWI_STATE_LO_DISABLE2;
3554	else
3555		return (BWI_STATE_LO_DISABLE1 | BWI_STATE_LO_DISABLE2);
3556}
3557
3558int
3559bwi_regwin_is_enabled(struct bwi_softc *sc, struct bwi_regwin *rw)
3560{
3561	uint32_t val, disable_bits;
3562
3563	disable_bits = bwi_regwin_disable_bits(sc);
3564	val = CSR_READ_4(sc, BWI_STATE_LO);
3565
3566	if ((val & (BWI_STATE_LO_CLOCK |
3567		    BWI_STATE_LO_RESET |
3568		    disable_bits)) == BWI_STATE_LO_CLOCK) {
3569		DPRINTF(sc, BWI_DBG_ATTACH | BWI_DBG_INIT, "%s is enabled\n",
3570			bwi_regwin_name(rw));
3571		return 1;
3572	} else {
3573		DPRINTF(sc, BWI_DBG_ATTACH | BWI_DBG_INIT, "%s is disabled\n",
3574			bwi_regwin_name(rw));
3575		return 0;
3576	}
3577}
3578
3579void
3580bwi_regwin_disable(struct bwi_softc *sc, struct bwi_regwin *rw, uint32_t flags)
3581{
3582	uint32_t state_lo, disable_bits;
3583	int i;
3584
3585	state_lo = CSR_READ_4(sc, BWI_STATE_LO);
3586
3587	/*
3588	 * If current regwin is in 'reset' state, it was already disabled.
3589	 */
3590	if (state_lo & BWI_STATE_LO_RESET) {
3591		DPRINTF(sc, BWI_DBG_ATTACH | BWI_DBG_INIT,
3592			"%s was already disabled\n", bwi_regwin_name(rw));
3593		return;
3594	}
3595
3596	disable_bits = bwi_regwin_disable_bits(sc);
3597
3598	/*
3599	 * Disable normal clock
3600	 */
3601	state_lo = BWI_STATE_LO_CLOCK | disable_bits;
3602	CSR_WRITE_4(sc, BWI_STATE_LO, state_lo);
3603
3604	/*
3605	 * Wait until normal clock is disabled
3606	 */
3607#define NRETRY	1000
3608	for (i = 0; i < NRETRY; ++i) {
3609		state_lo = CSR_READ_4(sc, BWI_STATE_LO);
3610		if (state_lo & disable_bits)
3611			break;
3612		DELAY(10);
3613	}
3614	if (i == NRETRY) {
3615		device_printf(sc->sc_dev, "%s disable clock timeout\n",
3616			      bwi_regwin_name(rw));
3617	}
3618
3619	for (i = 0; i < NRETRY; ++i) {
3620		uint32_t state_hi;
3621
3622		state_hi = CSR_READ_4(sc, BWI_STATE_HI);
3623		if ((state_hi & BWI_STATE_HI_BUSY) == 0)
3624			break;
3625		DELAY(10);
3626	}
3627	if (i == NRETRY) {
3628		device_printf(sc->sc_dev, "%s wait BUSY unset timeout\n",
3629			      bwi_regwin_name(rw));
3630	}
3631#undef NRETRY
3632
3633	/*
3634	 * Reset and disable regwin with gated clock
3635	 */
3636	state_lo = BWI_STATE_LO_RESET | disable_bits |
3637		   BWI_STATE_LO_CLOCK | BWI_STATE_LO_GATED_CLOCK |
3638		   __SHIFTIN(flags, BWI_STATE_LO_FLAGS_MASK);
3639	CSR_WRITE_4(sc, BWI_STATE_LO, state_lo);
3640
3641	/* Flush pending bus write */
3642	CSR_READ_4(sc, BWI_STATE_LO);
3643	DELAY(1);
3644
3645	/* Reset and disable regwin */
3646	state_lo = BWI_STATE_LO_RESET | disable_bits |
3647		   __SHIFTIN(flags, BWI_STATE_LO_FLAGS_MASK);
3648	CSR_WRITE_4(sc, BWI_STATE_LO, state_lo);
3649
3650	/* Flush pending bus write */
3651	CSR_READ_4(sc, BWI_STATE_LO);
3652	DELAY(1);
3653}
3654
3655void
3656bwi_regwin_enable(struct bwi_softc *sc, struct bwi_regwin *rw, uint32_t flags)
3657{
3658	uint32_t state_lo, state_hi, imstate;
3659
3660	bwi_regwin_disable(sc, rw, flags);
3661
3662	/* Reset regwin with gated clock */
3663	state_lo = BWI_STATE_LO_RESET |
3664		   BWI_STATE_LO_CLOCK |
3665		   BWI_STATE_LO_GATED_CLOCK |
3666		   __SHIFTIN(flags, BWI_STATE_LO_FLAGS_MASK);
3667	CSR_WRITE_4(sc, BWI_STATE_LO, state_lo);
3668
3669	/* Flush pending bus write */
3670	CSR_READ_4(sc, BWI_STATE_LO);
3671	DELAY(1);
3672
3673	state_hi = CSR_READ_4(sc, BWI_STATE_HI);
3674	if (state_hi & BWI_STATE_HI_SERROR)
3675		CSR_WRITE_4(sc, BWI_STATE_HI, 0);
3676
3677	imstate = CSR_READ_4(sc, BWI_IMSTATE);
3678	if (imstate & (BWI_IMSTATE_INBAND_ERR | BWI_IMSTATE_TIMEOUT)) {
3679		imstate &= ~(BWI_IMSTATE_INBAND_ERR | BWI_IMSTATE_TIMEOUT);
3680		CSR_WRITE_4(sc, BWI_IMSTATE, imstate);
3681	}
3682
3683	/* Enable regwin with gated clock */
3684	state_lo = BWI_STATE_LO_CLOCK |
3685		   BWI_STATE_LO_GATED_CLOCK |
3686		   __SHIFTIN(flags, BWI_STATE_LO_FLAGS_MASK);
3687	CSR_WRITE_4(sc, BWI_STATE_LO, state_lo);
3688
3689	/* Flush pending bus write */
3690	CSR_READ_4(sc, BWI_STATE_LO);
3691	DELAY(1);
3692
3693	/* Enable regwin with normal clock */
3694	state_lo = BWI_STATE_LO_CLOCK |
3695		   __SHIFTIN(flags, BWI_STATE_LO_FLAGS_MASK);
3696	CSR_WRITE_4(sc, BWI_STATE_LO, state_lo);
3697
3698	/* Flush pending bus write */
3699	CSR_READ_4(sc, BWI_STATE_LO);
3700	DELAY(1);
3701}
3702
3703static void
3704bwi_set_bssid(struct bwi_softc *sc, const uint8_t *bssid)
3705{
3706	struct ifnet *ifp = sc->sc_ifp;
3707	struct bwi_mac *mac;
3708	struct bwi_myaddr_bssid buf;
3709	const uint8_t *p;
3710	uint32_t val;
3711	int n, i;
3712
3713	KASSERT(sc->sc_cur_regwin->rw_type == BWI_REGWIN_T_MAC,
3714	    ("current regwin type %d", sc->sc_cur_regwin->rw_type));
3715	mac = (struct bwi_mac *)sc->sc_cur_regwin;
3716
3717	bwi_set_addr_filter(sc, BWI_ADDR_FILTER_BSSID, bssid);
3718
3719	bcopy(IF_LLADDR(ifp), buf.myaddr, sizeof(buf.myaddr));
3720	bcopy(bssid, buf.bssid, sizeof(buf.bssid));
3721
3722	n = sizeof(buf) / sizeof(val);
3723	p = (const uint8_t *)&buf;
3724	for (i = 0; i < n; ++i) {
3725		int j;
3726
3727		val = 0;
3728		for (j = 0; j < sizeof(val); ++j)
3729			val |= ((uint32_t)(*p++)) << (j * 8);
3730
3731		TMPLT_WRITE_4(mac, 0x20 + (i * sizeof(val)), val);
3732	}
3733}
3734
3735static void
3736bwi_updateslot(struct ifnet *ifp)
3737{
3738	struct bwi_softc *sc = ifp->if_softc;
3739	struct ieee80211com *ic = ifp->if_l2com;
3740	struct bwi_mac *mac;
3741
3742	BWI_LOCK(sc);
3743	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
3744		DPRINTF(sc, BWI_DBG_80211, "%s\n", __func__);
3745
3746		KASSERT(sc->sc_cur_regwin->rw_type == BWI_REGWIN_T_MAC,
3747		    ("current regwin type %d", sc->sc_cur_regwin->rw_type));
3748		mac = (struct bwi_mac *)sc->sc_cur_regwin;
3749
3750		bwi_mac_updateslot(mac, (ic->ic_flags & IEEE80211_F_SHSLOT));
3751	}
3752	BWI_UNLOCK(sc);
3753}
3754
3755static void
3756bwi_calibrate(void *xsc)
3757{
3758	struct bwi_softc *sc = xsc;
3759#ifdef INVARIANTS
3760	struct ifnet *ifp = sc->sc_ifp;
3761	struct ieee80211com *ic = ifp->if_l2com;
3762#endif
3763	struct bwi_mac *mac;
3764
3765	BWI_ASSERT_LOCKED(sc);
3766
3767	KASSERT(ic->ic_opmode != IEEE80211_M_MONITOR,
3768	    ("opmode %d", ic->ic_opmode));
3769
3770	KASSERT(sc->sc_cur_regwin->rw_type == BWI_REGWIN_T_MAC,
3771	    ("current regwin type %d", sc->sc_cur_regwin->rw_type));
3772	mac = (struct bwi_mac *)sc->sc_cur_regwin;
3773
3774	bwi_mac_calibrate_txpower(mac, sc->sc_txpwrcb_type);
3775	sc->sc_txpwrcb_type = BWI_TXPWR_CALIB;
3776
3777	/* XXX 15 seconds */
3778	callout_reset(&sc->sc_calib_ch, hz * 15, bwi_calibrate, sc);
3779}
3780
3781static int
3782bwi_calc_rssi(struct bwi_softc *sc, const struct bwi_rxbuf_hdr *hdr)
3783{
3784	struct bwi_mac *mac;
3785
3786	KASSERT(sc->sc_cur_regwin->rw_type == BWI_REGWIN_T_MAC,
3787	    ("current regwin type %d", sc->sc_cur_regwin->rw_type));
3788	mac = (struct bwi_mac *)sc->sc_cur_regwin;
3789
3790	return bwi_rf_calc_rssi(mac, hdr);
3791}
3792
3793static int
3794bwi_calc_noise(struct bwi_softc *sc)
3795{
3796	struct bwi_mac *mac;
3797
3798	KASSERT(sc->sc_cur_regwin->rw_type == BWI_REGWIN_T_MAC,
3799	    ("current regwin type %d", sc->sc_cur_regwin->rw_type));
3800	mac = (struct bwi_mac *)sc->sc_cur_regwin;
3801
3802	return bwi_rf_calc_noise(mac);
3803}
3804
3805static __inline uint8_t
3806bwi_plcp2rate(const uint32_t plcp0, enum ieee80211_phytype type)
3807{
3808	uint32_t plcp = le32toh(plcp0) & IEEE80211_OFDM_PLCP_RATE_MASK;
3809	return (ieee80211_plcp2rate(plcp, type));
3810}
3811
3812static void
3813bwi_rx_radiotap(struct bwi_softc *sc, struct mbuf *m,
3814    struct bwi_rxbuf_hdr *hdr, const void *plcp, int rate, int rssi, int noise)
3815{
3816	const struct ieee80211_frame_min *wh;
3817
3818	sc->sc_rx_th.wr_flags = IEEE80211_RADIOTAP_F_FCS;
3819	if (htole16(hdr->rxh_flags1) & BWI_RXH_F1_SHPREAMBLE)
3820		sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
3821
3822	wh = mtod(m, const struct ieee80211_frame_min *);
3823	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED)
3824		sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_WEP;
3825
3826	sc->sc_rx_th.wr_tsf = hdr->rxh_tsf; /* No endian convertion */
3827	sc->sc_rx_th.wr_rate = rate;
3828	sc->sc_rx_th.wr_antsignal = rssi;
3829	sc->sc_rx_th.wr_antnoise = noise;
3830}
3831
3832static void
3833bwi_led_attach(struct bwi_softc *sc)
3834{
3835	const uint8_t *led_act = NULL;
3836	uint16_t gpio, val[BWI_LED_MAX];
3837	int i;
3838
3839#define N(arr)	(int)(sizeof(arr) / sizeof(arr[0]))
3840
3841	for (i = 0; i < N(bwi_vendor_led_act); ++i) {
3842		if (sc->sc_pci_subvid == bwi_vendor_led_act[i].vid) {
3843			led_act = bwi_vendor_led_act[i].led_act;
3844			break;
3845		}
3846	}
3847	if (led_act == NULL)
3848		led_act = bwi_default_led_act;
3849
3850#undef N
3851
3852	gpio = bwi_read_sprom(sc, BWI_SPROM_GPIO01);
3853	val[0] = __SHIFTOUT(gpio, BWI_SPROM_GPIO_0);
3854	val[1] = __SHIFTOUT(gpio, BWI_SPROM_GPIO_1);
3855
3856	gpio = bwi_read_sprom(sc, BWI_SPROM_GPIO23);
3857	val[2] = __SHIFTOUT(gpio, BWI_SPROM_GPIO_2);
3858	val[3] = __SHIFTOUT(gpio, BWI_SPROM_GPIO_3);
3859
3860	for (i = 0; i < BWI_LED_MAX; ++i) {
3861		struct bwi_led *led = &sc->sc_leds[i];
3862
3863		if (val[i] == 0xff) {
3864			led->l_act = led_act[i];
3865		} else {
3866			if (val[i] & BWI_LED_ACT_LOW)
3867				led->l_flags |= BWI_LED_F_ACTLOW;
3868			led->l_act = __SHIFTOUT(val[i], BWI_LED_ACT_MASK);
3869		}
3870		led->l_mask = (1 << i);
3871
3872		if (led->l_act == BWI_LED_ACT_BLINK_SLOW ||
3873		    led->l_act == BWI_LED_ACT_BLINK_POLL ||
3874		    led->l_act == BWI_LED_ACT_BLINK) {
3875			led->l_flags |= BWI_LED_F_BLINK;
3876			if (led->l_act == BWI_LED_ACT_BLINK_POLL)
3877				led->l_flags |= BWI_LED_F_POLLABLE;
3878			else if (led->l_act == BWI_LED_ACT_BLINK_SLOW)
3879				led->l_flags |= BWI_LED_F_SLOW;
3880
3881			if (sc->sc_blink_led == NULL) {
3882				sc->sc_blink_led = led;
3883				if (led->l_flags & BWI_LED_F_SLOW)
3884					BWI_LED_SLOWDOWN(sc->sc_led_idle);
3885			}
3886		}
3887
3888		DPRINTF(sc, BWI_DBG_LED | BWI_DBG_ATTACH,
3889			"%dth led, act %d, lowact %d\n", i,
3890			led->l_act, led->l_flags & BWI_LED_F_ACTLOW);
3891	}
3892	callout_init_mtx(&sc->sc_led_blink_ch, &sc->sc_mtx, 0);
3893}
3894
3895static __inline uint16_t
3896bwi_led_onoff(const struct bwi_led *led, uint16_t val, int on)
3897{
3898	if (led->l_flags & BWI_LED_F_ACTLOW)
3899		on = !on;
3900	if (on)
3901		val |= led->l_mask;
3902	else
3903		val &= ~led->l_mask;
3904	return val;
3905}
3906
3907static void
3908bwi_led_newstate(struct bwi_softc *sc, enum ieee80211_state nstate)
3909{
3910	struct ifnet *ifp = sc->sc_ifp;
3911	struct ieee80211com *ic = ifp->if_l2com;
3912	uint16_t val;
3913	int i;
3914
3915	if (nstate == IEEE80211_S_INIT) {
3916		callout_stop(&sc->sc_led_blink_ch);
3917		sc->sc_led_blinking = 0;
3918	}
3919
3920	if ((ic->ic_ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
3921		return;
3922
3923	val = CSR_READ_2(sc, BWI_MAC_GPIO_CTRL);
3924	for (i = 0; i < BWI_LED_MAX; ++i) {
3925		struct bwi_led *led = &sc->sc_leds[i];
3926		int on;
3927
3928		if (led->l_act == BWI_LED_ACT_UNKN ||
3929		    led->l_act == BWI_LED_ACT_NULL)
3930			continue;
3931
3932		if ((led->l_flags & BWI_LED_F_BLINK) &&
3933		    nstate != IEEE80211_S_INIT)
3934		    	continue;
3935
3936		switch (led->l_act) {
3937		case BWI_LED_ACT_ON:	/* Always on */
3938			on = 1;
3939			break;
3940		case BWI_LED_ACT_OFF:	/* Always off */
3941		case BWI_LED_ACT_5GHZ:	/* TODO: 11A */
3942			on = 0;
3943			break;
3944		default:
3945			on = 1;
3946			switch (nstate) {
3947			case IEEE80211_S_INIT:
3948				on = 0;
3949				break;
3950			case IEEE80211_S_RUN:
3951				if (led->l_act == BWI_LED_ACT_11G &&
3952				    ic->ic_curmode != IEEE80211_MODE_11G)
3953					on = 0;
3954				break;
3955			default:
3956				if (led->l_act == BWI_LED_ACT_ASSOC)
3957					on = 0;
3958				break;
3959			}
3960			break;
3961		}
3962
3963		val = bwi_led_onoff(led, val, on);
3964	}
3965	CSR_WRITE_2(sc, BWI_MAC_GPIO_CTRL, val);
3966}
3967static void
3968bwi_led_event(struct bwi_softc *sc, int event)
3969{
3970	struct bwi_led *led = sc->sc_blink_led;
3971	int rate;
3972
3973	if (event == BWI_LED_EVENT_POLL) {
3974		if ((led->l_flags & BWI_LED_F_POLLABLE) == 0)
3975			return;
3976		if (ticks - sc->sc_led_ticks < sc->sc_led_idle)
3977			return;
3978	}
3979
3980	sc->sc_led_ticks = ticks;
3981	if (sc->sc_led_blinking)
3982		return;
3983
3984	switch (event) {
3985	case BWI_LED_EVENT_RX:
3986		rate = sc->sc_rx_rate;
3987		break;
3988	case BWI_LED_EVENT_TX:
3989		rate = sc->sc_tx_rate;
3990		break;
3991	case BWI_LED_EVENT_POLL:
3992		rate = 0;
3993		break;
3994	default:
3995		panic("unknown LED event %d\n", event);
3996		break;
3997	}
3998	bwi_led_blink_start(sc, bwi_led_duration[rate].on_dur,
3999	    bwi_led_duration[rate].off_dur);
4000}
4001
4002static void
4003bwi_led_blink_start(struct bwi_softc *sc, int on_dur, int off_dur)
4004{
4005	struct bwi_led *led = sc->sc_blink_led;
4006	uint16_t val;
4007
4008	val = CSR_READ_2(sc, BWI_MAC_GPIO_CTRL);
4009	val = bwi_led_onoff(led, val, 1);
4010	CSR_WRITE_2(sc, BWI_MAC_GPIO_CTRL, val);
4011
4012	if (led->l_flags & BWI_LED_F_SLOW) {
4013		BWI_LED_SLOWDOWN(on_dur);
4014		BWI_LED_SLOWDOWN(off_dur);
4015	}
4016
4017	sc->sc_led_blinking = 1;
4018	sc->sc_led_blink_offdur = off_dur;
4019
4020	callout_reset(&sc->sc_led_blink_ch, on_dur, bwi_led_blink_next, sc);
4021}
4022
4023static void
4024bwi_led_blink_next(void *xsc)
4025{
4026	struct bwi_softc *sc = xsc;
4027	uint16_t val;
4028
4029	val = CSR_READ_2(sc, BWI_MAC_GPIO_CTRL);
4030	val = bwi_led_onoff(sc->sc_blink_led, val, 0);
4031	CSR_WRITE_2(sc, BWI_MAC_GPIO_CTRL, val);
4032
4033	callout_reset(&sc->sc_led_blink_ch, sc->sc_led_blink_offdur,
4034	    bwi_led_blink_end, sc);
4035}
4036
4037static void
4038bwi_led_blink_end(void *xsc)
4039{
4040	struct bwi_softc *sc = xsc;
4041	sc->sc_led_blinking = 0;
4042}
4043
4044static void
4045bwi_restart(void *xsc, int pending)
4046{
4047	struct bwi_softc *sc = xsc;
4048	struct ifnet *ifp = sc->sc_ifp;
4049
4050	if_printf(ifp, "%s begin, help!\n", __func__);
4051	BWI_LOCK(sc);
4052	bwi_init_statechg(xsc, 0);
4053#if 0
4054	bwi_start_locked(ifp);
4055#endif
4056	BWI_UNLOCK(sc);
4057}
4058