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