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