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