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