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