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