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