wpi - Serialize interrupts, fixup mcluster allocation size, and cleanup
[dragonfly.git] / sys / dev / netif / wpi / if_wpi.c
1 /*-
2  * Copyright (c) 2006,2007
3  *      Damien Bergamini <damien.bergamini@free.fr>
4  *      Benjamin Close <Benjamin.Close@clearchain.com>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18
19 #define VERSION "20071127"
20
21
22 /*
23 __FBSDID("$FreeBSD: src/sys/dev/wpi/if_wpi.c,v 1.27.2.2 2010/02/14 09:34:27 gavin Exp $");
24 */
25
26 /*
27  * Driver for Intel PRO/Wireless 3945ABG 802.11 network adapters.
28  *
29  * The 3945ABG network adapter doesn't use traditional hardware as
30  * many other adaptors do. Instead at run time the eeprom is set into a known
31  * state and told to load boot firmware. The boot firmware loads an init and a
32  * main  binary firmware image into SRAM on the card via DMA.
33  * Once the firmware is loaded, the driver/hw then
34  * communicate by way of circular dma rings via the the SRAM to the firmware.
35  *
36  * There is 6 memory rings. 1 command ring, 1 rx data ring & 4 tx data rings.
37  * The 4 tx data rings allow for prioritization QoS.
38  *
39  * The rx data ring consists of 32 dma buffers. Two registers are used to
40  * indicate where in the ring the driver and the firmware are up to. The
41  * driver sets the initial read index (reg1) and the initial write index (reg2),
42  * the firmware updates the read index (reg1) on rx of a packet and fires an
43  * interrupt. The driver then processes the buffers starting at reg1 indicating
44  * to the firmware which buffers have been accessed by updating reg2. At the
45  * same time allocating new memory for the processed buffer.
46  *
47  * A similar thing happens with the tx rings. The difference is the firmware
48  * stop processing buffers once the queue is full and until confirmation
49  * of a successful transmition (tx_intr) has occurred.
50  *
51  * The command ring operates in the same manner as the tx queues.
52  *
53  * All communication direct to the card (ie eeprom) is classed as Stage1
54  * communication
55  *
56  * All communication via the firmware to the card is classed as State2.
57  * The firmware consists of 2 parts. A bootstrap firmware and a runtime
58  * firmware. The bootstrap firmware and runtime firmware are loaded
59  * from host memory via dma to the card then told to execute. From this point
60  * on the majority of communications between the driver and the card goes
61  * via the firmware.
62  */
63
64 #include <sys/param.h>
65 #include <sys/sysctl.h>
66 #include <sys/sockio.h>
67 #include <sys/mbuf.h>
68 #include <sys/kernel.h>
69 #include <sys/socket.h>
70 #include <sys/systm.h>
71 #include <sys/malloc.h>
72 #include <sys/queue.h>
73 #include <sys/taskqueue.h>
74 #include <sys/module.h>
75 #include <sys/bus.h>
76 #include <sys/endian.h>
77 #include <sys/linker.h>
78 #include <sys/firmware.h>
79
80 #include <sys/bus.h>
81 #include <sys/resource.h>
82 #include <sys/rman.h>
83
84 #include <bus/pci/pcireg.h>
85 #include <bus/pci/pcivar.h>
86
87 #include <net/bpf.h>
88 #include <net/if.h>
89 #include <net/if_arp.h>
90 #include <net/ifq_var.h>
91 #include <net/ethernet.h>
92 #include <net/if_dl.h>
93 #include <net/if_media.h>
94 #include <net/if_types.h>
95
96 #include <netproto/802_11/ieee80211_var.h>
97 #include <netproto/802_11/ieee80211_radiotap.h>
98 #include <netproto/802_11/ieee80211_regdomain.h>
99 #include <netproto/802_11/ieee80211_ratectl.h>
100
101 #include <netinet/in.h>
102 #include <netinet/in_systm.h>
103 #include <netinet/in_var.h>
104 #include <netinet/ip.h>
105 #include <netinet/if_ether.h>
106
107 /* XXX: move elsewhere */
108 #define abs(x) (((x) < 0) ? -(x) : (x))
109
110 #include "if_wpireg.h"
111 #include "if_wpivar.h"
112
113 #define WPI_DEBUG
114
115 #ifdef WPI_DEBUG
116 #define DPRINTF(x)      do { if (wpi_debug != 0) kprintf x; } while (0)
117 #define DPRINTFN(n, x)  do { if (wpi_debug & n) kprintf x; } while (0)
118 #define WPI_DEBUG_SET   (wpi_debug != 0)
119
120 enum {
121         WPI_DEBUG_UNUSED        = 0x00000001,   /* Unused */
122         WPI_DEBUG_HW            = 0x00000002,   /* Stage 1 (eeprom) debugging */
123         WPI_DEBUG_TX            = 0x00000004,   /* Stage 2 TX intrp debugging*/
124         WPI_DEBUG_RX            = 0x00000008,   /* Stage 2 RX intrp debugging */
125         WPI_DEBUG_CMD           = 0x00000010,   /* Stage 2 CMD intrp debugging*/
126         WPI_DEBUG_FIRMWARE      = 0x00000020,   /* firmware(9) loading debug  */
127         WPI_DEBUG_DMA           = 0x00000040,   /* DMA (de)allocations/syncs  */
128         WPI_DEBUG_SCANNING      = 0x00000080,   /* Stage 2 Scanning debugging */
129         WPI_DEBUG_NOTIFY        = 0x00000100,   /* State 2 Noftif intr debug */
130         WPI_DEBUG_TEMP          = 0x00000200,   /* TXPower/Temp Calibration */
131         WPI_DEBUG_OPS           = 0x00000400,   /* wpi_ops taskq debug */
132         WPI_DEBUG_WATCHDOG      = 0x00000800,   /* Watch dog debug */
133         WPI_DEBUG_ANY           = 0xffffffff
134 };
135
136 static int wpi_debug = 1;
137 SYSCTL_INT(_debug, OID_AUTO, wpi, CTLFLAG_RW, &wpi_debug, 0, "wpi debug level");
138 TUNABLE_INT("debug.wpi", &wpi_debug);
139
140 #else
141 #define DPRINTF(x)
142 #define DPRINTFN(n, x)
143 #define WPI_DEBUG_SET   0
144 #endif
145
146 struct wpi_ident {
147         uint16_t        vendor;
148         uint16_t        device;
149         uint16_t        subdevice;
150         const char      *name;
151 };
152
153 static const struct wpi_ident wpi_ident_table[] = {
154         /* The below entries support ABG regardless of the subid */
155         { 0x8086, 0x4222,    0x0, "Intel(R) PRO/Wireless 3945ABG" },
156         { 0x8086, 0x4227,    0x0, "Intel(R) PRO/Wireless 3945ABG" },
157         /* The below entries only support BG */
158         { 0x8086, 0x4222, 0x1005, "Intel(R) PRO/Wireless 3945BG"  },
159         { 0x8086, 0x4222, 0x1034, "Intel(R) PRO/Wireless 3945BG"  },
160         { 0x8086, 0x4227, 0x1014, "Intel(R) PRO/Wireless 3945BG"  },
161         { 0x8086, 0x4222, 0x1044, "Intel(R) PRO/Wireless 3945BG"  },
162         { 0, 0, 0, NULL }
163 };
164
165 static struct ieee80211vap *wpi_vap_create(struct ieee80211com *,
166                     const char name[IFNAMSIZ], int unit, int opmode,
167                     int flags, const uint8_t bssid[IEEE80211_ADDR_LEN],
168                     const uint8_t mac[IEEE80211_ADDR_LEN]);
169 static void     wpi_vap_delete(struct ieee80211vap *);
170 static int      wpi_dma_contig_alloc(struct wpi_softc *, struct wpi_dma_info *,
171                     void **, bus_size_t, bus_size_t, int);
172 static void     wpi_dma_contig_free(struct wpi_dma_info *);
173 static void     wpi_dma_map_addr(void *, bus_dma_segment_t *, int, int);
174 static int      wpi_alloc_shared(struct wpi_softc *);
175 static void     wpi_free_shared(struct wpi_softc *);
176 static int      wpi_alloc_rx_ring(struct wpi_softc *, struct wpi_rx_ring *);
177 static void     wpi_reset_rx_ring(struct wpi_softc *, struct wpi_rx_ring *);
178 static void     wpi_free_rx_ring(struct wpi_softc *, struct wpi_rx_ring *);
179 static int      wpi_alloc_tx_ring(struct wpi_softc *, struct wpi_tx_ring *,
180                     int, int);
181 static void     wpi_reset_tx_ring(struct wpi_softc *, struct wpi_tx_ring *);
182 static void     wpi_free_tx_ring(struct wpi_softc *, struct wpi_tx_ring *);
183 static struct ieee80211_node *wpi_node_alloc(struct ieee80211vap *,
184                             const uint8_t mac[IEEE80211_ADDR_LEN]);
185 static int      wpi_newstate(struct ieee80211vap *, enum ieee80211_state, int);
186 static void     wpi_mem_lock(struct wpi_softc *);
187 static void     wpi_mem_unlock(struct wpi_softc *);
188 static uint32_t wpi_mem_read(struct wpi_softc *, uint16_t);
189 static void     wpi_mem_write(struct wpi_softc *, uint16_t, uint32_t);
190 static void     wpi_mem_write_region_4(struct wpi_softc *, uint16_t,
191                     const uint32_t *, int);
192 static uint16_t wpi_read_prom_data(struct wpi_softc *, uint32_t, void *, int);
193 static int      wpi_alloc_fwmem(struct wpi_softc *);
194 static void     wpi_free_fwmem(struct wpi_softc *);
195 static int      wpi_load_firmware(struct wpi_softc *);
196 static void     wpi_unload_firmware(struct wpi_softc *);
197 static int      wpi_load_microcode(struct wpi_softc *, const uint8_t *, int);
198 static void     wpi_rx_intr(struct wpi_softc *, struct wpi_rx_desc *,
199                     struct wpi_rx_data *);
200 static void     wpi_tx_intr(struct wpi_softc *, struct wpi_rx_desc *);
201 static void     wpi_cmd_intr(struct wpi_softc *, struct wpi_rx_desc *);
202 static void     wpi_notif_intr(struct wpi_softc *);
203 static void     wpi_intr(void *);
204 static uint8_t  wpi_plcp_signal(int);
205 static void     wpi_watchdog(void *);
206 static int      wpi_tx_data(struct wpi_softc *, struct mbuf *,
207                     struct ieee80211_node *, int);
208 static void     wpi_start(struct ifnet *);
209 static void     wpi_start_locked(struct ifnet *);
210 static int      wpi_raw_xmit(struct ieee80211_node *, struct mbuf *,
211                     const struct ieee80211_bpf_params *);
212 static void     wpi_scan_start(struct ieee80211com *);
213 static void     wpi_scan_end(struct ieee80211com *);
214 static void     wpi_set_channel(struct ieee80211com *);
215 static void     wpi_scan_curchan(struct ieee80211_scan_state *, unsigned long);
216 static void     wpi_scan_mindwell(struct ieee80211_scan_state *);
217 static int      wpi_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
218 static void     wpi_read_eeprom(struct wpi_softc *,
219                     uint8_t macaddr[IEEE80211_ADDR_LEN]);
220 static void     wpi_read_eeprom_channels(struct wpi_softc *, int);
221 static void     wpi_read_eeprom_group(struct wpi_softc *, int);
222 static int      wpi_cmd(struct wpi_softc *, int, const void *, int, int);
223 static int      wpi_wme_update(struct ieee80211com *);
224 static int      wpi_mrr_setup(struct wpi_softc *);
225 static void     wpi_set_led(struct wpi_softc *, uint8_t, uint8_t, uint8_t);
226 static void     wpi_enable_tsf(struct wpi_softc *, struct ieee80211_node *);
227 #if 0
228 static int      wpi_setup_beacon(struct wpi_softc *, struct ieee80211_node *);
229 #endif
230 static int      wpi_auth(struct wpi_softc *, struct ieee80211vap *);
231 static int      wpi_run(struct wpi_softc *, struct ieee80211vap *);
232 static int      wpi_scan(struct wpi_softc *);
233 static int      wpi_config(struct wpi_softc *);
234 static void     wpi_stop_master(struct wpi_softc *);
235 static int      wpi_power_up(struct wpi_softc *);
236 static int      wpi_reset(struct wpi_softc *);
237 static void     wpi_hwreset(void *, int);
238 static void     wpi_rfreset(void *, int);
239 static void     wpi_hw_config(struct wpi_softc *);
240 static void     wpi_init(void *);
241 static void     wpi_init_locked(struct wpi_softc *, int);
242 static void     wpi_stop(struct wpi_softc *);
243 static void     wpi_stop_locked(struct wpi_softc *);
244
245 static void     wpi_newassoc(struct ieee80211_node *, int);
246 static int      wpi_set_txpower(struct wpi_softc *, struct ieee80211_channel *,
247                     int);
248 static void     wpi_calib_timeout(void *);
249 static void     wpi_power_calibration(struct wpi_softc *, int);
250 static int      wpi_get_power_index(struct wpi_softc *,
251                     struct wpi_power_group *, struct ieee80211_channel *, int);
252 #ifdef WPI_DEBUG
253 static const char *wpi_cmd_str(int);
254 #endif
255 static int wpi_probe(device_t);
256 static int wpi_attach(device_t);
257 static int wpi_detach(device_t);
258 static int wpi_shutdown(device_t);
259 static int wpi_suspend(device_t);
260 static int wpi_resume(device_t);
261
262
263 static device_method_t wpi_methods[] = {
264         /* Device interface */
265         DEVMETHOD(device_probe,         wpi_probe),
266         DEVMETHOD(device_attach,        wpi_attach),
267         DEVMETHOD(device_detach,        wpi_detach),
268         DEVMETHOD(device_shutdown,      wpi_shutdown),
269         DEVMETHOD(device_suspend,       wpi_suspend),
270         DEVMETHOD(device_resume,        wpi_resume),
271
272         { 0, 0 }
273 };
274
275 static driver_t wpi_driver = {
276         "wpi",
277         wpi_methods,
278         sizeof (struct wpi_softc)
279 };
280
281 static devclass_t wpi_devclass;
282
283 DRIVER_MODULE(wpi, pci, wpi_driver, wpi_devclass, 0, 0);
284
285 static const uint8_t wpi_ridx_to_plcp[] = {
286         /* OFDM: IEEE Std 802.11a-1999, pp. 14 Table 80 */
287         /* R1-R4 (ral/ural is R4-R1) */
288         0xd, 0xf, 0x5, 0x7, 0x9, 0xb, 0x1, 0x3,
289         /* CCK: device-dependent */
290         10, 20, 55, 110
291 };
292 static const uint8_t wpi_ridx_to_rate[] = {
293         12, 18, 24, 36, 48, 72, 96, 108, /* OFDM */
294         2, 4, 11, 22 /*CCK */
295 };
296
297
298 static int
299 wpi_probe(device_t dev)
300 {
301         const struct wpi_ident *ident;
302
303         for (ident = wpi_ident_table; ident->name != NULL; ident++) {
304                 if (pci_get_vendor(dev) == ident->vendor &&
305                     pci_get_device(dev) == ident->device) {
306                         device_set_desc(dev, ident->name);
307                         return 0;
308                 }
309         }
310         return ENXIO;
311 }
312
313 /**
314  * Load the firmare image from disk to the allocated dma buffer.
315  * we also maintain the reference to the firmware pointer as there
316  * is times where we may need to reload the firmware but we are not
317  * in a context that can access the filesystem (ie taskq cause by restart)
318  *
319  * @return 0 on success, an errno on failure
320  */
321 static int
322 wpi_load_firmware(struct wpi_softc *sc)
323 {
324         const struct firmware *fp;
325         struct wpi_dma_info *dma = &sc->fw_dma;
326         const struct wpi_firmware_hdr *hdr;
327 #if 0
328         struct ifnet *ifp;
329 #endif
330         const uint8_t *itext, *idata, *rtext, *rdata, *btext;
331         uint32_t itextsz, idatasz, rtextsz, rdatasz, btextsz;
332         int error;
333
334 #if 0
335         ifp = sc->sc_ifp;
336 #endif
337         DPRINTFN(WPI_DEBUG_FIRMWARE,
338             ("Attempting Loading Firmware from wpi_fw module\n"));
339
340         WPI_UNLOCK(sc);
341
342 #if 0
343         lwkt_serialize_exit(ifp->if_serializer);
344 #endif
345
346 #if 0
347         if ((img = firmware_image_load("", dma->tag)) == NULL) {
348                 error = ENOENT;
349                 lwkt_serialize_enter(ifp->if_serializer);
350                 goto fail;
351         }
352 #endif
353
354
355         if (sc->fw_fp == NULL && (sc->fw_fp = firmware_get("wpifw")) == NULL) {
356                 device_printf(sc->sc_dev,
357                     "could not load firmware image 'wpifw_fw'\n");
358                 error = ENOENT;
359                 WPI_LOCK(sc);
360 #if 0
361                 lwkt_serialize_enter(ifp->if_serializer);
362 #endif
363                 goto fail;
364         }
365
366         fp = sc->fw_fp;
367
368 #if 0
369         lwkt_serialize_enter(ifp->if_serializer);
370 #endif
371         WPI_LOCK(sc);
372
373
374         /* Validate the firmware is minimum a particular version */
375         if (fp->version < WPI_FW_MINVERSION) {
376             device_printf(sc->sc_dev,
377                            "firmware version is too old. Need %d, got %d\n",
378                            WPI_FW_MINVERSION,
379                            fp->version);
380             error = ENXIO;
381             goto fail;
382         }
383 #if 0
384 #endif
385
386         if (fp->datasize < sizeof (struct wpi_firmware_hdr)) {
387                 device_printf(sc->sc_dev,
388                     "firmware file too short: %zu bytes\n", fp->datasize);
389                 error = ENXIO;
390                 goto fail;
391         }
392
393         hdr = (const struct wpi_firmware_hdr *)fp->data;
394
395         /*     |  RUNTIME FIRMWARE   |    INIT FIRMWARE    | BOOT FW  |
396            |HDR|<--TEXT-->|<--DATA-->|<--TEXT-->|<--DATA-->|<--TEXT-->| */
397
398         rtextsz = le32toh(hdr->rtextsz);
399         rdatasz = le32toh(hdr->rdatasz);
400         itextsz = le32toh(hdr->itextsz);
401         idatasz = le32toh(hdr->idatasz);
402         btextsz = le32toh(hdr->btextsz);
403
404         /* check that all firmware segments are present */
405         if (fp->datasize < sizeof (struct wpi_firmware_hdr) +
406                 rtextsz + rdatasz + itextsz + idatasz + btextsz) {
407                 device_printf(sc->sc_dev,
408                     "firmware file too short: %zu bytes\n", fp->datasize);
409                 error = ENXIO; /* XXX appropriate error code? */
410                 goto fail;
411         }
412
413         /* get pointers to firmware segments */
414         rtext = (const uint8_t *)(hdr + 1);
415         rdata = rtext + rtextsz;
416         itext = rdata + rdatasz;
417         idata = itext + itextsz;
418         btext = idata + idatasz;
419
420         DPRINTFN(WPI_DEBUG_FIRMWARE,
421             ("Firmware Version: Major %d, Minor %d, Driver %d, \n"
422              "runtime (text: %u, data: %u) init (text: %u, data %u) boot (text %u)\n",
423              (le32toh(hdr->version) & 0xff000000) >> 24,
424              (le32toh(hdr->version) & 0x00ff0000) >> 16,
425              (le32toh(hdr->version) & 0x0000ffff),
426              rtextsz, rdatasz,
427              itextsz, idatasz, btextsz));
428
429         DPRINTFN(WPI_DEBUG_FIRMWARE,("rtext 0x%x\n", *(const uint32_t *)rtext));
430         DPRINTFN(WPI_DEBUG_FIRMWARE,("rdata 0x%x\n", *(const uint32_t *)rdata));
431         DPRINTFN(WPI_DEBUG_FIRMWARE,("itext 0x%x\n", *(const uint32_t *)itext));
432         DPRINTFN(WPI_DEBUG_FIRMWARE,("idata 0x%x\n", *(const uint32_t *)idata));
433         DPRINTFN(WPI_DEBUG_FIRMWARE,("btext 0x%x\n", *(const uint32_t *)btext));
434
435         /* sanity checks */
436         if (rtextsz > WPI_FW_MAIN_TEXT_MAXSZ ||
437             rdatasz > WPI_FW_MAIN_DATA_MAXSZ ||
438             itextsz > WPI_FW_INIT_TEXT_MAXSZ ||
439             idatasz > WPI_FW_INIT_DATA_MAXSZ ||
440             btextsz > WPI_FW_BOOT_TEXT_MAXSZ ||
441             (btextsz & 3) != 0) {
442                 device_printf(sc->sc_dev, "firmware invalid\n");
443                 error = EINVAL;
444                 goto fail;
445         }
446
447         /* copy initialization images into pre-allocated DMA-safe memory */
448         memcpy(dma->vaddr, idata, idatasz);
449         memcpy(dma->vaddr + WPI_FW_INIT_DATA_MAXSZ, itext, itextsz);
450
451         bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
452
453         /* tell adapter where to find initialization images */
454         wpi_mem_lock(sc);
455         wpi_mem_write(sc, WPI_MEM_DATA_BASE, dma->paddr);
456         wpi_mem_write(sc, WPI_MEM_DATA_SIZE, idatasz);
457         wpi_mem_write(sc, WPI_MEM_TEXT_BASE,
458             dma->paddr + WPI_FW_INIT_DATA_MAXSZ);
459         wpi_mem_write(sc, WPI_MEM_TEXT_SIZE, itextsz);
460         wpi_mem_unlock(sc);
461
462         /* load firmware boot code */
463         if ((error = wpi_load_microcode(sc, btext, btextsz)) != 0) {
464             device_printf(sc->sc_dev, "Failed to load microcode\n");
465             goto fail;
466         }
467
468         /* now press "execute" */
469         WPI_WRITE(sc, WPI_RESET, 0);
470
471         /* wait at most one second for the first alive notification */
472         if ((error = lksleep(sc, &sc->sc_lock, 0, "wpiinit", hz)) != 0) {
473                 device_printf(sc->sc_dev,
474                     "timeout waiting for adapter to initialize\n");
475                 goto fail;
476         }
477
478         /* copy runtime images into pre-allocated DMA-sage memory */
479         memcpy(dma->vaddr, rdata, rdatasz);
480         memcpy(dma->vaddr + WPI_FW_MAIN_DATA_MAXSZ, rtext, rtextsz);
481         bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
482
483         /* tell adapter where to find runtime images */
484         wpi_mem_lock(sc);
485         wpi_mem_write(sc, WPI_MEM_DATA_BASE, dma->paddr);
486         wpi_mem_write(sc, WPI_MEM_DATA_SIZE, rdatasz);
487         wpi_mem_write(sc, WPI_MEM_TEXT_BASE,
488             dma->paddr + WPI_FW_MAIN_DATA_MAXSZ);
489         wpi_mem_write(sc, WPI_MEM_TEXT_SIZE, WPI_FW_UPDATED | rtextsz);
490         wpi_mem_unlock(sc);
491
492         /* wait at most one second for the first alive notification */
493         if ((error = lksleep(sc, &sc->sc_lock, 0, "wpiinit", hz)) != 0) {
494                 device_printf(sc->sc_dev,
495                     "timeout waiting for adapter to initialize2\n");
496                 goto fail;
497         }
498
499         DPRINTFN(WPI_DEBUG_FIRMWARE,
500             ("Firmware loaded to driver successfully\n"));
501 /*
502         sc->sc_fw_image = img;
503 */
504         return error;
505 fail:
506         wpi_unload_firmware(sc);
507         return error;
508 }
509
510 /**
511  * Free the referenced firmware image
512  */
513 static void
514 wpi_unload_firmware(struct wpi_softc *sc)
515 {
516         struct ifnet *ifp;
517         ifp = sc->sc_ifp;
518
519         if (sc->fw_fp) {
520                 WPI_UNLOCK(sc);
521 #if 0
522                 lwkt_serialize_exit(ifp->if_serializer);
523 #endif
524                 firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
525 #if 0
526                 firmware_image_unload(sc->sc_fw_image);
527 #endif
528 #if 0
529                 lwkt_serialize_enter(ifp->if_serializer);
530 #endif
531                 WPI_LOCK(sc);
532                 sc->fw_fp = NULL;
533         }
534 }
535
536 static int
537 wpi_attach(device_t dev)
538 {
539         struct wpi_softc *sc = device_get_softc(dev);
540         struct ifnet *ifp;
541         struct ieee80211com *ic;
542         int ac, error, supportsa = 1;
543         uint32_t tmp;
544         const struct wpi_ident *ident;
545         uint8_t macaddr[IEEE80211_ADDR_LEN];
546
547         sc->sc_dev = dev;
548
549         if (bootverbose || WPI_DEBUG_SET)
550             device_printf(sc->sc_dev,"Driver Revision %s\n", VERSION);
551
552         /*
553          * Some card's only support 802.11b/g not a, check to see if
554          * this is one such card. A 0x0 in the subdevice table indicates
555          * the entire subdevice range is to be ignored.
556          */
557         for (ident = wpi_ident_table; ident->name != NULL; ident++) {
558                 if (ident->subdevice &&
559                     pci_get_subdevice(dev) == ident->subdevice) {
560                     supportsa = 0;
561                     break;
562                 }
563         }
564
565         /* Create the tasks that can be queued */
566         TASK_INIT(&sc->sc_restarttask, 0, wpi_hwreset, sc);
567         TASK_INIT(&sc->sc_radiotask, 0, wpi_rfreset, sc);
568
569         WPI_LOCK_INIT(sc);
570
571         callout_init(&sc->calib_to);
572         callout_init(&sc->watchdog_to);
573
574         if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
575                 device_printf(dev, "chip is in D%d power mode "
576                     "-- setting to D0\n", pci_get_powerstate(dev));
577                 pci_set_powerstate(dev, PCI_POWERSTATE_D0);
578         }
579
580         /* disable the retry timeout register */
581         pci_write_config(dev, 0x41, 0, 1);
582
583         /* enable bus-mastering */
584         pci_enable_busmaster(dev);
585
586         sc->mem_rid = PCIR_BAR(0);
587         sc->mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &sc->mem_rid,
588             RF_ACTIVE);
589         if (sc->mem == NULL) {
590                 device_printf(dev, "could not allocate memory resource\n");
591                 error = ENOMEM;
592                 goto fail;
593         }
594
595         sc->sc_st = rman_get_bustag(sc->mem);
596         sc->sc_sh = rman_get_bushandle(sc->mem);
597
598         sc->irq_rid = 0;
599         sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->irq_rid,
600             RF_ACTIVE | RF_SHAREABLE);
601         if (sc->irq == NULL) {
602                 device_printf(dev, "could not allocate interrupt resource\n");
603                 error = ENOMEM;
604                 goto fail;
605         }
606
607         /*
608          * Allocate DMA memory for firmware transfers.
609          */
610         if ((error = wpi_alloc_fwmem(sc)) != 0) {
611                 kprintf(": could not allocate firmware memory\n");
612                 error = ENOMEM;
613                 goto fail;
614         }
615
616         /*
617          * Put adapter into a known state.
618          */
619         if ((error = wpi_reset(sc)) != 0) {
620                 device_printf(dev, "could not reset adapter\n");
621                 goto fail;
622         }
623
624         wpi_mem_lock(sc);
625         tmp = wpi_mem_read(sc, WPI_MEM_PCIDEV);
626         if (bootverbose || WPI_DEBUG_SET)
627             device_printf(sc->sc_dev, "Hardware Revision (0x%X)\n", tmp);
628
629         wpi_mem_unlock(sc);
630
631         /* Allocate shared page */
632         if ((error = wpi_alloc_shared(sc)) != 0) {
633                 device_printf(dev, "could not allocate shared page\n");
634                 goto fail;
635         }
636
637         /* tx data queues  - 4 for QoS purposes */
638         for (ac = 0; ac < WME_NUM_AC; ac++) {
639                 error = wpi_alloc_tx_ring(sc, &sc->txq[ac], WPI_TX_RING_COUNT, ac);
640                 if (error != 0) {
641                     device_printf(dev, "could not allocate Tx ring %d\n",ac);
642                     goto fail;
643                 }
644         }
645
646         /* command queue to talk to the card's firmware */
647         error = wpi_alloc_tx_ring(sc, &sc->cmdq, WPI_CMD_RING_COUNT, 4);
648         if (error != 0) {
649                 device_printf(dev, "could not allocate command ring\n");
650                 goto fail;
651         }
652
653         /* receive data queue */
654         error = wpi_alloc_rx_ring(sc, &sc->rxq);
655         if (error != 0) {
656                 device_printf(dev, "could not allocate Rx ring\n");
657                 goto fail;
658         }
659
660         ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
661         if (ifp == NULL) {
662                 device_printf(dev, "can not if_alloc()\n");
663                 error = ENOMEM;
664                 goto fail;
665         }
666         ic = ifp->if_l2com;
667
668         ic->ic_ifp = ifp;
669         ic->ic_phytype = IEEE80211_T_OFDM;      /* not only, but not used */
670         ic->ic_opmode = IEEE80211_M_STA;        /* default to BSS mode */
671
672         /* set device capabilities */
673         ic->ic_caps =
674                   IEEE80211_C_STA               /* station mode supported */
675                 | IEEE80211_C_MONITOR           /* monitor mode supported */
676                 | IEEE80211_C_TXPMGT            /* tx power management */
677                 | IEEE80211_C_SHSLOT            /* short slot time supported */
678                 | IEEE80211_C_SHPREAMBLE        /* short preamble supported */
679                 | IEEE80211_C_WPA               /* 802.11i */
680 /* XXX looks like WME is partly supported? */
681 #if 0
682                 | IEEE80211_C_IBSS              /* IBSS mode support */
683                 | IEEE80211_C_BGSCAN            /* capable of bg scanning */
684                 | IEEE80211_C_WME               /* 802.11e */
685                 | IEEE80211_C_HOSTAP            /* Host access point mode */
686 #endif
687                 ;
688
689         /*
690          * Read in the eeprom and also setup the channels for
691          * net80211. We don't set the rates as net80211 does this for us
692          */
693         wpi_read_eeprom(sc, macaddr);
694
695         if (bootverbose || WPI_DEBUG_SET) {
696             device_printf(sc->sc_dev, "Regulatory Domain: %.4s\n", sc->domain);
697             device_printf(sc->sc_dev, "Hardware Type: %c\n",
698                           sc->type > 1 ? 'B': '?');
699             device_printf(sc->sc_dev, "Hardware Revision: %c\n",
700                           ((le16toh(sc->rev) & 0xf0) == 0xd0) ? 'D': '?');
701             device_printf(sc->sc_dev, "SKU %s support 802.11a\n",
702                           supportsa ? "does" : "does not");
703
704             /* XXX hw_config uses the PCIDEV for the Hardware rev. Must check
705                what sc->rev really represents - benjsc 20070615 */
706         }
707
708         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
709         ifp->if_softc = sc;
710         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
711         ifp->if_init = wpi_init;
712         ifp->if_ioctl = wpi_ioctl;
713         ifp->if_start = wpi_start;
714         ifq_set_maxlen(&ifp->if_snd, IFQ_MAXLEN);
715         ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
716         ifq_set_ready(&ifp->if_snd);
717
718         ieee80211_ifattach(ic, macaddr);
719         /* override default methods */
720         ic->ic_node_alloc = wpi_node_alloc;
721         ic->ic_newassoc = wpi_newassoc;
722         ic->ic_raw_xmit = wpi_raw_xmit;
723         ic->ic_wme.wme_update = wpi_wme_update;
724         ic->ic_scan_start = wpi_scan_start;
725         ic->ic_scan_end = wpi_scan_end;
726         ic->ic_set_channel = wpi_set_channel;
727         ic->ic_scan_curchan = wpi_scan_curchan;
728         ic->ic_scan_mindwell = wpi_scan_mindwell;
729
730         ic->ic_vap_create = wpi_vap_create;
731         ic->ic_vap_delete = wpi_vap_delete;
732
733         ieee80211_radiotap_attach(ic,
734             &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap),
735                 WPI_TX_RADIOTAP_PRESENT,
736             &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
737                 WPI_RX_RADIOTAP_PRESENT);
738
739         /*
740          * Hook our interrupt after all initialization is complete.
741          */
742         error = bus_setup_intr(dev, sc->irq, INTR_MPSAFE,
743             wpi_intr, sc, &sc->sc_ih, ifp->if_serializer);
744         if (error != 0) {
745                 device_printf(dev, "could not set up interrupt\n");
746                 goto fail;
747         }
748
749         if (bootverbose)
750                 ieee80211_announce(ic);
751 #ifdef XXX_DEBUG
752         ieee80211_announce_channels(ic);
753 #endif
754         return 0;
755
756 fail:   wpi_detach(dev);
757         return ENXIO;
758 }
759
760 static int
761 wpi_detach(device_t dev)
762 {
763         struct wpi_softc *sc = device_get_softc(dev);
764         struct ifnet *ifp = sc->sc_ifp;
765         struct ieee80211com *ic;
766         int ac;
767
768         if (ifp != NULL) {
769                 ic = ifp->if_l2com;
770
771                 ieee80211_draintask(ic, &sc->sc_restarttask);
772                 ieee80211_draintask(ic, &sc->sc_radiotask);
773                 wpi_stop(sc);
774                 callout_stop(&sc->watchdog_to);
775                 callout_stop(&sc->calib_to);
776                 ieee80211_ifdetach(ic);
777         }
778
779         WPI_LOCK(sc);
780         if (sc->txq[0].data_dmat) {
781                 for (ac = 0; ac < WME_NUM_AC; ac++)
782                         wpi_free_tx_ring(sc, &sc->txq[ac]);
783
784                 wpi_free_tx_ring(sc, &sc->cmdq);
785                 wpi_free_rx_ring(sc, &sc->rxq);
786                 wpi_free_shared(sc);
787         }
788
789         if (sc->fw_fp != NULL) {
790                 wpi_unload_firmware(sc);
791         }
792
793         if (sc->fw_dma.tag)
794                 wpi_free_fwmem(sc);
795         WPI_UNLOCK(sc);
796
797         if (sc->irq != NULL) {
798                 bus_teardown_intr(dev, sc->irq, sc->sc_ih);
799                 bus_release_resource(dev, SYS_RES_IRQ, sc->irq_rid, sc->irq);
800         }
801
802         if (sc->mem != NULL)
803                 bus_release_resource(dev, SYS_RES_MEMORY, sc->mem_rid, sc->mem);
804
805         if (ifp != NULL)
806                 if_free(ifp);
807
808         WPI_LOCK_DESTROY(sc);
809
810         return 0;
811 }
812
813 static struct ieee80211vap *
814 wpi_vap_create(struct ieee80211com *ic,
815         const char name[IFNAMSIZ], int unit, int opmode, int flags,
816         const uint8_t bssid[IEEE80211_ADDR_LEN],
817         const uint8_t mac[IEEE80211_ADDR_LEN])
818 {
819         struct wpi_vap *wvp;
820         struct ieee80211vap *vap;
821
822         if (!TAILQ_EMPTY(&ic->ic_vaps))         /* only one at a time */
823                 return NULL;
824         wvp = (struct wpi_vap *) kmalloc(sizeof(struct wpi_vap),
825             M_80211_VAP, M_NOWAIT | M_ZERO);
826         if (wvp == NULL)
827                 return NULL;
828         vap = &wvp->vap;
829         ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid, mac);
830         /* override with driver methods */
831         wvp->newstate = vap->iv_newstate;
832         vap->iv_newstate = wpi_newstate;
833
834         ieee80211_ratectl_init(vap);
835
836         /* complete setup */
837         ieee80211_vap_attach(vap, ieee80211_media_change, ieee80211_media_status);
838         ic->ic_opmode = opmode;
839         return vap;
840 }
841
842 static void
843 wpi_vap_delete(struct ieee80211vap *vap)
844 {
845         struct wpi_vap *wvp = WPI_VAP(vap);
846
847         ieee80211_ratectl_deinit(vap);
848         ieee80211_vap_detach(vap);
849         kfree(wvp, M_80211_VAP);
850 }
851
852 static void
853 wpi_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
854 {
855         if (error != 0)
856                 return;
857
858         KASSERT(nsegs == 1, ("too many DMA segments, %d should be 1", nsegs));
859
860         *(bus_addr_t *)arg = segs[0].ds_addr;
861 }
862
863 /*
864  * Allocates a contiguous block of dma memory of the requested size and
865  * alignment. Due to limitations of the FreeBSD dma subsystem as of 20071217,
866  * allocations greater than 4096 may fail. Hence if the requested alignment is
867  * greater we allocate 'alignment' size extra memory and shift the vaddr and
868  * paddr after the dma load. This bypasses the problem at the cost of a little
869  * more memory.
870  */
871 static int
872 wpi_dma_contig_alloc(struct wpi_softc *sc, struct wpi_dma_info *dma,
873     void **kvap, bus_size_t size, bus_size_t alignment, int flags)
874 {
875         int error;
876         bus_size_t align;
877         bus_size_t reqsize;
878
879         DPRINTFN(WPI_DEBUG_DMA,
880             ("Size: %zd - alignment %zd\n", size, alignment));
881
882         dma->size = size;
883         dma->tag = NULL;
884
885         if (alignment > 4096) {
886                 align = PAGE_SIZE;
887                 reqsize = size + alignment;
888         } else {
889                 align = alignment;
890                 reqsize = size;
891         }
892         error = bus_dma_tag_create(dma->tag, align,
893             0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR,
894             NULL, NULL, reqsize,
895             1, reqsize, flags,
896             &dma->tag);
897         if (error != 0) {
898                 device_printf(sc->sc_dev,
899                     "could not create shared page DMA tag\n");
900                 goto fail;
901         }
902         error = bus_dmamem_alloc(dma->tag, (void **)&dma->vaddr_start,
903             flags | BUS_DMA_ZERO, &dma->map);
904         if (error != 0) {
905                 device_printf(sc->sc_dev,
906                     "could not allocate shared page DMA memory\n");
907                 goto fail;
908         }
909
910         error = bus_dmamap_load(dma->tag, dma->map, dma->vaddr_start,
911             reqsize,  wpi_dma_map_addr, &dma->paddr_start, flags);
912
913         /* Save the original pointers so we can free all the memory */
914         dma->paddr = dma->paddr_start;
915         dma->vaddr = dma->vaddr_start;
916
917         /*
918          * Check the alignment and increment by 4096 until we get the
919          * requested alignment. Fail if can't obtain the alignment
920          * we requested.
921          */
922         if ((dma->paddr & (alignment -1 )) != 0) {
923                 int i;
924
925                 for (i = 0; i < alignment / 4096; i++) {
926                         if ((dma->paddr & (alignment - 1 )) == 0)
927                                 break;
928                         dma->paddr += 4096;
929                         dma->vaddr += 4096;
930                 }
931                 if (i == alignment / 4096) {
932                         device_printf(sc->sc_dev,
933                             "alignment requirement was not satisfied\n");
934                         goto fail;
935                 }
936         }
937
938         if (error != 0) {
939                 device_printf(sc->sc_dev,
940                     "could not load shared page DMA map\n");
941                 goto fail;
942         }
943
944         if (kvap != NULL)
945                 *kvap = dma->vaddr;
946
947         return 0;
948
949 fail:
950         wpi_dma_contig_free(dma);
951         return error;
952 }
953
954 static void
955 wpi_dma_contig_free(struct wpi_dma_info *dma)
956 {
957         if (dma->tag) {
958                 if (dma->map != NULL) {
959                         if (dma->paddr_start != 0) {
960                                 bus_dmamap_sync(dma->tag, dma->map,
961                                     BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
962                                 bus_dmamap_unload(dma->tag, dma->map);
963                         }
964                         bus_dmamem_free(dma->tag, &dma->vaddr_start, dma->map);
965                 }
966                 bus_dma_tag_destroy(dma->tag);
967         }
968 }
969
970 /*
971  * Allocate a shared page between host and NIC.
972  */
973 static int
974 wpi_alloc_shared(struct wpi_softc *sc)
975 {
976         int error;
977
978         error = wpi_dma_contig_alloc(sc, &sc->shared_dma,
979             (void **)&sc->shared, sizeof (struct wpi_shared),
980             PAGE_SIZE,
981             BUS_DMA_NOWAIT);
982
983         if (error != 0) {
984                 device_printf(sc->sc_dev,
985                     "could not allocate shared area DMA memory\n");
986         }
987
988         return error;
989 }
990
991 static void
992 wpi_free_shared(struct wpi_softc *sc)
993 {
994         wpi_dma_contig_free(&sc->shared_dma);
995 }
996
997 static int
998 wpi_alloc_rx_ring(struct wpi_softc *sc, struct wpi_rx_ring *ring)
999 {
1000
1001         int i, error;
1002
1003         ring->cur = 0;
1004
1005         error = wpi_dma_contig_alloc(sc, &ring->desc_dma,
1006             (void **)&ring->desc, WPI_RX_RING_COUNT * sizeof (uint32_t),
1007             WPI_RING_DMA_ALIGN, BUS_DMA_NOWAIT);
1008
1009         if (error != 0) {
1010                 device_printf(sc->sc_dev,
1011                     "%s: could not allocate rx ring DMA memory, error %d\n",
1012                     __func__, error);
1013                 goto fail;
1014         }
1015
1016         error = bus_dma_tag_create(ring->data_dmat, 1, 0,
1017             BUS_SPACE_MAXADDR_32BIT,
1018             BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES, 1,
1019             MCLBYTES, BUS_DMA_NOWAIT, &ring->data_dmat);
1020         if (error != 0) {
1021                 device_printf(sc->sc_dev,
1022                     "%s: bus_dma_tag_create_failed, error %d\n",
1023                     __func__, error);
1024                 goto fail;
1025         }
1026
1027         /*
1028          * Setup Rx buffers.
1029          */
1030         for (i = 0; i < WPI_RX_RING_COUNT; i++) {
1031                 struct wpi_rx_data *data = &ring->data[i];
1032                 struct mbuf *m;
1033                 bus_addr_t paddr;
1034
1035                 error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
1036                 if (error != 0) {
1037                         device_printf(sc->sc_dev,
1038                             "%s: bus_dmamap_create failed, error %d\n",
1039                             __func__, error);
1040                         goto fail;
1041                 }
1042                 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1043                 if (m == NULL) {
1044                         device_printf(sc->sc_dev,
1045                            "%s: could not allocate rx mbuf\n", __func__);
1046                         error = ENOMEM;
1047                         goto fail;
1048                 }
1049                 /* map page */
1050                 error = bus_dmamap_load(ring->data_dmat, data->map,
1051                     mtod(m, caddr_t), MCLBYTES,
1052                     wpi_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
1053                 if (error != 0 && error != EFBIG) {
1054                         device_printf(sc->sc_dev,
1055                             "%s: bus_dmamap_load failed, error %d\n",
1056                             __func__, error);
1057                         m_freem(m);
1058                         error = ENOMEM; /* XXX unique code */
1059                         goto fail;
1060                 }
1061                 bus_dmamap_sync(ring->data_dmat, data->map,
1062                     BUS_DMASYNC_PREWRITE);
1063
1064                 data->m = m;
1065                 ring->desc[i] = htole32(paddr);
1066         }
1067         bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
1068             BUS_DMASYNC_PREWRITE);
1069         return 0;
1070 fail:
1071         wpi_free_rx_ring(sc, ring);
1072         return error;
1073 }
1074
1075 static void
1076 wpi_reset_rx_ring(struct wpi_softc *sc, struct wpi_rx_ring *ring)
1077 {
1078         int ntries;
1079
1080         wpi_mem_lock(sc);
1081
1082         WPI_WRITE(sc, WPI_RX_CONFIG, 0);
1083
1084         for (ntries = 0; ntries < 100; ntries++) {
1085                 if (WPI_READ(sc, WPI_RX_STATUS) & WPI_RX_IDLE)
1086                         break;
1087                 DELAY(10);
1088         }
1089
1090         wpi_mem_unlock(sc);
1091
1092 #ifdef WPI_DEBUG
1093         if (ntries == 100 && wpi_debug > 0)
1094                 device_printf(sc->sc_dev, "timeout resetting Rx ring\n");
1095 #endif
1096
1097         ring->cur = 0;
1098 }
1099
1100 static void
1101 wpi_free_rx_ring(struct wpi_softc *sc, struct wpi_rx_ring *ring)
1102 {
1103         int i;
1104
1105         wpi_dma_contig_free(&ring->desc_dma);
1106
1107         for (i = 0; i < WPI_RX_RING_COUNT; i++)
1108                 if (ring->data[i].m != NULL)
1109                         m_freem(ring->data[i].m);
1110 }
1111
1112 static int
1113 wpi_alloc_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring, int count,
1114         int qid)
1115 {
1116         struct wpi_tx_data *data;
1117         int i, error;
1118
1119         ring->qid = qid;
1120         ring->count = count;
1121         ring->queued = 0;
1122         ring->cur = 0;
1123         ring->data = NULL;
1124
1125         error = wpi_dma_contig_alloc(sc, &ring->desc_dma,
1126                 (void **)&ring->desc, count * sizeof (struct wpi_tx_desc),
1127                 WPI_RING_DMA_ALIGN, BUS_DMA_NOWAIT);
1128
1129         if (error != 0) {
1130             device_printf(sc->sc_dev, "could not allocate tx dma memory\n");
1131             goto fail;
1132         }
1133
1134         /* update shared page with ring's base address */
1135         sc->shared->txbase[qid] = htole32(ring->desc_dma.paddr);
1136
1137         error = wpi_dma_contig_alloc(sc, &ring->cmd_dma, (void **)&ring->cmd,
1138                 count * sizeof (struct wpi_tx_cmd), WPI_RING_DMA_ALIGN,
1139                 BUS_DMA_NOWAIT);
1140
1141         if (error != 0) {
1142                 device_printf(sc->sc_dev,
1143                     "could not allocate tx command DMA memory\n");
1144                 goto fail;
1145         }
1146
1147         ring->data = kmalloc(count * sizeof (struct wpi_tx_data), M_DEVBUF,
1148             M_NOWAIT | M_ZERO);
1149         if (ring->data == NULL) {
1150                 device_printf(sc->sc_dev,
1151                     "could not allocate tx data slots\n");
1152                 goto fail;
1153         }
1154
1155         error = bus_dma_tag_create(ring->data_dmat, 1, 0,
1156             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
1157             WPI_MAX_SCATTER - 1, MCLBYTES, BUS_DMA_NOWAIT,
1158             &ring->data_dmat);
1159         if (error != 0) {
1160                 device_printf(sc->sc_dev, "could not create data DMA tag\n");
1161                 goto fail;
1162         }
1163
1164         for (i = 0; i < count; i++) {
1165                 data = &ring->data[i];
1166
1167                 error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
1168                 if (error != 0) {
1169                         device_printf(sc->sc_dev,
1170                             "could not create tx buf DMA map\n");
1171                         goto fail;
1172                 }
1173                 bus_dmamap_sync(ring->data_dmat, data->map,
1174                     BUS_DMASYNC_PREWRITE);
1175         }
1176
1177         return 0;
1178
1179 fail:
1180         wpi_free_tx_ring(sc, ring);
1181         return error;
1182 }
1183
1184 static void
1185 wpi_reset_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring)
1186 {
1187         struct wpi_tx_data *data;
1188         int i, ntries;
1189
1190         wpi_mem_lock(sc);
1191
1192         WPI_WRITE(sc, WPI_TX_CONFIG(ring->qid), 0);
1193         for (ntries = 0; ntries < 100; ntries++) {
1194                 if (WPI_READ(sc, WPI_TX_STATUS) & WPI_TX_IDLE(ring->qid))
1195                         break;
1196                 DELAY(10);
1197         }
1198 #ifdef WPI_DEBUG
1199         if (ntries == 100 && wpi_debug > 0)
1200                 device_printf(sc->sc_dev, "timeout resetting Tx ring %d\n",
1201                     ring->qid);
1202 #endif
1203         wpi_mem_unlock(sc);
1204
1205         for (i = 0; i < ring->count; i++) {
1206                 data = &ring->data[i];
1207
1208                 if (data->m != NULL) {
1209                         bus_dmamap_unload(ring->data_dmat, data->map);
1210                         m_freem(data->m);
1211                         data->m = NULL;
1212                 }
1213         }
1214
1215         ring->queued = 0;
1216         ring->cur = 0;
1217 }
1218
1219 static void
1220 wpi_free_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring)
1221 {
1222         struct wpi_tx_data *data;
1223         int i;
1224
1225         wpi_dma_contig_free(&ring->desc_dma);
1226         wpi_dma_contig_free(&ring->cmd_dma);
1227
1228         if (ring->data != NULL) {
1229                 for (i = 0; i < ring->count; i++) {
1230                         data = &ring->data[i];
1231
1232                         if (data->m != NULL) {
1233                                 bus_dmamap_sync(ring->data_dmat, data->map,
1234                                     BUS_DMASYNC_POSTWRITE);
1235                                 bus_dmamap_unload(ring->data_dmat, data->map);
1236                                 m_freem(data->m);
1237                                 data->m = NULL;
1238                         }
1239                 }
1240                 kfree(ring->data, M_DEVBUF);
1241         }
1242
1243         if (ring->data_dmat != NULL)
1244                 bus_dma_tag_destroy(ring->data_dmat);
1245 }
1246
1247 static int
1248 wpi_shutdown(device_t dev)
1249 {
1250         struct wpi_softc *sc = device_get_softc(dev);
1251
1252         WPI_LOCK(sc);
1253         wpi_stop_locked(sc);
1254         wpi_unload_firmware(sc);
1255         WPI_UNLOCK(sc);
1256
1257         return 0;
1258 }
1259
1260 static int
1261 wpi_suspend(device_t dev)
1262 {
1263         struct wpi_softc *sc = device_get_softc(dev);
1264
1265         wpi_stop(sc);
1266         return 0;
1267 }
1268
1269 static int
1270 wpi_resume(device_t dev)
1271 {
1272         struct wpi_softc *sc = device_get_softc(dev);
1273         struct ifnet *ifp = sc->sc_ifp;
1274
1275         pci_write_config(dev, 0x41, 0, 1);
1276
1277         if (ifp->if_flags & IFF_UP) {
1278                 wpi_init(ifp->if_softc);
1279                 if (ifp->if_flags & IFF_RUNNING)
1280                         wpi_start(ifp);
1281         }
1282         return 0;
1283 }
1284
1285 /* ARGSUSED */
1286 static struct ieee80211_node *
1287 wpi_node_alloc(struct ieee80211vap *vap __unused,
1288         const uint8_t mac[IEEE80211_ADDR_LEN] __unused)
1289 {
1290         struct wpi_node *wn;
1291
1292         wn = kmalloc(sizeof (struct wpi_node), M_80211_NODE, M_NOWAIT | M_ZERO);
1293
1294         return &wn->ni;
1295 }
1296
1297 /**
1298  * Called by net80211 when ever there is a change to 80211 state machine
1299  */
1300 static int
1301 wpi_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
1302 {
1303         struct wpi_vap *wvp = WPI_VAP(vap);
1304         struct ieee80211com *ic = vap->iv_ic;
1305         struct ifnet *ifp = ic->ic_ifp;
1306         struct wpi_softc *sc = ifp->if_softc;
1307         int error;
1308
1309         DPRINTF(("%s: %s -> %s flags 0x%x\n", __func__,
1310                 ieee80211_state_name[vap->iv_state],
1311                 ieee80211_state_name[nstate], sc->flags));
1312
1313         IEEE80211_UNLOCK(ic);
1314         WPI_LOCK(sc);
1315         if (nstate == IEEE80211_S_AUTH) {
1316                 /* The node must be registered in the firmware before auth */
1317                 error = wpi_auth(sc, vap);
1318                 if (error != 0) {
1319                         device_printf(sc->sc_dev,
1320                             "%s: could not move to auth state, error %d\n",
1321                             __func__, error);
1322                 }
1323         }
1324         if (nstate == IEEE80211_S_RUN && vap->iv_state != IEEE80211_S_RUN) {
1325                 error = wpi_run(sc, vap);
1326                 if (error != 0) {
1327                         device_printf(sc->sc_dev,
1328                             "%s: could not move to run state, error %d\n",
1329                             __func__, error);
1330                 }
1331         }
1332         if (nstate == IEEE80211_S_RUN) {
1333                 /* RUN -> RUN transition; just restart the timers */
1334                 wpi_calib_timeout(sc);
1335                 /* XXX split out rate control timer */
1336         }
1337         WPI_UNLOCK(sc);
1338         IEEE80211_LOCK(ic);
1339         return wvp->newstate(vap, nstate, arg);
1340 }
1341
1342 /*
1343  * Grab exclusive access to NIC memory.
1344  */
1345 static void
1346 wpi_mem_lock(struct wpi_softc *sc)
1347 {
1348         int ntries;
1349         uint32_t tmp;
1350
1351         tmp = WPI_READ(sc, WPI_GPIO_CTL);
1352         WPI_WRITE(sc, WPI_GPIO_CTL, tmp | WPI_GPIO_MAC);
1353
1354         /* spin until we actually get the lock */
1355         for (ntries = 0; ntries < 100; ntries++) {
1356                 if ((WPI_READ(sc, WPI_GPIO_CTL) &
1357                         (WPI_GPIO_CLOCK | WPI_GPIO_SLEEP)) == WPI_GPIO_CLOCK)
1358                         break;
1359                 DELAY(10);
1360         }
1361         if (ntries == 100)
1362                 device_printf(sc->sc_dev, "could not lock memory\n");
1363 }
1364
1365 /*
1366  * Release lock on NIC memory.
1367  */
1368 static void
1369 wpi_mem_unlock(struct wpi_softc *sc)
1370 {
1371         uint32_t tmp = WPI_READ(sc, WPI_GPIO_CTL);
1372         WPI_WRITE(sc, WPI_GPIO_CTL, tmp & ~WPI_GPIO_MAC);
1373 }
1374
1375 static uint32_t
1376 wpi_mem_read(struct wpi_softc *sc, uint16_t addr)
1377 {
1378         WPI_WRITE(sc, WPI_READ_MEM_ADDR, WPI_MEM_4 | addr);
1379         return WPI_READ(sc, WPI_READ_MEM_DATA);
1380 }
1381
1382 static void
1383 wpi_mem_write(struct wpi_softc *sc, uint16_t addr, uint32_t data)
1384 {
1385         WPI_WRITE(sc, WPI_WRITE_MEM_ADDR, WPI_MEM_4 | addr);
1386         WPI_WRITE(sc, WPI_WRITE_MEM_DATA, data);
1387 }
1388
1389 static void
1390 wpi_mem_write_region_4(struct wpi_softc *sc, uint16_t addr,
1391     const uint32_t *data, int wlen)
1392 {
1393         for (; wlen > 0; wlen--, data++, addr+=4)
1394                 wpi_mem_write(sc, addr, *data);
1395 }
1396
1397 /*
1398  * Read data from the EEPROM.  We access EEPROM through the MAC instead of
1399  * using the traditional bit-bang method. Data is read up until len bytes have
1400  * been obtained.
1401  */
1402 static uint16_t
1403 wpi_read_prom_data(struct wpi_softc *sc, uint32_t addr, void *data, int len)
1404 {
1405         int ntries;
1406         uint32_t val;
1407         uint8_t *out = data;
1408
1409         wpi_mem_lock(sc);
1410
1411         for (; len > 0; len -= 2, addr++) {
1412                 WPI_WRITE(sc, WPI_EEPROM_CTL, addr << 2);
1413
1414                 for (ntries = 0; ntries < 10; ntries++) {
1415                         if ((val = WPI_READ(sc, WPI_EEPROM_CTL)) & WPI_EEPROM_READY)
1416                                 break;
1417                         DELAY(5);
1418                 }
1419
1420                 if (ntries == 10) {
1421                         device_printf(sc->sc_dev, "could not read EEPROM\n");
1422                         return ETIMEDOUT;
1423                 }
1424
1425                 *out++= val >> 16;
1426                 if (len > 1)
1427                         *out ++= val >> 24;
1428         }
1429
1430         wpi_mem_unlock(sc);
1431
1432         return 0;
1433 }
1434
1435 /*
1436  * The firmware text and data segments are transferred to the NIC using DMA.
1437  * The driver just copies the firmware into DMA-safe memory and tells the NIC
1438  * where to find it.  Once the NIC has copied the firmware into its internal
1439  * memory, we can free our local copy in the driver.
1440  */
1441 static int
1442 wpi_load_microcode(struct wpi_softc *sc, const uint8_t *fw, int size)
1443 {
1444         int error, ntries;
1445
1446         DPRINTFN(WPI_DEBUG_HW,("Loading microcode  size 0x%x\n", size));
1447
1448         size /= sizeof(uint32_t);
1449
1450         wpi_mem_lock(sc);
1451
1452         wpi_mem_write_region_4(sc, WPI_MEM_UCODE_BASE,
1453             (const uint32_t *)fw, size);
1454
1455         wpi_mem_write(sc, WPI_MEM_UCODE_SRC, 0);
1456         wpi_mem_write(sc, WPI_MEM_UCODE_DST, WPI_FW_TEXT);
1457         wpi_mem_write(sc, WPI_MEM_UCODE_SIZE, size);
1458
1459         /* run microcode */
1460         wpi_mem_write(sc, WPI_MEM_UCODE_CTL, WPI_UC_RUN);
1461
1462         /* wait while the adapter is busy copying the firmware */
1463         for (error = 0, ntries = 0; ntries < 1000; ntries++) {
1464                 uint32_t status = WPI_READ(sc, WPI_TX_STATUS);
1465                 DPRINTFN(WPI_DEBUG_HW,
1466                     ("firmware status=0x%x, val=0x%x, result=0x%x\n", status,
1467                      WPI_TX_IDLE(6), status & WPI_TX_IDLE(6)));
1468                 if (status & WPI_TX_IDLE(6)) {
1469                         DPRINTFN(WPI_DEBUG_HW,
1470                             ("Status Match! - ntries = %d\n", ntries));
1471                         break;
1472                 }
1473                 DELAY(10);
1474         }
1475         if (ntries == 1000) {
1476                 device_printf(sc->sc_dev, "timeout transferring firmware\n");
1477                 error = ETIMEDOUT;
1478         }
1479
1480         /* start the microcode executing */
1481         wpi_mem_write(sc, WPI_MEM_UCODE_CTL, WPI_UC_ENABLE);
1482
1483         wpi_mem_unlock(sc);
1484
1485         return (error);
1486 }
1487
1488 static void
1489 wpi_rx_intr(struct wpi_softc *sc, struct wpi_rx_desc *desc,
1490         struct wpi_rx_data *data)
1491 {
1492         struct ifnet *ifp = sc->sc_ifp;
1493         struct ieee80211com *ic = ifp->if_l2com;
1494         struct wpi_rx_ring *ring = &sc->rxq;
1495         struct wpi_rx_stat *stat;
1496         struct wpi_rx_head *head;
1497         struct wpi_rx_tail *tail;
1498         struct ieee80211_node *ni;
1499         struct mbuf *m, *mnew;
1500         bus_addr_t paddr;
1501         int error;
1502
1503         stat = (struct wpi_rx_stat *)(desc + 1);
1504
1505         if (stat->len > WPI_STAT_MAXLEN) {
1506                 device_printf(sc->sc_dev, "invalid rx statistic header\n");
1507                 ifp->if_ierrors++;
1508                 return;
1509         }
1510
1511         head = (struct wpi_rx_head *)((caddr_t)(stat + 1) + stat->len);
1512         tail = (struct wpi_rx_tail *)((caddr_t)(head + 1) + le16toh(head->len));
1513
1514         DPRINTFN(WPI_DEBUG_RX, ("rx intr: idx=%d len=%d stat len=%d rssi=%d "
1515             "rate=%x chan=%d tstamp=%ju\n", ring->cur, le32toh(desc->len),
1516             le16toh(head->len), (int8_t)stat->rssi, head->rate, head->chan,
1517             (uintmax_t)le64toh(tail->tstamp)));
1518
1519         /* discard Rx frames with bad CRC early */
1520         if ((le32toh(tail->flags) & WPI_RX_NOERROR) != WPI_RX_NOERROR) {
1521                 DPRINTFN(WPI_DEBUG_RX, ("%s: rx flags error %x\n", __func__,
1522                     le32toh(tail->flags)));
1523                 ifp->if_ierrors++;
1524                 return;
1525         }
1526         if (le16toh(head->len) < sizeof (struct ieee80211_frame)) {
1527                 DPRINTFN(WPI_DEBUG_RX, ("%s: frame too short: %d\n", __func__,
1528                     le16toh(head->len)));
1529                 ifp->if_ierrors++;
1530                 return;
1531         }
1532
1533         /* XXX don't need mbuf, just dma buffer */
1534         mnew = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1535         if (mnew == NULL) {
1536                 DPRINTFN(WPI_DEBUG_RX, ("%s: no mbuf to restock ring\n",
1537                     __func__));
1538                 ifp->if_ierrors++;
1539                 return;
1540         }
1541         error = bus_dmamap_load(ring->data_dmat, data->map,
1542             mtod(mnew, caddr_t), MCLBYTES,
1543             wpi_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
1544         if (error != 0 && error != EFBIG) {
1545                 device_printf(sc->sc_dev,
1546                     "%s: bus_dmamap_load failed, error %d\n", __func__, error);
1547                 m_freem(mnew);
1548                 ifp->if_ierrors++;
1549                 return;
1550         }
1551         bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1552
1553         /* finalize mbuf and swap in new one */
1554         m = data->m;
1555         m->m_pkthdr.rcvif = ifp;
1556         m->m_data = (caddr_t)(head + 1);
1557         m->m_pkthdr.len = m->m_len = le16toh(head->len);
1558
1559         data->m = mnew;
1560         /* update Rx descriptor */
1561         ring->desc[ring->cur] = htole32(paddr);
1562
1563         if (ieee80211_radiotap_active(ic)) {
1564                 struct wpi_rx_radiotap_header *tap = &sc->sc_rxtap;
1565
1566                 tap->wr_flags = 0;
1567                 tap->wr_chan_freq =
1568                         htole16(ic->ic_channels[head->chan].ic_freq);
1569                 tap->wr_chan_flags =
1570                         htole16(ic->ic_channels[head->chan].ic_flags);
1571                 tap->wr_dbm_antsignal = (int8_t)(stat->rssi - WPI_RSSI_OFFSET);
1572                 tap->wr_dbm_antnoise = (int8_t)le16toh(stat->noise);
1573                 tap->wr_tsft = tail->tstamp;
1574                 tap->wr_antenna = (le16toh(head->flags) >> 4) & 0xf;
1575                 switch (head->rate) {
1576                 /* CCK rates */
1577                 case  10: tap->wr_rate =   2; break;
1578                 case  20: tap->wr_rate =   4; break;
1579                 case  55: tap->wr_rate =  11; break;
1580                 case 110: tap->wr_rate =  22; break;
1581                 /* OFDM rates */
1582                 case 0xd: tap->wr_rate =  12; break;
1583                 case 0xf: tap->wr_rate =  18; break;
1584                 case 0x5: tap->wr_rate =  24; break;
1585                 case 0x7: tap->wr_rate =  36; break;
1586                 case 0x9: tap->wr_rate =  48; break;
1587                 case 0xb: tap->wr_rate =  72; break;
1588                 case 0x1: tap->wr_rate =  96; break;
1589                 case 0x3: tap->wr_rate = 108; break;
1590                 /* unknown rate: should not happen */
1591                 default:  tap->wr_rate =   0;
1592                 }
1593                 if (le16toh(head->flags) & 0x4)
1594                         tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
1595         }
1596
1597         WPI_UNLOCK(sc);
1598
1599         ni = ieee80211_find_rxnode(ic, mtod(m, struct ieee80211_frame_min *));
1600         if (ni != NULL) {
1601                 (void) ieee80211_input(ni, m, stat->rssi, 0);
1602                 ieee80211_free_node(ni);
1603         } else
1604                 (void) ieee80211_input_all(ic, m, stat->rssi, 0);
1605
1606         WPI_LOCK(sc);
1607 }
1608
1609 static void
1610 wpi_tx_intr(struct wpi_softc *sc, struct wpi_rx_desc *desc)
1611 {
1612         struct ifnet *ifp = sc->sc_ifp;
1613         struct wpi_tx_ring *ring = &sc->txq[desc->qid & 0x3];
1614         struct wpi_tx_data *txdata = &ring->data[desc->idx];
1615         struct wpi_tx_stat *stat = (struct wpi_tx_stat *)(desc + 1);
1616         struct ieee80211_node *ni = txdata->ni;
1617         struct ieee80211vap *vap = ni->ni_vap;
1618         int retrycnt = 0;
1619
1620         DPRINTFN(WPI_DEBUG_TX, ("tx done: qid=%d idx=%d retries=%d nkill=%d "
1621             "rate=%x duration=%d status=%x\n", desc->qid, desc->idx,
1622             stat->ntries, stat->nkill, stat->rate, le32toh(stat->duration),
1623             le32toh(stat->status)));
1624
1625         /*
1626          * Update rate control statistics for the node.
1627          * XXX we should not count mgmt frames since they're always sent at
1628          * the lowest available bit-rate.
1629          * XXX frames w/o ACK shouldn't be used either
1630          */
1631         if (stat->ntries > 0) {
1632                 DPRINTFN(WPI_DEBUG_TX, ("%d retries\n", stat->ntries));
1633                 retrycnt = 1;
1634         }
1635         ieee80211_ratectl_tx_complete(vap, ni, IEEE80211_RATECTL_TX_SUCCESS,
1636                 &retrycnt, NULL);
1637
1638         /* XXX oerrors should only count errors !maxtries */
1639         if ((le32toh(stat->status) & 0xff) != 1)
1640                 ifp->if_oerrors++;
1641         else
1642                 ifp->if_opackets++;
1643
1644         bus_dmamap_sync(ring->data_dmat, txdata->map, BUS_DMASYNC_POSTWRITE);
1645         bus_dmamap_unload(ring->data_dmat, txdata->map);
1646         /* XXX handle M_TXCB? */
1647         m_freem(txdata->m);
1648         txdata->m = NULL;
1649         ieee80211_free_node(txdata->ni);
1650         txdata->ni = NULL;
1651
1652         ring->queued--;
1653
1654         sc->sc_tx_timer = 0;
1655         ifp->if_flags &= ~IFF_OACTIVE;
1656         wpi_start_locked(ifp);
1657 }
1658
1659 static void
1660 wpi_cmd_intr(struct wpi_softc *sc, struct wpi_rx_desc *desc)
1661 {
1662         struct wpi_tx_ring *ring = &sc->cmdq;
1663         struct wpi_tx_data *data;
1664
1665         DPRINTFN(WPI_DEBUG_CMD, ("cmd notification qid=%x idx=%d flags=%x "
1666                                  "type=%s len=%d\n", desc->qid, desc->idx,
1667                                  desc->flags, wpi_cmd_str(desc->type),
1668                                  le32toh(desc->len)));
1669
1670         if ((desc->qid & 7) != 4)
1671                 return; /* not a command ack */
1672
1673         data = &ring->data[desc->idx];
1674
1675         /* if the command was mapped in a mbuf, free it */
1676         if (data->m != NULL) {
1677                 bus_dmamap_unload(ring->data_dmat, data->map);
1678                 m_freem(data->m);
1679                 data->m = NULL;
1680         }
1681
1682         sc->flags &= ~WPI_FLAG_BUSY;
1683         wakeup(&ring->cmd[desc->idx]);
1684 }
1685
1686 static void
1687 wpi_notif_intr(struct wpi_softc *sc)
1688 {
1689         struct ifnet *ifp = sc->sc_ifp;
1690         struct ieee80211com *ic = ifp->if_l2com;
1691         struct wpi_rx_desc *desc;
1692         struct wpi_rx_data *data;
1693         uint32_t hw;
1694
1695         hw = le32toh(sc->shared->next);
1696         while (sc->rxq.cur != hw) {
1697                 data = &sc->rxq.data[sc->rxq.cur];
1698                 desc = (void *)data->m->m_ext.ext_buf;
1699
1700                 DPRINTFN(WPI_DEBUG_NOTIFY,
1701                          ("notify qid=%x idx=%d flags=%x type=%d len=%d\n",
1702                           desc->qid,
1703                           desc->idx,
1704                           desc->flags,
1705                           desc->type,
1706                           le32toh(desc->len)));
1707
1708                 if (!(desc->qid & 0x80))        /* reply to a command */
1709                         wpi_cmd_intr(sc, desc);
1710
1711                 switch (desc->type) {
1712                 case WPI_RX_DONE:
1713                         /* a 802.11 frame was received */
1714                         wpi_rx_intr(sc, desc, data);
1715                         break;
1716
1717                 case WPI_TX_DONE:
1718                         /* a 802.11 frame has been transmitted */
1719                         wpi_tx_intr(sc, desc);
1720                         break;
1721
1722                 case WPI_UC_READY:
1723                 {
1724                         struct wpi_ucode_info *uc =
1725                                 (struct wpi_ucode_info *)(desc + 1);
1726
1727                         /* the microcontroller is ready */
1728                         DPRINTF(("microcode alive notification version %x "
1729                                 "alive %x\n", le32toh(uc->version),
1730                                 le32toh(uc->valid)));
1731
1732                         if (le32toh(uc->valid) != 1) {
1733                                 device_printf(sc->sc_dev,
1734                                     "microcontroller initialization failed\n");
1735                                 wpi_stop_locked(sc);
1736                         }
1737                         break;
1738                 }
1739                 case WPI_STATE_CHANGED:
1740                 {
1741                         uint32_t *status = (uint32_t *)(desc + 1);
1742
1743                         /* enabled/disabled notification */
1744                         DPRINTF(("state changed to %x\n", le32toh(*status)));
1745
1746                         if (le32toh(*status) & 1) {
1747                                 device_printf(sc->sc_dev,
1748                                     "Radio transmitter is switched off\n");
1749                                 sc->flags |= WPI_FLAG_HW_RADIO_OFF;
1750                                 ifp->if_flags &= ~IFF_RUNNING;
1751                                 /* Disable firmware commands */
1752                                 WPI_WRITE(sc, WPI_UCODE_SET, WPI_DISABLE_CMD);
1753                         }
1754                         break;
1755                 }
1756                 case WPI_START_SCAN:
1757                 {
1758 #ifdef WPI_DEBUG
1759                         struct wpi_start_scan *scan =
1760                                 (struct wpi_start_scan *)(desc + 1);
1761 #endif
1762
1763                         DPRINTFN(WPI_DEBUG_SCANNING,
1764                                  ("scanning channel %d status %x\n",
1765                             scan->chan, le32toh(scan->status)));
1766                         break;
1767                 }
1768                 case WPI_STOP_SCAN:
1769                 {
1770 #ifdef WPI_DEBUG
1771                         struct wpi_stop_scan *scan =
1772                                 (struct wpi_stop_scan *)(desc + 1);
1773 #endif
1774                         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1775
1776                         DPRINTFN(WPI_DEBUG_SCANNING,
1777                             ("scan finished nchan=%d status=%d chan=%d\n",
1778                              scan->nchan, scan->status, scan->chan));
1779
1780                         sc->sc_scan_timer = 0;
1781                         ieee80211_scan_next(vap);
1782                         break;
1783                 }
1784                 case WPI_MISSED_BEACON:
1785                 {
1786                         struct wpi_missed_beacon *beacon =
1787                                 (struct wpi_missed_beacon *)(desc + 1);
1788                         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1789
1790                         if (le32toh(beacon->consecutive) >=
1791                             vap->iv_bmissthreshold) {
1792                                 DPRINTF(("Beacon miss: %u >= %u\n",
1793                                          le32toh(beacon->consecutive),
1794                                          vap->iv_bmissthreshold));
1795                                 ieee80211_beacon_miss(ic);
1796                         }
1797                         break;
1798                 }
1799                 }
1800
1801                 sc->rxq.cur = (sc->rxq.cur + 1) % WPI_RX_RING_COUNT;
1802         }
1803
1804         /* tell the firmware what we have processed */
1805         hw = (hw == 0) ? WPI_RX_RING_COUNT - 1 : hw - 1;
1806         WPI_WRITE(sc, WPI_RX_WIDX, hw & ~7);
1807 }
1808
1809 static void
1810 wpi_intr(void *arg)
1811 {
1812         struct wpi_softc *sc = arg;
1813         uint32_t r;
1814
1815         WPI_LOCK(sc);
1816
1817         r = WPI_READ(sc, WPI_INTR);
1818         if (r == 0 || r == 0xffffffff) {
1819                 WPI_UNLOCK(sc);
1820                 return;
1821         }
1822
1823         /* disable interrupts */
1824         WPI_WRITE(sc, WPI_MASK, 0);
1825         /* ack interrupts */
1826         WPI_WRITE(sc, WPI_INTR, r);
1827
1828         if (r & (WPI_SW_ERROR | WPI_HW_ERROR)) {
1829                 struct ifnet *ifp = sc->sc_ifp;
1830                 struct ieee80211com *ic = ifp->if_l2com;
1831                 struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1832
1833                 device_printf(sc->sc_dev, "fatal firmware error\n");
1834                 DPRINTFN(6,("(%s)\n", (r & WPI_SW_ERROR) ? "(Software Error)" :
1835                                 "(Hardware Error)"));
1836                 if (vap != NULL)
1837                         ieee80211_cancel_scan(vap);
1838                 ieee80211_runtask(ic, &sc->sc_restarttask);
1839                 sc->flags &= ~WPI_FLAG_BUSY;
1840                 WPI_UNLOCK(sc);
1841                 return;
1842         }
1843
1844         if (r & WPI_RX_INTR)
1845                 wpi_notif_intr(sc);
1846
1847         if (r & WPI_ALIVE_INTR) /* firmware initialized */
1848                 wakeup(sc);
1849
1850         /* re-enable interrupts */
1851         if (sc->sc_ifp->if_flags & IFF_UP)
1852                 WPI_WRITE(sc, WPI_MASK, WPI_INTR_MASK);
1853
1854         WPI_UNLOCK(sc);
1855 }
1856
1857 static uint8_t
1858 wpi_plcp_signal(int rate)
1859 {
1860         switch (rate) {
1861         /* CCK rates (returned values are device-dependent) */
1862         case 2:         return 10;
1863         case 4:         return 20;
1864         case 11:        return 55;
1865         case 22:        return 110;
1866
1867         /* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
1868         /* R1-R4 (ral/ural is R4-R1) */
1869         case 12:        return 0xd;
1870         case 18:        return 0xf;
1871         case 24:        return 0x5;
1872         case 36:        return 0x7;
1873         case 48:        return 0x9;
1874         case 72:        return 0xb;
1875         case 96:        return 0x1;
1876         case 108:       return 0x3;
1877
1878         /* unsupported rates (should not get there) */
1879         default:        return 0;
1880         }
1881 }
1882
1883 /* quickly determine if a given rate is CCK or OFDM */
1884 #define WPI_RATE_IS_OFDM(rate) ((rate) >= 12 && (rate) != 22)
1885
1886 /*
1887  * Construct the data packet for a transmit buffer and acutally put
1888  * the buffer onto the transmit ring, kicking the card to process the
1889  * the buffer.
1890  */
1891 static int
1892 wpi_tx_data(struct wpi_softc *sc, struct mbuf *m0, struct ieee80211_node *ni,
1893         int ac)
1894 {
1895         struct ieee80211vap *vap = ni->ni_vap;
1896         struct ifnet *ifp = sc->sc_ifp;
1897         struct ieee80211com *ic = ifp->if_l2com;
1898         const struct chanAccParams *cap = &ic->ic_wme.wme_chanParams;
1899         struct wpi_tx_ring *ring = &sc->txq[ac];
1900         struct wpi_tx_desc *desc;
1901         struct wpi_tx_data *data;
1902         struct wpi_tx_cmd *cmd;
1903         struct wpi_cmd_data *tx;
1904         struct ieee80211_frame *wh;
1905         const struct ieee80211_txparam *tp;
1906         struct ieee80211_key *k;
1907         struct mbuf *mnew;
1908         int i, error, nsegs, rate, hdrlen, ismcast;
1909         bus_dma_segment_t segs[WPI_MAX_SCATTER];
1910
1911         desc = &ring->desc[ring->cur];
1912         data = &ring->data[ring->cur];
1913
1914         wh = mtod(m0, struct ieee80211_frame *);
1915
1916         hdrlen = ieee80211_hdrsize(wh);
1917         ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
1918
1919         if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1920                 k = ieee80211_crypto_encap(ni, m0);
1921                 if (k == NULL) {
1922                         m_freem(m0);
1923                         return ENOBUFS;
1924                 }
1925                 /* packet header may have moved, reset our local pointer */
1926                 wh = mtod(m0, struct ieee80211_frame *);
1927         }
1928
1929         cmd = &ring->cmd[ring->cur];
1930         cmd->code = WPI_CMD_TX_DATA;
1931         cmd->flags = 0;
1932         cmd->qid = ring->qid;
1933         cmd->idx = ring->cur;
1934
1935         tx = (struct wpi_cmd_data *)cmd->data;
1936         tx->flags = htole32(WPI_TX_AUTO_SEQ);
1937         tx->timeout = htole16(0);
1938         tx->ofdm_mask = 0xff;
1939         tx->cck_mask = 0x0f;
1940         tx->lifetime = htole32(WPI_LIFETIME_INFINITE);
1941         tx->id = ismcast ? WPI_ID_BROADCAST : WPI_ID_BSS;
1942         tx->len = htole16(m0->m_pkthdr.len);
1943
1944         if (!ismcast) {
1945                 if ((ni->ni_flags & IEEE80211_NODE_QOS) == 0 ||
1946                     !cap->cap_wmeParams[ac].wmep_noackPolicy)
1947                         tx->flags |= htole32(WPI_TX_NEED_ACK);
1948                 if (m0->m_pkthdr.len + IEEE80211_CRC_LEN > vap->iv_rtsthreshold) {
1949                         tx->flags |= htole32(WPI_TX_NEED_RTS|WPI_TX_FULL_TXOP);
1950                         tx->rts_ntries = 7;
1951                 }
1952         }
1953         /* pick a rate */
1954         tp = &vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)];
1955         if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_MGT) {
1956                 uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
1957                 /* tell h/w to set timestamp in probe responses */
1958                 if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1959                         tx->flags |= htole32(WPI_TX_INSERT_TSTAMP);
1960                 if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
1961                     subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
1962                         tx->timeout = htole16(3);
1963                 else
1964                         tx->timeout = htole16(2);
1965                 rate = tp->mgmtrate;
1966         } else if (ismcast) {
1967                 rate = tp->mcastrate;
1968         } else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE) {
1969                 rate = tp->ucastrate;
1970         } else {
1971                 (void) ieee80211_ratectl_rate(ni, NULL, 0);
1972                 rate = ni->ni_txrate;
1973         }
1974         tx->rate = wpi_plcp_signal(rate);
1975
1976         /* be very persistant at sending frames out */
1977 #if 0
1978         tx->data_ntries = tp->maxretry;
1979 #else
1980         tx->data_ntries = 30;           /* XXX way too high */
1981 #endif
1982
1983         if (ieee80211_radiotap_active_vap(vap)) {
1984                 struct wpi_tx_radiotap_header *tap = &sc->sc_txtap;
1985                 tap->wt_flags = 0;
1986                 tap->wt_rate = rate;
1987                 tap->wt_hwqueue = ac;
1988                 if (wh->i_fc[1] & IEEE80211_FC1_WEP)
1989                         tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
1990
1991                 ieee80211_radiotap_tx(vap, m0);
1992         }
1993
1994         /* save and trim IEEE802.11 header */
1995         m_copydata(m0, 0, hdrlen, (caddr_t)&tx->wh);
1996         m_adj(m0, hdrlen);
1997
1998         error = bus_dmamap_load_mbuf_segment(ring->data_dmat, data->map, m0, segs,
1999             1, &nsegs, BUS_DMA_NOWAIT);
2000         if (error != 0 && error != EFBIG) {
2001                 device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
2002                     error);
2003                 m_freem(m0);
2004                 return error;
2005         }
2006         if (error != 0) {
2007                 /* XXX use m_collapse */
2008                 mnew = m_defrag(m0, M_NOWAIT);
2009                 if (mnew == NULL) {
2010                         device_printf(sc->sc_dev,
2011                             "could not defragment mbuf\n");
2012                         m_freem(m0);
2013                         return ENOBUFS;
2014                 }
2015                 m0 = mnew;
2016
2017                 error = bus_dmamap_load_mbuf_segment(ring->data_dmat, data->map,
2018                     m0, segs, 1, &nsegs, BUS_DMA_NOWAIT);
2019                 if (error != 0) {
2020                         device_printf(sc->sc_dev,
2021                             "could not map mbuf (error %d)\n", error);
2022                         m_freem(m0);
2023                         return error;
2024                 }
2025         }
2026
2027         data->m = m0;
2028         data->ni = ni;
2029
2030         DPRINTFN(WPI_DEBUG_TX, ("sending data: qid=%d idx=%d len=%d nsegs=%d\n",
2031             ring->qid, ring->cur, m0->m_pkthdr.len, nsegs));
2032
2033         /* first scatter/gather segment is used by the tx data command */
2034         desc->flags = htole32(WPI_PAD32(m0->m_pkthdr.len) << 28 |
2035             (1 + nsegs) << 24);
2036         desc->segs[0].addr = htole32(ring->cmd_dma.paddr +
2037             ring->cur * sizeof (struct wpi_tx_cmd));
2038         desc->segs[0].len  = htole32(4 + sizeof (struct wpi_cmd_data));
2039         for (i = 1; i <= nsegs; i++) {
2040                 desc->segs[i].addr = htole32(segs[i - 1].ds_addr);
2041                 desc->segs[i].len  = htole32(segs[i - 1].ds_len);
2042         }
2043
2044         bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
2045         bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
2046             BUS_DMASYNC_PREWRITE);
2047
2048         ring->queued++;
2049
2050         /* kick ring */
2051         ring->cur = (ring->cur + 1) % WPI_TX_RING_COUNT;
2052         WPI_WRITE(sc, WPI_TX_WIDX, ring->qid << 8 | ring->cur);
2053
2054         return 0;
2055 }
2056
2057 /**
2058  * Process data waiting to be sent on the IFNET output queue
2059  */
2060 static void
2061 wpi_start(struct ifnet *ifp)
2062 {
2063         struct wpi_softc *sc = ifp->if_softc;
2064
2065         WPI_LOCK(sc);
2066         wpi_start_locked(ifp);
2067         WPI_UNLOCK(sc);
2068 }
2069
2070 static void
2071 wpi_start_locked(struct ifnet *ifp)
2072 {
2073         struct wpi_softc *sc = ifp->if_softc;
2074         struct ieee80211_node *ni;
2075         struct mbuf *m;
2076         int ac;
2077
2078         WPI_LOCK_ASSERT(sc);
2079
2080         if ((ifp->if_flags & IFF_RUNNING) == 0) {
2081                 ifq_purge(&ifp->if_snd);
2082                 return;
2083         }
2084
2085         for (;;) {
2086                 IF_DEQUEUE(&ifp->if_snd, m);
2087                 if (m == NULL)
2088                         break;
2089                 ac = M_WME_GETAC(m);
2090                 if (sc->txq[ac].queued > sc->txq[ac].count - 8) {
2091                         /* there is no place left in this ring */
2092                         ifq_prepend(&ifp->if_snd, m);
2093                         ifp->if_flags |= IFF_OACTIVE;
2094                         break;
2095                 }
2096                 ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
2097                 if (wpi_tx_data(sc, m, ni, ac) != 0) {
2098                         ieee80211_free_node(ni);
2099                         ifp->if_oerrors++;
2100                         break;
2101                 }
2102                 sc->sc_tx_timer = 5;
2103         }
2104 }
2105
2106 static int
2107 wpi_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
2108         const struct ieee80211_bpf_params *params)
2109 {
2110         struct ieee80211com *ic = ni->ni_ic;
2111         struct ifnet *ifp = ic->ic_ifp;
2112         struct wpi_softc *sc = ifp->if_softc;
2113
2114         /* prevent management frames from being sent if we're not ready */
2115         if (!(ifp->if_flags & IFF_RUNNING)) {
2116                 m_freem(m);
2117                 ieee80211_free_node(ni);
2118                 return ENETDOWN;
2119         }
2120         WPI_LOCK(sc);
2121
2122         /* management frames go into ring 0 */
2123         if (sc->txq[0].queued > sc->txq[0].count - 8) {
2124                 ifp->if_flags |= IFF_OACTIVE;
2125                 m_freem(m);
2126                 WPI_UNLOCK(sc);
2127                 ieee80211_free_node(ni);
2128                 return ENOBUFS;         /* XXX */
2129         }
2130
2131         ifp->if_opackets++;
2132         if (wpi_tx_data(sc, m, ni, 0) != 0)
2133                 goto bad;
2134         sc->sc_tx_timer = 5;
2135         callout_reset(&sc->watchdog_to, hz, wpi_watchdog, sc);
2136
2137         WPI_UNLOCK(sc);
2138         return 0;
2139 bad:
2140         ifp->if_oerrors++;
2141         WPI_UNLOCK(sc);
2142         ieee80211_free_node(ni);
2143         return EIO;             /* XXX */
2144 }
2145
2146 static int
2147 wpi_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data, struct ucred *cred)
2148 {
2149         struct wpi_softc *sc = ifp->if_softc;
2150         struct ieee80211com *ic = ifp->if_l2com;
2151         struct ifreq *ifr = (struct ifreq *) data;
2152         int error = 0, startall = 0;
2153
2154         switch (cmd) {
2155         case SIOCSIFFLAGS:
2156                 WPI_LOCK(sc);
2157                 if ((ifp->if_flags & IFF_UP)) {
2158                         if (!(ifp->if_flags & IFF_RUNNING)) {
2159                                 wpi_init_locked(sc, 0);
2160                                 startall = 1;
2161                         }
2162                 } else if ((ifp->if_flags & IFF_RUNNING) ||
2163                            (sc->flags & WPI_FLAG_HW_RADIO_OFF))
2164                         wpi_stop_locked(sc);
2165                 WPI_UNLOCK(sc);
2166                 if (startall)
2167                         ieee80211_start_all(ic);
2168                 break;
2169         case SIOCGIFMEDIA:
2170                 error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
2171                 break;
2172         case SIOCGIFADDR:
2173                 error = ether_ioctl(ifp, cmd, data);
2174                 break;
2175         default:
2176                 error = EINVAL;
2177                 break;
2178         }
2179         return error;
2180 }
2181
2182 /*
2183  * Extract various information from EEPROM.
2184  */
2185 static void
2186 wpi_read_eeprom(struct wpi_softc *sc, uint8_t macaddr[IEEE80211_ADDR_LEN])
2187 {
2188         int i;
2189
2190         /* read the hardware capabilities, revision and SKU type */
2191         wpi_read_prom_data(sc, WPI_EEPROM_CAPABILITIES, &sc->cap,1);
2192         wpi_read_prom_data(sc, WPI_EEPROM_REVISION, &sc->rev,2);
2193         wpi_read_prom_data(sc, WPI_EEPROM_TYPE, &sc->type, 1);
2194
2195         /* read the regulatory domain */
2196         wpi_read_prom_data(sc, WPI_EEPROM_DOMAIN, sc->domain, 4);
2197
2198         /* read in the hw MAC address */
2199         wpi_read_prom_data(sc, WPI_EEPROM_MAC, macaddr, 6);
2200
2201         /* read the list of authorized channels */
2202         for (i = 0; i < WPI_CHAN_BANDS_COUNT; i++)
2203                 wpi_read_eeprom_channels(sc,i);
2204
2205         /* read the power level calibration info for each group */
2206         for (i = 0; i < WPI_POWER_GROUPS_COUNT; i++)
2207                 wpi_read_eeprom_group(sc,i);
2208 }
2209
2210 /*
2211  * Send a command to the firmware.
2212  */
2213 static int
2214 wpi_cmd(struct wpi_softc *sc, int code, const void *buf, int size, int async)
2215 {
2216         struct wpi_tx_ring *ring = &sc->cmdq;
2217         struct wpi_tx_desc *desc;
2218         struct wpi_tx_cmd *cmd;
2219
2220 #ifdef WPI_DEBUG
2221         if (!async) {
2222                 WPI_LOCK_ASSERT(sc);
2223         }
2224 #endif
2225
2226         DPRINTFN(WPI_DEBUG_CMD,("wpi_cmd %d size %d async %d\n", code, size,
2227                     async));
2228
2229         if (sc->flags & WPI_FLAG_BUSY) {
2230                 device_printf(sc->sc_dev, "%s: cmd %d not sent, busy\n",
2231                     __func__, code);
2232                 return EAGAIN;
2233         }
2234         sc->flags|= WPI_FLAG_BUSY;
2235
2236         KASSERT(size <= sizeof cmd->data, ("command %d too large: %d bytes",
2237             code, size));
2238
2239         desc = &ring->desc[ring->cur];
2240         cmd = &ring->cmd[ring->cur];
2241
2242         cmd->code = code;
2243         cmd->flags = 0;
2244         cmd->qid = ring->qid;
2245         cmd->idx = ring->cur;
2246         memcpy(cmd->data, buf, size);
2247
2248         desc->flags = htole32(WPI_PAD32(size) << 28 | 1 << 24);
2249         desc->segs[0].addr = htole32(ring->cmd_dma.paddr +
2250                 ring->cur * sizeof (struct wpi_tx_cmd));
2251         desc->segs[0].len  = htole32(4 + size);
2252
2253         /* kick cmd ring */
2254         ring->cur = (ring->cur + 1) % WPI_CMD_RING_COUNT;
2255         WPI_WRITE(sc, WPI_TX_WIDX, ring->qid << 8 | ring->cur);
2256
2257         if (async) {
2258                 sc->flags &= ~ WPI_FLAG_BUSY;
2259                 return 0;
2260         }
2261
2262         return lksleep(cmd, &sc->sc_lock, 0, "wpicmd", hz);
2263 }
2264
2265 static int
2266 wpi_wme_update(struct ieee80211com *ic)
2267 {
2268 #define WPI_EXP2(v)     htole16((1 << (v)) - 1)
2269 #define WPI_USEC(v)     htole16(IEEE80211_TXOP_TO_US(v))
2270         struct wpi_softc *sc = ic->ic_ifp->if_softc;
2271         const struct wmeParams *wmep;
2272         struct wpi_wme_setup wme;
2273         int ac;
2274
2275         /* don't override default WME values if WME is not actually enabled */
2276         if (!(ic->ic_flags & IEEE80211_F_WME))
2277                 return 0;
2278
2279         wme.flags = 0;
2280         for (ac = 0; ac < WME_NUM_AC; ac++) {
2281                 wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
2282                 wme.ac[ac].aifsn = wmep->wmep_aifsn;
2283                 wme.ac[ac].cwmin = WPI_EXP2(wmep->wmep_logcwmin);
2284                 wme.ac[ac].cwmax = WPI_EXP2(wmep->wmep_logcwmax);
2285                 wme.ac[ac].txop  = WPI_USEC(wmep->wmep_txopLimit);
2286
2287                 DPRINTF(("setting WME for queue %d aifsn=%d cwmin=%d cwmax=%d "
2288                     "txop=%d\n", ac, wme.ac[ac].aifsn, wme.ac[ac].cwmin,
2289                     wme.ac[ac].cwmax, wme.ac[ac].txop));
2290         }
2291         return wpi_cmd(sc, WPI_CMD_SET_WME, &wme, sizeof wme, 1);
2292 #undef WPI_USEC
2293 #undef WPI_EXP2
2294 }
2295
2296 /*
2297  * Configure h/w multi-rate retries.
2298  */
2299 static int
2300 wpi_mrr_setup(struct wpi_softc *sc)
2301 {
2302         struct ifnet *ifp = sc->sc_ifp;
2303         struct ieee80211com *ic = ifp->if_l2com;
2304         struct wpi_mrr_setup mrr;
2305         int i, error;
2306
2307         memset(&mrr, 0, sizeof (struct wpi_mrr_setup));
2308
2309         /* CCK rates (not used with 802.11a) */
2310         for (i = WPI_CCK1; i <= WPI_CCK11; i++) {
2311                 mrr.rates[i].flags = 0;
2312                 mrr.rates[i].signal = wpi_ridx_to_plcp[i];
2313                 /* fallback to the immediate lower CCK rate (if any) */
2314                 mrr.rates[i].next = (i == WPI_CCK1) ? WPI_CCK1 : i - 1;
2315                 /* try one time at this rate before falling back to "next" */
2316                 mrr.rates[i].ntries = 1;
2317         }
2318
2319         /* OFDM rates (not used with 802.11b) */
2320         for (i = WPI_OFDM6; i <= WPI_OFDM54; i++) {
2321                 mrr.rates[i].flags = 0;
2322                 mrr.rates[i].signal = wpi_ridx_to_plcp[i];
2323                 /* fallback to the immediate lower OFDM rate (if any) */
2324                 /* we allow fallback from OFDM/6 to CCK/2 in 11b/g mode */
2325                 mrr.rates[i].next = (i == WPI_OFDM6) ?
2326                     ((ic->ic_curmode == IEEE80211_MODE_11A) ?
2327                         WPI_OFDM6 : WPI_CCK2) :
2328                     i - 1;
2329                 /* try one time at this rate before falling back to "next" */
2330                 mrr.rates[i].ntries = 1;
2331         }
2332
2333         /* setup MRR for control frames */
2334         mrr.which = htole32(WPI_MRR_CTL);
2335         error = wpi_cmd(sc, WPI_CMD_MRR_SETUP, &mrr, sizeof mrr, 0);
2336         if (error != 0) {
2337                 device_printf(sc->sc_dev,
2338                     "could not setup MRR for control frames\n");
2339                 return error;
2340         }
2341
2342         /* setup MRR for data frames */
2343         mrr.which = htole32(WPI_MRR_DATA);
2344         error = wpi_cmd(sc, WPI_CMD_MRR_SETUP, &mrr, sizeof mrr, 0);
2345         if (error != 0) {
2346                 device_printf(sc->sc_dev,
2347                     "could not setup MRR for data frames\n");
2348                 return error;
2349         }
2350
2351         return 0;
2352 }
2353
2354 static void
2355 wpi_set_led(struct wpi_softc *sc, uint8_t which, uint8_t off, uint8_t on)
2356 {
2357         struct wpi_cmd_led led;
2358
2359         led.which = which;
2360         led.unit = htole32(100000);     /* on/off in unit of 100ms */
2361         led.off = off;
2362         led.on = on;
2363
2364         (void)wpi_cmd(sc, WPI_CMD_SET_LED, &led, sizeof led, 1);
2365 }
2366
2367 static void
2368 wpi_enable_tsf(struct wpi_softc *sc, struct ieee80211_node *ni)
2369 {
2370         struct wpi_cmd_tsf tsf;
2371         uint64_t val, mod;
2372
2373         memset(&tsf, 0, sizeof tsf);
2374         memcpy(&tsf.tstamp, ni->ni_tstamp.data, 8);
2375         tsf.bintval = htole16(ni->ni_intval);
2376         tsf.lintval = htole16(10);
2377
2378         /* compute remaining time until next beacon */
2379         val = (uint64_t)ni->ni_intval  * 1024;  /* msec -> usec */
2380         mod = le64toh(tsf.tstamp) % val;
2381         tsf.binitval = htole32((uint32_t)(val - mod));
2382
2383         if (wpi_cmd(sc, WPI_CMD_TSF, &tsf, sizeof tsf, 1) != 0)
2384                 device_printf(sc->sc_dev, "could not enable TSF\n");
2385 }
2386
2387 #if 0
2388 /*
2389  * Build a beacon frame that the firmware will broadcast periodically in
2390  * IBSS or HostAP modes.
2391  */
2392 static int
2393 wpi_setup_beacon(struct wpi_softc *sc, struct ieee80211_node *ni)
2394 {
2395         struct ifnet *ifp = sc->sc_ifp;
2396         struct ieee80211com *ic = ifp->if_l2com;
2397         struct wpi_tx_ring *ring = &sc->cmdq;
2398         struct wpi_tx_desc *desc;
2399         struct wpi_tx_data *data;
2400         struct wpi_tx_cmd *cmd;
2401         struct wpi_cmd_beacon *bcn;
2402         struct ieee80211_beacon_offsets bo;
2403         struct mbuf *m0;
2404         bus_addr_t physaddr;
2405         int error;
2406
2407         desc = &ring->desc[ring->cur];
2408         data = &ring->data[ring->cur];
2409
2410         m0 = ieee80211_beacon_alloc(ic, ni, &bo);
2411         if (m0 == NULL) {
2412                 device_printf(sc->sc_dev, "could not allocate beacon frame\n");
2413                 return ENOMEM;
2414         }
2415
2416         cmd = &ring->cmd[ring->cur];
2417         cmd->code = WPI_CMD_SET_BEACON;
2418         cmd->flags = 0;
2419         cmd->qid = ring->qid;
2420         cmd->idx = ring->cur;
2421
2422         bcn = (struct wpi_cmd_beacon *)cmd->data;
2423         memset(bcn, 0, sizeof (struct wpi_cmd_beacon));
2424         bcn->id = WPI_ID_BROADCAST;
2425         bcn->ofdm_mask = 0xff;
2426         bcn->cck_mask = 0x0f;
2427         bcn->lifetime = htole32(WPI_LIFETIME_INFINITE);
2428         bcn->len = htole16(m0->m_pkthdr.len);
2429         bcn->rate = (ic->ic_curmode == IEEE80211_MODE_11A) ?
2430                 wpi_plcp_signal(12) : wpi_plcp_signal(2);
2431         bcn->flags = htole32(WPI_TX_AUTO_SEQ | WPI_TX_INSERT_TSTAMP);
2432
2433         /* save and trim IEEE802.11 header */
2434         m_copydata(m0, 0, sizeof (struct ieee80211_frame), (caddr_t)&bcn->wh);
2435         m_adj(m0, sizeof (struct ieee80211_frame));
2436
2437         /* assume beacon frame is contiguous */
2438         error = bus_dmamap_load(ring->data_dmat, data->map, mtod(m0, void *),
2439             m0->m_pkthdr.len, wpi_dma_map_addr, &physaddr, 0);
2440         if (error != 0) {
2441                 device_printf(sc->sc_dev, "could not map beacon\n");
2442                 m_freem(m0);
2443                 return error;
2444         }
2445
2446         data->m = m0;
2447
2448         /* first scatter/gather segment is used by the beacon command */
2449         desc->flags = htole32(WPI_PAD32(m0->m_pkthdr.len) << 28 | 2 << 24);
2450         desc->segs[0].addr = htole32(ring->cmd_dma.paddr +
2451                 ring->cur * sizeof (struct wpi_tx_cmd));
2452         desc->segs[0].len  = htole32(4 + sizeof (struct wpi_cmd_beacon));
2453         desc->segs[1].addr = htole32(physaddr);
2454         desc->segs[1].len  = htole32(m0->m_pkthdr.len);
2455
2456         /* kick cmd ring */
2457         ring->cur = (ring->cur + 1) % WPI_CMD_RING_COUNT;
2458         WPI_WRITE(sc, WPI_TX_WIDX, ring->qid << 8 | ring->cur);
2459
2460         return 0;
2461 }
2462 #endif
2463
2464 static int
2465 wpi_auth(struct wpi_softc *sc, struct ieee80211vap *vap)
2466 {
2467         struct ieee80211com *ic = vap->iv_ic;
2468         struct ieee80211_node *ni = vap->iv_bss;
2469         struct wpi_node_info node;
2470         int error;
2471
2472
2473         /* update adapter's configuration */
2474         sc->config.associd = 0;
2475         sc->config.filter &= ~htole32(WPI_FILTER_BSS);
2476         IEEE80211_ADDR_COPY(sc->config.bssid, ni->ni_bssid);
2477         sc->config.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
2478         if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) {
2479                 sc->config.flags |= htole32(WPI_CONFIG_AUTO |
2480                     WPI_CONFIG_24GHZ);
2481         }
2482         if (IEEE80211_IS_CHAN_A(ni->ni_chan)) {
2483                 sc->config.cck_mask  = 0;
2484                 sc->config.ofdm_mask = 0x15;
2485         } else if (IEEE80211_IS_CHAN_B(ni->ni_chan)) {
2486                 sc->config.cck_mask  = 0x03;
2487                 sc->config.ofdm_mask = 0;
2488         } else {
2489                 /* XXX assume 802.11b/g */
2490                 sc->config.cck_mask  = 0x0f;
2491                 sc->config.ofdm_mask = 0x15;
2492         }
2493
2494         DPRINTF(("config chan %d flags %x cck %x ofdm %x\n", sc->config.chan,
2495                 sc->config.flags, sc->config.cck_mask, sc->config.ofdm_mask));
2496         error = wpi_cmd(sc, WPI_CMD_CONFIGURE, &sc->config,
2497                 sizeof (struct wpi_config), 1);
2498         if (error != 0) {
2499                 device_printf(sc->sc_dev, "could not configure\n");
2500                 return error;
2501         }
2502
2503         /* configuration has changed, set Tx power accordingly */
2504         if ((error = wpi_set_txpower(sc, ni->ni_chan, 1)) != 0) {
2505                 device_printf(sc->sc_dev, "could not set Tx power\n");
2506                 return error;
2507         }
2508
2509         /* add default node */
2510         memset(&node, 0, sizeof node);
2511         IEEE80211_ADDR_COPY(node.bssid, ni->ni_bssid);
2512         node.id = WPI_ID_BSS;
2513         node.rate = (ic->ic_curmode == IEEE80211_MODE_11A) ?
2514             wpi_plcp_signal(12) : wpi_plcp_signal(2);
2515         node.action = htole32(WPI_ACTION_SET_RATE);
2516         node.antenna = WPI_ANTENNA_BOTH;
2517         error = wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, 1);
2518         if (error != 0)
2519                 device_printf(sc->sc_dev, "could not add BSS node\n");
2520
2521         return (error);
2522 }
2523
2524 static int
2525 wpi_run(struct wpi_softc *sc, struct ieee80211vap *vap)
2526 {
2527         struct ieee80211com *ic = vap->iv_ic;
2528         struct ieee80211_node *ni = vap->iv_bss;
2529         int error;
2530
2531         if (vap->iv_opmode == IEEE80211_M_MONITOR) {
2532                 /* link LED blinks while monitoring */
2533                 wpi_set_led(sc, WPI_LED_LINK, 5, 5);
2534                 return 0;
2535         }
2536
2537         wpi_enable_tsf(sc, ni);
2538
2539         /* update adapter's configuration */
2540         sc->config.associd = htole16(ni->ni_associd & ~0xc000);
2541         /* short preamble/slot time are negotiated when associating */
2542         sc->config.flags &= ~htole32(WPI_CONFIG_SHPREAMBLE |
2543             WPI_CONFIG_SHSLOT);
2544         if (ic->ic_flags & IEEE80211_F_SHSLOT)
2545                 sc->config.flags |= htole32(WPI_CONFIG_SHSLOT);
2546         if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
2547                 sc->config.flags |= htole32(WPI_CONFIG_SHPREAMBLE);
2548         sc->config.filter |= htole32(WPI_FILTER_BSS);
2549
2550         /* XXX put somewhere HC_QOS_SUPPORT_ASSOC + HC_IBSS_START */
2551
2552         DPRINTF(("config chan %d flags %x\n", sc->config.chan,
2553                     sc->config.flags));
2554         error = wpi_cmd(sc, WPI_CMD_CONFIGURE, &sc->config, sizeof (struct
2555                     wpi_config), 1);
2556         if (error != 0) {
2557                 device_printf(sc->sc_dev, "could not update configuration\n");
2558                 return error;
2559         }
2560
2561         error = wpi_set_txpower(sc, ni->ni_chan, 1);
2562         if (error != 0) {
2563                 device_printf(sc->sc_dev, "could set txpower\n");
2564                 return error;
2565         }
2566
2567         /* link LED always on while associated */
2568         wpi_set_led(sc, WPI_LED_LINK, 0, 1);
2569
2570         /* start automatic rate control timer */
2571         callout_reset(&sc->calib_to, 60*hz, wpi_calib_timeout, sc);
2572
2573         return (error);
2574 }
2575
2576 /*
2577  * Send a scan request to the firmware.  Since this command is huge, we map it
2578  * into a mbufcluster instead of using the pre-allocated set of commands. Note,
2579  * much of this code is similar to that in wpi_cmd but because we must manually
2580  * construct the probe & channels, we duplicate what's needed here. XXX In the
2581  * future, this function should be modified to use wpi_cmd to help cleanup the
2582  * code base.
2583  */
2584 static int
2585 wpi_scan(struct wpi_softc *sc)
2586 {
2587         struct ifnet *ifp = sc->sc_ifp;
2588         struct ieee80211com *ic = ifp->if_l2com;
2589         struct ieee80211_scan_state *ss = ic->ic_scan;
2590         struct wpi_tx_ring *ring = &sc->cmdq;
2591         struct wpi_tx_desc *desc;
2592         struct wpi_tx_data *data;
2593         struct wpi_tx_cmd *cmd;
2594         struct wpi_scan_hdr *hdr;
2595         struct wpi_scan_chan *chan;
2596         struct ieee80211_frame *wh;
2597         struct ieee80211_rateset *rs;
2598         struct ieee80211_channel *c;
2599         enum ieee80211_phymode mode;
2600         uint8_t *frm;
2601         int nrates, pktlen, error, i, nssid;
2602         bus_addr_t physaddr;
2603
2604         desc = &ring->desc[ring->cur];
2605         data = &ring->data[ring->cur];
2606
2607         data->m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2608         if (data->m == NULL) {
2609                 device_printf(sc->sc_dev,
2610                     "could not allocate mbuf for scan command\n");
2611                 return ENOMEM;
2612         }
2613
2614         cmd = mtod(data->m, struct wpi_tx_cmd *);
2615         cmd->code = WPI_CMD_SCAN;
2616         cmd->flags = 0;
2617         cmd->qid = ring->qid;
2618         cmd->idx = ring->cur;
2619
2620         hdr = (struct wpi_scan_hdr *)cmd->data;
2621         memset(hdr, 0, sizeof(struct wpi_scan_hdr));
2622
2623         /*
2624          * Move to the next channel if no packets are received within 5 msecs
2625          * after sending the probe request (this helps to reduce the duration
2626          * of active scans).
2627          */
2628         hdr->quiet = htole16(5);
2629         hdr->threshold = htole16(1);
2630
2631         if (IEEE80211_IS_CHAN_A(ic->ic_curchan)) {
2632                 /* send probe requests at 6Mbps */
2633                 hdr->tx.rate = wpi_ridx_to_plcp[WPI_OFDM6];
2634
2635                 /* Enable crc checking */
2636                 hdr->promotion = htole16(1);
2637         } else {
2638                 hdr->flags = htole32(WPI_CONFIG_24GHZ | WPI_CONFIG_AUTO);
2639                 /* send probe requests at 1Mbps */
2640                 hdr->tx.rate = wpi_ridx_to_plcp[WPI_CCK1];
2641         }
2642         hdr->tx.id = WPI_ID_BROADCAST;
2643         hdr->tx.lifetime = htole32(WPI_LIFETIME_INFINITE);
2644         hdr->tx.flags = htole32(WPI_TX_AUTO_SEQ);
2645
2646         memset(hdr->scan_essids, 0, sizeof(hdr->scan_essids));
2647         nssid = MIN(ss->ss_nssid, WPI_SCAN_MAX_ESSIDS);
2648         for (i = 0; i < nssid; i++) {
2649                 hdr->scan_essids[i].id = IEEE80211_ELEMID_SSID;
2650                 hdr->scan_essids[i].esslen = MIN(ss->ss_ssid[i].len, 32);
2651                 memcpy(hdr->scan_essids[i].essid, ss->ss_ssid[i].ssid,
2652                     hdr->scan_essids[i].esslen);
2653 #ifdef WPI_DEBUG
2654                 if (wpi_debug & WPI_DEBUG_SCANNING) {
2655                         kprintf("Scanning Essid: ");
2656                         ieee80211_print_essid(hdr->scan_essids[i].essid,
2657                             hdr->scan_essids[i].esslen);
2658                         kprintf("\n");
2659                 }
2660 #endif
2661         }
2662
2663         /*
2664          * Build a probe request frame.  Most of the following code is a
2665          * copy & paste of what is done in net80211.
2666          */
2667         wh = (struct ieee80211_frame *)&hdr->scan_essids[4];
2668         wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
2669                 IEEE80211_FC0_SUBTYPE_PROBE_REQ;
2670         wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
2671         IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
2672         IEEE80211_ADDR_COPY(wh->i_addr2, IF_LLADDR(ifp));
2673         IEEE80211_ADDR_COPY(wh->i_addr3, ifp->if_broadcastaddr);
2674         *(u_int16_t *)&wh->i_dur[0] = 0;        /* filled by h/w */
2675         *(u_int16_t *)&wh->i_seq[0] = 0;        /* filled by h/w */
2676
2677         frm = (uint8_t *)(wh + 1);
2678
2679         /* add essid IE, the hardware will fill this in for us */
2680         *frm++ = IEEE80211_ELEMID_SSID;
2681         *frm++ = 0;
2682
2683         mode = ieee80211_chan2mode(ic->ic_curchan);
2684         rs = &ic->ic_sup_rates[mode];
2685
2686         /* add supported rates IE */
2687         *frm++ = IEEE80211_ELEMID_RATES;
2688         nrates = rs->rs_nrates;
2689         if (nrates > IEEE80211_RATE_SIZE)
2690                 nrates = IEEE80211_RATE_SIZE;
2691         *frm++ = nrates;
2692         memcpy(frm, rs->rs_rates, nrates);
2693         frm += nrates;
2694
2695         /* add supported xrates IE */
2696         if (rs->rs_nrates > IEEE80211_RATE_SIZE) {
2697                 nrates = rs->rs_nrates - IEEE80211_RATE_SIZE;
2698                 *frm++ = IEEE80211_ELEMID_XRATES;
2699                 *frm++ = nrates;
2700                 memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates);
2701                 frm += nrates;
2702         }
2703
2704         /* setup length of probe request */
2705         hdr->tx.len = htole16(frm - (uint8_t *)wh);
2706
2707         /*
2708          * Construct information about the channel that we
2709          * want to scan. The firmware expects this to be directly
2710          * after the scan probe request
2711          */
2712         c = ic->ic_curchan;
2713         chan = (struct wpi_scan_chan *)frm;
2714         chan->chan = ieee80211_chan2ieee(ic, c);
2715         chan->flags = 0;
2716         if (!(c->ic_flags & IEEE80211_CHAN_PASSIVE)) {
2717                 chan->flags |= WPI_CHAN_ACTIVE;
2718                 if (nssid != 0)
2719                         chan->flags |= WPI_CHAN_DIRECT;
2720         }
2721         chan->gain_dsp = 0x6e; /* Default level */
2722         if (IEEE80211_IS_CHAN_5GHZ(c)) {
2723                 chan->active = htole16(10);
2724                 chan->passive = htole16(ss->ss_maxdwell);
2725                 chan->gain_radio = 0x3b;
2726         } else {
2727                 chan->active = htole16(20);
2728                 chan->passive = htole16(ss->ss_maxdwell);
2729                 chan->gain_radio = 0x28;
2730         }
2731
2732         DPRINTFN(WPI_DEBUG_SCANNING,
2733             ("Scanning %u Passive: %d\n",
2734              chan->chan,
2735              c->ic_flags & IEEE80211_CHAN_PASSIVE));
2736
2737         hdr->nchan++;
2738         chan++;
2739
2740         frm += sizeof (struct wpi_scan_chan);
2741 #if 0
2742         // XXX All Channels....
2743         for (c  = &ic->ic_channels[1];
2744              c <= &ic->ic_channels[IEEE80211_CHAN_MAX]; c++) {
2745                 if ((c->ic_flags & ic->ic_curchan->ic_flags) != ic->ic_curchan->ic_flags)
2746                         continue;
2747
2748                 chan->chan = ieee80211_chan2ieee(ic, c);
2749                 chan->flags = 0;
2750                 if (!(c->ic_flags & IEEE80211_CHAN_PASSIVE)) {
2751                     chan->flags |= WPI_CHAN_ACTIVE;
2752                     if (ic->ic_des_ssid[0].len != 0)
2753                         chan->flags |= WPI_CHAN_DIRECT;
2754                 }
2755                 chan->gain_dsp = 0x6e; /* Default level */
2756                 if (IEEE80211_IS_CHAN_5GHZ(c)) {
2757                         chan->active = htole16(10);
2758                         chan->passive = htole16(110);
2759                         chan->gain_radio = 0x3b;
2760                 } else {
2761                         chan->active = htole16(20);
2762                         chan->passive = htole16(120);
2763                         chan->gain_radio = 0x28;
2764                 }
2765
2766                 DPRINTFN(WPI_DEBUG_SCANNING,
2767                          ("Scanning %u Passive: %d\n",
2768                           chan->chan,
2769                           c->ic_flags & IEEE80211_CHAN_PASSIVE));
2770
2771                 hdr->nchan++;
2772                 chan++;
2773
2774                 frm += sizeof (struct wpi_scan_chan);
2775         }
2776 #endif
2777
2778         hdr->len = htole16(frm - (uint8_t *)hdr);
2779         pktlen = frm - (uint8_t *)cmd;
2780
2781         error = bus_dmamap_load(ring->data_dmat, data->map, cmd, pktlen,
2782             wpi_dma_map_addr, &physaddr, BUS_DMA_NOWAIT);
2783         if (error != 0) {
2784                 device_printf(sc->sc_dev, "could not map scan command\n");
2785                 m_freem(data->m);
2786                 data->m = NULL;
2787                 return error;
2788         }
2789
2790         desc->flags = htole32(WPI_PAD32(pktlen) << 28 | 1 << 24);
2791         desc->segs[0].addr = htole32(physaddr);
2792         desc->segs[0].len  = htole32(pktlen);
2793
2794         bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
2795             BUS_DMASYNC_PREWRITE);
2796         bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
2797
2798         /* kick cmd ring */
2799         ring->cur = (ring->cur + 1) % WPI_CMD_RING_COUNT;
2800         WPI_WRITE(sc, WPI_TX_WIDX, ring->qid << 8 | ring->cur);
2801
2802         sc->sc_scan_timer = 5;
2803         return 0;       /* will be notified async. of failure/success */
2804 }
2805
2806 /**
2807  * Configure the card to listen to a particular channel, this transisions the
2808  * card in to being able to receive frames from remote devices.
2809  */
2810 static int
2811 wpi_config(struct wpi_softc *sc)
2812 {
2813         struct ifnet *ifp = sc->sc_ifp;
2814         struct ieee80211com *ic = ifp->if_l2com;
2815         struct wpi_power power;
2816         struct wpi_bluetooth bluetooth;
2817         struct wpi_node_info node;
2818         int error;
2819
2820         /* set power mode */
2821         memset(&power, 0, sizeof power);
2822         power.flags = htole32(WPI_POWER_CAM|0x8);
2823         error = wpi_cmd(sc, WPI_CMD_SET_POWER_MODE, &power, sizeof power, 0);
2824         if (error != 0) {
2825                 device_printf(sc->sc_dev, "could not set power mode\n");
2826                 return error;
2827         }
2828
2829         /* configure bluetooth coexistence */
2830         memset(&bluetooth, 0, sizeof bluetooth);
2831         bluetooth.flags = 3;
2832         bluetooth.lead = 0xaa;
2833         bluetooth.kill = 1;
2834         error = wpi_cmd(sc, WPI_CMD_BLUETOOTH, &bluetooth, sizeof bluetooth,
2835             0);
2836         if (error != 0) {
2837                 device_printf(sc->sc_dev,
2838                     "could not configure bluetooth coexistence\n");
2839                 return error;
2840         }
2841
2842         /* configure adapter */
2843         memset(&sc->config, 0, sizeof (struct wpi_config));
2844         IEEE80211_ADDR_COPY(sc->config.myaddr, IF_LLADDR(ifp));
2845         /*set default channel*/
2846         sc->config.chan = htole16(ieee80211_chan2ieee(ic, ic->ic_curchan));
2847         sc->config.flags = htole32(WPI_CONFIG_TSF);
2848         if (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan)) {
2849                 sc->config.flags |= htole32(WPI_CONFIG_AUTO |
2850                     WPI_CONFIG_24GHZ);
2851         }
2852         sc->config.filter = 0;
2853         switch (ic->ic_opmode) {
2854         case IEEE80211_M_STA:
2855         case IEEE80211_M_WDS:   /* No know setup, use STA for now */
2856                 sc->config.mode = WPI_MODE_STA;
2857                 sc->config.filter |= htole32(WPI_FILTER_MULTICAST);
2858                 break;
2859         case IEEE80211_M_IBSS:
2860         case IEEE80211_M_AHDEMO:
2861                 sc->config.mode = WPI_MODE_IBSS;
2862                 sc->config.filter |= htole32(WPI_FILTER_BEACON |
2863                                              WPI_FILTER_MULTICAST);
2864                 break;
2865         case IEEE80211_M_HOSTAP:
2866                 sc->config.mode = WPI_MODE_HOSTAP;
2867                 break;
2868         case IEEE80211_M_MONITOR:
2869                 sc->config.mode = WPI_MODE_MONITOR;
2870                 sc->config.filter |= htole32(WPI_FILTER_MULTICAST |
2871                         WPI_FILTER_CTL | WPI_FILTER_PROMISC);
2872                 break;
2873         default:
2874                 device_printf(sc->sc_dev, "unknown opmode %d\n", ic->ic_opmode);
2875                 return EINVAL;
2876         }
2877         sc->config.cck_mask  = 0x0f;    /* not yet negotiated */
2878         sc->config.ofdm_mask = 0xff;    /* not yet negotiated */
2879         error = wpi_cmd(sc, WPI_CMD_CONFIGURE, &sc->config,
2880                 sizeof (struct wpi_config), 0);
2881         if (error != 0) {
2882                 device_printf(sc->sc_dev, "configure command failed\n");
2883                 return error;
2884         }
2885
2886         /* configuration has changed, set Tx power accordingly */
2887         if ((error = wpi_set_txpower(sc, ic->ic_curchan, 0)) != 0) {
2888             device_printf(sc->sc_dev, "could not set Tx power\n");
2889             return error;
2890         }
2891
2892         /* add broadcast node */
2893         memset(&node, 0, sizeof node);
2894         IEEE80211_ADDR_COPY(node.bssid, ifp->if_broadcastaddr);
2895         node.id = WPI_ID_BROADCAST;
2896         node.rate = wpi_plcp_signal(2);
2897         error = wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, 0);
2898         if (error != 0) {
2899                 device_printf(sc->sc_dev, "could not add broadcast node\n");
2900                 return error;
2901         }
2902
2903         /* Setup rate scalling */
2904         error = wpi_mrr_setup(sc);
2905         if (error != 0) {
2906                 device_printf(sc->sc_dev, "could not setup MRR\n");
2907                 return error;
2908         }
2909
2910         return 0;
2911 }
2912
2913 static void
2914 wpi_stop_master(struct wpi_softc *sc)
2915 {
2916         uint32_t tmp;
2917         int ntries;
2918
2919         DPRINTFN(WPI_DEBUG_HW,("Disabling Firmware execution\n"));
2920
2921         tmp = WPI_READ(sc, WPI_RESET);
2922         WPI_WRITE(sc, WPI_RESET, tmp | WPI_STOP_MASTER | WPI_NEVO_RESET);
2923
2924         tmp = WPI_READ(sc, WPI_GPIO_CTL);
2925         if ((tmp & WPI_GPIO_PWR_STATUS) == WPI_GPIO_PWR_SLEEP)
2926                 return; /* already asleep */
2927
2928         for (ntries = 0; ntries < 100; ntries++) {
2929                 if (WPI_READ(sc, WPI_RESET) & WPI_MASTER_DISABLED)
2930                         break;
2931                 DELAY(10);
2932         }
2933         if (ntries == 100) {
2934                 device_printf(sc->sc_dev, "timeout waiting for master\n");
2935         }
2936 }
2937
2938 static int
2939 wpi_power_up(struct wpi_softc *sc)
2940 {
2941         uint32_t tmp;
2942         int ntries;
2943
2944         wpi_mem_lock(sc);
2945         tmp = wpi_mem_read(sc, WPI_MEM_POWER);
2946         wpi_mem_write(sc, WPI_MEM_POWER, tmp & ~0x03000000);
2947         wpi_mem_unlock(sc);
2948
2949         for (ntries = 0; ntries < 5000; ntries++) {
2950                 if (WPI_READ(sc, WPI_GPIO_STATUS) & WPI_POWERED)
2951                         break;
2952                 DELAY(10);
2953         }
2954         if (ntries == 5000) {
2955                 device_printf(sc->sc_dev,
2956                     "timeout waiting for NIC to power up\n");
2957                 return ETIMEDOUT;
2958         }
2959         return 0;
2960 }
2961
2962 static int
2963 wpi_reset(struct wpi_softc *sc)
2964 {
2965         uint32_t tmp;
2966         int ntries;
2967
2968         DPRINTFN(WPI_DEBUG_HW,
2969             ("Resetting the card - clearing any uploaded firmware\n"));
2970
2971         /* clear any pending interrupts */
2972         WPI_WRITE(sc, WPI_INTR, 0xffffffff);
2973
2974         tmp = WPI_READ(sc, WPI_PLL_CTL);
2975         WPI_WRITE(sc, WPI_PLL_CTL, tmp | WPI_PLL_INIT);
2976
2977         tmp = WPI_READ(sc, WPI_CHICKEN);
2978         WPI_WRITE(sc, WPI_CHICKEN, tmp | WPI_CHICKEN_RXNOLOS);
2979
2980         tmp = WPI_READ(sc, WPI_GPIO_CTL);
2981         WPI_WRITE(sc, WPI_GPIO_CTL, tmp | WPI_GPIO_INIT);
2982
2983         /* wait for clock stabilization */
2984         for (ntries = 0; ntries < 25000; ntries++) {
2985                 if (WPI_READ(sc, WPI_GPIO_CTL) & WPI_GPIO_CLOCK)
2986                         break;
2987                 DELAY(10);
2988         }
2989         if (ntries == 25000) {
2990                 device_printf(sc->sc_dev,
2991                     "timeout waiting for clock stabilization\n");
2992                 return ETIMEDOUT;
2993         }
2994
2995         /* initialize EEPROM */
2996         tmp = WPI_READ(sc, WPI_EEPROM_STATUS);
2997
2998         if ((tmp & WPI_EEPROM_VERSION) == 0) {
2999                 device_printf(sc->sc_dev, "EEPROM not found\n");
3000                 return EIO;
3001         }
3002         WPI_WRITE(sc, WPI_EEPROM_STATUS, tmp & ~WPI_EEPROM_LOCKED);
3003
3004         return 0;
3005 }
3006
3007 static void
3008 wpi_hw_config(struct wpi_softc *sc)
3009 {
3010         uint32_t rev, hw;
3011
3012         /* voodoo from the Linux "driver".. */
3013         hw = WPI_READ(sc, WPI_HWCONFIG);
3014
3015         rev = pci_read_config(sc->sc_dev, PCIR_REVID, 1);
3016         if ((rev & 0xc0) == 0x40)
3017                 hw |= WPI_HW_ALM_MB;
3018         else if (!(rev & 0x80))
3019                 hw |= WPI_HW_ALM_MM;
3020
3021         if (sc->cap == 0x80)
3022                 hw |= WPI_HW_SKU_MRC;
3023
3024         hw &= ~WPI_HW_REV_D;
3025         if ((le16toh(sc->rev) & 0xf0) == 0xd0)
3026                 hw |= WPI_HW_REV_D;
3027
3028         if (sc->type > 1)
3029                 hw |= WPI_HW_TYPE_B;
3030
3031         WPI_WRITE(sc, WPI_HWCONFIG, hw);
3032 }
3033
3034 static void
3035 wpi_rfkill_resume(struct wpi_softc *sc)
3036 {
3037         struct ifnet *ifp = sc->sc_ifp;
3038         struct ieee80211com *ic = ifp->if_l2com;
3039         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3040         int ntries;
3041
3042         /* enable firmware again */
3043         WPI_WRITE(sc, WPI_UCODE_CLR, WPI_RADIO_OFF);
3044         WPI_WRITE(sc, WPI_UCODE_CLR, WPI_DISABLE_CMD);
3045
3046         /* wait for thermal sensors to calibrate */
3047         for (ntries = 0; ntries < 1000; ntries++) {
3048                 if ((sc->temp = (int)WPI_READ(sc, WPI_TEMPERATURE)) != 0)
3049                         break;
3050                 DELAY(10);
3051         }
3052
3053         if (ntries == 1000) {
3054                 device_printf(sc->sc_dev,
3055                     "timeout waiting for thermal calibration\n");
3056                 WPI_UNLOCK(sc);
3057                 return;
3058         }
3059         DPRINTFN(WPI_DEBUG_TEMP,("temperature %d\n", sc->temp));
3060
3061         if (wpi_config(sc) != 0) {
3062                 device_printf(sc->sc_dev, "device config failed\n");
3063                 WPI_UNLOCK(sc);
3064                 return;
3065         }
3066
3067         ifp->if_flags &= ~IFF_OACTIVE;
3068         ifp->if_flags |= IFF_RUNNING;
3069         sc->flags &= ~WPI_FLAG_HW_RADIO_OFF;
3070
3071         if (vap != NULL) {
3072                 if ((ic->ic_flags & IEEE80211_F_SCAN) == 0) {
3073                         if (vap->iv_opmode != IEEE80211_M_MONITOR) {
3074                                 ieee80211_beacon_miss(ic);
3075                                 wpi_set_led(sc, WPI_LED_LINK, 0, 1);
3076                         } else
3077                                 wpi_set_led(sc, WPI_LED_LINK, 5, 5);
3078                 } else {
3079                         ieee80211_scan_next(vap);
3080                         wpi_set_led(sc, WPI_LED_LINK, 20, 2);
3081                 }
3082         }
3083
3084         callout_reset(&sc->watchdog_to, hz, wpi_watchdog, sc);
3085 }
3086
3087 static void
3088 wpi_init_locked(struct wpi_softc *sc, int force)
3089 {
3090         struct ifnet *ifp = sc->sc_ifp;
3091         uint32_t tmp;
3092         int ntries, qid;
3093
3094         wpi_stop_locked(sc);
3095         (void)wpi_reset(sc);
3096
3097         wpi_mem_lock(sc);
3098         wpi_mem_write(sc, WPI_MEM_CLOCK1, 0xa00);
3099         DELAY(20);
3100         tmp = wpi_mem_read(sc, WPI_MEM_PCIDEV);
3101         wpi_mem_write(sc, WPI_MEM_PCIDEV, tmp | 0x800);
3102         wpi_mem_unlock(sc);
3103
3104         (void)wpi_power_up(sc);
3105         wpi_hw_config(sc);
3106
3107         /* init Rx ring */
3108         wpi_mem_lock(sc);
3109         WPI_WRITE(sc, WPI_RX_BASE, sc->rxq.desc_dma.paddr);
3110         WPI_WRITE(sc, WPI_RX_RIDX_PTR, sc->shared_dma.paddr +
3111             offsetof(struct wpi_shared, next));
3112         WPI_WRITE(sc, WPI_RX_WIDX, (WPI_RX_RING_COUNT - 1) & ~7);
3113         WPI_WRITE(sc, WPI_RX_CONFIG, 0xa9601010);
3114         wpi_mem_unlock(sc);
3115
3116         /* init Tx rings */
3117         wpi_mem_lock(sc);
3118         wpi_mem_write(sc, WPI_MEM_MODE, 2); /* bypass mode */
3119         wpi_mem_write(sc, WPI_MEM_RA, 1);   /* enable RA0 */
3120         wpi_mem_write(sc, WPI_MEM_TXCFG, 0x3f); /* enable all 6 Tx rings */
3121         wpi_mem_write(sc, WPI_MEM_BYPASS1, 0x10000);
3122         wpi_mem_write(sc, WPI_MEM_BYPASS2, 0x30002);
3123         wpi_mem_write(sc, WPI_MEM_MAGIC4, 4);
3124         wpi_mem_write(sc, WPI_MEM_MAGIC5, 5);
3125
3126         WPI_WRITE(sc, WPI_TX_BASE_PTR, sc->shared_dma.paddr);
3127         WPI_WRITE(sc, WPI_MSG_CONFIG, 0xffff05a5);
3128
3129         for (qid = 0; qid < 6; qid++) {
3130                 WPI_WRITE(sc, WPI_TX_CTL(qid), 0);
3131                 WPI_WRITE(sc, WPI_TX_BASE(qid), 0);
3132                 WPI_WRITE(sc, WPI_TX_CONFIG(qid), 0x80200008);
3133         }
3134         wpi_mem_unlock(sc);
3135
3136         /* clear "radio off" and "disable command" bits (reversed logic) */
3137         WPI_WRITE(sc, WPI_UCODE_CLR, WPI_RADIO_OFF);
3138         WPI_WRITE(sc, WPI_UCODE_CLR, WPI_DISABLE_CMD);
3139         sc->flags &= ~WPI_FLAG_HW_RADIO_OFF;
3140
3141         /* clear any pending interrupts */
3142         WPI_WRITE(sc, WPI_INTR, 0xffffffff);
3143
3144         /* enable interrupts */
3145         WPI_WRITE(sc, WPI_MASK, WPI_INTR_MASK);
3146
3147         WPI_WRITE(sc, WPI_UCODE_CLR, WPI_RADIO_OFF);
3148         WPI_WRITE(sc, WPI_UCODE_CLR, WPI_RADIO_OFF);
3149
3150         if ((wpi_load_firmware(sc)) != 0) {
3151             device_printf(sc->sc_dev,
3152                 "A problem occurred loading the firmware to the driver\n");
3153             return;
3154         }
3155
3156         /* At this point the firmware is up and running. If the hardware
3157          * RF switch is turned off thermal calibration will fail, though
3158          * the card is still happy to continue to accept commands, catch
3159          * this case and schedule a task to watch for it to be turned on.
3160          */
3161         wpi_mem_lock(sc);
3162         tmp = wpi_mem_read(sc, WPI_MEM_HW_RADIO_OFF);
3163         wpi_mem_unlock(sc);
3164
3165         if (!(tmp & 0x1)) {
3166                 sc->flags |= WPI_FLAG_HW_RADIO_OFF;
3167                 device_printf(sc->sc_dev,"Radio Transmitter is switched off\n");
3168                 goto out;
3169         }
3170
3171         /* wait for thermal sensors to calibrate */
3172         for (ntries = 0; ntries < 1000; ntries++) {
3173                 if ((sc->temp = (int)WPI_READ(sc, WPI_TEMPERATURE)) != 0)
3174                         break;
3175                 DELAY(10);
3176         }
3177
3178         if (ntries == 1000) {
3179                 device_printf(sc->sc_dev,
3180                     "timeout waiting for thermal sensors calibration\n");
3181                 return;
3182         }
3183         DPRINTFN(WPI_DEBUG_TEMP,("temperature %d\n", sc->temp));
3184
3185         if (wpi_config(sc) != 0) {
3186                 device_printf(sc->sc_dev, "device config failed\n");
3187                 return;
3188         }
3189
3190         ifp->if_flags &= ~IFF_OACTIVE;
3191         ifp->if_flags |= IFF_RUNNING;
3192 out:
3193         callout_reset(&sc->watchdog_to, hz, wpi_watchdog, sc);
3194 }
3195
3196 static void
3197 wpi_init(void *arg)
3198 {
3199         struct wpi_softc *sc = arg;
3200         struct ifnet *ifp = sc->sc_ifp;
3201         struct ieee80211com *ic = ifp->if_l2com;
3202
3203         WPI_LOCK(sc);
3204         wpi_init_locked(sc, 0);
3205         WPI_UNLOCK(sc);
3206
3207         if (ifp->if_flags & IFF_RUNNING)
3208                 ieee80211_start_all(ic);                /* start all vaps */
3209 }
3210
3211 static void
3212 wpi_stop_locked(struct wpi_softc *sc)
3213 {
3214         struct ifnet *ifp = sc->sc_ifp;
3215         uint32_t tmp;
3216         int ac;
3217
3218         sc->sc_tx_timer = 0;
3219         sc->sc_scan_timer = 0;
3220         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
3221         sc->flags &= ~WPI_FLAG_HW_RADIO_OFF;
3222         callout_stop(&sc->watchdog_to);
3223         callout_stop(&sc->calib_to);
3224
3225
3226         /* disable interrupts */
3227         WPI_WRITE(sc, WPI_MASK, 0);
3228         WPI_WRITE(sc, WPI_INTR, WPI_INTR_MASK);
3229         WPI_WRITE(sc, WPI_INTR_STATUS, 0xff);
3230         WPI_WRITE(sc, WPI_INTR_STATUS, 0x00070000);
3231
3232         wpi_mem_lock(sc);
3233         wpi_mem_write(sc, WPI_MEM_MODE, 0);
3234         wpi_mem_unlock(sc);
3235
3236         /* reset all Tx rings */
3237         for (ac = 0; ac < 4; ac++)
3238                 wpi_reset_tx_ring(sc, &sc->txq[ac]);
3239         wpi_reset_tx_ring(sc, &sc->cmdq);
3240
3241         /* reset Rx ring */
3242         wpi_reset_rx_ring(sc, &sc->rxq);
3243
3244         wpi_mem_lock(sc);
3245         wpi_mem_write(sc, WPI_MEM_CLOCK2, 0x200);
3246         wpi_mem_unlock(sc);
3247
3248         DELAY(5);
3249
3250         wpi_stop_master(sc);
3251
3252         tmp = WPI_READ(sc, WPI_RESET);
3253         WPI_WRITE(sc, WPI_RESET, tmp | WPI_SW_RESET);
3254         sc->flags &= ~WPI_FLAG_BUSY;
3255 }
3256
3257 static void
3258 wpi_stop(struct wpi_softc *sc)
3259 {
3260         WPI_LOCK(sc);
3261         wpi_stop_locked(sc);
3262         WPI_UNLOCK(sc);
3263 }
3264
3265 static void
3266 wpi_newassoc(struct ieee80211_node *ni, int isnew)
3267 {
3268         /* XXX move */
3269         ieee80211_ratectl_node_init(ni);
3270 }
3271
3272 static void
3273 wpi_calib_timeout(void *arg)
3274 {
3275         struct wpi_softc *sc = arg;
3276         struct ifnet *ifp = sc->sc_ifp;
3277         struct ieee80211com *ic = ifp->if_l2com;
3278         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3279         int temp;
3280
3281         if (vap->iv_state != IEEE80211_S_RUN)
3282                 return;
3283
3284         /* update sensor data */
3285         temp = (int)WPI_READ(sc, WPI_TEMPERATURE);
3286         DPRINTFN(WPI_DEBUG_TEMP,("Temp in calibration is: %d\n", temp));
3287
3288         wpi_power_calibration(sc, temp);
3289
3290         callout_reset(&sc->calib_to, 60*hz, wpi_calib_timeout, sc);
3291 }
3292
3293 /*
3294  * This function is called periodically (every 60 seconds) to adjust output
3295  * power to temperature changes.
3296  */
3297 static void
3298 wpi_power_calibration(struct wpi_softc *sc, int temp)
3299 {
3300         struct ifnet *ifp = sc->sc_ifp;
3301         struct ieee80211com *ic = ifp->if_l2com;
3302         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3303
3304         /* sanity-check read value */
3305         if (temp < -260 || temp > 25) {
3306                 /* this can't be correct, ignore */
3307                 DPRINTFN(WPI_DEBUG_TEMP,
3308                     ("out-of-range temperature reported: %d\n", temp));
3309                 return;
3310         }
3311
3312         DPRINTFN(WPI_DEBUG_TEMP,("temperature %d->%d\n", sc->temp, temp));
3313
3314         /* adjust Tx power if need be */
3315         if (abs(temp - sc->temp) <= 6)
3316                 return;
3317
3318         sc->temp = temp;
3319
3320         if (wpi_set_txpower(sc, vap->iv_bss->ni_chan, 1) != 0) {
3321                 /* just warn, too bad for the automatic calibration... */
3322                 device_printf(sc->sc_dev,"could not adjust Tx power\n");
3323         }
3324 }
3325
3326 /**
3327  * Read the eeprom to find out what channels are valid for the given
3328  * band and update net80211 with what we find.
3329  */
3330 static void
3331 wpi_read_eeprom_channels(struct wpi_softc *sc, int n)
3332 {
3333         struct ifnet *ifp = sc->sc_ifp;
3334         struct ieee80211com *ic = ifp->if_l2com;
3335         const struct wpi_chan_band *band = &wpi_bands[n];
3336         struct wpi_eeprom_chan channels[WPI_MAX_CHAN_PER_BAND];
3337         struct ieee80211_channel *c;
3338         int chan, i, passive;
3339
3340         wpi_read_prom_data(sc, band->addr, channels,
3341             band->nchan * sizeof (struct wpi_eeprom_chan));
3342
3343         for (i = 0; i < band->nchan; i++) {
3344                 if (!(channels[i].flags & WPI_EEPROM_CHAN_VALID)) {
3345                         DPRINTFN(WPI_DEBUG_HW,
3346                             ("Channel Not Valid: %d, band %d\n",
3347                              band->chan[i],n));
3348                         continue;
3349                 }
3350
3351                 passive = 0;
3352                 chan = band->chan[i];
3353                 c = &ic->ic_channels[ic->ic_nchans++];
3354
3355                 /* is active scan allowed on this channel? */
3356                 if (!(channels[i].flags & WPI_EEPROM_CHAN_ACTIVE)) {
3357                         passive = IEEE80211_CHAN_PASSIVE;
3358                 }
3359
3360                 if (n == 0) {   /* 2GHz band */
3361                         c->ic_ieee = chan;
3362                         c->ic_freq = ieee80211_ieee2mhz(chan,
3363                             IEEE80211_CHAN_2GHZ);
3364                         c->ic_flags = IEEE80211_CHAN_B | passive;
3365
3366                         c = &ic->ic_channels[ic->ic_nchans++];
3367                         c->ic_ieee = chan;
3368                         c->ic_freq = ieee80211_ieee2mhz(chan,
3369                             IEEE80211_CHAN_2GHZ);
3370                         c->ic_flags = IEEE80211_CHAN_G | passive;
3371
3372                 } else {        /* 5GHz band */
3373                         /*
3374                          * Some 3945ABG adapters support channels 7, 8, 11
3375                          * and 12 in the 2GHz *and* 5GHz bands.
3376                          * Because of limitations in our net80211(9) stack,
3377                          * we can't support these channels in 5GHz band.
3378                          * XXX not true; just need to map to proper frequency
3379                          */
3380                         if (chan <= 14)
3381                                 continue;
3382
3383                         c->ic_ieee = chan;
3384                         c->ic_freq = ieee80211_ieee2mhz(chan,
3385                             IEEE80211_CHAN_5GHZ);
3386                         c->ic_flags = IEEE80211_CHAN_A | passive;
3387                 }
3388
3389                 /* save maximum allowed power for this channel */
3390                 sc->maxpwr[chan] = channels[i].maxpwr;
3391
3392 #if 0
3393                 // XXX We can probably use this an get rid of maxpwr - ben 20070617
3394                 ic->ic_channels[chan].ic_maxpower = channels[i].maxpwr;
3395                 //ic->ic_channels[chan].ic_minpower...
3396                 //ic->ic_channels[chan].ic_maxregtxpower...
3397 #endif
3398
3399                 DPRINTF(("adding chan %d (%dMHz) flags=0x%x maxpwr=%d"
3400                     " passive=%d, offset %d\n", chan, c->ic_freq,
3401                     channels[i].flags, sc->maxpwr[chan],
3402                     (c->ic_flags & IEEE80211_CHAN_PASSIVE) != 0,
3403                     ic->ic_nchans));
3404         }
3405 }
3406
3407 static void
3408 wpi_read_eeprom_group(struct wpi_softc *sc, int n)
3409 {
3410         struct wpi_power_group *group = &sc->groups[n];
3411         struct wpi_eeprom_group rgroup;
3412         int i;
3413
3414         wpi_read_prom_data(sc, WPI_EEPROM_POWER_GRP + n * 32, &rgroup,
3415             sizeof rgroup);
3416
3417         /* save power group information */
3418         group->chan   = rgroup.chan;
3419         group->maxpwr = rgroup.maxpwr;
3420         /* temperature at which the samples were taken */
3421         group->temp   = (int16_t)le16toh(rgroup.temp);
3422
3423         DPRINTF(("power group %d: chan=%d maxpwr=%d temp=%d\n", n,
3424                     group->chan, group->maxpwr, group->temp));
3425
3426         for (i = 0; i < WPI_SAMPLES_COUNT; i++) {
3427                 group->samples[i].index = rgroup.samples[i].index;
3428                 group->samples[i].power = rgroup.samples[i].power;
3429
3430                 DPRINTF(("\tsample %d: index=%d power=%d\n", i,
3431                             group->samples[i].index, group->samples[i].power));
3432         }
3433 }
3434
3435 /*
3436  * Update Tx power to match what is defined for channel `c'.
3437  */
3438 static int
3439 wpi_set_txpower(struct wpi_softc *sc, struct ieee80211_channel *c, int async)
3440 {
3441         struct ifnet *ifp = sc->sc_ifp;
3442         struct ieee80211com *ic = ifp->if_l2com;
3443         struct wpi_power_group *group;
3444         struct wpi_cmd_txpower txpower;
3445         u_int chan;
3446         int i;
3447
3448         /* get channel number */
3449         chan = ieee80211_chan2ieee(ic, c);
3450
3451         /* find the power group to which this channel belongs */
3452         if (IEEE80211_IS_CHAN_5GHZ(c)) {
3453                 for (group = &sc->groups[1]; group < &sc->groups[4]; group++)
3454                         if (chan <= group->chan)
3455                                 break;
3456         } else
3457                 group = &sc->groups[0];
3458
3459         memset(&txpower, 0, sizeof txpower);
3460         txpower.band = IEEE80211_IS_CHAN_5GHZ(c) ? 0 : 1;
3461         txpower.channel = htole16(chan);
3462
3463         /* set Tx power for all OFDM and CCK rates */
3464         for (i = 0; i <= 11 ; i++) {
3465                 /* retrieve Tx power for this channel/rate combination */
3466                 int idx = wpi_get_power_index(sc, group, c,
3467                     wpi_ridx_to_rate[i]);
3468
3469                 txpower.rates[i].rate = wpi_ridx_to_plcp[i];
3470
3471                 if (IEEE80211_IS_CHAN_5GHZ(c)) {
3472                         txpower.rates[i].gain_radio = wpi_rf_gain_5ghz[idx];
3473                         txpower.rates[i].gain_dsp = wpi_dsp_gain_5ghz[idx];
3474                 } else {
3475                         txpower.rates[i].gain_radio = wpi_rf_gain_2ghz[idx];
3476                         txpower.rates[i].gain_dsp = wpi_dsp_gain_2ghz[idx];
3477                 }
3478                 DPRINTFN(WPI_DEBUG_TEMP,("chan %d/rate %d: power index %d\n",
3479                             chan, wpi_ridx_to_rate[i], idx));
3480         }
3481
3482         return wpi_cmd(sc, WPI_CMD_TXPOWER, &txpower, sizeof txpower, async);
3483 }
3484
3485 /*
3486  * Determine Tx power index for a given channel/rate combination.
3487  * This takes into account the regulatory information from EEPROM and the
3488  * current temperature.
3489  */
3490 static int
3491 wpi_get_power_index(struct wpi_softc *sc, struct wpi_power_group *group,
3492     struct ieee80211_channel *c, int rate)
3493 {
3494 /* fixed-point arithmetic division using a n-bit fractional part */
3495 #define fdivround(a, b, n)      \
3496         ((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
3497
3498 /* linear interpolation */
3499 #define interpolate(x, x1, y1, x2, y2, n)       \
3500         ((y1) + fdivround(((x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
3501
3502         struct ifnet *ifp = sc->sc_ifp;
3503         struct ieee80211com *ic = ifp->if_l2com;
3504         struct wpi_power_sample *sample;
3505         int pwr, idx;
3506         u_int chan;
3507
3508         /* get channel number */
3509         chan = ieee80211_chan2ieee(ic, c);
3510
3511         /* default power is group's maximum power - 3dB */
3512         pwr = group->maxpwr / 2;
3513
3514         /* decrease power for highest OFDM rates to reduce distortion */
3515         switch (rate) {
3516                 case 72:        /* 36Mb/s */
3517                         pwr -= IEEE80211_IS_CHAN_2GHZ(c) ? 0 :  5;
3518                         break;
3519                 case 96:        /* 48Mb/s */
3520                         pwr -= IEEE80211_IS_CHAN_2GHZ(c) ? 7 : 10;
3521                         break;
3522                 case 108:       /* 54Mb/s */
3523                         pwr -= IEEE80211_IS_CHAN_2GHZ(c) ? 9 : 12;
3524                         break;
3525         }
3526
3527         /* never exceed channel's maximum allowed Tx power */
3528         pwr = min(pwr, sc->maxpwr[chan]);
3529
3530         /* retrieve power index into gain tables from samples */
3531         for (sample = group->samples; sample < &group->samples[3]; sample++)
3532                 if (pwr > sample[1].power)
3533                         break;
3534         /* fixed-point linear interpolation using a 19-bit fractional part */
3535         idx = interpolate(pwr, sample[0].power, sample[0].index,
3536             sample[1].power, sample[1].index, 19);
3537
3538         /*
3539          *  Adjust power index based on current temperature
3540          *      - if colder than factory-calibrated: decreate output power
3541          *      - if warmer than factory-calibrated: increase output power
3542          */
3543         idx -= (sc->temp - group->temp) * 11 / 100;
3544
3545         /* decrease power for CCK rates (-5dB) */
3546         if (!WPI_RATE_IS_OFDM(rate))
3547                 idx += 10;
3548
3549         /* keep power index in a valid range */
3550         if (idx < 0)
3551                 return 0;
3552         if (idx > WPI_MAX_PWR_INDEX)
3553                 return WPI_MAX_PWR_INDEX;
3554         return idx;
3555
3556 #undef interpolate
3557 #undef fdivround
3558 }
3559
3560 /**
3561  * Called by net80211 framework to indicate that a scan
3562  * is starting. This function doesn't actually do the scan,
3563  * wpi_scan_curchan starts things off. This function is more
3564  * of an early warning from the framework we should get ready
3565  * for the scan.
3566  */
3567 static void
3568 wpi_scan_start(struct ieee80211com *ic)
3569 {
3570         struct ifnet *ifp = ic->ic_ifp;
3571         struct wpi_softc *sc = ifp->if_softc;
3572
3573         WPI_LOCK(sc);
3574         wpi_set_led(sc, WPI_LED_LINK, 20, 2);
3575         WPI_UNLOCK(sc);
3576 }
3577
3578 /**
3579  * Called by the net80211 framework, indicates that the
3580  * scan has ended. If there is a scan in progress on the card
3581  * then it should be aborted.
3582  */
3583 static void
3584 wpi_scan_end(struct ieee80211com *ic)
3585 {
3586         /* XXX ignore */
3587 }
3588
3589 /**
3590  * Called by the net80211 framework to indicate to the driver
3591  * that the channel should be changed
3592  */
3593 static void
3594 wpi_set_channel(struct ieee80211com *ic)
3595 {
3596         struct ifnet *ifp = ic->ic_ifp;
3597         struct wpi_softc *sc = ifp->if_softc;
3598         int error;
3599
3600         /*
3601          * Only need to set the channel in Monitor mode. AP scanning and auth
3602          * are already taken care of by their respective firmware commands.
3603          */
3604         if (ic->ic_opmode == IEEE80211_M_MONITOR) {
3605                 error = wpi_config(sc);
3606                 if (error != 0)
3607                         device_printf(sc->sc_dev,
3608                             "error %d settting channel\n", error);
3609         }
3610 }
3611
3612 /**
3613  * Called by net80211 to indicate that we need to scan the current
3614  * channel. The channel is previously be set via the wpi_set_channel
3615  * callback.
3616  */
3617 static void
3618 wpi_scan_curchan(struct ieee80211_scan_state *ss, unsigned long maxdwell)
3619 {
3620         struct ieee80211vap *vap = ss->ss_vap;
3621         struct ifnet *ifp = vap->iv_ic->ic_ifp;
3622         struct wpi_softc *sc = ifp->if_softc;
3623
3624         WPI_LOCK(sc);
3625         if (wpi_scan(sc))
3626                 ieee80211_cancel_scan(vap);
3627         WPI_UNLOCK(sc);
3628 }
3629
3630 /**
3631  * Called by the net80211 framework to indicate
3632  * the minimum dwell time has been met, terminate the scan.
3633  * We don't actually terminate the scan as the firmware will notify
3634  * us when it's finished and we have no way to interrupt it.
3635  */
3636 static void
3637 wpi_scan_mindwell(struct ieee80211_scan_state *ss)
3638 {
3639         /* NB: don't try to abort scan; wait for firmware to finish */
3640 }
3641
3642 static void
3643 wpi_hwreset(void *arg, int pending)
3644 {
3645         struct wpi_softc *sc = arg;
3646
3647         WPI_LOCK(sc);
3648         wpi_init_locked(sc, 0);
3649         WPI_UNLOCK(sc);
3650 }
3651
3652 static void
3653 wpi_rfreset(void *arg, int pending)
3654 {
3655         struct wpi_softc *sc = arg;
3656
3657         WPI_LOCK(sc);
3658         wpi_rfkill_resume(sc);
3659         WPI_UNLOCK(sc);
3660 }
3661
3662 /*
3663  * Allocate DMA-safe memory for firmware transfer.
3664  */
3665 static int
3666 wpi_alloc_fwmem(struct wpi_softc *sc)
3667 {
3668         /* allocate enough contiguous space to store text and data */
3669         return wpi_dma_contig_alloc(sc, &sc->fw_dma, NULL,
3670             WPI_FW_MAIN_TEXT_MAXSZ + WPI_FW_MAIN_DATA_MAXSZ, 1,
3671             BUS_DMA_NOWAIT);
3672 }
3673
3674 static void
3675 wpi_free_fwmem(struct wpi_softc *sc)
3676 {
3677         wpi_dma_contig_free(&sc->fw_dma);
3678 }
3679
3680 /**
3681  * Called every second, wpi_watchdog used by the watch dog timer
3682  * to check that the card is still alive
3683  */
3684 static void
3685 wpi_watchdog(void *arg)
3686 {
3687         struct wpi_softc *sc = arg;
3688         struct ifnet *ifp = sc->sc_ifp;
3689         struct ieee80211com *ic = ifp->if_l2com;
3690         uint32_t tmp;
3691
3692         DPRINTFN(WPI_DEBUG_WATCHDOG,("Watchdog: tick\n"));
3693
3694         if (sc->flags & WPI_FLAG_HW_RADIO_OFF) {
3695                 /* No need to lock firmware memory */
3696                 tmp = wpi_mem_read(sc, WPI_MEM_HW_RADIO_OFF);
3697
3698                 if ((tmp & 0x1) == 0) {
3699                         /* Radio kill switch is still off */
3700                         callout_reset(&sc->watchdog_to, hz, wpi_watchdog, sc);
3701                         return;
3702                 }
3703
3704                 device_printf(sc->sc_dev, "Hardware Switch Enabled\n");
3705                 ieee80211_runtask(ic, &sc->sc_radiotask);
3706                 return;
3707         }
3708
3709         if (sc->sc_tx_timer > 0) {
3710                 if (--sc->sc_tx_timer == 0) {
3711                         device_printf(sc->sc_dev,"device timeout\n");
3712                         ifp->if_oerrors++;
3713                         ieee80211_runtask(ic, &sc->sc_restarttask);
3714                 }
3715         }
3716         if (sc->sc_scan_timer > 0) {
3717                 struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3718                 if (--sc->sc_scan_timer == 0 && vap != NULL) {
3719                         device_printf(sc->sc_dev,"scan timeout\n");
3720                         ieee80211_cancel_scan(vap);
3721                         ieee80211_runtask(ic, &sc->sc_restarttask);
3722                 }
3723         }
3724
3725         if (ifp->if_flags & IFF_RUNNING)
3726                 callout_reset(&sc->watchdog_to, hz, wpi_watchdog, sc);
3727 }
3728
3729 #ifdef WPI_DEBUG
3730 static const char *wpi_cmd_str(int cmd)
3731 {
3732         switch (cmd) {
3733         case WPI_DISABLE_CMD:   return "WPI_DISABLE_CMD";
3734         case WPI_CMD_CONFIGURE: return "WPI_CMD_CONFIGURE";
3735         case WPI_CMD_ASSOCIATE: return "WPI_CMD_ASSOCIATE";
3736         case WPI_CMD_SET_WME:   return "WPI_CMD_SET_WME";
3737         case WPI_CMD_TSF:       return "WPI_CMD_TSF";
3738         case WPI_CMD_ADD_NODE:  return "WPI_CMD_ADD_NODE";
3739         case WPI_CMD_TX_DATA:   return "WPI_CMD_TX_DATA";
3740         case WPI_CMD_MRR_SETUP: return "WPI_CMD_MRR_SETUP";
3741         case WPI_CMD_SET_LED:   return "WPI_CMD_SET_LED";
3742         case WPI_CMD_SET_POWER_MODE: return "WPI_CMD_SET_POWER_MODE";
3743         case WPI_CMD_SCAN:      return "WPI_CMD_SCAN";
3744         case WPI_CMD_SET_BEACON:return "WPI_CMD_SET_BEACON";
3745         case WPI_CMD_TXPOWER:   return "WPI_CMD_TXPOWER";
3746         case WPI_CMD_BLUETOOTH: return "WPI_CMD_BLUETOOTH";
3747
3748         default:
3749                 KASSERT(1, ("Unknown Command: %d\n", cmd));
3750                 return "UNKNOWN CMD";   /* Make the compiler happy */
3751         }
3752 }
3753 #endif
3754
3755 MODULE_DEPEND(wpi, pci,  1, 1, 1);
3756 MODULE_DEPEND(wpi, wlan, 1, 1, 1);
3757 MODULE_DEPEND(wpi, firmware, 1, 1, 1);
3758 MODULE_DEPEND(wpi, wlan_amrr, 1, 1, 1);
3759 /*
3760 MODULE_DEPEND(wpi, wpifw_fw_fw, 1, 1, 1);
3761 MODULE_DEPEND(wpi, ath_rate, 1, 1, 1);
3762 */