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