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