]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/wpi/if_wpi.c
Add TX status codes (obtained from iwlegacy)
[FreeBSD/FreeBSD.git] / sys / dev / 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 #include <sys/cdefs.h>
20 __FBSDID("$FreeBSD$");
21
22 /*
23  * Driver for Intel PRO/Wireless 3945ABG 802.11 network adapters.
24  *
25  * The 3945ABG network adapter doesn't use traditional hardware as
26  * many other adaptors do. Instead at run time the eeprom is set into a known
27  * state and told to load boot firmware. The boot firmware loads an init and a
28  * main  binary firmware image into SRAM on the card via DMA.
29  * Once the firmware is loaded, the driver/hw then
30  * communicate by way of circular dma rings via the SRAM to the firmware.
31  *
32  * There is 6 memory rings. 1 command ring, 1 rx data ring & 4 tx data rings.
33  * The 4 tx data rings allow for prioritization QoS.
34  *
35  * The rx data ring consists of 32 dma buffers. Two registers are used to
36  * indicate where in the ring the driver and the firmware are up to. The
37  * driver sets the initial read index (reg1) and the initial write index (reg2),
38  * the firmware updates the read index (reg1) on rx of a packet and fires an
39  * interrupt. The driver then processes the buffers starting at reg1 indicating
40  * to the firmware which buffers have been accessed by updating reg2. At the
41  * same time allocating new memory for the processed buffer.
42  *
43  * A similar thing happens with the tx rings. The difference is the firmware
44  * stop processing buffers once the queue is full and until confirmation
45  * of a successful transmition (tx_done) has occurred.
46  *
47  * The command ring operates in the same manner as the tx queues.
48  *
49  * All communication direct to the card (ie eeprom) is classed as Stage1
50  * communication
51  *
52  * All communication via the firmware to the card is classed as State2.
53  * The firmware consists of 2 parts. A bootstrap firmware and a runtime
54  * firmware. The bootstrap firmware and runtime firmware are loaded
55  * from host memory via dma to the card then told to execute. From this point
56  * on the majority of communications between the driver and the card goes
57  * via the firmware.
58  */
59
60 #include "opt_wlan.h"
61 #include "opt_wpi.h"
62
63 #include <sys/param.h>
64 #include <sys/sysctl.h>
65 #include <sys/sockio.h>
66 #include <sys/mbuf.h>
67 #include <sys/kernel.h>
68 #include <sys/socket.h>
69 #include <sys/systm.h>
70 #include <sys/malloc.h>
71 #include <sys/queue.h>
72 #include <sys/taskqueue.h>
73 #include <sys/module.h>
74 #include <sys/bus.h>
75 #include <sys/endian.h>
76 #include <sys/linker.h>
77 #include <sys/firmware.h>
78
79 #include <machine/bus.h>
80 #include <machine/resource.h>
81 #include <sys/rman.h>
82
83 #include <dev/pci/pcireg.h>
84 #include <dev/pci/pcivar.h>
85
86 #include <net/bpf.h>
87 #include <net/if.h>
88 #include <net/if_var.h>
89 #include <net/if_arp.h>
90 #include <net/ethernet.h>
91 #include <net/if_dl.h>
92 #include <net/if_media.h>
93 #include <net/if_types.h>
94
95 #include <netinet/in.h>
96 #include <netinet/in_systm.h>
97 #include <netinet/in_var.h>
98 #include <netinet/if_ether.h>
99 #include <netinet/ip.h>
100
101 #include <net80211/ieee80211_var.h>
102 #include <net80211/ieee80211_radiotap.h>
103 #include <net80211/ieee80211_regdomain.h>
104 #include <net80211/ieee80211_ratectl.h>
105
106 #include <dev/wpi/if_wpireg.h>
107 #include <dev/wpi/if_wpivar.h>
108 #include <dev/wpi/if_wpi_debug.h>
109
110 struct wpi_ident {
111         uint16_t        vendor;
112         uint16_t        device;
113         uint16_t        subdevice;
114         const char      *name;
115 };
116
117 static const struct wpi_ident wpi_ident_table[] = {
118         /* The below entries support ABG regardless of the subid */
119         { 0x8086, 0x4222,    0x0, "Intel(R) PRO/Wireless 3945ABG" },
120         { 0x8086, 0x4227,    0x0, "Intel(R) PRO/Wireless 3945ABG" },
121         /* The below entries only support BG */
122         { 0x8086, 0x4222, 0x1005, "Intel(R) PRO/Wireless 3945BG"  },
123         { 0x8086, 0x4222, 0x1034, "Intel(R) PRO/Wireless 3945BG"  },
124         { 0x8086, 0x4227, 0x1014, "Intel(R) PRO/Wireless 3945BG"  },
125         { 0x8086, 0x4222, 0x1044, "Intel(R) PRO/Wireless 3945BG"  },
126         { 0, 0, 0, NULL }
127 };
128
129 static int      wpi_probe(device_t);
130 static int      wpi_attach(device_t);
131 static void     wpi_radiotap_attach(struct wpi_softc *);
132 static void     wpi_sysctlattach(struct wpi_softc *);
133 static void     wpi_init_beacon(struct wpi_vap *);
134 static struct ieee80211vap *wpi_vap_create(struct ieee80211com *,
135                     const char [IFNAMSIZ], int, enum ieee80211_opmode, int,
136                     const uint8_t [IEEE80211_ADDR_LEN],
137                     const uint8_t [IEEE80211_ADDR_LEN]);
138 static void     wpi_vap_delete(struct ieee80211vap *);
139 static int      wpi_detach(device_t);
140 static int      wpi_shutdown(device_t);
141 static int      wpi_suspend(device_t);
142 static int      wpi_resume(device_t);
143 static int      wpi_nic_lock(struct wpi_softc *);
144 static int      wpi_read_prom_data(struct wpi_softc *, uint32_t, void *, int);
145 static void     wpi_dma_map_addr(void *, bus_dma_segment_t *, int, int);
146 static int      wpi_dma_contig_alloc(struct wpi_softc *, struct wpi_dma_info *,
147                     void **, bus_size_t, bus_size_t);
148 static void     wpi_dma_contig_free(struct wpi_dma_info *);
149 static int      wpi_alloc_shared(struct wpi_softc *);
150 static void     wpi_free_shared(struct wpi_softc *);
151 static int      wpi_alloc_fwmem(struct wpi_softc *);
152 static void     wpi_free_fwmem(struct wpi_softc *);
153 static int      wpi_alloc_rx_ring(struct wpi_softc *);
154 static void     wpi_update_rx_ring(struct wpi_softc *);
155 static void     wpi_reset_rx_ring(struct wpi_softc *);
156 static void     wpi_free_rx_ring(struct wpi_softc *);
157 static int      wpi_alloc_tx_ring(struct wpi_softc *, struct wpi_tx_ring *,
158                     int);
159 static void     wpi_update_tx_ring(struct wpi_softc *, struct wpi_tx_ring *);
160 static void     wpi_reset_tx_ring(struct wpi_softc *, struct wpi_tx_ring *);
161 static void     wpi_free_tx_ring(struct wpi_softc *, struct wpi_tx_ring *);
162 static int      wpi_read_eeprom(struct wpi_softc *,
163                     uint8_t macaddr[IEEE80211_ADDR_LEN]);
164 static uint32_t wpi_eeprom_channel_flags(struct wpi_eeprom_chan *);
165 static void     wpi_read_eeprom_band(struct wpi_softc *, int);
166 static int      wpi_read_eeprom_channels(struct wpi_softc *, int);
167 static struct wpi_eeprom_chan *wpi_find_eeprom_channel(struct wpi_softc *,
168                     struct ieee80211_channel *);
169 static int      wpi_setregdomain(struct ieee80211com *,
170                     struct ieee80211_regdomain *, int,
171                     struct ieee80211_channel[]);
172 static int      wpi_read_eeprom_group(struct wpi_softc *, int);
173 static int      wpi_add_node_entry_adhoc(struct wpi_softc *);
174 static void     wpi_node_free(struct ieee80211_node *);
175 static struct ieee80211_node *wpi_node_alloc(struct ieee80211vap *,
176                     const uint8_t mac[IEEE80211_ADDR_LEN]);
177 static int      wpi_newstate(struct ieee80211vap *, enum ieee80211_state, int);
178 static void     wpi_calib_timeout(void *);
179 static void     wpi_rx_done(struct wpi_softc *, struct wpi_rx_desc *,
180                     struct wpi_rx_data *);
181 static void     wpi_rx_statistics(struct wpi_softc *, struct wpi_rx_desc *,
182                     struct wpi_rx_data *);
183 static void     wpi_tx_done(struct wpi_softc *, struct wpi_rx_desc *);
184 static void     wpi_cmd_done(struct wpi_softc *, struct wpi_rx_desc *);
185 static void     wpi_notif_intr(struct wpi_softc *);
186 static void     wpi_wakeup_intr(struct wpi_softc *);
187 #ifdef WPI_DEBUG
188 static void     wpi_debug_registers(struct wpi_softc *);
189 #endif
190 static void     wpi_fatal_intr(struct wpi_softc *);
191 static void     wpi_intr(void *);
192 static int      wpi_cmd2(struct wpi_softc *, struct wpi_buf *);
193 static int      wpi_tx_data(struct wpi_softc *, struct mbuf *,
194                     struct ieee80211_node *);
195 static int      wpi_tx_data_raw(struct wpi_softc *, struct mbuf *,
196                     struct ieee80211_node *,
197                     const struct ieee80211_bpf_params *);
198 static int      wpi_raw_xmit(struct ieee80211_node *, struct mbuf *,
199                     const struct ieee80211_bpf_params *);
200 static void     wpi_start(struct ifnet *);
201 static void     wpi_start_task(void *, int);
202 static void     wpi_watchdog_rfkill(void *);
203 static void     wpi_scan_timeout(void *);
204 static void     wpi_tx_timeout(void *);
205 static int      wpi_ioctl(struct ifnet *, u_long, caddr_t);
206 static int      wpi_cmd(struct wpi_softc *, int, const void *, size_t, int);
207 static int      wpi_mrr_setup(struct wpi_softc *);
208 static int      wpi_add_node(struct wpi_softc *, struct ieee80211_node *);
209 static int      wpi_add_broadcast_node(struct wpi_softc *, int);
210 static int      wpi_add_ibss_node(struct wpi_softc *, struct ieee80211_node *);
211 static void     wpi_del_node(struct wpi_softc *, struct ieee80211_node *);
212 static int      wpi_updateedca(struct ieee80211com *);
213 static void     wpi_set_promisc(struct wpi_softc *);
214 static void     wpi_update_promisc(struct ifnet *);
215 static void     wpi_update_mcast(struct ifnet *);
216 static void     wpi_set_led(struct wpi_softc *, uint8_t, uint8_t, uint8_t);
217 static int      wpi_set_timing(struct wpi_softc *, struct ieee80211_node *);
218 static void     wpi_power_calibration(struct wpi_softc *);
219 static int      wpi_set_txpower(struct wpi_softc *, int);
220 static int      wpi_get_power_index(struct wpi_softc *,
221                     struct wpi_power_group *, uint8_t, int, int);
222 static int      wpi_set_pslevel(struct wpi_softc *, uint8_t, int, int);
223 static int      wpi_send_btcoex(struct wpi_softc *);
224 static int      wpi_send_rxon(struct wpi_softc *, int, int);
225 static int      wpi_config(struct wpi_softc *);
226 static uint16_t wpi_get_active_dwell_time(struct wpi_softc *,
227                     struct ieee80211_channel *, uint8_t);
228 static uint16_t wpi_limit_dwell(struct wpi_softc *, uint16_t);
229 static uint16_t wpi_get_passive_dwell_time(struct wpi_softc *,
230                     struct ieee80211_channel *);
231 static int      wpi_scan(struct wpi_softc *, struct ieee80211_channel *);
232 static int      wpi_auth(struct wpi_softc *, struct ieee80211vap *);
233 static int      wpi_config_beacon(struct wpi_vap *);
234 static int      wpi_setup_beacon(struct wpi_softc *, struct ieee80211_node *);
235 static void     wpi_update_beacon(struct ieee80211vap *, int);
236 static void     wpi_newassoc(struct ieee80211_node *, int);
237 static int      wpi_run(struct wpi_softc *, struct ieee80211vap *);
238 static int      wpi_load_key(struct ieee80211_node *,
239                     const struct ieee80211_key *);
240 static void     wpi_load_key_cb(void *, struct ieee80211_node *);
241 static int      wpi_set_global_keys(struct ieee80211_node *);
242 static int      wpi_del_key(struct ieee80211_node *,
243                     const struct ieee80211_key *);
244 static void     wpi_del_key_cb(void *, struct ieee80211_node *);
245 static int      wpi_process_key(struct ieee80211vap *,
246                     const struct ieee80211_key *, int);
247 static int      wpi_key_set(struct ieee80211vap *,
248                     const struct ieee80211_key *,
249                     const uint8_t mac[IEEE80211_ADDR_LEN]);
250 static int      wpi_key_delete(struct ieee80211vap *,
251                     const struct ieee80211_key *);
252 static int      wpi_post_alive(struct wpi_softc *);
253 static int      wpi_load_bootcode(struct wpi_softc *, const uint8_t *, int);
254 static int      wpi_load_firmware(struct wpi_softc *);
255 static int      wpi_read_firmware(struct wpi_softc *);
256 static void     wpi_unload_firmware(struct wpi_softc *);
257 static int      wpi_clock_wait(struct wpi_softc *);
258 static int      wpi_apm_init(struct wpi_softc *);
259 static void     wpi_apm_stop_master(struct wpi_softc *);
260 static void     wpi_apm_stop(struct wpi_softc *);
261 static void     wpi_nic_config(struct wpi_softc *);
262 static int      wpi_hw_init(struct wpi_softc *);
263 static void     wpi_hw_stop(struct wpi_softc *);
264 static void     wpi_radio_on(void *, int);
265 static void     wpi_radio_off(void *, int);
266 static void     wpi_init(void *);
267 static void     wpi_stop_locked(struct wpi_softc *);
268 static void     wpi_stop(struct wpi_softc *);
269 static void     wpi_scan_start(struct ieee80211com *);
270 static void     wpi_scan_end(struct ieee80211com *);
271 static void     wpi_set_channel(struct ieee80211com *);
272 static void     wpi_scan_curchan(struct ieee80211_scan_state *, unsigned long);
273 static void     wpi_scan_mindwell(struct ieee80211_scan_state *);
274 static void     wpi_hw_reset(void *, int);
275
276 static device_method_t wpi_methods[] = {
277         /* Device interface */
278         DEVMETHOD(device_probe,         wpi_probe),
279         DEVMETHOD(device_attach,        wpi_attach),
280         DEVMETHOD(device_detach,        wpi_detach),
281         DEVMETHOD(device_shutdown,      wpi_shutdown),
282         DEVMETHOD(device_suspend,       wpi_suspend),
283         DEVMETHOD(device_resume,        wpi_resume),
284
285         DEVMETHOD_END
286 };
287
288 static driver_t wpi_driver = {
289         "wpi",
290         wpi_methods,
291         sizeof (struct wpi_softc)
292 };
293 static devclass_t wpi_devclass;
294
295 DRIVER_MODULE(wpi, pci, wpi_driver, wpi_devclass, NULL, NULL);
296
297 MODULE_VERSION(wpi, 1);
298
299 MODULE_DEPEND(wpi, pci,  1, 1, 1);
300 MODULE_DEPEND(wpi, wlan, 1, 1, 1);
301 MODULE_DEPEND(wpi, firmware, 1, 1, 1);
302
303 static int
304 wpi_probe(device_t dev)
305 {
306         const struct wpi_ident *ident;
307
308         for (ident = wpi_ident_table; ident->name != NULL; ident++) {
309                 if (pci_get_vendor(dev) == ident->vendor &&
310                     pci_get_device(dev) == ident->device) {
311                         device_set_desc(dev, ident->name);
312                         return (BUS_PROBE_DEFAULT);
313                 }
314         }
315         return ENXIO;
316 }
317
318 static int
319 wpi_attach(device_t dev)
320 {
321         struct wpi_softc *sc = (struct wpi_softc *)device_get_softc(dev);
322         struct ieee80211com *ic;
323         struct ifnet *ifp;
324         int i, error, rid;
325 #ifdef WPI_DEBUG
326         int supportsa = 1;
327         const struct wpi_ident *ident;
328 #endif
329         uint8_t macaddr[IEEE80211_ADDR_LEN];
330
331         sc->sc_dev = dev;
332
333 #ifdef WPI_DEBUG
334         error = resource_int_value(device_get_name(sc->sc_dev),
335             device_get_unit(sc->sc_dev), "debug", &(sc->sc_debug));
336         if (error != 0)
337                 sc->sc_debug = 0;
338 #else
339         sc->sc_debug = 0;
340 #endif
341
342         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
343
344         /*
345          * Get the offset of the PCI Express Capability Structure in PCI
346          * Configuration Space.
347          */
348         error = pci_find_cap(dev, PCIY_EXPRESS, &sc->sc_cap_off);
349         if (error != 0) {
350                 device_printf(dev, "PCIe capability structure not found!\n");
351                 return error;
352         }
353
354         /*
355          * Some card's only support 802.11b/g not a, check to see if
356          * this is one such card. A 0x0 in the subdevice table indicates
357          * the entire subdevice range is to be ignored.
358          */
359 #ifdef WPI_DEBUG
360         for (ident = wpi_ident_table; ident->name != NULL; ident++) {
361                 if (ident->subdevice &&
362                     pci_get_subdevice(dev) == ident->subdevice) {
363                     supportsa = 0;
364                     break;
365                 }
366         }
367 #endif
368
369         /* Clear device-specific "PCI retry timeout" register (41h). */
370         pci_write_config(dev, 0x41, 0, 1);
371
372         /* Enable bus-mastering. */
373         pci_enable_busmaster(dev);
374
375         rid = PCIR_BAR(0);
376         sc->mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
377             RF_ACTIVE);
378         if (sc->mem == NULL) {
379                 device_printf(dev, "can't map mem space\n");
380                 return ENOMEM;
381         }
382         sc->sc_st = rman_get_bustag(sc->mem);
383         sc->sc_sh = rman_get_bushandle(sc->mem);
384
385         i = 1;
386         rid = 0;
387         if (pci_alloc_msi(dev, &i) == 0)
388                 rid = 1;
389         /* Install interrupt handler. */
390         sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE |
391             (rid != 0 ? 0 : RF_SHAREABLE));
392         if (sc->irq == NULL) {
393                 device_printf(dev, "can't map interrupt\n");
394                 error = ENOMEM;
395                 goto fail;
396         }
397
398         WPI_LOCK_INIT(sc);
399         WPI_TX_LOCK_INIT(sc);
400         WPI_RXON_LOCK_INIT(sc);
401         WPI_NT_LOCK_INIT(sc);
402         WPI_TXQ_LOCK_INIT(sc);
403         WPI_TXQ_STATE_LOCK_INIT(sc);
404
405         /* Allocate DMA memory for firmware transfers. */
406         if ((error = wpi_alloc_fwmem(sc)) != 0) {
407                 device_printf(dev,
408                     "could not allocate memory for firmware, error %d\n",
409                     error);
410                 goto fail;
411         }
412
413         /* Allocate shared page. */
414         if ((error = wpi_alloc_shared(sc)) != 0) {
415                 device_printf(dev, "could not allocate shared page\n");
416                 goto fail;
417         }
418
419         /* Allocate TX rings - 4 for QoS purposes, 1 for commands. */
420         for (i = 0; i < WPI_NTXQUEUES; i++) {
421                 if ((error = wpi_alloc_tx_ring(sc, &sc->txq[i], i)) != 0) {
422                         device_printf(dev,
423                             "could not allocate TX ring %d, error %d\n", i,
424                             error);
425                         goto fail;
426                 }
427         }
428
429         /* Allocate RX ring. */
430         if ((error = wpi_alloc_rx_ring(sc)) != 0) {
431                 device_printf(dev, "could not allocate RX ring, error %d\n",
432                     error);
433                 goto fail;
434         }
435
436         /* Clear pending interrupts. */
437         WPI_WRITE(sc, WPI_INT, 0xffffffff);
438
439         ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
440         if (ifp == NULL) {
441                 device_printf(dev, "can not allocate ifnet structure\n");
442                 goto fail;
443         }
444
445         ic = ifp->if_l2com;
446         ic->ic_ifp = ifp;
447         ic->ic_phytype = IEEE80211_T_OFDM;      /* not only, but not used */
448         ic->ic_opmode = IEEE80211_M_STA;        /* default to BSS mode */
449
450         /* Set device capabilities. */
451         ic->ic_caps =
452                   IEEE80211_C_STA               /* station mode supported */
453                 | IEEE80211_C_IBSS              /* IBSS mode supported */
454                 | IEEE80211_C_HOSTAP            /* Host access point mode */
455                 | IEEE80211_C_MONITOR           /* monitor mode supported */
456                 | IEEE80211_C_AHDEMO            /* adhoc demo mode */
457                 | IEEE80211_C_BGSCAN            /* capable of bg scanning */
458                 | IEEE80211_C_TXPMGT            /* tx power management */
459                 | IEEE80211_C_SHSLOT            /* short slot time supported */
460                 | IEEE80211_C_WPA               /* 802.11i */
461                 | IEEE80211_C_SHPREAMBLE        /* short preamble supported */
462                 | IEEE80211_C_WME               /* 802.11e */
463                 | IEEE80211_C_PMGT              /* Station-side power mgmt */
464                 ;
465
466         ic->ic_cryptocaps =
467                   IEEE80211_CRYPTO_AES_CCM;
468
469         /*
470          * Read in the eeprom and also setup the channels for
471          * net80211. We don't set the rates as net80211 does this for us
472          */
473         if ((error = wpi_read_eeprom(sc, macaddr)) != 0) {
474                 device_printf(dev, "could not read EEPROM, error %d\n",
475                     error);
476                 goto fail;
477         }
478
479 #ifdef WPI_DEBUG
480         if (bootverbose) {
481                 device_printf(sc->sc_dev, "Regulatory Domain: %.4s\n",
482                     sc->domain);
483                 device_printf(sc->sc_dev, "Hardware Type: %c\n",
484                     sc->type > 1 ? 'B': '?');
485                 device_printf(sc->sc_dev, "Hardware Revision: %c\n",
486                     ((sc->rev & 0xf0) == 0xd0) ? 'D': '?');
487                 device_printf(sc->sc_dev, "SKU %s support 802.11a\n",
488                     supportsa ? "does" : "does not");
489
490                 /* XXX hw_config uses the PCIDEV for the Hardware rev. Must
491                    check what sc->rev really represents - benjsc 20070615 */
492         }
493 #endif
494
495         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
496         ifp->if_softc = sc;
497         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
498         ifp->if_init = wpi_init;
499         ifp->if_ioctl = wpi_ioctl;
500         ifp->if_start = wpi_start;
501         IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
502         ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
503         IFQ_SET_READY(&ifp->if_snd);
504
505         ieee80211_ifattach(ic, macaddr);
506         ic->ic_vap_create = wpi_vap_create;
507         ic->ic_vap_delete = wpi_vap_delete;
508         ic->ic_raw_xmit = wpi_raw_xmit;
509         ic->ic_node_alloc = wpi_node_alloc;
510         sc->sc_node_free = ic->ic_node_free;
511         ic->ic_node_free = wpi_node_free;
512         ic->ic_wme.wme_update = wpi_updateedca;
513         ic->ic_update_promisc = wpi_update_promisc;
514         ic->ic_update_mcast = wpi_update_mcast;
515         ic->ic_newassoc = wpi_newassoc;
516         ic->ic_scan_start = wpi_scan_start;
517         ic->ic_scan_end = wpi_scan_end;
518         ic->ic_set_channel = wpi_set_channel;
519         ic->ic_scan_curchan = wpi_scan_curchan;
520         ic->ic_scan_mindwell = wpi_scan_mindwell;
521         ic->ic_setregdomain = wpi_setregdomain;
522
523         wpi_radiotap_attach(sc);
524
525         callout_init_mtx(&sc->calib_to, &sc->rxon_mtx, 0);
526         callout_init_mtx(&sc->scan_timeout, &sc->rxon_mtx, 0);
527         callout_init_mtx(&sc->tx_timeout, &sc->txq_state_mtx, 0);
528         callout_init_mtx(&sc->watchdog_rfkill, &sc->sc_mtx, 0);
529         TASK_INIT(&sc->sc_reinittask, 0, wpi_hw_reset, sc);
530         TASK_INIT(&sc->sc_radiooff_task, 0, wpi_radio_off, sc);
531         TASK_INIT(&sc->sc_radioon_task, 0, wpi_radio_on, sc);
532         TASK_INIT(&sc->sc_start_task, 0, wpi_start_task, sc);
533
534         sc->sc_tq = taskqueue_create("wpi_taskq", M_WAITOK,
535             taskqueue_thread_enqueue, &sc->sc_tq);
536         error = taskqueue_start_threads(&sc->sc_tq, 1, 0, "wpi_taskq");
537         if (error != 0) {
538                 device_printf(dev, "can't start threads, error %d\n", error);
539                 goto fail;
540         }
541
542         wpi_sysctlattach(sc);
543
544         /*
545          * Hook our interrupt after all initialization is complete.
546          */
547         error = bus_setup_intr(dev, sc->irq, INTR_TYPE_NET | INTR_MPSAFE,
548             NULL, wpi_intr, sc, &sc->sc_ih);
549         if (error != 0) {
550                 device_printf(dev, "can't establish interrupt, error %d\n",
551                     error);
552                 goto fail;
553         }
554
555         if (bootverbose)
556                 ieee80211_announce(ic);
557
558 #ifdef WPI_DEBUG
559         if (sc->sc_debug & WPI_DEBUG_HW)
560                 ieee80211_announce_channels(ic);
561 #endif
562
563         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
564         return 0;
565
566 fail:   wpi_detach(dev);
567         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
568         return error;
569 }
570
571 /*
572  * Attach the interface to 802.11 radiotap.
573  */
574 static void
575 wpi_radiotap_attach(struct wpi_softc *sc)
576 {
577         struct ifnet *ifp = sc->sc_ifp;
578         struct ieee80211com *ic = ifp->if_l2com;
579         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
580         ieee80211_radiotap_attach(ic,
581             &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap),
582                 WPI_TX_RADIOTAP_PRESENT,
583             &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
584                 WPI_RX_RADIOTAP_PRESENT);
585         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
586 }
587
588 static void
589 wpi_sysctlattach(struct wpi_softc *sc)
590 {
591 #ifdef WPI_DEBUG
592         struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
593         struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
594
595         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
596             "debug", CTLFLAG_RW, &sc->sc_debug, sc->sc_debug,
597                 "control debugging printfs");
598 #endif
599 }
600
601 static void
602 wpi_init_beacon(struct wpi_vap *wvp)
603 {
604         struct wpi_buf *bcn = &wvp->wv_bcbuf;
605         struct wpi_cmd_beacon *cmd = (struct wpi_cmd_beacon *)&bcn->data;
606
607         cmd->id = WPI_ID_BROADCAST;
608         cmd->ofdm_mask = 0xff;
609         cmd->cck_mask = 0x0f;
610         cmd->lifetime = htole32(WPI_LIFETIME_INFINITE);
611         cmd->flags = htole32(WPI_TX_AUTO_SEQ | WPI_TX_INSERT_TSTAMP);
612
613         bcn->code = WPI_CMD_SET_BEACON;
614         bcn->ac = WPI_CMD_QUEUE_NUM;
615         bcn->size = sizeof(struct wpi_cmd_beacon);
616 }
617
618 static struct ieee80211vap *
619 wpi_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
620     enum ieee80211_opmode opmode, int flags,
621     const uint8_t bssid[IEEE80211_ADDR_LEN],
622     const uint8_t mac[IEEE80211_ADDR_LEN])
623 {
624         struct wpi_vap *wvp;
625         struct ieee80211vap *vap;
626
627         if (!TAILQ_EMPTY(&ic->ic_vaps))         /* only one at a time */
628                 return NULL;
629
630         wvp = (struct wpi_vap *) malloc(sizeof(struct wpi_vap),
631             M_80211_VAP, M_NOWAIT | M_ZERO);
632         if (wvp == NULL)
633                 return NULL;
634         vap = &wvp->wv_vap;
635         ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid, mac);
636
637         if (opmode == IEEE80211_M_IBSS || opmode == IEEE80211_M_HOSTAP) {
638                 WPI_VAP_LOCK_INIT(wvp);
639                 wpi_init_beacon(wvp);
640         }
641
642         /* Override with driver methods. */
643         vap->iv_key_set = wpi_key_set;
644         vap->iv_key_delete = wpi_key_delete;
645         wvp->wv_newstate = vap->iv_newstate;
646         vap->iv_newstate = wpi_newstate;
647         vap->iv_update_beacon = wpi_update_beacon;
648         vap->iv_max_aid = WPI_ID_IBSS_MAX - WPI_ID_IBSS_MIN + 1;
649
650         ieee80211_ratectl_init(vap);
651         /* Complete setup. */
652         ieee80211_vap_attach(vap, ieee80211_media_change,
653             ieee80211_media_status);
654         ic->ic_opmode = opmode;
655         return vap;
656 }
657
658 static void
659 wpi_vap_delete(struct ieee80211vap *vap)
660 {
661         struct wpi_vap *wvp = WPI_VAP(vap);
662         struct wpi_buf *bcn = &wvp->wv_bcbuf;
663         enum ieee80211_opmode opmode = vap->iv_opmode;
664
665         ieee80211_ratectl_deinit(vap);
666         ieee80211_vap_detach(vap);
667
668         if (opmode == IEEE80211_M_IBSS || opmode == IEEE80211_M_HOSTAP) {
669                 if (bcn->m != NULL)
670                         m_freem(bcn->m);
671
672                 WPI_VAP_LOCK_DESTROY(wvp);
673         }
674
675         free(wvp, M_80211_VAP);
676 }
677
678 static int
679 wpi_detach(device_t dev)
680 {
681         struct wpi_softc *sc = device_get_softc(dev);
682         struct ifnet *ifp = sc->sc_ifp;
683         struct ieee80211com *ic;
684         int qid;
685
686         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
687
688         if (ifp != NULL) {
689                 ic = ifp->if_l2com;
690
691                 ieee80211_draintask(ic, &sc->sc_radioon_task);
692                 ieee80211_draintask(ic, &sc->sc_start_task);
693
694                 wpi_stop(sc);
695
696                 taskqueue_drain_all(sc->sc_tq);
697                 taskqueue_free(sc->sc_tq);
698
699                 callout_drain(&sc->watchdog_rfkill);
700                 callout_drain(&sc->tx_timeout);
701                 callout_drain(&sc->scan_timeout);
702                 callout_drain(&sc->calib_to);
703                 ieee80211_ifdetach(ic);
704         }
705
706         /* Uninstall interrupt handler. */
707         if (sc->irq != NULL) {
708                 bus_teardown_intr(dev, sc->irq, sc->sc_ih);
709                 bus_release_resource(dev, SYS_RES_IRQ, rman_get_rid(sc->irq),
710                     sc->irq);
711                 pci_release_msi(dev);
712         }
713
714         if (sc->txq[0].data_dmat) {
715                 /* Free DMA resources. */
716                 for (qid = 0; qid < WPI_NTXQUEUES; qid++)
717                         wpi_free_tx_ring(sc, &sc->txq[qid]);
718
719                 wpi_free_rx_ring(sc);
720                 wpi_free_shared(sc);
721         }
722
723         if (sc->fw_dma.tag)
724                 wpi_free_fwmem(sc);
725                 
726         if (sc->mem != NULL)
727                 bus_release_resource(dev, SYS_RES_MEMORY,
728                     rman_get_rid(sc->mem), sc->mem);
729
730         if (ifp != NULL)
731                 if_free(ifp);
732
733         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
734         WPI_TXQ_STATE_LOCK_DESTROY(sc);
735         WPI_TXQ_LOCK_DESTROY(sc);
736         WPI_NT_LOCK_DESTROY(sc);
737         WPI_RXON_LOCK_DESTROY(sc);
738         WPI_TX_LOCK_DESTROY(sc);
739         WPI_LOCK_DESTROY(sc);
740         return 0;
741 }
742
743 static int
744 wpi_shutdown(device_t dev)
745 {
746         struct wpi_softc *sc = device_get_softc(dev);
747
748         wpi_stop(sc);
749         return 0;
750 }
751
752 static int
753 wpi_suspend(device_t dev)
754 {
755         struct wpi_softc *sc = device_get_softc(dev);
756         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
757
758         ieee80211_suspend_all(ic);
759         return 0;
760 }
761
762 static int
763 wpi_resume(device_t dev)
764 {
765         struct wpi_softc *sc = device_get_softc(dev);
766         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
767
768         /* Clear device-specific "PCI retry timeout" register (41h). */
769         pci_write_config(dev, 0x41, 0, 1);
770
771         ieee80211_resume_all(ic);
772         return 0;
773 }
774
775 /*
776  * Grab exclusive access to NIC memory.
777  */
778 static int
779 wpi_nic_lock(struct wpi_softc *sc)
780 {
781         int ntries;
782
783         /* Request exclusive access to NIC. */
784         WPI_SETBITS(sc, WPI_GP_CNTRL, WPI_GP_CNTRL_MAC_ACCESS_REQ);
785
786         /* Spin until we actually get the lock. */
787         for (ntries = 0; ntries < 1000; ntries++) {
788                 if ((WPI_READ(sc, WPI_GP_CNTRL) &
789                     (WPI_GP_CNTRL_MAC_ACCESS_ENA | WPI_GP_CNTRL_SLEEP)) ==
790                     WPI_GP_CNTRL_MAC_ACCESS_ENA)
791                         return 0;
792                 DELAY(10);
793         }
794
795         device_printf(sc->sc_dev, "could not lock memory\n");
796
797         return ETIMEDOUT;
798 }
799
800 /*
801  * Release lock on NIC memory.
802  */
803 static __inline void
804 wpi_nic_unlock(struct wpi_softc *sc)
805 {
806         WPI_CLRBITS(sc, WPI_GP_CNTRL, WPI_GP_CNTRL_MAC_ACCESS_REQ);
807 }
808
809 static __inline uint32_t
810 wpi_prph_read(struct wpi_softc *sc, uint32_t addr)
811 {
812         WPI_WRITE(sc, WPI_PRPH_RADDR, WPI_PRPH_DWORD | addr);
813         WPI_BARRIER_READ_WRITE(sc);
814         return WPI_READ(sc, WPI_PRPH_RDATA);
815 }
816
817 static __inline void
818 wpi_prph_write(struct wpi_softc *sc, uint32_t addr, uint32_t data)
819 {
820         WPI_WRITE(sc, WPI_PRPH_WADDR, WPI_PRPH_DWORD | addr);
821         WPI_BARRIER_WRITE(sc);
822         WPI_WRITE(sc, WPI_PRPH_WDATA, data);
823 }
824
825 static __inline void
826 wpi_prph_setbits(struct wpi_softc *sc, uint32_t addr, uint32_t mask)
827 {
828         wpi_prph_write(sc, addr, wpi_prph_read(sc, addr) | mask);
829 }
830
831 static __inline void
832 wpi_prph_clrbits(struct wpi_softc *sc, uint32_t addr, uint32_t mask)
833 {
834         wpi_prph_write(sc, addr, wpi_prph_read(sc, addr) & ~mask);
835 }
836
837 static __inline void
838 wpi_prph_write_region_4(struct wpi_softc *sc, uint32_t addr,
839     const uint32_t *data, int count)
840 {
841         for (; count > 0; count--, data++, addr += 4)
842                 wpi_prph_write(sc, addr, *data);
843 }
844
845 static __inline uint32_t
846 wpi_mem_read(struct wpi_softc *sc, uint32_t addr)
847 {
848         WPI_WRITE(sc, WPI_MEM_RADDR, addr);
849         WPI_BARRIER_READ_WRITE(sc);
850         return WPI_READ(sc, WPI_MEM_RDATA);
851 }
852
853 static __inline void
854 wpi_mem_read_region_4(struct wpi_softc *sc, uint32_t addr, uint32_t *data,
855     int count)
856 {
857         for (; count > 0; count--, addr += 4)
858                 *data++ = wpi_mem_read(sc, addr);
859 }
860
861 static int
862 wpi_read_prom_data(struct wpi_softc *sc, uint32_t addr, void *data, int count)
863 {
864         uint8_t *out = data;
865         uint32_t val;
866         int error, ntries;
867
868         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
869
870         if ((error = wpi_nic_lock(sc)) != 0)
871                 return error;
872
873         for (; count > 0; count -= 2, addr++) {
874                 WPI_WRITE(sc, WPI_EEPROM, addr << 2);
875                 for (ntries = 0; ntries < 10; ntries++) {
876                         val = WPI_READ(sc, WPI_EEPROM);
877                         if (val & WPI_EEPROM_READ_VALID)
878                                 break;
879                         DELAY(5);
880                 }
881                 if (ntries == 10) {
882                         device_printf(sc->sc_dev,
883                             "timeout reading ROM at 0x%x\n", addr);
884                         return ETIMEDOUT;
885                 }
886                 *out++= val >> 16;
887                 if (count > 1)
888                         *out ++= val >> 24;
889         }
890
891         wpi_nic_unlock(sc);
892
893         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
894
895         return 0;
896 }
897
898 static void
899 wpi_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
900 {
901         if (error != 0)
902                 return;
903         KASSERT(nsegs == 1, ("too many DMA segments, %d should be 1", nsegs));
904         *(bus_addr_t *)arg = segs[0].ds_addr;
905 }
906
907 /*
908  * Allocates a contiguous block of dma memory of the requested size and
909  * alignment.
910  */
911 static int
912 wpi_dma_contig_alloc(struct wpi_softc *sc, struct wpi_dma_info *dma,
913     void **kvap, bus_size_t size, bus_size_t alignment)
914 {
915         int error;
916
917         dma->tag = NULL;
918         dma->size = size;
919
920         error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), alignment,
921             0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, size,
922             1, size, BUS_DMA_NOWAIT, NULL, NULL, &dma->tag);
923         if (error != 0)
924                 goto fail;
925
926         error = bus_dmamem_alloc(dma->tag, (void **)&dma->vaddr,
927             BUS_DMA_NOWAIT | BUS_DMA_ZERO | BUS_DMA_COHERENT, &dma->map);
928         if (error != 0)
929                 goto fail;
930
931         error = bus_dmamap_load(dma->tag, dma->map, dma->vaddr, size,
932             wpi_dma_map_addr, &dma->paddr, BUS_DMA_NOWAIT);
933         if (error != 0)
934                 goto fail;
935
936         bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
937
938         if (kvap != NULL)
939                 *kvap = dma->vaddr;
940
941         return 0;
942
943 fail:   wpi_dma_contig_free(dma);
944         return error;
945 }
946
947 static void
948 wpi_dma_contig_free(struct wpi_dma_info *dma)
949 {
950         if (dma->vaddr != NULL) {
951                 bus_dmamap_sync(dma->tag, dma->map,
952                     BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
953                 bus_dmamap_unload(dma->tag, dma->map);
954                 bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
955                 dma->vaddr = NULL;
956         }
957         if (dma->tag != NULL) {
958                 bus_dma_tag_destroy(dma->tag);
959                 dma->tag = NULL;
960         }
961 }
962
963 /*
964  * Allocate a shared page between host and NIC.
965  */
966 static int
967 wpi_alloc_shared(struct wpi_softc *sc)
968 {
969         /* Shared buffer must be aligned on a 4KB boundary. */
970         return wpi_dma_contig_alloc(sc, &sc->shared_dma,
971             (void **)&sc->shared, sizeof (struct wpi_shared), 4096);
972 }
973
974 static void
975 wpi_free_shared(struct wpi_softc *sc)
976 {
977         wpi_dma_contig_free(&sc->shared_dma);
978 }
979
980 /*
981  * Allocate DMA-safe memory for firmware transfer.
982  */
983 static int
984 wpi_alloc_fwmem(struct wpi_softc *sc)
985 {
986         /* Must be aligned on a 16-byte boundary. */
987         return wpi_dma_contig_alloc(sc, &sc->fw_dma, NULL,
988             WPI_FW_TEXT_MAXSZ + WPI_FW_DATA_MAXSZ, 16);
989 }
990
991 static void
992 wpi_free_fwmem(struct wpi_softc *sc)
993 {
994         wpi_dma_contig_free(&sc->fw_dma);
995 }
996
997 static int
998 wpi_alloc_rx_ring(struct wpi_softc *sc)
999 {
1000         struct wpi_rx_ring *ring = &sc->rxq;
1001         bus_size_t size;
1002         int i, error;
1003
1004         ring->cur = 0;
1005         ring->update = 0;
1006
1007         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
1008
1009         /* Allocate RX descriptors (16KB aligned.) */
1010         size = WPI_RX_RING_COUNT * sizeof (uint32_t);
1011         error = wpi_dma_contig_alloc(sc, &ring->desc_dma,
1012             (void **)&ring->desc, size, WPI_RING_DMA_ALIGN);
1013         if (error != 0) {
1014                 device_printf(sc->sc_dev,
1015                     "%s: could not allocate RX ring DMA memory, error %d\n",
1016                     __func__, error);
1017                 goto fail;
1018         }
1019
1020         /* Create RX buffer DMA tag. */
1021         error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0, 
1022             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
1023             MJUMPAGESIZE, 1, MJUMPAGESIZE, BUS_DMA_NOWAIT, NULL, NULL,
1024             &ring->data_dmat);
1025         if (error != 0) {
1026                 device_printf(sc->sc_dev,
1027                     "%s: could not create RX buf DMA tag, error %d\n",
1028                     __func__, error);
1029                 goto fail;
1030         }
1031
1032         /*
1033          * Allocate and map RX buffers.
1034          */
1035         for (i = 0; i < WPI_RX_RING_COUNT; i++) {
1036                 struct wpi_rx_data *data = &ring->data[i];
1037                 bus_addr_t paddr;
1038
1039                 error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
1040                 if (error != 0) {
1041                         device_printf(sc->sc_dev,
1042                             "%s: could not create RX buf DMA map, error %d\n",
1043                             __func__, error);
1044                         goto fail;
1045                 }
1046
1047                 data->m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE);
1048                 if (data->m == NULL) {
1049                         device_printf(sc->sc_dev,
1050                             "%s: could not allocate RX mbuf\n", __func__);
1051                         error = ENOBUFS;
1052                         goto fail;
1053                 }
1054
1055                 error = bus_dmamap_load(ring->data_dmat, data->map,
1056                     mtod(data->m, void *), MJUMPAGESIZE, wpi_dma_map_addr,
1057                     &paddr, BUS_DMA_NOWAIT);
1058                 if (error != 0 && error != EFBIG) {
1059                         device_printf(sc->sc_dev,
1060                             "%s: can't map mbuf (error %d)\n", __func__,
1061                             error);
1062                         goto fail;
1063                 }
1064
1065                 /* Set physical address of RX buffer. */
1066                 ring->desc[i] = htole32(paddr);
1067         }
1068
1069         bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
1070             BUS_DMASYNC_PREWRITE);
1071
1072         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
1073
1074         return 0;
1075
1076 fail:   wpi_free_rx_ring(sc);
1077
1078         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
1079
1080         return error;
1081 }
1082
1083 static void
1084 wpi_update_rx_ring(struct wpi_softc *sc)
1085 {
1086         struct wpi_rx_ring *ring = &sc->rxq;
1087
1088         if (ring->update != 0) {
1089                 /* Wait for INT_WAKEUP event. */
1090                 return;
1091         }
1092
1093         if (WPI_READ(sc, WPI_UCODE_GP1) & WPI_UCODE_GP1_MAC_SLEEP) {
1094                 DPRINTF(sc, WPI_DEBUG_PWRSAVE, "%s: wakeup request\n",
1095                     __func__);
1096
1097                 WPI_SETBITS(sc, WPI_GP_CNTRL, WPI_GP_CNTRL_MAC_ACCESS_REQ);
1098                 ring->update = 1;
1099         } else
1100                 WPI_WRITE(sc, WPI_FH_RX_WPTR, ring->cur & ~7);
1101 }
1102
1103 static void
1104 wpi_reset_rx_ring(struct wpi_softc *sc)
1105 {
1106         struct wpi_rx_ring *ring = &sc->rxq;
1107         int ntries;
1108
1109         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
1110
1111         if (wpi_nic_lock(sc) == 0) {
1112                 WPI_WRITE(sc, WPI_FH_RX_CONFIG, 0);
1113                 for (ntries = 0; ntries < 1000; ntries++) {
1114                         if (WPI_READ(sc, WPI_FH_RX_STATUS) &
1115                             WPI_FH_RX_STATUS_IDLE)
1116                                 break;
1117                         DELAY(10);
1118                 }
1119                 wpi_nic_unlock(sc);
1120         }
1121
1122         ring->cur = 0;
1123         ring->update = 0;
1124 }
1125
1126 static void
1127 wpi_free_rx_ring(struct wpi_softc *sc)
1128 {
1129         struct wpi_rx_ring *ring = &sc->rxq;
1130         int i;
1131
1132         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
1133
1134         wpi_dma_contig_free(&ring->desc_dma);
1135
1136         for (i = 0; i < WPI_RX_RING_COUNT; i++) {
1137                 struct wpi_rx_data *data = &ring->data[i];
1138
1139                 if (data->m != NULL) {
1140                         bus_dmamap_sync(ring->data_dmat, data->map,
1141                             BUS_DMASYNC_POSTREAD);
1142                         bus_dmamap_unload(ring->data_dmat, data->map);
1143                         m_freem(data->m);
1144                         data->m = NULL;
1145                 }
1146                 if (data->map != NULL)
1147                         bus_dmamap_destroy(ring->data_dmat, data->map);
1148         }
1149         if (ring->data_dmat != NULL) {
1150                 bus_dma_tag_destroy(ring->data_dmat);
1151                 ring->data_dmat = NULL;
1152         }
1153 }
1154
1155 static int
1156 wpi_alloc_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring, int qid)
1157 {
1158         bus_addr_t paddr;
1159         bus_size_t size;
1160         int i, error;
1161
1162         ring->qid = qid;
1163         ring->queued = 0;
1164         ring->cur = 0;
1165         ring->update = 0;
1166
1167         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
1168
1169         /* Allocate TX descriptors (16KB aligned.) */
1170         size = WPI_TX_RING_COUNT * sizeof (struct wpi_tx_desc);
1171         error = wpi_dma_contig_alloc(sc, &ring->desc_dma, (void **)&ring->desc,
1172             size, WPI_RING_DMA_ALIGN);
1173         if (error != 0) {
1174                 device_printf(sc->sc_dev,
1175                     "%s: could not allocate TX ring DMA memory, error %d\n",
1176                     __func__, error);
1177                 goto fail;
1178         }
1179
1180         /* Update shared area with ring physical address. */
1181         sc->shared->txbase[qid] = htole32(ring->desc_dma.paddr);
1182         bus_dmamap_sync(sc->shared_dma.tag, sc->shared_dma.map,
1183             BUS_DMASYNC_PREWRITE);
1184
1185         /*
1186          * We only use rings 0 through 4 (4 EDCA + cmd) so there is no need
1187          * to allocate commands space for other rings.
1188          * XXX Do we really need to allocate descriptors for other rings?
1189          */
1190         if (qid > WPI_CMD_QUEUE_NUM) {
1191                 DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
1192                 return 0;
1193         }
1194
1195         size = WPI_TX_RING_COUNT * sizeof (struct wpi_tx_cmd);
1196         error = wpi_dma_contig_alloc(sc, &ring->cmd_dma, (void **)&ring->cmd,
1197             size, 4);
1198         if (error != 0) {
1199                 device_printf(sc->sc_dev,
1200                     "%s: could not allocate TX cmd DMA memory, error %d\n",
1201                     __func__, error);
1202                 goto fail;
1203         }
1204
1205         error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
1206             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
1207             WPI_MAX_SCATTER - 1, MCLBYTES, BUS_DMA_NOWAIT, NULL, NULL,
1208             &ring->data_dmat);
1209         if (error != 0) {
1210                 device_printf(sc->sc_dev,
1211                     "%s: could not create TX buf DMA tag, error %d\n",
1212                     __func__, error);
1213                 goto fail;
1214         }
1215
1216         paddr = ring->cmd_dma.paddr;
1217         for (i = 0; i < WPI_TX_RING_COUNT; i++) {
1218                 struct wpi_tx_data *data = &ring->data[i];
1219
1220                 data->cmd_paddr = paddr;
1221                 paddr += sizeof (struct wpi_tx_cmd);
1222
1223                 error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
1224                 if (error != 0) {
1225                         device_printf(sc->sc_dev,
1226                             "%s: could not create TX buf DMA map, error %d\n",
1227                             __func__, error);
1228                         goto fail;
1229                 }
1230         }
1231
1232         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
1233
1234         return 0;
1235
1236 fail:   wpi_free_tx_ring(sc, ring);
1237         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
1238         return error;
1239 }
1240
1241 static void
1242 wpi_update_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring)
1243 {
1244         if (ring->update != 0) {
1245                 /* Wait for INT_WAKEUP event. */
1246                 return;
1247         }
1248
1249         if (WPI_READ(sc, WPI_UCODE_GP1) & WPI_UCODE_GP1_MAC_SLEEP) {
1250                 DPRINTF(sc, WPI_DEBUG_PWRSAVE, "%s (%d): requesting wakeup\n",
1251                     __func__, ring->qid);
1252
1253                 WPI_SETBITS(sc, WPI_GP_CNTRL, WPI_GP_CNTRL_MAC_ACCESS_REQ);
1254                 ring->update = 1;
1255         } else
1256                 WPI_WRITE(sc, WPI_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
1257 }
1258
1259 static void
1260 wpi_reset_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring)
1261 {
1262         int i;
1263
1264         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
1265
1266         for (i = 0; i < WPI_TX_RING_COUNT; i++) {
1267                 struct wpi_tx_data *data = &ring->data[i];
1268
1269                 if (data->m != NULL) {
1270                         bus_dmamap_sync(ring->data_dmat, data->map,
1271                             BUS_DMASYNC_POSTWRITE);
1272                         bus_dmamap_unload(ring->data_dmat, data->map);
1273                         m_freem(data->m);
1274                         data->m = NULL;
1275                 }
1276         }
1277         /* Clear TX descriptors. */
1278         memset(ring->desc, 0, ring->desc_dma.size);
1279         bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
1280             BUS_DMASYNC_PREWRITE);
1281         sc->qfullmsk &= ~(1 << ring->qid);
1282         ring->queued = 0;
1283         ring->cur = 0;
1284         ring->update = 0;
1285 }
1286
1287 static void
1288 wpi_free_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring)
1289 {
1290         int i;
1291
1292         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
1293
1294         wpi_dma_contig_free(&ring->desc_dma);
1295         wpi_dma_contig_free(&ring->cmd_dma);
1296
1297         for (i = 0; i < WPI_TX_RING_COUNT; i++) {
1298                 struct wpi_tx_data *data = &ring->data[i];
1299
1300                 if (data->m != NULL) {
1301                         bus_dmamap_sync(ring->data_dmat, data->map,
1302                             BUS_DMASYNC_POSTWRITE);
1303                         bus_dmamap_unload(ring->data_dmat, data->map);
1304                         m_freem(data->m);
1305                 }
1306                 if (data->map != NULL)
1307                         bus_dmamap_destroy(ring->data_dmat, data->map);
1308         }
1309         if (ring->data_dmat != NULL) {
1310                 bus_dma_tag_destroy(ring->data_dmat);
1311                 ring->data_dmat = NULL;
1312         }
1313 }
1314
1315 /*
1316  * Extract various information from EEPROM.
1317  */
1318 static int
1319 wpi_read_eeprom(struct wpi_softc *sc, uint8_t macaddr[IEEE80211_ADDR_LEN])
1320 {
1321 #define WPI_CHK(res) do {               \
1322         if ((error = res) != 0)         \
1323                 goto fail;              \
1324 } while (0)
1325         int error, i;
1326
1327         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
1328
1329         /* Adapter has to be powered on for EEPROM access to work. */
1330         if ((error = wpi_apm_init(sc)) != 0) {
1331                 device_printf(sc->sc_dev,
1332                     "%s: could not power ON adapter, error %d\n", __func__,
1333                     error);
1334                 return error;
1335         }
1336
1337         if ((WPI_READ(sc, WPI_EEPROM_GP) & 0x6) == 0) {
1338                 device_printf(sc->sc_dev, "bad EEPROM signature\n");
1339                 error = EIO;
1340                 goto fail;
1341         }
1342         /* Clear HW ownership of EEPROM. */
1343         WPI_CLRBITS(sc, WPI_EEPROM_GP, WPI_EEPROM_GP_IF_OWNER);
1344
1345         /* Read the hardware capabilities, revision and SKU type. */
1346         WPI_CHK(wpi_read_prom_data(sc, WPI_EEPROM_SKU_CAP, &sc->cap,
1347             sizeof(sc->cap)));
1348         WPI_CHK(wpi_read_prom_data(sc, WPI_EEPROM_REVISION, &sc->rev,
1349             sizeof(sc->rev)));
1350         WPI_CHK(wpi_read_prom_data(sc, WPI_EEPROM_TYPE, &sc->type,
1351             sizeof(sc->type)));
1352
1353         sc->rev = le16toh(sc->rev);
1354         DPRINTF(sc, WPI_DEBUG_EEPROM, "cap=%x rev=%x type=%x\n", sc->cap,
1355             sc->rev, sc->type);
1356
1357         /* Read the regulatory domain (4 ASCII characters.) */
1358         WPI_CHK(wpi_read_prom_data(sc, WPI_EEPROM_DOMAIN, sc->domain,
1359             sizeof(sc->domain)));
1360
1361         /* Read MAC address. */
1362         WPI_CHK(wpi_read_prom_data(sc, WPI_EEPROM_MAC, macaddr,
1363             IEEE80211_ADDR_LEN));
1364
1365         /* Read the list of authorized channels. */
1366         for (i = 0; i < WPI_CHAN_BANDS_COUNT; i++)
1367                 WPI_CHK(wpi_read_eeprom_channels(sc, i));
1368
1369         /* Read the list of TX power groups. */
1370         for (i = 0; i < WPI_POWER_GROUPS_COUNT; i++)
1371                 WPI_CHK(wpi_read_eeprom_group(sc, i));
1372
1373 fail:   wpi_apm_stop(sc);       /* Power OFF adapter. */
1374
1375         DPRINTF(sc, WPI_DEBUG_TRACE, error ? TRACE_STR_END_ERR : TRACE_STR_END,
1376             __func__);
1377
1378         return error;
1379 #undef WPI_CHK
1380 }
1381
1382 /*
1383  * Translate EEPROM flags to net80211.
1384  */
1385 static uint32_t
1386 wpi_eeprom_channel_flags(struct wpi_eeprom_chan *channel)
1387 {
1388         uint32_t nflags;
1389
1390         nflags = 0;
1391         if ((channel->flags & WPI_EEPROM_CHAN_ACTIVE) == 0)
1392                 nflags |= IEEE80211_CHAN_PASSIVE;
1393         if ((channel->flags & WPI_EEPROM_CHAN_IBSS) == 0)
1394                 nflags |= IEEE80211_CHAN_NOADHOC;
1395         if (channel->flags & WPI_EEPROM_CHAN_RADAR) {
1396                 nflags |= IEEE80211_CHAN_DFS;
1397                 /* XXX apparently IBSS may still be marked */
1398                 nflags |= IEEE80211_CHAN_NOADHOC;
1399         }
1400
1401         /* XXX HOSTAP uses WPI_MODE_IBSS */
1402         if (nflags & IEEE80211_CHAN_NOADHOC)
1403                 nflags |= IEEE80211_CHAN_NOHOSTAP;
1404
1405         return nflags;
1406 }
1407
1408 static void
1409 wpi_read_eeprom_band(struct wpi_softc *sc, int n)
1410 {
1411         struct ifnet *ifp = sc->sc_ifp;
1412         struct ieee80211com *ic = ifp->if_l2com;
1413         struct wpi_eeprom_chan *channels = sc->eeprom_channels[n];
1414         const struct wpi_chan_band *band = &wpi_bands[n];
1415         struct ieee80211_channel *c;
1416         uint8_t chan;
1417         int i, nflags;
1418
1419         for (i = 0; i < band->nchan; i++) {
1420                 if (!(channels[i].flags & WPI_EEPROM_CHAN_VALID)) {
1421                         DPRINTF(sc, WPI_DEBUG_EEPROM,
1422                             "Channel Not Valid: %d, band %d\n",
1423                              band->chan[i],n);
1424                         continue;
1425                 }
1426
1427                 chan = band->chan[i];
1428                 nflags = wpi_eeprom_channel_flags(&channels[i]);
1429
1430                 c = &ic->ic_channels[ic->ic_nchans++];
1431                 c->ic_ieee = chan;
1432                 c->ic_maxregpower = channels[i].maxpwr;
1433                 c->ic_maxpower = 2*c->ic_maxregpower;
1434
1435                 if (n == 0) {   /* 2GHz band */
1436                         c->ic_freq = ieee80211_ieee2mhz(chan,
1437                             IEEE80211_CHAN_G);
1438
1439                         /* G =>'s B is supported */
1440                         c->ic_flags = IEEE80211_CHAN_B | nflags;
1441                         c = &ic->ic_channels[ic->ic_nchans++];
1442                         c[0] = c[-1];
1443                         c->ic_flags = IEEE80211_CHAN_G | nflags;
1444                 } else {        /* 5GHz band */
1445                         c->ic_freq = ieee80211_ieee2mhz(chan,
1446                             IEEE80211_CHAN_A);
1447
1448                         c->ic_flags = IEEE80211_CHAN_A | nflags;
1449                 }
1450
1451                 /* Save maximum allowed TX power for this channel. */
1452                 sc->maxpwr[chan] = channels[i].maxpwr;
1453
1454                 DPRINTF(sc, WPI_DEBUG_EEPROM,
1455                     "adding chan %d (%dMHz) flags=0x%x maxpwr=%d passive=%d,"
1456                     " offset %d\n", chan, c->ic_freq,
1457                     channels[i].flags, sc->maxpwr[chan],
1458                     IEEE80211_IS_CHAN_PASSIVE(c), ic->ic_nchans);
1459         }
1460 }
1461
1462 /**
1463  * Read the eeprom to find out what channels are valid for the given
1464  * band and update net80211 with what we find.
1465  */
1466 static int
1467 wpi_read_eeprom_channels(struct wpi_softc *sc, int n)
1468 {
1469         struct ifnet *ifp = sc->sc_ifp;
1470         struct ieee80211com *ic = ifp->if_l2com;
1471         const struct wpi_chan_band *band = &wpi_bands[n];
1472         int error;
1473
1474         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
1475
1476         error = wpi_read_prom_data(sc, band->addr, &sc->eeprom_channels[n],
1477             band->nchan * sizeof (struct wpi_eeprom_chan));
1478         if (error != 0) {
1479                 DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
1480                 return error;
1481         }
1482
1483         wpi_read_eeprom_band(sc, n);
1484
1485         ieee80211_sort_channels(ic->ic_channels, ic->ic_nchans);
1486
1487         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
1488
1489         return 0;
1490 }
1491
1492 static struct wpi_eeprom_chan *
1493 wpi_find_eeprom_channel(struct wpi_softc *sc, struct ieee80211_channel *c)
1494 {
1495         int i, j;
1496
1497         for (j = 0; j < WPI_CHAN_BANDS_COUNT; j++)
1498                 for (i = 0; i < wpi_bands[j].nchan; i++)
1499                         if (wpi_bands[j].chan[i] == c->ic_ieee)
1500                                 return &sc->eeprom_channels[j][i];
1501
1502         return NULL;
1503 }
1504
1505 /*
1506  * Enforce flags read from EEPROM.
1507  */
1508 static int
1509 wpi_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *rd,
1510     int nchan, struct ieee80211_channel chans[])
1511 {
1512         struct ifnet *ifp = ic->ic_ifp;
1513         struct wpi_softc *sc = ifp->if_softc;
1514         int i;
1515
1516         for (i = 0; i < nchan; i++) {
1517                 struct ieee80211_channel *c = &chans[i];
1518                 struct wpi_eeprom_chan *channel;
1519
1520                 channel = wpi_find_eeprom_channel(sc, c);
1521                 if (channel == NULL) {
1522                         if_printf(ic->ic_ifp,
1523                             "%s: invalid channel %u freq %u/0x%x\n",
1524                             __func__, c->ic_ieee, c->ic_freq, c->ic_flags);
1525                         return EINVAL;
1526                 }
1527                 c->ic_flags |= wpi_eeprom_channel_flags(channel);
1528         }
1529
1530         return 0;
1531 }
1532
1533 static int
1534 wpi_read_eeprom_group(struct wpi_softc *sc, int n)
1535 {
1536         struct wpi_power_group *group = &sc->groups[n];
1537         struct wpi_eeprom_group rgroup;
1538         int i, error;
1539
1540         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
1541
1542         if ((error = wpi_read_prom_data(sc, WPI_EEPROM_POWER_GRP + n * 32,
1543             &rgroup, sizeof rgroup)) != 0) {
1544                 DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
1545                 return error;
1546         }
1547
1548         /* Save TX power group information. */
1549         group->chan   = rgroup.chan;
1550         group->maxpwr = rgroup.maxpwr;
1551         /* Retrieve temperature at which the samples were taken. */
1552         group->temp   = (int16_t)le16toh(rgroup.temp);
1553
1554         DPRINTF(sc, WPI_DEBUG_EEPROM,
1555             "power group %d: chan=%d maxpwr=%d temp=%d\n", n, group->chan,
1556             group->maxpwr, group->temp);
1557
1558         for (i = 0; i < WPI_SAMPLES_COUNT; i++) {
1559                 group->samples[i].index = rgroup.samples[i].index;
1560                 group->samples[i].power = rgroup.samples[i].power;
1561
1562                 DPRINTF(sc, WPI_DEBUG_EEPROM,
1563                     "\tsample %d: index=%d power=%d\n", i,
1564                     group->samples[i].index, group->samples[i].power);
1565         }
1566
1567         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
1568
1569         return 0;
1570 }
1571
1572 static int
1573 wpi_add_node_entry_adhoc(struct wpi_softc *sc)
1574 {
1575         int newid = WPI_ID_IBSS_MIN;
1576
1577         for (; newid <= WPI_ID_IBSS_MAX; newid++) {
1578                 if ((sc->nodesmsk & (1 << newid)) == 0) {
1579                         sc->nodesmsk |= 1 << newid;
1580                         return newid;
1581                 }
1582         }
1583
1584         return WPI_ID_UNDEFINED;
1585 }
1586
1587 static __inline int
1588 wpi_add_node_entry_sta(struct wpi_softc *sc)
1589 {
1590         sc->nodesmsk |= 1 << WPI_ID_BSS;
1591
1592         return WPI_ID_BSS;
1593 }
1594
1595 static __inline int
1596 wpi_check_node_entry(struct wpi_softc *sc, uint8_t id)
1597 {
1598         if (id == WPI_ID_UNDEFINED)
1599                 return 0;
1600
1601         return (sc->nodesmsk >> id) & 1;
1602 }
1603
1604 static __inline void
1605 wpi_clear_node_table(struct wpi_softc *sc)
1606 {
1607         sc->nodesmsk = 0;
1608 }
1609
1610 static __inline void
1611 wpi_del_node_entry(struct wpi_softc *sc, uint8_t id)
1612 {
1613         sc->nodesmsk &= ~(1 << id);
1614 }
1615
1616 static struct ieee80211_node *
1617 wpi_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
1618 {
1619         struct wpi_node *wn;
1620
1621         wn = malloc(sizeof (struct wpi_node), M_80211_NODE,
1622             M_NOWAIT | M_ZERO);
1623
1624         if (wn == NULL)
1625                 return NULL;
1626
1627         wn->id = WPI_ID_UNDEFINED;
1628
1629         return &wn->ni;
1630 }
1631
1632 static void
1633 wpi_node_free(struct ieee80211_node *ni)
1634 {
1635         struct ieee80211com *ic = ni->ni_ic;
1636         struct wpi_softc *sc = ic->ic_ifp->if_softc;
1637         struct wpi_node *wn = WPI_NODE(ni);
1638
1639         if (wn->id != WPI_ID_UNDEFINED) {
1640                 WPI_NT_LOCK(sc);
1641                 if (wpi_check_node_entry(sc, wn->id)) {
1642                         wpi_del_node_entry(sc, wn->id);
1643                         wpi_del_node(sc, ni);
1644                 }
1645                 WPI_NT_UNLOCK(sc);
1646         }
1647
1648         sc->sc_node_free(ni);
1649 }
1650
1651 static __inline int
1652 wpi_check_bss_filter(struct wpi_softc *sc)
1653 {
1654         return (sc->rxon.filter & htole32(WPI_FILTER_BSS)) != 0;
1655 }
1656
1657 /**
1658  * Called by net80211 when ever there is a change to 80211 state machine
1659  */
1660 static int
1661 wpi_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
1662 {
1663         struct wpi_vap *wvp = WPI_VAP(vap);
1664         struct ieee80211com *ic = vap->iv_ic;
1665         struct ifnet *ifp = ic->ic_ifp;
1666         struct wpi_softc *sc = ifp->if_softc;
1667         int error = 0;
1668
1669         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
1670
1671         DPRINTF(sc, WPI_DEBUG_STATE, "%s: %s -> %s\n", __func__,
1672                 ieee80211_state_name[vap->iv_state],
1673                 ieee80211_state_name[nstate]);
1674
1675         if (vap->iv_state == IEEE80211_S_RUN && nstate != IEEE80211_S_RUN) {
1676                 if ((error = wpi_set_pslevel(sc, 0, 0, 1)) != 0) {
1677                         device_printf(sc->sc_dev,
1678                             "%s: could not set power saving level\n",
1679                             __func__);
1680                         return error;
1681                 }
1682         }
1683
1684         switch (nstate) {
1685         case IEEE80211_S_SCAN:
1686                 WPI_RXON_LOCK(sc);
1687                 if (wpi_check_bss_filter(sc) != 0 &&
1688                     vap->iv_opmode != IEEE80211_M_STA) {
1689                         sc->rxon.filter &= ~htole32(WPI_FILTER_BSS);
1690                         if ((error = wpi_send_rxon(sc, 0, 1)) != 0) {
1691                                 device_printf(sc->sc_dev,
1692                                     "%s: could not send RXON\n", __func__);
1693                         }
1694                 }
1695                 WPI_RXON_UNLOCK(sc);
1696                 break;
1697
1698         case IEEE80211_S_ASSOC:
1699                 if (vap->iv_state != IEEE80211_S_RUN)
1700                         break;
1701                 /* FALLTHROUGH */
1702         case IEEE80211_S_AUTH:
1703                 /*
1704                  * The node must be registered in the firmware before auth.
1705                  * Also the associd must be cleared on RUN -> ASSOC
1706                  * transitions.
1707                  */
1708                 if ((error = wpi_auth(sc, vap)) != 0) {
1709                         device_printf(sc->sc_dev,
1710                             "%s: could not move to AUTH state, error %d\n",
1711                             __func__, error);
1712                 }
1713                 break;
1714
1715         case IEEE80211_S_RUN:
1716                 /*
1717                  * RUN -> RUN transition; Just restart the timers.
1718                  */
1719                 if (vap->iv_state == IEEE80211_S_RUN) {
1720                         WPI_RXON_LOCK(sc);
1721                         wpi_calib_timeout(sc);
1722                         WPI_RXON_UNLOCK(sc);
1723                         break;
1724                 }
1725
1726                 /*
1727                  * !RUN -> RUN requires setting the association id
1728                  * which is done with a firmware cmd.  We also defer
1729                  * starting the timers until that work is done.
1730                  */
1731                 if ((error = wpi_run(sc, vap)) != 0) {
1732                         device_printf(sc->sc_dev,
1733                             "%s: could not move to RUN state\n", __func__);
1734                 }
1735                 break;
1736
1737         default:
1738                 break;
1739         }
1740         if (error != 0) {
1741                 DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
1742                 return error;
1743         }
1744
1745         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
1746
1747         return wvp->wv_newstate(vap, nstate, arg);
1748 }
1749
1750 static void
1751 wpi_calib_timeout(void *arg)
1752 {
1753         struct wpi_softc *sc = arg;
1754
1755         if (wpi_check_bss_filter(sc) == 0)
1756                 return;
1757
1758         wpi_power_calibration(sc);
1759
1760         callout_reset(&sc->calib_to, 60*hz, wpi_calib_timeout, sc);
1761 }
1762
1763 static __inline uint8_t
1764 rate2plcp(const uint8_t rate)
1765 {
1766         switch (rate) {
1767         case 12:        return 0xd;
1768         case 18:        return 0xf;
1769         case 24:        return 0x5;
1770         case 36:        return 0x7;
1771         case 48:        return 0x9;
1772         case 72:        return 0xb;
1773         case 96:        return 0x1;
1774         case 108:       return 0x3;
1775         case 2:         return 10;
1776         case 4:         return 20;
1777         case 11:        return 55;
1778         case 22:        return 110;
1779         default:        return 0;
1780         }
1781 }
1782
1783 static __inline uint8_t
1784 plcp2rate(const uint8_t plcp)
1785 {
1786         switch (plcp) {
1787         case 0xd:       return 12;
1788         case 0xf:       return 18;
1789         case 0x5:       return 24;
1790         case 0x7:       return 36;
1791         case 0x9:       return 48;
1792         case 0xb:       return 72;
1793         case 0x1:       return 96;
1794         case 0x3:       return 108;
1795         case 10:        return 2;
1796         case 20:        return 4;
1797         case 55:        return 11;
1798         case 110:       return 22;
1799         default:        return 0;
1800         }
1801 }
1802
1803 /* Quickly determine if a given rate is CCK or OFDM. */
1804 #define WPI_RATE_IS_OFDM(rate)  ((rate) >= 12 && (rate) != 22)
1805
1806 static void
1807 wpi_rx_done(struct wpi_softc *sc, struct wpi_rx_desc *desc,
1808     struct wpi_rx_data *data)
1809 {
1810         struct ifnet *ifp = sc->sc_ifp;
1811         struct ieee80211com *ic = ifp->if_l2com;
1812         struct wpi_rx_ring *ring = &sc->rxq;
1813         struct wpi_rx_stat *stat;
1814         struct wpi_rx_head *head;
1815         struct wpi_rx_tail *tail;
1816         struct ieee80211_frame *wh;
1817         struct ieee80211_node *ni;
1818         struct mbuf *m, *m1;
1819         bus_addr_t paddr;
1820         uint32_t flags;
1821         uint16_t len;
1822         int error;
1823
1824         stat = (struct wpi_rx_stat *)(desc + 1);
1825
1826         if (stat->len > WPI_STAT_MAXLEN) {
1827                 device_printf(sc->sc_dev, "invalid RX statistic header\n");
1828                 goto fail1;
1829         }
1830
1831         bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD);
1832         head = (struct wpi_rx_head *)((caddr_t)(stat + 1) + stat->len);
1833         len = le16toh(head->len);
1834         tail = (struct wpi_rx_tail *)((caddr_t)(head + 1) + len);
1835         flags = le32toh(tail->flags);
1836
1837         DPRINTF(sc, WPI_DEBUG_RECV, "%s: idx %d len %d stat len %u rssi %d"
1838             " rate %x chan %d tstamp %ju\n", __func__, ring->cur,
1839             le32toh(desc->len), len, (int8_t)stat->rssi,
1840             head->plcp, head->chan, (uintmax_t)le64toh(tail->tstamp));
1841
1842         /* Discard frames with a bad FCS early. */
1843         if ((flags & WPI_RX_NOERROR) != WPI_RX_NOERROR) {
1844                 DPRINTF(sc, WPI_DEBUG_RECV, "%s: RX flags error %x\n",
1845                     __func__, flags);
1846                 goto fail1;
1847         }
1848         /* Discard frames that are too short. */
1849         if (len < sizeof (*wh)) {
1850                 DPRINTF(sc, WPI_DEBUG_RECV, "%s: frame too short: %d\n",
1851                     __func__, len);
1852                 goto fail1;
1853         }
1854
1855         m1 = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE);
1856         if (m1 == NULL) {
1857                 DPRINTF(sc, WPI_DEBUG_ANY, "%s: no mbuf to restock ring\n",
1858                     __func__);
1859                 goto fail1;
1860         }
1861         bus_dmamap_unload(ring->data_dmat, data->map);
1862
1863         error = bus_dmamap_load(ring->data_dmat, data->map, mtod(m1, void *),
1864             MJUMPAGESIZE, wpi_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
1865         if (error != 0 && error != EFBIG) {
1866                 device_printf(sc->sc_dev,
1867                     "%s: bus_dmamap_load failed, error %d\n", __func__, error);
1868                 m_freem(m1);
1869
1870                 /* Try to reload the old mbuf. */
1871                 error = bus_dmamap_load(ring->data_dmat, data->map,
1872                     mtod(data->m, void *), MJUMPAGESIZE, wpi_dma_map_addr,
1873                     &paddr, BUS_DMA_NOWAIT);
1874                 if (error != 0 && error != EFBIG) {
1875                         panic("%s: could not load old RX mbuf", __func__);
1876                 }
1877                 /* Physical address may have changed. */
1878                 ring->desc[ring->cur] = htole32(paddr);
1879                 bus_dmamap_sync(ring->data_dmat, ring->desc_dma.map,
1880                     BUS_DMASYNC_PREWRITE);
1881                 goto fail1;
1882         }
1883
1884         m = data->m;
1885         data->m = m1;
1886         /* Update RX descriptor. */
1887         ring->desc[ring->cur] = htole32(paddr);
1888         bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
1889             BUS_DMASYNC_PREWRITE);
1890
1891         /* Finalize mbuf. */
1892         m->m_pkthdr.rcvif = ifp;
1893         m->m_data = (caddr_t)(head + 1);
1894         m->m_pkthdr.len = m->m_len = len;
1895
1896         /* Grab a reference to the source node. */
1897         wh = mtod(m, struct ieee80211_frame *);
1898
1899         if ((wh->i_fc[1] & IEEE80211_FC1_PROTECTED) &&
1900             (flags & WPI_RX_CIPHER_MASK) == WPI_RX_CIPHER_CCMP) {
1901                 /* Check whether decryption was successful or not. */
1902                 if ((flags & WPI_RX_DECRYPT_MASK) != WPI_RX_DECRYPT_OK) {
1903                         DPRINTF(sc, WPI_DEBUG_RECV,
1904                             "CCMP decryption failed 0x%x\n", flags);
1905                         goto fail2;
1906                 }
1907                 m->m_flags |= M_WEP;
1908         }
1909
1910         ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
1911
1912         if (ieee80211_radiotap_active(ic)) {
1913                 struct wpi_rx_radiotap_header *tap = &sc->sc_rxtap;
1914
1915                 tap->wr_flags = 0;
1916                 if (head->flags & htole16(WPI_STAT_FLAG_SHPREAMBLE))
1917                         tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
1918                 tap->wr_dbm_antsignal = (int8_t)(stat->rssi + WPI_RSSI_OFFSET);
1919                 tap->wr_dbm_antnoise = WPI_RSSI_OFFSET;
1920                 tap->wr_tsft = tail->tstamp;
1921                 tap->wr_antenna = (le16toh(head->flags) >> 4) & 0xf;
1922                 tap->wr_rate = plcp2rate(head->plcp);
1923         }
1924
1925         WPI_UNLOCK(sc);
1926
1927         /* Send the frame to the 802.11 layer. */
1928         if (ni != NULL) {
1929                 (void)ieee80211_input(ni, m, stat->rssi, WPI_RSSI_OFFSET);
1930                 /* Node is no longer needed. */
1931                 ieee80211_free_node(ni);
1932         } else
1933                 (void)ieee80211_input_all(ic, m, stat->rssi, WPI_RSSI_OFFSET);
1934
1935         WPI_LOCK(sc);
1936
1937         return;
1938
1939 fail2:  m_freem(m);
1940
1941 fail1:  if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
1942 }
1943
1944 static void
1945 wpi_rx_statistics(struct wpi_softc *sc, struct wpi_rx_desc *desc,
1946     struct wpi_rx_data *data)
1947 {
1948         /* Ignore */
1949 }
1950
1951 static void
1952 wpi_tx_done(struct wpi_softc *sc, struct wpi_rx_desc *desc)
1953 {
1954         struct ifnet *ifp = sc->sc_ifp;
1955         struct wpi_tx_ring *ring = &sc->txq[desc->qid & 0x3];
1956         struct wpi_tx_data *data = &ring->data[desc->idx];
1957         struct wpi_tx_stat *stat = (struct wpi_tx_stat *)(desc + 1);
1958         struct mbuf *m;
1959         struct ieee80211_node *ni;
1960         struct ieee80211vap *vap;
1961         struct ieee80211com *ic;
1962         uint32_t status = le32toh(stat->status);
1963         int ackfailcnt = stat->ackfailcnt / WPI_NTRIES_DEFAULT;
1964
1965         KASSERT(data->ni != NULL, ("no node"));
1966         KASSERT(data->m != NULL, ("no mbuf"));
1967
1968         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
1969
1970         DPRINTF(sc, WPI_DEBUG_XMIT, "%s: "
1971             "qid %d idx %d retries %d btkillcnt %d rate %x duration %d "
1972             "status %x\n", __func__, desc->qid, desc->idx, stat->ackfailcnt,
1973             stat->btkillcnt, stat->rate, le32toh(stat->duration), status);
1974
1975         /* Unmap and free mbuf. */
1976         bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTWRITE);
1977         bus_dmamap_unload(ring->data_dmat, data->map);
1978         m = data->m, data->m = NULL;
1979         ni = data->ni, data->ni = NULL;
1980         vap = ni->ni_vap;
1981         ic = vap->iv_ic;
1982
1983         /*
1984          * Update rate control statistics for the node.
1985          */
1986         if (status & WPI_TX_STATUS_FAIL) {
1987                 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
1988                 ieee80211_ratectl_tx_complete(vap, ni,
1989                     IEEE80211_RATECTL_TX_FAILURE, &ackfailcnt, NULL);
1990         } else {
1991                 if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
1992                 ieee80211_ratectl_tx_complete(vap, ni,
1993                     IEEE80211_RATECTL_TX_SUCCESS, &ackfailcnt, NULL);
1994         }
1995
1996         ieee80211_tx_complete(ni, m, (status & WPI_TX_STATUS_FAIL) != 0);
1997
1998         WPI_TXQ_STATE_LOCK(sc);
1999         ring->queued -= 1;
2000         if (ring->queued > 0) {
2001                 callout_reset(&sc->tx_timeout, 5*hz, wpi_tx_timeout, sc);
2002
2003                 if (sc->qfullmsk != 0 &&
2004                     ring->queued < WPI_TX_RING_LOMARK) {
2005                         sc->qfullmsk &= ~(1 << ring->qid);
2006                         IF_LOCK(&ifp->if_snd);
2007                         if (sc->qfullmsk == 0 &&
2008                             (ifp->if_drv_flags & IFF_DRV_OACTIVE)) {
2009                                 ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2010                                 IF_UNLOCK(&ifp->if_snd);
2011                                 ieee80211_runtask(ic, &sc->sc_start_task);
2012                         } else
2013                                 IF_UNLOCK(&ifp->if_snd);
2014                 }
2015         } else
2016                 callout_stop(&sc->tx_timeout);
2017         WPI_TXQ_STATE_UNLOCK(sc);
2018
2019         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
2020 }
2021
2022 /*
2023  * Process a "command done" firmware notification.  This is where we wakeup
2024  * processes waiting for a synchronous command completion.
2025  */
2026 static void
2027 wpi_cmd_done(struct wpi_softc *sc, struct wpi_rx_desc *desc)
2028 {
2029         struct wpi_tx_ring *ring = &sc->txq[WPI_CMD_QUEUE_NUM];
2030         struct wpi_tx_data *data;
2031
2032         DPRINTF(sc, WPI_DEBUG_CMD, "cmd notification qid %x idx %d flags %x "
2033                                    "type %s len %d\n", desc->qid, desc->idx,
2034                                    desc->flags, wpi_cmd_str(desc->type),
2035                                    le32toh(desc->len));
2036
2037         if ((desc->qid & WPI_RX_DESC_QID_MSK) != WPI_CMD_QUEUE_NUM)
2038                 return; /* Not a command ack. */
2039
2040         KASSERT(ring->queued == 0, ("ring->queued must be 0"));
2041
2042         data = &ring->data[desc->idx];
2043
2044         /* If the command was mapped in an mbuf, free it. */
2045         if (data->m != NULL) {
2046                 bus_dmamap_sync(ring->data_dmat, data->map,
2047                     BUS_DMASYNC_POSTWRITE);
2048                 bus_dmamap_unload(ring->data_dmat, data->map);
2049                 m_freem(data->m);
2050                 data->m = NULL;
2051         }
2052
2053         wakeup(&ring->cmd[desc->idx]);
2054 }
2055
2056 static void
2057 wpi_notif_intr(struct wpi_softc *sc)
2058 {
2059         struct ifnet *ifp = sc->sc_ifp;
2060         struct ieee80211com *ic = ifp->if_l2com;
2061         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2062         uint32_t hw;
2063
2064         bus_dmamap_sync(sc->shared_dma.tag, sc->shared_dma.map,
2065             BUS_DMASYNC_POSTREAD);
2066
2067         hw = le32toh(sc->shared->next);
2068         hw = (hw == 0) ? WPI_RX_RING_COUNT - 1 : hw - 1;
2069
2070         while (sc->rxq.cur != hw) {
2071                 sc->rxq.cur = (sc->rxq.cur + 1) % WPI_RX_RING_COUNT;
2072
2073                 struct wpi_rx_data *data = &sc->rxq.data[sc->rxq.cur];
2074                 struct wpi_rx_desc *desc;
2075
2076                 bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2077                     BUS_DMASYNC_POSTREAD);
2078                 desc = mtod(data->m, struct wpi_rx_desc *);
2079
2080                 DPRINTF(sc, WPI_DEBUG_NOTIFY,
2081                     "%s: cur=%d; qid %x idx %d flags %x type %d(%s) len %d\n",
2082                     __func__, sc->rxq.cur, desc->qid, desc->idx, desc->flags,
2083                     desc->type, wpi_cmd_str(desc->type), le32toh(desc->len));
2084
2085                 if (!(desc->qid & WPI_UNSOLICITED_RX_NOTIF)) {
2086                         /* Reply to a command. */
2087                         wpi_cmd_done(sc, desc);
2088                 }
2089
2090                 switch (desc->type) {
2091                 case WPI_RX_DONE:
2092                         /* An 802.11 frame has been received. */
2093                         wpi_rx_done(sc, desc, data);
2094
2095                         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
2096                                 /* wpi_stop() was called. */
2097                                 return;
2098                         }
2099
2100                         break;
2101
2102                 case WPI_TX_DONE:
2103                         /* An 802.11 frame has been transmitted. */
2104                         wpi_tx_done(sc, desc);
2105                         break;
2106
2107                 case WPI_RX_STATISTICS:
2108                 case WPI_BEACON_STATISTICS:
2109                         wpi_rx_statistics(sc, desc, data);
2110                         break;
2111
2112                 case WPI_BEACON_MISSED:
2113                 {
2114                         struct wpi_beacon_missed *miss =
2115                             (struct wpi_beacon_missed *)(desc + 1);
2116                         uint32_t misses;
2117
2118                         bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2119                             BUS_DMASYNC_POSTREAD);
2120                         misses = le32toh(miss->consecutive);
2121
2122                         DPRINTF(sc, WPI_DEBUG_STATE,
2123                             "%s: beacons missed %d/%d\n", __func__, misses,
2124                             le32toh(miss->total));
2125
2126                         if (vap->iv_state == IEEE80211_S_RUN &&
2127                             (ic->ic_flags & IEEE80211_F_SCAN) == 0 &&
2128                             misses >= vap->iv_bmissthreshold)
2129                                 ieee80211_beacon_miss(ic);
2130
2131                         break;
2132                 }
2133                 case WPI_UC_READY:
2134                 {
2135                         struct wpi_ucode_info *uc =
2136                             (struct wpi_ucode_info *)(desc + 1);
2137
2138                         /* The microcontroller is ready. */
2139                         bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2140                             BUS_DMASYNC_POSTREAD);
2141                         DPRINTF(sc, WPI_DEBUG_RESET,
2142                             "microcode alive notification version=%d.%d "
2143                             "subtype=%x alive=%x\n", uc->major, uc->minor,
2144                             uc->subtype, le32toh(uc->valid));
2145
2146                         if (le32toh(uc->valid) != 1) {
2147                                 device_printf(sc->sc_dev,
2148                                     "microcontroller initialization failed\n");
2149                                 wpi_stop_locked(sc);
2150                         }
2151                         /* Save the address of the error log in SRAM. */
2152                         sc->errptr = le32toh(uc->errptr);
2153                         break;
2154                 }
2155                 case WPI_STATE_CHANGED:
2156                 {
2157                         bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2158                             BUS_DMASYNC_POSTREAD);
2159
2160                         uint32_t *status = (uint32_t *)(desc + 1);
2161
2162                         DPRINTF(sc, WPI_DEBUG_STATE, "state changed to %x\n",
2163                             le32toh(*status));
2164
2165                         if (le32toh(*status) & 1) {
2166                                 WPI_NT_LOCK(sc);
2167                                 wpi_clear_node_table(sc);
2168                                 WPI_NT_UNLOCK(sc);
2169                                 taskqueue_enqueue(sc->sc_tq,
2170                                     &sc->sc_radiooff_task);
2171                                 return;
2172                         }
2173                         break;
2174                 }
2175                 case WPI_START_SCAN:
2176                 {
2177                         bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2178                             BUS_DMASYNC_POSTREAD);
2179 #ifdef WPI_DEBUG
2180                         struct wpi_start_scan *scan =
2181                             (struct wpi_start_scan *)(desc + 1);
2182                         DPRINTF(sc, WPI_DEBUG_SCAN,
2183                             "%s: scanning channel %d status %x\n",
2184                             __func__, scan->chan, le32toh(scan->status));
2185 #endif
2186                         break;
2187                 }
2188                 case WPI_STOP_SCAN:
2189                 {
2190                         bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2191                             BUS_DMASYNC_POSTREAD);
2192 #ifdef WPI_DEBUG
2193                         struct wpi_stop_scan *scan =
2194                             (struct wpi_stop_scan *)(desc + 1);
2195                         DPRINTF(sc, WPI_DEBUG_SCAN,
2196                             "scan finished nchan=%d status=%d chan=%d\n",
2197                             scan->nchan, scan->status, scan->chan);
2198 #endif
2199                         WPI_RXON_LOCK(sc);
2200                         callout_stop(&sc->scan_timeout);
2201                         WPI_RXON_UNLOCK(sc);
2202                         ieee80211_scan_next(vap);
2203                         break;
2204                 }
2205                 }
2206
2207                 if (sc->rxq.cur % 8 == 0) {
2208                         /* Tell the firmware what we have processed. */
2209                         wpi_update_rx_ring(sc);
2210                 }
2211         }
2212 }
2213
2214 /*
2215  * Process an INT_WAKEUP interrupt raised when the microcontroller wakes up
2216  * from power-down sleep mode.
2217  */
2218 static void
2219 wpi_wakeup_intr(struct wpi_softc *sc)
2220 {
2221         int qid;
2222
2223         DPRINTF(sc, WPI_DEBUG_PWRSAVE,
2224             "%s: ucode wakeup from power-down sleep\n", __func__);
2225
2226         /* Wakeup RX and TX rings. */
2227         if (sc->rxq.update) {
2228                 sc->rxq.update = 0;
2229                 wpi_update_rx_ring(sc);
2230         }
2231         WPI_TXQ_LOCK(sc);
2232         for (qid = 0; qid < WPI_DRV_NTXQUEUES; qid++) {
2233                 struct wpi_tx_ring *ring = &sc->txq[qid];
2234
2235                 if (ring->update) {
2236                         ring->update = 0;
2237                         wpi_update_tx_ring(sc, ring);
2238                 }
2239         }
2240         WPI_TXQ_UNLOCK(sc);
2241
2242         WPI_CLRBITS(sc, WPI_GP_CNTRL, WPI_GP_CNTRL_MAC_ACCESS_REQ);
2243 }
2244
2245 /*
2246  * This function prints firmware registers
2247  */
2248 #ifdef WPI_DEBUG
2249 static void
2250 wpi_debug_registers(struct wpi_softc *sc)
2251 {
2252 #define COUNTOF(array) (sizeof(array) / sizeof(array[0]))
2253         int i;
2254         static const uint32_t csr_tbl[] = {
2255                 WPI_HW_IF_CONFIG,
2256                 WPI_INT,
2257                 WPI_INT_MASK,
2258                 WPI_FH_INT,
2259                 WPI_GPIO_IN,
2260                 WPI_RESET,
2261                 WPI_GP_CNTRL,
2262                 WPI_EEPROM,
2263                 WPI_EEPROM_GP,
2264                 WPI_GIO,
2265                 WPI_UCODE_GP1,
2266                 WPI_UCODE_GP2,
2267                 WPI_GIO_CHICKEN,
2268                 WPI_ANA_PLL,
2269                 WPI_DBG_HPET_MEM,
2270         };
2271         static const uint32_t prph_tbl[] = {
2272                 WPI_APMG_CLK_CTRL,
2273                 WPI_APMG_PS,
2274                 WPI_APMG_PCI_STT,
2275                 WPI_APMG_RFKILL,
2276         };
2277
2278         DPRINTF(sc, WPI_DEBUG_REGISTER,"%s","\n");
2279
2280         for (i = 0; i <  COUNTOF(csr_tbl); i++) {
2281                 DPRINTF(sc, WPI_DEBUG_REGISTER, "  %-18s: 0x%08x ",
2282                     wpi_get_csr_string(csr_tbl[i]), WPI_READ(sc, csr_tbl[i]));
2283
2284                 if ((i + 1) % 2 == 0)
2285                         DPRINTF(sc, WPI_DEBUG_REGISTER, "\n");
2286         }
2287         DPRINTF(sc, WPI_DEBUG_REGISTER, "\n\n");
2288
2289         if (wpi_nic_lock(sc) == 0) {
2290                 for (i = 0; i < COUNTOF(prph_tbl); i++) {
2291                         DPRINTF(sc, WPI_DEBUG_REGISTER, "  %-18s: 0x%08x ",
2292                             wpi_get_prph_string(prph_tbl[i]),
2293                             wpi_prph_read(sc, prph_tbl[i]));
2294
2295                         if ((i + 1) % 2 == 0)
2296                                 DPRINTF(sc, WPI_DEBUG_REGISTER, "\n");
2297                 }
2298                 DPRINTF(sc, WPI_DEBUG_REGISTER, "\n");
2299                 wpi_nic_unlock(sc);
2300         } else {
2301                 DPRINTF(sc, WPI_DEBUG_REGISTER,
2302                     "Cannot access internal registers.\n");
2303         }
2304 #undef COUNTOF
2305 }
2306 #endif
2307
2308 /*
2309  * Dump the error log of the firmware when a firmware panic occurs.  Although
2310  * we can't debug the firmware because it is neither open source nor free, it
2311  * can help us to identify certain classes of problems.
2312  */
2313 static void
2314 wpi_fatal_intr(struct wpi_softc *sc)
2315 {
2316         struct wpi_fw_dump dump;
2317         uint32_t i, offset, count;
2318         const uint32_t size_errmsg =
2319             (sizeof (wpi_fw_errmsg) / sizeof ((wpi_fw_errmsg)[0]));
2320
2321         /* Check that the error log address is valid. */
2322         if (sc->errptr < WPI_FW_DATA_BASE ||
2323             sc->errptr + sizeof (dump) >
2324             WPI_FW_DATA_BASE + WPI_FW_DATA_MAXSZ) {
2325                 printf("%s: bad firmware error log address 0x%08x\n", __func__,
2326                     sc->errptr);
2327                 return;
2328         }
2329         if (wpi_nic_lock(sc) != 0) {
2330                 printf("%s: could not read firmware error log\n", __func__);
2331                 return;
2332         }
2333         /* Read number of entries in the log. */
2334         count = wpi_mem_read(sc, sc->errptr);
2335         if (count == 0 || count * sizeof (dump) > WPI_FW_DATA_MAXSZ) {
2336                 printf("%s: invalid count field (count = %u)\n", __func__,
2337                     count);
2338                 wpi_nic_unlock(sc);
2339                 return;
2340         }
2341         /* Skip "count" field. */
2342         offset = sc->errptr + sizeof (uint32_t);
2343         printf("firmware error log (count = %u):\n", count);
2344         for (i = 0; i < count; i++) {
2345                 wpi_mem_read_region_4(sc, offset, (uint32_t *)&dump,
2346                     sizeof (dump) / sizeof (uint32_t));
2347
2348                 printf("  error type = \"%s\" (0x%08X)\n",
2349                     (dump.desc < size_errmsg) ?
2350                         wpi_fw_errmsg[dump.desc] : "UNKNOWN",
2351                     dump.desc);
2352                 printf("  error data      = 0x%08X\n",
2353                     dump.data);
2354                 printf("  branch link     = 0x%08X%08X\n",
2355                     dump.blink[0], dump.blink[1]);
2356                 printf("  interrupt link  = 0x%08X%08X\n",
2357                     dump.ilink[0], dump.ilink[1]);
2358                 printf("  time            = %u\n", dump.time);
2359
2360                 offset += sizeof (dump);
2361         }
2362         wpi_nic_unlock(sc);
2363         /* Dump driver status (TX and RX rings) while we're here. */
2364         printf("driver status:\n");
2365         WPI_TXQ_LOCK(sc);
2366         for (i = 0; i < WPI_DRV_NTXQUEUES; i++) {
2367                 struct wpi_tx_ring *ring = &sc->txq[i];
2368                 printf("  tx ring %2d: qid=%-2d cur=%-3d queued=%-3d\n",
2369                     i, ring->qid, ring->cur, ring->queued);
2370         }
2371         WPI_TXQ_UNLOCK(sc);
2372         printf("  rx ring: cur=%d\n", sc->rxq.cur);
2373 }
2374
2375 static void
2376 wpi_intr(void *arg)
2377 {
2378         struct wpi_softc *sc = arg;
2379         struct ifnet *ifp = sc->sc_ifp;
2380         uint32_t r1, r2;
2381
2382         WPI_LOCK(sc);
2383
2384         /* Disable interrupts. */
2385         WPI_WRITE(sc, WPI_INT_MASK, 0);
2386
2387         r1 = WPI_READ(sc, WPI_INT);
2388
2389         if (r1 == 0xffffffff || (r1 & 0xfffffff0) == 0xa5a5a5a0)
2390                 goto end;       /* Hardware gone! */
2391
2392         r2 = WPI_READ(sc, WPI_FH_INT);
2393
2394         DPRINTF(sc, WPI_DEBUG_INTR, "%s: reg1=0x%08x reg2=0x%08x\n", __func__,
2395             r1, r2);
2396
2397         if (r1 == 0 && r2 == 0)
2398                 goto done;      /* Interrupt not for us. */
2399
2400         /* Acknowledge interrupts. */
2401         WPI_WRITE(sc, WPI_INT, r1);
2402         WPI_WRITE(sc, WPI_FH_INT, r2);
2403
2404         if (r1 & (WPI_INT_SW_ERR | WPI_INT_HW_ERR)) {
2405                 device_printf(sc->sc_dev, "fatal firmware error\n");
2406 #ifdef WPI_DEBUG
2407                 wpi_debug_registers(sc);
2408 #endif
2409                 wpi_fatal_intr(sc);
2410                 DPRINTF(sc, WPI_DEBUG_HW,
2411                     "(%s)\n", (r1 & WPI_INT_SW_ERR) ? "(Software Error)" :
2412                     "(Hardware Error)");
2413                 taskqueue_enqueue(sc->sc_tq, &sc->sc_reinittask);
2414                 goto end;
2415         }
2416
2417         if ((r1 & (WPI_INT_FH_RX | WPI_INT_SW_RX)) ||
2418             (r2 & WPI_FH_INT_RX))
2419                 wpi_notif_intr(sc);
2420
2421         if (r1 & WPI_INT_ALIVE)
2422                 wakeup(sc);     /* Firmware is alive. */
2423
2424         if (r1 & WPI_INT_WAKEUP)
2425                 wpi_wakeup_intr(sc);
2426
2427 done:
2428         /* Re-enable interrupts. */
2429         if (ifp->if_flags & IFF_UP)
2430                 WPI_WRITE(sc, WPI_INT_MASK, WPI_INT_MASK_DEF);
2431
2432 end:    WPI_UNLOCK(sc);
2433 }
2434
2435 static int
2436 wpi_cmd2(struct wpi_softc *sc, struct wpi_buf *buf)
2437 {
2438         struct ifnet *ifp = sc->sc_ifp;
2439         struct ieee80211_frame *wh;
2440         struct wpi_tx_cmd *cmd;
2441         struct wpi_tx_data *data;
2442         struct wpi_tx_desc *desc;
2443         struct wpi_tx_ring *ring;
2444         struct mbuf *m1;
2445         bus_dma_segment_t *seg, segs[WPI_MAX_SCATTER];
2446         int error, i, hdrlen, nsegs, totlen, pad;
2447
2448         WPI_TXQ_LOCK(sc);
2449
2450         KASSERT(buf->size <= sizeof(buf->data), ("buffer overflow"));
2451
2452         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
2453
2454         if (sc->txq_active == 0) {
2455                 /* wpi_stop() was called */
2456                 error = ENETDOWN;
2457                 goto fail;
2458         }
2459
2460         wh = mtod(buf->m, struct ieee80211_frame *);
2461         hdrlen = ieee80211_anyhdrsize(wh);
2462         totlen = buf->m->m_pkthdr.len;
2463
2464         if (hdrlen & 3) {
2465                 /* First segment length must be a multiple of 4. */
2466                 pad = 4 - (hdrlen & 3);
2467         } else
2468                 pad = 0;
2469
2470         ring = &sc->txq[buf->ac];
2471         desc = &ring->desc[ring->cur];
2472         data = &ring->data[ring->cur];
2473
2474         /* Prepare TX firmware command. */
2475         cmd = &ring->cmd[ring->cur];
2476         cmd->code = buf->code;
2477         cmd->flags = 0;
2478         cmd->qid = ring->qid;
2479         cmd->idx = ring->cur;
2480
2481         memcpy(cmd->data, buf->data, buf->size);
2482
2483         /* Save and trim IEEE802.11 header. */
2484         memcpy((uint8_t *)(cmd->data + buf->size), wh, hdrlen);
2485         m_adj(buf->m, hdrlen);
2486
2487         error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, buf->m,
2488             segs, &nsegs, BUS_DMA_NOWAIT);
2489         if (error != 0 && error != EFBIG) {
2490                 device_printf(sc->sc_dev,
2491                     "%s: can't map mbuf (error %d)\n", __func__, error);
2492                 goto fail;
2493         }
2494         if (error != 0) {
2495                 /* Too many DMA segments, linearize mbuf. */
2496                 m1 = m_collapse(buf->m, M_NOWAIT, WPI_MAX_SCATTER - 1);
2497                 if (m1 == NULL) {
2498                         device_printf(sc->sc_dev,
2499                             "%s: could not defrag mbuf\n", __func__);
2500                         error = ENOBUFS;
2501                         goto fail;
2502                 }
2503                 buf->m = m1;
2504
2505                 error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map,
2506                     buf->m, segs, &nsegs, BUS_DMA_NOWAIT);
2507                 if (error != 0) {
2508                         device_printf(sc->sc_dev,
2509                             "%s: can't map mbuf (error %d)\n", __func__,
2510                             error);
2511                         goto fail;
2512                 }
2513         }
2514
2515         KASSERT(nsegs < WPI_MAX_SCATTER,
2516             ("too many DMA segments, nsegs (%d) should be less than %d",
2517              nsegs, WPI_MAX_SCATTER));
2518
2519         data->m = buf->m;
2520         data->ni = buf->ni;
2521
2522         DPRINTF(sc, WPI_DEBUG_XMIT, "%s: qid %d idx %d len %d nsegs %d\n",
2523             __func__, ring->qid, ring->cur, totlen, nsegs);
2524
2525         /* Fill TX descriptor. */
2526         desc->nsegs = WPI_PAD32(totlen + pad) << 4 | (1 + nsegs);
2527         /* First DMA segment is used by the TX command. */
2528         desc->segs[0].addr = htole32(data->cmd_paddr);
2529         desc->segs[0].len  = htole32(4 + buf->size + hdrlen + pad);
2530         /* Other DMA segments are for data payload. */
2531         seg = &segs[0];
2532         for (i = 1; i <= nsegs; i++) {
2533                 desc->segs[i].addr = htole32(seg->ds_addr);
2534                 desc->segs[i].len  = htole32(seg->ds_len);
2535                 seg++;
2536         }
2537
2538         bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
2539         bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
2540             BUS_DMASYNC_PREWRITE);
2541         bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
2542             BUS_DMASYNC_PREWRITE);
2543
2544         /* Kick TX ring. */
2545         ring->cur = (ring->cur + 1) % WPI_TX_RING_COUNT;
2546         wpi_update_tx_ring(sc, ring);
2547
2548         if (ring->qid < WPI_CMD_QUEUE_NUM) {
2549                 /* Mark TX ring as full if we reach a certain threshold. */
2550                 WPI_TXQ_STATE_LOCK(sc);
2551                 if (++ring->queued > WPI_TX_RING_HIMARK) {
2552                         sc->qfullmsk |= 1 << ring->qid;
2553
2554                         IF_LOCK(&ifp->if_snd);
2555                         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2556                         IF_UNLOCK(&ifp->if_snd);
2557                 }
2558
2559                 callout_reset(&sc->tx_timeout, 5*hz, wpi_tx_timeout, sc);
2560                 WPI_TXQ_STATE_UNLOCK(sc);
2561         }
2562
2563         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
2564
2565         WPI_TXQ_UNLOCK(sc);
2566
2567         return 0;
2568
2569 fail:   m_freem(buf->m);
2570
2571         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
2572
2573         WPI_TXQ_UNLOCK(sc);
2574
2575         return error;
2576 }
2577
2578 /*
2579  * Construct the data packet for a transmit buffer.
2580  */
2581 static int
2582 wpi_tx_data(struct wpi_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
2583 {
2584         const struct ieee80211_txparam *tp;
2585         struct ieee80211vap *vap = ni->ni_vap;
2586         struct ieee80211com *ic = ni->ni_ic;
2587         struct wpi_node *wn = WPI_NODE(ni);
2588         struct ieee80211_channel *chan;
2589         struct ieee80211_frame *wh;
2590         struct ieee80211_key *k = NULL;
2591         struct wpi_buf tx_data;
2592         struct wpi_cmd_data *tx = (struct wpi_cmd_data *)&tx_data.data;
2593         uint32_t flags;
2594         uint16_t qos;
2595         uint8_t tid, type;
2596         int ac, error, swcrypt, rate, ismcast, totlen;
2597
2598         wh = mtod(m, struct ieee80211_frame *);
2599         type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
2600         ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
2601
2602         /* Select EDCA Access Category and TX ring for this frame. */
2603         if (IEEE80211_QOS_HAS_SEQ(wh)) {
2604                 qos = ((const struct ieee80211_qosframe *)wh)->i_qos[0];
2605                 tid = qos & IEEE80211_QOS_TID;
2606         } else {
2607                 qos = 0;
2608                 tid = 0;
2609         }
2610         ac = M_WME_GETAC(m);
2611
2612         chan = (ni->ni_chan != IEEE80211_CHAN_ANYC) ?
2613                 ni->ni_chan : ic->ic_curchan;
2614         tp = &vap->iv_txparms[ieee80211_chan2mode(chan)];
2615
2616         /* Choose a TX rate index. */
2617         if (type == IEEE80211_FC0_TYPE_MGT)
2618                 rate = tp->mgmtrate;
2619         else if (ismcast)
2620                 rate = tp->mcastrate;
2621         else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
2622                 rate = tp->ucastrate;
2623         else if (m->m_flags & M_EAPOL)
2624                 rate = tp->mgmtrate;
2625         else {
2626                 /* XXX pass pktlen */
2627                 (void) ieee80211_ratectl_rate(ni, NULL, 0);
2628                 rate = ni->ni_txrate;
2629         }
2630
2631         /* Encrypt the frame if need be. */
2632         if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
2633                 /* Retrieve key for TX. */
2634                 k = ieee80211_crypto_encap(ni, m);
2635                 if (k == NULL) {
2636                         error = ENOBUFS;
2637                         goto fail;
2638                 }
2639                 swcrypt = k->wk_flags & IEEE80211_KEY_SWCRYPT;
2640
2641                 /* 802.11 header may have moved. */
2642                 wh = mtod(m, struct ieee80211_frame *);
2643         }
2644         totlen = m->m_pkthdr.len;
2645
2646         if (ieee80211_radiotap_active_vap(vap)) {
2647                 struct wpi_tx_radiotap_header *tap = &sc->sc_txtap;
2648
2649                 tap->wt_flags = 0;
2650                 tap->wt_rate = rate;
2651                 if (k != NULL)
2652                         tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
2653
2654                 ieee80211_radiotap_tx(vap, m);
2655         }
2656
2657         flags = 0;
2658         if (!ismcast) {
2659                 /* Unicast frame, check if an ACK is expected. */
2660                 if (!qos || (qos & IEEE80211_QOS_ACKPOLICY) !=
2661                     IEEE80211_QOS_ACKPOLICY_NOACK)
2662                         flags |= WPI_TX_NEED_ACK;
2663         }
2664
2665         if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG)
2666                 flags |= WPI_TX_MORE_FRAG;      /* Cannot happen yet. */
2667
2668         /* Check if frame must be protected using RTS/CTS or CTS-to-self. */
2669         if (!ismcast) {
2670                 /* NB: Group frames are sent using CCK in 802.11b/g. */
2671                 if (totlen + IEEE80211_CRC_LEN > vap->iv_rtsthreshold) {
2672                         flags |= WPI_TX_NEED_RTS;
2673                 } else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
2674                     WPI_RATE_IS_OFDM(rate)) {
2675                         if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
2676                                 flags |= WPI_TX_NEED_CTS;
2677                         else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
2678                                 flags |= WPI_TX_NEED_RTS;
2679                 }
2680
2681                 if (flags & (WPI_TX_NEED_RTS | WPI_TX_NEED_CTS))
2682                         flags |= WPI_TX_FULL_TXOP;
2683         }
2684
2685         memset(tx, 0, sizeof (struct wpi_cmd_data));
2686         if (type == IEEE80211_FC0_TYPE_MGT) {
2687                 uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
2688
2689                 /* Tell HW to set timestamp in probe responses. */
2690                 if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
2691                         flags |= WPI_TX_INSERT_TSTAMP;
2692                 if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
2693                     subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
2694                         tx->timeout = htole16(3);
2695                 else
2696                         tx->timeout = htole16(2);
2697         }
2698
2699         if (ismcast || type != IEEE80211_FC0_TYPE_DATA)
2700                 tx->id = WPI_ID_BROADCAST;
2701         else {
2702                 if (wn->id == WPI_ID_UNDEFINED) {
2703                         device_printf(sc->sc_dev,
2704                             "%s: undefined node id\n", __func__);
2705                         error = EINVAL;
2706                         goto fail;
2707                 }
2708
2709                 tx->id = wn->id;
2710         }
2711
2712         if (k != NULL && !swcrypt) {
2713                 switch (k->wk_cipher->ic_cipher) {
2714                 case IEEE80211_CIPHER_AES_CCM:
2715                         tx->security = WPI_CIPHER_CCMP;
2716                         break;
2717
2718                 default:
2719                         break;
2720                 }
2721
2722                 memcpy(tx->key, k->wk_key, k->wk_keylen);
2723         }
2724
2725         tx->len = htole16(totlen);
2726         tx->flags = htole32(flags);
2727         tx->plcp = rate2plcp(rate);
2728         tx->tid = tid;
2729         tx->lifetime = htole32(WPI_LIFETIME_INFINITE);
2730         tx->ofdm_mask = 0xff;
2731         tx->cck_mask = 0x0f;
2732         tx->rts_ntries = 7;
2733         tx->data_ntries = tp->maxretry;
2734
2735         tx_data.ni = ni;
2736         tx_data.m = m;
2737         tx_data.size = sizeof(struct wpi_cmd_data);
2738         tx_data.code = WPI_CMD_TX_DATA;
2739         tx_data.ac = ac;
2740
2741         return wpi_cmd2(sc, &tx_data);
2742
2743 fail:   m_freem(m);
2744         return error;
2745 }
2746
2747 static int
2748 wpi_tx_data_raw(struct wpi_softc *sc, struct mbuf *m,
2749     struct ieee80211_node *ni, const struct ieee80211_bpf_params *params)
2750 {
2751         struct ieee80211vap *vap = ni->ni_vap;
2752         struct ieee80211_key *k = NULL;
2753         struct ieee80211_frame *wh;
2754         struct wpi_buf tx_data;
2755         struct wpi_cmd_data *tx = (struct wpi_cmd_data *)&tx_data.data;
2756         uint32_t flags;
2757         uint8_t type;
2758         int ac, rate, swcrypt, totlen;
2759
2760         wh = mtod(m, struct ieee80211_frame *);
2761         type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
2762
2763         ac = params->ibp_pri & 3;
2764
2765         /* Choose a TX rate index. */
2766         rate = params->ibp_rate0;
2767
2768         flags = 0;
2769         if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0)
2770                 flags |= WPI_TX_NEED_ACK;
2771         if (params->ibp_flags & IEEE80211_BPF_RTS)
2772                 flags |= WPI_TX_NEED_RTS;
2773         if (params->ibp_flags & IEEE80211_BPF_CTS)
2774                 flags |= WPI_TX_NEED_CTS;
2775         if (flags & (WPI_TX_NEED_RTS | WPI_TX_NEED_CTS))
2776                 flags |= WPI_TX_FULL_TXOP;
2777
2778         /* Encrypt the frame if need be. */
2779         if (params->ibp_flags & IEEE80211_BPF_CRYPTO) {
2780                 /* Retrieve key for TX. */
2781                 k = ieee80211_crypto_encap(ni, m);
2782                 if (k == NULL) {
2783                         m_freem(m);
2784                         return ENOBUFS;
2785                 }
2786                 swcrypt = k->wk_flags & IEEE80211_KEY_SWCRYPT;
2787
2788                 /* 802.11 header may have moved. */
2789                 wh = mtod(m, struct ieee80211_frame *);
2790         }
2791         totlen = m->m_pkthdr.len;
2792
2793         if (ieee80211_radiotap_active_vap(vap)) {
2794                 struct wpi_tx_radiotap_header *tap = &sc->sc_txtap;
2795
2796                 tap->wt_flags = 0;
2797                 tap->wt_rate = rate;
2798                 if (params->ibp_flags & IEEE80211_BPF_CRYPTO)
2799                         tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
2800
2801                 ieee80211_radiotap_tx(vap, m);
2802         }
2803
2804         memset(tx, 0, sizeof (struct wpi_cmd_data));
2805         if (type == IEEE80211_FC0_TYPE_MGT) {
2806                 uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
2807
2808                 /* Tell HW to set timestamp in probe responses. */
2809                 if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
2810                         flags |= WPI_TX_INSERT_TSTAMP;
2811                 if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
2812                     subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
2813                         tx->timeout = htole16(3);
2814                 else
2815                         tx->timeout = htole16(2);
2816         }
2817
2818         if (k != NULL && !swcrypt) {
2819                 switch (k->wk_cipher->ic_cipher) {
2820                 case IEEE80211_CIPHER_AES_CCM:
2821                         tx->security = WPI_CIPHER_CCMP;
2822                         break;
2823
2824                 default:
2825                         break;
2826                 }
2827
2828                 memcpy(tx->key, k->wk_key, k->wk_keylen);
2829         }
2830
2831         tx->len = htole16(totlen);
2832         tx->flags = htole32(flags);
2833         tx->plcp = rate2plcp(rate);
2834         tx->id = WPI_ID_BROADCAST;
2835         tx->lifetime = htole32(WPI_LIFETIME_INFINITE);
2836         tx->rts_ntries = params->ibp_try1;
2837         tx->data_ntries = params->ibp_try0;
2838
2839         tx_data.ni = ni;
2840         tx_data.m = m;
2841         tx_data.size = sizeof(struct wpi_cmd_data);
2842         tx_data.code = WPI_CMD_TX_DATA;
2843         tx_data.ac = ac;
2844
2845         return wpi_cmd2(sc, &tx_data);
2846 }
2847
2848 static int
2849 wpi_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
2850     const struct ieee80211_bpf_params *params)
2851 {
2852         struct ieee80211com *ic = ni->ni_ic;
2853         struct ifnet *ifp = ic->ic_ifp;
2854         struct wpi_softc *sc = ifp->if_softc;
2855         int error = 0;
2856
2857         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
2858
2859         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
2860                 ieee80211_free_node(ni);
2861                 m_freem(m);
2862                 return ENETDOWN;
2863         }
2864
2865         WPI_TX_LOCK(sc);
2866         if (params == NULL) {
2867                 /*
2868                  * Legacy path; interpret frame contents to decide
2869                  * precisely how to send the frame.
2870                  */
2871                 error = wpi_tx_data(sc, m, ni);
2872         } else {
2873                 /*
2874                  * Caller supplied explicit parameters to use in
2875                  * sending the frame.
2876                  */
2877                 error = wpi_tx_data_raw(sc, m, ni, params);
2878         }
2879         WPI_TX_UNLOCK(sc);
2880
2881         if (error != 0) {
2882                 /* NB: m is reclaimed on tx failure */
2883                 ieee80211_free_node(ni);
2884                 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
2885
2886                 DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
2887
2888                 return error;
2889         }
2890
2891         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
2892
2893         return 0;
2894 }
2895
2896 /**
2897  * Process data waiting to be sent on the IFNET output queue
2898  */
2899 static void
2900 wpi_start(struct ifnet *ifp)
2901 {
2902         struct wpi_softc *sc = ifp->if_softc;
2903         struct ieee80211_node *ni;
2904         struct mbuf *m;
2905
2906         WPI_TX_LOCK(sc);
2907         DPRINTF(sc, WPI_DEBUG_XMIT, "%s: called\n", __func__);
2908
2909         for (;;) {
2910                 IF_LOCK(&ifp->if_snd);
2911                 if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
2912                     (ifp->if_drv_flags & IFF_DRV_OACTIVE)) {
2913                         IF_UNLOCK(&ifp->if_snd);
2914                         break;
2915                 }
2916                 IF_UNLOCK(&ifp->if_snd);
2917
2918                 IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
2919                 if (m == NULL)
2920                         break;
2921                 ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
2922                 if (wpi_tx_data(sc, m, ni) != 0) {
2923                         ieee80211_free_node(ni);
2924                         if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
2925                 }
2926         }
2927
2928         DPRINTF(sc, WPI_DEBUG_XMIT, "%s: done\n", __func__);
2929         WPI_TX_UNLOCK(sc);
2930 }
2931
2932 static void
2933 wpi_start_task(void *arg0, int pending)
2934 {
2935         struct wpi_softc *sc = arg0;
2936         struct ifnet *ifp = sc->sc_ifp;
2937
2938         wpi_start(ifp);
2939 }
2940
2941 static void
2942 wpi_watchdog_rfkill(void *arg)
2943 {
2944         struct wpi_softc *sc = arg;
2945         struct ifnet *ifp = sc->sc_ifp;
2946         struct ieee80211com *ic = ifp->if_l2com;
2947
2948         DPRINTF(sc, WPI_DEBUG_WATCHDOG, "RFkill Watchdog: tick\n");
2949
2950         /* No need to lock firmware memory. */
2951         if ((wpi_prph_read(sc, WPI_APMG_RFKILL) & 0x1) == 0) {
2952                 /* Radio kill switch is still off. */
2953                 callout_reset(&sc->watchdog_rfkill, hz, wpi_watchdog_rfkill,
2954                     sc);
2955         } else
2956                 ieee80211_runtask(ic, &sc->sc_radioon_task);
2957 }
2958
2959 static void
2960 wpi_scan_timeout(void *arg)
2961 {
2962         struct wpi_softc *sc = arg;
2963         struct ifnet *ifp = sc->sc_ifp;
2964
2965         if_printf(ifp, "scan timeout\n");
2966         taskqueue_enqueue(sc->sc_tq, &sc->sc_reinittask);
2967 }
2968
2969 static void
2970 wpi_tx_timeout(void *arg)
2971 {
2972         struct wpi_softc *sc = arg;
2973         struct ifnet *ifp = sc->sc_ifp;
2974
2975         if_printf(ifp, "device timeout\n");
2976         if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
2977         taskqueue_enqueue(sc->sc_tq, &sc->sc_reinittask);
2978 }
2979
2980 static int
2981 wpi_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
2982 {
2983         struct wpi_softc *sc = ifp->if_softc;
2984         struct ieee80211com *ic = ifp->if_l2com;
2985         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2986         struct ifreq *ifr = (struct ifreq *) data;
2987         int error = 0;
2988
2989         switch (cmd) {
2990         case SIOCGIFADDR:
2991                 error = ether_ioctl(ifp, cmd, data);
2992                 break;
2993         case SIOCSIFFLAGS:
2994                 if (ifp->if_flags & IFF_UP) {
2995                         wpi_init(sc);
2996
2997                         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 &&
2998                             vap != NULL)
2999                                 ieee80211_stop(vap);
3000                 } else if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0)
3001                         wpi_stop(sc);
3002                 break;
3003         case SIOCGIFMEDIA:
3004                 error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
3005                 break;
3006         default:
3007                 error = EINVAL;
3008                 break;
3009         }
3010         return error;
3011 }
3012
3013 /*
3014  * Send a command to the firmware.
3015  */
3016 static int
3017 wpi_cmd(struct wpi_softc *sc, int code, const void *buf, size_t size,
3018     int async)
3019 {
3020         struct wpi_tx_ring *ring = &sc->txq[WPI_CMD_QUEUE_NUM];
3021         struct wpi_tx_desc *desc;
3022         struct wpi_tx_data *data;
3023         struct wpi_tx_cmd *cmd;
3024         struct mbuf *m;
3025         bus_addr_t paddr;
3026         int totlen, error;
3027
3028         WPI_TXQ_LOCK(sc);
3029
3030         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
3031
3032         if (sc->txq_active == 0) {
3033                 /* wpi_stop() was called */
3034                 error = 0;
3035                 goto fail;
3036         }
3037
3038         if (async == 0)
3039                 WPI_LOCK_ASSERT(sc);
3040
3041         DPRINTF(sc, WPI_DEBUG_CMD, "%s: cmd %s size %zu async %d\n",
3042             __func__, wpi_cmd_str(code), size, async);
3043
3044         desc = &ring->desc[ring->cur];
3045         data = &ring->data[ring->cur];
3046         totlen = 4 + size;
3047
3048         if (size > sizeof cmd->data) {
3049                 /* Command is too large to fit in a descriptor. */
3050                 if (totlen > MCLBYTES) {
3051                         error = EINVAL;
3052                         goto fail;
3053                 }
3054                 m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE);
3055                 if (m == NULL) {
3056                         error = ENOMEM;
3057                         goto fail;
3058                 }
3059                 cmd = mtod(m, struct wpi_tx_cmd *);
3060                 error = bus_dmamap_load(ring->data_dmat, data->map, cmd,
3061                     totlen, wpi_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
3062                 if (error != 0) {
3063                         m_freem(m);
3064                         goto fail;
3065                 }
3066                 data->m = m;
3067         } else {
3068                 cmd = &ring->cmd[ring->cur];
3069                 paddr = data->cmd_paddr;
3070         }
3071
3072         cmd->code = code;
3073         cmd->flags = 0;
3074         cmd->qid = ring->qid;
3075         cmd->idx = ring->cur;
3076         memcpy(cmd->data, buf, size);
3077
3078         desc->nsegs = 1 + (WPI_PAD32(size) << 4);
3079         desc->segs[0].addr = htole32(paddr);
3080         desc->segs[0].len  = htole32(totlen);
3081
3082         if (size > sizeof cmd->data) {
3083                 bus_dmamap_sync(ring->data_dmat, data->map,
3084                     BUS_DMASYNC_PREWRITE);
3085         } else {
3086                 bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
3087                     BUS_DMASYNC_PREWRITE);
3088         }
3089         bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
3090             BUS_DMASYNC_PREWRITE);
3091
3092         /* Kick command ring. */
3093         ring->cur = (ring->cur + 1) % WPI_TX_RING_COUNT;
3094         wpi_update_tx_ring(sc, ring);
3095
3096         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
3097
3098         WPI_TXQ_UNLOCK(sc);
3099
3100         if (async)
3101                 return 0;
3102
3103         return mtx_sleep(cmd, &sc->sc_mtx, PCATCH, "wpicmd", hz);
3104
3105 fail:   DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
3106
3107         WPI_TXQ_UNLOCK(sc);
3108
3109         return error;
3110 }
3111
3112 /*
3113  * Configure HW multi-rate retries.
3114  */
3115 static int
3116 wpi_mrr_setup(struct wpi_softc *sc)
3117 {
3118         struct ifnet *ifp = sc->sc_ifp;
3119         struct ieee80211com *ic = ifp->if_l2com;
3120         struct wpi_mrr_setup mrr;
3121         int i, error;
3122
3123         /* CCK rates (not used with 802.11a). */
3124         for (i = WPI_RIDX_CCK1; i <= WPI_RIDX_CCK11; i++) {
3125                 mrr.rates[i].flags = 0;
3126                 mrr.rates[i].plcp = wpi_ridx_to_plcp[i];
3127                 /* Fallback to the immediate lower CCK rate (if any.) */
3128                 mrr.rates[i].next =
3129                     (i == WPI_RIDX_CCK1) ? WPI_RIDX_CCK1 : i - 1;
3130                 /* Try twice at this rate before falling back to "next". */
3131                 mrr.rates[i].ntries = WPI_NTRIES_DEFAULT;
3132         }
3133         /* OFDM rates (not used with 802.11b). */
3134         for (i = WPI_RIDX_OFDM6; i <= WPI_RIDX_OFDM54; i++) {
3135                 mrr.rates[i].flags = 0;
3136                 mrr.rates[i].plcp = wpi_ridx_to_plcp[i];
3137                 /* Fallback to the immediate lower rate (if any.) */
3138                 /* We allow fallback from OFDM/6 to CCK/2 in 11b/g mode. */
3139                 mrr.rates[i].next = (i == WPI_RIDX_OFDM6) ?
3140                     ((ic->ic_curmode == IEEE80211_MODE_11A) ?
3141                         WPI_RIDX_OFDM6 : WPI_RIDX_CCK2) :
3142                     i - 1;
3143                 /* Try twice at this rate before falling back to "next". */
3144                 mrr.rates[i].ntries = WPI_NTRIES_DEFAULT;
3145         }
3146         /* Setup MRR for control frames. */
3147         mrr.which = htole32(WPI_MRR_CTL);
3148         error = wpi_cmd(sc, WPI_CMD_MRR_SETUP, &mrr, sizeof mrr, 0);
3149         if (error != 0) {
3150                 device_printf(sc->sc_dev,
3151                     "could not setup MRR for control frames\n");
3152                 return error;
3153         }
3154         /* Setup MRR for data frames. */
3155         mrr.which = htole32(WPI_MRR_DATA);
3156         error = wpi_cmd(sc, WPI_CMD_MRR_SETUP, &mrr, sizeof mrr, 0);
3157         if (error != 0) {
3158                 device_printf(sc->sc_dev,
3159                     "could not setup MRR for data frames\n");
3160                 return error;
3161         }
3162         return 0;
3163 }
3164
3165 static int
3166 wpi_add_node(struct wpi_softc *sc, struct ieee80211_node *ni)
3167 {
3168         struct ieee80211com *ic = ni->ni_ic;
3169         struct wpi_vap *wvp = WPI_VAP(ni->ni_vap);
3170         struct wpi_node *wn = WPI_NODE(ni);
3171         struct wpi_node_info node;
3172         int error;
3173
3174         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3175
3176         if (wn->id == WPI_ID_UNDEFINED)
3177                 return EINVAL;
3178
3179         memset(&node, 0, sizeof node);
3180         IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr);
3181         node.id = wn->id;
3182         node.plcp = (ic->ic_curmode == IEEE80211_MODE_11A) ?
3183             wpi_ridx_to_plcp[WPI_RIDX_OFDM6] : wpi_ridx_to_plcp[WPI_RIDX_CCK1];
3184         node.action = htole32(WPI_ACTION_SET_RATE);
3185         node.antenna = WPI_ANTENNA_BOTH;
3186
3187         DPRINTF(sc, WPI_DEBUG_NODE, "%s: adding node %d (%s)\n", __func__,
3188             wn->id, ether_sprintf(ni->ni_macaddr));
3189
3190         error = wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, 1);
3191         if (error != 0) {
3192                 device_printf(sc->sc_dev,
3193                     "%s: wpi_cmd() call failed with error code %d\n", __func__,
3194                     error);
3195                 return error;
3196         }
3197
3198         if (wvp->wv_gtk != 0) {
3199                 error = wpi_set_global_keys(ni);
3200                 if (error != 0) {
3201                         device_printf(sc->sc_dev,
3202                             "%s: error while setting global keys\n", __func__);
3203                         return ENXIO;
3204                 }
3205         }
3206
3207         return 0;
3208 }
3209
3210 /*
3211  * Broadcast node is used to send group-addressed and management frames.
3212  */
3213 static int
3214 wpi_add_broadcast_node(struct wpi_softc *sc, int async)
3215 {
3216         struct ifnet *ifp = sc->sc_ifp;
3217         struct ieee80211com *ic = ifp->if_l2com;
3218         struct wpi_node_info node;
3219
3220         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3221
3222         memset(&node, 0, sizeof node);
3223         IEEE80211_ADDR_COPY(node.macaddr, ifp->if_broadcastaddr);
3224         node.id = WPI_ID_BROADCAST;
3225         node.plcp = (ic->ic_curmode == IEEE80211_MODE_11A) ?
3226             wpi_ridx_to_plcp[WPI_RIDX_OFDM6] : wpi_ridx_to_plcp[WPI_RIDX_CCK1];
3227         node.action = htole32(WPI_ACTION_SET_RATE);
3228         node.antenna = WPI_ANTENNA_BOTH;
3229
3230         DPRINTF(sc, WPI_DEBUG_NODE, "%s: adding broadcast node\n", __func__);
3231
3232         return wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, async);
3233 }
3234
3235 static int
3236 wpi_add_sta_node(struct wpi_softc *sc, struct ieee80211_node *ni)
3237 {
3238         struct wpi_node *wn = WPI_NODE(ni);
3239         int error;
3240
3241         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3242
3243         wn->id = wpi_add_node_entry_sta(sc);
3244
3245         if ((error = wpi_add_node(sc, ni)) != 0) {
3246                 wpi_del_node_entry(sc, wn->id);
3247                 wn->id = WPI_ID_UNDEFINED;
3248                 return error;
3249         }
3250
3251         return 0;
3252 }
3253
3254 static int
3255 wpi_add_ibss_node(struct wpi_softc *sc, struct ieee80211_node *ni)
3256 {
3257         struct wpi_node *wn = WPI_NODE(ni);
3258         int error;
3259
3260         KASSERT(wn->id == WPI_ID_UNDEFINED,
3261             ("the node %d was added before", wn->id));
3262
3263         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3264
3265         if ((wn->id = wpi_add_node_entry_adhoc(sc)) == WPI_ID_UNDEFINED) {
3266                 device_printf(sc->sc_dev, "%s: h/w table is full\n", __func__);
3267                 return ENOMEM;
3268         }
3269
3270         if ((error = wpi_add_node(sc, ni)) != 0) {
3271                 wpi_del_node_entry(sc, wn->id);
3272                 wn->id = WPI_ID_UNDEFINED;
3273                 return error;
3274         }
3275
3276         return 0;
3277 }
3278
3279 static void
3280 wpi_del_node(struct wpi_softc *sc, struct ieee80211_node *ni)
3281 {
3282         struct wpi_node *wn = WPI_NODE(ni);
3283         struct wpi_cmd_del_node node;
3284         int error;
3285
3286         KASSERT(wn->id != WPI_ID_UNDEFINED, ("undefined node id passed"));
3287
3288         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3289
3290         memset(&node, 0, sizeof node);
3291         IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr);
3292         node.count = 1;
3293
3294         DPRINTF(sc, WPI_DEBUG_NODE, "%s: deleting node %d (%s)\n", __func__,
3295             wn->id, ether_sprintf(ni->ni_macaddr));
3296
3297         error = wpi_cmd(sc, WPI_CMD_DEL_NODE, &node, sizeof node, 1);
3298         if (error != 0) {
3299                 device_printf(sc->sc_dev,
3300                     "%s: could not delete node %u, error %d\n", __func__,
3301                     wn->id, error);
3302         }
3303 }
3304
3305 static int
3306 wpi_updateedca(struct ieee80211com *ic)
3307 {
3308 #define WPI_EXP2(x)     ((1 << (x)) - 1)        /* CWmin = 2^ECWmin - 1 */
3309         struct wpi_softc *sc = ic->ic_ifp->if_softc;
3310         struct wpi_edca_params cmd;
3311         int aci, error;
3312
3313         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
3314
3315         memset(&cmd, 0, sizeof cmd);
3316         cmd.flags = htole32(WPI_EDCA_UPDATE);
3317         for (aci = 0; aci < WME_NUM_AC; aci++) {
3318                 const struct wmeParams *ac =
3319                     &ic->ic_wme.wme_chanParams.cap_wmeParams[aci];
3320                 cmd.ac[aci].aifsn = ac->wmep_aifsn;
3321                 cmd.ac[aci].cwmin = htole16(WPI_EXP2(ac->wmep_logcwmin));
3322                 cmd.ac[aci].cwmax = htole16(WPI_EXP2(ac->wmep_logcwmax));
3323                 cmd.ac[aci].txoplimit = 
3324                     htole16(IEEE80211_TXOP_TO_US(ac->wmep_txopLimit));
3325
3326                 DPRINTF(sc, WPI_DEBUG_EDCA,
3327                     "setting WME for queue %d aifsn=%d cwmin=%d cwmax=%d "
3328                     "txoplimit=%d\n", aci, cmd.ac[aci].aifsn,
3329                     cmd.ac[aci].cwmin, cmd.ac[aci].cwmax,
3330                     cmd.ac[aci].txoplimit);
3331         }
3332         error = wpi_cmd(sc, WPI_CMD_EDCA_PARAMS, &cmd, sizeof cmd, 1);
3333
3334         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
3335
3336         return error;
3337 #undef WPI_EXP2
3338 }
3339
3340 static void
3341 wpi_set_promisc(struct wpi_softc *sc)
3342 {
3343         struct ifnet *ifp = sc->sc_ifp;
3344         struct ieee80211com *ic = ifp->if_l2com;
3345         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3346         uint32_t promisc_filter;
3347
3348         promisc_filter = WPI_FILTER_CTL;
3349         if (vap != NULL && vap->iv_opmode != IEEE80211_M_HOSTAP)
3350                 promisc_filter |= WPI_FILTER_PROMISC;
3351
3352         if (ifp->if_flags & IFF_PROMISC)
3353                 sc->rxon.filter |= htole32(promisc_filter);
3354         else
3355                 sc->rxon.filter &= ~htole32(promisc_filter);
3356 }
3357
3358 static void
3359 wpi_update_promisc(struct ifnet *ifp)
3360 {
3361         struct wpi_softc *sc = ifp->if_softc;
3362
3363         WPI_RXON_LOCK(sc);
3364         wpi_set_promisc(sc);
3365
3366         if (wpi_send_rxon(sc, 1, 1) != 0) {
3367                 device_printf(sc->sc_dev, "%s: could not send RXON\n",
3368                     __func__);
3369         }
3370         WPI_RXON_UNLOCK(sc);
3371 }
3372
3373 static void
3374 wpi_update_mcast(struct ifnet *ifp)
3375 {
3376         /* Ignore */
3377 }
3378
3379 static void
3380 wpi_set_led(struct wpi_softc *sc, uint8_t which, uint8_t off, uint8_t on)
3381 {
3382         struct wpi_cmd_led led;
3383
3384         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3385
3386         led.which = which;
3387         led.unit = htole32(100000);     /* on/off in unit of 100ms */
3388         led.off = off;
3389         led.on = on;
3390         (void)wpi_cmd(sc, WPI_CMD_SET_LED, &led, sizeof led, 1);
3391 }
3392
3393 static int
3394 wpi_set_timing(struct wpi_softc *sc, struct ieee80211_node *ni)
3395 {
3396         struct wpi_cmd_timing cmd;
3397         uint64_t val, mod;
3398
3399         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3400
3401         memset(&cmd, 0, sizeof cmd);
3402         memcpy(&cmd.tstamp, ni->ni_tstamp.data, sizeof (uint64_t));
3403         cmd.bintval = htole16(ni->ni_intval);
3404         cmd.lintval = htole16(10);
3405
3406         /* Compute remaining time until next beacon. */
3407         val = (uint64_t)ni->ni_intval * IEEE80211_DUR_TU;
3408         mod = le64toh(cmd.tstamp) % val;
3409         cmd.binitval = htole32((uint32_t)(val - mod));
3410
3411         DPRINTF(sc, WPI_DEBUG_RESET, "timing bintval=%u tstamp=%ju, init=%u\n",
3412             ni->ni_intval, le64toh(cmd.tstamp), (uint32_t)(val - mod));
3413
3414         return wpi_cmd(sc, WPI_CMD_TIMING, &cmd, sizeof cmd, 1);
3415 }
3416
3417 /*
3418  * This function is called periodically (every 60 seconds) to adjust output
3419  * power to temperature changes.
3420  */
3421 static void
3422 wpi_power_calibration(struct wpi_softc *sc)
3423 {
3424         int temp;
3425
3426         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3427
3428         /* Update sensor data. */
3429         temp = (int)WPI_READ(sc, WPI_UCODE_GP2);
3430         DPRINTF(sc, WPI_DEBUG_TEMP, "Temp in calibration is: %d\n", temp);
3431
3432         /* Sanity-check read value. */
3433         if (temp < -260 || temp > 25) {
3434                 /* This can't be correct, ignore. */
3435                 DPRINTF(sc, WPI_DEBUG_TEMP,
3436                     "out-of-range temperature reported: %d\n", temp);
3437                 return;
3438         }
3439
3440         DPRINTF(sc, WPI_DEBUG_TEMP, "temperature %d->%d\n", sc->temp, temp);
3441
3442         /* Adjust Tx power if need be. */
3443         if (abs(temp - sc->temp) <= 6)
3444                 return;
3445
3446         sc->temp = temp;
3447
3448         if (wpi_set_txpower(sc, 1) != 0) {
3449                 /* just warn, too bad for the automatic calibration... */
3450                 device_printf(sc->sc_dev,"could not adjust Tx power\n");
3451         }
3452 }
3453
3454 /*
3455  * Set TX power for current channel.
3456  */
3457 static int
3458 wpi_set_txpower(struct wpi_softc *sc, int async)
3459 {
3460         struct wpi_power_group *group;
3461         struct wpi_cmd_txpower cmd;
3462         uint8_t chan;
3463         int idx, is_chan_5ghz, i;
3464
3465         /* Retrieve current channel from last RXON. */
3466         chan = sc->rxon.chan;
3467         is_chan_5ghz = (sc->rxon.flags & htole32(WPI_RXON_24GHZ)) == 0;
3468
3469         /* Find the TX power group to which this channel belongs. */
3470         if (is_chan_5ghz) {
3471                 for (group = &sc->groups[1]; group < &sc->groups[4]; group++)
3472                         if (chan <= group->chan)
3473                                 break;
3474         } else
3475                 group = &sc->groups[0];
3476
3477         memset(&cmd, 0, sizeof cmd);
3478         cmd.band = is_chan_5ghz ? WPI_BAND_5GHZ : WPI_BAND_2GHZ;
3479         cmd.chan = htole16(chan);
3480
3481         /* Set TX power for all OFDM and CCK rates. */
3482         for (i = 0; i <= WPI_RIDX_MAX ; i++) {
3483                 /* Retrieve TX power for this channel/rate. */
3484                 idx = wpi_get_power_index(sc, group, chan, is_chan_5ghz, i);
3485
3486                 cmd.rates[i].plcp = wpi_ridx_to_plcp[i];
3487
3488                 if (is_chan_5ghz) {
3489                         cmd.rates[i].rf_gain = wpi_rf_gain_5ghz[idx];
3490                         cmd.rates[i].dsp_gain = wpi_dsp_gain_5ghz[idx];
3491                 } else {
3492                         cmd.rates[i].rf_gain = wpi_rf_gain_2ghz[idx];
3493                         cmd.rates[i].dsp_gain = wpi_dsp_gain_2ghz[idx];
3494                 }
3495                 DPRINTF(sc, WPI_DEBUG_TEMP,
3496                     "chan %d/ridx %d: power index %d\n", chan, i, idx);
3497         }
3498
3499         return wpi_cmd(sc, WPI_CMD_TXPOWER, &cmd, sizeof cmd, async);
3500 }
3501
3502 /*
3503  * Determine Tx power index for a given channel/rate combination.
3504  * This takes into account the regulatory information from EEPROM and the
3505  * current temperature.
3506  */
3507 static int
3508 wpi_get_power_index(struct wpi_softc *sc, struct wpi_power_group *group,
3509     uint8_t chan, int is_chan_5ghz, int ridx)
3510 {
3511 /* Fixed-point arithmetic division using a n-bit fractional part. */
3512 #define fdivround(a, b, n)      \
3513         ((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
3514
3515 /* Linear interpolation. */
3516 #define interpolate(x, x1, y1, x2, y2, n)       \
3517         ((y1) + fdivround(((x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
3518
3519         struct wpi_power_sample *sample;
3520         int pwr, idx;
3521
3522         /* Default TX power is group maximum TX power minus 3dB. */
3523         pwr = group->maxpwr / 2;
3524
3525         /* Decrease TX power for highest OFDM rates to reduce distortion. */
3526         switch (ridx) {
3527         case WPI_RIDX_OFDM36:
3528                 pwr -= is_chan_5ghz ?  5 : 0;
3529                 break;
3530         case WPI_RIDX_OFDM48:
3531                 pwr -= is_chan_5ghz ? 10 : 7;
3532                 break;
3533         case WPI_RIDX_OFDM54:
3534                 pwr -= is_chan_5ghz ? 12 : 9;
3535                 break;
3536         }
3537
3538         /* Never exceed the channel maximum allowed TX power. */
3539         pwr = min(pwr, sc->maxpwr[chan]);
3540
3541         /* Retrieve TX power index into gain tables from samples. */
3542         for (sample = group->samples; sample < &group->samples[3]; sample++)
3543                 if (pwr > sample[1].power)
3544                         break;
3545         /* Fixed-point linear interpolation using a 19-bit fractional part. */
3546         idx = interpolate(pwr, sample[0].power, sample[0].index,
3547             sample[1].power, sample[1].index, 19);
3548
3549         /*-
3550          * Adjust power index based on current temperature:
3551          * - if cooler than factory-calibrated: decrease output power
3552          * - if warmer than factory-calibrated: increase output power
3553          */
3554         idx -= (sc->temp - group->temp) * 11 / 100;
3555
3556         /* Decrease TX power for CCK rates (-5dB). */
3557         if (ridx >= WPI_RIDX_CCK1)
3558                 idx += 10;
3559
3560         /* Make sure idx stays in a valid range. */
3561         if (idx < 0)
3562                 return 0;
3563         if (idx > WPI_MAX_PWR_INDEX)
3564                 return WPI_MAX_PWR_INDEX;
3565         return idx;
3566
3567 #undef interpolate
3568 #undef fdivround
3569 }
3570
3571 /*
3572  * Set STA mode power saving level (between 0 and 5).
3573  * Level 0 is CAM (Continuously Aware Mode), 5 is for maximum power saving.
3574  */
3575 static int
3576 wpi_set_pslevel(struct wpi_softc *sc, uint8_t dtim, int level, int async)
3577 {
3578         struct wpi_pmgt_cmd cmd;
3579         const struct wpi_pmgt *pmgt;
3580         uint32_t max, skip_dtim;
3581         uint32_t reg;
3582         int i;
3583
3584         DPRINTF(sc, WPI_DEBUG_PWRSAVE,
3585             "%s: dtim=%d, level=%d, async=%d\n",
3586             __func__, dtim, level, async);
3587
3588         /* Select which PS parameters to use. */
3589         if (dtim <= 10)
3590                 pmgt = &wpi_pmgt[0][level];
3591         else
3592                 pmgt = &wpi_pmgt[1][level];
3593
3594         memset(&cmd, 0, sizeof cmd);
3595         if (level != 0) /* not CAM */
3596                 cmd.flags |= htole16(WPI_PS_ALLOW_SLEEP);
3597         /* Retrieve PCIe Active State Power Management (ASPM). */
3598         reg = pci_read_config(sc->sc_dev, sc->sc_cap_off + 0x10, 1);
3599         if (!(reg & 0x1))       /* L0s Entry disabled. */
3600                 cmd.flags |= htole16(WPI_PS_PCI_PMGT);
3601
3602         cmd.rxtimeout = htole32(pmgt->rxtimeout * IEEE80211_DUR_TU);
3603         cmd.txtimeout = htole32(pmgt->txtimeout * IEEE80211_DUR_TU);
3604
3605         if (dtim == 0) {
3606                 dtim = 1;
3607                 skip_dtim = 0;
3608         } else
3609                 skip_dtim = pmgt->skip_dtim;
3610
3611         if (skip_dtim != 0) {
3612                 cmd.flags |= htole16(WPI_PS_SLEEP_OVER_DTIM);
3613                 max = pmgt->intval[4];
3614                 if (max == (uint32_t)-1)
3615                         max = dtim * (skip_dtim + 1);
3616                 else if (max > dtim)
3617                         max = (max / dtim) * dtim;
3618         } else
3619                 max = dtim;
3620
3621         for (i = 0; i < 5; i++)
3622                 cmd.intval[i] = htole32(MIN(max, pmgt->intval[i]));
3623
3624         return wpi_cmd(sc, WPI_CMD_SET_POWER_MODE, &cmd, sizeof cmd, async);
3625 }
3626
3627 static int
3628 wpi_send_btcoex(struct wpi_softc *sc)
3629 {
3630         struct wpi_bluetooth cmd;
3631
3632         memset(&cmd, 0, sizeof cmd);
3633         cmd.flags = WPI_BT_COEX_MODE_4WIRE;
3634         cmd.lead_time = WPI_BT_LEAD_TIME_DEF;
3635         cmd.max_kill = WPI_BT_MAX_KILL_DEF;
3636         DPRINTF(sc, WPI_DEBUG_RESET, "%s: configuring bluetooth coexistence\n",
3637             __func__);
3638         return wpi_cmd(sc, WPI_CMD_BT_COEX, &cmd, sizeof(cmd), 0);
3639 }
3640
3641 static int
3642 wpi_send_rxon(struct wpi_softc *sc, int assoc, int async)
3643 {
3644         int error;
3645
3646         if (async)
3647                 WPI_RXON_LOCK_ASSERT(sc);
3648
3649         if (assoc && wpi_check_bss_filter(sc) != 0) {
3650                 struct wpi_assoc rxon_assoc;
3651
3652                 rxon_assoc.flags = sc->rxon.flags;
3653                 rxon_assoc.filter = sc->rxon.filter;
3654                 rxon_assoc.ofdm_mask = sc->rxon.ofdm_mask;
3655                 rxon_assoc.cck_mask = sc->rxon.cck_mask;
3656                 rxon_assoc.reserved = 0;
3657
3658                 error = wpi_cmd(sc, WPI_CMD_RXON_ASSOC, &rxon_assoc,
3659                     sizeof (struct wpi_assoc), async);
3660                 if (error != 0) {
3661                         device_printf(sc->sc_dev,
3662                             "RXON_ASSOC command failed, error %d\n", error);
3663                         return error;
3664                 }
3665         } else {
3666                 if (async) {
3667                         WPI_NT_LOCK(sc);
3668                         error = wpi_cmd(sc, WPI_CMD_RXON, &sc->rxon,
3669                             sizeof (struct wpi_rxon), async);
3670                         if (error == 0)
3671                                 wpi_clear_node_table(sc);
3672                         WPI_NT_UNLOCK(sc);
3673                 } else {
3674                         error = wpi_cmd(sc, WPI_CMD_RXON, &sc->rxon,
3675                             sizeof (struct wpi_rxon), async);
3676                         if (error == 0)
3677                                 wpi_clear_node_table(sc);
3678                 }
3679
3680                 if (error != 0) {
3681                         device_printf(sc->sc_dev,
3682                             "RXON command failed, error %d\n", error);
3683                         return error;
3684                 }
3685
3686                 /* Add broadcast node. */
3687                 error = wpi_add_broadcast_node(sc, async);
3688                 if (error != 0) {
3689                         device_printf(sc->sc_dev,
3690                             "could not add broadcast node, error %d\n", error);
3691                         return error;
3692                 }
3693         }
3694
3695         /* Configuration has changed, set Tx power accordingly. */
3696         if ((error = wpi_set_txpower(sc, async)) != 0) {
3697                 device_printf(sc->sc_dev,
3698                     "%s: could not set TX power, error %d\n", __func__, error);
3699                 return error;
3700         }
3701
3702         return 0;
3703 }
3704
3705 /**
3706  * Configure the card to listen to a particular channel, this transisions the
3707  * card in to being able to receive frames from remote devices.
3708  */
3709 static int
3710 wpi_config(struct wpi_softc *sc)
3711 {
3712         struct ifnet *ifp = sc->sc_ifp;
3713         struct ieee80211com *ic = ifp->if_l2com;
3714         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3715         struct ieee80211_channel *c = ic->ic_curchan;
3716         uint32_t flags;
3717         int error;
3718
3719         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
3720
3721         /* Set power saving level to CAM during initialization. */
3722         if ((error = wpi_set_pslevel(sc, 0, 0, 0)) != 0) {
3723                 device_printf(sc->sc_dev,
3724                     "%s: could not set power saving level\n", __func__);
3725                 return error;
3726         }
3727
3728         /* Configure bluetooth coexistence. */
3729         if ((error = wpi_send_btcoex(sc)) != 0) {
3730                 device_printf(sc->sc_dev,
3731                     "could not configure bluetooth coexistence\n");
3732                 return error;
3733         }
3734
3735         /* Configure adapter. */
3736         memset(&sc->rxon, 0, sizeof (struct wpi_rxon));
3737         IEEE80211_ADDR_COPY(sc->rxon.myaddr, vap->iv_myaddr);
3738
3739         /* Set default channel. */
3740         sc->rxon.chan = ieee80211_chan2ieee(ic, c);
3741         sc->rxon.flags = htole32(WPI_RXON_TSF | WPI_RXON_CTS_TO_SELF);
3742         if (IEEE80211_IS_CHAN_2GHZ(c))
3743                 sc->rxon.flags |= htole32(WPI_RXON_AUTO | WPI_RXON_24GHZ);
3744
3745         sc->rxon.filter = WPI_FILTER_MULTICAST;
3746         switch (ic->ic_opmode) {
3747         case IEEE80211_M_STA:
3748                 sc->rxon.mode = WPI_MODE_STA;
3749                 break;
3750         case IEEE80211_M_IBSS:
3751                 sc->rxon.mode = WPI_MODE_IBSS;
3752                 sc->rxon.filter |= WPI_FILTER_BEACON;
3753                 break;
3754         case IEEE80211_M_HOSTAP:
3755                 /* XXX workaround for beaconing */
3756                 sc->rxon.mode = WPI_MODE_IBSS;
3757                 sc->rxon.filter |= WPI_FILTER_ASSOC | WPI_FILTER_PROMISC;
3758                 break;
3759         case IEEE80211_M_AHDEMO:
3760                 /* XXX workaround for passive channels selection */
3761                 sc->rxon.mode = WPI_MODE_HOSTAP;
3762                 break;
3763         case IEEE80211_M_MONITOR:
3764                 sc->rxon.mode = WPI_MODE_MONITOR;
3765                 break;
3766         default:
3767                 device_printf(sc->sc_dev, "unknown opmode %d\n",
3768                     ic->ic_opmode);
3769                 return EINVAL;
3770         }
3771         sc->rxon.filter = htole32(sc->rxon.filter);
3772         wpi_set_promisc(sc);
3773         sc->rxon.cck_mask  = 0x0f;      /* not yet negotiated */
3774         sc->rxon.ofdm_mask = 0xff;      /* not yet negotiated */
3775
3776         if ((error = wpi_send_rxon(sc, 0, 0)) != 0) {
3777                 device_printf(sc->sc_dev, "%s: could not send RXON\n",
3778                     __func__);
3779                 return error;
3780         }
3781
3782         /* Setup rate scalling. */
3783         if ((error = wpi_mrr_setup(sc)) != 0) {
3784                 device_printf(sc->sc_dev, "could not setup MRR, error %d\n",
3785                     error);
3786                 return error;
3787         }
3788
3789         /* Disable beacon notifications (unused). */
3790         flags = WPI_STATISTICS_BEACON_DISABLE;
3791         error = wpi_cmd(sc, WPI_CMD_GET_STATISTICS, &flags, sizeof flags, 1);
3792         if (error != 0) {
3793                 device_printf(sc->sc_dev,
3794                     "could not disable beacon statistics, error %d\n", error);
3795                 return error;
3796         }
3797
3798         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
3799
3800         return 0;
3801 }
3802
3803 static uint16_t
3804 wpi_get_active_dwell_time(struct wpi_softc *sc,
3805     struct ieee80211_channel *c, uint8_t n_probes)
3806 {
3807         /* No channel? Default to 2GHz settings. */
3808         if (c == NULL || IEEE80211_IS_CHAN_2GHZ(c)) {
3809                 return (WPI_ACTIVE_DWELL_TIME_2GHZ +
3810                 WPI_ACTIVE_DWELL_FACTOR_2GHZ * (n_probes + 1));
3811         }
3812
3813         /* 5GHz dwell time. */
3814         return (WPI_ACTIVE_DWELL_TIME_5GHZ +
3815             WPI_ACTIVE_DWELL_FACTOR_5GHZ * (n_probes + 1));
3816 }
3817
3818 /*
3819  * Limit the total dwell time to 85% of the beacon interval.
3820  *
3821  * Returns the dwell time in milliseconds.
3822  */
3823 static uint16_t
3824 wpi_limit_dwell(struct wpi_softc *sc, uint16_t dwell_time)
3825 {
3826         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3827         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3828         int bintval = 0;
3829
3830         /* bintval is in TU (1.024mS) */
3831         if (vap != NULL)
3832                 bintval = vap->iv_bss->ni_intval;
3833
3834         /*
3835          * If it's non-zero, we should calculate the minimum of
3836          * it and the DWELL_BASE.
3837          *
3838          * XXX Yes, the math should take into account that bintval
3839          * is 1.024mS, not 1mS..
3840          */
3841         if (bintval > 0) {
3842                 DPRINTF(sc, WPI_DEBUG_SCAN, "%s: bintval=%d\n", __func__,
3843                     bintval);
3844                 return (MIN(WPI_PASSIVE_DWELL_BASE, ((bintval * 85) / 100)));
3845         }
3846
3847         /* No association context? Default. */
3848         return (WPI_PASSIVE_DWELL_BASE);
3849 }
3850
3851 static uint16_t
3852 wpi_get_passive_dwell_time(struct wpi_softc *sc, struct ieee80211_channel *c)
3853 {
3854         uint16_t passive;
3855
3856         if (c == NULL || IEEE80211_IS_CHAN_2GHZ(c))
3857                 passive = WPI_PASSIVE_DWELL_BASE + WPI_PASSIVE_DWELL_TIME_2GHZ;
3858         else
3859                 passive = WPI_PASSIVE_DWELL_BASE + WPI_PASSIVE_DWELL_TIME_5GHZ;
3860
3861         /* Clamp to the beacon interval if we're associated. */
3862         return (wpi_limit_dwell(sc, passive));
3863 }
3864
3865 /*
3866  * Send a scan request to the firmware.
3867  */
3868 static int
3869 wpi_scan(struct wpi_softc *sc, struct ieee80211_channel *c)
3870 {
3871         struct ifnet *ifp = sc->sc_ifp;
3872         struct ieee80211com *ic = ifp->if_l2com;
3873         struct ieee80211_scan_state *ss = ic->ic_scan;
3874         struct ieee80211vap *vap = ss->ss_vap;
3875         struct wpi_scan_hdr *hdr;
3876         struct wpi_cmd_data *tx;
3877         struct wpi_scan_essid *essids;
3878         struct wpi_scan_chan *chan;
3879         struct ieee80211_frame *wh;
3880         struct ieee80211_rateset *rs;
3881         uint16_t dwell_active, dwell_passive;
3882         uint8_t *buf, *frm;
3883         int buflen, error, i, nssid;
3884
3885         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
3886
3887         /*
3888          * We are absolutely not allowed to send a scan command when another
3889          * scan command is pending.
3890          */
3891         if (callout_pending(&sc->scan_timeout)) {
3892                 device_printf(sc->sc_dev, "%s: called whilst scanning!\n",
3893                     __func__);
3894
3895                 DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
3896
3897                 return (EAGAIN);
3898         }
3899
3900         buf = malloc(WPI_SCAN_MAXSZ, M_DEVBUF, M_NOWAIT | M_ZERO);
3901         if (buf == NULL) {
3902                 device_printf(sc->sc_dev,
3903                     "%s: could not allocate buffer for scan command\n",
3904                     __func__);
3905                 error = ENOMEM;
3906                 goto fail;
3907         }
3908         hdr = (struct wpi_scan_hdr *)buf;
3909
3910         /*
3911          * Move to the next channel if no packets are received within 10 msecs
3912          * after sending the probe request.
3913          */
3914         hdr->quiet_time = htole16(10);          /* timeout in milliseconds */
3915         hdr->quiet_threshold = htole16(1);      /* min # of packets */
3916         /*
3917          * Max needs to be greater than active and passive and quiet!
3918          * It's also in microseconds!
3919          */
3920         hdr->max_svc = htole32(250 * IEEE80211_DUR_TU);
3921         hdr->pause_svc = htole32((4 << 24) |
3922             (100 * IEEE80211_DUR_TU));  /* Hardcode for now */
3923         hdr->filter = htole32(WPI_FILTER_MULTICAST | WPI_FILTER_BEACON);
3924
3925         tx = (struct wpi_cmd_data *)(hdr + 1);
3926         tx->flags = htole32(WPI_TX_AUTO_SEQ);
3927         tx->id = WPI_ID_BROADCAST;
3928         tx->lifetime = htole32(WPI_LIFETIME_INFINITE);
3929
3930         if (IEEE80211_IS_CHAN_5GHZ(c)) {
3931                 /* Send probe requests at 6Mbps. */
3932                 tx->plcp = wpi_ridx_to_plcp[WPI_RIDX_OFDM6];
3933                 rs = &ic->ic_sup_rates[IEEE80211_MODE_11A];
3934         } else {
3935                 hdr->flags = htole32(WPI_RXON_24GHZ | WPI_RXON_AUTO);
3936                 /* Send probe requests at 1Mbps. */
3937                 tx->plcp = wpi_ridx_to_plcp[WPI_RIDX_CCK1];
3938                 rs = &ic->ic_sup_rates[IEEE80211_MODE_11G];
3939         }
3940
3941         essids = (struct wpi_scan_essid *)(tx + 1);
3942         nssid = MIN(ss->ss_nssid, WPI_SCAN_MAX_ESSIDS);
3943         for (i = 0; i < nssid; i++) {
3944                 essids[i].id = IEEE80211_ELEMID_SSID;
3945                 essids[i].len = MIN(ss->ss_ssid[i].len, IEEE80211_NWID_LEN);
3946                 memcpy(essids[i].data, ss->ss_ssid[i].ssid, essids[i].len);
3947 #ifdef WPI_DEBUG
3948                 if (sc->sc_debug & WPI_DEBUG_SCAN) {
3949                         printf("Scanning Essid: ");
3950                         ieee80211_print_essid(essids[i].data, essids[i].len);
3951                         printf("\n");
3952                 }
3953 #endif
3954         }
3955
3956         /*
3957          * Build a probe request frame.  Most of the following code is a
3958          * copy & paste of what is done in net80211.
3959          */
3960         wh = (struct ieee80211_frame *)(essids + WPI_SCAN_MAX_ESSIDS);
3961         wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
3962                 IEEE80211_FC0_SUBTYPE_PROBE_REQ;
3963         wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
3964         IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
3965         IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr);
3966         IEEE80211_ADDR_COPY(wh->i_addr3, ifp->if_broadcastaddr);
3967         *(uint16_t *)&wh->i_dur[0] = 0; /* filled by h/w */
3968         *(uint16_t *)&wh->i_seq[0] = 0; /* filled by h/w */
3969
3970         frm = (uint8_t *)(wh + 1);
3971         frm = ieee80211_add_ssid(frm, NULL, 0);
3972         frm = ieee80211_add_rates(frm, rs);
3973         if (rs->rs_nrates > IEEE80211_RATE_SIZE)
3974                 frm = ieee80211_add_xrates(frm, rs);
3975
3976         /* Set length of probe request. */
3977         tx->len = htole16(frm - (uint8_t *)wh);
3978
3979         /*
3980          * Construct information about the channel that we
3981          * want to scan. The firmware expects this to be directly
3982          * after the scan probe request
3983          */
3984         chan = (struct wpi_scan_chan *)frm;
3985         chan->chan = htole16(ieee80211_chan2ieee(ic, c));
3986         chan->flags = 0;
3987         if (nssid) {
3988                 hdr->crc_threshold = WPI_SCAN_CRC_TH_DEFAULT;
3989                 chan->flags |= WPI_CHAN_NPBREQS(nssid);
3990         } else
3991                 hdr->crc_threshold = WPI_SCAN_CRC_TH_NEVER;
3992
3993         if (!IEEE80211_IS_CHAN_PASSIVE(c))
3994                 chan->flags |= WPI_CHAN_ACTIVE;
3995
3996         /*
3997          * Calculate the active/passive dwell times.
3998          */
3999
4000         dwell_active = wpi_get_active_dwell_time(sc, c, nssid);
4001         dwell_passive = wpi_get_passive_dwell_time(sc, c);
4002
4003         /* Make sure they're valid. */
4004         if (dwell_passive <= dwell_active)
4005                 dwell_passive = dwell_active + 1;
4006
4007         chan->active = htole16(dwell_active);
4008         chan->passive = htole16(dwell_passive);
4009
4010         chan->dsp_gain = 0x6e;  /* Default level */
4011
4012         if (IEEE80211_IS_CHAN_5GHZ(c))
4013                 chan->rf_gain = 0x3b;
4014         else
4015                 chan->rf_gain = 0x28;
4016
4017         DPRINTF(sc, WPI_DEBUG_SCAN, "Scanning %u Passive: %d\n",
4018             chan->chan, IEEE80211_IS_CHAN_PASSIVE(c));
4019
4020         hdr->nchan++;
4021
4022         if (hdr->nchan == 1 && sc->rxon.chan == chan->chan) {
4023                 /* XXX Force probe request transmission. */
4024                 memcpy(chan + 1, chan, sizeof (struct wpi_scan_chan));
4025
4026                 chan++;
4027
4028                 /* Reduce unnecessary delay. */
4029                 chan->flags = 0;
4030                 chan->passive = chan->active = hdr->quiet_time;
4031
4032                 hdr->nchan++;
4033         }
4034
4035         chan++;
4036
4037         buflen = (uint8_t *)chan - buf;
4038         hdr->len = htole16(buflen);
4039
4040         DPRINTF(sc, WPI_DEBUG_CMD, "sending scan command nchan=%d\n",
4041             hdr->nchan);
4042         error = wpi_cmd(sc, WPI_CMD_SCAN, buf, buflen, 1);
4043         free(buf, M_DEVBUF);
4044
4045         if (error != 0)
4046                 goto fail;
4047
4048         callout_reset(&sc->scan_timeout, 5*hz, wpi_scan_timeout, sc);
4049
4050         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
4051
4052         return 0;
4053
4054 fail:   DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
4055
4056         return error;
4057 }
4058
4059 static int
4060 wpi_auth(struct wpi_softc *sc, struct ieee80211vap *vap)
4061 {
4062         struct ieee80211com *ic = vap->iv_ic;
4063         struct ieee80211_node *ni = vap->iv_bss;
4064         struct ieee80211_channel *c = ni->ni_chan;
4065         int error;
4066
4067         WPI_RXON_LOCK(sc);
4068
4069         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
4070
4071         /* Update adapter configuration. */
4072         sc->rxon.associd = 0;
4073         sc->rxon.filter &= ~htole32(WPI_FILTER_BSS);
4074         IEEE80211_ADDR_COPY(sc->rxon.bssid, ni->ni_bssid);
4075         sc->rxon.chan = ieee80211_chan2ieee(ic, c);
4076         sc->rxon.flags = htole32(WPI_RXON_TSF | WPI_RXON_CTS_TO_SELF);
4077         if (IEEE80211_IS_CHAN_2GHZ(c))
4078                 sc->rxon.flags |= htole32(WPI_RXON_AUTO | WPI_RXON_24GHZ);
4079         if (ic->ic_flags & IEEE80211_F_SHSLOT)
4080                 sc->rxon.flags |= htole32(WPI_RXON_SHSLOT);
4081         if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
4082                 sc->rxon.flags |= htole32(WPI_RXON_SHPREAMBLE);
4083         if (IEEE80211_IS_CHAN_A(c)) {
4084                 sc->rxon.cck_mask  = 0;
4085                 sc->rxon.ofdm_mask = 0x15;
4086         } else if (IEEE80211_IS_CHAN_B(c)) {
4087                 sc->rxon.cck_mask  = 0x03;
4088                 sc->rxon.ofdm_mask = 0;
4089         } else {
4090                 /* Assume 802.11b/g. */
4091                 sc->rxon.cck_mask  = 0x0f;
4092                 sc->rxon.ofdm_mask = 0x15;
4093         }
4094
4095         DPRINTF(sc, WPI_DEBUG_STATE, "rxon chan %d flags %x cck %x ofdm %x\n",
4096             sc->rxon.chan, sc->rxon.flags, sc->rxon.cck_mask,
4097             sc->rxon.ofdm_mask);
4098
4099         if ((error = wpi_send_rxon(sc, 0, 1)) != 0) {
4100                 device_printf(sc->sc_dev, "%s: could not send RXON\n",
4101                     __func__);
4102         }
4103
4104         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
4105
4106         WPI_RXON_UNLOCK(sc);
4107
4108         return error;
4109 }
4110
4111 static int
4112 wpi_config_beacon(struct wpi_vap *wvp)
4113 {
4114         struct ieee80211com *ic = wvp->wv_vap.iv_ic;
4115         struct ieee80211_beacon_offsets *bo = &wvp->wv_boff;
4116         struct wpi_buf *bcn = &wvp->wv_bcbuf;
4117         struct wpi_softc *sc = ic->ic_ifp->if_softc;
4118         struct wpi_cmd_beacon *cmd = (struct wpi_cmd_beacon *)&bcn->data;
4119         struct ieee80211_tim_ie *tie;
4120         struct mbuf *m;
4121         uint8_t *ptr;
4122         int error;
4123
4124         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4125
4126         WPI_VAP_LOCK_ASSERT(wvp);
4127
4128         cmd->len = htole16(bcn->m->m_pkthdr.len);
4129         cmd->plcp = (ic->ic_curmode == IEEE80211_MODE_11A) ?
4130             wpi_ridx_to_plcp[WPI_RIDX_OFDM6] : wpi_ridx_to_plcp[WPI_RIDX_CCK1];
4131
4132         /* XXX seems to be unused */
4133         if (*(bo->bo_tim) == IEEE80211_ELEMID_TIM) {
4134                 tie = (struct ieee80211_tim_ie *) bo->bo_tim;
4135                 ptr = mtod(bcn->m, uint8_t *);
4136
4137                 cmd->tim = htole16(bo->bo_tim - ptr);
4138                 cmd->timsz = tie->tim_len;
4139         }
4140
4141         /* Necessary for recursion in ieee80211_beacon_update(). */
4142         m = bcn->m;
4143         bcn->m = m_dup(m, M_NOWAIT);
4144         if (bcn->m == NULL) {
4145                 device_printf(sc->sc_dev,
4146                     "%s: could not copy beacon frame\n", __func__);
4147                 error = ENOMEM;
4148                 goto end;
4149         }
4150
4151         if ((error = wpi_cmd2(sc, bcn)) != 0) {
4152                 device_printf(sc->sc_dev,
4153                     "%s: could not update beacon frame, error %d", __func__,
4154                     error);
4155         }
4156
4157         /* Restore mbuf. */
4158 end:    bcn->m = m;
4159
4160         return error;
4161 }
4162
4163 static int
4164 wpi_setup_beacon(struct wpi_softc *sc, struct ieee80211_node *ni)
4165 {
4166         struct wpi_vap *wvp = WPI_VAP(ni->ni_vap);
4167         struct wpi_buf *bcn = &wvp->wv_bcbuf;
4168         struct ieee80211_beacon_offsets *bo = &wvp->wv_boff;
4169         struct mbuf *m;
4170         int error;
4171
4172         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4173
4174         if (ni->ni_chan == IEEE80211_CHAN_ANYC)
4175                 return EINVAL;
4176
4177         m = ieee80211_beacon_alloc(ni, bo);
4178         if (m == NULL) {
4179                 device_printf(sc->sc_dev,
4180                     "%s: could not allocate beacon frame\n", __func__);
4181                 return ENOMEM;
4182         }
4183
4184         WPI_VAP_LOCK(wvp);
4185         if (bcn->m != NULL)
4186                 m_freem(bcn->m);
4187
4188         bcn->m = m;
4189
4190         error = wpi_config_beacon(wvp);
4191         WPI_VAP_UNLOCK(wvp);
4192
4193         return error;
4194 }
4195
4196 static void
4197 wpi_update_beacon(struct ieee80211vap *vap, int item)
4198 {
4199         struct wpi_softc *sc = vap->iv_ic->ic_ifp->if_softc;
4200         struct wpi_vap *wvp = WPI_VAP(vap);
4201         struct wpi_buf *bcn = &wvp->wv_bcbuf;
4202         struct ieee80211_beacon_offsets *bo = &wvp->wv_boff;
4203         struct ieee80211_node *ni = vap->iv_bss;
4204         int mcast = 0;
4205
4206         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
4207
4208         WPI_VAP_LOCK(wvp);
4209         if (bcn->m == NULL) {
4210                 bcn->m = ieee80211_beacon_alloc(ni, bo);
4211                 if (bcn->m == NULL) {
4212                         device_printf(sc->sc_dev,
4213                             "%s: could not allocate beacon frame\n", __func__);
4214
4215                         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR,
4216                             __func__);
4217
4218                         WPI_VAP_UNLOCK(wvp);
4219                         return;
4220                 }
4221         }
4222         WPI_VAP_UNLOCK(wvp);
4223
4224         if (item == IEEE80211_BEACON_TIM)
4225                 mcast = 1;      /* TODO */
4226
4227         setbit(bo->bo_flags, item);
4228         ieee80211_beacon_update(ni, bo, bcn->m, mcast);
4229
4230         WPI_VAP_LOCK(wvp);
4231         wpi_config_beacon(wvp);
4232         WPI_VAP_UNLOCK(wvp);
4233
4234         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
4235 }
4236
4237 static void
4238 wpi_newassoc(struct ieee80211_node *ni, int isnew)
4239 {
4240         struct ieee80211vap *vap = ni->ni_vap;
4241         struct wpi_softc *sc = ni->ni_ic->ic_ifp->if_softc;
4242         struct wpi_node *wn = WPI_NODE(ni);
4243         int error;
4244
4245         WPI_NT_LOCK(sc);
4246
4247         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4248
4249         if (vap->iv_opmode != IEEE80211_M_STA && wn->id == WPI_ID_UNDEFINED) {
4250                 if ((error = wpi_add_ibss_node(sc, ni)) != 0) {
4251                         device_printf(sc->sc_dev,
4252                             "%s: could not add IBSS node, error %d\n",
4253                             __func__, error);
4254                 }
4255         }
4256         WPI_NT_UNLOCK(sc);
4257 }
4258
4259 static int
4260 wpi_run(struct wpi_softc *sc, struct ieee80211vap *vap)
4261 {
4262         struct ieee80211com *ic = vap->iv_ic;
4263         struct ieee80211_node *ni = vap->iv_bss;
4264         struct ieee80211_channel *c = ni->ni_chan;
4265         int error;
4266
4267         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
4268
4269         if (vap->iv_opmode == IEEE80211_M_MONITOR) {
4270                 /* Link LED blinks while monitoring. */
4271                 wpi_set_led(sc, WPI_LED_LINK, 5, 5);
4272                 return 0;
4273         }
4274
4275         /* XXX kernel panic workaround */
4276         if (c == IEEE80211_CHAN_ANYC) {
4277                 device_printf(sc->sc_dev, "%s: incomplete configuration\n",
4278                     __func__);
4279                 return EINVAL;
4280         }
4281
4282         if ((error = wpi_set_timing(sc, ni)) != 0) {
4283                 device_printf(sc->sc_dev,
4284                     "%s: could not set timing, error %d\n", __func__, error);
4285                 return error;
4286         }
4287
4288         /* Update adapter configuration. */
4289         WPI_RXON_LOCK(sc);
4290         IEEE80211_ADDR_COPY(sc->rxon.bssid, ni->ni_bssid);
4291         sc->rxon.associd = htole16(IEEE80211_NODE_AID(ni));
4292         sc->rxon.chan = ieee80211_chan2ieee(ic, c);
4293         sc->rxon.flags = htole32(WPI_RXON_TSF | WPI_RXON_CTS_TO_SELF);
4294         if (IEEE80211_IS_CHAN_2GHZ(c))
4295                 sc->rxon.flags |= htole32(WPI_RXON_AUTO | WPI_RXON_24GHZ);
4296         if (ic->ic_flags & IEEE80211_F_SHSLOT)
4297                 sc->rxon.flags |= htole32(WPI_RXON_SHSLOT);
4298         if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
4299                 sc->rxon.flags |= htole32(WPI_RXON_SHPREAMBLE);
4300         if (IEEE80211_IS_CHAN_A(c)) {
4301                 sc->rxon.cck_mask  = 0;
4302                 sc->rxon.ofdm_mask = 0x15;
4303         } else if (IEEE80211_IS_CHAN_B(c)) {
4304                 sc->rxon.cck_mask  = 0x03;
4305                 sc->rxon.ofdm_mask = 0;
4306         } else {
4307                 /* Assume 802.11b/g. */
4308                 sc->rxon.cck_mask  = 0x0f;
4309                 sc->rxon.ofdm_mask = 0x15;
4310         }
4311         sc->rxon.filter |= htole32(WPI_FILTER_BSS);
4312
4313         DPRINTF(sc, WPI_DEBUG_STATE, "rxon chan %d flags %x\n",
4314             sc->rxon.chan, sc->rxon.flags);
4315
4316         if ((error = wpi_send_rxon(sc, 0, 1)) != 0) {
4317                 device_printf(sc->sc_dev, "%s: could not send RXON\n",
4318                     __func__);
4319                 return error;
4320         }
4321
4322         /* Start periodic calibration timer. */
4323         callout_reset(&sc->calib_to, 60*hz, wpi_calib_timeout, sc);
4324
4325         WPI_RXON_UNLOCK(sc);
4326
4327         if (vap->iv_opmode == IEEE80211_M_IBSS ||
4328             vap->iv_opmode == IEEE80211_M_HOSTAP) {
4329                 if ((error = wpi_setup_beacon(sc, ni)) != 0) {
4330                         device_printf(sc->sc_dev,
4331                             "%s: could not setup beacon, error %d\n", __func__,
4332                             error);
4333                         return error;
4334                 }
4335         }
4336
4337         if (vap->iv_opmode == IEEE80211_M_STA) {
4338                 /* Add BSS node. */
4339                 WPI_NT_LOCK(sc);
4340                 error = wpi_add_sta_node(sc, ni);
4341                 WPI_NT_UNLOCK(sc);
4342                 if (error != 0) {
4343                         device_printf(sc->sc_dev,
4344                             "%s: could not add BSS node, error %d\n", __func__,
4345                             error);
4346                         return error;
4347                 }
4348         }
4349
4350         /* Link LED always on while associated. */
4351         wpi_set_led(sc, WPI_LED_LINK, 0, 1);
4352
4353         /* Enable power-saving mode if requested by user. */
4354         if ((vap->iv_flags & IEEE80211_F_PMGTON) &&
4355             vap->iv_opmode != IEEE80211_M_IBSS)
4356                 (void)wpi_set_pslevel(sc, 0, 3, 1);
4357
4358         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
4359
4360         return 0;
4361 }
4362
4363 static int
4364 wpi_load_key(struct ieee80211_node *ni, const struct ieee80211_key *k)
4365 {
4366         const struct ieee80211_cipher *cip = k->wk_cipher;
4367         struct ieee80211vap *vap = ni->ni_vap;
4368         struct wpi_softc *sc = ni->ni_ic->ic_ifp->if_softc;
4369         struct wpi_node *wn = WPI_NODE(ni);
4370         struct wpi_node_info node;
4371         uint16_t kflags;
4372         int error;
4373
4374         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4375
4376         if (wpi_check_node_entry(sc, wn->id) == 0) {
4377                 device_printf(sc->sc_dev, "%s: node does not exist\n",
4378                     __func__);
4379                 return 0;
4380         }
4381
4382         switch (cip->ic_cipher) {
4383         case IEEE80211_CIPHER_AES_CCM:
4384                 kflags = WPI_KFLAG_CCMP;
4385                 break;
4386
4387         default:
4388                 device_printf(sc->sc_dev, "%s: unknown cipher %d\n", __func__,
4389                     cip->ic_cipher);
4390                 return 0;
4391         }
4392
4393         kflags |= WPI_KFLAG_KID(k->wk_keyix);
4394         if (k->wk_flags & IEEE80211_KEY_GROUP)
4395                 kflags |= WPI_KFLAG_MULTICAST;
4396
4397         memset(&node, 0, sizeof node);
4398         node.id = wn->id;
4399         node.control = WPI_NODE_UPDATE;
4400         node.flags = WPI_FLAG_KEY_SET;
4401         node.kflags = htole16(kflags);
4402         memcpy(node.key, k->wk_key, k->wk_keylen);
4403 again:
4404         DPRINTF(sc, WPI_DEBUG_KEY,
4405             "%s: setting %s key id %d for node %d (%s)\n", __func__,
4406             (kflags & WPI_KFLAG_MULTICAST) ? "group" : "ucast", k->wk_keyix,
4407             node.id, ether_sprintf(ni->ni_macaddr));
4408
4409         error = wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, 1);
4410         if (error != 0) {
4411                 device_printf(sc->sc_dev, "can't update node info, error %d\n",
4412                     error);
4413                 return !error;
4414         }
4415
4416         if (!(kflags & WPI_KFLAG_MULTICAST) && &vap->iv_nw_keys[0] <= k &&
4417             k < &vap->iv_nw_keys[IEEE80211_WEP_NKID]) {
4418                 kflags |= WPI_KFLAG_MULTICAST;
4419                 node.kflags = htole16(kflags);
4420
4421                 goto again;
4422         }
4423
4424         return 1;
4425 }
4426
4427 static void
4428 wpi_load_key_cb(void *arg, struct ieee80211_node *ni)
4429 {
4430         const struct ieee80211_key *k = arg;
4431         struct ieee80211vap *vap = ni->ni_vap;
4432         struct wpi_softc *sc = ni->ni_ic->ic_ifp->if_softc;
4433         struct wpi_node *wn = WPI_NODE(ni);
4434         int error;
4435
4436         if (vap->iv_bss == ni && wn->id == WPI_ID_UNDEFINED)
4437                 return;
4438
4439         WPI_NT_LOCK(sc);
4440         error = wpi_load_key(ni, k);
4441         WPI_NT_UNLOCK(sc);
4442
4443         if (error == 0) {
4444                 device_printf(sc->sc_dev, "%s: error while setting key\n",
4445                     __func__);
4446         }
4447 }
4448
4449 static int
4450 wpi_set_global_keys(struct ieee80211_node *ni)
4451 {
4452         struct ieee80211vap *vap = ni->ni_vap;
4453         struct ieee80211_key *wk = &vap->iv_nw_keys[0];
4454         int error = 1;
4455
4456         for (; wk < &vap->iv_nw_keys[IEEE80211_WEP_NKID] && error; wk++)
4457                 if (wk->wk_keyix != IEEE80211_KEYIX_NONE)
4458                         error = wpi_load_key(ni, wk);
4459
4460         return !error;
4461 }
4462
4463 static int
4464 wpi_del_key(struct ieee80211_node *ni, const struct ieee80211_key *k)
4465 {
4466         struct ieee80211vap *vap = ni->ni_vap;
4467         struct wpi_softc *sc = ni->ni_ic->ic_ifp->if_softc;
4468         struct wpi_node *wn = WPI_NODE(ni);
4469         struct wpi_node_info node;
4470         uint16_t kflags;
4471         int error;
4472
4473         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4474
4475         if (wpi_check_node_entry(sc, wn->id) == 0) {
4476                 DPRINTF(sc, WPI_DEBUG_KEY, "%s: node was removed\n", __func__);
4477                 return 1;       /* Nothing to do. */
4478         }
4479
4480         kflags = WPI_KFLAG_KID(k->wk_keyix);
4481         if (k->wk_flags & IEEE80211_KEY_GROUP)
4482                 kflags |= WPI_KFLAG_MULTICAST;
4483
4484         memset(&node, 0, sizeof node);
4485         node.id = wn->id;
4486         node.control = WPI_NODE_UPDATE;
4487         node.flags = WPI_FLAG_KEY_SET;
4488         node.kflags = htole16(kflags);
4489 again:
4490         DPRINTF(sc, WPI_DEBUG_KEY, "%s: deleting %s key %d for node %d (%s)\n",
4491             __func__, (kflags & WPI_KFLAG_MULTICAST) ? "group" : "ucast",
4492             k->wk_keyix, node.id, ether_sprintf(ni->ni_macaddr));
4493
4494         error = wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, 1);
4495         if (error != 0) {
4496                 device_printf(sc->sc_dev, "can't update node info, error %d\n",
4497                     error);
4498                 return !error;
4499         }
4500
4501         if (!(kflags & WPI_KFLAG_MULTICAST) && &vap->iv_nw_keys[0] <= k &&
4502             k < &vap->iv_nw_keys[IEEE80211_WEP_NKID]) {
4503                 kflags |= WPI_KFLAG_MULTICAST;
4504                 node.kflags = htole16(kflags);
4505
4506                 goto again;
4507         }
4508
4509         return 1;
4510 }
4511
4512 static void
4513 wpi_del_key_cb(void *arg, struct ieee80211_node *ni)
4514 {
4515         const struct ieee80211_key *k = arg;
4516         struct ieee80211vap *vap = ni->ni_vap;
4517         struct wpi_softc *sc = ni->ni_ic->ic_ifp->if_softc;
4518         struct wpi_node *wn = WPI_NODE(ni);
4519         int error;
4520
4521         if (vap->iv_bss == ni && wn->id == WPI_ID_UNDEFINED)
4522                 return;
4523
4524         WPI_NT_LOCK(sc);
4525         error = wpi_del_key(ni, k);
4526         WPI_NT_UNLOCK(sc);
4527
4528         if (error == 0) {
4529                 device_printf(sc->sc_dev, "%s: error while deleting key\n",
4530                     __func__);
4531         }
4532 }
4533
4534 static int
4535 wpi_process_key(struct ieee80211vap *vap, const struct ieee80211_key *k,
4536     int set)
4537 {
4538         struct ieee80211com *ic = vap->iv_ic;
4539         struct wpi_softc *sc = ic->ic_ifp->if_softc;
4540         struct wpi_vap *wvp = WPI_VAP(vap);
4541         struct ieee80211_node *ni;
4542         int error, ni_ref = 0;
4543
4544         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4545
4546         if (k->wk_flags & IEEE80211_KEY_SWCRYPT) {
4547                 /* Not for us. */
4548                 return 1;
4549         }
4550
4551         if (!(k->wk_flags & IEEE80211_KEY_RECV)) {
4552                 /* XMIT keys are handled in wpi_tx_data(). */
4553                 return 1;
4554         }
4555
4556         /* Handle group keys. */
4557         if (&vap->iv_nw_keys[0] <= k &&
4558             k < &vap->iv_nw_keys[IEEE80211_WEP_NKID]) {
4559                 WPI_NT_LOCK(sc);
4560                 if (set)
4561                         wvp->wv_gtk |= WPI_VAP_KEY(k->wk_keyix);
4562                 else
4563                         wvp->wv_gtk &= ~WPI_VAP_KEY(k->wk_keyix);
4564                 WPI_NT_UNLOCK(sc);
4565
4566                 if (vap->iv_state == IEEE80211_S_RUN) {
4567                         ieee80211_iterate_nodes(&ic->ic_sta,
4568                             set ? wpi_load_key_cb : wpi_del_key_cb,
4569                             __DECONST(void *, k));
4570                 }
4571
4572                 return 1;
4573         }
4574
4575         switch (vap->iv_opmode) {
4576         case IEEE80211_M_STA:
4577                 ni = vap->iv_bss;
4578                 break;
4579
4580         case IEEE80211_M_IBSS:
4581         case IEEE80211_M_AHDEMO:
4582         case IEEE80211_M_HOSTAP:
4583                 ni = ieee80211_find_vap_node(&ic->ic_sta, vap, k->wk_macaddr);
4584                 if (ni == NULL)
4585                         return 0;       /* should not happen */
4586
4587                 ni_ref = 1;
4588                 break;
4589
4590         default:
4591                 device_printf(sc->sc_dev, "%s: unknown opmode %d\n", __func__,
4592                     vap->iv_opmode);
4593                 return 0;
4594         }
4595
4596         WPI_NT_LOCK(sc);
4597         if (set)
4598                 error = wpi_load_key(ni, k);
4599         else
4600                 error = wpi_del_key(ni, k);
4601         WPI_NT_UNLOCK(sc);
4602
4603         if (ni_ref)
4604                 ieee80211_node_decref(ni);
4605
4606         return error;
4607 }
4608
4609 static int
4610 wpi_key_set(struct ieee80211vap *vap, const struct ieee80211_key *k,
4611     const uint8_t mac[IEEE80211_ADDR_LEN])
4612 {
4613         return wpi_process_key(vap, k, 1);
4614 }
4615
4616 static int
4617 wpi_key_delete(struct ieee80211vap *vap, const struct ieee80211_key *k)
4618 {
4619         return wpi_process_key(vap, k, 0);
4620 }
4621
4622 /*
4623  * This function is called after the runtime firmware notifies us of its
4624  * readiness (called in a process context).
4625  */
4626 static int
4627 wpi_post_alive(struct wpi_softc *sc)
4628 {
4629         int ntries, error;
4630
4631         /* Check (again) that the radio is not disabled. */
4632         if ((error = wpi_nic_lock(sc)) != 0)
4633                 return error;
4634
4635         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4636
4637         /* NB: Runtime firmware must be up and running. */
4638         if (!(wpi_prph_read(sc, WPI_APMG_RFKILL) & 1)) {
4639                 device_printf(sc->sc_dev,
4640                     "RF switch: radio disabled (%s)\n", __func__);
4641                 wpi_nic_unlock(sc);
4642                 return EPERM;   /* :-) */
4643         }
4644         wpi_nic_unlock(sc);
4645
4646         /* Wait for thermal sensor to calibrate. */
4647         for (ntries = 0; ntries < 1000; ntries++) {
4648                 if ((sc->temp = (int)WPI_READ(sc, WPI_UCODE_GP2)) != 0)
4649                         break;
4650                 DELAY(10);
4651         }
4652
4653         if (ntries == 1000) {
4654                 device_printf(sc->sc_dev,
4655                     "timeout waiting for thermal sensor calibration\n");
4656                 return ETIMEDOUT;
4657         }
4658
4659         DPRINTF(sc, WPI_DEBUG_TEMP, "temperature %d\n", sc->temp);
4660         return 0;
4661 }
4662
4663 /*
4664  * The firmware boot code is small and is intended to be copied directly into
4665  * the NIC internal memory (no DMA transfer).
4666  */
4667 static int
4668 wpi_load_bootcode(struct wpi_softc *sc, const uint8_t *ucode, int size)
4669 {
4670         int error, ntries;
4671
4672         DPRINTF(sc, WPI_DEBUG_HW, "Loading microcode size 0x%x\n", size);
4673
4674         size /= sizeof (uint32_t);
4675
4676         if ((error = wpi_nic_lock(sc)) != 0)
4677                 return error;
4678
4679         /* Copy microcode image into NIC memory. */
4680         wpi_prph_write_region_4(sc, WPI_BSM_SRAM_BASE,
4681             (const uint32_t *)ucode, size);
4682
4683         wpi_prph_write(sc, WPI_BSM_WR_MEM_SRC, 0);
4684         wpi_prph_write(sc, WPI_BSM_WR_MEM_DST, WPI_FW_TEXT_BASE);
4685         wpi_prph_write(sc, WPI_BSM_WR_DWCOUNT, size);
4686
4687         /* Start boot load now. */
4688         wpi_prph_write(sc, WPI_BSM_WR_CTRL, WPI_BSM_WR_CTRL_START);
4689
4690         /* Wait for transfer to complete. */
4691         for (ntries = 0; ntries < 1000; ntries++) {
4692                 uint32_t status = WPI_READ(sc, WPI_FH_TX_STATUS);
4693                 DPRINTF(sc, WPI_DEBUG_HW,
4694                     "firmware status=0x%x, val=0x%x, result=0x%x\n", status,
4695                     WPI_FH_TX_STATUS_IDLE(6),
4696                     status & WPI_FH_TX_STATUS_IDLE(6));
4697                 if (status & WPI_FH_TX_STATUS_IDLE(6)) {
4698                         DPRINTF(sc, WPI_DEBUG_HW,
4699                             "Status Match! - ntries = %d\n", ntries);
4700                         break;
4701                 }
4702                 DELAY(10);
4703         }
4704         if (ntries == 1000) {
4705                 device_printf(sc->sc_dev, "%s: could not load boot firmware\n",
4706                     __func__);
4707                 wpi_nic_unlock(sc);
4708                 return ETIMEDOUT;
4709         }
4710
4711         /* Enable boot after power up. */
4712         wpi_prph_write(sc, WPI_BSM_WR_CTRL, WPI_BSM_WR_CTRL_START_EN);
4713
4714         wpi_nic_unlock(sc);
4715         return 0;
4716 }
4717
4718 static int
4719 wpi_load_firmware(struct wpi_softc *sc)
4720 {
4721         struct wpi_fw_info *fw = &sc->fw;
4722         struct wpi_dma_info *dma = &sc->fw_dma;
4723         int error;
4724
4725         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4726
4727         /* Copy initialization sections into pre-allocated DMA-safe memory. */
4728         memcpy(dma->vaddr, fw->init.data, fw->init.datasz);
4729         bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
4730         memcpy(dma->vaddr + WPI_FW_DATA_MAXSZ, fw->init.text, fw->init.textsz);
4731         bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
4732
4733         /* Tell adapter where to find initialization sections. */
4734         if ((error = wpi_nic_lock(sc)) != 0)
4735                 return error;
4736         wpi_prph_write(sc, WPI_BSM_DRAM_DATA_ADDR, dma->paddr);
4737         wpi_prph_write(sc, WPI_BSM_DRAM_DATA_SIZE, fw->init.datasz);
4738         wpi_prph_write(sc, WPI_BSM_DRAM_TEXT_ADDR,
4739             dma->paddr + WPI_FW_DATA_MAXSZ);
4740         wpi_prph_write(sc, WPI_BSM_DRAM_TEXT_SIZE, fw->init.textsz);
4741         wpi_nic_unlock(sc);
4742
4743         /* Load firmware boot code. */
4744         error = wpi_load_bootcode(sc, fw->boot.text, fw->boot.textsz);
4745         if (error != 0) {
4746                 device_printf(sc->sc_dev, "%s: could not load boot firmware\n",
4747                     __func__);
4748                 return error;
4749         }
4750
4751         /* Now press "execute". */
4752         WPI_WRITE(sc, WPI_RESET, 0);
4753
4754         /* Wait at most one second for first alive notification. */
4755         if ((error = mtx_sleep(sc, &sc->sc_mtx, PCATCH, "wpiinit", hz)) != 0) {
4756                 device_printf(sc->sc_dev,
4757                     "%s: timeout waiting for adapter to initialize, error %d\n",
4758                     __func__, error);
4759                 return error;
4760         }
4761
4762         /* Copy runtime sections into pre-allocated DMA-safe memory. */
4763         memcpy(dma->vaddr, fw->main.data, fw->main.datasz);
4764         bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
4765         memcpy(dma->vaddr + WPI_FW_DATA_MAXSZ, fw->main.text, fw->main.textsz);
4766         bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
4767
4768         /* Tell adapter where to find runtime sections. */
4769         if ((error = wpi_nic_lock(sc)) != 0)
4770                 return error;
4771         wpi_prph_write(sc, WPI_BSM_DRAM_DATA_ADDR, dma->paddr);
4772         wpi_prph_write(sc, WPI_BSM_DRAM_DATA_SIZE, fw->main.datasz);
4773         wpi_prph_write(sc, WPI_BSM_DRAM_TEXT_ADDR,
4774             dma->paddr + WPI_FW_DATA_MAXSZ);
4775         wpi_prph_write(sc, WPI_BSM_DRAM_TEXT_SIZE,
4776             WPI_FW_UPDATED | fw->main.textsz);
4777         wpi_nic_unlock(sc);
4778
4779         return 0;
4780 }
4781
4782 static int
4783 wpi_read_firmware(struct wpi_softc *sc)
4784 {
4785         const struct firmware *fp;
4786         struct wpi_fw_info *fw = &sc->fw;
4787         const struct wpi_firmware_hdr *hdr;
4788         int error;
4789
4790         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4791
4792         DPRINTF(sc, WPI_DEBUG_FIRMWARE,
4793             "Attempting Loading Firmware from %s module\n", WPI_FW_NAME);
4794
4795         WPI_UNLOCK(sc);
4796         fp = firmware_get(WPI_FW_NAME);
4797         WPI_LOCK(sc);
4798
4799         if (fp == NULL) {
4800                 device_printf(sc->sc_dev,
4801                     "could not load firmware image '%s'\n", WPI_FW_NAME);
4802                 return EINVAL;
4803         }
4804
4805         sc->fw_fp = fp;
4806
4807         if (fp->datasize < sizeof (struct wpi_firmware_hdr)) {
4808                 device_printf(sc->sc_dev,
4809                     "firmware file too short: %zu bytes\n", fp->datasize);
4810                 error = EINVAL;
4811                 goto fail;
4812         }
4813
4814         fw->size = fp->datasize;
4815         fw->data = (const uint8_t *)fp->data;
4816
4817         /* Extract firmware header information. */
4818         hdr = (const struct wpi_firmware_hdr *)fw->data;
4819
4820         /*     |  RUNTIME FIRMWARE   |    INIT FIRMWARE    | BOOT FW  |
4821            |HDR|<--TEXT-->|<--DATA-->|<--TEXT-->|<--DATA-->|<--TEXT-->| */
4822
4823         fw->main.textsz = le32toh(hdr->rtextsz);
4824         fw->main.datasz = le32toh(hdr->rdatasz);
4825         fw->init.textsz = le32toh(hdr->itextsz);
4826         fw->init.datasz = le32toh(hdr->idatasz);
4827         fw->boot.textsz = le32toh(hdr->btextsz);
4828         fw->boot.datasz = 0;
4829
4830         /* Sanity-check firmware header. */
4831         if (fw->main.textsz > WPI_FW_TEXT_MAXSZ ||
4832             fw->main.datasz > WPI_FW_DATA_MAXSZ ||
4833             fw->init.textsz > WPI_FW_TEXT_MAXSZ ||
4834             fw->init.datasz > WPI_FW_DATA_MAXSZ ||
4835             fw->boot.textsz > WPI_FW_BOOT_TEXT_MAXSZ ||
4836             (fw->boot.textsz & 3) != 0) {
4837                 device_printf(sc->sc_dev, "invalid firmware header\n");
4838                 error = EINVAL;
4839                 goto fail;
4840         }
4841
4842         /* Check that all firmware sections fit. */
4843         if (fw->size < sizeof (*hdr) + fw->main.textsz + fw->main.datasz +
4844             fw->init.textsz + fw->init.datasz + fw->boot.textsz) {
4845                 device_printf(sc->sc_dev,
4846                     "firmware file too short: %zu bytes\n", fw->size);
4847                 error = EINVAL;
4848                 goto fail;
4849         }
4850
4851         /* Get pointers to firmware sections. */
4852         fw->main.text = (const uint8_t *)(hdr + 1);
4853         fw->main.data = fw->main.text + fw->main.textsz;
4854         fw->init.text = fw->main.data + fw->main.datasz;
4855         fw->init.data = fw->init.text + fw->init.textsz;
4856         fw->boot.text = fw->init.data + fw->init.datasz;
4857
4858         DPRINTF(sc, WPI_DEBUG_FIRMWARE,
4859             "Firmware Version: Major %d, Minor %d, Driver %d, \n"
4860             "runtime (text: %u, data: %u) init (text: %u, data %u) "
4861             "boot (text %u)\n", hdr->major, hdr->minor, le32toh(hdr->driver),
4862             fw->main.textsz, fw->main.datasz,
4863             fw->init.textsz, fw->init.datasz, fw->boot.textsz);
4864
4865         DPRINTF(sc, WPI_DEBUG_FIRMWARE, "fw->main.text %p\n", fw->main.text);
4866         DPRINTF(sc, WPI_DEBUG_FIRMWARE, "fw->main.data %p\n", fw->main.data);
4867         DPRINTF(sc, WPI_DEBUG_FIRMWARE, "fw->init.text %p\n", fw->init.text);
4868         DPRINTF(sc, WPI_DEBUG_FIRMWARE, "fw->init.data %p\n", fw->init.data);
4869         DPRINTF(sc, WPI_DEBUG_FIRMWARE, "fw->boot.text %p\n", fw->boot.text);
4870
4871         return 0;
4872
4873 fail:   wpi_unload_firmware(sc);
4874         return error;
4875 }
4876
4877 /**
4878  * Free the referenced firmware image
4879  */
4880 static void
4881 wpi_unload_firmware(struct wpi_softc *sc)
4882 {
4883         if (sc->fw_fp != NULL) {
4884                 firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
4885                 sc->fw_fp = NULL;
4886         }
4887 }
4888
4889 static int
4890 wpi_clock_wait(struct wpi_softc *sc)
4891 {
4892         int ntries;
4893
4894         /* Set "initialization complete" bit. */
4895         WPI_SETBITS(sc, WPI_GP_CNTRL, WPI_GP_CNTRL_INIT_DONE);
4896
4897         /* Wait for clock stabilization. */
4898         for (ntries = 0; ntries < 2500; ntries++) {
4899                 if (WPI_READ(sc, WPI_GP_CNTRL) & WPI_GP_CNTRL_MAC_CLOCK_READY)
4900                         return 0;
4901                 DELAY(100);
4902         }
4903         device_printf(sc->sc_dev,
4904             "%s: timeout waiting for clock stabilization\n", __func__);
4905
4906         return ETIMEDOUT;
4907 }
4908
4909 static int
4910 wpi_apm_init(struct wpi_softc *sc)
4911 {
4912         uint32_t reg;
4913         int error;
4914
4915         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4916
4917         /* Disable L0s exit timer (NMI bug workaround). */
4918         WPI_SETBITS(sc, WPI_GIO_CHICKEN, WPI_GIO_CHICKEN_DIS_L0S_TIMER);
4919         /* Don't wait for ICH L0s (ICH bug workaround). */
4920         WPI_SETBITS(sc, WPI_GIO_CHICKEN, WPI_GIO_CHICKEN_L1A_NO_L0S_RX);
4921
4922         /* Set FH wait threshold to max (HW bug under stress workaround). */
4923         WPI_SETBITS(sc, WPI_DBG_HPET_MEM, 0xffff0000);
4924
4925         /* Retrieve PCIe Active State Power Management (ASPM). */
4926         reg = pci_read_config(sc->sc_dev, sc->sc_cap_off + 0x10, 1);
4927         /* Workaround for HW instability in PCIe L0->L0s->L1 transition. */
4928         if (reg & 0x02) /* L1 Entry enabled. */
4929                 WPI_SETBITS(sc, WPI_GIO, WPI_GIO_L0S_ENA);
4930         else
4931                 WPI_CLRBITS(sc, WPI_GIO, WPI_GIO_L0S_ENA);
4932
4933         WPI_SETBITS(sc, WPI_ANA_PLL, WPI_ANA_PLL_INIT);
4934
4935         /* Wait for clock stabilization before accessing prph. */
4936         if ((error = wpi_clock_wait(sc)) != 0)
4937                 return error;
4938
4939         if ((error = wpi_nic_lock(sc)) != 0)
4940                 return error;
4941         /* Cleanup. */
4942         wpi_prph_write(sc, WPI_APMG_CLK_DIS, 0x00000400);
4943         wpi_prph_clrbits(sc, WPI_APMG_PS, 0x00000200);
4944
4945         /* Enable DMA and BSM (Bootstrap State Machine). */
4946         wpi_prph_write(sc, WPI_APMG_CLK_EN,
4947             WPI_APMG_CLK_CTRL_DMA_CLK_RQT | WPI_APMG_CLK_CTRL_BSM_CLK_RQT);
4948         DELAY(20);
4949         /* Disable L1-Active. */
4950         wpi_prph_setbits(sc, WPI_APMG_PCI_STT, WPI_APMG_PCI_STT_L1A_DIS);
4951         wpi_nic_unlock(sc);
4952
4953         return 0;
4954 }
4955
4956 static void
4957 wpi_apm_stop_master(struct wpi_softc *sc)
4958 {
4959         int ntries;
4960
4961         /* Stop busmaster DMA activity. */
4962         WPI_SETBITS(sc, WPI_RESET, WPI_RESET_STOP_MASTER);
4963          
4964         if ((WPI_READ(sc, WPI_GP_CNTRL) & WPI_GP_CNTRL_PS_MASK) ==
4965             WPI_GP_CNTRL_MAC_PS)
4966                 return; /* Already asleep. */
4967
4968         for (ntries = 0; ntries < 100; ntries++) {
4969                 if (WPI_READ(sc, WPI_RESET) & WPI_RESET_MASTER_DISABLED)
4970                         return;
4971                 DELAY(10);
4972         }
4973         device_printf(sc->sc_dev, "%s: timeout waiting for master\n",
4974             __func__);
4975 }
4976
4977 static void
4978 wpi_apm_stop(struct wpi_softc *sc)
4979 {
4980         wpi_apm_stop_master(sc);
4981
4982         /* Reset the entire device. */
4983         WPI_SETBITS(sc, WPI_RESET, WPI_RESET_SW);
4984         DELAY(10);
4985         /* Clear "initialization complete" bit. */
4986         WPI_CLRBITS(sc, WPI_GP_CNTRL, WPI_GP_CNTRL_INIT_DONE);
4987 }
4988
4989 static void
4990 wpi_nic_config(struct wpi_softc *sc)
4991 {
4992         uint32_t rev;
4993
4994         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4995
4996         /* voodoo from the Linux "driver".. */
4997         rev = pci_read_config(sc->sc_dev, PCIR_REVID, 1);
4998         if ((rev & 0xc0) == 0x40)
4999                 WPI_SETBITS(sc, WPI_HW_IF_CONFIG, WPI_HW_IF_CONFIG_ALM_MB);
5000         else if (!(rev & 0x80))
5001                 WPI_SETBITS(sc, WPI_HW_IF_CONFIG, WPI_HW_IF_CONFIG_ALM_MM);
5002
5003         if (sc->cap == 0x80)
5004                 WPI_SETBITS(sc, WPI_HW_IF_CONFIG, WPI_HW_IF_CONFIG_SKU_MRC);
5005
5006         if ((sc->rev & 0xf0) == 0xd0)
5007                 WPI_SETBITS(sc, WPI_HW_IF_CONFIG, WPI_HW_IF_CONFIG_REV_D);
5008         else
5009                 WPI_CLRBITS(sc, WPI_HW_IF_CONFIG, WPI_HW_IF_CONFIG_REV_D);
5010
5011         if (sc->type > 1)
5012                 WPI_SETBITS(sc, WPI_HW_IF_CONFIG, WPI_HW_IF_CONFIG_TYPE_B);
5013 }
5014
5015 static int
5016 wpi_hw_init(struct wpi_softc *sc)
5017 {
5018         int chnl, ntries, error;
5019
5020         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
5021
5022         /* Clear pending interrupts. */
5023         WPI_WRITE(sc, WPI_INT, 0xffffffff);
5024
5025         if ((error = wpi_apm_init(sc)) != 0) {
5026                 device_printf(sc->sc_dev,
5027                     "%s: could not power ON adapter, error %d\n", __func__,
5028                     error);
5029                 return error;
5030         }
5031
5032         /* Select VMAIN power source. */
5033         if ((error = wpi_nic_lock(sc)) != 0)
5034                 return error;
5035         wpi_prph_clrbits(sc, WPI_APMG_PS, WPI_APMG_PS_PWR_SRC_MASK);
5036         wpi_nic_unlock(sc);
5037         /* Spin until VMAIN gets selected. */
5038         for (ntries = 0; ntries < 5000; ntries++) {
5039                 if (WPI_READ(sc, WPI_GPIO_IN) & WPI_GPIO_IN_VMAIN)
5040                         break;
5041                 DELAY(10);
5042         }
5043         if (ntries == 5000) {
5044                 device_printf(sc->sc_dev, "timeout selecting power source\n");
5045                 return ETIMEDOUT;
5046         }
5047
5048         /* Perform adapter initialization. */
5049         wpi_nic_config(sc);
5050
5051         /* Initialize RX ring. */
5052         if ((error = wpi_nic_lock(sc)) != 0)
5053                 return error;
5054         /* Set physical address of RX ring. */
5055         WPI_WRITE(sc, WPI_FH_RX_BASE, sc->rxq.desc_dma.paddr);
5056         /* Set physical address of RX read pointer. */
5057         WPI_WRITE(sc, WPI_FH_RX_RPTR_ADDR, sc->shared_dma.paddr +
5058             offsetof(struct wpi_shared, next));
5059         WPI_WRITE(sc, WPI_FH_RX_WPTR, 0);
5060         /* Enable RX. */
5061         WPI_WRITE(sc, WPI_FH_RX_CONFIG,
5062             WPI_FH_RX_CONFIG_DMA_ENA |
5063             WPI_FH_RX_CONFIG_RDRBD_ENA |
5064             WPI_FH_RX_CONFIG_WRSTATUS_ENA |
5065             WPI_FH_RX_CONFIG_MAXFRAG |
5066             WPI_FH_RX_CONFIG_NRBD(WPI_RX_RING_COUNT_LOG) |
5067             WPI_FH_RX_CONFIG_IRQ_DST_HOST |
5068             WPI_FH_RX_CONFIG_IRQ_TIMEOUT(1));
5069         (void)WPI_READ(sc, WPI_FH_RSSR_TBL);    /* barrier */
5070         wpi_nic_unlock(sc);
5071         WPI_WRITE(sc, WPI_FH_RX_WPTR, (WPI_RX_RING_COUNT - 1) & ~7);
5072
5073         /* Initialize TX rings. */
5074         if ((error = wpi_nic_lock(sc)) != 0)
5075                 return error;
5076         wpi_prph_write(sc, WPI_ALM_SCHED_MODE, 2);      /* bypass mode */
5077         wpi_prph_write(sc, WPI_ALM_SCHED_ARASTAT, 1);   /* enable RA0 */
5078         /* Enable all 6 TX rings. */
5079         wpi_prph_write(sc, WPI_ALM_SCHED_TXFACT, 0x3f);
5080         wpi_prph_write(sc, WPI_ALM_SCHED_SBYPASS_MODE1, 0x10000);
5081         wpi_prph_write(sc, WPI_ALM_SCHED_SBYPASS_MODE2, 0x30002);
5082         wpi_prph_write(sc, WPI_ALM_SCHED_TXF4MF, 4);
5083         wpi_prph_write(sc, WPI_ALM_SCHED_TXF5MF, 5);
5084         /* Set physical address of TX rings. */
5085         WPI_WRITE(sc, WPI_FH_TX_BASE, sc->shared_dma.paddr);
5086         WPI_WRITE(sc, WPI_FH_MSG_CONFIG, 0xffff05a5);
5087
5088         /* Enable all DMA channels. */
5089         for (chnl = 0; chnl < WPI_NDMACHNLS; chnl++) {
5090                 WPI_WRITE(sc, WPI_FH_CBBC_CTRL(chnl), 0);
5091                 WPI_WRITE(sc, WPI_FH_CBBC_BASE(chnl), 0);
5092                 WPI_WRITE(sc, WPI_FH_TX_CONFIG(chnl), 0x80200008);
5093         }
5094         wpi_nic_unlock(sc);
5095         (void)WPI_READ(sc, WPI_FH_TX_BASE);     /* barrier */
5096
5097         /* Clear "radio off" and "commands blocked" bits. */
5098         WPI_WRITE(sc, WPI_UCODE_GP1_CLR, WPI_UCODE_GP1_RFKILL);
5099         WPI_WRITE(sc, WPI_UCODE_GP1_CLR, WPI_UCODE_GP1_CMD_BLOCKED);
5100
5101         /* Clear pending interrupts. */
5102         WPI_WRITE(sc, WPI_INT, 0xffffffff);
5103         /* Enable interrupts. */
5104         WPI_WRITE(sc, WPI_INT_MASK, WPI_INT_MASK_DEF);
5105
5106         /* _Really_ make sure "radio off" bit is cleared! */
5107         WPI_WRITE(sc, WPI_UCODE_GP1_CLR, WPI_UCODE_GP1_RFKILL);
5108         WPI_WRITE(sc, WPI_UCODE_GP1_CLR, WPI_UCODE_GP1_RFKILL);
5109
5110         if ((error = wpi_load_firmware(sc)) != 0) {
5111                 device_printf(sc->sc_dev,
5112                     "%s: could not load firmware, error %d\n", __func__,
5113                     error);
5114                 return error;
5115         }
5116         /* Wait at most one second for firmware alive notification. */
5117         if ((error = mtx_sleep(sc, &sc->sc_mtx, PCATCH, "wpiinit", hz)) != 0) {
5118                 device_printf(sc->sc_dev,
5119                     "%s: timeout waiting for adapter to initialize, error %d\n",
5120                     __func__, error);
5121                 return error;
5122         }
5123
5124         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
5125
5126         /* Do post-firmware initialization. */
5127         return wpi_post_alive(sc);
5128 }
5129
5130 static void
5131 wpi_hw_stop(struct wpi_softc *sc)
5132 {
5133         int chnl, qid, ntries;
5134
5135         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
5136
5137         if (WPI_READ(sc, WPI_UCODE_GP1) & WPI_UCODE_GP1_MAC_SLEEP)
5138                 wpi_nic_lock(sc);
5139
5140         WPI_WRITE(sc, WPI_RESET, WPI_RESET_NEVO);
5141
5142         /* Disable interrupts. */
5143         WPI_WRITE(sc, WPI_INT_MASK, 0);
5144         WPI_WRITE(sc, WPI_INT, 0xffffffff);
5145         WPI_WRITE(sc, WPI_FH_INT, 0xffffffff);
5146
5147         /* Make sure we no longer hold the NIC lock. */
5148         wpi_nic_unlock(sc);
5149
5150         if (wpi_nic_lock(sc) == 0) {
5151                 /* Stop TX scheduler. */
5152                 wpi_prph_write(sc, WPI_ALM_SCHED_MODE, 0);
5153                 wpi_prph_write(sc, WPI_ALM_SCHED_TXFACT, 0);
5154
5155                 /* Stop all DMA channels. */
5156                 for (chnl = 0; chnl < WPI_NDMACHNLS; chnl++) {
5157                         WPI_WRITE(sc, WPI_FH_TX_CONFIG(chnl), 0);
5158                         for (ntries = 0; ntries < 200; ntries++) {
5159                                 if (WPI_READ(sc, WPI_FH_TX_STATUS) &
5160                                     WPI_FH_TX_STATUS_IDLE(chnl))
5161                                         break;
5162                                 DELAY(10);
5163                         }
5164                 }
5165                 wpi_nic_unlock(sc);
5166         }
5167
5168         /* Stop RX ring. */
5169         wpi_reset_rx_ring(sc);
5170
5171         /* Reset all TX rings. */
5172         for (qid = 0; qid < WPI_NTXQUEUES; qid++)
5173                 wpi_reset_tx_ring(sc, &sc->txq[qid]);
5174
5175         if (wpi_nic_lock(sc) == 0) {
5176                 wpi_prph_write(sc, WPI_APMG_CLK_DIS,
5177                     WPI_APMG_CLK_CTRL_DMA_CLK_RQT);
5178                 wpi_nic_unlock(sc);
5179         }
5180         DELAY(5);
5181         /* Power OFF adapter. */
5182         wpi_apm_stop(sc);
5183 }
5184
5185 static void
5186 wpi_radio_on(void *arg0, int pending)
5187 {
5188         struct wpi_softc *sc = arg0;
5189         struct ifnet *ifp = sc->sc_ifp;
5190         struct ieee80211com *ic = ifp->if_l2com;
5191         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
5192
5193         device_printf(sc->sc_dev, "RF switch: radio enabled\n");
5194
5195         if (vap != NULL) {
5196                 wpi_init(sc);
5197                 ieee80211_init(vap);
5198         }
5199
5200         if (WPI_READ(sc, WPI_GP_CNTRL) & WPI_GP_CNTRL_RFKILL) {
5201                 WPI_LOCK(sc);
5202                 callout_stop(&sc->watchdog_rfkill);
5203                 WPI_UNLOCK(sc);
5204         }
5205 }
5206
5207 static void
5208 wpi_radio_off(void *arg0, int pending)
5209 {
5210         struct wpi_softc *sc = arg0;
5211         struct ifnet *ifp = sc->sc_ifp;
5212         struct ieee80211com *ic = ifp->if_l2com;
5213         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
5214
5215         device_printf(sc->sc_dev, "RF switch: radio disabled\n");
5216
5217         wpi_stop(sc);
5218         if (vap != NULL)
5219                 ieee80211_stop(vap);
5220
5221         WPI_LOCK(sc);
5222         callout_reset(&sc->watchdog_rfkill, hz, wpi_watchdog_rfkill, sc);
5223         WPI_UNLOCK(sc);
5224 }
5225
5226 static void
5227 wpi_init(void *arg)
5228 {
5229         struct wpi_softc *sc = arg;
5230         struct ifnet *ifp = sc->sc_ifp;
5231         struct ieee80211com *ic = ifp->if_l2com;
5232         int error;
5233
5234         WPI_LOCK(sc);
5235
5236         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
5237
5238         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0)
5239                 goto end;
5240
5241         /* Check that the radio is not disabled by hardware switch. */
5242         if (!(WPI_READ(sc, WPI_GP_CNTRL) & WPI_GP_CNTRL_RFKILL)) {
5243                 device_printf(sc->sc_dev,
5244                     "RF switch: radio disabled (%s)\n", __func__);
5245                 callout_reset(&sc->watchdog_rfkill, hz, wpi_watchdog_rfkill,
5246                     sc);
5247                 goto end;
5248         }
5249
5250         /* Read firmware images from the filesystem. */
5251         if ((error = wpi_read_firmware(sc)) != 0) {
5252                 device_printf(sc->sc_dev,
5253                     "%s: could not read firmware, error %d\n", __func__,
5254                     error);
5255                 goto fail;
5256         }
5257
5258         /* Initialize hardware and upload firmware. */
5259         error = wpi_hw_init(sc);
5260         wpi_unload_firmware(sc);
5261         if (error != 0) {
5262                 device_printf(sc->sc_dev,
5263                     "%s: could not initialize hardware, error %d\n", __func__,
5264                     error);
5265                 goto fail;
5266         }
5267
5268         /* Configure adapter now that it is ready. */
5269         sc->txq_active = 1;
5270         if ((error = wpi_config(sc)) != 0) {
5271                 device_printf(sc->sc_dev,
5272                     "%s: could not configure device, error %d\n", __func__,
5273                     error);
5274                 goto fail;
5275         }
5276
5277         IF_LOCK(&ifp->if_snd);
5278         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5279         ifp->if_drv_flags |= IFF_DRV_RUNNING;
5280         IF_UNLOCK(&ifp->if_snd);
5281
5282         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
5283
5284         WPI_UNLOCK(sc);
5285
5286         ieee80211_start_all(ic);
5287
5288         return;
5289
5290 fail:   wpi_stop_locked(sc);
5291 end:    DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
5292         WPI_UNLOCK(sc);
5293 }
5294
5295 static void
5296 wpi_stop_locked(struct wpi_softc *sc)
5297 {
5298         struct ifnet *ifp = sc->sc_ifp;
5299
5300         WPI_LOCK_ASSERT(sc);
5301
5302         WPI_TXQ_LOCK(sc);
5303         sc->txq_active = 0;
5304         WPI_TXQ_UNLOCK(sc);
5305
5306         WPI_TXQ_STATE_LOCK(sc);
5307         callout_stop(&sc->tx_timeout);
5308         WPI_TXQ_STATE_UNLOCK(sc);
5309
5310         WPI_RXON_LOCK(sc);
5311         callout_stop(&sc->scan_timeout);
5312         callout_stop(&sc->calib_to);
5313         WPI_RXON_UNLOCK(sc);
5314
5315         IF_LOCK(&ifp->if_snd);
5316         ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
5317         IF_UNLOCK(&ifp->if_snd);
5318
5319         /* Power OFF hardware. */
5320         wpi_hw_stop(sc);
5321 }
5322
5323 static void
5324 wpi_stop(struct wpi_softc *sc)
5325 {
5326         WPI_LOCK(sc);
5327         wpi_stop_locked(sc);
5328         WPI_UNLOCK(sc);
5329 }
5330
5331 /*
5332  * Callback from net80211 to start a scan.
5333  */
5334 static void
5335 wpi_scan_start(struct ieee80211com *ic)
5336 {
5337         struct wpi_softc *sc = ic->ic_ifp->if_softc;
5338
5339         wpi_set_led(sc, WPI_LED_LINK, 20, 2);
5340 }
5341
5342 /*
5343  * Callback from net80211 to terminate a scan.
5344  */
5345 static void
5346 wpi_scan_end(struct ieee80211com *ic)
5347 {
5348         struct ifnet *ifp = ic->ic_ifp;
5349         struct wpi_softc *sc = ifp->if_softc;
5350         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
5351
5352         if (vap->iv_state == IEEE80211_S_RUN)
5353                 wpi_set_led(sc, WPI_LED_LINK, 0, 1);
5354 }
5355
5356 /**
5357  * Called by the net80211 framework to indicate to the driver
5358  * that the channel should be changed
5359  */
5360 static void
5361 wpi_set_channel(struct ieee80211com *ic)
5362 {
5363         const struct ieee80211_channel *c = ic->ic_curchan;
5364         struct ifnet *ifp = ic->ic_ifp;
5365         struct wpi_softc *sc = ifp->if_softc;
5366         int error;
5367
5368         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
5369
5370         WPI_LOCK(sc);
5371         sc->sc_rxtap.wr_chan_freq = htole16(c->ic_freq);
5372         sc->sc_rxtap.wr_chan_flags = htole16(c->ic_flags);
5373         WPI_UNLOCK(sc);
5374         WPI_TX_LOCK(sc);
5375         sc->sc_txtap.wt_chan_freq = htole16(c->ic_freq);
5376         sc->sc_txtap.wt_chan_flags = htole16(c->ic_flags);
5377         WPI_TX_UNLOCK(sc);
5378
5379         /*
5380          * Only need to set the channel in Monitor mode. AP scanning and auth
5381          * are already taken care of by their respective firmware commands.
5382          */
5383         if (ic->ic_opmode == IEEE80211_M_MONITOR) {
5384                 WPI_RXON_LOCK(sc);
5385                 sc->rxon.chan = ieee80211_chan2ieee(ic, c);
5386                 if (IEEE80211_IS_CHAN_2GHZ(c)) {
5387                         sc->rxon.flags |= htole32(WPI_RXON_AUTO |
5388                             WPI_RXON_24GHZ);
5389                 } else {
5390                         sc->rxon.flags &= ~htole32(WPI_RXON_AUTO |
5391                             WPI_RXON_24GHZ);
5392                 }
5393                 if ((error = wpi_send_rxon(sc, 0, 1)) != 0)
5394                         device_printf(sc->sc_dev,
5395                             "%s: error %d setting channel\n", __func__,
5396                             error);
5397                 WPI_RXON_UNLOCK(sc);
5398         }
5399 }
5400
5401 /**
5402  * Called by net80211 to indicate that we need to scan the current
5403  * channel. The channel is previously be set via the wpi_set_channel
5404  * callback.
5405  */
5406 static void
5407 wpi_scan_curchan(struct ieee80211_scan_state *ss, unsigned long maxdwell)
5408 {
5409         struct ieee80211vap *vap = ss->ss_vap;
5410         struct ieee80211com *ic = vap->iv_ic;
5411         struct wpi_softc *sc = ic->ic_ifp->if_softc;
5412         int error;
5413
5414         WPI_RXON_LOCK(sc);
5415         error = wpi_scan(sc, ic->ic_curchan);
5416         WPI_RXON_UNLOCK(sc);
5417         if (error != 0)
5418                 ieee80211_cancel_scan(vap);
5419 }
5420
5421 /**
5422  * Called by the net80211 framework to indicate
5423  * the minimum dwell time has been met, terminate the scan.
5424  * We don't actually terminate the scan as the firmware will notify
5425  * us when it's finished and we have no way to interrupt it.
5426  */
5427 static void
5428 wpi_scan_mindwell(struct ieee80211_scan_state *ss)
5429 {
5430         /* NB: don't try to abort scan; wait for firmware to finish */
5431 }
5432
5433 static void
5434 wpi_hw_reset(void *arg, int pending)
5435 {
5436         struct wpi_softc *sc = arg;
5437         struct ifnet *ifp = sc->sc_ifp;
5438         struct ieee80211com *ic = ifp->if_l2com;
5439         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
5440
5441         DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
5442
5443         if (vap != NULL && (ic->ic_flags & IEEE80211_F_SCAN))
5444                 ieee80211_cancel_scan(vap);
5445
5446         wpi_stop(sc);
5447         if (vap != NULL)
5448                 ieee80211_stop(vap);
5449         wpi_init(sc);
5450         if (vap != NULL)
5451                 ieee80211_init(vap);
5452 }