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