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