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