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