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