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