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