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