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