c4c0a6f3c0b73b9c5b574afa986b27e266a0c924
[dragonfly.git] / sys / dev / netif / acx / if_acx.c
1 /*
2  * Copyright (c) 2006 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/acx/if_acx.c,v 1.26 2008/02/14 12:53:52 sephe Exp $
35  */
36
37 /*
38  * Copyright (c) 2003-2004 wlan.kewl.org Project
39  * All rights reserved.
40  * 
41  * $Id: LICENSE,v 1.1.1.1 2004/07/01 12:20:39 darron Exp $
42  *  
43  * Redistribution and use in source and binary forms, with or without
44  * modification, are permitted provided that the following conditions
45  * are met:
46  * 
47  * 1. Redistributions of source code must retain the above copyright
48  *    notice, this list of conditions and the following disclaimer.
49  * 
50  * 2. Redistributions in binary form must reproduce the above copyright
51  *    notice, this list of conditions and the following disclaimer in the
52  *    documentation and/or other materials provided with the distribution.
53  *    
54  * 3. All advertising materials mentioning features or use of this software
55  *    must display the following acknowledgement:
56  * 
57  *    This product includes software developed by the wlan.kewl.org Project.
58  * 
59  * 4. Neither the name of the wlan.kewl.org Project nor the names of its
60  *    contributors may be used to endorse or promote products derived from
61  *    this software without specific prior written permission.
62  * 
63  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
64  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
65  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
66  * THE wlan.kewl.org Project BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
67  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
68  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
69  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
70  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
71  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
72  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
73  */
74
75 #include <sys/param.h>
76 #include <sys/endian.h>
77 #include <sys/kernel.h>
78 #include <sys/bus.h>
79 #include <sys/firmware.h>
80 #include <sys/malloc.h>
81 #include <sys/proc.h>
82 #include <sys/rman.h>
83 #include <sys/serialize.h>
84 #include <sys/socket.h>
85 #include <sys/sockio.h>
86 #include <sys/sysctl.h>
87
88 #include <net/ethernet.h>
89 #include <net/if.h>
90 #include <net/bpf.h>
91 #include <net/if_arp.h>
92 #include <net/if_dl.h>
93 #include <net/if_media.h>
94 #include <net/ifq_var.h>
95
96 #include <netproto/802_11/ieee80211_var.h>
97 #include <netproto/802_11/ieee80211_radiotap.h>
98 #include <netproto/802_11/wlan_ratectl/amrr/ieee80211_amrr_param.h>
99 #include <netproto/802_11/wlan_ratectl/onoe/ieee80211_onoe_param.h>
100
101 #include <bus/pci/pcireg.h>
102 #include <bus/pci/pcivar.h>
103 #include <bus/pci/pcidevs.h>
104
105 #define ACX_DEBUG
106
107 #include <dev/netif/acx/if_acxreg.h>
108 #include <dev/netif/acx/if_acxvar.h>
109 #include <dev/netif/acx/acxcmd.h>
110
111 static int      acx_probe(device_t);
112 static int      acx_attach(device_t);
113 static int      acx_detach(device_t);
114 static int      acx_shutdown(device_t);
115
116 static void     acx_init(void *);
117 static void     acx_start(struct ifnet *);
118 static int      acx_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
119 static void     acx_watchdog(struct ifnet *);
120
121 static void     acx_intr(void *);
122 static void     acx_txeof(struct acx_softc *);
123 static void     acx_txerr(struct acx_softc *, uint8_t);
124 static void     acx_rxeof(struct acx_softc *);
125 static void     acx_disable_intr(struct acx_softc *);
126 static void     acx_enable_intr(struct acx_softc *);
127
128 static int      acx_reset(struct acx_softc *);
129 static int      acx_stop(struct acx_softc *);
130 static void     acx_init_info_reg(struct acx_softc *);
131 static int      acx_config(struct acx_softc *);
132 static int      acx_read_config(struct acx_softc *, struct acx_config *);
133 static int      acx_write_config(struct acx_softc *, struct acx_config *);
134 static int      acx_rx_config(struct acx_softc *, int);
135 static int      acx_set_crypt_keys(struct acx_softc *);
136
137 static int      acx_dma_alloc(struct acx_softc *);
138 static void     acx_dma_free(struct acx_softc *);
139 static int      acx_init_tx_ring(struct acx_softc *);
140 static int      acx_init_rx_ring(struct acx_softc *);
141 static int      acx_newbuf(struct acx_softc *, struct acx_rxbuf *, int);
142 static int      acx_encap(struct acx_softc *, struct acx_txbuf *,
143                           struct mbuf *, struct ieee80211_node *);
144
145 static int      acx_set_null_tmplt(struct acx_softc *);
146 static int      acx_set_probe_req_tmplt(struct acx_softc *, const char *, int);
147 static int      acx_set_probe_resp_tmplt(struct acx_softc *,
148                                          struct ieee80211_node *);
149 static int      acx_set_beacon_tmplt(struct acx_softc *,
150                                      struct ieee80211_node *);
151
152 static int      acx_read_eeprom(struct acx_softc *, uint32_t, uint8_t *);
153 static int      acx_read_phyreg(struct acx_softc *, uint32_t, uint8_t *);
154
155 static int      acx_alloc_firmware(struct acx_softc *);
156 static void     acx_free_firmware(struct acx_softc *);
157 static int      acx_setup_firmware(struct acx_softc *, struct fw_image *,
158                                    const uint8_t **, int *);
159 static int      acx_load_firmware(struct acx_softc *, uint32_t,
160                                   const uint8_t *, int);
161 static int      acx_load_radio_firmware(struct acx_softc *, const uint8_t *,
162                                         uint32_t);
163 static int      acx_load_base_firmware(struct acx_softc *, const uint8_t *,
164                                        uint32_t);
165
166 static void     acx_next_scan(void *);
167 static int      acx_set_chan(struct acx_softc *, struct ieee80211_channel *);
168
169 static int      acx_media_change(struct ifnet *);
170 static int      acx_newstate(struct ieee80211com *, enum ieee80211_state, int);
171
172 static int      acx_sysctl_msdu_lifetime(SYSCTL_HANDLER_ARGS);
173 static int      acx_sysctl_free_firmware(SYSCTL_HANDLER_ARGS);
174
175 const struct ieee80211_rateset  acx_rates_11b =
176         { 5, { 2, 4, 11, 22, 44 } };
177 const struct ieee80211_rateset  acx_rates_11g =
178         { 13, { 2, 4, 11, 22, 44, 12, 18, 24, 36, 48, 72, 96, 108 } };
179
180 static const struct acx_device {
181         uint16_t        vid;
182         uint16_t        did;
183         void            (*set_param)(device_t);
184         const char      *desc;
185 } acx_devices[] = {
186         { PCI_VENDOR_TI, PCI_PRODUCT_TI_ACX100A, acx100_set_param,
187           "Texas Instruments TNETW1100A Wireless Adapter" },
188         { PCI_VENDOR_TI, PCI_PRODUCT_TI_ACX100B, acx100_set_param,
189           "Texas Instruments TNETW1100B Wireless Adapter" },
190         { PCI_VENDOR_TI, PCI_PRODUCT_TI_ACX111, acx111_set_param,
191           "Texas Instruments TNETW1130 Wireless Adapter" },
192         { 0, 0, NULL, NULL }
193 };
194
195 static device_method_t acx_methods[] = {
196         DEVMETHOD(device_probe,         acx_probe),
197         DEVMETHOD(device_attach,        acx_attach),
198         DEVMETHOD(device_detach,        acx_detach),
199         DEVMETHOD(device_shutdown,      acx_shutdown),
200 #if 0
201         DEVMETHOD(device_suspend,       acx_suspend),
202         DEVMETHOD(device_resume,        acx_resume),
203 #endif
204         { 0, 0 }
205 };
206
207 static driver_t acx_driver = {
208         "acx",
209         acx_methods,
210         sizeof(struct acx_softc)
211 };
212
213 static devclass_t acx_devclass;
214
215 DRIVER_MODULE(acx, pci, acx_driver, acx_devclass, 0, 0);
216 DRIVER_MODULE(acx, cardbus, acx_driver, acx_devclass, 0, 0);
217
218 MODULE_DEPEND(acx, wlan, 1, 1, 1);
219 MODULE_DEPEND(acx, wlan_ratectl_onoe, 1, 1, 1);
220 MODULE_DEPEND(acx, wlan_ratectl_amrr, 1, 1, 1);
221 MODULE_DEPEND(acx, pci, 1, 1, 1);
222 MODULE_DEPEND(acx, cardbus, 1, 1, 1);
223
224 static __inline int
225 acx_get_rssi(struct acx_softc *sc, uint8_t raw)
226 {
227         int rssi;
228
229         rssi = ((sc->chip_rssi_corr / 2) + (raw * 5)) / sc->chip_rssi_corr;
230         return rssi > 100 ? 100 : rssi;
231 }
232
233 static int
234 acx_probe(device_t dev)
235 {
236         const struct acx_device *a;
237         uint16_t did, vid;
238
239         vid = pci_get_vendor(dev);
240         did = pci_get_device(dev);
241         for (a = acx_devices; a->desc != NULL; ++a) {
242                 if (vid == a->vid && did == a->did) {
243                         a->set_param(dev);
244                         device_set_desc(dev, a->desc);
245                         return 0;
246                 }
247         }
248         return ENXIO;
249 }
250
251 static int
252 acx_attach(device_t dev)
253 {
254         struct acx_softc *sc;
255         struct ifnet *ifp;
256         struct ieee80211com *ic;
257         int i, error;
258
259         sc = device_get_softc(dev);
260         ic = &sc->sc_ic;
261         ifp = &ic->ic_if;
262
263         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
264
265 #ifndef BURN_BRIDGES
266         if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
267                 uint32_t mem1, mem2, irq;
268
269                 mem1 = pci_read_config(dev, sc->chip_mem1_rid, 4);
270                 mem2 = pci_read_config(dev, sc->chip_mem2_rid, 4);
271                 irq = pci_read_config(dev, PCIR_INTLINE, 4);
272
273                 device_printf(dev, "chip is in D%d power mode "
274                     "-- setting to D0\n", pci_get_powerstate(dev));
275
276                 pci_set_powerstate(dev, PCI_POWERSTATE_D0);
277
278                 pci_write_config(dev, sc->chip_mem1_rid, mem1, 4);
279                 pci_write_config(dev, sc->chip_mem2_rid, mem2, 4);
280                 pci_write_config(dev, PCIR_INTLINE, irq, 4);
281         }
282 #endif  /* !BURN_BRIDGE */
283
284         /* Enable bus mastering */
285         pci_enable_busmaster(dev); 
286
287         /* Allocate IO memory 1 */
288         sc->sc_mem1_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
289                                                  &sc->chip_mem1_rid,
290                                                  RF_ACTIVE);
291         if (sc->sc_mem1_res == NULL) {
292                 error = ENXIO;
293                 device_printf(dev, "can't allocate IO mem1\n");
294                 goto fail;
295         }
296         sc->sc_mem1_bt = rman_get_bustag(sc->sc_mem1_res);
297         sc->sc_mem1_bh = rman_get_bushandle(sc->sc_mem1_res);
298
299         /* Allocate IO memory 2 */
300         sc->sc_mem2_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
301                                                  &sc->chip_mem2_rid,
302                                                  RF_ACTIVE);
303         if (sc->sc_mem2_res == NULL) {
304                 error = ENXIO;
305                 device_printf(dev, "can't allocate IO mem2\n");
306                 goto fail;
307         }
308         sc->sc_mem2_bt = rman_get_bustag(sc->sc_mem2_res);
309         sc->sc_mem2_bh = rman_get_bushandle(sc->sc_mem2_res);
310
311         /* Allocate irq */
312         sc->sc_irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ,
313                                                 &sc->sc_irq_rid,
314                                                 RF_SHAREABLE | RF_ACTIVE);
315         if (sc->sc_irq_res == NULL) {
316                 error = ENXIO;
317                 device_printf(dev, "can't allocate intr\n");
318                 goto fail;
319         }
320
321         /* Initilize channel scanning timer */
322         callout_init(&sc->sc_scan_timer);
323
324         /* Allocate busdma stuffs */
325         error = acx_dma_alloc(sc);
326         if (error)
327                 goto fail;
328
329         /* Reset Hardware */
330         error = acx_reset(sc);
331         if (error)
332                 goto fail;
333
334         /* Disable interrupts before firmware is loaded */
335         acx_disable_intr(sc);
336
337         /* Get radio type and form factor */
338 #define EEINFO_RETRY_MAX        50
339         for (i = 0; i < EEINFO_RETRY_MAX; ++i) {
340                 uint16_t ee_info;
341
342                 ee_info = CSR_READ_2(sc, ACXREG_EEPROM_INFO);
343                 if (ACX_EEINFO_HAS_RADIO_TYPE(ee_info)) {
344                         sc->sc_form_factor = ACX_EEINFO_FORM_FACTOR(ee_info);
345                         sc->sc_radio_type = ACX_EEINFO_RADIO_TYPE(ee_info);
346                         break;
347                 }
348                 DELAY(10000);
349         }
350         if (i == EEINFO_RETRY_MAX) {
351                 error = ENXIO;
352                 goto fail;
353         }
354 #undef EEINFO_RETRY_MAX
355
356         DPRINTF((&sc->sc_ic.ic_if, "radio type %02x\n", sc->sc_radio_type));
357
358 #ifdef DUMP_EEPROM
359         for (i = 0; i < 0x40; ++i) {
360                 uint8_t val;
361
362                 error = acx_read_eeprom(sc, i, &val);
363                 if (i % 10 == 0)
364                         kprintf("\n");
365                 kprintf("%02x ", val);
366         }
367         kprintf("\n");
368 #endif  /* DUMP_EEPROM */
369
370         /* Get EEPROM version */
371         error = acx_read_eeprom(sc, ACX_EE_VERSION_OFS, &sc->sc_eeprom_ver);
372         if (error)
373                 goto fail;
374         DPRINTF((&sc->sc_ic.ic_if, "EEPROM version %u\n", sc->sc_eeprom_ver));
375
376         /*
377          * Initialize device sysctl before ieee80211_ifattach()
378          */
379         sc->sc_long_retry_limit = 4;
380         sc->sc_msdu_lifetime = 4096;
381         sc->sc_scan_dwell = 200;        /* 200 milliseconds */
382
383         sysctl_ctx_init(&sc->sc_sysctl_ctx);
384         sc->sc_sysctl_tree = SYSCTL_ADD_NODE(&sc->sc_sysctl_ctx,
385                                              SYSCTL_STATIC_CHILDREN(_hw),
386                                              OID_AUTO,
387                                              device_get_nameunit(dev),
388                                              CTLFLAG_RD, 0, "");
389         if (sc->sc_sysctl_tree == NULL) {
390                 device_printf(dev, "can't add sysctl node\n");
391                 error = ENXIO;
392                 goto fail;
393         }
394         SYSCTL_ADD_PROC(&sc->sc_sysctl_ctx,
395                         SYSCTL_CHILDREN(sc->sc_sysctl_tree),
396                         OID_AUTO, "msdu_lifetime",
397                         CTLTYPE_INT | CTLFLAG_RW,
398                         sc, 0, acx_sysctl_msdu_lifetime, "I",
399                         "MSDU life time");
400         SYSCTL_ADD_INT(&sc->sc_sysctl_ctx,
401                        SYSCTL_CHILDREN(sc->sc_sysctl_tree), OID_AUTO,
402                        "long_retry_limit", CTLFLAG_RW,
403                        &sc->sc_long_retry_limit, 0, "Long retry limit");
404         SYSCTL_ADD_INT(&sc->sc_sysctl_ctx,
405                        SYSCTL_CHILDREN(sc->sc_sysctl_tree), OID_AUTO,
406                        "scan_dwell", CTLFLAG_RW,
407                        &sc->sc_scan_dwell, 0, "Scan channel dwell time (ms)");
408
409         /*
410          * Nodes for firmware operation
411          */
412         SYSCTL_ADD_INT(&sc->sc_sysctl_ctx,
413                        SYSCTL_CHILDREN(sc->sc_sysctl_tree), OID_AUTO,
414                        "combined_radio_fw", CTLFLAG_RW,
415                        &sc->sc_firmware.combined_radio_fw, 0,
416                        "Radio and base firmwares are combined");
417         SYSCTL_ADD_PROC(&sc->sc_sysctl_ctx,
418                         SYSCTL_CHILDREN(sc->sc_sysctl_tree),
419                         OID_AUTO, "free_fw",
420                         CTLTYPE_INT | CTLFLAG_RW,
421                         sc, 0, acx_sysctl_free_firmware, "I",
422                         "Free firmware");
423
424         /*
425          * Nodes for statistics
426          */
427         SYSCTL_ADD_UQUAD(&sc->sc_sysctl_ctx,
428                          SYSCTL_CHILDREN(sc->sc_sysctl_tree), OID_AUTO,
429                          "frag_error", CTLFLAG_RW, &sc->sc_stats.err_oth_frag,
430                          0, "Fragment errors");
431         SYSCTL_ADD_UQUAD(&sc->sc_sysctl_ctx,
432                          SYSCTL_CHILDREN(sc->sc_sysctl_tree), OID_AUTO,
433                          "tx_abort", CTLFLAG_RW, &sc->sc_stats.err_abort,
434                          0, "TX abortions");
435         SYSCTL_ADD_UQUAD(&sc->sc_sysctl_ctx,
436                          SYSCTL_CHILDREN(sc->sc_sysctl_tree), OID_AUTO,
437                          "tx_invalid", CTLFLAG_RW, &sc->sc_stats.err_param,
438                          0, "Invalid TX param in TX descriptor");
439         SYSCTL_ADD_UQUAD(&sc->sc_sysctl_ctx,
440                          SYSCTL_CHILDREN(sc->sc_sysctl_tree), OID_AUTO,
441                          "no_wepkey", CTLFLAG_RW, &sc->sc_stats.err_no_wepkey,
442                          0, "No WEP key exists");
443         SYSCTL_ADD_UQUAD(&sc->sc_sysctl_ctx,
444                          SYSCTL_CHILDREN(sc->sc_sysctl_tree), OID_AUTO,
445                          "msdu_timeout", CTLFLAG_RW,
446                          &sc->sc_stats.err_msdu_timeout,
447                          0, "MSDU timeouts");
448         SYSCTL_ADD_UQUAD(&sc->sc_sysctl_ctx,
449                          SYSCTL_CHILDREN(sc->sc_sysctl_tree), OID_AUTO,
450                          "ex_txretry", CTLFLAG_RW, &sc->sc_stats.err_ex_retry,
451                          0, "Excessive TX retries");
452         SYSCTL_ADD_UQUAD(&sc->sc_sysctl_ctx,
453                          SYSCTL_CHILDREN(sc->sc_sysctl_tree), OID_AUTO,
454                          "buf_oflow", CTLFLAG_RW, &sc->sc_stats.err_buf_oflow,
455                          0, "Buffer overflows");
456         SYSCTL_ADD_UQUAD(&sc->sc_sysctl_ctx,
457                          SYSCTL_CHILDREN(sc->sc_sysctl_tree), OID_AUTO,
458                          "dma_error", CTLFLAG_RW, &sc->sc_stats.err_dma,
459                          0, "DMA errors");
460         SYSCTL_ADD_UQUAD(&sc->sc_sysctl_ctx,
461                          SYSCTL_CHILDREN(sc->sc_sysctl_tree), OID_AUTO,
462                          "unkn_error", CTLFLAG_RW, &sc->sc_stats.err_unkn,
463                          0, "Unknown errors");
464
465         ifp->if_softc = sc;
466         ifp->if_init = acx_init;
467         ifp->if_ioctl = acx_ioctl;
468         ifp->if_start = acx_start;
469         ifp->if_watchdog = acx_watchdog;
470         ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
471         ifq_set_maxlen(&ifp->if_snd, IFQ_MAXLEN);
472         ifq_set_ready(&ifp->if_snd);
473
474         /* Set channels */
475         for (i = 1; i <= 14; ++i) {
476                 ic->ic_channels[i].ic_freq =
477                         ieee80211_ieee2mhz(i, IEEE80211_CHAN_2GHZ);
478                 ic->ic_channels[i].ic_flags = sc->chip_chan_flags;
479         }
480
481         ic->ic_opmode = IEEE80211_M_STA;
482         ic->ic_state = IEEE80211_S_INIT;
483
484         /*
485          * NOTE: Don't overwrite ic_caps set by chip specific code
486          */
487         ic->ic_caps |= IEEE80211_C_WEP |        /* WEP */
488                        IEEE80211_C_HOSTAP |     /* HostAP mode */
489                        IEEE80211_C_MONITOR |    /* Monitor mode */
490                        IEEE80211_C_IBSS |       /* IBSS modes */
491                        IEEE80211_C_SHPREAMBLE;  /* Short preamble */
492         ic->ic_caps_ext = IEEE80211_CEXT_PBCC;  /* PBCC modulation */
493
494         /* Get station id */
495         for (i = 0; i < IEEE80211_ADDR_LEN; ++i) {
496                 error = acx_read_eeprom(sc, sc->chip_ee_eaddr_ofs - i,
497                                         &ic->ic_myaddr[i]);
498         }
499
500         ieee80211_ifattach(ic);
501
502         /* Enable software beacon missing */
503         ic->ic_flags_ext |= IEEE80211_FEXT_SWBMISS;
504
505         /* Override newstate */
506         sc->sc_newstate = ic->ic_newstate;
507         ic->ic_newstate = acx_newstate;
508
509         ieee80211_media_init(ic, acx_media_change, ieee80211_media_status);
510
511         /*
512          * Radio tap attaching
513          */
514         bpfattach_dlt(ifp, DLT_IEEE802_11_RADIO,
515                       sizeof(struct ieee80211_frame) + sizeof(sc->sc_tx_th),
516                       &sc->sc_drvbpf);
517
518         sc->sc_tx_th_len = roundup(sizeof(sc->sc_tx_th), sizeof(uint32_t));
519         sc->sc_tx_th.wt_ihdr.it_len = htole16(sc->sc_tx_th_len);
520         sc->sc_tx_th.wt_ihdr.it_present = htole32(ACX_TX_RADIOTAP_PRESENT);
521
522         sc->sc_rx_th_len = roundup(sizeof(sc->sc_rx_th), sizeof(uint32_t));
523         sc->sc_rx_th.wr_ihdr.it_len = htole16(sc->sc_rx_th_len);
524         sc->sc_rx_th.wr_ihdr.it_present = htole32(ACX_RX_RADIOTAP_PRESENT);
525
526         error = bus_setup_intr(dev, sc->sc_irq_res, INTR_MPSAFE, acx_intr, sc,
527                                &sc->sc_irq_handle, ifp->if_serializer);
528         if (error) {
529                 device_printf(dev, "can't set up interrupt\n");
530                 bpfdetach(ifp);
531                 ieee80211_ifdetach(ic);
532                 goto fail;
533         }
534
535         if (bootverbose)
536                 ieee80211_announce(ic);
537
538         return 0;
539 fail:
540         acx_detach(dev);
541         return error;
542 }
543
544 static int
545 acx_detach(device_t dev)
546 {
547         struct acx_softc *sc = device_get_softc(dev);
548
549         if (device_is_attached(dev)) {
550                 struct ieee80211com *ic = &sc->sc_ic;
551                 struct ifnet *ifp = &ic->ic_if;
552
553                 lwkt_serialize_enter(ifp->if_serializer);
554
555                 acx_stop(sc);
556                 acx_free_firmware(sc);
557                 bus_teardown_intr(dev, sc->sc_irq_res, sc->sc_irq_handle);
558
559                 lwkt_serialize_exit(ifp->if_serializer);
560
561                 bpfdetach(ifp);
562                 ieee80211_ifdetach(ic);
563         }
564
565         if (sc->sc_sysctl_tree != NULL)
566                 sysctl_ctx_free(&sc->sc_sysctl_ctx);
567
568         if (sc->sc_irq_res != NULL) {
569                 bus_release_resource(dev, SYS_RES_IRQ, sc->sc_irq_rid,
570                                      sc->sc_irq_res);
571         }
572         if (sc->sc_mem1_res != NULL) {
573                 bus_release_resource(dev, SYS_RES_MEMORY, sc->chip_mem1_rid,
574                                      sc->sc_mem1_res);
575         }
576         if (sc->sc_mem2_res != NULL) {
577                 bus_release_resource(dev, SYS_RES_MEMORY, sc->chip_mem2_rid,
578                                      sc->sc_mem2_res);
579         }
580
581         acx_dma_free(sc);
582         return 0;
583 }
584
585 static int
586 acx_shutdown(device_t dev)
587 {
588         struct acx_softc *sc = device_get_softc(dev);
589
590         lwkt_serialize_enter(sc->sc_ic.ic_if.if_serializer);
591         acx_stop(sc);
592         lwkt_serialize_exit(sc->sc_ic.ic_if.if_serializer);
593         return 0;
594 }
595
596 static void
597 acx_init(void *arg)
598 {
599         struct acx_softc *sc = arg;
600         struct ieee80211com *ic = &sc->sc_ic;
601         struct ifnet *ifp = &ic->ic_if;
602         struct acx_firmware *fw = &sc->sc_firmware;
603         int error;
604
605         error = acx_stop(sc);
606         if (error)
607                 return;
608
609         error = acx_alloc_firmware(sc);
610         if (error)
611                 return;
612
613         error = acx_init_tx_ring(sc);
614         if (error) {
615                 if_printf(ifp, "can't initialize TX ring\n");
616                 goto back;
617         }
618
619         error = acx_init_rx_ring(sc);
620         if (error) {
621                 if_printf(ifp, "can't initialize RX ring\n");
622                 goto back;
623         }
624
625         error = acx_load_base_firmware(sc, fw->base_fw, fw->base_fw_len);
626         if (error)
627                 goto back;
628
629         /*
630          * Initialize command and information registers
631          * NOTE: This should be done after base firmware is loaded
632          */
633         acx_init_cmd_reg(sc);
634         acx_init_info_reg(sc);
635
636         sc->sc_flags |= ACX_FLAG_FW_LOADED;
637
638 #if 0
639         if (sc->chip_post_basefw != NULL) {
640                 error = sc->chip_post_basefw(sc);
641                 if (error)
642                         goto back;
643         }
644 #endif
645
646         if (fw->radio_fw != NULL) {
647                 error = acx_load_radio_firmware(sc, fw->radio_fw,
648                                                 fw->radio_fw_len);
649                 if (error)
650                         goto back;
651         }
652
653         error = sc->chip_init(sc);
654         if (error)
655                 goto back;
656
657         /* Get and set device various configuration */
658         error = acx_config(sc);
659         if (error)
660                 goto back;
661
662         /* Setup crypto stuffs */
663         if (sc->sc_ic.ic_flags & IEEE80211_F_PRIVACY) {
664                 error = acx_set_crypt_keys(sc);
665                 if (error)
666                         goto back;
667                 sc->sc_ic.ic_flags &= ~IEEE80211_F_DROPUNENC;
668         }
669
670         /* Turn on power led */
671         CSR_CLRB_2(sc, ACXREG_GPIO_OUT, sc->chip_gpio_pled);
672
673         acx_enable_intr(sc);
674
675         ifp->if_flags |= IFF_RUNNING;
676         ifp->if_flags &= ~IFF_OACTIVE;
677
678         if (ic->ic_opmode != IEEE80211_M_MONITOR) {
679                 if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
680                         ieee80211_new_state(&sc->sc_ic, IEEE80211_S_SCAN, -1);
681         } else {
682                 ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
683         }
684 back:
685         if (error)
686                 acx_stop(sc);
687 }
688
689 static void
690 acx_init_info_reg(struct acx_softc *sc)
691 {
692         sc->sc_info = CSR_READ_4(sc, ACXREG_INFO_REG_OFFSET);
693         sc->sc_info_param = sc->sc_info + ACX_INFO_REG_SIZE;
694 }
695
696 static int
697 acx_set_crypt_keys(struct acx_softc *sc)
698 {
699         struct ieee80211com *ic = &sc->sc_ic;
700         struct acx_conf_wep_txkey wep_txkey;
701         int i, error, got_wk = 0;
702
703         for (i = 0; i < IEEE80211_WEP_NKID; ++i) {
704                 struct ieee80211_key *wk = &ic->ic_nw_keys[i];
705
706                 if (wk->wk_keylen == 0)
707                         continue;
708
709                 if (sc->chip_hw_crypt) {
710                         error = sc->chip_set_wepkey(sc, wk, i);
711                         if (error)
712                                 return error;
713                         got_wk = 1;
714                 } else if (wk->wk_flags & IEEE80211_KEY_XMIT) {
715                         wk->wk_flags |= IEEE80211_KEY_SWCRYPT;
716                 }
717         }
718
719         if (!got_wk || sc->chip_hw_crypt ||
720             ic->ic_def_txkey == IEEE80211_KEYIX_NONE)
721                 return 0;
722
723         /* Set current WEP key index */
724         wep_txkey.wep_txkey = ic->ic_def_txkey;
725         if (acx_set_wep_txkey_conf(sc, &wep_txkey) != 0) {
726                 if_printf(&ic->ic_if, "set WEP txkey failed\n");
727                 return ENXIO;
728         }
729         return 0;
730 }
731
732 static void
733 acx_next_scan(void *arg)
734 {
735         struct acx_softc *sc = arg;
736         struct ieee80211com *ic = &sc->sc_ic;
737         struct ifnet *ifp = &ic->ic_if;
738
739         lwkt_serialize_enter(ifp->if_serializer);
740
741         if (ic->ic_state == IEEE80211_S_SCAN)
742                 ieee80211_next_scan(ic);
743
744         lwkt_serialize_exit(ifp->if_serializer);
745 }
746
747 static int
748 acx_stop(struct acx_softc *sc)
749 {
750         struct ieee80211com *ic = &sc->sc_ic;
751         struct ifnet *ifp = &ic->ic_if;
752         struct acx_buf_data *bd = &sc->sc_buf_data;
753         struct acx_ring_data *rd = &sc->sc_ring_data;
754         int i, error;
755
756         ASSERT_SERIALIZED(ifp->if_serializer);
757
758         ieee80211_new_state(&sc->sc_ic, IEEE80211_S_INIT, -1);
759
760         sc->sc_firmware_ver = 0;
761         sc->sc_hardware_id = 0;
762
763         /* Reset hardware */
764         error = acx_reset(sc);
765         if (error)
766                 return error;
767
768         /* Firmware no longer functions after hardware reset */
769         sc->sc_flags &= ~ACX_FLAG_FW_LOADED;
770
771         acx_disable_intr(sc);
772
773         /* Stop backgroud scanning */
774         callout_stop(&sc->sc_scan_timer);
775
776         /* Turn off power led */
777         CSR_SETB_2(sc, ACXREG_GPIO_OUT, sc->chip_gpio_pled);
778
779         /* Free TX mbuf */
780         for (i = 0; i < ACX_TX_DESC_CNT; ++i) {
781                 struct acx_txbuf *buf;
782
783                 buf = &bd->tx_buf[i];
784
785                 if (buf->tb_mbuf != NULL) {
786                         bus_dmamap_unload(bd->mbuf_dma_tag,
787                                           buf->tb_mbuf_dmamap);
788                         m_freem(buf->tb_mbuf);
789                         buf->tb_mbuf = NULL;
790                 }
791
792                 if (buf->tb_node != NULL)
793                         ieee80211_free_node(buf->tb_node);
794                 buf->tb_node = NULL;
795         }
796
797         /* Clear TX host descriptors */
798         bzero(rd->tx_ring, ACX_TX_RING_SIZE);
799
800         /* Free RX mbuf */
801         for (i = 0; i < ACX_RX_DESC_CNT; ++i) {
802                 if (bd->rx_buf[i].rb_mbuf != NULL) {
803                         bus_dmamap_unload(bd->mbuf_dma_tag,
804                                           bd->rx_buf[i].rb_mbuf_dmamap);
805                         m_freem(bd->rx_buf[i].rb_mbuf);
806                         bd->rx_buf[i].rb_mbuf = NULL;
807                 }
808         }
809
810         /* Clear RX host descriptors */
811         bzero(rd->rx_ring, ACX_RX_RING_SIZE);
812
813         sc->sc_tx_timer = 0;
814         ifp->if_timer = 0;
815         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
816
817         return 0;
818 }
819
820 static int
821 acx_config(struct acx_softc *sc)
822 {
823         struct acx_config conf;
824         int error;
825
826         error = acx_read_config(sc, &conf);
827         if (error)
828                 return error;
829
830         error = acx_write_config(sc, &conf);
831         if (error)
832                 return error;
833
834         error = acx_rx_config(sc, sc->sc_flags & ACX_FLAG_PROMISC);
835         if (error)
836                 return error;
837
838         if (acx_set_probe_req_tmplt(sc, "", 0) != 0) {
839                 if_printf(&sc->sc_ic.ic_if, "can't set probe req template "
840                           "(empty ssid)\n");
841                 return ENXIO;
842         }
843
844         /* XXX for PM?? */
845         if (acx_set_null_tmplt(sc) != 0) {
846                 if_printf(&sc->sc_ic.ic_if, "can't set null data template\n");
847                 return ENXIO;
848         }
849         return 0;
850 }
851
852 static int
853 acx_read_config(struct acx_softc *sc, struct acx_config *conf)
854 {
855         struct acx_conf_eaddr addr;
856         struct acx_conf_regdom reg_dom;
857         struct acx_conf_antenna ant;
858         struct acx_conf_fwrev fw_rev;
859         uint32_t fw_rev_no;
860         uint8_t sen;
861         int i, error;
862
863         /* Get station id */
864         if (acx_get_eaddr_conf(sc, &addr) != 0) {
865                 if_printf(&sc->sc_ic.ic_if, "can't get station id\n");
866                 return ENXIO;
867         }
868
869         /*
870          * Get and print station id in case that EEPROM station id's
871          * offset is not correct
872          */
873         for (i = 0; i < IEEE80211_ADDR_LEN; ++i)
874                 conf->eaddr[IEEE80211_ADDR_LEN - 1 - i] = addr.eaddr[i];
875         if_printf(&sc->sc_ic.ic_if, "MAC address (from firmware): %6D\n",
876                   conf->eaddr, ":");
877
878         /* Get region domain */
879         if (acx_get_regdom_conf(sc, &reg_dom) != 0) {
880                 if_printf(&sc->sc_ic.ic_if, "can't get region domain\n");
881                 return ENXIO;
882         }
883         conf->regdom = reg_dom.regdom;
884         DPRINTF((&sc->sc_ic.ic_if, "regdom %02x\n", reg_dom.regdom));
885
886         /* Get antenna */
887         if (acx_get_antenna_conf(sc, &ant) != 0) {
888                 if_printf(&sc->sc_ic.ic_if, "can't get antenna\n");
889                 return ENXIO;
890         }
891         conf->antenna = ant.antenna;
892         DPRINTF((&sc->sc_ic.ic_if, "antenna %02x\n", ant.antenna));
893
894         /* Get sensitivity XXX not used */
895         if (sc->sc_radio_type == ACX_RADIO_TYPE_MAXIM ||
896             sc->sc_radio_type == ACX_RADIO_TYPE_RFMD ||
897             sc->sc_radio_type == ACX_RADIO_TYPE_RALINK) {
898                 error = acx_read_phyreg(sc, ACXRV_PHYREG_SENSITIVITY, &sen);
899                 if (error) {
900                         if_printf(&sc->sc_ic.ic_if, "can't get sensitivity\n");
901                         return error;
902                 }
903         } else {
904                 sen = 0;
905         }
906         DPRINTF((&sc->sc_ic.ic_if, "sensitivity %02x\n", sen));
907
908         /* Get firmware revision */
909         if (acx_get_fwrev_conf(sc, &fw_rev) != 0) {
910                 if_printf(&sc->sc_ic.ic_if, "can't get firmware revision\n");
911                 return ENXIO;
912         }
913
914         if (strncmp(fw_rev.fw_rev, "Rev ", 4) != 0) {
915                 if_printf(&sc->sc_ic.ic_if, "strange revision string -- %s\n",
916                           fw_rev.fw_rev);
917                 fw_rev_no = 0x01090407;
918         } else {
919                 char *s, *endp;
920
921                 /*
922                  *  01234
923                  * "Rev xx.xx.xx.xx"
924                  *      ^ Start from here
925                  */
926                 s = &fw_rev.fw_rev[4];
927                 fw_rev_no = 0;
928                 for (i = 0; i < 4; ++i) {
929                         uint8_t val;
930
931                         val = strtoul(s, &endp, 16);
932                         fw_rev_no |= val << ((3 - i) * 8);
933
934                         if (*endp == '\0')
935                                 break;
936                         else
937                                 s = ++endp;
938                 }
939         }
940         sc->sc_firmware_ver = fw_rev_no;
941         sc->sc_hardware_id = le32toh(fw_rev.hw_id);
942         DPRINTF((&sc->sc_ic.ic_if, "fw rev %08x, hw id %08x\n",
943                  sc->sc_firmware_ver, sc->sc_hardware_id));
944
945         if (sc->chip_read_config != NULL) {
946                 error = sc->chip_read_config(sc, conf);
947                 if (error)
948                         return error;
949         }
950         return 0;
951 }
952
953 static int
954 acx_write_config(struct acx_softc *sc, struct acx_config *conf)
955 {
956         struct acx_conf_nretry_short sretry;
957         struct acx_conf_nretry_long lretry;
958         struct acx_conf_msdu_lifetime msdu_lifetime;
959         struct acx_conf_rate_fallback rate_fb;
960         struct acx_conf_antenna ant;
961         struct acx_conf_regdom reg_dom;
962         int error;
963
964         /* Set number of long/short retry */
965         KKASSERT(sc->chip_short_retry_limit > 0);
966         sretry.nretry = sc->chip_short_retry_limit;
967         if (acx_set_nretry_short_conf(sc, &sretry) != 0) {
968                 if_printf(&sc->sc_ic.ic_if, "can't set short retry limit\n");
969                 return ENXIO;
970         }
971
972         lretry.nretry = sc->sc_long_retry_limit;
973         if (acx_set_nretry_long_conf(sc, &lretry) != 0) {
974                 if_printf(&sc->sc_ic.ic_if, "can't set long retry limit\n");
975                 return ENXIO;
976         }
977
978         /* Set MSDU lifetime */
979         msdu_lifetime.lifetime = htole32(sc->sc_msdu_lifetime);
980         if (acx_set_msdu_lifetime_conf(sc, &msdu_lifetime) != 0) {
981                 if_printf(&sc->sc_ic.ic_if, "can't set MSDU lifetime\n");
982                 return ENXIO;
983         }
984
985         /* Enable rate fallback */
986         rate_fb.ratefb_enable = 1;
987         if (acx_set_rate_fallback_conf(sc, &rate_fb) != 0) {
988                 if_printf(&sc->sc_ic.ic_if, "can't enable rate fallback\n");
989                 return ENXIO;
990         }
991
992         /* Set antenna */
993         ant.antenna = conf->antenna;
994         if (acx_set_antenna_conf(sc, &ant) != 0) {
995                 if_printf(&sc->sc_ic.ic_if, "can't set antenna\n");
996                 return ENXIO;
997         }
998
999         /* Set region domain */
1000         reg_dom.regdom = conf->regdom;
1001         if (acx_set_regdom_conf(sc, &reg_dom) != 0) {
1002                 if_printf(&sc->sc_ic.ic_if, "can't set region domain\n");
1003                 return ENXIO;
1004         }
1005
1006         if (sc->chip_write_config != NULL) {
1007                 error = sc->chip_write_config(sc, conf);
1008                 if (error)
1009                         return error;
1010         }
1011
1012         return 0;
1013 }
1014
1015 static int
1016 acx_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data, struct ucred *cr)
1017 {
1018         struct acx_softc *sc = ifp->if_softc;
1019         struct ieee80211com *ic = &sc->sc_ic;
1020         struct ifreq *req;
1021         int error;
1022
1023         error = 0;
1024         req = (struct ifreq *)data;
1025
1026         switch (cmd) {
1027         case SIOCSIFFLAGS:
1028                 if (ifp->if_flags & IFF_UP) {
1029                         if ((ifp->if_flags & IFF_RUNNING)) {
1030                                 int promisc = -1;
1031
1032                                 if ((ifp->if_flags & IFF_PROMISC) &&
1033                                     (sc->sc_flags & ACX_FLAG_PROMISC) == 0)
1034                                         promisc = 1;
1035                                 else if ((ifp->if_flags & IFF_PROMISC) == 0 &&
1036                                          (sc->sc_flags & ACX_FLAG_PROMISC))
1037                                         promisc = 0;
1038
1039                                 /*
1040                                  * Promisc mode is always enabled when
1041                                  * operation mode is Monitor.
1042                                  */
1043                                 if (ic->ic_opmode != IEEE80211_M_MONITOR &&
1044                                     promisc >= 0)
1045                                         error = acx_rx_config(sc, promisc);
1046                         } else {
1047                                 acx_init(sc);
1048                         }
1049                 } else {
1050                         if (ifp->if_flags & IFF_RUNNING)
1051                                 acx_stop(sc);
1052                 }
1053
1054                 if (ifp->if_flags & IFF_PROMISC)
1055                         sc->sc_flags |= ACX_FLAG_PROMISC;
1056                 else
1057                         sc->sc_flags &= ~ACX_FLAG_PROMISC;
1058                 break;
1059         case SIOCADDMULTI:
1060         case SIOCDELMULTI:
1061                 /* TODO */
1062                 break;
1063         default:
1064                 error = ieee80211_ioctl(ic, cmd, data, cr);
1065                 break;
1066         }
1067
1068         if (error == ENETRESET) {
1069                 if ((ifp->if_flags & (IFF_RUNNING | IFF_UP)) ==
1070                     (IFF_RUNNING | IFF_UP))
1071                         acx_init(sc);
1072                 error = 0;
1073         }
1074         return error;
1075 }
1076
1077 static void
1078 acx_start(struct ifnet *ifp)
1079 {
1080         struct acx_softc *sc = ifp->if_softc;
1081         struct ieee80211com *ic = &sc->sc_ic;
1082         struct acx_buf_data *bd = &sc->sc_buf_data;
1083         struct acx_txbuf *buf;
1084         int trans, idx;
1085
1086         ASSERT_SERIALIZED(ifp->if_serializer);
1087
1088         if ((sc->sc_flags & ACX_FLAG_FW_LOADED) == 0 ||
1089             (ifp->if_flags & IFF_RUNNING) == 0 ||
1090             (ifp->if_flags & IFF_OACTIVE))
1091                 return;
1092
1093         /*
1094          * NOTE:
1095          * We can't start from a random position that TX descriptor
1096          * is free, since hardware will be confused by that.
1097          * We have to follow the order of the TX ring.
1098          */
1099         idx = bd->tx_free_start;
1100         trans = 0;
1101         for (buf = &bd->tx_buf[idx]; buf->tb_mbuf == NULL;
1102              buf = &bd->tx_buf[idx]) {
1103                 struct ieee80211_frame *f;
1104                 struct ieee80211_node *ni = NULL;
1105                 struct mbuf *m;
1106                 int mgmt_pkt = 0;
1107
1108                 if (!IF_QEMPTY(&ic->ic_mgtq)) {
1109                         IF_DEQUEUE(&ic->ic_mgtq, m);
1110
1111                         ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
1112                         m->m_pkthdr.rcvif = NULL;
1113
1114                         mgmt_pkt = 1;
1115
1116                         /*
1117                          * Don't transmit probe response firmware will
1118                          * do it for us.
1119                          */
1120                         f = mtod(m, struct ieee80211_frame *);
1121                         if ((f->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
1122                             IEEE80211_FC0_TYPE_MGT &&
1123                             (f->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
1124                             IEEE80211_FC0_SUBTYPE_PROBE_RESP) {
1125                                 if (ni != NULL)
1126                                         ieee80211_free_node(ni);
1127                                 m_freem(m);
1128                                 continue;
1129                         }
1130                 } else if (!ifq_is_empty(&ifp->if_snd)) {
1131                         struct ether_header *eh;
1132
1133                         if (ic->ic_state != IEEE80211_S_RUN)
1134                                 break;
1135
1136                         m = ifq_dequeue(&ifp->if_snd, NULL);
1137                         if (m == NULL)
1138                                 break;
1139
1140                         if (m->m_len < sizeof(struct ether_header)) {
1141                                 m = m_pullup(m, sizeof(struct ether_header));
1142                                 if (m == NULL) {
1143                                         ifp->if_oerrors++;
1144                                         continue;
1145                                 }
1146                         }
1147                         eh = mtod(m, struct ether_header *);
1148
1149                         ni = ieee80211_find_txnode(ic, eh->ether_dhost);
1150                         if (ni == NULL) {
1151                                 m_freem(m);
1152                                 ifp->if_oerrors++;
1153                                 continue;
1154                         }
1155
1156                         /* TODO power save */
1157
1158                         BPF_MTAP(ifp, m);
1159
1160                         m = ieee80211_encap(ic, m, ni);
1161                         if (m == NULL) {
1162                                 ieee80211_free_node(ni);
1163                                 ifp->if_oerrors++;
1164                                 continue;
1165                         }
1166                 } else {
1167                         break;
1168                 }
1169
1170                 if (ic->ic_rawbpf != NULL)
1171                         bpf_mtap(ic->ic_rawbpf, m);
1172
1173                 f = mtod(m, struct ieee80211_frame *);
1174                 if ((f->i_fc[1] & IEEE80211_FC1_WEP) && !sc->chip_hw_crypt) {
1175                         KASSERT(ni != NULL, ("TX node is NULL (WEP)\n"));
1176                         if (ieee80211_crypto_encap(ic, ni, m) == NULL) {
1177                                 ieee80211_free_node(ni);
1178                                 m_freem(m);
1179                                 ifp->if_oerrors++;
1180                                 continue;
1181                         }
1182                 }
1183
1184                 /*
1185                  * Since mgmt data are transmitted at fixed rate
1186                  * they will not be used to do rate control.
1187                  */
1188                 if (mgmt_pkt && ni != NULL) {
1189                         ieee80211_free_node(ni);
1190                         ni = NULL;
1191                 }
1192
1193                 if (acx_encap(sc, buf, m, ni) != 0) {
1194                         /*
1195                          * NOTE: `m' will be freed in acx_encap()
1196                          * if we reach here.
1197                          */
1198                         if (ni != NULL)
1199                                 ieee80211_free_node(ni);
1200                         ifp->if_oerrors++;
1201                         continue;
1202                 }
1203
1204                 /*
1205                  * NOTE:
1206                  * 1) `m' should not be touched after acx_encap()
1207                  * 2) `node' will be used to do TX rate control during
1208                  *    acx_txeof(), so it is not freed here.  acx_txeof()
1209                  *    will free it for us
1210                  */
1211
1212                 trans = 1;
1213                 bd->tx_used_count++;
1214                 idx = (idx + 1) % ACX_TX_DESC_CNT;
1215         }
1216         bd->tx_free_start = idx;
1217
1218         if (bd->tx_used_count == ACX_TX_DESC_CNT)
1219                 ifp->if_flags |= IFF_OACTIVE;
1220
1221         if (trans && sc->sc_tx_timer == 0)
1222                 sc->sc_tx_timer = 5;
1223         ifp->if_timer = 1;
1224 }
1225
1226 static void
1227 acx_watchdog(struct ifnet *ifp)
1228 {
1229         struct acx_softc *sc = ifp->if_softc;
1230
1231         ifp->if_timer = 0;
1232
1233         if ((ifp->if_flags & IFF_RUNNING) == 0)
1234                 return;
1235
1236         if (sc->sc_tx_timer) {
1237                 if (--sc->sc_tx_timer == 0) {
1238                         if_printf(ifp, "watchdog timeout\n");
1239                         ifp->if_oerrors++;
1240                         acx_txeof(ifp->if_softc);
1241                 } else {
1242                         ifp->if_timer = 1;
1243                 }
1244         }
1245         ieee80211_watchdog(&sc->sc_ic);
1246 }
1247
1248 static void
1249 acx_intr(void *arg)
1250 {
1251         struct acx_softc *sc = arg;
1252         uint16_t intr_status;
1253
1254         if ((sc->sc_flags & ACX_FLAG_FW_LOADED) == 0)
1255                 return;
1256
1257         intr_status = CSR_READ_2(sc, ACXREG_INTR_STATUS_CLR);
1258         if (intr_status == ACXRV_INTR_ALL) {
1259                 /* not our interrupt */
1260                 return;
1261         }
1262
1263         intr_status &= sc->chip_intr_enable;
1264         if (intr_status == 0) {
1265                 /* not interrupts we care about */
1266                 return;
1267         }
1268
1269         /* Acknowledge all interrupts */
1270         CSR_WRITE_2(sc, ACXREG_INTR_ACK, ACXRV_INTR_ALL);
1271
1272         if (intr_status & ACXRV_INTR_TX_FINI)
1273                 acx_txeof(sc);
1274
1275         if (intr_status & ACXRV_INTR_RX_FINI)
1276                 acx_rxeof(sc);
1277 }
1278
1279 static void
1280 acx_disable_intr(struct acx_softc *sc)
1281 {
1282         CSR_WRITE_2(sc, ACXREG_INTR_MASK, sc->chip_intr_disable);
1283         CSR_WRITE_2(sc, ACXREG_EVENT_MASK, 0);
1284 }
1285
1286 static void
1287 acx_enable_intr(struct acx_softc *sc)
1288 {
1289         /* Mask out interrupts that are not in the enable set */
1290         CSR_WRITE_2(sc, ACXREG_INTR_MASK, ~sc->chip_intr_enable);
1291         CSR_WRITE_2(sc, ACXREG_EVENT_MASK, ACXRV_EVENT_DISABLE);
1292 }
1293
1294 static void
1295 acx_txeof(struct acx_softc *sc)
1296 {
1297         struct acx_buf_data *bd;
1298         struct acx_txbuf *buf;
1299         struct ifnet *ifp;
1300         int idx;
1301
1302         ifp = &sc->sc_ic.ic_if;
1303         ASSERT_SERIALIZED(ifp->if_serializer);
1304
1305         bd = &sc->sc_buf_data;
1306         idx = bd->tx_used_start;
1307         for (buf = &bd->tx_buf[idx]; buf->tb_mbuf != NULL;
1308              buf = &bd->tx_buf[idx]) {
1309                 uint8_t ctrl, error;
1310                 int frame_len;
1311
1312                 ctrl = FW_TXDESC_GETFIELD_1(sc, buf, f_tx_ctrl);
1313                 if ((ctrl & (DESC_CTRL_HOSTOWN | DESC_CTRL_ACXDONE)) !=
1314                     (DESC_CTRL_HOSTOWN | DESC_CTRL_ACXDONE))
1315                         break;
1316
1317                 bus_dmamap_unload(bd->mbuf_dma_tag, buf->tb_mbuf_dmamap);
1318                 frame_len = buf->tb_mbuf->m_pkthdr.len;
1319                 m_freem(buf->tb_mbuf);
1320                 buf->tb_mbuf = NULL;
1321
1322                 error = FW_TXDESC_GETFIELD_1(sc, buf, f_tx_error);
1323                 if (error) {
1324                         acx_txerr(sc, error);
1325                         ifp->if_oerrors++;
1326                 } else {
1327                         ifp->if_opackets++;
1328                 }
1329
1330                 if (buf->tb_node != NULL) {
1331                         sc->chip_tx_complete(sc, buf, frame_len, error);
1332                         ieee80211_free_node(buf->tb_node);
1333                         buf->tb_node = NULL;
1334                 }
1335
1336                 FW_TXDESC_SETFIELD_1(sc, buf, f_tx_ctrl, DESC_CTRL_HOSTOWN);
1337
1338                 bd->tx_used_count--;
1339
1340                 idx = (idx + 1) % ACX_TX_DESC_CNT;
1341         }
1342         bd->tx_used_start = idx;
1343
1344         sc->sc_tx_timer = bd->tx_used_count == 0 ? 0 : 5;
1345
1346         if (bd->tx_used_count != ACX_TX_DESC_CNT) {
1347                 ifp->if_flags &= ~IFF_OACTIVE;
1348                 acx_start(ifp);
1349         }
1350 }
1351
1352 static void
1353 acx_txerr(struct acx_softc *sc, uint8_t err)
1354 {
1355         struct ifnet *ifp = &sc->sc_ic.ic_if;
1356         struct acx_stats *stats = &sc->sc_stats;
1357
1358         if (err == DESC_ERR_EXCESSIVE_RETRY) {
1359                 /*
1360                  * This a common error (see comment below),
1361                  * so print it using DPRINTF()
1362                  */
1363                 DPRINTF((ifp, "TX failed -- excessive retry\n"));
1364         } else {
1365                 if_printf(ifp, "TX failed -- ");
1366         }
1367
1368         /*
1369          * Although `err' looks like bitmask, it never
1370          * has multiple bits set.
1371          */
1372         switch (err) {
1373 #if 0
1374         case DESC_ERR_OTHER_FRAG:
1375                 /* XXX what's this */
1376                 kprintf("error in other fragment\n");
1377                 stats->err_oth_frag++;
1378                 break;
1379 #endif
1380         case DESC_ERR_ABORT:
1381                 kprintf("aborted\n");
1382                 stats->err_abort++;
1383                 break;
1384         case DESC_ERR_PARAM:
1385                 kprintf("wrong parameters in descriptor\n");
1386                 stats->err_param++;
1387                 break;
1388         case DESC_ERR_NO_WEPKEY:
1389                 kprintf("WEP key missing\n");
1390                 stats->err_no_wepkey++;
1391                 break;
1392         case DESC_ERR_MSDU_TIMEOUT:
1393                 kprintf("MSDU life timeout\n");
1394                 stats->err_msdu_timeout++;
1395                 break;
1396         case DESC_ERR_EXCESSIVE_RETRY:
1397                 /*
1398                  * Possible causes:
1399                  * 1) Distance is too long
1400                  * 2) Transmit failed (e.g. no MAC level ACK)
1401                  * 3) Chip overheated (this should be rare)
1402                  */
1403                 stats->err_ex_retry++;
1404                 break;
1405         case DESC_ERR_BUF_OVERFLOW:
1406                 kprintf("buffer overflow\n");
1407                 stats->err_buf_oflow++;
1408                 break;
1409         case DESC_ERR_DMA:
1410                 kprintf("DMA error\n");
1411                 stats->err_dma++;
1412                 break;
1413         default:
1414                 kprintf("unknown error %d\n", err);
1415                 stats->err_unkn++;
1416                 break;
1417         }
1418 }
1419
1420 static void
1421 acx_rxeof(struct acx_softc *sc)
1422 {
1423         struct ieee80211com *ic = &sc->sc_ic;
1424         struct acx_ring_data *rd = &sc->sc_ring_data;
1425         struct acx_buf_data *bd = &sc->sc_buf_data;
1426         struct ifnet *ifp = &ic->ic_if;
1427         int idx, ready;
1428
1429         ASSERT_SERIALIZED(ic->ic_if.if_serializer);
1430
1431         bus_dmamap_sync(rd->rx_ring_dma_tag, rd->rx_ring_dmamap,
1432                         BUS_DMASYNC_POSTREAD);
1433
1434         /*
1435          * Locate first "ready" rx buffer,
1436          * start from last stopped position
1437          */
1438         idx = bd->rx_scan_start;
1439         ready = 0;
1440         do {
1441                 struct acx_rxbuf *buf;
1442
1443                 buf = &bd->rx_buf[idx];
1444                 if ((buf->rb_desc->h_ctrl & htole16(DESC_CTRL_HOSTOWN)) &&
1445                     (buf->rb_desc->h_status & htole32(DESC_STATUS_FULL))) {
1446                         ready = 1;
1447                         break;
1448                 }
1449                 idx = (idx + 1) % ACX_RX_DESC_CNT;
1450         } while (idx != bd->rx_scan_start);
1451
1452         if (!ready)
1453                 return;
1454
1455         /*
1456          * NOTE: don't mess up `idx' here, it will
1457          * be used in the following code
1458          */
1459
1460         do {
1461                 struct acx_rxbuf_hdr *head;
1462                 struct acx_rxbuf *buf;
1463                 struct ieee80211_frame_min *wh;
1464                 struct mbuf *m;
1465                 uint32_t desc_status;
1466                 uint16_t desc_ctrl;
1467                 int len, error, rssi, is_priv;
1468
1469                 buf = &bd->rx_buf[idx];
1470
1471                 desc_ctrl = le16toh(buf->rb_desc->h_ctrl);
1472                 desc_status = le32toh(buf->rb_desc->h_status);
1473                 if (!(desc_ctrl & DESC_CTRL_HOSTOWN) ||
1474                     !(desc_status & DESC_STATUS_FULL))
1475                         break;
1476
1477                 bus_dmamap_sync(bd->mbuf_dma_tag, buf->rb_mbuf_dmamap,
1478                                 BUS_DMASYNC_POSTREAD);
1479
1480                 m = buf->rb_mbuf;
1481
1482                 error = acx_newbuf(sc, buf, 0);
1483                 if (error) {
1484                         ifp->if_ierrors++;
1485                         goto next;
1486                 }
1487
1488                 head = mtod(m, struct acx_rxbuf_hdr *);
1489                 len = le16toh(head->rbh_len) & ACX_RXBUF_LEN_MASK;
1490                 rssi = acx_get_rssi(sc, head->rbh_level);
1491
1492                 m_adj(m, sizeof(struct acx_rxbuf_hdr) + sc->chip_rxbuf_exhdr);
1493                 m->m_len = m->m_pkthdr.len = len;
1494                 m->m_pkthdr.rcvif = &ic->ic_if;
1495
1496                 wh = mtod(m, struct ieee80211_frame_min *);
1497                 is_priv = (wh->i_fc[1] & IEEE80211_FC1_WEP);
1498
1499                 if (sc->sc_drvbpf != NULL) {
1500                         sc->sc_rx_th.wr_tsf = htole32(head->rbh_time);
1501
1502                         sc->sc_rx_th.wr_flags = 0;
1503                         if (is_priv) {
1504                                 sc->sc_rx_th.wr_flags |=
1505                                         IEEE80211_RADIOTAP_F_WEP;
1506                         }
1507                         if (head->rbh_bbp_stat & ACX_RXBUF_STAT_SHPRE) {
1508                                 sc->sc_rx_th.wr_flags |=
1509                                         IEEE80211_RADIOTAP_F_SHORTPRE;
1510                         }
1511
1512                         if (sc->chip_phymode == IEEE80211_MODE_11G) {
1513                                 sc->sc_rx_th.wr_rate =
1514                                     ieee80211_plcp2rate(head->rbh_plcp,
1515                                     head->rbh_bbp_stat & ACX_RXBUF_STAT_OFDM);
1516                         } else {
1517                                 sc->sc_rx_th.wr_rate =
1518                                     ieee80211_plcp2rate(head->rbh_plcp, 0);
1519                         }
1520
1521                         sc->sc_rx_th.wr_antsignal = rssi;
1522
1523                         if (head->rbh_bbp_stat & ACX_RXBUF_STAT_ANT1)
1524                                 sc->sc_rx_th.wr_antenna = 1;
1525                         else
1526                                 sc->sc_rx_th.wr_antenna = 0;
1527
1528                         bpf_ptap(sc->sc_drvbpf, m, &sc->sc_rx_th,
1529                                  sc->sc_rx_th_len);
1530                 }
1531
1532                 if (len >= sizeof(struct ieee80211_frame_min) &&
1533                     len < MCLBYTES) {
1534                         struct ieee80211_node *ni;
1535
1536                         if (is_priv && sc->chip_hw_crypt) {
1537                                 /* Short circuit software WEP */
1538                                 wh->i_fc[1] &= ~IEEE80211_FC1_WEP;
1539
1540                                 /* Do chip specific RX buffer processing */
1541                                 if (sc->chip_proc_wep_rxbuf != NULL) {
1542                                         sc->chip_proc_wep_rxbuf(sc, m, &len);
1543                                         wh = mtod(m,
1544                                              struct ieee80211_frame_min *);
1545                                 }
1546                         }
1547                         m->m_len = m->m_pkthdr.len = len;
1548
1549                         ni = ieee80211_find_rxnode(ic, wh);
1550                         ieee80211_input(ic, m, ni, rssi,
1551                                         le32toh(head->rbh_time));
1552                         ieee80211_free_node(ni);
1553
1554                         ifp->if_ipackets++;
1555                 } else {
1556                         if (len < sizeof(struct ieee80211_frame_min)) {
1557                                 if (ic->ic_rawbpf != NULL &&
1558                                     len >= sizeof(struct ieee80211_frame_ack))
1559                                         bpf_mtap(ic->ic_rawbpf, m);
1560
1561                                 if (ic->ic_opmode != IEEE80211_M_MONITOR)
1562                                         ic->ic_stats.is_rx_tooshort++;
1563                         }
1564                         m_freem(m);
1565                 }
1566 next:
1567                 buf->rb_desc->h_ctrl = htole16(desc_ctrl & ~DESC_CTRL_HOSTOWN);
1568                 buf->rb_desc->h_status = 0;
1569                 bus_dmamap_sync(rd->rx_ring_dma_tag, rd->rx_ring_dmamap,
1570                                 BUS_DMASYNC_PREWRITE);
1571
1572                 idx = (idx + 1) % ACX_RX_DESC_CNT;
1573         } while (idx != bd->rx_scan_start);
1574
1575         /*
1576          * Record the position so that next
1577          * time we can start from it
1578          */
1579         bd->rx_scan_start = idx;
1580 }
1581
1582 static int
1583 acx_reset(struct acx_softc *sc)
1584 {
1585         uint16_t reg;
1586
1587         /* Halt ECPU */
1588         CSR_SETB_2(sc, ACXREG_ECPU_CTRL, ACXRV_ECPU_HALT);
1589
1590         /* Software reset */
1591         reg = CSR_READ_2(sc, ACXREG_SOFT_RESET);
1592         CSR_WRITE_2(sc, ACXREG_SOFT_RESET, reg | ACXRV_SOFT_RESET);
1593         DELAY(100);
1594         CSR_WRITE_2(sc, ACXREG_SOFT_RESET, reg);
1595
1596         /* Initialize EEPROM */
1597         CSR_SETB_2(sc, ACXREG_EEPROM_INIT, ACXRV_EEPROM_INIT);
1598         DELAY(50000);
1599
1600         /* Test whether ECPU is stopped */
1601         reg = CSR_READ_2(sc, ACXREG_ECPU_CTRL);
1602         if (!(reg & ACXRV_ECPU_HALT)) {
1603                 if_printf(&sc->sc_ic.ic_if, "can't halt ECPU\n");
1604                 return ENXIO;
1605         }
1606         return 0;
1607 }
1608
1609 static int
1610 acx_read_eeprom(struct acx_softc *sc, uint32_t offset, uint8_t *val)
1611 {
1612         int i;
1613
1614         CSR_WRITE_4(sc, ACXREG_EEPROM_CONF, 0);
1615         CSR_WRITE_4(sc, ACXREG_EEPROM_ADDR, offset);
1616         CSR_WRITE_4(sc, ACXREG_EEPROM_CTRL, ACXRV_EEPROM_READ);
1617
1618 #define EE_READ_RETRY_MAX       100
1619         for (i = 0; i < EE_READ_RETRY_MAX; ++i) {
1620                 if (CSR_READ_2(sc, ACXREG_EEPROM_CTRL) == 0)
1621                         break;
1622                 DELAY(10000);
1623         }
1624         if (i == EE_READ_RETRY_MAX) {
1625                 if_printf(&sc->sc_ic.ic_if, "can't read EEPROM offset %x "
1626                           "(timeout)\n", offset);
1627                 return ETIMEDOUT;
1628         }
1629 #undef EE_READ_RETRY_MAX
1630
1631         *val = CSR_READ_1(sc, ACXREG_EEPROM_DATA);
1632         return 0;
1633 }
1634
1635 static int
1636 acx_read_phyreg(struct acx_softc *sc, uint32_t reg, uint8_t *val)
1637 {
1638         int i;
1639
1640         CSR_WRITE_4(sc, ACXREG_PHY_ADDR, reg);
1641         CSR_WRITE_4(sc, ACXREG_PHY_CTRL, ACXRV_PHY_READ);
1642
1643 #define PHY_READ_RETRY_MAX      100
1644         for (i = 0; i < PHY_READ_RETRY_MAX; ++i) {
1645                 if (CSR_READ_4(sc, ACXREG_PHY_CTRL) == 0)
1646                         break;
1647                 DELAY(10000);
1648         }
1649         if (i == PHY_READ_RETRY_MAX) {
1650                 if_printf(&sc->sc_ic.ic_if, "can't read phy reg %x (timeout)\n",
1651                           reg);
1652                 return ETIMEDOUT;
1653         }
1654 #undef PHY_READ_RETRY_MAX
1655
1656         *val = CSR_READ_1(sc, ACXREG_PHY_DATA);
1657         return 0;
1658 }
1659
1660 void
1661 acx_write_phyreg(struct acx_softc *sc, uint32_t reg, uint8_t val)
1662 {
1663         CSR_WRITE_4(sc, ACXREG_PHY_DATA, val);
1664         CSR_WRITE_4(sc, ACXREG_PHY_ADDR, reg);
1665         CSR_WRITE_4(sc, ACXREG_PHY_CTRL, ACXRV_PHY_WRITE);
1666 }
1667
1668 static int
1669 acx_alloc_firmware(struct acx_softc *sc)
1670 {
1671         struct acx_firmware *fw = &sc->sc_firmware;
1672         struct ifnet *ifp = &sc->sc_ic.ic_if;
1673         struct fw_image *img;
1674         char filename[64];
1675         int error = 0;
1676
1677         /*
1678          * NB: serializer need to be released before loading firmware
1679          *     image to avoid possible dead lock
1680          */
1681         ASSERT_SERIALIZED(ifp->if_serializer);
1682
1683         if (fw->base_fw_image == NULL) {
1684                 if (fw->combined_radio_fw) {
1685                         ksnprintf(filename, sizeof(filename),
1686                                   ACX_BASE_RADIO_FW_PATH,
1687                                   fw->fwdir, sc->sc_radio_type);
1688                 } else {
1689                         ksnprintf(filename, sizeof(filename),
1690                                   ACX_BASE_FW_PATH, fw->fwdir);
1691                 }
1692
1693                 lwkt_serialize_exit(ifp->if_serializer);
1694                 img = firmware_image_load(filename, NULL);
1695                 lwkt_serialize_enter(ifp->if_serializer);
1696
1697                 fw->base_fw_image = img;
1698                 if (fw->base_fw_image == NULL) {
1699                         if_printf(ifp, "load %s base fw failed\n", filename);
1700                         error = EIO;
1701                         goto back;
1702                 }
1703
1704                 error = acx_setup_firmware(sc, fw->base_fw_image,
1705                                            &fw->base_fw, &fw->base_fw_len);
1706                 if (error)
1707                         goto back;
1708         }
1709
1710         if (!fw->combined_radio_fw && fw->radio_fw_image == NULL) {
1711                 ksnprintf(filename, sizeof(filename), ACX_RADIO_FW_PATH,
1712                           fw->fwdir, sc->sc_radio_type);
1713
1714                 lwkt_serialize_exit(ifp->if_serializer);
1715                 img = firmware_image_load(filename, NULL);
1716                 lwkt_serialize_enter(ifp->if_serializer);
1717
1718                 fw->radio_fw_image = img;
1719                 if (fw->radio_fw_image == NULL) {
1720                         if_printf(ifp, "load %s radio fw failed\n", filename);
1721                         error = EIO;
1722                         goto back;
1723                 }
1724
1725                 error = acx_setup_firmware(sc, fw->radio_fw_image,
1726                                            &fw->radio_fw, &fw->radio_fw_len);
1727         }
1728 back:
1729         if (error)
1730                 acx_free_firmware(sc);
1731         return error;
1732 }
1733
1734 static int
1735 acx_setup_firmware(struct acx_softc *sc, struct fw_image *img,
1736                    const uint8_t **ptr, int *len)
1737 {
1738         const struct acx_firmware_hdr *hdr;
1739         const uint8_t *p;
1740         uint32_t cksum;
1741         int i;
1742
1743         *ptr = NULL;
1744         *len = 0;
1745
1746         /*
1747          * Make sure that the firmware image contains more than just a header
1748          */
1749         if (img->fw_imglen <= sizeof(*hdr)) {
1750                 if_printf(&sc->sc_ic.ic_if, "%s is invalid image, "
1751                           "size %u (too small)\n",
1752                           img->fw_name, img->fw_imglen);
1753                 return EINVAL;
1754         }
1755         hdr = (const struct acx_firmware_hdr *)img->fw_image;
1756
1757         /*
1758          * Verify length
1759          */
1760         if (hdr->fwh_len != img->fw_imglen - sizeof(*hdr)) {
1761                 if_printf(&sc->sc_ic.ic_if, "%s is invalid image, "
1762                           "size in hdr %u and image size %u mismatches\n",
1763                           img->fw_name, hdr->fwh_len, img->fw_imglen);
1764                 return EINVAL;
1765         }
1766
1767         /*
1768          * Verify cksum
1769          */
1770         cksum = 0;
1771         for (i = 0, p = (const uint8_t *)&hdr->fwh_len;
1772              i < img->fw_imglen - sizeof(hdr->fwh_cksum); ++i, ++p)
1773                 cksum += *p;
1774         if (cksum != hdr->fwh_cksum) {
1775                 if_printf(&sc->sc_ic.ic_if, "%s is invalid image, "
1776                           "checksum mismatch\n", img->fw_name);
1777                 return EINVAL;
1778         }
1779
1780         *ptr = ((const uint8_t *)img->fw_image + sizeof(*hdr));
1781         *len = img->fw_imglen - sizeof(*hdr);
1782         return 0;
1783 }
1784
1785 static void
1786 acx_free_firmware(struct acx_softc *sc)
1787 {
1788         struct acx_firmware *fw = &sc->sc_firmware;
1789
1790         if (fw->base_fw_image != NULL) {
1791                 firmware_image_unload(fw->base_fw_image);
1792                 fw->base_fw_image = NULL;
1793                 fw->base_fw = NULL;
1794                 fw->base_fw_len = 0;
1795         }
1796         if (fw->radio_fw_image != NULL) {
1797                 firmware_image_unload(fw->radio_fw_image);
1798                 fw->radio_fw_image = NULL;
1799                 fw->radio_fw = NULL;
1800                 fw->radio_fw_len = 0;
1801         }
1802 }
1803
1804 static int
1805 acx_load_base_firmware(struct acx_softc *sc, const uint8_t *base_fw,
1806                        uint32_t base_fw_len)
1807 {
1808         int i, error;
1809
1810         /* Load base firmware */
1811         error = acx_load_firmware(sc, 0, base_fw, base_fw_len);
1812         if (error) {
1813                 if_printf(&sc->sc_ic.ic_if, "can't load base firmware\n");
1814                 return error;
1815         }
1816         DPRINTF((&sc->sc_ic.ic_if, "base firmware loaded\n"));
1817
1818         /* Start ECPU */
1819         CSR_WRITE_2(sc, ACXREG_ECPU_CTRL, ACXRV_ECPU_START);
1820
1821         /* Wait for ECPU to be up */
1822         for (i = 0; i < 500; ++i) {
1823                 uint16_t reg;
1824
1825                 reg = CSR_READ_2(sc, ACXREG_INTR_STATUS);
1826                 if (reg & ACXRV_INTR_FCS_THRESH) {
1827                         CSR_WRITE_2(sc, ACXREG_INTR_ACK, ACXRV_INTR_FCS_THRESH);
1828                         return 0;
1829                 }
1830                 DELAY(10000);
1831         }
1832
1833         if_printf(&sc->sc_ic.ic_if, "can't initialize ECPU (timeout)\n");
1834         return ENXIO;
1835 }
1836
1837 static int
1838 acx_load_radio_firmware(struct acx_softc *sc, const uint8_t *radio_fw,
1839                         uint32_t radio_fw_len)
1840 {
1841         struct acx_conf_mmap mem_map;
1842         uint32_t radio_fw_ofs;
1843         int error;
1844
1845         /*
1846          * Get the position, where base firmware is loaded, so that
1847          * radio firmware can be loaded after it.
1848          */
1849         if (acx_get_mmap_conf(sc, &mem_map) != 0)
1850                 return ENXIO;
1851         radio_fw_ofs = le32toh(mem_map.code_end);
1852
1853         /* Put ECPU into sleeping state, before loading radio firmware */
1854         if (acx_sleep(sc) != 0)
1855                 return ENXIO;
1856
1857         /* Load radio firmware */
1858         error = acx_load_firmware(sc, radio_fw_ofs, radio_fw, radio_fw_len);
1859         if (error) {
1860                 if_printf(&sc->sc_ic.ic_if, "can't load radio firmware\n");
1861                 return ENXIO;
1862         }
1863         DPRINTF((&sc->sc_ic.ic_if, "radio firmware loaded\n"));
1864
1865         /* Wake up sleeping ECPU, after radio firmware is loaded */
1866         if (acx_wakeup(sc) != 0)
1867                 return ENXIO;
1868
1869         /* Initialize radio */
1870         if (acx_init_radio(sc, radio_fw_ofs, radio_fw_len) != 0)
1871                 return ENXIO;
1872
1873         /* Verify radio firmware's loading position */
1874         if (acx_get_mmap_conf(sc, &mem_map) != 0)
1875                 return ENXIO;
1876         if (le32toh(mem_map.code_end) != radio_fw_ofs + radio_fw_len) {
1877                 if_printf(&sc->sc_ic.ic_if, "loaded radio firmware position "
1878                           "mismatch\n");
1879                 return ENXIO;
1880         }
1881
1882         DPRINTF((&sc->sc_ic.ic_if, "radio firmware initialized\n"));
1883         return 0;
1884 }
1885
1886 static int
1887 acx_load_firmware(struct acx_softc *sc, uint32_t offset, const uint8_t *data,
1888                   int data_len)
1889 {
1890         const uint32_t *fw;
1891         int i, fw_len;
1892
1893         fw = (const uint32_t *)data;
1894         fw_len = data_len / sizeof(uint32_t);
1895
1896         /*
1897          * LOADFW_AUTO_INC only works with some older firmware:
1898          * 1) acx100's firmware
1899          * 2) acx111's firmware whose rev is 0x00010011
1900          */
1901
1902         /* Load firmware */
1903         CSR_WRITE_4(sc, ACXREG_FWMEM_START, ACXRV_FWMEM_START_OP);
1904 #ifndef LOADFW_AUTO_INC
1905         CSR_WRITE_4(sc, ACXREG_FWMEM_CTRL, 0);
1906 #else
1907         CSR_WRITE_4(sc, ACXREG_FWMEM_CTRL, ACXRV_FWMEM_ADDR_AUTOINC);
1908         CSR_WRITE_4(sc, ACXREG_FWMEM_ADDR, offset);
1909 #endif
1910
1911         for (i = 0; i < fw_len; ++i) {
1912 #ifndef LOADFW_AUTO_INC
1913                 CSR_WRITE_4(sc, ACXREG_FWMEM_ADDR, offset + (i * 4));
1914 #endif
1915                 CSR_WRITE_4(sc, ACXREG_FWMEM_DATA, be32toh(fw[i]));
1916         }
1917
1918         /* Verify firmware */
1919         CSR_WRITE_4(sc, ACXREG_FWMEM_START, ACXRV_FWMEM_START_OP);
1920 #ifndef LOADFW_AUTO_INC
1921         CSR_WRITE_4(sc, ACXREG_FWMEM_CTRL, 0);
1922 #else
1923         CSR_WRITE_4(sc, ACXREG_FWMEM_CTRL, ACXRV_FWMEM_ADDR_AUTOINC);
1924         CSR_WRITE_4(sc, ACXREG_FWMEM_ADDR, offset);
1925 #endif
1926
1927         for (i = 0; i < fw_len; ++i) {
1928                 uint32_t val;
1929
1930 #ifndef LOADFW_AUTO_INC
1931                 CSR_WRITE_4(sc, ACXREG_FWMEM_ADDR, offset + (i * 4));
1932 #endif
1933                 val = CSR_READ_4(sc, ACXREG_FWMEM_DATA);
1934                 if (be32toh(fw[i]) != val) {
1935                         if_printf(&sc->sc_ic.ic_if, "fireware mismatch "
1936                                   "fw %08x  loaded %08x\n", fw[i], val);
1937                         return ENXIO;
1938                 }
1939         }
1940         return 0;
1941 }
1942
1943 static int
1944 acx_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
1945 {
1946         struct ifnet *ifp = &ic->ic_if;
1947         struct acx_softc *sc = ifp->if_softc;
1948         struct ieee80211_node *ni = NULL;
1949         struct ieee80211_channel *c = NULL;
1950         int error = 1, mode = 0;
1951
1952         ASSERT_SERIALIZED(ifp->if_serializer);
1953
1954         ieee80211_ratectl_newstate(ic, nstate);
1955         callout_stop(&sc->sc_scan_timer);
1956
1957         switch (nstate) {
1958         case IEEE80211_S_SCAN:
1959                 acx_set_chan(sc, ic->ic_curchan);
1960                 callout_reset(&sc->sc_scan_timer,
1961                               (hz * sc->sc_scan_dwell) / 1000,
1962                               acx_next_scan, sc);
1963                 break;
1964         case IEEE80211_S_AUTH:
1965                 if (ic->ic_opmode == IEEE80211_M_STA) {
1966                         ni = ic->ic_bss;
1967                         c = ni->ni_chan;
1968                         mode = ACX_MODE_STA;
1969                 }
1970                 break;
1971         case IEEE80211_S_RUN:
1972                 if (ic->ic_opmode == IEEE80211_M_IBSS ||
1973                     ic->ic_opmode == IEEE80211_M_HOSTAP) {
1974                         ni = ic->ic_bss;
1975                         c = ni->ni_chan;
1976                         if (ic->ic_opmode == IEEE80211_M_IBSS)
1977                                 mode = ACX_MODE_ADHOC;
1978                         else
1979                                 mode = ACX_MODE_AP;
1980
1981                         if (acx_set_beacon_tmplt(sc, ni) != 0) {
1982                                 if_printf(ifp, "set bescon template failed\n");
1983                                 goto back;
1984                         }
1985                         if (acx_set_probe_resp_tmplt(sc, ni) != 0) {
1986                                 if_printf(ifp, "set probe response template"
1987                                           " failed\n");
1988                                 goto back;
1989                         }
1990                 } else if (ic->ic_opmode == IEEE80211_M_MONITOR) {
1991                         ni = ic->ic_bss;
1992                         c = ic->ic_curchan;
1993                         mode = ACX_MODE_STA;
1994                 }
1995                 break;
1996         default:
1997                 break;
1998         }
1999
2000         if (ni != NULL) {
2001                 KKASSERT(c != NULL);
2002
2003                 if (acx_set_chan(sc, c) != 0)
2004                         goto back;
2005
2006                 if (acx_join_bss(sc, mode, ni, c) != 0) {
2007                         if_printf(ifp, "join BSS failed\n");
2008                         goto back;
2009                 }
2010         }
2011
2012         error = 0;
2013 back:
2014         if (error) {
2015                 /* XXX */
2016                 nstate = IEEE80211_S_INIT;
2017                 arg = -1;
2018         }
2019         return sc->sc_newstate(ic, nstate, arg);
2020 }
2021
2022 int
2023 acx_init_tmplt_ordered(struct acx_softc *sc)
2024 {
2025 #define INIT_TMPLT(name)                        \
2026 do {                                            \
2027         if (acx_init_##name##_tmplt(sc) != 0)   \
2028                 return 1;                       \
2029 } while (0)
2030
2031         /*
2032          * NOTE:
2033          * Order of templates initialization:
2034          * 1) Probe request
2035          * 2) NULL data
2036          * 3) Beacon
2037          * 4) TIM
2038          * 5) Probe response
2039          * Above order is critical to get a correct memory map.
2040          */
2041         INIT_TMPLT(probe_req);
2042         INIT_TMPLT(null_data);
2043         INIT_TMPLT(beacon);
2044         INIT_TMPLT(tim);
2045         INIT_TMPLT(probe_resp);
2046
2047 #undef INIT_TMPLT
2048         return 0;
2049 }
2050
2051 static void
2052 acx_ring_dma_addr(void *arg, bus_dma_segment_t *seg, int nseg, int error)
2053 {
2054         *((uint32_t *)arg) = seg->ds_addr;
2055 }
2056
2057 static int
2058 acx_dma_alloc(struct acx_softc *sc)
2059 {
2060         struct acx_ring_data *rd = &sc->sc_ring_data;
2061         struct acx_buf_data *bd = &sc->sc_buf_data;
2062         int i, error;
2063
2064         /* Allocate DMA stuffs for RX descriptors  */
2065         error = bus_dma_tag_create(NULL, PAGE_SIZE, 0,
2066                                    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR,
2067                                    NULL, NULL,
2068                                    ACX_RX_RING_SIZE, 1, ACX_RX_RING_SIZE,
2069                                    0, &rd->rx_ring_dma_tag);
2070         if (error) {
2071                 if_printf(&sc->sc_ic.ic_if, "can't create rx ring dma tag\n");
2072                 return error;
2073         }
2074
2075         error = bus_dmamem_alloc(rd->rx_ring_dma_tag, (void **)&rd->rx_ring,
2076                                  BUS_DMA_WAITOK | BUS_DMA_ZERO,
2077                                  &rd->rx_ring_dmamap);
2078         if (error) {
2079                 if_printf(&sc->sc_ic.ic_if,
2080                           "can't allocate rx ring dma memory\n");
2081                 bus_dma_tag_destroy(rd->rx_ring_dma_tag);
2082                 rd->rx_ring_dma_tag = NULL;
2083                 return error;
2084         }
2085
2086         error = bus_dmamap_load(rd->rx_ring_dma_tag, rd->rx_ring_dmamap,
2087                                 rd->rx_ring, ACX_RX_RING_SIZE,
2088                                 acx_ring_dma_addr, &rd->rx_ring_paddr,
2089                                 BUS_DMA_WAITOK);
2090         if (error) {
2091                 if_printf(&sc->sc_ic.ic_if, "can't get rx ring dma address\n");
2092                 bus_dmamem_free(rd->rx_ring_dma_tag, rd->rx_ring,
2093                                 rd->rx_ring_dmamap);
2094                 bus_dma_tag_destroy(rd->rx_ring_dma_tag);
2095                 rd->rx_ring_dma_tag = NULL;
2096                 return error;
2097         }
2098
2099         /* Allocate DMA stuffs for TX descriptors */
2100         error = bus_dma_tag_create(NULL, PAGE_SIZE, 0,
2101                                    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR,
2102                                    NULL, NULL,
2103                                    ACX_TX_RING_SIZE, 1, ACX_TX_RING_SIZE,
2104                                    0, &rd->tx_ring_dma_tag);
2105         if (error) {
2106                 if_printf(&sc->sc_ic.ic_if, "can't create tx ring dma tag\n");
2107                 return error;
2108         }
2109
2110         error = bus_dmamem_alloc(rd->tx_ring_dma_tag, (void **)&rd->tx_ring,
2111                                  BUS_DMA_WAITOK | BUS_DMA_ZERO,
2112                                  &rd->tx_ring_dmamap);
2113         if (error) {
2114                 if_printf(&sc->sc_ic.ic_if,
2115                           "can't allocate tx ring dma memory\n");
2116                 bus_dma_tag_destroy(rd->tx_ring_dma_tag);
2117                 rd->tx_ring_dma_tag = NULL;
2118                 return error;
2119         }
2120
2121         error = bus_dmamap_load(rd->tx_ring_dma_tag, rd->tx_ring_dmamap,
2122                                 rd->tx_ring, ACX_TX_RING_SIZE,
2123                                 acx_ring_dma_addr, &rd->tx_ring_paddr,
2124                                 BUS_DMA_WAITOK);
2125         if (error) {
2126                 if_printf(&sc->sc_ic.ic_if, "can't get tx ring dma address\n");
2127                 bus_dmamem_free(rd->tx_ring_dma_tag, rd->tx_ring,
2128                                 rd->tx_ring_dmamap);
2129                 bus_dma_tag_destroy(rd->tx_ring_dma_tag);
2130                 rd->tx_ring_dma_tag = NULL;
2131                 return error;
2132         }
2133
2134         /* Create DMA tag for RX/TX mbuf map */
2135         error = bus_dma_tag_create(NULL, 1, 0,
2136                                    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR,
2137                                    NULL, NULL,
2138                                    MCLBYTES, 1, MCLBYTES,
2139                                    0, &bd->mbuf_dma_tag);
2140         if (error) {
2141                 if_printf(&sc->sc_ic.ic_if, "can't create mbuf dma tag\n");
2142                 return error;
2143         }
2144
2145         /* Create a spare RX DMA map */
2146         error = bus_dmamap_create(bd->mbuf_dma_tag, 0, &bd->mbuf_tmp_dmamap);
2147         if (error) {
2148                 if_printf(&sc->sc_ic.ic_if, "can't create tmp mbuf dma map\n");
2149                 bus_dma_tag_destroy(bd->mbuf_dma_tag);
2150                 bd->mbuf_dma_tag = NULL;
2151                 return error;
2152         }
2153
2154         /* Create DMA map for RX mbufs */
2155         for (i = 0; i < ACX_RX_DESC_CNT; ++i) {
2156                 error = bus_dmamap_create(bd->mbuf_dma_tag, 0,
2157                                           &bd->rx_buf[i].rb_mbuf_dmamap);
2158                 if (error) {
2159                         if_printf(&sc->sc_ic.ic_if, "can't create rx mbuf "
2160                                   "dma map (%d)\n", i);
2161                         return error;
2162                 }
2163                 bd->rx_buf[i].rb_desc = &rd->rx_ring[i];
2164         }
2165
2166         /* Create DMA map for TX mbufs */
2167         for (i = 0; i < ACX_TX_DESC_CNT; ++i) {
2168                 error = bus_dmamap_create(bd->mbuf_dma_tag, 0,
2169                                           &bd->tx_buf[i].tb_mbuf_dmamap);
2170                 if (error) {
2171                         if_printf(&sc->sc_ic.ic_if, "can't create tx mbuf "
2172                                   "dma map (%d)\n", i);
2173                         return error;
2174                 }
2175                 bd->tx_buf[i].tb_desc1 = &rd->tx_ring[i * 2];
2176                 bd->tx_buf[i].tb_desc2 = &rd->tx_ring[(i * 2) + 1];
2177         }
2178
2179         return 0;
2180 }
2181
2182 static void
2183 acx_dma_free(struct acx_softc *sc)
2184 {
2185         struct acx_ring_data *rd = &sc->sc_ring_data;
2186         struct acx_buf_data *bd = &sc->sc_buf_data;
2187         int i;
2188
2189         if (rd->rx_ring_dma_tag != NULL) {
2190                 bus_dmamap_unload(rd->rx_ring_dma_tag, rd->rx_ring_dmamap);
2191                 bus_dmamem_free(rd->rx_ring_dma_tag, rd->rx_ring,
2192                                 rd->rx_ring_dmamap);
2193                 bus_dma_tag_destroy(rd->rx_ring_dma_tag);
2194         }
2195
2196         if (rd->tx_ring_dma_tag != NULL) {
2197                 bus_dmamap_unload(rd->tx_ring_dma_tag, rd->tx_ring_dmamap);
2198                 bus_dmamem_free(rd->tx_ring_dma_tag, rd->tx_ring,
2199                                 rd->tx_ring_dmamap);
2200                 bus_dma_tag_destroy(rd->tx_ring_dma_tag);
2201         }
2202
2203         for (i = 0; i < ACX_RX_DESC_CNT; ++i) {
2204                 if (bd->rx_buf[i].rb_desc != NULL) {
2205                         if (bd->rx_buf[i].rb_mbuf != NULL) {
2206                                 bus_dmamap_unload(bd->mbuf_dma_tag,
2207                                                   bd->rx_buf[i].rb_mbuf_dmamap);
2208                                 m_freem(bd->rx_buf[i].rb_mbuf);
2209                         }
2210                         bus_dmamap_destroy(bd->mbuf_dma_tag,
2211                                            bd->rx_buf[i].rb_mbuf_dmamap);
2212                 }
2213         }
2214
2215         for (i = 0; i < ACX_TX_DESC_CNT; ++i) {
2216                 if (bd->tx_buf[i].tb_desc1 != NULL) {
2217                         if (bd->tx_buf[i].tb_mbuf != NULL) {
2218                                 bus_dmamap_unload(bd->mbuf_dma_tag,
2219                                                   bd->tx_buf[i].tb_mbuf_dmamap);
2220                                 m_freem(bd->tx_buf[i].tb_mbuf);
2221                         }
2222                         bus_dmamap_destroy(bd->mbuf_dma_tag,
2223                                            bd->tx_buf[i].tb_mbuf_dmamap);
2224                 }
2225         }
2226
2227         if (bd->mbuf_dma_tag != NULL) {
2228                 bus_dmamap_destroy(bd->mbuf_dma_tag, bd->mbuf_tmp_dmamap);
2229                 bus_dma_tag_destroy(bd->mbuf_dma_tag);
2230         }
2231 }
2232
2233 static int
2234 acx_init_tx_ring(struct acx_softc *sc)
2235 {
2236         struct acx_ring_data *rd;
2237         struct acx_buf_data *bd;
2238         uint32_t paddr;
2239         int i;
2240
2241         rd = &sc->sc_ring_data;
2242         paddr = rd->tx_ring_paddr;
2243         for (i = 0; i < (ACX_TX_DESC_CNT * 2) - 1; ++i) {
2244                 paddr += sizeof(struct acx_host_desc);
2245
2246                 rd->tx_ring[i].h_ctrl = htole16(DESC_CTRL_HOSTOWN);
2247
2248                 if (i == (ACX_TX_DESC_CNT * 2) - 1)
2249                         rd->tx_ring[i].h_next_desc = htole32(rd->tx_ring_paddr);
2250                 else
2251                         rd->tx_ring[i].h_next_desc = htole32(paddr);
2252         }
2253
2254         bus_dmamap_sync(rd->tx_ring_dma_tag, rd->tx_ring_dmamap,
2255                         BUS_DMASYNC_PREWRITE);
2256
2257         bd = &sc->sc_buf_data;
2258         bd->tx_free_start = 0;
2259         bd->tx_used_start = 0;
2260         bd->tx_used_count = 0;
2261
2262         return 0;
2263 }
2264
2265 static int
2266 acx_init_rx_ring(struct acx_softc *sc)
2267 {
2268         struct acx_ring_data *rd;
2269         struct acx_buf_data *bd;
2270         uint32_t paddr;
2271         int i;
2272
2273         bd = &sc->sc_buf_data;
2274         rd = &sc->sc_ring_data;
2275         paddr = rd->rx_ring_paddr;
2276
2277         for (i = 0; i < ACX_RX_DESC_CNT; ++i) {
2278                 int error;
2279
2280                 paddr += sizeof(struct acx_host_desc);
2281
2282                 error = acx_newbuf(sc, &bd->rx_buf[i], 1);
2283                 if (error)
2284                         return error;
2285
2286                 if (i == ACX_RX_DESC_CNT - 1)
2287                         rd->rx_ring[i].h_next_desc = htole32(rd->rx_ring_paddr);
2288                 else
2289                         rd->rx_ring[i].h_next_desc = htole32(paddr);
2290         }
2291
2292         bus_dmamap_sync(rd->rx_ring_dma_tag, rd->rx_ring_dmamap,
2293                         BUS_DMASYNC_PREWRITE);
2294
2295         bd->rx_scan_start = 0;
2296         return 0;
2297 }
2298
2299 static void
2300 acx_buf_dma_addr(void *arg, bus_dma_segment_t *seg, int nseg,
2301                  bus_size_t mapsz, int error)
2302 {
2303         if (error)
2304                 return;
2305
2306         /* XXX */
2307         KASSERT(nseg == 1, ("too many RX dma segments\n"));
2308         *((uint32_t *)arg) = seg->ds_addr;
2309 }
2310
2311 static int
2312 acx_newbuf(struct acx_softc *sc, struct acx_rxbuf *rb, int wait)
2313 {
2314         struct acx_buf_data *bd;
2315         struct mbuf *m;
2316         bus_dmamap_t map;
2317         uint32_t paddr;
2318         int error;
2319
2320         bd = &sc->sc_buf_data;
2321
2322         m = m_getcl(wait ? MB_WAIT : MB_DONTWAIT, MT_DATA, M_PKTHDR);
2323         if (m == NULL)
2324                 return ENOBUFS;
2325
2326         m->m_len = m->m_pkthdr.len = MCLBYTES;
2327
2328         error = bus_dmamap_load_mbuf(bd->mbuf_dma_tag, bd->mbuf_tmp_dmamap,
2329                                      m, acx_buf_dma_addr, &paddr,
2330                                      wait ? BUS_DMA_WAITOK : BUS_DMA_NOWAIT);
2331         if (error) {
2332                 m_freem(m);
2333                 if_printf(&sc->sc_ic.ic_if, "can't map rx mbuf %d\n", error);
2334                 return error;
2335         }
2336
2337         /* Unload originally mapped mbuf */
2338         bus_dmamap_unload(bd->mbuf_dma_tag, rb->rb_mbuf_dmamap);
2339
2340         /* Swap this dmamap with tmp dmamap */
2341         map = rb->rb_mbuf_dmamap;
2342         rb->rb_mbuf_dmamap = bd->mbuf_tmp_dmamap;
2343         bd->mbuf_tmp_dmamap = map;
2344
2345         rb->rb_mbuf = m;
2346         rb->rb_desc->h_data_paddr = htole32(paddr);
2347         rb->rb_desc->h_data_len = htole16(m->m_len);
2348
2349         bus_dmamap_sync(bd->mbuf_dma_tag, rb->rb_mbuf_dmamap,
2350                         BUS_DMASYNC_PREREAD);
2351         return 0;
2352 }
2353
2354 static int
2355 acx_encap(struct acx_softc *sc, struct acx_txbuf *txbuf, struct mbuf *m,
2356           struct ieee80211_node *ni)
2357 {
2358         struct acx_buf_data *bd = &sc->sc_buf_data;
2359         struct acx_ring_data *rd = &sc->sc_ring_data;
2360         uint32_t paddr;
2361         uint8_t ctrl, rate;
2362         int error;
2363
2364         KASSERT(txbuf->tb_mbuf == NULL, ("free TX buf has mbuf installed\n"));
2365         error = 0;
2366
2367         if (m->m_pkthdr.len > MCLBYTES) {
2368                 if_printf(&sc->sc_ic.ic_if, "mbuf too big\n");
2369                 error = E2BIG;
2370                 goto back;
2371         } else if (m->m_pkthdr.len < ACX_FRAME_HDRLEN) {
2372                 if_printf(&sc->sc_ic.ic_if, "mbuf too small\n");
2373                 error = EINVAL;
2374                 goto back;
2375         }
2376
2377         error = bus_dmamap_load_mbuf(bd->mbuf_dma_tag, txbuf->tb_mbuf_dmamap,
2378                                      m, acx_buf_dma_addr, &paddr,
2379                                      BUS_DMA_NOWAIT);
2380         if (error && error != EFBIG) {
2381                 if_printf(&sc->sc_ic.ic_if, "can't map tx mbuf1 %d\n", error);
2382                 goto back;
2383         }
2384
2385         if (error) {    /* error == EFBIG */
2386                 struct mbuf *m_new;
2387
2388                 m_new = m_defrag(m, MB_DONTWAIT);
2389                 if (m_new == NULL) {
2390                         if_printf(&sc->sc_ic.ic_if, "can't defrag tx mbuf\n");
2391                         error = ENOBUFS;
2392                         goto back;
2393                 } else {
2394                         m = m_new;
2395                 }
2396
2397                 error = bus_dmamap_load_mbuf(bd->mbuf_dma_tag,
2398                                              txbuf->tb_mbuf_dmamap, m,
2399                                              acx_buf_dma_addr, &paddr,
2400                                              BUS_DMA_NOWAIT);
2401                 if (error) {
2402                         if_printf(&sc->sc_ic.ic_if, "can't map tx mbuf2 %d\n",
2403                                   error);
2404                         goto back;
2405                 }
2406         }
2407
2408         error = 0;
2409
2410         bus_dmamap_sync(bd->mbuf_dma_tag, txbuf->tb_mbuf_dmamap,
2411                         BUS_DMASYNC_PREWRITE);
2412
2413         txbuf->tb_mbuf = m;
2414         txbuf->tb_node = ni;
2415
2416         /*
2417          * TX buffers are accessed in following way:
2418          * acx_fw_txdesc -> acx_host_desc -> buffer
2419          *
2420          * It is quite strange that acx also querys acx_host_desc next to
2421          * the one we have assigned to acx_fw_txdesc even if first one's
2422          * acx_host_desc.h_data_len == acx_fw_txdesc.f_tx_len
2423          *
2424          * So we allocate two acx_host_desc for one acx_fw_txdesc and
2425          * assign the first acx_host_desc to acx_fw_txdesc
2426          *
2427          * For acx111
2428          * host_desc1.h_data_len = buffer_len
2429          * host_desc2.h_data_len = buffer_len - mac_header_len
2430          *
2431          * For acx100
2432          * host_desc1.h_data_len = mac_header_len
2433          * host_desc2.h_data_len = buffer_len - mac_header_len
2434          */
2435
2436         txbuf->tb_desc1->h_data_paddr = htole32(paddr);
2437         txbuf->tb_desc2->h_data_paddr = htole32(paddr + ACX_FRAME_HDRLEN);
2438
2439         txbuf->tb_desc1->h_data_len =
2440                 htole16(sc->chip_txdesc1_len ? sc->chip_txdesc1_len
2441                                              : m->m_pkthdr.len);
2442         txbuf->tb_desc2->h_data_len =
2443                 htole16(m->m_pkthdr.len - ACX_FRAME_HDRLEN);
2444
2445         /*
2446          * NOTE:
2447          * We can't simply assign f_tx_ctrl, we will first read it back
2448          * and change it bit by bit
2449          */
2450         ctrl = FW_TXDESC_GETFIELD_1(sc, txbuf, f_tx_ctrl);
2451         ctrl |= sc->chip_fw_txdesc_ctrl; /* extra chip specific flags */
2452         ctrl &= ~(DESC_CTRL_HOSTOWN | DESC_CTRL_ACXDONE);
2453
2454         FW_TXDESC_SETFIELD_2(sc, txbuf, f_tx_len, m->m_pkthdr.len);
2455         FW_TXDESC_SETFIELD_1(sc, txbuf, f_tx_error, 0);
2456         FW_TXDESC_SETFIELD_1(sc, txbuf, f_tx_data_nretry, 0);
2457         FW_TXDESC_SETFIELD_1(sc, txbuf, f_tx_rts_nretry, 0);
2458         FW_TXDESC_SETFIELD_1(sc, txbuf, f_tx_rts_ok, 0);
2459         rate = sc->chip_set_fw_txdesc_rate(sc, txbuf, ni, m->m_pkthdr.len);
2460
2461         if (sc->sc_drvbpf != NULL) {
2462                 struct ieee80211_frame_min *wh;
2463
2464                 wh = mtod(m, struct ieee80211_frame_min *);
2465                 sc->sc_tx_th.wt_flags = 0;
2466                 if (wh->i_fc[1] & IEEE80211_FC1_WEP)
2467                         sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
2468                 sc->sc_tx_th.wt_rate = rate;
2469
2470                 bpf_ptap(sc->sc_drvbpf, m, &sc->sc_tx_th, sc->sc_tx_th_len);
2471         }
2472
2473         txbuf->tb_desc1->h_ctrl = 0;
2474         txbuf->tb_desc2->h_ctrl = 0;
2475         bus_dmamap_sync(rd->tx_ring_dma_tag, rd->tx_ring_dmamap,
2476                         BUS_DMASYNC_PREWRITE);
2477
2478         FW_TXDESC_SETFIELD_1(sc, txbuf, f_tx_ctrl2, 0);
2479         FW_TXDESC_SETFIELD_1(sc, txbuf, f_tx_ctrl, ctrl);
2480
2481         /* Tell chip to inform us about TX completion */
2482         CSR_WRITE_2(sc, ACXREG_INTR_TRIG, ACXRV_TRIG_TX_FINI);
2483 back:
2484         if (error)
2485                 m_freem(m);
2486         return error;
2487 }
2488
2489 static int
2490 acx_set_null_tmplt(struct acx_softc *sc)
2491 {
2492         struct acx_tmplt_null_data n;
2493         struct ieee80211_frame *f;
2494
2495         bzero(&n, sizeof(n));
2496
2497         f = &n.data;
2498         f->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_DATA |
2499                      IEEE80211_FC0_SUBTYPE_NODATA;
2500         IEEE80211_ADDR_COPY(f->i_addr1, etherbroadcastaddr);
2501         IEEE80211_ADDR_COPY(f->i_addr2, IF_LLADDR(&sc->sc_ic.ic_if));
2502         IEEE80211_ADDR_COPY(f->i_addr3, etherbroadcastaddr);
2503
2504         return _acx_set_null_data_tmplt(sc, &n, sizeof(n));
2505 }
2506
2507 static int
2508 acx_set_probe_req_tmplt(struct acx_softc *sc, const char *ssid, int ssid_len)
2509 {
2510         struct acx_tmplt_probe_req req;
2511         struct ieee80211_frame *f;
2512         uint8_t *v;
2513         int vlen;
2514
2515         bzero(&req, sizeof(req));
2516
2517         f = &req.data.u_data.f;
2518         f->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
2519                      IEEE80211_FC0_SUBTYPE_PROBE_REQ;
2520         IEEE80211_ADDR_COPY(f->i_addr1, etherbroadcastaddr);
2521         IEEE80211_ADDR_COPY(f->i_addr2, IF_LLADDR(&sc->sc_ic.ic_if));
2522         IEEE80211_ADDR_COPY(f->i_addr3, etherbroadcastaddr);
2523
2524         v = req.data.u_data.var;
2525         v = ieee80211_add_ssid(v, ssid, ssid_len);
2526         v = ieee80211_add_rates(v, &sc->sc_ic.ic_sup_rates[sc->chip_phymode]);
2527         v = ieee80211_add_xrates(v, &sc->sc_ic.ic_sup_rates[sc->chip_phymode]);
2528         vlen = v - req.data.u_data.var;
2529
2530         return _acx_set_probe_req_tmplt(sc, &req,
2531                                         ACX_TMPLT_PROBE_REQ_SIZ(vlen));
2532 }
2533
2534 static int
2535 acx_set_probe_resp_tmplt(struct acx_softc *sc, struct ieee80211_node *ni)
2536 {
2537         struct ieee80211com *ic = &sc->sc_ic;
2538         struct acx_tmplt_probe_resp resp;
2539         struct ieee80211_frame *f;
2540         struct mbuf *m;
2541         int len;
2542
2543         m = ieee80211_probe_resp_alloc(ic, ni);
2544         if (m == NULL)
2545                 return 1;
2546         DPRINTF((&ic->ic_if, "%s alloc probe resp size %d\n", __func__,
2547                  m->m_pkthdr.len));
2548
2549         f = mtod(m, struct ieee80211_frame *);
2550         IEEE80211_ADDR_COPY(f->i_addr1, etherbroadcastaddr);
2551
2552         bzero(&resp, sizeof(resp));
2553         m_copydata(m, 0, m->m_pkthdr.len, (caddr_t)&resp.data);
2554         len = m->m_pkthdr.len + sizeof(resp.size);
2555         m_freem(m);
2556
2557         return _acx_set_probe_resp_tmplt(sc, &resp, len);
2558 }
2559
2560 static int
2561 acx_set_beacon_tmplt(struct acx_softc *sc, struct ieee80211_node *ni)
2562 {
2563         struct ieee80211com *ic = &sc->sc_ic;
2564         struct acx_tmplt_beacon beacon;
2565         struct acx_tmplt_tim tim;
2566         struct ieee80211_beacon_offsets bo;
2567         struct mbuf *m;
2568         int beacon_tmplt_len = 0, tim_tmplt_len = 0;
2569
2570         bzero(&bo, sizeof(bo));
2571         m = ieee80211_beacon_alloc(ic, ni, &bo);
2572         if (m == NULL)
2573                 return 1;
2574         DPRINTF((&ic->ic_if, "%s alloc beacon size %d\n", __func__,
2575                  m->m_pkthdr.len));
2576
2577         if (bo.bo_tim_len == 0) {
2578                 beacon_tmplt_len = m->m_pkthdr.len;
2579         } else {
2580                 beacon_tmplt_len = bo.bo_tim - mtod(m, uint8_t *);
2581                 tim_tmplt_len = m->m_pkthdr.len - beacon_tmplt_len;
2582         }
2583
2584         bzero(&beacon, sizeof(beacon));
2585         bzero(&tim, sizeof(tim));
2586
2587         m_copydata(m, 0, beacon_tmplt_len, (caddr_t)&beacon.data);
2588         if (tim_tmplt_len != 0) {
2589                 m_copydata(m, beacon_tmplt_len, tim_tmplt_len,
2590                            (caddr_t)&tim.data);
2591         }
2592         m_freem(m);
2593
2594         beacon_tmplt_len += sizeof(beacon.size);
2595         if (_acx_set_beacon_tmplt(sc, &beacon, beacon_tmplt_len) != 0)
2596                 return 1;
2597
2598         if (tim_tmplt_len != 0) {
2599                 tim_tmplt_len += sizeof(tim.size);
2600                 if (_acx_set_tim_tmplt(sc, &tim, tim_tmplt_len) != 0)
2601                         return 1;
2602         }
2603         return 0;
2604 }
2605
2606 static int
2607 acx_sysctl_msdu_lifetime(SYSCTL_HANDLER_ARGS)
2608 {
2609         struct acx_softc *sc = arg1;
2610         struct ifnet *ifp = &sc->sc_ic.ic_if;
2611         int error = 0, v;
2612
2613         lwkt_serialize_enter(ifp->if_serializer);
2614
2615         v = sc->sc_msdu_lifetime;
2616         error = sysctl_handle_int(oidp, &v, 0, req);
2617         if (error || req->newptr == NULL)
2618                 goto back;
2619         if (v <= 0) {
2620                 error = EINVAL;
2621                 goto back;
2622         }
2623
2624         if (sc->sc_flags & ACX_FLAG_FW_LOADED) {
2625                 struct acx_conf_msdu_lifetime msdu_lifetime;
2626
2627                 msdu_lifetime.lifetime = htole32(v);
2628                 if (acx_set_msdu_lifetime_conf(sc, &msdu_lifetime) != 0) {
2629                         if_printf(&sc->sc_ic.ic_if,
2630                                   "can't set MSDU lifetime\n");
2631                         error = ENXIO;
2632                         goto back;
2633                 }
2634         }
2635         sc->sc_msdu_lifetime = v;
2636 back:
2637         lwkt_serialize_exit(ifp->if_serializer);
2638         return error;
2639 }
2640
2641 static int
2642 acx_sysctl_free_firmware(SYSCTL_HANDLER_ARGS)
2643 {
2644         struct acx_softc *sc = arg1;
2645         struct ifnet *ifp = &sc->sc_ic.ic_if;
2646         int error = 0, v;
2647
2648         lwkt_serialize_enter(ifp->if_serializer);
2649
2650         v = 0;
2651         error = sysctl_handle_int(oidp, &v, 0, req);
2652         if (error || req->newptr == NULL)
2653                 goto back;
2654         if (v == 0)     /* Do nothing */
2655                 goto back;
2656
2657         acx_free_firmware(sc);
2658 back:
2659         lwkt_serialize_exit(ifp->if_serializer);
2660         return error;
2661 }
2662
2663 static int
2664 acx_media_change(struct ifnet *ifp)
2665 {
2666         int error;
2667
2668         error = ieee80211_media_change(ifp);
2669         if (error != ENETRESET)
2670                 return error;
2671
2672         if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
2673                 acx_init(ifp->if_softc);
2674         return 0;
2675 }
2676
2677 static int
2678 acx_rx_config(struct acx_softc *sc, int promisc)
2679 {
2680         struct acx_conf_rxopt rx_opt;
2681         struct ieee80211com *ic = &sc->sc_ic;
2682
2683         /*
2684          * What we want to receive and how to receive
2685          */
2686
2687         /* Common for all operational modes */
2688         rx_opt.opt1 = RXOPT1_INCL_RXBUF_HDR;
2689         rx_opt.opt2 = RXOPT2_RECV_ASSOC_REQ |
2690                       RXOPT2_RECV_AUTH |
2691                       RXOPT2_RECV_BEACON |
2692                       RXOPT2_RECV_CF |
2693                       RXOPT2_RECV_CTRL |
2694                       RXOPT2_RECV_DATA |
2695                       RXOPT2_RECV_MGMT |
2696                       RXOPT2_RECV_PROBE_REQ |
2697                       RXOPT2_RECV_PROBE_RESP |
2698                       RXOPT2_RECV_OTHER;
2699
2700         if (ic->ic_opmode == IEEE80211_M_MONITOR) {
2701                 rx_opt.opt1 |= RXOPT1_PROMISC;
2702                 rx_opt.opt2 |= RXOPT2_RECV_BROKEN | RXOPT2_RECV_ACK;
2703         } else {
2704                 rx_opt.opt1 |= promisc ? RXOPT1_PROMISC : RXOPT1_FILT_FDEST;
2705         }
2706
2707         if (acx_set_rxopt_conf(sc, &rx_opt) != 0) {
2708                 if_printf(&sc->sc_ic.ic_if, "can't config RX\n");
2709                 return ENXIO;
2710         }
2711         return 0;
2712 }
2713
2714 static int
2715 acx_set_chan(struct acx_softc *sc, struct ieee80211_channel *c)
2716 {
2717         struct ieee80211com *ic = &sc->sc_ic;
2718         uint16_t flags;
2719         uint8_t chan;
2720
2721         chan = ieee80211_chan2ieee(ic, c);
2722         DPRINTF((&ic->ic_if, "to chan %u\n", chan));
2723         if (acx_enable_txchan(sc, chan) != 0) {
2724                 if_printf(&ic->ic_if, "enable TX on channel %d failed\n", chan);
2725                 return EIO;
2726         }
2727         if (acx_enable_rxchan(sc, chan) != 0) {
2728                 if_printf(&ic->ic_if, "enable RX on channel %d failed\n", chan);
2729                 return EIO;
2730         }
2731
2732         if (IEEE80211_IS_CHAN_G(c))
2733                 flags = IEEE80211_CHAN_G;
2734         else
2735                 flags = IEEE80211_CHAN_B;
2736
2737         sc->sc_tx_th.wt_chan_freq = sc->sc_rx_th.wr_chan_freq =
2738                 htole16(c->ic_freq);
2739         sc->sc_tx_th.wt_chan_flags = sc->sc_rx_th.wr_chan_flags =
2740                 htole16(flags);
2741         return 0;
2742 }