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