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