]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/iwi/if_iwi.c
add -n option to suppress clearing the build tree and add -DNO_CLEAN
[FreeBSD/FreeBSD.git] / sys / dev / iwi / if_iwi.c
1 /*-
2  * Copyright (c) 2004, 2005
3  *      Damien Bergamini <damien.bergamini@free.fr>. All rights reserved.
4  * Copyright (c) 2005-2006 Sam Leffler, Errno Consulting
5  * Copyright (c) 2007 Andrew Thompson <thompsa@FreeBSD.org>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice unmodified, this list of conditions, and the following
12  *    disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32
33 /*-
34  * Intel(R) PRO/Wireless 2200BG/2225BG/2915ABG driver
35  * http://www.intel.com/network/connectivity/products/wireless/prowireless_mobile.htm
36  */
37
38 #include <sys/param.h>
39 #include <sys/sysctl.h>
40 #include <sys/sockio.h>
41 #include <sys/mbuf.h>
42 #include <sys/kernel.h>
43 #include <sys/socket.h>
44 #include <sys/systm.h>
45 #include <sys/malloc.h>
46 #include <sys/lock.h>
47 #include <sys/mutex.h>
48 #include <sys/module.h>
49 #include <sys/bus.h>
50 #include <sys/endian.h>
51 #include <sys/proc.h>
52 #include <sys/mount.h>
53 #include <sys/namei.h>
54 #include <sys/linker.h>
55 #include <sys/firmware.h>
56 #include <sys/kthread.h>
57 #include <sys/taskqueue.h>
58
59 #include <machine/bus.h>
60 #include <machine/resource.h>
61 #include <sys/rman.h>
62
63 #include <dev/pci/pcireg.h>
64 #include <dev/pci/pcivar.h>
65
66 #include <net/bpf.h>
67 #include <net/if.h>
68 #include <net/if_arp.h>
69 #include <net/ethernet.h>
70 #include <net/if_dl.h>
71 #include <net/if_media.h>
72 #include <net/if_types.h>
73
74 #include <net80211/ieee80211_var.h>
75 #include <net80211/ieee80211_radiotap.h>
76 #include <net80211/ieee80211_input.h>
77 #include <net80211/ieee80211_regdomain.h>
78
79 #include <netinet/in.h>
80 #include <netinet/in_systm.h>
81 #include <netinet/in_var.h>
82 #include <netinet/ip.h>
83 #include <netinet/if_ether.h>
84
85 #include <dev/iwi/if_iwireg.h>
86 #include <dev/iwi/if_iwivar.h>
87
88 #define IWI_DEBUG
89 #ifdef IWI_DEBUG
90 #define DPRINTF(x)      do { if (iwi_debug > 0) printf x; } while (0)
91 #define DPRINTFN(n, x)  do { if (iwi_debug >= (n)) printf x; } while (0)
92 int iwi_debug = 0;
93 SYSCTL_INT(_debug, OID_AUTO, iwi, CTLFLAG_RW, &iwi_debug, 0, "iwi debug level");
94
95 static const char *iwi_fw_states[] = {
96         "IDLE",                 /* IWI_FW_IDLE */
97         "LOADING",              /* IWI_FW_LOADING */
98         "ASSOCIATING",          /* IWI_FW_ASSOCIATING */
99         "DISASSOCIATING",       /* IWI_FW_DISASSOCIATING */
100         "SCANNING",             /* IWI_FW_SCANNING */
101 };
102 #else
103 #define DPRINTF(x)
104 #define DPRINTFN(n, x)
105 #endif
106
107 MODULE_DEPEND(iwi, pci,  1, 1, 1);
108 MODULE_DEPEND(iwi, wlan, 1, 1, 1);
109 MODULE_DEPEND(iwi, firmware, 1, 1, 1);
110
111 enum {
112         IWI_LED_TX,
113         IWI_LED_RX,
114         IWI_LED_POLL,
115 };
116
117 struct iwi_ident {
118         uint16_t        vendor;
119         uint16_t        device;
120         const char      *name;
121 };
122
123 static const struct iwi_ident iwi_ident_table[] = {
124         { 0x8086, 0x4220, "Intel(R) PRO/Wireless 2200BG" },
125         { 0x8086, 0x4221, "Intel(R) PRO/Wireless 2225BG" },
126         { 0x8086, 0x4223, "Intel(R) PRO/Wireless 2915ABG" },
127         { 0x8086, 0x4224, "Intel(R) PRO/Wireless 2915ABG" },
128
129         { 0, 0, NULL }
130 };
131
132 static struct ieee80211vap *iwi_vap_create(struct ieee80211com *,
133                     const char name[IFNAMSIZ], int unit, int opmode, int flags,
134                     const uint8_t bssid[IEEE80211_ADDR_LEN],
135                     const uint8_t mac[IEEE80211_ADDR_LEN]);
136 static void     iwi_vap_delete(struct ieee80211vap *);
137 static void     iwi_dma_map_addr(void *, bus_dma_segment_t *, int, int);
138 static int      iwi_alloc_cmd_ring(struct iwi_softc *, struct iwi_cmd_ring *,
139                     int);
140 static void     iwi_reset_cmd_ring(struct iwi_softc *, struct iwi_cmd_ring *);
141 static void     iwi_free_cmd_ring(struct iwi_softc *, struct iwi_cmd_ring *);
142 static int      iwi_alloc_tx_ring(struct iwi_softc *, struct iwi_tx_ring *,
143                     int, bus_addr_t, bus_addr_t);
144 static void     iwi_reset_tx_ring(struct iwi_softc *, struct iwi_tx_ring *);
145 static void     iwi_free_tx_ring(struct iwi_softc *, struct iwi_tx_ring *);
146 static int      iwi_alloc_rx_ring(struct iwi_softc *, struct iwi_rx_ring *,
147                     int);
148 static void     iwi_reset_rx_ring(struct iwi_softc *, struct iwi_rx_ring *);
149 static void     iwi_free_rx_ring(struct iwi_softc *, struct iwi_rx_ring *);
150 static struct ieee80211_node *iwi_node_alloc(struct ieee80211vap *,
151                     const uint8_t [IEEE80211_ADDR_LEN]);
152 static void     iwi_node_free(struct ieee80211_node *);
153 static void     iwi_media_status(struct ifnet *, struct ifmediareq *);
154 static int      iwi_newstate(struct ieee80211vap *, enum ieee80211_state, int);
155 static void     iwi_wme_init(struct iwi_softc *);
156 static int      iwi_wme_setparams(struct iwi_softc *, struct ieee80211com *);
157 static int      iwi_wme_update(struct ieee80211com *);
158 static uint16_t iwi_read_prom_word(struct iwi_softc *, uint8_t);
159 static void     iwi_frame_intr(struct iwi_softc *, struct iwi_rx_data *, int,
160                     struct iwi_frame *);
161 static void     iwi_authsuccess(void *, int);
162 static void     iwi_assocsuccess(void *, int);
163 static void     iwi_assocfailed(void *, int);
164 static void     iwi_notification_intr(struct iwi_softc *, struct iwi_notif *);
165 static void     iwi_rx_intr(struct iwi_softc *);
166 static void     iwi_tx_intr(struct iwi_softc *, struct iwi_tx_ring *);
167 static void     iwi_intr(void *);
168 static int      iwi_cmd(struct iwi_softc *, uint8_t, void *, uint8_t);
169 static void     iwi_write_ibssnode(struct iwi_softc *, const u_int8_t [], int);
170 static int      iwi_tx_start(struct ifnet *, struct mbuf *,
171                     struct ieee80211_node *, int);
172 static int      iwi_raw_xmit(struct ieee80211_node *, struct mbuf *,
173                     const struct ieee80211_bpf_params *);
174 static void     iwi_start_locked(struct ifnet *);
175 static void     iwi_start(struct ifnet *);
176 static void     iwi_watchdog(void *);
177 static int      iwi_ioctl(struct ifnet *, u_long, caddr_t);
178 static void     iwi_stop_master(struct iwi_softc *);
179 static int      iwi_reset(struct iwi_softc *);
180 static int      iwi_load_ucode(struct iwi_softc *, const struct iwi_fw *);
181 static int      iwi_load_firmware(struct iwi_softc *, const struct iwi_fw *);
182 static void     iwi_release_fw_dma(struct iwi_softc *sc);
183 static int      iwi_config(struct iwi_softc *);
184 static int      iwi_get_firmware(struct iwi_softc *, enum ieee80211_opmode);
185 static void     iwi_put_firmware(struct iwi_softc *);
186 static int      iwi_scanchan(struct iwi_softc *, unsigned long, int);
187 static void     iwi_scan_start(struct ieee80211com *);
188 static void     iwi_scan_end(struct ieee80211com *);
189 static void     iwi_scanabort(void *, int);
190 static void     iwi_set_channel(struct ieee80211com *);
191 static void     iwi_scan_curchan(struct ieee80211_scan_state *, unsigned long maxdwell);
192 #if 0
193 static void     iwi_scan_allchan(struct ieee80211com *, unsigned long maxdwell);
194 #endif
195 static void     iwi_scan_mindwell(struct ieee80211_scan_state *);
196 static void     iwi_ops(void *, int);
197 static int      iwi_queue_cmd(struct iwi_softc *, int, unsigned long);
198 static int      iwi_auth_and_assoc(struct iwi_softc *, struct ieee80211vap *);
199 static int      iwi_disassociate(struct iwi_softc *, int quiet);
200 static void     iwi_init_locked(struct iwi_softc *);
201 static void     iwi_init(void *);
202 static int      iwi_init_fw_dma(struct iwi_softc *, int);
203 static void     iwi_stop_locked(void *);
204 static void     iwi_stop(struct iwi_softc *);
205 static void     iwi_restart(void *, int);
206 static int      iwi_getrfkill(struct iwi_softc *);
207 static void     iwi_radio_on(void *, int);
208 static void     iwi_radio_off(void *, int);
209 static void     iwi_sysctlattach(struct iwi_softc *);
210 static void     iwi_led_event(struct iwi_softc *, int);
211 static void     iwi_ledattach(struct iwi_softc *);
212
213 static int iwi_probe(device_t);
214 static int iwi_attach(device_t);
215 static int iwi_detach(device_t);
216 static int iwi_shutdown(device_t);
217 static int iwi_suspend(device_t);
218 static int iwi_resume(device_t);
219
220 static device_method_t iwi_methods[] = {
221         /* Device interface */
222         DEVMETHOD(device_probe,         iwi_probe),
223         DEVMETHOD(device_attach,        iwi_attach),
224         DEVMETHOD(device_detach,        iwi_detach),
225         DEVMETHOD(device_shutdown,      iwi_shutdown),
226         DEVMETHOD(device_suspend,       iwi_suspend),
227         DEVMETHOD(device_resume,        iwi_resume),
228
229         { 0, 0 }
230 };
231
232 static driver_t iwi_driver = {
233         "iwi",
234         iwi_methods,
235         sizeof (struct iwi_softc)
236 };
237
238 static devclass_t iwi_devclass;
239
240 DRIVER_MODULE(iwi, pci, iwi_driver, iwi_devclass, 0, 0);
241
242 static __inline uint8_t
243 MEM_READ_1(struct iwi_softc *sc, uint32_t addr)
244 {
245         CSR_WRITE_4(sc, IWI_CSR_INDIRECT_ADDR, addr);
246         return CSR_READ_1(sc, IWI_CSR_INDIRECT_DATA);
247 }
248
249 static __inline uint32_t
250 MEM_READ_4(struct iwi_softc *sc, uint32_t addr)
251 {
252         CSR_WRITE_4(sc, IWI_CSR_INDIRECT_ADDR, addr);
253         return CSR_READ_4(sc, IWI_CSR_INDIRECT_DATA);
254 }
255
256 static int
257 iwi_probe(device_t dev)
258 {
259         const struct iwi_ident *ident;
260
261         for (ident = iwi_ident_table; ident->name != NULL; ident++) {
262                 if (pci_get_vendor(dev) == ident->vendor &&
263                     pci_get_device(dev) == ident->device) {
264                         device_set_desc(dev, ident->name);
265                         return 0;
266                 }
267         }
268         return ENXIO;
269 }
270
271 /* Base Address Register */
272 #define IWI_PCI_BAR0    0x10
273
274 static int
275 iwi_attach(device_t dev)
276 {
277         struct iwi_softc *sc = device_get_softc(dev);
278         struct ifnet *ifp;
279         struct ieee80211com *ic;
280         uint16_t val;
281         int i, error;
282         uint8_t bands;
283
284         sc->sc_dev = dev;
285
286         ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
287         if (ifp == NULL) {
288                 device_printf(dev, "can not if_alloc()\n");
289                 return ENXIO;
290         }
291         ic = ifp->if_l2com;
292
293         IWI_LOCK_INIT(sc);
294         IWI_CMD_LOCK_INIT(sc);
295
296         sc->sc_unr = new_unrhdr(1, IWI_MAX_IBSSNODE-1, &sc->sc_mtx);
297
298         sc->sc_tq = taskqueue_create("iwi_taskq", M_NOWAIT | M_ZERO,
299                 taskqueue_thread_enqueue, &sc->sc_tq);
300         taskqueue_start_threads(&sc->sc_tq, 1, PI_NET, "%s taskq",
301                 device_get_nameunit(dev));
302         sc->sc_tq2 = taskqueue_create("iwi_taskq2", M_NOWAIT | M_ZERO,
303                 taskqueue_thread_enqueue, &sc->sc_tq2);
304         taskqueue_start_threads(&sc->sc_tq2, 1, PI_NET, "%s taskq2",
305                 device_get_nameunit(dev));
306
307         TASK_INIT(&sc->sc_radiontask, 0, iwi_radio_on, sc);
308         TASK_INIT(&sc->sc_radiofftask, 0, iwi_radio_off, sc);
309         TASK_INIT(&sc->sc_restarttask, 0, iwi_restart, sc);
310         TASK_INIT(&sc->sc_opstask, 0, iwi_ops, sc);
311         TASK_INIT(&sc->sc_scanaborttask, 0, iwi_scanabort, sc);
312         callout_init_mtx(&sc->sc_wdtimer, &sc->sc_mtx, 0);
313         callout_init_mtx(&sc->sc_rftimer, &sc->sc_mtx, 0);
314
315         if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
316                 device_printf(dev, "chip is in D%d power mode "
317                     "-- setting to D0\n", pci_get_powerstate(dev));
318                 pci_set_powerstate(dev, PCI_POWERSTATE_D0);
319         }
320
321         pci_write_config(dev, 0x41, 0, 1);
322
323         /* enable bus-mastering */
324         pci_enable_busmaster(dev);
325
326         sc->mem_rid = IWI_PCI_BAR0;
327         sc->mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &sc->mem_rid,
328             RF_ACTIVE);
329         if (sc->mem == NULL) {
330                 device_printf(dev, "could not allocate memory resource\n");
331                 goto fail;
332         }
333
334         sc->sc_st = rman_get_bustag(sc->mem);
335         sc->sc_sh = rman_get_bushandle(sc->mem);
336
337         sc->irq_rid = 0;
338         sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->irq_rid,
339             RF_ACTIVE | RF_SHAREABLE);
340         if (sc->irq == NULL) {
341                 device_printf(dev, "could not allocate interrupt resource\n");
342                 goto fail;
343         }
344
345         if (iwi_reset(sc) != 0) {
346                 device_printf(dev, "could not reset adapter\n");
347                 goto fail;
348         }
349
350         /*
351          * Allocate rings.
352          */
353         if (iwi_alloc_cmd_ring(sc, &sc->cmdq, IWI_CMD_RING_COUNT) != 0) {
354                 device_printf(dev, "could not allocate Cmd ring\n");
355                 goto fail;
356         }
357
358         for (i = 0; i < 4; i++) {
359                 error = iwi_alloc_tx_ring(sc, &sc->txq[i], IWI_TX_RING_COUNT,
360                     IWI_CSR_TX1_RIDX + i * 4,
361                     IWI_CSR_TX1_WIDX + i * 4);
362                 if (error != 0) {
363                         device_printf(dev, "could not allocate Tx ring %d\n",
364                                 i+i);
365                         goto fail;
366                 }
367         }
368
369         if (iwi_alloc_rx_ring(sc, &sc->rxq, IWI_RX_RING_COUNT) != 0) {
370                 device_printf(dev, "could not allocate Rx ring\n");
371                 goto fail;
372         }
373
374         iwi_wme_init(sc);
375
376         ifp->if_softc = sc;
377         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
378         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
379         ifp->if_init = iwi_init;
380         ifp->if_ioctl = iwi_ioctl;
381         ifp->if_start = iwi_start;
382         IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
383         ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
384         IFQ_SET_READY(&ifp->if_snd);
385
386         ic->ic_ifp = ifp;
387         ic->ic_opmode = IEEE80211_M_STA;
388         ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
389
390         /* set device capabilities */
391         ic->ic_caps =
392               IEEE80211_C_STA           /* station mode supported */
393             | IEEE80211_C_IBSS          /* IBSS mode supported */
394             | IEEE80211_C_MONITOR       /* monitor mode supported */
395             | IEEE80211_C_PMGT          /* power save supported */
396             | IEEE80211_C_SHPREAMBLE    /* short preamble supported */
397             | IEEE80211_C_WPA           /* 802.11i */
398             | IEEE80211_C_WME           /* 802.11e */
399 #if 0
400             | IEEE80211_C_BGSCAN        /* capable of bg scanning */
401 #endif
402             ;
403
404         /* read MAC address from EEPROM */
405         val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 0);
406         ic->ic_myaddr[0] = val & 0xff;
407         ic->ic_myaddr[1] = val >> 8;
408         val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 1);
409         ic->ic_myaddr[2] = val & 0xff;
410         ic->ic_myaddr[3] = val >> 8;
411         val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 2);
412         ic->ic_myaddr[4] = val & 0xff;
413         ic->ic_myaddr[5] = val >> 8;
414         
415         bands = 0;
416         setbit(&bands, IEEE80211_MODE_11B);
417         setbit(&bands, IEEE80211_MODE_11G);
418         if (pci_get_device(dev) >= 0x4223) 
419                 setbit(&bands, IEEE80211_MODE_11A);
420         ieee80211_init_channels(ic, NULL, &bands);
421
422         ieee80211_ifattach(ic);
423         /* override default methods */
424         ic->ic_node_alloc = iwi_node_alloc;
425         sc->sc_node_free = ic->ic_node_free;
426         ic->ic_node_free = iwi_node_free;
427         ic->ic_raw_xmit = iwi_raw_xmit;
428         ic->ic_scan_start = iwi_scan_start;
429         ic->ic_scan_end = iwi_scan_end;
430         ic->ic_set_channel = iwi_set_channel;
431         ic->ic_scan_curchan = iwi_scan_curchan;
432         ic->ic_scan_mindwell = iwi_scan_mindwell;
433         ic->ic_wme.wme_update = iwi_wme_update;
434
435         ic->ic_vap_create = iwi_vap_create;
436         ic->ic_vap_delete = iwi_vap_delete;
437
438         bpfattach(ifp, DLT_IEEE802_11_RADIO,
439             sizeof (struct ieee80211_frame) + sizeof (sc->sc_txtap));
440
441         sc->sc_rxtap_len = sizeof sc->sc_rxtap;
442         sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
443         sc->sc_rxtap.wr_ihdr.it_present = htole32(IWI_RX_RADIOTAP_PRESENT);
444
445         sc->sc_txtap_len = sizeof sc->sc_txtap;
446         sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
447         sc->sc_txtap.wt_ihdr.it_present = htole32(IWI_TX_RADIOTAP_PRESENT);
448
449         iwi_sysctlattach(sc);
450         iwi_ledattach(sc);
451
452         /*
453          * Hook our interrupt after all initialization is complete.
454          */
455         error = bus_setup_intr(dev, sc->irq, INTR_TYPE_NET | INTR_MPSAFE,
456             NULL, iwi_intr, sc, &sc->sc_ih);
457         if (error != 0) {
458                 device_printf(dev, "could not set up interrupt\n");
459                 goto fail;
460         }
461
462         if (bootverbose)
463                 ieee80211_announce(ic);
464
465         return 0;
466 fail:
467         /* XXX fix */
468         iwi_detach(dev);
469         return ENXIO;
470 }
471
472 static int
473 iwi_detach(device_t dev)
474 {
475         struct iwi_softc *sc = device_get_softc(dev);
476         struct ifnet *ifp = sc->sc_ifp;
477         struct ieee80211com *ic = ifp->if_l2com;
478
479         iwi_stop(sc);
480
481         bpfdetach(ifp);
482         ieee80211_ifdetach(ic);
483
484         /* NB: do early to drain any pending tasks */
485         taskqueue_free(sc->sc_tq);
486         taskqueue_free(sc->sc_tq2);
487
488         iwi_put_firmware(sc);
489         iwi_release_fw_dma(sc);
490
491         iwi_free_cmd_ring(sc, &sc->cmdq);
492         iwi_free_tx_ring(sc, &sc->txq[0]);
493         iwi_free_tx_ring(sc, &sc->txq[1]);
494         iwi_free_tx_ring(sc, &sc->txq[2]);
495         iwi_free_tx_ring(sc, &sc->txq[3]);
496         iwi_free_rx_ring(sc, &sc->rxq);
497
498         bus_teardown_intr(dev, sc->irq, sc->sc_ih);
499         bus_release_resource(dev, SYS_RES_IRQ, sc->irq_rid, sc->irq);
500
501         bus_release_resource(dev, SYS_RES_MEMORY, sc->mem_rid, sc->mem);
502
503         delete_unrhdr(sc->sc_unr);
504
505         IWI_LOCK_DESTROY(sc);
506         IWI_CMD_LOCK_DESTROY(sc);
507
508         if_free(ifp);
509
510         return 0;
511 }
512
513 static struct ieee80211vap *
514 iwi_vap_create(struct ieee80211com *ic,
515         const char name[IFNAMSIZ], int unit, int opmode, int flags,
516         const uint8_t bssid[IEEE80211_ADDR_LEN],
517         const uint8_t mac[IEEE80211_ADDR_LEN])
518 {
519         struct ifnet *ifp = ic->ic_ifp;
520         struct iwi_softc *sc = ifp->if_softc;
521         struct iwi_vap *ivp;
522         struct ieee80211vap *vap;
523         int i;
524
525         if (!TAILQ_EMPTY(&ic->ic_vaps))         /* only one at a time */
526                 return NULL;
527         /*
528          * Get firmware image (and possibly dma memory) on mode change.
529          */
530         if (iwi_get_firmware(sc, opmode))
531                 return NULL;
532         /* allocate DMA memory for mapping firmware image */
533         i = sc->fw_fw.size;
534         if (sc->fw_boot.size > i)
535                 i = sc->fw_boot.size;
536         /* XXX do we dma the ucode as well ? */
537         if (sc->fw_uc.size > i)
538                 i = sc->fw_uc.size;
539         if (iwi_init_fw_dma(sc, i))
540                 return NULL;
541
542         ivp = (struct iwi_vap *) malloc(sizeof(struct iwi_vap),
543             M_80211_VAP, M_NOWAIT | M_ZERO);
544         if (ivp == NULL)
545                 return NULL;
546         vap = &ivp->iwi_vap;
547         ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid, mac);
548         /* override the default, the setting comes from the linux driver */
549         vap->iv_bmissthreshold = 24;
550         /* override with driver methods */
551         ivp->iwi_newstate = vap->iv_newstate;
552         vap->iv_newstate = iwi_newstate;
553
554         TASK_INIT(&ivp->iwi_authsuccess_task, 0, iwi_authsuccess, vap);
555         TASK_INIT(&ivp->iwi_assocsuccess_task, 0, iwi_assocsuccess, vap);
556         TASK_INIT(&ivp->iwi_assocfailed_task, 0, iwi_assocfailed, vap);
557
558         /* complete setup */
559         ieee80211_vap_attach(vap, ieee80211_media_change, iwi_media_status);
560         ic->ic_opmode = opmode;
561         return vap;
562 }
563
564 static void
565 iwi_vap_delete(struct ieee80211vap *vap)
566 {
567         struct iwi_vap *ivp = IWI_VAP(vap);
568
569         ieee80211_vap_detach(vap);
570         free(ivp, M_80211_VAP);
571 }
572
573 static void
574 iwi_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
575 {
576         if (error != 0)
577                 return;
578
579         KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
580
581         *(bus_addr_t *)arg = segs[0].ds_addr;
582 }
583
584 static int
585 iwi_alloc_cmd_ring(struct iwi_softc *sc, struct iwi_cmd_ring *ring, int count)
586 {
587         int error;
588
589         ring->count = count;
590         ring->queued = 0;
591         ring->cur = ring->next = 0;
592
593         error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 4, 0,
594             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
595             count * IWI_CMD_DESC_SIZE, 1, count * IWI_CMD_DESC_SIZE, 0, 
596             NULL, NULL, &ring->desc_dmat);
597         if (error != 0) {
598                 device_printf(sc->sc_dev, "could not create desc DMA tag\n");
599                 goto fail;
600         }
601
602         error = bus_dmamem_alloc(ring->desc_dmat, (void **)&ring->desc,
603             BUS_DMA_NOWAIT | BUS_DMA_ZERO, &ring->desc_map);
604         if (error != 0) {
605                 device_printf(sc->sc_dev, "could not allocate DMA memory\n");
606                 goto fail;
607         }
608
609         error = bus_dmamap_load(ring->desc_dmat, ring->desc_map, ring->desc,
610             count * IWI_CMD_DESC_SIZE, iwi_dma_map_addr, &ring->physaddr, 0);
611         if (error != 0) {
612                 device_printf(sc->sc_dev, "could not load desc DMA map\n");
613                 goto fail;
614         }
615
616         return 0;
617
618 fail:   iwi_free_cmd_ring(sc, ring);
619         return error;
620 }
621
622 static void
623 iwi_reset_cmd_ring(struct iwi_softc *sc, struct iwi_cmd_ring *ring)
624 {
625         ring->queued = 0;
626         ring->cur = ring->next = 0;
627 }
628
629 static void
630 iwi_free_cmd_ring(struct iwi_softc *sc, struct iwi_cmd_ring *ring)
631 {
632         if (ring->desc != NULL) {
633                 bus_dmamap_sync(ring->desc_dmat, ring->desc_map,
634                     BUS_DMASYNC_POSTWRITE);
635                 bus_dmamap_unload(ring->desc_dmat, ring->desc_map);
636                 bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
637         }
638
639         if (ring->desc_dmat != NULL)
640                 bus_dma_tag_destroy(ring->desc_dmat);   
641 }
642
643 static int
644 iwi_alloc_tx_ring(struct iwi_softc *sc, struct iwi_tx_ring *ring, int count,
645     bus_addr_t csr_ridx, bus_addr_t csr_widx)
646 {
647         int i, error;
648
649         ring->count = count;
650         ring->queued = 0;
651         ring->cur = ring->next = 0;
652         ring->csr_ridx = csr_ridx;
653         ring->csr_widx = csr_widx;
654
655         error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 4, 0,
656             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
657             count * IWI_TX_DESC_SIZE, 1, count * IWI_TX_DESC_SIZE, 0, NULL, 
658             NULL, &ring->desc_dmat);
659         if (error != 0) {
660                 device_printf(sc->sc_dev, "could not create desc DMA tag\n");
661                 goto fail;
662         }
663
664         error = bus_dmamem_alloc(ring->desc_dmat, (void **)&ring->desc,
665             BUS_DMA_NOWAIT | BUS_DMA_ZERO, &ring->desc_map);
666         if (error != 0) {
667                 device_printf(sc->sc_dev, "could not allocate DMA memory\n");
668                 goto fail;
669         }
670
671         error = bus_dmamap_load(ring->desc_dmat, ring->desc_map, ring->desc,
672             count * IWI_TX_DESC_SIZE, iwi_dma_map_addr, &ring->physaddr, 0);
673         if (error != 0) {
674                 device_printf(sc->sc_dev, "could not load desc DMA map\n");
675                 goto fail;
676         }
677
678         ring->data = malloc(count * sizeof (struct iwi_tx_data), M_DEVBUF,
679             M_NOWAIT | M_ZERO);
680         if (ring->data == NULL) {
681                 device_printf(sc->sc_dev, "could not allocate soft data\n");
682                 error = ENOMEM;
683                 goto fail;
684         }
685
686         error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
687         BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
688         IWI_MAX_NSEG, MCLBYTES, 0, NULL, NULL, &ring->data_dmat);
689         if (error != 0) {
690                 device_printf(sc->sc_dev, "could not create data DMA tag\n");
691                 goto fail;
692         }
693
694         for (i = 0; i < count; i++) {
695                 error = bus_dmamap_create(ring->data_dmat, 0,
696                     &ring->data[i].map);
697                 if (error != 0) {
698                         device_printf(sc->sc_dev, "could not create DMA map\n");
699                         goto fail;
700                 }
701         }
702
703         return 0;
704
705 fail:   iwi_free_tx_ring(sc, ring);
706         return error;
707 }
708
709 static void
710 iwi_reset_tx_ring(struct iwi_softc *sc, struct iwi_tx_ring *ring)
711 {
712         struct iwi_tx_data *data;
713         int i;
714
715         for (i = 0; i < ring->count; i++) {
716                 data = &ring->data[i];
717
718                 if (data->m != NULL) {
719                         bus_dmamap_sync(ring->data_dmat, data->map,
720                             BUS_DMASYNC_POSTWRITE);
721                         bus_dmamap_unload(ring->data_dmat, data->map);
722                         m_freem(data->m);
723                         data->m = NULL;
724                 }
725
726                 if (data->ni != NULL) {
727                         ieee80211_free_node(data->ni);
728                         data->ni = NULL;
729                 }
730         }
731
732         ring->queued = 0;
733         ring->cur = ring->next = 0;
734 }
735
736 static void
737 iwi_free_tx_ring(struct iwi_softc *sc, struct iwi_tx_ring *ring)
738 {
739         struct iwi_tx_data *data;
740         int i;
741
742         if (ring->desc != NULL) {
743                 bus_dmamap_sync(ring->desc_dmat, ring->desc_map,
744                     BUS_DMASYNC_POSTWRITE);
745                 bus_dmamap_unload(ring->desc_dmat, ring->desc_map);
746                 bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
747         }
748
749         if (ring->desc_dmat != NULL)
750                 bus_dma_tag_destroy(ring->desc_dmat);
751
752         if (ring->data != NULL) {
753                 for (i = 0; i < ring->count; i++) {
754                         data = &ring->data[i];
755
756                         if (data->m != NULL) {
757                                 bus_dmamap_sync(ring->data_dmat, data->map,
758                                     BUS_DMASYNC_POSTWRITE);
759                                 bus_dmamap_unload(ring->data_dmat, data->map);
760                                 m_freem(data->m);
761                         }
762
763                         if (data->ni != NULL)
764                                 ieee80211_free_node(data->ni);
765
766                         if (data->map != NULL)
767                                 bus_dmamap_destroy(ring->data_dmat, data->map);
768                 }
769
770                 free(ring->data, M_DEVBUF);
771         }
772
773         if (ring->data_dmat != NULL)
774                 bus_dma_tag_destroy(ring->data_dmat);
775 }
776
777 static int
778 iwi_alloc_rx_ring(struct iwi_softc *sc, struct iwi_rx_ring *ring, int count)
779 {
780         struct iwi_rx_data *data;
781         int i, error;
782
783         ring->count = count;
784         ring->cur = 0;
785
786         ring->data = malloc(count * sizeof (struct iwi_rx_data), M_DEVBUF,
787             M_NOWAIT | M_ZERO);
788         if (ring->data == NULL) {
789                 device_printf(sc->sc_dev, "could not allocate soft data\n");
790                 error = ENOMEM;
791                 goto fail;
792         }
793
794         error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
795             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
796             1, MCLBYTES, 0, NULL, NULL, &ring->data_dmat);
797         if (error != 0) {
798                 device_printf(sc->sc_dev, "could not create data DMA tag\n");
799                 goto fail;
800         }
801
802         for (i = 0; i < count; i++) {
803                 data = &ring->data[i];
804
805                 error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
806                 if (error != 0) {
807                         device_printf(sc->sc_dev, "could not create DMA map\n");
808                         goto fail;
809                 }
810
811                 data->m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
812                 if (data->m == NULL) {
813                         device_printf(sc->sc_dev,
814                             "could not allocate rx mbuf\n");
815                         error = ENOMEM;
816                         goto fail;
817                 }
818
819                 error = bus_dmamap_load(ring->data_dmat, data->map,
820                     mtod(data->m, void *), MCLBYTES, iwi_dma_map_addr,
821                     &data->physaddr, 0);
822                 if (error != 0) {
823                         device_printf(sc->sc_dev,
824                             "could not load rx buf DMA map");
825                         goto fail;
826                 }
827
828                 data->reg = IWI_CSR_RX_BASE + i * 4;
829         }
830
831         return 0;
832
833 fail:   iwi_free_rx_ring(sc, ring);
834         return error;
835 }
836
837 static void
838 iwi_reset_rx_ring(struct iwi_softc *sc, struct iwi_rx_ring *ring)
839 {
840         ring->cur = 0;
841 }
842
843 static void
844 iwi_free_rx_ring(struct iwi_softc *sc, struct iwi_rx_ring *ring)
845 {
846         struct iwi_rx_data *data;
847         int i;
848
849         if (ring->data != NULL) {
850                 for (i = 0; i < ring->count; i++) {
851                         data = &ring->data[i];
852
853                         if (data->m != NULL) {
854                                 bus_dmamap_sync(ring->data_dmat, data->map,
855                                     BUS_DMASYNC_POSTREAD);
856                                 bus_dmamap_unload(ring->data_dmat, data->map);
857                                 m_freem(data->m);
858                         }
859
860                         if (data->map != NULL)
861                                 bus_dmamap_destroy(ring->data_dmat, data->map);
862                 }
863
864                 free(ring->data, M_DEVBUF);
865         }
866
867         if (ring->data_dmat != NULL)
868                 bus_dma_tag_destroy(ring->data_dmat);
869 }
870
871 static int
872 iwi_shutdown(device_t dev)
873 {
874         struct iwi_softc *sc = device_get_softc(dev);
875
876         iwi_stop(sc);
877         iwi_put_firmware(sc);           /* ??? XXX */
878
879         return 0;
880 }
881
882 static int
883 iwi_suspend(device_t dev)
884 {
885         struct iwi_softc *sc = device_get_softc(dev);
886
887         iwi_stop(sc);
888
889         return 0;
890 }
891
892 static int
893 iwi_resume(device_t dev)
894 {
895         struct iwi_softc *sc = device_get_softc(dev);
896         struct ifnet *ifp = sc->sc_ifp;
897
898         pci_write_config(dev, 0x41, 0, 1);
899
900         if (ifp->if_flags & IFF_UP)
901                 iwi_init(sc);
902
903         return 0;
904 }
905
906 static struct ieee80211_node *
907 iwi_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
908 {
909         struct iwi_node *in;
910
911         in = malloc(sizeof (struct iwi_node), M_80211_NODE, M_NOWAIT | M_ZERO);
912         if (in == NULL)
913                 return NULL;
914         /* XXX assign sta table entry for adhoc */
915         in->in_station = -1;
916
917         return &in->in_node;
918 }
919
920 static void
921 iwi_node_free(struct ieee80211_node *ni)
922 {
923         struct ieee80211com *ic = ni->ni_ic;
924         struct iwi_softc *sc = ic->ic_ifp->if_softc;
925         struct iwi_node *in = (struct iwi_node *)ni;
926
927         if (in->in_station != -1) {
928                 DPRINTF(("%s mac %6D station %u\n", __func__,
929                     ni->ni_macaddr, ":", in->in_station));
930                 free_unr(sc->sc_unr, in->in_station);
931         }
932
933         sc->sc_node_free(ni);
934 }
935
936 /* 
937  * Convert h/w rate code to IEEE rate code.
938  */
939 static int
940 iwi_cvtrate(int iwirate)
941 {
942         switch (iwirate) {
943         case IWI_RATE_DS1:      return 2;
944         case IWI_RATE_DS2:      return 4;
945         case IWI_RATE_DS5:      return 11;
946         case IWI_RATE_DS11:     return 22;
947         case IWI_RATE_OFDM6:    return 12;
948         case IWI_RATE_OFDM9:    return 18;
949         case IWI_RATE_OFDM12:   return 24;
950         case IWI_RATE_OFDM18:   return 36;
951         case IWI_RATE_OFDM24:   return 48;
952         case IWI_RATE_OFDM36:   return 72;
953         case IWI_RATE_OFDM48:   return 96;
954         case IWI_RATE_OFDM54:   return 108;
955         }
956         return 0;
957 }
958
959 /*
960  * The firmware automatically adapts the transmit speed.  We report its current
961  * value here.
962  */
963 static void
964 iwi_media_status(struct ifnet *ifp, struct ifmediareq *imr)
965 {
966         struct ieee80211vap *vap = ifp->if_softc;
967         struct ieee80211com *ic = vap->iv_ic;
968         struct iwi_softc *sc = ic->ic_ifp->if_softc;
969
970         /* read current transmission rate from adapter */
971         vap->iv_bss->ni_txrate =
972             iwi_cvtrate(CSR_READ_4(sc, IWI_CSR_CURRENT_TX_RATE));
973         ieee80211_media_status(ifp, imr);
974 }
975
976 static int
977 iwi_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
978 {
979         struct iwi_vap *ivp = IWI_VAP(vap);
980         struct ieee80211com *ic = vap->iv_ic;
981         struct ifnet *ifp = ic->ic_ifp;
982         struct iwi_softc *sc = ifp->if_softc;
983         IWI_LOCK_DECL;
984
985         DPRINTF(("%s: %s -> %s flags 0x%x\n", __func__,
986                 ieee80211_state_name[vap->iv_state],
987                 ieee80211_state_name[nstate], sc->flags));
988
989         switch (nstate) {
990         case IEEE80211_S_INIT:
991                 IWI_LOCK(sc);
992                 /*
993                  * NB: don't try to do this if iwi_stop_master has
994                  *     shutdown the firmware and disabled interrupts.
995                  */
996                 if (vap->iv_state == IEEE80211_S_RUN &&
997                     (sc->flags & IWI_FLAG_FW_INITED))
998                         iwi_queue_cmd(sc, IWI_DISASSOC, 1);
999                 IWI_UNLOCK(sc);
1000                 break;
1001         case IEEE80211_S_AUTH:
1002                 iwi_queue_cmd(sc, IWI_AUTH, arg);
1003                 return EINPROGRESS;
1004         case IEEE80211_S_RUN:
1005                 if (vap->iv_opmode == IEEE80211_M_IBSS &&
1006                     vap->iv_state == IEEE80211_S_SCAN) {
1007                         /*
1008                          * XXX when joining an ibss network we are called
1009                          * with a SCAN -> RUN transition on scan complete.
1010                          * Use that to call iwi_auth_and_assoc.  On completing
1011                          * the join we are then called again with an
1012                          * AUTH -> RUN transition and we want to do nothing.
1013                          * This is all totally bogus and needs to be redone.
1014                          */
1015                         iwi_queue_cmd(sc, IWI_ASSOC, 0);
1016                         return EINPROGRESS;
1017                 }
1018                 break;
1019         case IEEE80211_S_ASSOC:
1020                 /*
1021                  * If we are transitioning from AUTH then just wait
1022                  * for the ASSOC status to come back from the firmware.
1023                  * Otherwise we need to issue the association request.
1024                  */
1025                 if (vap->iv_state == IEEE80211_S_AUTH)
1026                         break;
1027                 iwi_queue_cmd(sc, IWI_ASSOC, arg);
1028                 return EINPROGRESS;
1029         default:
1030                 break;
1031         }
1032         return ivp->iwi_newstate(vap, nstate, arg);
1033 }
1034
1035 /*
1036  * WME parameters coming from IEEE 802.11e specification.  These values are
1037  * already declared in ieee80211_proto.c, but they are static so they can't
1038  * be reused here.
1039  */
1040 static const struct wmeParams iwi_wme_cck_params[WME_NUM_AC] = {
1041         { 0, 3, 5,  7,   0 },   /* WME_AC_BE */
1042         { 0, 3, 5, 10,   0 },   /* WME_AC_BK */
1043         { 0, 2, 4,  5, 188 },   /* WME_AC_VI */
1044         { 0, 2, 3,  4, 102 }    /* WME_AC_VO */
1045 };
1046
1047 static const struct wmeParams iwi_wme_ofdm_params[WME_NUM_AC] = {
1048         { 0, 3, 4,  6,   0 },   /* WME_AC_BE */
1049         { 0, 3, 4, 10,   0 },   /* WME_AC_BK */
1050         { 0, 2, 3,  4,  94 },   /* WME_AC_VI */
1051         { 0, 2, 2,  3,  47 }    /* WME_AC_VO */
1052 };
1053 #define IWI_EXP2(v)     htole16((1 << (v)) - 1)
1054 #define IWI_USEC(v)     htole16(IEEE80211_TXOP_TO_US(v))
1055
1056 static void
1057 iwi_wme_init(struct iwi_softc *sc)
1058 {
1059         const struct wmeParams *wmep;
1060         int ac;
1061
1062         memset(sc->wme, 0, sizeof sc->wme);
1063         for (ac = 0; ac < WME_NUM_AC; ac++) {
1064                 /* set WME values for CCK modulation */
1065                 wmep = &iwi_wme_cck_params[ac];
1066                 sc->wme[1].aifsn[ac] = wmep->wmep_aifsn;
1067                 sc->wme[1].cwmin[ac] = IWI_EXP2(wmep->wmep_logcwmin);
1068                 sc->wme[1].cwmax[ac] = IWI_EXP2(wmep->wmep_logcwmax);
1069                 sc->wme[1].burst[ac] = IWI_USEC(wmep->wmep_txopLimit);
1070                 sc->wme[1].acm[ac]   = wmep->wmep_acm;
1071
1072                 /* set WME values for OFDM modulation */
1073                 wmep = &iwi_wme_ofdm_params[ac];
1074                 sc->wme[2].aifsn[ac] = wmep->wmep_aifsn;
1075                 sc->wme[2].cwmin[ac] = IWI_EXP2(wmep->wmep_logcwmin);
1076                 sc->wme[2].cwmax[ac] = IWI_EXP2(wmep->wmep_logcwmax);
1077                 sc->wme[2].burst[ac] = IWI_USEC(wmep->wmep_txopLimit);
1078                 sc->wme[2].acm[ac]   = wmep->wmep_acm;
1079         }
1080 }
1081
1082 static int
1083 iwi_wme_setparams(struct iwi_softc *sc, struct ieee80211com *ic)
1084 {
1085         const struct wmeParams *wmep;
1086         int ac;
1087
1088         for (ac = 0; ac < WME_NUM_AC; ac++) {
1089                 /* set WME values for current operating mode */
1090                 wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
1091                 sc->wme[0].aifsn[ac] = wmep->wmep_aifsn;
1092                 sc->wme[0].cwmin[ac] = IWI_EXP2(wmep->wmep_logcwmin);
1093                 sc->wme[0].cwmax[ac] = IWI_EXP2(wmep->wmep_logcwmax);
1094                 sc->wme[0].burst[ac] = IWI_USEC(wmep->wmep_txopLimit);
1095                 sc->wme[0].acm[ac]   = wmep->wmep_acm;
1096         }
1097
1098         DPRINTF(("Setting WME parameters\n"));
1099         return iwi_cmd(sc, IWI_CMD_SET_WME_PARAMS, sc->wme, sizeof sc->wme);
1100 }
1101 #undef IWI_USEC
1102 #undef IWI_EXP2
1103
1104 static int
1105 iwi_wme_update(struct ieee80211com *ic)
1106 {
1107         struct iwi_softc *sc = ic->ic_ifp->if_softc;
1108
1109         /*
1110          * We may be called to update the WME parameters in
1111          * the adapter at various places.  If we're already
1112          * associated then initiate the request immediately
1113          * (via the taskqueue); otherwise we assume the params
1114          * will get sent down to the adapter as part of the
1115          * work iwi_auth_and_assoc does.
1116          */
1117         return iwi_queue_cmd(sc, IWI_SET_WME, 0);
1118 }
1119
1120 static int
1121 iwi_wme_setie(struct iwi_softc *sc)
1122 {
1123         struct ieee80211_wme_info wme;
1124
1125         memset(&wme, 0, sizeof wme);
1126         wme.wme_id = IEEE80211_ELEMID_VENDOR;
1127         wme.wme_len = sizeof (struct ieee80211_wme_info) - 2;
1128         wme.wme_oui[0] = 0x00;
1129         wme.wme_oui[1] = 0x50;
1130         wme.wme_oui[2] = 0xf2;
1131         wme.wme_type = WME_OUI_TYPE;
1132         wme.wme_subtype = WME_INFO_OUI_SUBTYPE;
1133         wme.wme_version = WME_VERSION;
1134         wme.wme_info = 0;
1135
1136         DPRINTF(("Setting WME IE (len=%u)\n", wme.wme_len));
1137         return iwi_cmd(sc, IWI_CMD_SET_WMEIE, &wme, sizeof wme);
1138 }
1139
1140 /*
1141  * Read 16 bits at address 'addr' from the serial EEPROM.
1142  */
1143 static uint16_t
1144 iwi_read_prom_word(struct iwi_softc *sc, uint8_t addr)
1145 {
1146         uint32_t tmp;
1147         uint16_t val;
1148         int n;
1149
1150         /* clock C once before the first command */
1151         IWI_EEPROM_CTL(sc, 0);
1152         IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1153         IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1154         IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1155
1156         /* write start bit (1) */
1157         IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D);
1158         IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D | IWI_EEPROM_C);
1159
1160         /* write READ opcode (10) */
1161         IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D);
1162         IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D | IWI_EEPROM_C);
1163         IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1164         IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1165
1166         /* write address A7-A0 */
1167         for (n = 7; n >= 0; n--) {
1168                 IWI_EEPROM_CTL(sc, IWI_EEPROM_S |
1169                     (((addr >> n) & 1) << IWI_EEPROM_SHIFT_D));
1170                 IWI_EEPROM_CTL(sc, IWI_EEPROM_S |
1171                     (((addr >> n) & 1) << IWI_EEPROM_SHIFT_D) | IWI_EEPROM_C);
1172         }
1173
1174         IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1175
1176         /* read data Q15-Q0 */
1177         val = 0;
1178         for (n = 15; n >= 0; n--) {
1179                 IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1180                 IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1181                 tmp = MEM_READ_4(sc, IWI_MEM_EEPROM_CTL);
1182                 val |= ((tmp & IWI_EEPROM_Q) >> IWI_EEPROM_SHIFT_Q) << n;
1183         }
1184
1185         IWI_EEPROM_CTL(sc, 0);
1186
1187         /* clear Chip Select and clock C */
1188         IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1189         IWI_EEPROM_CTL(sc, 0);
1190         IWI_EEPROM_CTL(sc, IWI_EEPROM_C);
1191
1192         return val;
1193 }
1194
1195 static void
1196 iwi_setcurchan(struct iwi_softc *sc, int chan)
1197 {
1198         struct ifnet *ifp = sc->sc_ifp;
1199         struct ieee80211com *ic = ifp->if_l2com;
1200
1201         sc->curchan = chan;
1202
1203         sc->sc_rxtap.wr_chan_freq = sc->sc_txtap.wt_chan_freq =
1204                 htole16(ic->ic_curchan->ic_freq);
1205         sc->sc_rxtap.wr_chan_flags = sc->sc_txtap.wt_chan_flags =
1206                 htole16(ic->ic_curchan->ic_flags);
1207 }
1208
1209 static void
1210 iwi_frame_intr(struct iwi_softc *sc, struct iwi_rx_data *data, int i,
1211     struct iwi_frame *frame)
1212 {
1213         struct ifnet *ifp = sc->sc_ifp;
1214         struct ieee80211com *ic = ifp->if_l2com;
1215         struct mbuf *mnew, *m;
1216         struct ieee80211_node *ni;
1217         int type, error, framelen;
1218         IWI_LOCK_DECL;
1219
1220         framelen = le16toh(frame->len);
1221         if (framelen < IEEE80211_MIN_LEN || framelen > MCLBYTES) {
1222                 /*
1223                  * XXX >MCLBYTES is bogus as it means the h/w dma'd
1224                  *     out of bounds; need to figure out how to limit
1225                  *     frame size in the firmware
1226                  */
1227                 /* XXX stat */
1228                 DPRINTFN(1,
1229                     ("drop rx frame len=%u chan=%u rssi=%u rssi_dbm=%u\n",
1230                     le16toh(frame->len), frame->chan, frame->rssi,
1231                     frame->rssi_dbm));
1232                 return;
1233         }
1234
1235         DPRINTFN(5, ("received frame len=%u chan=%u rssi=%u rssi_dbm=%u\n",
1236             le16toh(frame->len), frame->chan, frame->rssi, frame->rssi_dbm));
1237
1238         if (frame->chan != sc->curchan)
1239                 iwi_setcurchan(sc, frame->chan);
1240
1241         /*
1242          * Try to allocate a new mbuf for this ring element and load it before
1243          * processing the current mbuf. If the ring element cannot be loaded,
1244          * drop the received packet and reuse the old mbuf. In the unlikely
1245          * case that the old mbuf can't be reloaded either, explicitly panic.
1246          */
1247         mnew = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
1248         if (mnew == NULL) {
1249                 ifp->if_ierrors++;
1250                 return;
1251         }
1252
1253         bus_dmamap_unload(sc->rxq.data_dmat, data->map);
1254
1255         error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1256             mtod(mnew, void *), MCLBYTES, iwi_dma_map_addr, &data->physaddr,
1257             0);
1258         if (error != 0) {
1259                 m_freem(mnew);
1260
1261                 /* try to reload the old mbuf */
1262                 error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1263                     mtod(data->m, void *), MCLBYTES, iwi_dma_map_addr,
1264                     &data->physaddr, 0);
1265                 if (error != 0) {
1266                         /* very unlikely that it will fail... */
1267                         panic("%s: could not load old rx mbuf",
1268                             device_get_name(sc->sc_dev));
1269                 }
1270                 ifp->if_ierrors++;
1271                 return;
1272         }
1273
1274         /*
1275          * New mbuf successfully loaded, update Rx ring and continue
1276          * processing.
1277          */
1278         m = data->m;
1279         data->m = mnew;
1280         CSR_WRITE_4(sc, data->reg, data->physaddr);
1281
1282         /* finalize mbuf */
1283         m->m_pkthdr.rcvif = ifp;
1284         m->m_pkthdr.len = m->m_len = sizeof (struct iwi_hdr) +
1285             sizeof (struct iwi_frame) + framelen;
1286
1287         m_adj(m, sizeof (struct iwi_hdr) + sizeof (struct iwi_frame));
1288
1289         if (bpf_peers_present(ifp->if_bpf)) {
1290                 struct iwi_rx_radiotap_header *tap = &sc->sc_rxtap;
1291
1292                 tap->wr_flags = 0;
1293                 tap->wr_rate = iwi_cvtrate(frame->rate);
1294                 tap->wr_antsignal = frame->signal;
1295                 tap->wr_antenna = frame->antenna;
1296
1297                 bpf_mtap2(ifp->if_bpf, tap, sc->sc_rxtap_len, m);
1298         }
1299         IWI_UNLOCK(sc);
1300
1301         ni = ieee80211_find_rxnode(ic, mtod(m, struct ieee80211_frame_min *));
1302         if (ni != NULL) {
1303                 type = ieee80211_input(ni, m, frame->rssi_dbm, 0, 0);
1304                 ieee80211_free_node(ni);
1305         } else
1306                 type = ieee80211_input_all(ic, m, frame->rssi_dbm, 0, 0);
1307
1308         IWI_LOCK(sc);
1309         if (sc->sc_softled) {
1310                 /*
1311                  * Blink for any data frame.  Otherwise do a
1312                  * heartbeat-style blink when idle.  The latter
1313                  * is mainly for station mode where we depend on
1314                  * periodic beacon frames to trigger the poll event.
1315                  */
1316                 if (type == IEEE80211_FC0_TYPE_DATA) {
1317                         sc->sc_rxrate = frame->rate;
1318                         iwi_led_event(sc, IWI_LED_RX);
1319                 } else if (ticks - sc->sc_ledevent >= sc->sc_ledidle)
1320                         iwi_led_event(sc, IWI_LED_POLL);
1321         }
1322 }
1323
1324 /*
1325  * Check for an association response frame to see if QoS
1326  * has been negotiated.  We parse just enough to figure
1327  * out if we're supposed to use QoS.  The proper solution
1328  * is to pass the frame up so ieee80211_input can do the
1329  * work but that's made hard by how things currently are
1330  * done in the driver.
1331  */
1332 static void
1333 iwi_checkforqos(struct ieee80211vap *vap,
1334         const struct ieee80211_frame *wh, int len)
1335 {
1336 #define SUBTYPE(wh)     ((wh)->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK)
1337         const uint8_t *frm, *efrm, *wme;
1338         struct ieee80211_node *ni;
1339         uint16_t capinfo, status, associd;
1340
1341         /* NB: +8 for capinfo, status, associd, and first ie */
1342         if (!(sizeof(*wh)+8 < len && len < IEEE80211_MAX_LEN) ||
1343             SUBTYPE(wh) != IEEE80211_FC0_SUBTYPE_ASSOC_RESP)
1344                 return;
1345         /*
1346          * asresp frame format
1347          *      [2] capability information
1348          *      [2] status
1349          *      [2] association ID
1350          *      [tlv] supported rates
1351          *      [tlv] extended supported rates
1352          *      [tlv] WME
1353          */
1354         frm = (const uint8_t *)&wh[1];
1355         efrm = ((const uint8_t *) wh) + len;
1356
1357         capinfo = le16toh(*(const uint16_t *)frm);
1358         frm += 2;
1359         status = le16toh(*(const uint16_t *)frm);
1360         frm += 2;
1361         associd = le16toh(*(const uint16_t *)frm);
1362         frm += 2;
1363
1364         wme = NULL;
1365         while (frm < efrm) {
1366                 IEEE80211_VERIFY_LENGTH(efrm - frm, frm[1], return);
1367                 switch (*frm) {
1368                 case IEEE80211_ELEMID_VENDOR:
1369                         if (iswmeoui(frm))
1370                                 wme = frm;
1371                         break;
1372                 }
1373                 frm += frm[1] + 2;
1374         }
1375
1376         ni = vap->iv_bss;
1377         ni->ni_capinfo = capinfo;
1378         ni->ni_associd = associd;
1379         if (wme != NULL)
1380                 ni->ni_flags |= IEEE80211_NODE_QOS;
1381         else
1382                 ni->ni_flags &= ~IEEE80211_NODE_QOS;
1383 #undef SUBTYPE
1384 }
1385
1386 /*
1387  * Task queue callbacks for iwi_notification_intr used to avoid LOR's.
1388  */
1389
1390 static void
1391 iwi_authsuccess(void *arg, int npending)
1392 {
1393         struct ieee80211vap *vap = arg;
1394
1395         ieee80211_new_state(vap, IEEE80211_S_ASSOC, -1);
1396 }
1397
1398 static void
1399 iwi_assocsuccess(void *arg, int npending)
1400 {
1401         struct ieee80211vap *vap = arg;
1402
1403         ieee80211_new_state(vap, IEEE80211_S_RUN, -1);
1404 }
1405
1406 static void
1407 iwi_assocfailed(void *arg, int npending)
1408 {
1409         struct ieee80211vap *vap = arg;
1410
1411         ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
1412 }
1413
1414 static void
1415 iwi_notification_intr(struct iwi_softc *sc, struct iwi_notif *notif)
1416 {
1417         struct ifnet *ifp = sc->sc_ifp;
1418         struct ieee80211com *ic = ifp->if_l2com;
1419         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1420         struct iwi_notif_scan_channel *chan;
1421         struct iwi_notif_scan_complete *scan;
1422         struct iwi_notif_authentication *auth;
1423         struct iwi_notif_association *assoc;
1424         struct iwi_notif_beacon_state *beacon;
1425
1426         switch (notif->type) {
1427         case IWI_NOTIF_TYPE_SCAN_CHANNEL:
1428                 chan = (struct iwi_notif_scan_channel *)(notif + 1);
1429
1430                 DPRINTFN(3, ("Scan of channel %u complete (%u)\n",
1431                     ieee80211_ieee2mhz(chan->nchan, 0), chan->nchan));
1432
1433                 /* Reset the timer, the scan is still going */
1434                 sc->sc_state_timer = 3;
1435                 break;
1436
1437         case IWI_NOTIF_TYPE_SCAN_COMPLETE:
1438                 scan = (struct iwi_notif_scan_complete *)(notif + 1);
1439
1440                 DPRINTFN(2, ("Scan completed (%u, %u)\n", scan->nchan,
1441                     scan->status));
1442
1443                 IWI_STATE_END(sc, IWI_FW_SCANNING);
1444
1445                 if (scan->status == IWI_SCAN_COMPLETED) {
1446                         /* NB: don't need to defer, net80211 does it for us */
1447                         ieee80211_scan_next(vap);
1448                 }
1449                 break;
1450
1451         case IWI_NOTIF_TYPE_AUTHENTICATION:
1452                 auth = (struct iwi_notif_authentication *)(notif + 1);
1453                 switch (auth->state) {
1454                 case IWI_AUTH_SUCCESS:
1455                         DPRINTFN(2, ("Authentication succeeeded\n"));
1456                         taskqueue_enqueue(taskqueue_swi,
1457                             &IWI_VAP(vap)->iwi_authsuccess_task);
1458                         break;
1459                 case IWI_AUTH_FAIL:
1460                         /*
1461                          * These are delivered as an unsolicited deauth
1462                          * (e.g. due to inactivity) or in response to an
1463                          * associate request.
1464                          */
1465                         sc->flags &= ~IWI_FLAG_ASSOCIATED;
1466                         if (vap->iv_state != IEEE80211_S_RUN) {
1467                                 DPRINTFN(2, ("Authentication failed\n"));
1468                                 vap->iv_stats.is_rx_auth_fail++;
1469                                 IWI_STATE_END(sc, IWI_FW_ASSOCIATING);
1470                         } else {
1471                                 DPRINTFN(2, ("Deauthenticated\n"));
1472                                 vap->iv_stats.is_rx_deauth++;
1473                         }
1474                         taskqueue_enqueue(taskqueue_swi,
1475                             &IWI_VAP(vap)->iwi_assocfailed_task);
1476                         break;
1477                 case IWI_AUTH_SENT_1:
1478                 case IWI_AUTH_RECV_2:
1479                 case IWI_AUTH_SEQ1_PASS:
1480                         break;
1481                 case IWI_AUTH_SEQ1_FAIL:
1482                         DPRINTFN(2, ("Initial authentication handshake failed; "
1483                                 "you probably need shared key\n"));
1484                         vap->iv_stats.is_rx_auth_fail++;
1485                         IWI_STATE_END(sc, IWI_FW_ASSOCIATING);
1486                         /* XXX retry shared key when in auto */
1487                         break;
1488                 default:
1489                         device_printf(sc->sc_dev,
1490                             "unknown authentication state %u\n", auth->state);
1491                         break;
1492                 }
1493                 break;
1494
1495         case IWI_NOTIF_TYPE_ASSOCIATION:
1496                 assoc = (struct iwi_notif_association *)(notif + 1);
1497                 switch (assoc->state) {
1498                 case IWI_AUTH_SUCCESS:
1499                         /* re-association, do nothing */
1500                         break;
1501                 case IWI_ASSOC_SUCCESS:
1502                         DPRINTFN(2, ("Association succeeded\n"));
1503                         sc->flags |= IWI_FLAG_ASSOCIATED;
1504                         IWI_STATE_END(sc, IWI_FW_ASSOCIATING);
1505                         iwi_checkforqos(vap,
1506                             (const struct ieee80211_frame *)(assoc+1),
1507                             le16toh(notif->len) - sizeof(*assoc));
1508                         taskqueue_enqueue(taskqueue_swi,
1509                             &IWI_VAP(vap)->iwi_assocsuccess_task);
1510                         break;
1511                 case IWI_ASSOC_INIT:
1512                         sc->flags &= ~IWI_FLAG_ASSOCIATED;
1513                         switch (sc->fw_state) {
1514                         case IWI_FW_ASSOCIATING:
1515                                 DPRINTFN(2, ("Association failed\n"));
1516                                 IWI_STATE_END(sc, IWI_FW_ASSOCIATING);
1517                                 taskqueue_enqueue(taskqueue_swi,
1518                                     &IWI_VAP(vap)->iwi_assocfailed_task);
1519                                 break;
1520
1521                         case IWI_FW_DISASSOCIATING:
1522                                 DPRINTFN(2, ("Dissassociated\n"));
1523                                 IWI_STATE_END(sc, IWI_FW_DISASSOCIATING);
1524                                 vap->iv_stats.is_rx_disassoc++;
1525                                 taskqueue_enqueue(taskqueue_swi,
1526                                     &IWI_VAP(vap)->iwi_assocfailed_task);
1527                                 break;
1528                         }
1529                         break;
1530                 default:
1531                         device_printf(sc->sc_dev,
1532                             "unknown association state %u\n", assoc->state);
1533                         break;
1534                 }
1535                 break;
1536
1537         case IWI_NOTIF_TYPE_BEACON:
1538                 /* XXX check struct length */
1539                 beacon = (struct iwi_notif_beacon_state *)(notif + 1);
1540
1541                 DPRINTFN(5, ("Beacon state (%u, %u)\n",
1542                     beacon->state, le32toh(beacon->number)));
1543
1544                 if (beacon->state == IWI_BEACON_MISS) {
1545                         /*
1546                          * The firmware notifies us of every beacon miss
1547                          * so we need to track the count against the
1548                          * configured threshold before notifying the
1549                          * 802.11 layer.
1550                          * XXX try to roam, drop assoc only on much higher count
1551                          */
1552                         if (le32toh(beacon->number) >= vap->iv_bmissthreshold) {
1553                                 DPRINTF(("Beacon miss: %u >= %u\n",
1554                                     le32toh(beacon->number),
1555                                     vap->iv_bmissthreshold));
1556                                 vap->iv_stats.is_beacon_miss++;
1557                                 /*
1558                                  * It's pointless to notify the 802.11 layer
1559                                  * as it'll try to send a probe request (which
1560                                  * we'll discard) and then timeout and drop us
1561                                  * into scan state.  Instead tell the firmware
1562                                  * to disassociate and then on completion we'll
1563                                  * kick the state machine to scan.
1564                                  */
1565                                 iwi_queue_cmd(sc, IWI_DISASSOC, 1);
1566                         }
1567                 }
1568                 break;
1569
1570         case IWI_NOTIF_TYPE_CALIBRATION:
1571         case IWI_NOTIF_TYPE_NOISE:
1572         case IWI_NOTIF_TYPE_LINK_QUALITY:
1573                 DPRINTFN(5, ("Notification (%u)\n", notif->type));
1574                 break;
1575
1576         default:
1577                 DPRINTF(("unknown notification type %u flags 0x%x len %u\n",
1578                     notif->type, notif->flags, le16toh(notif->len)));
1579                 break;
1580         }
1581 }
1582
1583 static void
1584 iwi_rx_intr(struct iwi_softc *sc)
1585 {
1586         struct iwi_rx_data *data;
1587         struct iwi_hdr *hdr;
1588         uint32_t hw;
1589
1590         hw = CSR_READ_4(sc, IWI_CSR_RX_RIDX);
1591
1592         for (; sc->rxq.cur != hw;) {
1593                 data = &sc->rxq.data[sc->rxq.cur];
1594
1595                 bus_dmamap_sync(sc->rxq.data_dmat, data->map,
1596                     BUS_DMASYNC_POSTREAD);
1597
1598                 hdr = mtod(data->m, struct iwi_hdr *);
1599
1600                 switch (hdr->type) {
1601                 case IWI_HDR_TYPE_FRAME:
1602                         iwi_frame_intr(sc, data, sc->rxq.cur,
1603                             (struct iwi_frame *)(hdr + 1));
1604                         break;
1605
1606                 case IWI_HDR_TYPE_NOTIF:
1607                         iwi_notification_intr(sc,
1608                             (struct iwi_notif *)(hdr + 1));
1609                         break;
1610
1611                 default:
1612                         device_printf(sc->sc_dev, "unknown hdr type %u\n",
1613                             hdr->type);
1614                 }
1615
1616                 DPRINTFN(15, ("rx done idx=%u\n", sc->rxq.cur));
1617
1618                 sc->rxq.cur = (sc->rxq.cur + 1) % IWI_RX_RING_COUNT;
1619         }
1620
1621         /* tell the firmware what we have processed */
1622         hw = (hw == 0) ? IWI_RX_RING_COUNT - 1 : hw - 1;
1623         CSR_WRITE_4(sc, IWI_CSR_RX_WIDX, hw);
1624 }
1625
1626 static void
1627 iwi_tx_intr(struct iwi_softc *sc, struct iwi_tx_ring *txq)
1628 {
1629         struct ifnet *ifp = sc->sc_ifp;
1630         struct iwi_tx_data *data;
1631         uint32_t hw;
1632
1633         hw = CSR_READ_4(sc, txq->csr_ridx);
1634
1635         for (; txq->next != hw;) {
1636                 data = &txq->data[txq->next];
1637
1638                 bus_dmamap_sync(txq->data_dmat, data->map,
1639                     BUS_DMASYNC_POSTWRITE);
1640                 bus_dmamap_unload(txq->data_dmat, data->map);
1641                 if (data->m->m_flags & M_TXCB)
1642                         ieee80211_process_callback(data->ni, data->m, 0/*XXX*/);
1643                 m_freem(data->m);
1644                 data->m = NULL;
1645                 ieee80211_free_node(data->ni);
1646                 data->ni = NULL;
1647
1648                 DPRINTFN(15, ("tx done idx=%u\n", txq->next));
1649
1650                 ifp->if_opackets++;
1651
1652                 txq->queued--;
1653                 txq->next = (txq->next + 1) % IWI_TX_RING_COUNT;
1654         }
1655
1656         sc->sc_tx_timer = 0;
1657         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1658
1659         if (sc->sc_softled)
1660                 iwi_led_event(sc, IWI_LED_TX);
1661
1662         iwi_start_locked(ifp);
1663 }
1664
1665 static void
1666 iwi_intr(void *arg)
1667 {
1668         struct iwi_softc *sc = arg;
1669         uint32_t r;
1670         IWI_LOCK_DECL;
1671
1672         IWI_LOCK(sc);
1673
1674         if ((r = CSR_READ_4(sc, IWI_CSR_INTR)) == 0 || r == 0xffffffff) {
1675                 IWI_UNLOCK(sc);
1676                 return;
1677         }
1678
1679         /* acknowledge interrupts */
1680         CSR_WRITE_4(sc, IWI_CSR_INTR, r);
1681
1682         if (r & IWI_INTR_FATAL_ERROR) {
1683                 device_printf(sc->sc_dev, "firmware error\n");
1684                 taskqueue_enqueue(sc->sc_tq2, &sc->sc_restarttask);
1685
1686                 sc->flags &= ~IWI_FLAG_BUSY;
1687                 sc->sc_busy_timer = 0;
1688                 wakeup(sc);
1689         }
1690
1691         if (r & IWI_INTR_FW_INITED) {
1692                 if (!(r & (IWI_INTR_FATAL_ERROR | IWI_INTR_PARITY_ERROR)))
1693                         wakeup(sc);
1694         }
1695
1696         if (r & IWI_INTR_RADIO_OFF)
1697                 taskqueue_enqueue(sc->sc_tq, &sc->sc_radiofftask);
1698
1699         if (r & IWI_INTR_CMD_DONE) {
1700                 sc->flags &= ~IWI_FLAG_BUSY;
1701                 sc->sc_busy_timer = 0;
1702                 wakeup(sc);
1703         }
1704
1705         if (r & IWI_INTR_TX1_DONE)
1706                 iwi_tx_intr(sc, &sc->txq[0]);
1707
1708         if (r & IWI_INTR_TX2_DONE)
1709                 iwi_tx_intr(sc, &sc->txq[1]);
1710
1711         if (r & IWI_INTR_TX3_DONE)
1712                 iwi_tx_intr(sc, &sc->txq[2]);
1713
1714         if (r & IWI_INTR_TX4_DONE)
1715                 iwi_tx_intr(sc, &sc->txq[3]);
1716
1717         if (r & IWI_INTR_RX_DONE)
1718                 iwi_rx_intr(sc);
1719
1720         if (r & IWI_INTR_PARITY_ERROR) {
1721                 /* XXX rate-limit */
1722                 device_printf(sc->sc_dev, "parity error\n");
1723         }
1724
1725         IWI_UNLOCK(sc);
1726 }
1727
1728 static int
1729 iwi_cmd(struct iwi_softc *sc, uint8_t type, void *data, uint8_t len)
1730 {
1731         struct iwi_cmd_desc *desc;
1732
1733         IWI_LOCK_ASSERT(sc);
1734
1735         if (sc->flags & IWI_FLAG_BUSY) {
1736                 device_printf(sc->sc_dev, "%s: cmd %d not sent, busy\n",
1737                         __func__, type);
1738                 return EAGAIN;
1739         }
1740         sc->flags |= IWI_FLAG_BUSY;
1741         sc->sc_busy_timer = 2;
1742
1743         desc = &sc->cmdq.desc[sc->cmdq.cur];
1744
1745         desc->hdr.type = IWI_HDR_TYPE_COMMAND;
1746         desc->hdr.flags = IWI_HDR_FLAG_IRQ;
1747         desc->type = type;
1748         desc->len = len;
1749         memcpy(desc->data, data, len);
1750
1751         bus_dmamap_sync(sc->cmdq.desc_dmat, sc->cmdq.desc_map,
1752             BUS_DMASYNC_PREWRITE);
1753
1754         DPRINTFN(2, ("sending command idx=%u type=%u len=%u\n", sc->cmdq.cur,
1755             type, len));
1756
1757         sc->cmdq.cur = (sc->cmdq.cur + 1) % IWI_CMD_RING_COUNT;
1758         CSR_WRITE_4(sc, IWI_CSR_CMD_WIDX, sc->cmdq.cur);
1759
1760         return msleep(sc, &sc->sc_mtx, 0, "iwicmd", hz);
1761 }
1762
1763 static void
1764 iwi_write_ibssnode(struct iwi_softc *sc,
1765         const u_int8_t addr[IEEE80211_ADDR_LEN], int entry)
1766 {
1767         struct iwi_ibssnode node;
1768
1769         /* write node information into NIC memory */
1770         memset(&node, 0, sizeof node);
1771         IEEE80211_ADDR_COPY(node.bssid, addr);
1772
1773         DPRINTF(("%s mac %6D station %u\n", __func__, node.bssid, ":", entry));
1774
1775         CSR_WRITE_REGION_1(sc,
1776             IWI_CSR_NODE_BASE + entry * sizeof node,
1777             (uint8_t *)&node, sizeof node);
1778 }
1779
1780 static int
1781 iwi_tx_start(struct ifnet *ifp, struct mbuf *m0, struct ieee80211_node *ni,
1782     int ac)
1783 {
1784         struct iwi_softc *sc = ifp->if_softc;
1785         struct ieee80211vap *vap = ni->ni_vap;
1786         struct ieee80211com *ic = ni->ni_ic;
1787         struct iwi_node *in = (struct iwi_node *)ni;
1788         const struct ieee80211_frame *wh;
1789         struct ieee80211_key *k;
1790         const struct chanAccParams *cap;
1791         struct iwi_tx_ring *txq = &sc->txq[ac];
1792         struct iwi_tx_data *data;
1793         struct iwi_tx_desc *desc;
1794         struct mbuf *mnew;
1795         bus_dma_segment_t segs[IWI_MAX_NSEG];
1796         int error, nsegs, hdrlen, i;
1797         int ismcast, flags, xflags, staid;
1798
1799         IWI_LOCK_ASSERT(sc);
1800         wh = mtod(m0, const struct ieee80211_frame *);
1801         /* NB: only data frames use this path */
1802         hdrlen = ieee80211_hdrsize(wh);
1803         ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
1804         flags = xflags = 0;
1805
1806         if (!ismcast)
1807                 flags |= IWI_DATA_FLAG_NEED_ACK;
1808         if (vap->iv_flags & IEEE80211_F_SHPREAMBLE)
1809                 flags |= IWI_DATA_FLAG_SHPREAMBLE;
1810         if (IEEE80211_QOS_HAS_SEQ(wh)) {
1811                 xflags |= IWI_DATA_XFLAG_QOS;
1812                 cap = &ic->ic_wme.wme_chanParams;
1813                 if (!cap->cap_wmeParams[ac].wmep_noackPolicy)
1814                         flags &= ~IWI_DATA_FLAG_NEED_ACK;
1815         }
1816
1817         /*
1818          * This is only used in IBSS mode where the firmware expect an index
1819          * in a h/w table instead of a destination address.
1820          */
1821         if (vap->iv_opmode == IEEE80211_M_IBSS) {
1822                 if (!ismcast) {
1823                         if (in->in_station == -1) {
1824                                 in->in_station = alloc_unr(sc->sc_unr);
1825                                 if (in->in_station == -1) {
1826                                         /* h/w table is full */
1827                                         m_freem(m0);
1828                                         ieee80211_free_node(ni);
1829                                         ifp->if_oerrors++;
1830                                         return 0;
1831                                 }
1832                                 iwi_write_ibssnode(sc,
1833                                         ni->ni_macaddr, in->in_station);
1834                         }
1835                         staid = in->in_station;
1836                 } else {
1837                         /*
1838                          * Multicast addresses have no associated node
1839                          * so there will be no station entry.  We reserve
1840                          * entry 0 for one mcast address and use that.
1841                          * If there are many being used this will be
1842                          * expensive and we'll need to do a better job
1843                          * but for now this handles the broadcast case.
1844                          */
1845                         if (!IEEE80211_ADDR_EQ(wh->i_addr1, sc->sc_mcast)) {
1846                                 IEEE80211_ADDR_COPY(sc->sc_mcast, wh->i_addr1);
1847                                 iwi_write_ibssnode(sc, sc->sc_mcast, 0);
1848                         }
1849                         staid = 0;
1850                 }
1851         } else
1852                 staid = 0;
1853
1854         if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1855                 k = ieee80211_crypto_encap(ni, m0);
1856                 if (k == NULL) {
1857                         m_freem(m0);
1858                         return ENOBUFS;
1859                 }
1860
1861                 /* packet header may have moved, reset our local pointer */
1862                 wh = mtod(m0, struct ieee80211_frame *);
1863         }
1864
1865         if (bpf_peers_present(ifp->if_bpf)) {
1866                 struct iwi_tx_radiotap_header *tap = &sc->sc_txtap;
1867
1868                 tap->wt_flags = 0;
1869
1870                 bpf_mtap2(ifp->if_bpf, tap, sc->sc_txtap_len, m0);
1871         }
1872
1873         data = &txq->data[txq->cur];
1874         desc = &txq->desc[txq->cur];
1875
1876         /* save and trim IEEE802.11 header */
1877         m_copydata(m0, 0, hdrlen, (caddr_t)&desc->wh);
1878         m_adj(m0, hdrlen);
1879
1880         error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map, m0, segs,
1881             &nsegs, 0);
1882         if (error != 0 && error != EFBIG) {
1883                 device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1884                     error);
1885                 m_freem(m0);
1886                 return error;
1887         }
1888         if (error != 0) {
1889                 mnew = m_defrag(m0, M_DONTWAIT);
1890                 if (mnew == NULL) {
1891                         device_printf(sc->sc_dev,
1892                             "could not defragment mbuf\n");
1893                         m_freem(m0);
1894                         return ENOBUFS;
1895                 }
1896                 m0 = mnew;
1897
1898                 error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map,
1899                     m0, segs, &nsegs, 0);
1900                 if (error != 0) {
1901                         device_printf(sc->sc_dev,
1902                             "could not map mbuf (error %d)\n", error);
1903                         m_freem(m0);
1904                         return error;
1905                 }
1906         }
1907
1908         data->m = m0;
1909         data->ni = ni;
1910
1911         desc->hdr.type = IWI_HDR_TYPE_DATA;
1912         desc->hdr.flags = IWI_HDR_FLAG_IRQ;
1913         desc->station = staid;
1914         desc->cmd = IWI_DATA_CMD_TX;
1915         desc->len = htole16(m0->m_pkthdr.len);
1916         desc->flags = flags;
1917         desc->xflags = xflags;
1918
1919 #if 0
1920         if (vap->iv_flags & IEEE80211_F_PRIVACY)
1921                 desc->wep_txkey = vap->iv_def_txkey;
1922         else
1923 #endif
1924                 desc->flags |= IWI_DATA_FLAG_NO_WEP;
1925
1926         desc->nseg = htole32(nsegs);
1927         for (i = 0; i < nsegs; i++) {
1928                 desc->seg_addr[i] = htole32(segs[i].ds_addr);
1929                 desc->seg_len[i]  = htole16(segs[i].ds_len);
1930         }
1931
1932         bus_dmamap_sync(txq->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1933         bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_PREWRITE);
1934
1935         DPRINTFN(5, ("sending data frame txq=%u idx=%u len=%u nseg=%u\n",
1936             ac, txq->cur, le16toh(desc->len), nsegs));
1937
1938         txq->queued++;
1939         txq->cur = (txq->cur + 1) % IWI_TX_RING_COUNT;
1940         CSR_WRITE_4(sc, txq->csr_widx, txq->cur);
1941
1942         return 0;
1943 }
1944
1945 static int
1946 iwi_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
1947         const struct ieee80211_bpf_params *params)
1948 {
1949         /* no support; just discard */
1950         m_freem(m);
1951         ieee80211_free_node(ni);
1952         return 0;
1953 }
1954
1955 static void
1956 iwi_start_locked(struct ifnet *ifp)
1957 {
1958         struct iwi_softc *sc = ifp->if_softc;
1959         struct mbuf *m;
1960         struct ieee80211_node *ni;
1961         int ac;
1962
1963         IWI_LOCK_ASSERT(sc);
1964
1965         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
1966                 return;
1967
1968         for (;;) {
1969                 IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
1970                 if (m == NULL)
1971                         break;
1972                 ac = M_WME_GETAC(m);
1973                 if (sc->txq[ac].queued > IWI_TX_RING_COUNT - 8) {
1974                         /* there is no place left in this ring; tail drop */
1975                         /* XXX tail drop */
1976                         IFQ_DRV_PREPEND(&ifp->if_snd, m);
1977                         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1978                         break;
1979                 }
1980
1981                 BPF_MTAP(ifp, m);
1982
1983                 ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1984                 m = ieee80211_encap(ni, m);
1985                 if (m == NULL) {
1986                         ieee80211_free_node(ni);
1987                         ifp->if_oerrors++;
1988                         continue;
1989                 }
1990
1991                 if (iwi_tx_start(ifp, m, ni, ac) != 0) {
1992                         ieee80211_free_node(ni);
1993                         ifp->if_oerrors++;
1994                         break;
1995                 }
1996
1997                 sc->sc_tx_timer = 5;
1998         }
1999 }
2000
2001 static void
2002 iwi_start(struct ifnet *ifp)
2003 {
2004         struct iwi_softc *sc = ifp->if_softc;
2005         IWI_LOCK_DECL;
2006
2007         IWI_LOCK(sc);
2008         iwi_start_locked(ifp);
2009         IWI_UNLOCK(sc);
2010 }
2011
2012 static void
2013 iwi_watchdog(void *arg)
2014 {
2015         struct iwi_softc *sc = arg;
2016         struct ifnet *ifp = sc->sc_ifp;
2017
2018         IWI_LOCK_ASSERT(sc);
2019
2020         if (sc->sc_tx_timer > 0) {
2021                 if (--sc->sc_tx_timer == 0) {
2022                         if_printf(ifp, "device timeout\n");
2023                         ifp->if_oerrors++;
2024                         taskqueue_enqueue(sc->sc_tq2, &sc->sc_restarttask);
2025                 }
2026         }
2027         if (sc->sc_state_timer > 0) {
2028                 if (--sc->sc_state_timer == 0) {
2029                         if_printf(ifp, "firmware stuck in state %d, resetting\n",
2030                             sc->fw_state);
2031                         taskqueue_enqueue(sc->sc_tq2, &sc->sc_restarttask);
2032                         if (sc->fw_state == IWI_FW_SCANNING) {
2033                                 struct ieee80211com *ic = ifp->if_l2com;
2034                                 ieee80211_cancel_scan(TAILQ_FIRST(&ic->ic_vaps));
2035                         }
2036                         sc->sc_state_timer = 3;
2037                 }
2038         }
2039         if (sc->sc_busy_timer > 0) {
2040                 if (--sc->sc_busy_timer == 0) {
2041                         if_printf(ifp, "firmware command timeout, resetting\n");
2042                         taskqueue_enqueue(sc->sc_tq2, &sc->sc_restarttask);
2043                 }
2044         }
2045         callout_reset(&sc->sc_wdtimer, hz, iwi_watchdog, sc);
2046 }
2047
2048 static int
2049 iwi_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
2050 {
2051         struct iwi_softc *sc = ifp->if_softc;
2052         struct ieee80211com *ic = ifp->if_l2com;
2053         struct ifreq *ifr = (struct ifreq *) data;
2054         int error = 0, startall = 0;
2055         IWI_LOCK_DECL;
2056
2057         switch (cmd) {
2058         case SIOCSIFFLAGS:
2059                 IWI_LOCK(sc);
2060                 if (ifp->if_flags & IFF_UP) {
2061                         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
2062                                 iwi_init_locked(sc);
2063                                 startall = 1;
2064                         }
2065                 } else {
2066                         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2067                                 iwi_stop_locked(sc);
2068                 }
2069                 IWI_UNLOCK(sc);
2070                 if (startall)
2071                         ieee80211_start_all(ic);
2072                 break;
2073         case SIOCGIFMEDIA:
2074                 error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
2075                 break;
2076         case SIOCGIFADDR:
2077                 error = ether_ioctl(ifp, cmd, data);
2078                 break;
2079         default:
2080                 error = EINVAL;
2081                 break;
2082         }
2083         return error;
2084 }
2085
2086 static void
2087 iwi_stop_master(struct iwi_softc *sc)
2088 {
2089         uint32_t tmp;
2090         int ntries;
2091
2092         /* disable interrupts */
2093         CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, 0);
2094
2095         CSR_WRITE_4(sc, IWI_CSR_RST, IWI_RST_STOP_MASTER);
2096         for (ntries = 0; ntries < 5; ntries++) {
2097                 if (CSR_READ_4(sc, IWI_CSR_RST) & IWI_RST_MASTER_DISABLED)
2098                         break;
2099                 DELAY(10);
2100         }
2101         if (ntries == 5)
2102                 device_printf(sc->sc_dev, "timeout waiting for master\n");
2103
2104         tmp = CSR_READ_4(sc, IWI_CSR_RST);
2105         CSR_WRITE_4(sc, IWI_CSR_RST, tmp | IWI_RST_PRINCETON_RESET);
2106
2107         sc->flags &= ~IWI_FLAG_FW_INITED;
2108 }
2109
2110 static int
2111 iwi_reset(struct iwi_softc *sc)
2112 {
2113         uint32_t tmp;
2114         int i, ntries;
2115
2116         iwi_stop_master(sc);
2117
2118         tmp = CSR_READ_4(sc, IWI_CSR_CTL);
2119         CSR_WRITE_4(sc, IWI_CSR_CTL, tmp | IWI_CTL_INIT);
2120
2121         CSR_WRITE_4(sc, IWI_CSR_READ_INT, IWI_READ_INT_INIT_HOST);
2122
2123         /* wait for clock stabilization */
2124         for (ntries = 0; ntries < 1000; ntries++) {
2125                 if (CSR_READ_4(sc, IWI_CSR_CTL) & IWI_CTL_CLOCK_READY)
2126                         break;
2127                 DELAY(200);
2128         }
2129         if (ntries == 1000) {
2130                 device_printf(sc->sc_dev,
2131                     "timeout waiting for clock stabilization\n");
2132                 return EIO;
2133         }
2134
2135         tmp = CSR_READ_4(sc, IWI_CSR_RST);
2136         CSR_WRITE_4(sc, IWI_CSR_RST, tmp | IWI_RST_SOFT_RESET);
2137
2138         DELAY(10);
2139
2140         tmp = CSR_READ_4(sc, IWI_CSR_CTL);
2141         CSR_WRITE_4(sc, IWI_CSR_CTL, tmp | IWI_CTL_INIT);
2142
2143         /* clear NIC memory */
2144         CSR_WRITE_4(sc, IWI_CSR_AUTOINC_ADDR, 0);
2145         for (i = 0; i < 0xc000; i++)
2146                 CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, 0);
2147
2148         return 0;
2149 }
2150
2151 static const struct iwi_firmware_ohdr *
2152 iwi_setup_ofw(struct iwi_softc *sc, struct iwi_fw *fw)
2153 {
2154         const struct firmware *fp = fw->fp;
2155         const struct iwi_firmware_ohdr *hdr;
2156
2157         if (fp->datasize < sizeof (struct iwi_firmware_ohdr)) {
2158                 device_printf(sc->sc_dev, "image '%s' too small\n", fp->name);
2159                 return NULL;
2160         }
2161         hdr = (const struct iwi_firmware_ohdr *)fp->data;
2162         if ((IWI_FW_GET_MAJOR(le32toh(hdr->version)) != IWI_FW_REQ_MAJOR) ||
2163             (IWI_FW_GET_MINOR(le32toh(hdr->version)) != IWI_FW_REQ_MINOR)) {
2164                 device_printf(sc->sc_dev, "version for '%s' %d.%d != %d.%d\n",
2165                     fp->name, IWI_FW_GET_MAJOR(le32toh(hdr->version)),
2166                     IWI_FW_GET_MINOR(le32toh(hdr->version)), IWI_FW_REQ_MAJOR,
2167                     IWI_FW_REQ_MINOR);
2168                 return NULL;
2169         }
2170         fw->data = ((const char *) fp->data) + sizeof(struct iwi_firmware_ohdr);
2171         fw->size = fp->datasize - sizeof(struct iwi_firmware_ohdr);
2172         fw->name = fp->name;
2173         return hdr;
2174 }
2175
2176 static const struct iwi_firmware_ohdr *
2177 iwi_setup_oucode(struct iwi_softc *sc, struct iwi_fw *fw)
2178 {
2179         const struct iwi_firmware_ohdr *hdr;
2180
2181         hdr = iwi_setup_ofw(sc, fw);
2182         if (hdr != NULL && le32toh(hdr->mode) != IWI_FW_MODE_UCODE) {
2183                 device_printf(sc->sc_dev, "%s is not a ucode image\n",
2184                     fw->name);
2185                 hdr = NULL;
2186         }
2187         return hdr;
2188 }
2189
2190 static void
2191 iwi_getfw(struct iwi_fw *fw, const char *fwname,
2192           struct iwi_fw *uc, const char *ucname)
2193 {
2194         if (fw->fp == NULL)
2195                 fw->fp = firmware_get(fwname);
2196         /* NB: pre-3.0 ucode is packaged separately */
2197         if (uc->fp == NULL && fw->fp != NULL && fw->fp->version < 300)
2198                 uc->fp = firmware_get(ucname);
2199 }
2200
2201 /*
2202  * Get the required firmware images if not already loaded.
2203  * Note that we hold firmware images so long as the device
2204  * is marked up in case we need to reload them on device init.
2205  * This is necessary because we re-init the device sometimes
2206  * from a context where we cannot read from the filesystem
2207  * (e.g. from the taskqueue thread when rfkill is re-enabled).
2208  * XXX return 0 on success, 1 on error.
2209  *
2210  * NB: the order of get'ing and put'ing images here is
2211  * intentional to support handling firmware images bundled
2212  * by operating mode and/or all together in one file with
2213  * the boot firmware as "master".
2214  */
2215 static int
2216 iwi_get_firmware(struct iwi_softc *sc, enum ieee80211_opmode opmode)
2217 {
2218         const struct iwi_firmware_hdr *hdr;
2219         const struct firmware *fp;
2220
2221         /* invalidate cached firmware on mode change */
2222         if (sc->fw_mode != opmode)
2223                 iwi_put_firmware(sc);
2224
2225         switch (opmode) {
2226         case IEEE80211_M_STA:
2227                 iwi_getfw(&sc->fw_fw, "iwi_bss", &sc->fw_uc, "iwi_ucode_bss");
2228                 break;
2229         case IEEE80211_M_IBSS:
2230                 iwi_getfw(&sc->fw_fw, "iwi_ibss", &sc->fw_uc, "iwi_ucode_ibss");
2231                 break;
2232         case IEEE80211_M_MONITOR:
2233                 iwi_getfw(&sc->fw_fw, "iwi_monitor",
2234                           &sc->fw_uc, "iwi_ucode_monitor");
2235                 break;
2236         default:
2237                 break;
2238         }
2239         fp = sc->fw_fw.fp;
2240         if (fp == NULL) {
2241                 device_printf(sc->sc_dev, "could not load firmware\n");
2242                 goto bad;
2243         }
2244         if (fp->version < 300) {
2245                 /*
2246                  * Firmware prior to 3.0 was packaged as separate
2247                  * boot, firmware, and ucode images.  Verify the
2248                  * ucode image was read in, retrieve the boot image
2249                  * if needed, and check version stamps for consistency.
2250                  * The version stamps in the data are also checked
2251                  * above; this is a bit paranoid but is a cheap
2252                  * safeguard against mis-packaging.
2253                  */
2254                 if (sc->fw_uc.fp == NULL) {
2255                         device_printf(sc->sc_dev, "could not load ucode\n");
2256                         goto bad;
2257                 }
2258                 if (sc->fw_boot.fp == NULL) {
2259                         sc->fw_boot.fp = firmware_get("iwi_boot");
2260                         if (sc->fw_boot.fp == NULL) {
2261                                 device_printf(sc->sc_dev,
2262                                         "could not load boot firmware\n");
2263                                 goto bad;
2264                         }
2265                 }
2266                 if (sc->fw_boot.fp->version != sc->fw_fw.fp->version ||
2267                     sc->fw_boot.fp->version != sc->fw_uc.fp->version) {
2268                         device_printf(sc->sc_dev,
2269                             "firmware version mismatch: "
2270                             "'%s' is %d, '%s' is %d, '%s' is %d\n",
2271                             sc->fw_boot.fp->name, sc->fw_boot.fp->version,
2272                             sc->fw_uc.fp->name, sc->fw_uc.fp->version,
2273                             sc->fw_fw.fp->name, sc->fw_fw.fp->version
2274                         );
2275                         goto bad;
2276                 }
2277                 /*
2278                  * Check and setup each image.
2279                  */
2280                 if (iwi_setup_oucode(sc, &sc->fw_uc) == NULL ||
2281                     iwi_setup_ofw(sc, &sc->fw_boot) == NULL ||
2282                     iwi_setup_ofw(sc, &sc->fw_fw) == NULL)
2283                         goto bad;
2284         } else {
2285                 /*
2286                  * Check and setup combined image.
2287                  */
2288                 if (fp->datasize < sizeof(struct iwi_firmware_hdr)) {
2289                         device_printf(sc->sc_dev, "image '%s' too small\n",
2290                             fp->name);
2291                         goto bad;
2292                 }
2293                 hdr = (const struct iwi_firmware_hdr *)fp->data;
2294                 if (fp->datasize < sizeof(*hdr) + le32toh(hdr->bsize) + le32toh(hdr->usize)
2295                                 + le32toh(hdr->fsize)) {
2296                         device_printf(sc->sc_dev, "image '%s' too small (2)\n",
2297                             fp->name);
2298                         goto bad;
2299                 }
2300                 sc->fw_boot.data = ((const char *) fp->data) + sizeof(*hdr);
2301                 sc->fw_boot.size = le32toh(hdr->bsize);
2302                 sc->fw_boot.name = fp->name;
2303                 sc->fw_uc.data = sc->fw_boot.data + sc->fw_boot.size;
2304                 sc->fw_uc.size = le32toh(hdr->usize);
2305                 sc->fw_uc.name = fp->name;
2306                 sc->fw_fw.data = sc->fw_uc.data + sc->fw_uc.size;
2307                 sc->fw_fw.size = le32toh(hdr->fsize);
2308                 sc->fw_fw.name = fp->name;
2309         }
2310 #if 0
2311         device_printf(sc->sc_dev, "boot %d ucode %d fw %d bytes\n",
2312                 sc->fw_boot.size, sc->fw_uc.size, sc->fw_fw.size);
2313 #endif
2314
2315         sc->fw_mode = opmode;
2316         return 0;
2317 bad:
2318         iwi_put_firmware(sc);
2319         return 1;
2320 }
2321
2322 static void
2323 iwi_put_fw(struct iwi_fw *fw)
2324 {
2325         if (fw->fp != NULL) {
2326                 firmware_put(fw->fp, FIRMWARE_UNLOAD);
2327                 fw->fp = NULL;
2328         }
2329         fw->data = NULL;
2330         fw->size = 0;
2331         fw->name = NULL;
2332 }
2333
2334 /*
2335  * Release any cached firmware images.
2336  */
2337 static void
2338 iwi_put_firmware(struct iwi_softc *sc)
2339 {
2340         iwi_put_fw(&sc->fw_uc);
2341         iwi_put_fw(&sc->fw_fw);
2342         iwi_put_fw(&sc->fw_boot);
2343 }
2344
2345 static int
2346 iwi_load_ucode(struct iwi_softc *sc, const struct iwi_fw *fw)
2347 {
2348         uint32_t tmp;
2349         const uint16_t *w;
2350         const char *uc = fw->data;
2351         size_t size = fw->size;
2352         int i, ntries, error;
2353
2354         IWI_LOCK_ASSERT(sc);
2355         error = 0;
2356         CSR_WRITE_4(sc, IWI_CSR_RST, CSR_READ_4(sc, IWI_CSR_RST) |
2357             IWI_RST_STOP_MASTER);
2358         for (ntries = 0; ntries < 5; ntries++) {
2359                 if (CSR_READ_4(sc, IWI_CSR_RST) & IWI_RST_MASTER_DISABLED)
2360                         break;
2361                 DELAY(10);
2362         }
2363         if (ntries == 5) {
2364                 device_printf(sc->sc_dev, "timeout waiting for master\n");
2365                 error = EIO;
2366                 goto fail;
2367         }
2368
2369         MEM_WRITE_4(sc, 0x3000e0, 0x80000000);
2370         DELAY(5000);
2371
2372         tmp = CSR_READ_4(sc, IWI_CSR_RST);
2373         tmp &= ~IWI_RST_PRINCETON_RESET;
2374         CSR_WRITE_4(sc, IWI_CSR_RST, tmp);
2375
2376         DELAY(5000);
2377         MEM_WRITE_4(sc, 0x3000e0, 0);
2378         DELAY(1000);
2379         MEM_WRITE_4(sc, IWI_MEM_EEPROM_EVENT, 1);
2380         DELAY(1000);
2381         MEM_WRITE_4(sc, IWI_MEM_EEPROM_EVENT, 0);
2382         DELAY(1000);
2383         MEM_WRITE_1(sc, 0x200000, 0x00);
2384         MEM_WRITE_1(sc, 0x200000, 0x40);
2385         DELAY(1000);
2386
2387         /* write microcode into adapter memory */
2388         for (w = (const uint16_t *)uc; size > 0; w++, size -= 2)
2389                 MEM_WRITE_2(sc, 0x200010, htole16(*w));
2390
2391         MEM_WRITE_1(sc, 0x200000, 0x00);
2392         MEM_WRITE_1(sc, 0x200000, 0x80);
2393
2394         /* wait until we get an answer */
2395         for (ntries = 0; ntries < 100; ntries++) {
2396                 if (MEM_READ_1(sc, 0x200000) & 1)
2397                         break;
2398                 DELAY(100);
2399         }
2400         if (ntries == 100) {
2401                 device_printf(sc->sc_dev,
2402                     "timeout waiting for ucode to initialize\n");
2403                 error = EIO;
2404                 goto fail;
2405         }
2406
2407         /* read the answer or the firmware will not initialize properly */
2408         for (i = 0; i < 7; i++)
2409                 MEM_READ_4(sc, 0x200004);
2410
2411         MEM_WRITE_1(sc, 0x200000, 0x00);
2412
2413 fail:
2414         return error;
2415 }
2416
2417 /* macro to handle unaligned little endian data in firmware image */
2418 #define GETLE32(p) ((p)[0] | (p)[1] << 8 | (p)[2] << 16 | (p)[3] << 24)
2419
2420 static int
2421 iwi_load_firmware(struct iwi_softc *sc, const struct iwi_fw *fw)
2422 {
2423         u_char *p, *end;
2424         uint32_t sentinel, ctl, src, dst, sum, len, mlen, tmp;
2425         int ntries, error;
2426
2427         IWI_LOCK_ASSERT(sc);
2428
2429         /* copy firmware image to DMA memory */
2430         memcpy(sc->fw_virtaddr, fw->data, fw->size);
2431
2432         /* make sure the adapter will get up-to-date values */
2433         bus_dmamap_sync(sc->fw_dmat, sc->fw_map, BUS_DMASYNC_PREWRITE);
2434
2435         /* tell the adapter where the command blocks are stored */
2436         MEM_WRITE_4(sc, 0x3000a0, 0x27000);
2437
2438         /*
2439          * Store command blocks into adapter's internal memory using register
2440          * indirections. The adapter will read the firmware image through DMA
2441          * using information stored in command blocks.
2442          */
2443         src = sc->fw_physaddr;
2444         p = sc->fw_virtaddr;
2445         end = p + fw->size;
2446         CSR_WRITE_4(sc, IWI_CSR_AUTOINC_ADDR, 0x27000);
2447
2448         while (p < end) {
2449                 dst = GETLE32(p); p += 4; src += 4;
2450                 len = GETLE32(p); p += 4; src += 4;
2451                 p += len;
2452
2453                 while (len > 0) {
2454                         mlen = min(len, IWI_CB_MAXDATALEN);
2455
2456                         ctl = IWI_CB_DEFAULT_CTL | mlen;
2457                         sum = ctl ^ src ^ dst;
2458
2459                         /* write a command block */
2460                         CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, ctl);
2461                         CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, src);
2462                         CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, dst);
2463                         CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, sum);
2464
2465                         src += mlen;
2466                         dst += mlen;
2467                         len -= mlen;
2468                 }
2469         }
2470
2471         /* write a fictive final command block (sentinel) */
2472         sentinel = CSR_READ_4(sc, IWI_CSR_AUTOINC_ADDR);
2473         CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, 0);
2474
2475         tmp = CSR_READ_4(sc, IWI_CSR_RST);
2476         tmp &= ~(IWI_RST_MASTER_DISABLED | IWI_RST_STOP_MASTER);
2477         CSR_WRITE_4(sc, IWI_CSR_RST, tmp);
2478
2479         /* tell the adapter to start processing command blocks */
2480         MEM_WRITE_4(sc, 0x3000a4, 0x540100);
2481
2482         /* wait until the adapter reaches the sentinel */
2483         for (ntries = 0; ntries < 400; ntries++) {
2484                 if (MEM_READ_4(sc, 0x3000d0) >= sentinel)
2485                         break;
2486                 DELAY(100);
2487         }
2488         /* sync dma, just in case */
2489         bus_dmamap_sync(sc->fw_dmat, sc->fw_map, BUS_DMASYNC_POSTWRITE);
2490         if (ntries == 400) {
2491                 device_printf(sc->sc_dev,
2492                     "timeout processing command blocks for %s firmware\n",
2493                     fw->name);
2494                 return EIO;
2495         }
2496
2497         /* we're done with command blocks processing */
2498         MEM_WRITE_4(sc, 0x3000a4, 0x540c00);
2499
2500         /* allow interrupts so we know when the firmware is ready */
2501         CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, IWI_INTR_MASK);
2502
2503         /* tell the adapter to initialize the firmware */
2504         CSR_WRITE_4(sc, IWI_CSR_RST, 0);
2505
2506         tmp = CSR_READ_4(sc, IWI_CSR_CTL);
2507         CSR_WRITE_4(sc, IWI_CSR_CTL, tmp | IWI_CTL_ALLOW_STANDBY);
2508
2509         /* wait at most one second for firmware initialization to complete */
2510         if ((error = msleep(sc, &sc->sc_mtx, 0, "iwiinit", hz)) != 0) {
2511                 device_printf(sc->sc_dev, "timeout waiting for %s firmware "
2512                     "initialization to complete\n", fw->name);
2513         }
2514
2515         return error;
2516 }
2517
2518 static int
2519 iwi_setpowermode(struct iwi_softc *sc, struct ieee80211vap *vap)
2520 {
2521         uint32_t data;
2522
2523         if (vap->iv_flags & IEEE80211_F_PMGTON) {
2524                 /* XXX set more fine-grained operation */
2525                 data = htole32(IWI_POWER_MODE_MAX);
2526         } else
2527                 data = htole32(IWI_POWER_MODE_CAM);
2528
2529         DPRINTF(("Setting power mode to %u\n", le32toh(data)));
2530         return iwi_cmd(sc, IWI_CMD_SET_POWER_MODE, &data, sizeof data);
2531 }
2532
2533 static int
2534 iwi_setwepkeys(struct iwi_softc *sc, struct ieee80211vap *vap)
2535 {
2536         struct iwi_wep_key wepkey;
2537         struct ieee80211_key *wk;
2538         int error, i;
2539
2540         for (i = 0; i < IEEE80211_WEP_NKID; i++) {
2541                 wk = &vap->iv_nw_keys[i];
2542
2543                 wepkey.cmd = IWI_WEP_KEY_CMD_SETKEY;
2544                 wepkey.idx = i;
2545                 wepkey.len = wk->wk_keylen;
2546                 memset(wepkey.key, 0, sizeof wepkey.key);
2547                 memcpy(wepkey.key, wk->wk_key, wk->wk_keylen);
2548                 DPRINTF(("Setting wep key index %u len %u\n", wepkey.idx,
2549                     wepkey.len));
2550                 error = iwi_cmd(sc, IWI_CMD_SET_WEP_KEY, &wepkey,
2551                     sizeof wepkey);
2552                 if (error != 0)
2553                         return error;
2554         }
2555         return 0;
2556 }
2557
2558 static int
2559 iwi_config(struct iwi_softc *sc)
2560 {
2561         struct ifnet *ifp = sc->sc_ifp;
2562         struct ieee80211com *ic = ifp->if_l2com;
2563         struct iwi_configuration config;
2564         struct iwi_rateset rs;
2565         struct iwi_txpower power;
2566         uint32_t data;
2567         int error, i;
2568
2569         IWI_LOCK_ASSERT(sc);
2570
2571         IEEE80211_ADDR_COPY(ic->ic_myaddr, IF_LLADDR(ifp));
2572         DPRINTF(("Setting MAC address to %6D\n", ic->ic_myaddr, ":"));
2573         error = iwi_cmd(sc, IWI_CMD_SET_MAC_ADDRESS, ic->ic_myaddr,
2574             IEEE80211_ADDR_LEN);
2575         if (error != 0)
2576                 return error;
2577
2578         memset(&config, 0, sizeof config);
2579         config.bluetooth_coexistence = sc->bluetooth;
2580         config.silence_threshold = 0x1e;
2581         config.antenna = sc->antenna;
2582         config.multicast_enabled = 1;
2583         config.answer_pbreq = (ic->ic_opmode == IEEE80211_M_IBSS) ? 1 : 0;
2584         config.disable_unicast_decryption = 1;
2585         config.disable_multicast_decryption = 1;
2586         DPRINTF(("Configuring adapter\n"));
2587         error = iwi_cmd(sc, IWI_CMD_SET_CONFIG, &config, sizeof config);
2588         if (error != 0)
2589                 return error;
2590         if (ic->ic_opmode == IEEE80211_M_IBSS) {
2591                 power.mode = IWI_MODE_11B;
2592                 power.nchan = 11;
2593                 for (i = 0; i < 11; i++) {
2594                         power.chan[i].chan = i + 1;
2595                         power.chan[i].power = IWI_TXPOWER_MAX;
2596                 }
2597                 DPRINTF(("Setting .11b channels tx power\n"));
2598                 error = iwi_cmd(sc, IWI_CMD_SET_TX_POWER, &power, sizeof power);
2599                 if (error != 0)
2600                         return error;
2601
2602                 power.mode = IWI_MODE_11G;
2603                 DPRINTF(("Setting .11g channels tx power\n"));
2604                 error = iwi_cmd(sc, IWI_CMD_SET_TX_POWER, &power, sizeof power);
2605                 if (error != 0)
2606                         return error;
2607         }
2608
2609         memset(&rs, 0, sizeof rs);
2610         rs.mode = IWI_MODE_11G;
2611         rs.type = IWI_RATESET_TYPE_SUPPORTED;
2612         rs.nrates = ic->ic_sup_rates[IEEE80211_MODE_11G].rs_nrates;
2613         memcpy(rs.rates, ic->ic_sup_rates[IEEE80211_MODE_11G].rs_rates,
2614             rs.nrates);
2615         DPRINTF(("Setting .11bg supported rates (%u)\n", rs.nrates));
2616         error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs);
2617         if (error != 0)
2618                 return error;
2619
2620         memset(&rs, 0, sizeof rs);
2621         rs.mode = IWI_MODE_11A;
2622         rs.type = IWI_RATESET_TYPE_SUPPORTED;
2623         rs.nrates = ic->ic_sup_rates[IEEE80211_MODE_11A].rs_nrates;
2624         memcpy(rs.rates, ic->ic_sup_rates[IEEE80211_MODE_11A].rs_rates,
2625             rs.nrates);
2626         DPRINTF(("Setting .11a supported rates (%u)\n", rs.nrates));
2627         error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs);
2628         if (error != 0)
2629                 return error;
2630
2631         data = htole32(arc4random());
2632         DPRINTF(("Setting initialization vector to %u\n", le32toh(data)));
2633         error = iwi_cmd(sc, IWI_CMD_SET_IV, &data, sizeof data);
2634         if (error != 0)
2635                 return error;
2636
2637         /* enable adapter */
2638         DPRINTF(("Enabling adapter\n"));
2639         return iwi_cmd(sc, IWI_CMD_ENABLE, NULL, 0);
2640 }
2641
2642 static __inline void
2643 set_scan_type(struct iwi_scan_ext *scan, int ix, int scan_type)
2644 {
2645         uint8_t *st = &scan->scan_type[ix / 2];
2646         if (ix % 2)
2647                 *st = (*st & 0xf0) | ((scan_type & 0xf) << 0);
2648         else
2649                 *st = (*st & 0x0f) | ((scan_type & 0xf) << 4);
2650 }
2651
2652 static int
2653 scan_type(const struct ieee80211_scan_state *ss,
2654         const struct ieee80211_channel *chan)
2655 {
2656         /* We can only set one essid for a directed scan */
2657         if (ss->ss_nssid != 0)
2658                 return IWI_SCAN_TYPE_BDIRECTED;
2659         if ((ss->ss_flags & IEEE80211_SCAN_ACTIVE) &&
2660             (chan->ic_flags & IEEE80211_CHAN_PASSIVE) == 0)
2661                 return IWI_SCAN_TYPE_BROADCAST;
2662         return IWI_SCAN_TYPE_PASSIVE;
2663 }
2664
2665 static __inline int
2666 scan_band(const struct ieee80211_channel *c)
2667 {
2668         return IEEE80211_IS_CHAN_5GHZ(c) ?  IWI_CHAN_5GHZ : IWI_CHAN_2GHZ;
2669 }
2670
2671 /*
2672  * Start a scan on the current channel or all channels.
2673  */
2674 static int
2675 iwi_scanchan(struct iwi_softc *sc, unsigned long maxdwell, int mode)
2676 {
2677         struct ieee80211com *ic;
2678         struct ieee80211_channel *chan;
2679         struct ieee80211_scan_state *ss;
2680         struct iwi_scan_ext scan;
2681         int error = 0;
2682
2683         IWI_LOCK_ASSERT(sc);
2684         if (sc->fw_state == IWI_FW_SCANNING) {
2685                 /*
2686                  * This should not happen as we only trigger scan_next after
2687                  * completion
2688                  */
2689                 DPRINTF(("%s: called too early - still scanning\n", __func__));
2690                 return (EBUSY);
2691         }
2692         IWI_STATE_BEGIN(sc, IWI_FW_SCANNING);
2693
2694         ic = sc->sc_ifp->if_l2com;
2695         ss = ic->ic_scan;
2696
2697         memset(&scan, 0, sizeof scan);
2698         scan.full_scan_index = htole32(++sc->sc_scangen);
2699         scan.dwell_time[IWI_SCAN_TYPE_PASSIVE] = htole16(maxdwell);
2700         if (ic->ic_flags_ext & IEEE80211_FEXT_BGSCAN) {
2701                 /*
2702                  * Use very short dwell times for when we send probe request
2703                  * frames.  Without this bg scans hang.  Ideally this should
2704                  * be handled with early-termination as done by net80211 but
2705                  * that's not feasible (aborting a scan is problematic).
2706                  */
2707                 scan.dwell_time[IWI_SCAN_TYPE_BROADCAST] = htole16(30);
2708                 scan.dwell_time[IWI_SCAN_TYPE_BDIRECTED] = htole16(30);
2709         } else {
2710                 scan.dwell_time[IWI_SCAN_TYPE_BROADCAST] = htole16(maxdwell);
2711                 scan.dwell_time[IWI_SCAN_TYPE_BDIRECTED] = htole16(maxdwell);
2712         }
2713
2714         /* We can only set one essid for a directed scan */
2715         if (ss->ss_nssid != 0) {
2716                 error = iwi_cmd(sc, IWI_CMD_SET_ESSID, ss->ss_ssid[0].ssid,
2717                     ss->ss_ssid[0].len);
2718                 if (error)
2719                         return (error);
2720         }
2721
2722         if (mode == IWI_SCAN_ALLCHAN) {
2723                 int i, next, band, b, bstart;
2724                 /*
2725                  * Convert scan list to run-length encoded channel list
2726                  * the firmware requires (preserving the order setup by
2727                  * net80211).  The first entry in each run specifies the
2728                  * band and the count of items in the run.
2729                  */
2730                 next = 0;               /* next open slot */
2731                 bstart = 0;             /* NB: not needed, silence compiler */
2732                 band = -1;              /* NB: impossible value */
2733                 KASSERT(ss->ss_last > 0, ("no channels"));
2734                 for (i = 0; i < ss->ss_last; i++) {
2735                         chan = ss->ss_chans[i];
2736                         b = scan_band(chan);
2737                         if (b != band) {
2738                                 if (band != -1)
2739                                         scan.channels[bstart] =
2740                                             (next - bstart) | band;
2741                                 /* NB: this allocates a slot for the run-len */
2742                                 band = b, bstart = next++;
2743                         }
2744                         if (next >= IWI_SCAN_CHANNELS) {
2745                                 DPRINTF(("truncating scan list\n"));
2746                                 break;
2747                         }
2748                         scan.channels[next] = ieee80211_chan2ieee(ic, chan);
2749                         set_scan_type(&scan, next, scan_type(ss, chan));
2750                         next++;
2751                 }
2752                 scan.channels[bstart] = (next - bstart) | band;
2753         } else {
2754                 /* Scan the current channel only */
2755                 chan = ic->ic_curchan;
2756                 scan.channels[0] = 1 | scan_band(chan);
2757                 scan.channels[1] = ieee80211_chan2ieee(ic, chan);
2758                 set_scan_type(&scan, 1, scan_type(ss, chan));
2759         }
2760 #ifdef IWI_DEBUG
2761         if (iwi_debug > 0) {
2762                 static const char *scantype[8] =
2763                    { "PSTOP", "PASV", "DIR", "BCAST", "BDIR", "5", "6", "7" };
2764                 int i;
2765                 printf("Scan request: index %u dwell %d/%d/%d\n"
2766                     , le32toh(scan.full_scan_index)
2767                     , le16toh(scan.dwell_time[IWI_SCAN_TYPE_PASSIVE])
2768                     , le16toh(scan.dwell_time[IWI_SCAN_TYPE_BROADCAST])
2769                     , le16toh(scan.dwell_time[IWI_SCAN_TYPE_BDIRECTED])
2770                 );
2771                 i = 0;
2772                 do {
2773                         int run = scan.channels[i];
2774                         if (run == 0)
2775                                 break;
2776                         printf("Scan %d %s channels:", run & 0x3f,
2777                             run & IWI_CHAN_2GHZ ? "2.4GHz" : "5GHz");
2778                         for (run &= 0x3f, i++; run > 0; run--, i++) {
2779                                 uint8_t type = scan.scan_type[i/2];
2780                                 printf(" %u/%s", scan.channels[i],
2781                                     scantype[(i & 1 ? type : type>>4) & 7]);
2782                         }
2783                         printf("\n");
2784                 } while (i < IWI_SCAN_CHANNELS);
2785         }
2786 #endif
2787
2788         return (iwi_cmd(sc, IWI_CMD_SCAN_EXT, &scan, sizeof scan));
2789 }
2790
2791 static void
2792 iwi_scanabort(void *arg, int npending)
2793 {
2794         struct iwi_softc *sc = arg;
2795         IWI_LOCK_DECL;
2796
2797         IWI_LOCK(sc);
2798         sc->flags &= ~IWI_FLAG_CHANNEL_SCAN;
2799         /* NB: make sure we're still scanning */
2800         if (sc->fw_state == IWI_FW_SCANNING)
2801                 iwi_cmd(sc, IWI_CMD_ABORT_SCAN, NULL, 0);
2802         IWI_UNLOCK(sc);
2803 }
2804
2805 static int
2806 iwi_set_sensitivity(struct iwi_softc *sc, int8_t rssi_dbm)
2807 {
2808         struct iwi_sensitivity sens;
2809
2810         DPRINTF(("Setting sensitivity to %d\n", rssi_dbm));
2811
2812         memset(&sens, 0, sizeof sens);
2813         sens.rssi = htole16(rssi_dbm);
2814         return iwi_cmd(sc, IWI_CMD_SET_SENSITIVITY, &sens, sizeof sens);
2815 }
2816
2817 static int
2818 iwi_auth_and_assoc(struct iwi_softc *sc, struct ieee80211vap *vap)
2819 {
2820         struct ieee80211com *ic = vap->iv_ic;
2821         struct ifnet *ifp = vap->iv_ifp;
2822         struct ieee80211_node *ni = vap->iv_bss;
2823         struct iwi_configuration config;
2824         struct iwi_associate *assoc = &sc->assoc;
2825         struct iwi_rateset rs;
2826         uint16_t capinfo;
2827         uint32_t data;
2828         int error, mode;
2829
2830         IWI_LOCK_ASSERT(sc);
2831
2832         if (sc->flags & IWI_FLAG_ASSOCIATED) {
2833                 DPRINTF(("Already associated\n"));
2834                 return (-1);
2835         }
2836
2837         IWI_STATE_BEGIN(sc, IWI_FW_ASSOCIATING);
2838         error = 0;
2839         mode = 0;
2840
2841         if (IEEE80211_IS_CHAN_A(ic->ic_curchan))
2842                 mode = IWI_MODE_11A;
2843         else if (IEEE80211_IS_CHAN_G(ic->ic_curchan))
2844                 mode = IWI_MODE_11G;
2845         if (IEEE80211_IS_CHAN_B(ic->ic_curchan))
2846                 mode = IWI_MODE_11B;
2847
2848         if (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan)) {
2849                 memset(&config, 0, sizeof config);
2850                 config.bluetooth_coexistence = sc->bluetooth;
2851                 config.antenna = sc->antenna;
2852                 config.multicast_enabled = 1;
2853                 if (mode == IWI_MODE_11G)
2854                         config.use_protection = 1;
2855                 config.answer_pbreq =
2856                     (vap->iv_opmode == IEEE80211_M_IBSS) ? 1 : 0;
2857                 config.disable_unicast_decryption = 1;
2858                 config.disable_multicast_decryption = 1;
2859                 DPRINTF(("Configuring adapter\n"));
2860                 error = iwi_cmd(sc, IWI_CMD_SET_CONFIG, &config, sizeof config);
2861                 if (error != 0)
2862                         goto done;
2863         }
2864
2865 #ifdef IWI_DEBUG
2866         if (iwi_debug > 0) {
2867                 printf("Setting ESSID to ");
2868                 ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
2869                 printf("\n");
2870         }
2871 #endif
2872         error = iwi_cmd(sc, IWI_CMD_SET_ESSID, ni->ni_essid, ni->ni_esslen);
2873         if (error != 0)
2874                 goto done;
2875
2876         error = iwi_setpowermode(sc, vap);
2877         if (error != 0)
2878                 goto done;
2879
2880         data = htole32(vap->iv_rtsthreshold);
2881         DPRINTF(("Setting RTS threshold to %u\n", le32toh(data)));
2882         error = iwi_cmd(sc, IWI_CMD_SET_RTS_THRESHOLD, &data, sizeof data);
2883         if (error != 0)
2884                 goto done;
2885
2886         data = htole32(vap->iv_fragthreshold);
2887         DPRINTF(("Setting fragmentation threshold to %u\n", le32toh(data)));
2888         error = iwi_cmd(sc, IWI_CMD_SET_FRAG_THRESHOLD, &data, sizeof data);
2889         if (error != 0)
2890                 goto done;
2891
2892         /* the rate set has already been "negotiated" */
2893         memset(&rs, 0, sizeof rs);
2894         rs.mode = mode;
2895         rs.type = IWI_RATESET_TYPE_NEGOTIATED;
2896         rs.nrates = ni->ni_rates.rs_nrates;
2897         if (rs.nrates > IWI_RATESET_SIZE) {
2898                 DPRINTF(("Truncating negotiated rate set from %u\n",
2899                     rs.nrates));
2900                 rs.nrates = IWI_RATESET_SIZE;
2901         }
2902         memcpy(rs.rates, ni->ni_rates.rs_rates, rs.nrates);
2903         DPRINTF(("Setting negotiated rates (%u)\n", rs.nrates));
2904         error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs);
2905         if (error != 0)
2906                 goto done;
2907
2908         memset(assoc, 0, sizeof *assoc);
2909
2910         if ((vap->iv_flags & IEEE80211_F_WME) && ni->ni_ies.wme_ie != NULL) {
2911                 /* NB: don't treat WME setup as failure */
2912                 if (iwi_wme_setparams(sc, ic) == 0 && iwi_wme_setie(sc) == 0)
2913                         assoc->policy |= htole16(IWI_POLICY_WME);
2914                 /* XXX complain on failure? */
2915         }
2916
2917         if (vap->iv_appie_wpa != NULL) {
2918                 struct ieee80211_appie *ie = vap->iv_appie_wpa;
2919
2920                 DPRINTF(("Setting optional IE (len=%u)\n", ie->ie_len));
2921                 error = iwi_cmd(sc, IWI_CMD_SET_OPTIE, ie->ie_data, ie->ie_len);
2922                 if (error != 0)
2923                         goto done;
2924         }
2925
2926         error = iwi_set_sensitivity(sc, ic->ic_node_getrssi(ni));
2927         if (error != 0)
2928                 goto done;
2929
2930         assoc->mode = mode;
2931         assoc->chan = ic->ic_curchan->ic_ieee;
2932         /*
2933          * NB: do not arrange for shared key auth w/o privacy
2934          *     (i.e. a wep key); it causes a firmware error.
2935          */
2936         if ((vap->iv_flags & IEEE80211_F_PRIVACY) &&
2937             ni->ni_authmode == IEEE80211_AUTH_SHARED) {
2938                 assoc->auth = IWI_AUTH_SHARED;
2939                 /*
2940                  * It's possible to have privacy marked but no default
2941                  * key setup.  This typically is due to a user app bug
2942                  * but if we blindly grab the key the firmware will
2943                  * barf so avoid it for now.
2944                  */ 
2945                 if (vap->iv_def_txkey != IEEE80211_KEYIX_NONE)
2946                         assoc->auth |= vap->iv_def_txkey << 4;
2947
2948                 error = iwi_setwepkeys(sc, vap);
2949                 if (error != 0)
2950                         goto done;
2951         }
2952         if (vap->iv_flags & IEEE80211_F_WPA)
2953                 assoc->policy |= htole16(IWI_POLICY_WPA);
2954         if (vap->iv_opmode == IEEE80211_M_IBSS && ni->ni_tstamp.tsf == 0)
2955                 assoc->type = IWI_HC_IBSS_START;
2956         else
2957                 assoc->type = IWI_HC_ASSOC;
2958         memcpy(assoc->tstamp, ni->ni_tstamp.data, 8);
2959
2960         if (vap->iv_opmode == IEEE80211_M_IBSS)
2961                 capinfo = IEEE80211_CAPINFO_IBSS;
2962         else
2963                 capinfo = IEEE80211_CAPINFO_ESS;
2964         if (vap->iv_flags & IEEE80211_F_PRIVACY)
2965                 capinfo |= IEEE80211_CAPINFO_PRIVACY;
2966         if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
2967             IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
2968                 capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
2969         if (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)
2970                 capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
2971         assoc->capinfo = htole16(capinfo);
2972
2973         assoc->lintval = htole16(ic->ic_lintval);
2974         assoc->intval = htole16(ni->ni_intval);
2975         IEEE80211_ADDR_COPY(assoc->bssid, ni->ni_bssid);
2976         if (vap->iv_opmode == IEEE80211_M_IBSS)
2977                 IEEE80211_ADDR_COPY(assoc->dst, ifp->if_broadcastaddr);
2978         else
2979                 IEEE80211_ADDR_COPY(assoc->dst, ni->ni_bssid);
2980
2981         DPRINTF(("%s bssid %6D dst %6D channel %u policy 0x%x "
2982             "auth %u capinfo 0x%x lintval %u bintval %u\n",
2983             assoc->type == IWI_HC_IBSS_START ? "Start" : "Join",
2984             assoc->bssid, ":", assoc->dst, ":",
2985             assoc->chan, le16toh(assoc->policy), assoc->auth,
2986             le16toh(assoc->capinfo), le16toh(assoc->lintval),
2987             le16toh(assoc->intval)));
2988         error = iwi_cmd(sc, IWI_CMD_ASSOCIATE, assoc, sizeof *assoc);
2989 done:
2990         if (error)
2991                 IWI_STATE_END(sc, IWI_FW_ASSOCIATING);
2992
2993         return (error);
2994 }
2995
2996 static int
2997 iwi_disassociate(struct iwi_softc *sc, int quiet)
2998 {
2999         struct iwi_associate *assoc = &sc->assoc;
3000
3001         if ((sc->flags & IWI_FLAG_ASSOCIATED) == 0) {
3002                 DPRINTF(("Not associated\n"));
3003                 return (-1);
3004         }
3005
3006         IWI_STATE_BEGIN(sc, IWI_FW_DISASSOCIATING);
3007
3008         if (quiet)
3009                 assoc->type = IWI_HC_DISASSOC_QUIET;
3010         else
3011                 assoc->type = IWI_HC_DISASSOC;
3012
3013         DPRINTF(("Trying to disassociate from %6D channel %u\n",
3014             assoc->bssid, ":", assoc->chan));
3015         return iwi_cmd(sc, IWI_CMD_ASSOCIATE, assoc, sizeof *assoc);
3016 }
3017
3018 /*
3019  * release dma resources for the firmware
3020  */
3021 static void
3022 iwi_release_fw_dma(struct iwi_softc *sc)
3023 {
3024         if (sc->fw_flags & IWI_FW_HAVE_PHY)
3025                 bus_dmamap_unload(sc->fw_dmat, sc->fw_map);
3026         if (sc->fw_flags & IWI_FW_HAVE_MAP)
3027                 bus_dmamem_free(sc->fw_dmat, sc->fw_virtaddr, sc->fw_map);
3028         if (sc->fw_flags & IWI_FW_HAVE_DMAT)
3029                 bus_dma_tag_destroy(sc->fw_dmat);
3030
3031         sc->fw_flags = 0;
3032         sc->fw_dma_size = 0;
3033         sc->fw_dmat = NULL;
3034         sc->fw_map = NULL;
3035         sc->fw_physaddr = 0;
3036         sc->fw_virtaddr = NULL;
3037 }
3038
3039 /*
3040  * allocate the dma descriptor for the firmware.
3041  * Return 0 on success, 1 on error.
3042  * Must be called unlocked, protected by IWI_FLAG_FW_LOADING.
3043  */
3044 static int
3045 iwi_init_fw_dma(struct iwi_softc *sc, int size)
3046 {
3047         if (sc->fw_dma_size >= size)
3048                 return 0;
3049         if (bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 4, 0,
3050             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
3051             size, 1, size, 0, NULL, NULL, &sc->fw_dmat) != 0) {
3052                 device_printf(sc->sc_dev,
3053                     "could not create firmware DMA tag\n");
3054                 goto error;
3055         }
3056         sc->fw_flags |= IWI_FW_HAVE_DMAT;
3057         if (bus_dmamem_alloc(sc->fw_dmat, &sc->fw_virtaddr, 0,
3058             &sc->fw_map) != 0) {
3059                 device_printf(sc->sc_dev,
3060                     "could not allocate firmware DMA memory\n");
3061                 goto error;
3062         }
3063         sc->fw_flags |= IWI_FW_HAVE_MAP;
3064         if (bus_dmamap_load(sc->fw_dmat, sc->fw_map, sc->fw_virtaddr,
3065             size, iwi_dma_map_addr, &sc->fw_physaddr, 0) != 0) {
3066                 device_printf(sc->sc_dev, "could not load firmware DMA map\n");
3067                 goto error;
3068         }
3069         sc->fw_flags |= IWI_FW_HAVE_PHY;
3070         sc->fw_dma_size = size;
3071         return 0;
3072
3073 error:
3074         iwi_release_fw_dma(sc);
3075         return 1;
3076 }
3077
3078 static void
3079 iwi_init_locked(struct iwi_softc *sc)
3080 {
3081         struct ifnet *ifp = sc->sc_ifp;
3082         struct iwi_rx_data *data;
3083         int i;
3084
3085         IWI_LOCK_ASSERT(sc);
3086
3087         if (sc->fw_state == IWI_FW_LOADING) {
3088                 device_printf(sc->sc_dev, "%s: already loading\n", __func__);
3089                 return;         /* XXX: condvar? */
3090         }
3091
3092         iwi_stop_locked(sc);
3093
3094         IWI_STATE_BEGIN(sc, IWI_FW_LOADING);
3095
3096         taskqueue_unblock(sc->sc_tq);
3097         taskqueue_unblock(sc->sc_tq2);
3098
3099         if (iwi_reset(sc) != 0) {
3100                 device_printf(sc->sc_dev, "could not reset adapter\n");
3101                 goto fail;
3102         }
3103         if (iwi_load_firmware(sc, &sc->fw_boot) != 0) {
3104                 device_printf(sc->sc_dev,
3105                     "could not load boot firmware %s\n", sc->fw_boot.name);
3106                 goto fail;
3107         }
3108         if (iwi_load_ucode(sc, &sc->fw_uc) != 0) {
3109                 device_printf(sc->sc_dev,
3110                     "could not load microcode %s\n", sc->fw_uc.name);
3111                 goto fail;
3112         }
3113
3114         iwi_stop_master(sc);
3115
3116         CSR_WRITE_4(sc, IWI_CSR_CMD_BASE, sc->cmdq.physaddr);
3117         CSR_WRITE_4(sc, IWI_CSR_CMD_SIZE, sc->cmdq.count);
3118         CSR_WRITE_4(sc, IWI_CSR_CMD_WIDX, sc->cmdq.cur);
3119
3120         CSR_WRITE_4(sc, IWI_CSR_TX1_BASE, sc->txq[0].physaddr);
3121         CSR_WRITE_4(sc, IWI_CSR_TX1_SIZE, sc->txq[0].count);
3122         CSR_WRITE_4(sc, IWI_CSR_TX1_WIDX, sc->txq[0].cur);
3123
3124         CSR_WRITE_4(sc, IWI_CSR_TX2_BASE, sc->txq[1].physaddr);
3125         CSR_WRITE_4(sc, IWI_CSR_TX2_SIZE, sc->txq[1].count);
3126         CSR_WRITE_4(sc, IWI_CSR_TX2_WIDX, sc->txq[1].cur);
3127
3128         CSR_WRITE_4(sc, IWI_CSR_TX3_BASE, sc->txq[2].physaddr);
3129         CSR_WRITE_4(sc, IWI_CSR_TX3_SIZE, sc->txq[2].count);
3130         CSR_WRITE_4(sc, IWI_CSR_TX3_WIDX, sc->txq[2].cur);
3131
3132         CSR_WRITE_4(sc, IWI_CSR_TX4_BASE, sc->txq[3].physaddr);
3133         CSR_WRITE_4(sc, IWI_CSR_TX4_SIZE, sc->txq[3].count);
3134         CSR_WRITE_4(sc, IWI_CSR_TX4_WIDX, sc->txq[3].cur);
3135
3136         for (i = 0; i < sc->rxq.count; i++) {
3137                 data = &sc->rxq.data[i];
3138                 CSR_WRITE_4(sc, data->reg, data->physaddr);
3139         }
3140
3141         CSR_WRITE_4(sc, IWI_CSR_RX_WIDX, sc->rxq.count - 1);
3142
3143         if (iwi_load_firmware(sc, &sc->fw_fw) != 0) {
3144                 device_printf(sc->sc_dev,
3145                     "could not load main firmware %s\n", sc->fw_fw.name);
3146                 goto fail;
3147         }
3148         sc->flags |= IWI_FLAG_FW_INITED;
3149
3150         IWI_STATE_END(sc, IWI_FW_LOADING);
3151
3152         if (iwi_config(sc) != 0) {
3153                 device_printf(sc->sc_dev, "unable to enable adapter\n");
3154                 goto fail2;
3155         }
3156
3157         callout_reset(&sc->sc_wdtimer, hz, iwi_watchdog, sc);
3158         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3159         ifp->if_drv_flags |= IFF_DRV_RUNNING;
3160         return;
3161 fail:
3162         IWI_STATE_END(sc, IWI_FW_LOADING);
3163 fail2:
3164         iwi_stop_locked(sc);
3165 }
3166
3167 static void
3168 iwi_init(void *priv)
3169 {
3170         struct iwi_softc *sc = priv;
3171         struct ifnet *ifp = sc->sc_ifp;
3172         struct ieee80211com *ic = ifp->if_l2com;
3173         IWI_LOCK_DECL;
3174
3175         IWI_LOCK(sc);
3176         iwi_init_locked(sc);
3177         IWI_UNLOCK(sc);
3178
3179         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
3180                 ieee80211_start_all(ic);
3181 }
3182
3183 static void
3184 iwi_stop_locked(void *priv)
3185 {
3186         struct iwi_softc *sc = priv;
3187         struct ifnet *ifp = sc->sc_ifp;
3188
3189         IWI_LOCK_ASSERT(sc);
3190
3191         ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
3192
3193         taskqueue_block(sc->sc_tq);
3194         taskqueue_block(sc->sc_tq2);
3195         if (sc->sc_softled) {
3196                 callout_stop(&sc->sc_ledtimer);
3197                 sc->sc_blinking = 0;
3198         }
3199         callout_stop(&sc->sc_wdtimer);
3200         callout_stop(&sc->sc_rftimer);
3201
3202         iwi_stop_master(sc);
3203
3204         CSR_WRITE_4(sc, IWI_CSR_RST, IWI_RST_SOFT_RESET);
3205
3206         /* reset rings */
3207         iwi_reset_cmd_ring(sc, &sc->cmdq);
3208         iwi_reset_tx_ring(sc, &sc->txq[0]);
3209         iwi_reset_tx_ring(sc, &sc->txq[1]);
3210         iwi_reset_tx_ring(sc, &sc->txq[2]);
3211         iwi_reset_tx_ring(sc, &sc->txq[3]);
3212         iwi_reset_rx_ring(sc, &sc->rxq);
3213
3214         memset(sc->sc_cmd, 0, sizeof(sc->sc_cmd));
3215         sc->sc_tx_timer = 0;
3216         sc->sc_state_timer = 0;
3217         sc->sc_busy_timer = 0;
3218         sc->flags &= ~(IWI_FLAG_BUSY | IWI_FLAG_ASSOCIATED);
3219         sc->fw_state = IWI_FW_IDLE;
3220         wakeup(sc);
3221 }
3222
3223 static void
3224 iwi_stop(struct iwi_softc *sc)
3225 {
3226         IWI_LOCK_DECL;
3227
3228         IWI_LOCK(sc);
3229         iwi_stop_locked(sc);
3230         IWI_UNLOCK(sc);
3231 }
3232
3233 static void
3234 iwi_restart(void *arg, int npending)
3235 {
3236         struct iwi_softc *sc = arg;
3237
3238         iwi_init(sc);
3239 }
3240
3241 /*
3242  * Return whether or not the radio is enabled in hardware
3243  * (i.e. the rfkill switch is "off").
3244  */
3245 static int
3246 iwi_getrfkill(struct iwi_softc *sc)
3247 {
3248         return (CSR_READ_4(sc, IWI_CSR_IO) & IWI_IO_RADIO_ENABLED) == 0;
3249 }
3250
3251 static void
3252 iwi_radio_on(void *arg, int pending)
3253 {
3254         struct iwi_softc *sc = arg;
3255         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3256
3257         device_printf(sc->sc_dev, "radio turned on\n");
3258
3259         iwi_init(sc);
3260         ieee80211_notify_radio(ic, 1);
3261 }
3262
3263 static void
3264 iwi_rfkill_poll(void *arg)
3265 {
3266         struct iwi_softc *sc = arg;
3267
3268         IWI_LOCK_ASSERT(sc);
3269
3270         /*
3271          * Check for a change in rfkill state.  We get an
3272          * interrupt when a radio is disabled but not when
3273          * it is enabled so we must poll for the latter.
3274          */
3275         if (!iwi_getrfkill(sc)) {
3276                 taskqueue_unblock(sc->sc_tq);
3277                 taskqueue_enqueue(sc->sc_tq, &sc->sc_radiontask);
3278                 return;
3279         }
3280         callout_reset(&sc->sc_rftimer, 2*hz, iwi_rfkill_poll, sc);
3281 }
3282
3283 static void
3284 iwi_radio_off(void *arg, int pending)
3285 {
3286         struct iwi_softc *sc = arg;
3287         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3288         IWI_LOCK_DECL;
3289
3290         device_printf(sc->sc_dev, "radio turned off\n");
3291
3292         ieee80211_notify_radio(ic, 0);
3293
3294         IWI_LOCK(sc);
3295         iwi_stop_locked(sc);
3296         iwi_rfkill_poll(sc);
3297         IWI_UNLOCK(sc);
3298 }
3299
3300 static int
3301 iwi_sysctl_stats(SYSCTL_HANDLER_ARGS)
3302 {
3303         struct iwi_softc *sc = arg1;
3304         uint32_t size, buf[128];
3305
3306         memset(buf, 0, sizeof buf);
3307
3308         if (!(sc->flags & IWI_FLAG_FW_INITED))
3309                 return SYSCTL_OUT(req, buf, sizeof buf);
3310
3311         size = min(CSR_READ_4(sc, IWI_CSR_TABLE0_SIZE), 128 - 1);
3312         CSR_READ_REGION_4(sc, IWI_CSR_TABLE0_BASE, &buf[1], size);
3313
3314         return SYSCTL_OUT(req, buf, size);
3315 }
3316
3317 static int
3318 iwi_sysctl_radio(SYSCTL_HANDLER_ARGS)
3319 {
3320         struct iwi_softc *sc = arg1;
3321         int val = !iwi_getrfkill(sc);
3322
3323         return SYSCTL_OUT(req, &val, sizeof val);
3324 }
3325
3326 /*
3327  * Add sysctl knobs.
3328  */
3329 static void
3330 iwi_sysctlattach(struct iwi_softc *sc)
3331 {
3332         struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
3333         struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
3334
3335         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "radio",
3336             CTLTYPE_INT | CTLFLAG_RD, sc, 0, iwi_sysctl_radio, "I",
3337             "radio transmitter switch state (0=off, 1=on)");
3338
3339         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "stats",
3340             CTLTYPE_OPAQUE | CTLFLAG_RD, sc, 0, iwi_sysctl_stats, "S",
3341             "statistics");
3342
3343         sc->bluetooth = 0;
3344         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "bluetooth",
3345             CTLFLAG_RW, &sc->bluetooth, 0, "bluetooth coexistence");
3346
3347         sc->antenna = IWI_ANTENNA_AUTO;
3348         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "antenna",
3349             CTLFLAG_RW, &sc->antenna, 0, "antenna (0=auto)");
3350 }
3351
3352 /*
3353  * LED support.
3354  *
3355  * Different cards have different capabilities.  Some have three
3356  * led's while others have only one.  The linux ipw driver defines
3357  * led's for link state (associated or not), band (11a, 11g, 11b),
3358  * and for link activity.  We use one led and vary the blink rate
3359  * according to the tx/rx traffic a la the ath driver.
3360  */
3361
3362 static __inline uint32_t
3363 iwi_toggle_event(uint32_t r)
3364 {
3365         return r &~ (IWI_RST_STANDBY | IWI_RST_GATE_ODMA |
3366                      IWI_RST_GATE_IDMA | IWI_RST_GATE_ADMA);
3367 }
3368
3369 static uint32_t
3370 iwi_read_event(struct iwi_softc *sc)
3371 {
3372         return MEM_READ_4(sc, IWI_MEM_EEPROM_EVENT);
3373 }
3374
3375 static void
3376 iwi_write_event(struct iwi_softc *sc, uint32_t v)
3377 {
3378         MEM_WRITE_4(sc, IWI_MEM_EEPROM_EVENT, v);
3379 }
3380
3381 static void
3382 iwi_led_done(void *arg)
3383 {
3384         struct iwi_softc *sc = arg;
3385
3386         sc->sc_blinking = 0;
3387 }
3388
3389 /*
3390  * Turn the activity LED off: flip the pin and then set a timer so no
3391  * update will happen for the specified duration.
3392  */
3393 static void
3394 iwi_led_off(void *arg)
3395 {
3396         struct iwi_softc *sc = arg;
3397         uint32_t v;
3398
3399         v = iwi_read_event(sc);
3400         v &= ~sc->sc_ledpin;
3401         iwi_write_event(sc, iwi_toggle_event(v));
3402         callout_reset(&sc->sc_ledtimer, sc->sc_ledoff, iwi_led_done, sc);
3403 }
3404
3405 /*
3406  * Blink the LED according to the specified on/off times.
3407  */
3408 static void
3409 iwi_led_blink(struct iwi_softc *sc, int on, int off)
3410 {
3411         uint32_t v;
3412
3413         v = iwi_read_event(sc);
3414         v |= sc->sc_ledpin;
3415         iwi_write_event(sc, iwi_toggle_event(v));
3416         sc->sc_blinking = 1;
3417         sc->sc_ledoff = off;
3418         callout_reset(&sc->sc_ledtimer, on, iwi_led_off, sc);
3419 }
3420
3421 static void
3422 iwi_led_event(struct iwi_softc *sc, int event)
3423 {
3424 #define N(a)    (sizeof(a)/sizeof(a[0]))
3425         /* NB: on/off times from the Atheros NDIS driver, w/ permission */
3426         static const struct {
3427                 u_int           rate;           /* tx/rx iwi rate */
3428                 u_int16_t       timeOn;         /* LED on time (ms) */
3429                 u_int16_t       timeOff;        /* LED off time (ms) */
3430         } blinkrates[] = {
3431                 { IWI_RATE_OFDM54, 40,  10 },
3432                 { IWI_RATE_OFDM48, 44,  11 },
3433                 { IWI_RATE_OFDM36, 50,  13 },
3434                 { IWI_RATE_OFDM24, 57,  14 },
3435                 { IWI_RATE_OFDM18, 67,  16 },
3436                 { IWI_RATE_OFDM12, 80,  20 },
3437                 { IWI_RATE_DS11,  100,  25 },
3438                 { IWI_RATE_OFDM9, 133,  34 },
3439                 { IWI_RATE_OFDM6, 160,  40 },
3440                 { IWI_RATE_DS5,   200,  50 },
3441                 {            6,   240,  58 },   /* XXX 3Mb/s if it existed */
3442                 { IWI_RATE_DS2,   267,  66 },
3443                 { IWI_RATE_DS1,   400, 100 },
3444                 {            0,   500, 130 },   /* unknown rate/polling */
3445         };
3446         uint32_t txrate;
3447         int j = 0;                      /* XXX silence compiler */
3448
3449         sc->sc_ledevent = ticks;        /* time of last event */
3450         if (sc->sc_blinking)            /* don't interrupt active blink */
3451                 return;
3452         switch (event) {
3453         case IWI_LED_POLL:
3454                 j = N(blinkrates)-1;
3455                 break;
3456         case IWI_LED_TX:
3457                 /* read current transmission rate from adapter */
3458                 txrate = CSR_READ_4(sc, IWI_CSR_CURRENT_TX_RATE);
3459                 if (blinkrates[sc->sc_txrix].rate != txrate) {
3460                         for (j = 0; j < N(blinkrates)-1; j++)
3461                                 if (blinkrates[j].rate == txrate)
3462                                         break;
3463                         sc->sc_txrix = j;
3464                 } else
3465                         j = sc->sc_txrix;
3466                 break;
3467         case IWI_LED_RX:
3468                 if (blinkrates[sc->sc_rxrix].rate != sc->sc_rxrate) {
3469                         for (j = 0; j < N(blinkrates)-1; j++)
3470                                 if (blinkrates[j].rate == sc->sc_rxrate)
3471                                         break;
3472                         sc->sc_rxrix = j;
3473                 } else
3474                         j = sc->sc_rxrix;
3475                 break;
3476         }
3477         /* XXX beware of overflow */
3478         iwi_led_blink(sc, (blinkrates[j].timeOn * hz) / 1000,
3479                 (blinkrates[j].timeOff * hz) / 1000);
3480 #undef N
3481 }
3482
3483 static int
3484 iwi_sysctl_softled(SYSCTL_HANDLER_ARGS)
3485 {
3486         struct iwi_softc *sc = arg1;
3487         int softled = sc->sc_softled;
3488         int error;
3489
3490         error = sysctl_handle_int(oidp, &softled, 0, req);
3491         if (error || !req->newptr)
3492                 return error;
3493         softled = (softled != 0);
3494         if (softled != sc->sc_softled) {
3495                 if (softled) {
3496                         uint32_t v = iwi_read_event(sc);
3497                         v &= ~sc->sc_ledpin;
3498                         iwi_write_event(sc, iwi_toggle_event(v));
3499                 }
3500                 sc->sc_softled = softled;
3501         }
3502         return 0;
3503 }
3504
3505 static void
3506 iwi_ledattach(struct iwi_softc *sc)
3507 {
3508         struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
3509         struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
3510
3511         sc->sc_blinking = 0;
3512         sc->sc_ledstate = 1;
3513         sc->sc_ledidle = (2700*hz)/1000;        /* 2.7sec */
3514         callout_init_mtx(&sc->sc_ledtimer, &sc->sc_mtx, 0);
3515
3516         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
3517                 "softled", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
3518                 iwi_sysctl_softled, "I", "enable/disable software LED support");
3519         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
3520                 "ledpin", CTLFLAG_RW, &sc->sc_ledpin, 0,
3521                 "pin setting to turn activity LED on");
3522         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
3523                 "ledidle", CTLFLAG_RW, &sc->sc_ledidle, 0,
3524                 "idle time for inactivity LED (ticks)");
3525         /* XXX for debugging */
3526         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
3527                 "nictype", CTLFLAG_RD, &sc->sc_nictype, 0,
3528                 "NIC type from EEPROM");
3529
3530         sc->sc_ledpin = IWI_RST_LED_ACTIVITY;
3531         sc->sc_softled = 1;
3532
3533         sc->sc_nictype = (iwi_read_prom_word(sc, IWI_EEPROM_NIC) >> 8) & 0xff;
3534         if (sc->sc_nictype == 1) {
3535                 /*
3536                  * NB: led's are reversed.
3537                  */
3538                 sc->sc_ledpin = IWI_RST_LED_ASSOCIATED;
3539         }
3540 }
3541
3542 static void
3543 iwi_ops(void *arg0, int npending)
3544 {
3545         static const char *opnames[] = {
3546                 [IWI_CMD_FREE]          = "FREE",
3547                 [IWI_SCAN_START]        = "SCAN_START",
3548                 [IWI_SET_CHANNEL]       = "SET_CHANNEL",
3549                 [IWI_AUTH]              = "AUTH",
3550                 [IWI_ASSOC]             = "ASSOC",
3551                 [IWI_DISASSOC]          = "DISASSOC",
3552                 [IWI_SCAN_CURCHAN]      = "SCAN_CURCHAN",
3553                 [IWI_SCAN_ALLCHAN]      = "SCAN_ALLCHAN",
3554                 [IWI_SET_WME]           = "SET_WME",
3555         };
3556         struct iwi_softc *sc = arg0;
3557         struct ifnet *ifp = sc->sc_ifp;
3558         struct ieee80211com *ic = ifp->if_l2com;
3559         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3560         IWI_LOCK_DECL;
3561         int cmd;
3562         unsigned long arg;
3563
3564 again:
3565         IWI_CMD_LOCK(sc);
3566         cmd = sc->sc_cmd[sc->sc_cmd_cur];
3567         if (cmd == IWI_CMD_FREE) {
3568                 /* No more commands to process */
3569                 IWI_CMD_UNLOCK(sc);
3570                 return;
3571         }
3572         arg = sc->sc_arg[sc->sc_cmd_cur];
3573         sc->sc_cmd[sc->sc_cmd_cur] = IWI_CMD_FREE;      /* free the slot */
3574         sc->sc_cmd_cur = (sc->sc_cmd_cur + 1) % IWI_CMD_MAXOPS;
3575         IWI_CMD_UNLOCK(sc);
3576
3577         IWI_LOCK(sc);
3578         while  (sc->fw_state != IWI_FW_IDLE || (sc->flags & IWI_FLAG_BUSY)) {
3579                 msleep(sc, &sc->sc_mtx, 0, "iwicmd", hz/10);
3580         }
3581
3582         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
3583                 IWI_UNLOCK(sc);
3584                 return;
3585         }
3586
3587         DPRINTF(("%s: %s arg %lu\n", __func__, opnames[cmd], arg));
3588         switch (cmd) {
3589         case IWI_AUTH:
3590         case IWI_ASSOC:
3591                 if (cmd == IWI_AUTH)
3592                         vap->iv_state = IEEE80211_S_AUTH;
3593                 else
3594                         vap->iv_state = IEEE80211_S_ASSOC;
3595                 iwi_auth_and_assoc(sc, vap);
3596                 /* NB: completion done in iwi_notification_intr */
3597                 break;
3598         case IWI_DISASSOC:
3599                 iwi_disassociate(sc, 0);
3600                 break;
3601         case IWI_SET_WME:
3602                 if (vap->iv_state == IEEE80211_S_RUN)
3603                         (void) iwi_wme_setparams(sc, ic);
3604                 break;
3605         case IWI_SCAN_START:
3606                 sc->flags |= IWI_FLAG_CHANNEL_SCAN;
3607                 break;
3608         case IWI_SCAN_CURCHAN:
3609         case IWI_SCAN_ALLCHAN:
3610                 if (!(sc->flags & IWI_FLAG_CHANNEL_SCAN)) {
3611                         DPRINTF(("%s: ic_scan_curchan while not scanning\n",
3612                             __func__));
3613                         goto done;
3614                 }
3615                 if (iwi_scanchan(sc, arg, cmd))
3616                         ieee80211_cancel_scan(vap);
3617                 break;
3618         }
3619 done:
3620         IWI_UNLOCK(sc);
3621
3622         /* Take another pass */
3623         goto again;
3624 }
3625
3626 static int
3627 iwi_queue_cmd(struct iwi_softc *sc, int cmd, unsigned long arg)
3628 {
3629         IWI_CMD_LOCK(sc);
3630         if (sc->sc_cmd[sc->sc_cmd_next] != 0) {
3631                 IWI_CMD_UNLOCK(sc);
3632                 DPRINTF(("%s: command %d dropped\n", __func__, cmd));
3633                 return (EBUSY);
3634         }
3635
3636         sc->sc_cmd[sc->sc_cmd_next] = cmd;
3637         sc->sc_arg[sc->sc_cmd_next] = arg;
3638         sc->sc_cmd_next = (sc->sc_cmd_next + 1) % IWI_CMD_MAXOPS;
3639         taskqueue_enqueue(sc->sc_tq, &sc->sc_opstask);
3640         IWI_CMD_UNLOCK(sc);
3641         return (0);
3642 }
3643
3644 static void
3645 iwi_scan_start(struct ieee80211com *ic)
3646 {
3647         struct ifnet *ifp = ic->ic_ifp;
3648         struct iwi_softc *sc = ifp->if_softc;
3649
3650         iwi_queue_cmd(sc, IWI_SCAN_START, 0);
3651 }
3652
3653 static void
3654 iwi_set_channel(struct ieee80211com *ic)
3655 {
3656         struct ifnet *ifp = ic->ic_ifp;
3657         struct iwi_softc *sc = ifp->if_softc;
3658         if (sc->fw_state == IWI_FW_IDLE)
3659                 iwi_setcurchan(sc, ic->ic_curchan->ic_ieee);
3660 }
3661
3662 static void
3663 iwi_scan_curchan(struct ieee80211_scan_state *ss, unsigned long maxdwell)
3664 {
3665         struct ieee80211vap *vap = ss->ss_vap;
3666         struct ifnet *ifp = vap->iv_ic->ic_ifp;
3667         struct iwi_softc *sc = ifp->if_softc;
3668
3669         iwi_queue_cmd(sc, IWI_SCAN_CURCHAN, maxdwell);
3670 }
3671
3672 #if 0
3673 static void
3674 iwi_scan_allchan(struct ieee80211com *ic, unsigned long maxdwell)
3675 {
3676         struct ifnet *ifp = ic->ic_ifp;
3677         struct iwi_softc *sc = ifp->if_softc;
3678
3679         iwi_queue_cmd(sc, IWI_SCAN_ALLCHAN, maxdwell);
3680 }
3681 #endif
3682
3683 static void
3684 iwi_scan_mindwell(struct ieee80211_scan_state *ss)
3685 {
3686         /* NB: don't try to abort scan; wait for firmware to finish */
3687 }
3688
3689 static void
3690 iwi_scan_end(struct ieee80211com *ic)
3691 {
3692         struct ifnet *ifp = ic->ic_ifp;
3693         struct iwi_softc *sc = ifp->if_softc;
3694
3695         taskqueue_enqueue(sc->sc_tq2, &sc->sc_scanaborttask);
3696 }