- serialize iwi(4)
[dragonfly.git] / sys / dev / netif / iwi / if_iwi.c
1 /*
2  * Copyright (c) 2004, 2005
3  *      Damien Bergamini <damien.bergamini@free.fr>.
4  * Copyright (c) 2004, 2005
5  *      Andrew Atrens <atrens@nortelnetworks.com>.
6  *
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice unmodified, this list of conditions, and the following
14  *    disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  * $DragonFly: src/sys/dev/netif/iwi/if_iwi.c,v 1.9 2005/12/18 02:47:34 sephe Exp $
32  */
33
34 #include "opt_inet.h"
35
36 #include <sys/cdefs.h>
37
38 /*-
39  * Intel(R) PRO/Wireless 2200BG/2915ABG driver
40  * http://www.intel.com/network/connectivity/products/wireless/prowireless_mobile.htm
41  */
42
43 #include <sys/param.h>
44 #include <sys/sysctl.h>
45 #include <sys/sockio.h>
46 #include <sys/mbuf.h>
47 #include <sys/kernel.h>
48 #include <sys/kthread.h>
49 #include <sys/socket.h>
50 #include <sys/systm.h>
51 #include <sys/malloc.h>
52 #include <sys/module.h>
53 #include <sys/bus.h>
54 #include <sys/endian.h>
55 #include <sys/proc.h>
56 #include <sys/ucred.h>
57 #include <sys/thread2.h>
58
59 #include <machine/bus.h>
60 #include <machine/resource.h>
61 #include <machine/clock.h>
62 #include <sys/rman.h>
63
64 #include <bus/pci/pcireg.h>
65 #include <bus/pci/pcivar.h>
66
67 #include <net/bpf.h>
68 #include <net/if.h>
69 #include <net/if_arp.h>
70 #include <net/ifq_var.h>
71 #include <net/ethernet.h>
72 #include <net/if_dl.h>
73 #include <net/if_media.h>
74 #include <net/if_types.h>
75 #include <net/ifq_var.h>
76
77 #include <netinet/in.h>
78 #include <netinet/in_systm.h>
79 #include <netinet/in_var.h>
80 #include <netinet/ip.h>
81 #include <netinet/if_ether.h>
82
83 #ifdef IPX
84 #include <netproto/ipx/ipx.h>
85 #include <netproto/ipx/ipx_if.h>
86 #endif
87
88 #include <netproto/802_11/ieee80211_var.h>
89 #include <netproto/802_11/ieee80211_ioctl.h>
90 #include <netproto/802_11/ieee80211_radiotap.h>
91 #include <netproto/802_11/if_wavelan_ieee.h>
92
93 #include "if_iwireg.h"
94 #include "if_iwivar.h"
95
96 #ifdef IWI_DEBUG
97 #define DPRINTF(x)      if (sc->debug_level > 0) printf x
98 #define DPRINTFN(n, x)  if (sc->debug_level >= (n)) printf x
99
100 #else
101 #define DPRINTF(x)
102 #define DPRINTFN(n, x)
103 #endif
104
105 MODULE_DEPEND(iwi, pci,  1, 1, 1);
106 MODULE_DEPEND(iwi, wlan, 1, 1, 1);
107
108 struct iwi_dump_buffer {
109         u_int32_t buf[128];
110 };
111
112 struct iwi_ident {
113         u_int16_t       vendor;
114         u_int16_t       device;
115         const char      *name;
116 };
117
118 static const struct iwi_ident iwi_ident_table[] = {
119         { 0x8086, 0x4220, "Intel(R) PRO/Wireless 2200BG MiniPCI" },
120         { 0x8086, 0x4223, "Intel(R) PRO/Wireless 2915ABG MiniPCI" },
121         { 0x8086, 0x4224, "Intel(R) PRO/Wireless 2915ABG MiniPCI" },
122
123         { 0, 0, NULL }
124 };
125
126 static const struct ieee80211_rateset iwi_rateset_11a =
127         { 8, { 12, 18, 24, 36, 48, 72, 96, 108 } };
128
129 static const struct ieee80211_rateset iwi_rateset_11b =
130         { 4, { 2, 4, 11, 22 } };
131
132 static const struct ieee80211_rateset iwi_rateset_11g =
133         { 12, { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 } };
134
135 static int              iwi_dma_alloc(struct iwi_softc *);
136 static void             iwi_release(struct iwi_softc *);
137 static int              iwi_media_change(struct ifnet *);
138 static void             iwi_media_status(struct ifnet *, struct ifmediareq *);
139 static u_int16_t        iwi_read_prom_word(struct iwi_softc *, u_int8_t);
140 static int              iwi_newstate(struct ieee80211com *,
141                             enum ieee80211_state, int);
142 static void             iwi_fix_channel(struct iwi_softc *, struct mbuf *);
143 static void             iwi_frame_intr(struct iwi_softc *,
144                             struct iwi_rx_buf *, int, struct iwi_frame *);
145 static void             iwi_notification_intr(struct iwi_softc *,
146                             struct iwi_notif *);
147 static void             iwi_rx_intr(struct iwi_softc *);
148 static void             iwi_tx_intr(struct iwi_softc *);
149 static void             iwi_intr(void *);
150 static void             iwi_dma_map_buf(void *, bus_dma_segment_t *, int,
151                             bus_size_t, int);
152 static void             iwi_dma_map_addr(void *, bus_dma_segment_t *, int, int);
153 static int              iwi_cmd(struct iwi_softc *, u_int8_t, void *, u_int8_t,
154                             int);
155 static int              iwi_tx_start(struct ifnet *, struct mbuf *,
156                             struct ieee80211_node *);
157 static void             iwi_start(struct ifnet *);
158 static void             iwi_watchdog(struct ifnet *);
159 static int              iwi_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *cr);
160 static void             iwi_stop_master(struct iwi_softc *);
161 static int              iwi_reset(struct iwi_softc *);
162 static int              iwi_load_ucode(struct iwi_softc *, void *, int);
163 static int              iwi_load_firmware(struct iwi_softc *, void *, int);
164 static int              iwi_cache_firmware(struct iwi_softc *, void *, int);
165 static void             iwi_free_firmware(struct iwi_softc *);
166 static int              iwi_config(struct iwi_softc *);
167 static int              iwi_scan(struct iwi_softc *);
168 static int              iwi_auth_and_assoc(struct iwi_softc *);
169 static void             iwi_init(void *);
170 static void             iwi_stop(void *);
171 static void             iwi_dump_fw_event_log(struct iwi_softc *sc);
172 static void             iwi_dump_fw_error_log(struct iwi_softc *sc);
173 static u_int8_t         iwi_find_station(struct iwi_softc *sc, u_int8_t *mac);
174 static int8_t           iwi_cache_station(struct iwi_softc *sc, u_int8_t *mac);
175 static int              iwi_adapter_config(struct iwi_softc *sc, int is_a, int cmd_wait);
176
177 static int              iwi_sysctl_bt_coexist(SYSCTL_HANDLER_ARGS);
178 static int              iwi_sysctl_bg_autodetect(SYSCTL_HANDLER_ARGS);
179 static int              iwi_sysctl_cts_to_self(SYSCTL_HANDLER_ARGS);
180 static int              iwi_sysctl_antenna_diversity(SYSCTL_HANDLER_ARGS);
181 static int              iwi_sysctl_radio(SYSCTL_HANDLER_ARGS);
182 static int              iwi_sysctl_stats(SYSCTL_HANDLER_ARGS);
183 static int              iwi_sysctl_dump_logs(SYSCTL_HANDLER_ARGS);
184 static int              iwi_sysctl_neg_best_rates_first(SYSCTL_HANDLER_ARGS);
185 static int              iwi_sysctl_disable_unicast_decryption(SYSCTL_HANDLER_ARGS);
186 static int              iwi_sysctl_disable_multicast_decryption(SYSCTL_HANDLER_ARGS);
187
188 static __inline u_int8_t MEM_READ_1(struct iwi_softc *sc, u_int32_t addr)
189 {
190         CSR_WRITE_4(sc, IWI_CSR_INDIRECT_ADDR, addr);
191         return CSR_READ_1(sc, IWI_CSR_INDIRECT_DATA);
192 }
193
194 static __inline u_int32_t MEM_READ_4(struct iwi_softc *sc, u_int32_t addr)
195 {
196         CSR_WRITE_4(sc, IWI_CSR_INDIRECT_ADDR, addr);
197         return CSR_READ_4(sc, IWI_CSR_INDIRECT_DATA);
198 }
199
200 static int iwi_probe(device_t);
201 static int iwi_attach(device_t);
202 static int iwi_detach(device_t);
203 static int iwi_shutdown(device_t);
204 static int iwi_suspend(device_t);
205 static int iwi_resume(device_t);
206
207 static device_method_t iwi_methods[] = {
208         /* Device interface */
209         DEVMETHOD(device_probe,         iwi_probe),
210         DEVMETHOD(device_attach,        iwi_attach),
211         DEVMETHOD(device_detach,        iwi_detach),
212         DEVMETHOD(device_shutdown,      iwi_shutdown),
213         DEVMETHOD(device_suspend,       iwi_suspend),
214         DEVMETHOD(device_resume,        iwi_resume),
215
216         { 0, 0 }
217 };
218
219 static driver_t iwi_driver = {
220         "iwi",
221         iwi_methods,
222         sizeof (struct iwi_softc),
223         0, /* baseclasses */
224         0, /* refs */
225         0  /* ops */
226 };
227
228 static devclass_t iwi_devclass;
229
230 DRIVER_MODULE(iwi, pci, iwi_driver, iwi_devclass, 0, 0);
231
232 static int
233 iwi_probe(device_t dev)
234 {
235         const struct iwi_ident *ident;
236
237         for (ident = iwi_ident_table; ident->name != NULL; ident++) {
238                 if (pci_get_vendor(dev) == ident->vendor &&
239                     pci_get_device(dev) == ident->device) {
240                         device_set_desc(dev, ident->name);
241                         return 0;
242                 }
243         }
244         return ENXIO;
245 }
246
247 static void
248 iwi_fw_monitor(void *arg)
249 {
250         struct iwi_softc *sc = (struct iwi_softc *)arg;
251         struct ifnet *ifp = &sc->sc_ic.ic_if;
252         int error, boff;
253
254         for ( ;; ) {
255                 crit_enter();
256                 tsleep_interlock(IWI_FW_WAKE_MONITOR(sc));
257                 error = tsleep(IWI_FW_WAKE_MONITOR(sc), 0, "iwifwm", 0 );
258                 crit_exit();
259
260                 if ( error == 0 ) {
261                         if ( sc->flags & IWI_FLAG_EXIT ) {
262                                 sc->flags &= ~( IWI_FLAG_EXIT );
263                                 break;
264                         } else if ( sc->flags & IWI_FLAG_RESET ) {
265                                 device_printf(sc->sc_dev, "firmware reset\n");
266                                 for ( boff = 1; sc->flags & IWI_FLAG_RESET ; boff++ ) {
267                                         if ( sc->debug_level > 0 )
268                                                 iwi_dump_fw_error_log(sc);
269                                         lwkt_serialize_enter(ifp->if_serializer);
270                                         iwi_init(sc);
271                                         lwkt_serialize_exit(ifp->if_serializer);
272                                         if ((sc->flags & IWI_FLAG_FW_INITED))
273                                                 sc->flags &= ~( IWI_FLAG_RESET );
274                                         crit_enter();
275                                         tsleep_interlock(IWI_FW_CMD_ACKED(sc));
276                                         error = tsleep(IWI_FW_CMD_ACKED(sc), 0,
277                                                        "iwirun", boff * hz );
278                                         crit_exit();
279                                 }
280                         }
281                 }
282         }
283         wakeup(IWI_FW_MON_EXIT(sc));
284         kthread_exit();
285 }
286
287 static int
288 iwi_start_fw_monitor_thread( struct iwi_softc *sc )
289 {
290        if (kthread_create(iwi_fw_monitor, sc, &sc->event_thread,
291                 "%s%d:fw-monitor", device_get_name(sc->sc_dev),
292                 device_get_unit(sc->sc_dev))) {
293                 device_printf (sc->sc_dev,
294                    "unable to create firmware monitor thread.\n");
295                 return -1;
296         }
297         return 0;
298 }
299
300 /* Base Address Register */
301 #define IWI_PCI_BAR0    0x10
302
303 static int
304 iwi_attach(device_t dev)
305 {
306         struct iwi_softc *sc = device_get_softc(dev);
307         struct ieee80211com *ic = &sc->sc_ic;
308         struct ifnet *ifp = &ic->ic_if;
309         u_int16_t val;
310         int error, rid, i;
311
312         sc->sc_dev = dev;
313
314         if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
315                 device_printf(dev, "chip is in D%d power mode "
316                     "-- setting to D0\n", pci_get_powerstate(dev));
317                 pci_set_powerstate(dev, PCI_POWERSTATE_D0);
318         }
319
320         pci_write_config(dev, 0x41, 0, 1);
321
322         /* enable bus-mastering */
323         pci_enable_busmaster(dev);
324
325         sc->num_stations = 0;
326
327         /* map the register window */
328         rid = IWI_PCI_BAR0;
329         sc->mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid, RF_ACTIVE);
330         if (sc->mem == NULL) {
331                 device_printf(dev, "could not allocate memory resource\n");
332                 error = ENXIO;
333                 goto fail;
334         }
335
336         sc->sc_st = rman_get_bustag(sc->mem);
337         sc->sc_sh = rman_get_bushandle(sc->mem);
338
339         rid = 0;
340         sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE |
341             RF_SHAREABLE);
342         if (sc->irq == NULL) {
343                 device_printf(dev, "could not allocate interrupt resource\n");
344                 error = ENXIO;
345                 goto fail;
346         }
347
348         error = iwi_reset(sc);
349         if (error != 0) {
350                 device_printf(dev, "could not reset adapter\n");
351                 goto fail;
352         }
353
354         if (iwi_start_fw_monitor_thread(sc)) {
355                 device_printf(dev, "could not start f/w reset thread\n");
356                 error = ENXIO;
357                 goto fail;
358         }
359
360         error = iwi_dma_alloc(sc);
361         if (error != 0) {
362                 device_printf(dev, "could not allocate DMA resources\n");
363                 goto fail;
364         }
365
366         ic->ic_phytype = IEEE80211_T_OFDM;
367         ic->ic_opmode  = IEEE80211_M_STA;
368         ic->ic_state   = IEEE80211_S_INIT;
369
370         /* set device capabilities */
371         ic->ic_caps = IEEE80211_C_IBSS | IEEE80211_C_PMGT | IEEE80211_C_WEP |
372             IEEE80211_C_TXPMGT | IEEE80211_C_SHPREAMBLE;
373
374         /* read MAC address from EEPROM */
375         val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 0);
376         ic->ic_myaddr[0] = val >> 8;
377         ic->ic_myaddr[1] = val & 0xff;
378         val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 1);
379         ic->ic_myaddr[2] = val >> 8;
380         ic->ic_myaddr[3] = val & 0xff;
381         val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 2);
382         ic->ic_myaddr[4] = val >> 8;
383         ic->ic_myaddr[5] = val & 0xff;
384
385         if (pci_get_device(dev) != 0x4220) {
386                 /* set supported .11a rates */
387                 ic->ic_sup_rates[IEEE80211_MODE_11A] = iwi_rateset_11a;
388
389                 /* set supported .11a channels */
390                 for (i = 36; i <= 64; i += 4) {
391                         ic->ic_channels[i].ic_freq =
392                             ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
393                         ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
394                 }
395                 for (i = 149; i <= 165; i += 4) {
396                         ic->ic_channels[i].ic_freq =
397                             ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
398                         ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
399                 }
400         }
401
402         /* set supported .11b and .11g rates */
403         ic->ic_sup_rates[IEEE80211_MODE_11B] = iwi_rateset_11b;
404         ic->ic_sup_rates[IEEE80211_MODE_11G] = iwi_rateset_11g;
405
406         /* set supported .11b and .11g channels (1 through 14) */
407         for (i = 1; i <= 14; i++) {
408                 ic->ic_channels[i].ic_freq =
409                     ieee80211_ieee2mhz(i, IEEE80211_CHAN_2GHZ);
410                 ic->ic_channels[i].ic_flags =
411                     IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
412                     IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
413         }
414
415         /* default to authmode OPEN */
416         sc->authmode = IEEE80211_AUTH_OPEN;
417
418         /* IBSS channel undefined for now */
419         ic->ic_ibss_chan = &ic->ic_channels[0];
420
421         ifp->if_softc = sc;
422         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
423         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
424         ifp->if_init = iwi_init;
425         ifp->if_ioctl = iwi_ioctl;
426         ifp->if_start = iwi_start;
427         ifp->if_watchdog = iwi_watchdog;
428         ifq_set_maxlen(&ifp->if_snd, IFQ_MAXLEN);
429         ifq_set_ready(&ifp->if_snd);
430
431         ieee80211_ifattach(ifp);
432         /* override state transition machine */
433         sc->sc_newstate = ic->ic_newstate;
434         ic->ic_newstate = iwi_newstate;
435         ieee80211_media_init(ifp, iwi_media_change, iwi_media_status);
436
437         bpfattach_dlt(ifp, DLT_IEEE802_11_RADIO,
438             sizeof (struct ieee80211_frame) + 64, &sc->sc_drvbpf);
439
440         sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
441         sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
442         sc->sc_rxtap.wr_ihdr.it_present = htole32(IWI_RX_RADIOTAP_PRESENT);
443
444         sc->sc_txtap_len = sizeof sc->sc_txtapu;
445         sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
446         sc->sc_txtap.wt_ihdr.it_present = htole32(IWI_TX_RADIOTAP_PRESENT);
447
448         /*
449          * Add sysctl knobs
450          * 
451          * use -1 to indicate 'default / not set'
452          */
453
454         sc->enable_bg_autodetect         = -1;
455         sc->enable_bt_coexist            = -1;
456         sc->enable_cts_to_self           = -1;
457         sc->antenna_diversity            = -1;
458         sc->enable_neg_best_first        = -1;
459         sc->disable_unicast_decryption   = -1;
460         sc->disable_multicast_decryption = -1;
461
462         sysctl_ctx_init(&sc->sysctl_ctx);
463         sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
464                                 SYSCTL_STATIC_CHILDREN(_hw),
465                                 OID_AUTO,
466                                 device_get_nameunit(dev),
467                                 CTLFLAG_RD,
468                                 0, "");
469
470         if (sc->sysctl_tree == NULL) {
471                 device_printf(dev, "sysctl add node failed\n");
472                 error = EIO;
473                 goto fail2;
474         }
475
476         SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
477                        OID_AUTO, "debug", CTLFLAG_RW, &sc->debug_level, 0,
478                       "Set driver debug level (0 = off)");
479
480         SYSCTL_ADD_PROC(&sc->sysctl_ctx,
481                         SYSCTL_CHILDREN(sc->sysctl_tree),
482                         OID_AUTO, "cts_to_self", CTLTYPE_INT|CTLFLAG_RW,
483                         (void *)sc, 0, iwi_sysctl_cts_to_self, "I", 
484                         "Enable cts to self [0 = Off] [1 = On] [-1 = Auto]" );
485
486         SYSCTL_ADD_PROC(&sc->sysctl_ctx,
487                         SYSCTL_CHILDREN(sc->sysctl_tree),
488                         OID_AUTO, "antenna_diversity", CTLTYPE_INT|CTLFLAG_RW,
489                         (void *)sc, 0, iwi_sysctl_antenna_diversity,
490                         "I", "Set antenna diversity [0 = Both] "
491                         "[1 = Antenna A] [3 = Antenna B] [-1 = Auto]" );
492
493         SYSCTL_ADD_PROC(&sc->sysctl_ctx,
494                         SYSCTL_CHILDREN(sc->sysctl_tree),
495                         OID_AUTO, "bluetooth_coexist", CTLTYPE_INT|CTLFLAG_RW,
496                         (void *)sc, 0, iwi_sysctl_bt_coexist,
497                         "I", "Enable bluetooth coexistence heuristics "
498                         "[0 = Off] [1 = On] [-1 = Auto]" );
499
500         SYSCTL_ADD_PROC(&sc->sysctl_ctx,
501                         SYSCTL_CHILDREN(sc->sysctl_tree),
502                         OID_AUTO, "bg_autodetect", CTLTYPE_INT|CTLFLAG_RW,
503                         (void *)sc, 0, iwi_sysctl_bg_autodetect,
504                         "I", "Set b/g autodetect [0 = Off] [1 = On] [-1 = Auto]" );
505
506
507         SYSCTL_ADD_PROC(&sc->sysctl_ctx,
508                         SYSCTL_CHILDREN(sc->sysctl_tree), OID_AUTO, "radio",
509                         CTLTYPE_INT | CTLFLAG_RD, sc, 0, iwi_sysctl_radio, "I",
510                         "Radio transmitter switch");
511
512         SYSCTL_ADD_PROC(&sc->sysctl_ctx,
513                         SYSCTL_CHILDREN(sc->sysctl_tree), OID_AUTO, "stats",
514                         CTLTYPE_OPAQUE | CTLFLAG_RD, sc, 0, iwi_sysctl_stats, 
515                         "S,iwi_dump_buffer", "statistics");
516
517         SYSCTL_ADD_PROC(&sc->sysctl_ctx,
518                         SYSCTL_CHILDREN(sc->sysctl_tree),
519                         OID_AUTO, "firmware_logs", CTLTYPE_INT|CTLFLAG_RW,
520                         (void *)sc, 0, iwi_sysctl_dump_logs, "I", "Dump firmware logs");
521
522         SYSCTL_ADD_PROC(&sc->sysctl_ctx,
523                         SYSCTL_CHILDREN(sc->sysctl_tree), OID_AUTO,
524                         "neg_best_rates_first",
525                         CTLTYPE_INT | CTLFLAG_RW, sc, 0,
526                         iwi_sysctl_neg_best_rates_first, "I",
527                          "Negotiate highest rates first.");
528
529         SYSCTL_ADD_PROC(&sc->sysctl_ctx,
530                         SYSCTL_CHILDREN(sc->sysctl_tree), OID_AUTO,
531                         "disable_unicast_decrypt",
532                         CTLTYPE_INT | CTLFLAG_RW, sc, 0,
533                         iwi_sysctl_disable_unicast_decryption, "I",
534                          "Disable unicast decryption.");
535
536         SYSCTL_ADD_PROC(&sc->sysctl_ctx,
537                         SYSCTL_CHILDREN(sc->sysctl_tree), OID_AUTO,
538                         "disable_multicast_decrypt",
539                         CTLTYPE_INT | CTLFLAG_RW, sc, 0,
540                         iwi_sysctl_disable_multicast_decryption, "I",
541                          "Disable multicast decryption.");
542
543         /*
544          * Hook our interrupt after all initialization is complete
545          */
546         error = bus_setup_intr(dev, sc->irq, INTR_MPSAFE,
547                                iwi_intr, sc, &sc->sc_ih, ifp->if_serializer);
548         if (error != 0) {
549                 device_printf(dev, "could not set up interrupt\n");
550                 goto fail2;
551         }
552
553         return 0;
554
555 fail2:
556         bpfdetach(ifp);
557         ieee80211_ifdetach(ifp);
558 fail:
559         iwi_detach(dev);
560         return error;
561 }
562
563 static int
564 iwi_detach(device_t dev)
565 {
566         struct iwi_softc *sc = device_get_softc(dev);
567         struct ifnet *ifp = &sc->sc_ic.ic_if;
568
569         sc->flags |= IWI_FLAG_EXIT;
570         wakeup(IWI_FW_WAKE_MONITOR(sc)); /* Stop firmware monitor. */
571
572         tsleep(IWI_FW_MON_EXIT(sc), 0, "iwiexi", 10 * hz);
573
574         lwkt_serialize_enter(ifp->if_serializer);
575         if (device_is_attached(dev)) {
576                 iwi_stop(sc);
577                 iwi_free_firmware(sc);
578                 bpfdetach(ifp);
579                 ieee80211_ifdetach(ifp);
580         }
581
582         if (sc->sysctl_tree) {
583                 sysctl_ctx_free(&sc->sysctl_ctx);
584                 sc->sysctl_tree = 0;
585         }
586
587         if (sc->sc_ih != NULL)
588                 bus_teardown_intr(dev, sc->irq, sc->sc_ih);
589
590         if (sc->irq != NULL)
591                 bus_release_resource(dev, SYS_RES_IRQ, 0, sc->irq);
592
593         if (sc->mem != NULL) {
594                 bus_release_resource(dev, SYS_RES_MEMORY, IWI_PCI_BAR0,
595                     sc->mem);
596         }
597         lwkt_serialize_exit(ifp->if_serializer);
598
599         iwi_release(sc);
600
601         return 0;
602 }
603
604 static int
605 iwi_dma_alloc(struct iwi_softc *sc)
606 {
607         int i, error;
608
609         error = bus_dma_tag_create(NULL, /* parent */
610                                    1, 0,
611                                    BUS_SPACE_MAXADDR_32BIT,
612                                    BUS_SPACE_MAXADDR,
613                                    NULL, NULL,
614                                    MAXBSIZE, 128,
615                                    BUS_SPACE_MAXSIZE_32BIT,
616                                    BUS_DMA_ALLOCNOW,
617                                    &sc->iwi_parent_tag );
618         if (error != 0) {
619                 device_printf(sc->sc_dev, "could not create parent tag\n");
620                 goto fail;
621         }
622         /*
623          * Allocate and map Tx ring
624          */
625         error = bus_dma_tag_create(sc->iwi_parent_tag, 4, 0, BUS_SPACE_MAXADDR_32BIT,
626             BUS_SPACE_MAXADDR, NULL, NULL,
627             sizeof (struct iwi_tx_desc) * IWI_TX_RING_SIZE, 1,
628             sizeof (struct iwi_tx_desc) * IWI_TX_RING_SIZE,
629             BUS_DMA_ALLOCNOW, &sc->tx_ring_dmat);
630         if (error != 0) {
631                 device_printf(sc->sc_dev, "could not create tx ring DMA tag\n");
632                 goto fail;
633         }
634
635         error = bus_dmamem_alloc(sc->tx_ring_dmat,(void **) &sc->tx_desc,
636             BUS_DMA_WAITOK | BUS_DMA_ZERO, &sc->tx_ring_map);
637         if (error != 0) {
638                 device_printf(sc->sc_dev,
639                     "could not allocate tx ring DMA memory\n");
640                 goto fail;
641         }
642
643         error = bus_dmamap_load(sc->tx_ring_dmat, sc->tx_ring_map,
644             sc->tx_desc, sizeof (struct iwi_tx_desc) * IWI_TX_RING_SIZE,
645             iwi_dma_map_addr, &sc->tx_ring_pa, 0);
646         if (error != 0) {
647                 device_printf(sc->sc_dev, "could not load tx ring DMA map\n");
648                 goto fail;
649         }
650
651         /*
652          * Allocate and map command ring
653          */
654         error = bus_dma_tag_create(sc->iwi_parent_tag, 4, 0, BUS_SPACE_MAXADDR_32BIT,
655             BUS_SPACE_MAXADDR, NULL, NULL,
656             sizeof (struct iwi_cmd_desc) * IWI_CMD_RING_SIZE, 1,
657             sizeof (struct iwi_cmd_desc) * IWI_CMD_RING_SIZE, 
658             BUS_DMA_ALLOCNOW,
659             &sc->cmd_ring_dmat);
660         if (error != 0) {
661                 device_printf(sc->sc_dev,
662                     "could not create command ring DMA tag\n");
663                 goto fail;
664         }
665
666         error = bus_dmamem_alloc(sc->cmd_ring_dmat, (void **)&sc->cmd_desc,
667             BUS_DMA_WAITOK | BUS_DMA_ZERO, &sc->cmd_ring_map);
668         if (error != 0) {
669                 device_printf(sc->sc_dev,
670                     "could not allocate command ring DMA memory\n");
671                 goto fail;
672         }
673
674         error = bus_dmamap_load(sc->cmd_ring_dmat, sc->cmd_ring_map,
675             sc->cmd_desc, sizeof (struct iwi_cmd_desc) * IWI_CMD_RING_SIZE,
676             iwi_dma_map_addr, &sc->cmd_ring_pa, 0);
677         if (error != 0) {
678                 device_printf(sc->sc_dev,
679                     "could not load command ring DMA map\n");
680                 goto fail;
681         }
682
683         /*
684          * Allocate Tx buffers DMA maps
685          */
686         error = bus_dma_tag_create(sc->iwi_parent_tag, 1, 0, BUS_SPACE_MAXADDR_32BIT,
687             BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES, IWI_MAX_NSEG, MCLBYTES,
688             BUS_DMA_ALLOCNOW, &sc->tx_buf_dmat);
689         if (error != 0) {
690                 device_printf(sc->sc_dev, "could not create tx buf DMA tag\n");
691                 goto fail;
692         }
693
694         for (i = 0; i < IWI_TX_RING_SIZE; i++) {
695                 error = bus_dmamap_create(sc->tx_buf_dmat, 0,
696                     &sc->tx_buf[i].map);
697                 if (error != 0) {
698                         device_printf(sc->sc_dev,
699                             "could not create tx buf DMA map");
700                         goto fail;
701                 }
702         }
703
704         /*
705          * Allocate and map Rx buffers
706          */
707         error = bus_dma_tag_create(sc->iwi_parent_tag, 1, 0, BUS_SPACE_MAXADDR_32BIT,
708             BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES, 1, MCLBYTES,
709             BUS_DMA_ALLOCNOW, &sc->rx_buf_dmat);
710         if (error != 0) {
711                 device_printf(sc->sc_dev, "could not create rx buf DMA tag\n");
712                 goto fail;
713         }
714
715         for (i = 0; i < IWI_RX_RING_SIZE; i++) {
716
717                 error = bus_dmamap_create(sc->rx_buf_dmat, 0,
718                     &sc->rx_buf[i].map);
719                 if (error != 0) {
720                         device_printf(sc->sc_dev,
721                             "could not create rx buf DMA map");
722                         goto fail;
723                 }
724
725                 sc->rx_buf[i].m = m_getcl(MB_DONTWAIT, MT_DATA, M_PKTHDR);
726                 if (sc->rx_buf[i].m == NULL) {
727                         device_printf(sc->sc_dev,
728                             "could not allocate rx mbuf\n");
729                         error = ENOMEM;
730                         goto fail;
731                 }
732
733                 error = bus_dmamap_load(sc->rx_buf_dmat, sc->rx_buf[i].map,
734                     mtod(sc->rx_buf[i].m, void *), MCLBYTES, iwi_dma_map_addr,
735                     &sc->rx_buf[i].physaddr, 0);
736                 if (error != 0) {
737                         device_printf(sc->sc_dev,
738                             "could not load rx buf DMA map");
739                         goto fail;
740                 }
741         }
742
743         return 0;
744
745 fail:   iwi_release(sc);
746         return error;
747 }
748
749 static void
750 iwi_release(struct iwi_softc *sc)
751 {
752         int i;
753
754         if (sc->tx_ring_dmat != NULL) {
755                 if (sc->tx_desc != NULL) {
756                         bus_dmamap_sync(sc->tx_ring_dmat, sc->tx_ring_map,
757                             BUS_DMASYNC_POSTWRITE);
758                         bus_dmamap_unload(sc->tx_ring_dmat, sc->tx_ring_map);
759                         bus_dmamem_free(sc->tx_ring_dmat, sc->tx_desc,
760                             sc->tx_ring_map);
761                 }
762                 bus_dma_tag_destroy(sc->tx_ring_dmat);
763         }
764
765         if (sc->cmd_ring_dmat != NULL) {
766                 if (sc->cmd_desc != NULL) {
767                         bus_dmamap_sync(sc->cmd_ring_dmat, sc->cmd_ring_map,
768                             BUS_DMASYNC_POSTWRITE);
769                         bus_dmamap_unload(sc->cmd_ring_dmat, sc->cmd_ring_map);
770                         bus_dmamem_free(sc->cmd_ring_dmat, sc->cmd_desc,
771                             sc->cmd_ring_map);
772                 }
773                 bus_dma_tag_destroy(sc->cmd_ring_dmat);
774         }
775
776         if (sc->tx_buf_dmat != NULL) {
777                 for (i = 0; i < IWI_TX_RING_SIZE; i++) {
778                         if (sc->tx_buf[i].m != NULL) {
779                                 bus_dmamap_sync(sc->tx_buf_dmat,
780                                     sc->tx_buf[i].map, BUS_DMASYNC_POSTWRITE);
781                                 bus_dmamap_unload(sc->tx_buf_dmat,
782                                     sc->tx_buf[i].map);
783                                 m_freem(sc->tx_buf[i].m);
784                         }
785                         bus_dmamap_destroy(sc->tx_buf_dmat, sc->tx_buf[i].map);
786                 }
787                 bus_dma_tag_destroy(sc->tx_buf_dmat);
788         }
789
790         if (sc->rx_buf_dmat != NULL) {
791                 for (i = 0; i < IWI_RX_RING_SIZE; i++) {
792                         if (sc->rx_buf[i].m != NULL) {
793                                 bus_dmamap_sync(sc->rx_buf_dmat,
794                                     sc->rx_buf[i].map, BUS_DMASYNC_POSTREAD);
795                                 bus_dmamap_unload(sc->rx_buf_dmat,
796                                     sc->rx_buf[i].map);
797                                 m_freem(sc->rx_buf[i].m);
798                         }
799                         bus_dmamap_destroy(sc->rx_buf_dmat, sc->rx_buf[i].map);
800                 }
801                 bus_dma_tag_destroy(sc->rx_buf_dmat);
802         }
803         if ( sc->iwi_parent_tag != NULL ) {
804                 bus_dma_tag_destroy(sc->iwi_parent_tag);
805         }
806 }
807
808 static int
809 iwi_shutdown(device_t dev)
810 {
811         struct iwi_softc *sc = device_get_softc(dev);
812         struct ifnet *ifp = &sc->sc_ic.ic_if;
813
814         lwkt_serialize_enter(ifp->if_serializer);
815         iwi_stop(sc);
816         lwkt_serialize_exit(ifp->if_serializer);
817
818         return 0;
819 }
820
821 static int
822 iwi_suspend(device_t dev)
823 {
824         struct iwi_softc *sc = device_get_softc(dev);
825         struct ifnet *ifp = &sc->sc_ic.ic_if;
826
827         lwkt_serialize_enter(ifp->if_serializer);
828         iwi_stop(sc);
829         lwkt_serialize_exit(ifp->if_serializer);
830
831         return 0;
832 }
833
834 static int
835 iwi_resume(device_t dev)
836 {
837         struct iwi_softc *sc = device_get_softc(dev);
838         struct ifnet *ifp = &sc->sc_ic.ic_if;
839
840         lwkt_serialize_enter(ifp->if_serializer);
841         pci_write_config(dev, 0x41, 0, 1);
842
843         if (ifp->if_flags & IFF_UP) {
844                 ifp->if_init(ifp->if_softc);
845                 if (ifp->if_flags & IFF_RUNNING)
846                         ifp->if_start(ifp);
847         }
848         lwkt_serialize_exit(ifp->if_serializer);
849         return 0;
850 }
851
852 static int
853 iwi_media_change(struct ifnet *ifp)
854 {
855         struct iwi_softc *sc = ifp->if_softc;
856         int error = 0;
857
858         error = ieee80211_media_change(ifp);
859         if (error != ENETRESET) {
860                 return error;
861         }
862         error = 0; /* clear ENETRESET */
863
864         if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING)){
865                 iwi_init(sc);
866                 error = tsleep( IWI_FW_CMD_ACKED(sc), 0, "iwirun", hz );
867         }
868         return error;
869 }
870
871 static void
872 iwi_media_status(struct ifnet *ifp, struct ifmediareq *imr)
873 {
874         struct iwi_softc *sc = ifp->if_softc;
875         struct ieee80211com *ic = &sc->sc_ic;
876 #define N(a)    (sizeof (a) / sizeof (a[0]))
877         static const struct {
878                 u_int32_t       val;
879                 int             rate;
880         } rates[] = {
881                 { IWI_RATE_DS1,      2 },
882                 { IWI_RATE_DS2,      4 },
883                 { IWI_RATE_DS5,     11 },
884                 { IWI_RATE_DS11,    22 },
885                 { IWI_RATE_OFDM6,   12 },
886                 { IWI_RATE_OFDM9,   18 },
887                 { IWI_RATE_OFDM12,  24 },
888                 { IWI_RATE_OFDM18,  36 },
889                 { IWI_RATE_OFDM24,  48 },
890                 { IWI_RATE_OFDM36,  72 },
891                 { IWI_RATE_OFDM48,  96 },
892                 { IWI_RATE_OFDM54, 108 },
893         };
894         u_int32_t val, i;
895         int rate;
896
897         imr->ifm_status = IFM_AVALID;
898         imr->ifm_active = IFM_IEEE80211;
899         if (ic->ic_state == IEEE80211_S_RUN)
900                 imr->ifm_status |= IFM_ACTIVE;
901
902         /* read current transmission rate from adapter */
903         val = CSR_READ_4(sc, IWI_CSR_CURRENT_TX_RATE);
904
905         /* convert rate to 802.11 rate */
906         for (i = 0; i < N(rates) && rates[i].val != val ; i++);
907         rate = (i < N(rates)) ? rates[i].rate : 0;
908
909         imr->ifm_active |= ieee80211_rate2media(ic, rate, ic->ic_curmode);
910         switch (ic->ic_opmode) {
911         case IEEE80211_M_STA:
912                 break;
913
914         case IEEE80211_M_IBSS:
915                 imr->ifm_active |= IFM_IEEE80211_ADHOC;
916                 break;
917
918         case IEEE80211_M_MONITOR:
919                 imr->ifm_active |= IFM_IEEE80211_MONITOR;
920                 break;
921
922         case IEEE80211_M_AHDEMO:
923         case IEEE80211_M_HOSTAP:
924                 /* should not get there */
925                 break;
926         }
927 #undef N
928 }
929
930 static int
931 iwi_disassociate( struct iwi_softc *sc  )
932 {
933         sc->assoc.type = 2; /* DISASSOCIATE */
934         return iwi_cmd(sc, IWI_CMD_ASSOCIATE, &sc->assoc, sizeof sc->assoc, 0);
935 }
936
937
938 static int
939 iwi_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg __unused)
940 {
941         struct iwi_softc *sc = ic->ic_softc;
942         struct ifnet *ifp = &ic->ic_if;
943
944         ASSERT_SERIALIZED(ifp->if_serializer);
945
946         switch (nstate) {
947         case IEEE80211_S_SCAN:
948                 if (sc->flags & IWI_FLAG_ASSOCIATED) {
949                         sc->flags &= ~( IWI_FLAG_ASSOCIATED );
950                         iwi_disassociate(sc);
951
952                         crit_enter();
953                         tsleep_interlock(IWI_FW_DEASSOCIATED(sc));
954                         lwkt_serialize_exit(ifp->if_serializer);
955                         tsleep(IWI_FW_DEASSOCIATED(sc), 0, "iwisca", hz );
956                         crit_exit();
957                         lwkt_serialize_enter(ifp->if_serializer);
958                 }
959                 if ( !(sc->flags & IWI_FLAG_SCANNING) &&
960                      !(sc->flags & IWI_FLAG_RF_DISABLED) ) {
961                         iwi_scan(sc);
962                 }
963                 break;
964
965         case IEEE80211_S_AUTH:
966                 if ( sc->flags & IWI_FLAG_ASSOCIATED ) {
967                         sc->flags &= ~( IWI_FLAG_ASSOCIATED );
968                         iwi_disassociate(sc);
969
970                         crit_enter();
971                         tsleep_interlock(IWI_FW_DEASSOCIATED(sc));
972                         lwkt_serialize_exit(ifp->if_serializer);
973                         tsleep(IWI_FW_DEASSOCIATED(sc), 0, "iwiaut", hz );
974                         crit_exit();
975                         lwkt_serialize_enter(ifp->if_serializer);
976                 }
977                 if ( iwi_auth_and_assoc(sc) != 0 )
978                         ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
979                 break;
980
981         case IEEE80211_S_RUN:
982                 if (sc->flags & IWI_FLAG_SCAN_COMPLETE) {
983                         sc->flags &= ~(IWI_FLAG_SCAN_COMPLETE);
984                         if (ic->ic_opmode == IEEE80211_M_IBSS ||
985                             ic->ic_opmode == IEEE80211_M_MONITOR ) {
986                                 /* 
987                                  * In IBSS mode, following an end_scan
988                                  * the ieee80211 stack state machine transitions
989                                  * straight to 'run' state. This is out of
990                                  * step with the firmware which requires
991                                  * an association first. Flip our state from
992                                  * RUN back to AUTH to allow us to tell the
993                                  * firmware to associate.
994                                  */
995                                 ieee80211_new_state(ic, IEEE80211_S_AUTH, -1);
996                         }
997                 }
998                 break;
999
1000         case IEEE80211_S_ASSOC:
1001                 break;
1002         case IEEE80211_S_INIT:
1003                 sc->flags &= ~( IWI_FLAG_SCANNING | IWI_FLAG_ASSOCIATED );
1004                 break;
1005         }
1006
1007         ic->ic_state = nstate;
1008         return 0;
1009 }
1010
1011 /*
1012  * Read 16 bits at address 'addr' from the serial EEPROM.
1013  * DON'T PLAY WITH THIS CODE UNLESS YOU KNOW *EXACTLY* WHAT YOU'RE DOING!
1014  */
1015 static u_int16_t
1016 iwi_read_prom_word(struct iwi_softc *sc, u_int8_t addr)
1017 {
1018         u_int32_t tmp;
1019         u_int16_t val;
1020         int n;
1021
1022         /* Clock C once before the first command */
1023         IWI_EEPROM_CTL(sc, 0);
1024         IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1025         IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1026         IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1027
1028         /* Write start bit (1) */
1029         IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D);
1030         IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D | IWI_EEPROM_C);
1031
1032         /* Write READ opcode (10) */
1033         IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D);
1034         IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D | IWI_EEPROM_C);
1035         IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1036         IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1037
1038         /* Write address A7-A0 */
1039         for (n = 7; n >= 0; n--) {
1040                 IWI_EEPROM_CTL(sc, IWI_EEPROM_S |
1041                     (((addr >> n) & 1) << IWI_EEPROM_SHIFT_D));
1042                 IWI_EEPROM_CTL(sc, IWI_EEPROM_S |
1043                     (((addr >> n) & 1) << IWI_EEPROM_SHIFT_D) | IWI_EEPROM_C);
1044         }
1045
1046         IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1047
1048         /* Read data Q15-Q0 */
1049         val = 0;
1050         for (n = 15; n >= 0; n--) {
1051                 IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1052                 IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1053                 tmp = MEM_READ_4(sc, IWI_MEM_EEPROM_CTL);
1054                 val |= ((tmp & IWI_EEPROM_Q) >> IWI_EEPROM_SHIFT_Q) << n;
1055         }
1056
1057         IWI_EEPROM_CTL(sc, 0);
1058
1059         /* Clear Chip Select and clock C */
1060         IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1061         IWI_EEPROM_CTL(sc, 0);
1062         IWI_EEPROM_CTL(sc, IWI_EEPROM_C);
1063
1064         return be16toh(val);
1065 }
1066
1067 /*
1068  * XXX: Hack to set the current channel to the value advertised in beacons or
1069  * probe responses. Only used during AP detection.
1070  */
1071 static void
1072 iwi_fix_channel(struct iwi_softc *sc, struct mbuf *m)
1073 {
1074         struct ieee80211com *ic = &sc->sc_ic;
1075         struct ieee80211_frame *wh;
1076         u_int8_t subtype;
1077         u_int8_t *frm, *efrm;
1078
1079         wh = mtod(m, struct ieee80211_frame *);
1080
1081         if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_MGT)
1082                 return;
1083
1084         subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
1085
1086         if (subtype != IEEE80211_FC0_SUBTYPE_BEACON &&
1087             subtype != IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1088                 return;
1089
1090         /*
1091          * Cache station entries from beacons and probes.
1092          */
1093         if ( iwi_find_station(sc, wh->i_addr2) == 0xff )
1094                 iwi_cache_station(sc, wh->i_addr2);
1095
1096         frm = (u_int8_t *)(wh + 1);
1097         efrm = mtod(m, u_int8_t *) + m->m_len;
1098
1099         frm += 12;      /* skip tstamp, bintval and capinfo fields */
1100 #if 0
1101         { /* XXX - debugging code */
1102                 u_int8_t *ptr;
1103                 u_int32_t cnt;
1104                 printf("Frame -->");
1105                 for ( ptr = frm, cnt = 0 ; ptr < efrm ; ptr++, cnt++ ) {
1106                         if ( cnt % 8 == 0 )
1107                                 printf("\n");
1108                         printf("0x%-2.2x ", *ptr);
1109                 }
1110                 printf("<-- End Frame\n");
1111         }
1112 #endif
1113
1114         while (frm < efrm) {
1115                 if (*frm == IEEE80211_ELEMID_DSPARMS)
1116 #if IEEE80211_CHAN_MAX < 255
1117                 if (frm[2] <= IEEE80211_CHAN_MAX)
1118 #endif
1119                         ic->ic_bss->ni_chan = &ic->ic_channels[frm[2]];
1120
1121                 frm += frm[1] + 2; /* advance to the next tag */
1122         }
1123 }
1124
1125 static void
1126 iwi_frame_intr(struct iwi_softc *sc, struct iwi_rx_buf *buf, int i,
1127     struct iwi_frame *frame)
1128 {
1129         struct ieee80211com *ic = &sc->sc_ic;
1130         struct ifnet *ifp = &ic->ic_if;
1131         struct mbuf *m;
1132         struct ieee80211_frame *wh;
1133         struct ieee80211_node *ni;
1134         int error;
1135
1136         DPRINTFN(5, ("RX!DATA!%u!%u!%u\n", le16toh(frame->len), frame->chan,
1137             frame->rssi_dbm));
1138
1139         if (le16toh(frame->len) < sizeof (struct ieee80211_frame_min) ||
1140             le16toh(frame->len) > MCLBYTES) {
1141                 device_printf(sc->sc_dev, "bad frame length\n");
1142                 return;
1143         }
1144
1145         bus_dmamap_unload(sc->rx_buf_dmat, buf->map);
1146
1147         /* Finalize mbuf */
1148         m = buf->m;
1149         m->m_pkthdr.rcvif = ifp;
1150         m->m_pkthdr.len = m->m_len = sizeof (struct iwi_hdr) +
1151             sizeof (struct iwi_frame) + le16toh(frame->len);
1152
1153         m_adj(m, sizeof (struct iwi_hdr) + sizeof (struct iwi_frame));
1154
1155         wh = mtod(m, struct ieee80211_frame *);
1156         if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1157                 /*
1158                  * Hardware decrypts the frame itself but leaves the WEP bit
1159                  * set in the 802.11 header and don't remove the iv and crc
1160                  * fields
1161                  */
1162                 wh->i_fc[1] &= ~IEEE80211_FC1_WEP;
1163                 bcopy(wh, (char *)wh + IEEE80211_WEP_IVLEN +
1164                     IEEE80211_WEP_KIDLEN, sizeof (struct ieee80211_frame));
1165                 m_adj(m, IEEE80211_WEP_IVLEN + IEEE80211_WEP_KIDLEN);
1166                 m_adj(m, -IEEE80211_WEP_CRCLEN);
1167                 wh = mtod(m, struct ieee80211_frame *);
1168         }
1169
1170         if (sc->sc_drvbpf != NULL) {
1171                 struct iwi_rx_radiotap_header *tap = &sc->sc_rxtap;
1172
1173                 tap->wr_flags = 0;
1174                 tap->wr_rate = frame->rate;
1175                 tap->wr_chan_freq =
1176                     htole16(ic->ic_channels[frame->chan].ic_freq);
1177                 tap->wr_chan_flags =
1178                     htole16(ic->ic_channels[frame->chan].ic_flags);
1179                 tap->wr_antsignal = frame->signal;
1180                 tap->wr_antnoise = frame->noise;
1181                 tap->wr_antenna = frame->antenna;
1182
1183                 bpf_ptap(sc->sc_drvbpf, m, tap, sc->sc_rxtap_len);
1184         }
1185
1186         if (ic->ic_state == IEEE80211_S_SCAN)
1187                 iwi_fix_channel(sc, m);
1188
1189         if (ic->ic_opmode != IEEE80211_M_STA) {
1190                 ni = ieee80211_find_node(ic, wh->i_addr2);
1191                 if (ni == NULL)
1192                         ni = ieee80211_ref_node(ic->ic_bss);
1193         } else
1194                 ni = ieee80211_ref_node(ic->ic_bss);
1195
1196         /* Send the frame to the upper layer */
1197         ieee80211_input(ifp, m, ni, IWI_RSSIDBM2RAW(frame->rssi_dbm), 0);
1198
1199         if (ni == ic->ic_bss)
1200                 ieee80211_unref_node(&ni);
1201         else
1202                 ieee80211_free_node(ic, ni);
1203
1204         buf->m = m_getcl(MB_DONTWAIT, MT_DATA, M_PKTHDR);
1205         if (buf->m == NULL) {
1206                 device_printf(sc->sc_dev, "could not allocate rx mbuf\n");
1207                 return;
1208         }
1209
1210         error = bus_dmamap_load(sc->rx_buf_dmat, buf->map, mtod(buf->m, void *),
1211             MCLBYTES, iwi_dma_map_addr, &buf->physaddr, 0);
1212         if (error != 0) {
1213                 device_printf(sc->sc_dev, "could not load rx buf DMA map\n");
1214                 m_freem(buf->m);
1215                 buf->m = NULL;
1216                 return;
1217         }
1218
1219         CSR_WRITE_4(sc, IWI_CSR_RX_BASE + i * 4, buf->physaddr);
1220 }
1221
1222 static void
1223 iwi_notification_intr(struct iwi_softc *sc, struct iwi_notif *notif)
1224 {
1225         struct ieee80211com *ic = &sc->sc_ic;
1226         struct ifnet *ifp = &ic->ic_if;
1227         struct iwi_notif_scan_channel *chan;
1228         struct iwi_notif_scan_complete *scan;
1229         struct iwi_notif_authentication *auth;
1230         struct iwi_notif_association *assoc;
1231
1232         switch (notif->type) {
1233         case IWI_NOTIF_TYPE_SCAN_CHANNEL:
1234                 chan = (struct iwi_notif_scan_channel *)(notif + 1);
1235
1236                 DPRINTFN(2, ("Scan channel (%u)\n", chan->nchan));
1237                 break;
1238
1239         case IWI_NOTIF_TYPE_SCAN_COMPLETE:
1240                 scan = (struct iwi_notif_scan_complete *)(notif + 1);
1241
1242                 DPRINTFN(2, ("Scan completed (%u, %u)\n", scan->nchan,
1243                     scan->status));
1244
1245                 sc->flags &= ~(IWI_FLAG_SCANNING);
1246                 sc->flags |= IWI_FLAG_SCAN_COMPLETE;
1247
1248                 if ( sc->flags & IWI_FLAG_SCAN_ABORT )
1249                         sc->flags &= ~(IWI_FLAG_SCAN_ABORT);
1250                 else
1251                         ieee80211_end_scan(ifp);
1252                 wakeup(IWI_FW_SCAN_COMPLETED(sc));
1253                 break;
1254
1255         case IWI_NOTIF_TYPE_AUTHENTICATION:
1256                 auth = (struct iwi_notif_authentication *)(notif + 1);
1257
1258                 DPRINTFN(2, ("Authentication (%u)\n", auth->state));
1259
1260                 switch (auth->state) {
1261                 case IWI_AUTHENTICATED:
1262                         ieee80211_new_state(ic, IEEE80211_S_ASSOC, -1);
1263                         break;
1264
1265                 case IWI_DEAUTHENTICATED:
1266                         ieee80211_begin_scan(ifp);/* not necessary */
1267                         break;
1268
1269                 default:
1270                         device_printf(sc->sc_dev,
1271                             "unknown authentication state %u\n", auth->state);
1272                 }
1273                 break;
1274
1275         case IWI_NOTIF_TYPE_ASSOCIATION:
1276                 assoc = (struct iwi_notif_association *)(notif + 1);
1277
1278                 DPRINTFN(2, ("Association (%u, %u)\n", assoc->state,
1279                     assoc->status));
1280
1281                 switch (assoc->state) {
1282                 case IWI_ASSOCIATED:
1283                         sc->flags |= IWI_FLAG_ASSOCIATED;
1284                         ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
1285                         break;
1286
1287                 case IWI_DEASSOCIATED:
1288                         sc->flags &= ~(IWI_FLAG_ASSOCIATED);
1289                         wakeup(IWI_FW_DEASSOCIATED(sc));
1290                         ieee80211_begin_scan(ifp);/* probably not necessary */
1291                         break;
1292
1293                 default:
1294                         device_printf(sc->sc_dev,
1295                             "unknown association state %u\n", assoc->state);
1296                 }
1297                 break;
1298
1299         case IWI_NOTIF_TYPE_CALIBRATION:
1300                 DPRINTFN(5, ("Notification calib (%u)\n", notif->type));
1301                 break;
1302         case IWI_NOTIF_TYPE_BEACON:
1303                 DPRINTFN(5, ("Notification beacon (%u)\n", notif->type));
1304                 break;
1305         case IWI_NOTIF_TYPE_NOISE:
1306                 DPRINTFN(5, ("Notification noise (%u)\n", notif->type));
1307                 break;
1308
1309         default:
1310                 device_printf(sc->sc_dev, "unknown notification type %u\n",
1311                     notif->type);
1312         }
1313 }
1314
1315 static void
1316 iwi_rx_intr(struct iwi_softc *sc)
1317 {
1318         struct iwi_rx_buf *buf;
1319         struct iwi_hdr *hdr;
1320         u_int32_t r, i;
1321
1322         r = CSR_READ_4(sc, IWI_CSR_RX_READ_INDEX);
1323
1324         for (i = (sc->rx_cur + 1) % IWI_RX_RING_SIZE; i != r;
1325              i = (i + 1) % IWI_RX_RING_SIZE) {
1326
1327                 buf = &sc->rx_buf[i];
1328
1329                 bus_dmamap_sync(sc->rx_buf_dmat, buf->map,
1330                     BUS_DMASYNC_POSTREAD);
1331
1332                 hdr = mtod(buf->m, struct iwi_hdr *);
1333
1334                 switch (hdr->type) {
1335                 case IWI_HDR_TYPE_FRAME:
1336                         iwi_frame_intr(sc, buf, i,
1337                             (struct iwi_frame *)(hdr + 1));
1338                         break;
1339
1340                 case IWI_HDR_TYPE_NOTIF:
1341                         iwi_notification_intr(sc,
1342                             (struct iwi_notif *)(hdr + 1));
1343                         break;
1344
1345                 default:
1346                         device_printf(sc->sc_dev, "unknown hdr type %u\n",
1347                             hdr->type);
1348                 }
1349         }
1350
1351         /* Tell the firmware what we have processed */
1352         sc->rx_cur = (r == 0) ? IWI_RX_RING_SIZE - 1 : r - 1;
1353         CSR_WRITE_4(sc, IWI_CSR_RX_WRITE_INDEX, sc->rx_cur);
1354 }
1355
1356 static void
1357 iwi_tx_intr(struct iwi_softc *sc)
1358 {
1359         struct ieee80211com *ic = &sc->sc_ic;
1360         struct ifnet *ifp = &ic->ic_if;
1361         struct iwi_tx_buf *buf;
1362         u_int32_t r, i;
1363
1364         r = CSR_READ_4(sc, IWI_CSR_TX1_READ_INDEX);
1365 #if  notyet
1366         bus_dmamap_sync(sc->tx_ring_dmat, sc->tx_ring_map, BUS_DMASYNC_POSTWRITE);
1367 #endif
1368
1369         for (i = (sc->tx_old + 1) % IWI_TX_RING_SIZE; i != r;
1370              i = (i + 1) % IWI_TX_RING_SIZE) {
1371
1372                 buf = &sc->tx_buf[i];
1373
1374                 bus_dmamap_sync(sc->tx_buf_dmat, buf->map,
1375                     BUS_DMASYNC_POSTWRITE);
1376                 bus_dmamap_unload(sc->tx_buf_dmat, buf->map);
1377                 m_freem(buf->m);
1378                 buf->m = NULL;
1379                 if (buf->ni != ic->ic_bss)
1380                         ieee80211_free_node(ic, buf->ni);
1381                 buf->ni = NULL;
1382
1383                 sc->tx_queued--;
1384
1385                 /* kill watchdog timer */
1386                 sc->sc_tx_timer = 0;
1387         }
1388
1389         /* Remember what the firmware has processed */
1390         sc->tx_old = (r == 0) ? IWI_TX_RING_SIZE - 1 : r - 1;
1391
1392         /* Call start() since some buffer descriptors have been released */
1393         ifp->if_flags &= ~IFF_OACTIVE;
1394         (*ifp->if_start)(ifp);
1395 }
1396
1397 static void
1398 iwi_intr(void *arg)
1399 {
1400         struct iwi_softc *sc = arg;
1401         struct ieee80211com *ic = &sc->sc_ic;
1402         struct ifnet *ifp = &ic->ic_if;
1403         u_int32_t r;
1404
1405         if ((r = CSR_READ_4(sc, IWI_CSR_INTR)) == 0 || r == 0xffffffff)
1406                 return;
1407
1408         /* Disable interrupts */
1409         CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, 0);
1410
1411         DPRINTFN(8, ("INTR!0x%08x\n", r));
1412
1413         sc->flags &= ~(IWI_FLAG_RF_DISABLED);
1414
1415         if (r & IWI_INTR_FATAL_ERROR) {
1416                 if (!(sc->flags & (IWI_FLAG_RESET | IWI_FLAG_EXIT))) {
1417                         sc->flags |= IWI_FLAG_RESET;
1418                         wakeup(IWI_FW_WAKE_MONITOR(sc));
1419                 }
1420         }
1421
1422         if (r & IWI_INTR_PARITY_ERROR) {
1423                 device_printf(sc->sc_dev, "fatal error\n");
1424                 sc->sc_ic.ic_if.if_flags &= ~IFF_UP;
1425                 iwi_stop(sc);
1426         }
1427
1428         if (r & IWI_INTR_FW_INITED) {
1429                 if (!(r & (IWI_INTR_FATAL_ERROR | IWI_INTR_PARITY_ERROR)))
1430                         wakeup(IWI_FW_INITIALIZED(sc));
1431         }
1432
1433         if (r & IWI_INTR_RADIO_OFF) {
1434                 DPRINTF(("radio transmitter off\n"));
1435                 sc->sc_ic.ic_if.if_flags &= ~IFF_UP;
1436                 iwi_stop(sc);
1437                 sc->flags |= IWI_FLAG_RF_DISABLED;
1438         }
1439
1440         if (r & IWI_INTR_RX_TRANSFER)
1441                 iwi_rx_intr(sc);
1442
1443         if (r & IWI_INTR_CMD_TRANSFER)
1444                 wakeup(IWI_FW_CMD_ACKED(sc));
1445
1446         if (r & IWI_INTR_TX1_TRANSFER)
1447                 iwi_tx_intr(sc);
1448
1449         if (r & ~(IWI_HANDLED_INTR_MASK)) {
1450                 device_printf(sc->sc_dev,
1451                               "unhandled interrupt(s) INTR!0x%08x\n",
1452                               r & ~(IWI_HANDLED_INTR_MASK));
1453         }
1454
1455         /* Acknowledge interrupts */
1456         CSR_WRITE_4(sc, IWI_CSR_INTR, r);
1457
1458         /* Re-enable interrupts */
1459         CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, IWI_INTR_MASK);
1460
1461         if ((ifp->if_flags & IFF_RUNNING) && !ifq_is_empty(&ifp->if_snd))
1462                 iwi_start(ifp);
1463 }
1464
1465 struct iwi_dma_mapping {
1466         bus_dma_segment_t segs[IWI_MAX_NSEG];
1467         int nseg;
1468         bus_size_t mapsize;
1469 };
1470
1471 static void
1472 iwi_dma_map_buf(void *arg, bus_dma_segment_t *segs, int nseg,
1473     bus_size_t mapsize, int error)
1474 {
1475         struct iwi_dma_mapping *map = arg;
1476
1477         if (error != 0)
1478                 return;
1479
1480         KASSERT(nseg <= IWI_MAX_NSEG, ("too many DMA segments %d", nseg));
1481
1482         bcopy(segs, map->segs, nseg * sizeof (bus_dma_segment_t));
1483         map->nseg = nseg;
1484         map->mapsize = mapsize;
1485 }
1486
1487 static void
1488 iwi_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg __unused, int error)
1489 {
1490         if (error != 0) {
1491                 printf("iwi: fatal DMA mapping error !!!\n");
1492                 return;
1493         }
1494
1495         KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
1496
1497         *(bus_addr_t *)arg = segs[0].ds_addr;
1498 }
1499
1500 static int
1501 iwi_cmd(struct iwi_softc *sc, u_int8_t type, void *data, u_int8_t len,
1502     int async)
1503 {
1504         struct iwi_cmd_desc *desc;
1505         int ret;
1506
1507         DPRINTFN(2, ("TX!CMD!%u!%u\n", type, len));
1508
1509         desc = &sc->cmd_desc[sc->cmd_cur];
1510         desc->hdr.type = IWI_HDR_TYPE_COMMAND;
1511         desc->hdr.flags = IWI_HDR_FLAG_IRQ;
1512         desc->type = type;
1513         desc->len = len;
1514         bcopy(data, desc->data, len);
1515
1516         bus_dmamap_sync(sc->cmd_ring_dmat, sc->cmd_ring_map,
1517             BUS_DMASYNC_PREWRITE);
1518
1519         sc->cmd_cur = (sc->cmd_cur + 1) % IWI_CMD_RING_SIZE;
1520         if (!async) {
1521                 struct ifnet *ifp = &sc->sc_ic.ic_if;
1522
1523                 crit_enter();
1524                 CSR_WRITE_4(sc, IWI_CSR_CMD_WRITE_INDEX, sc->cmd_cur);
1525                 tsleep_interlock(IWI_FW_CMD_ACKED(sc));
1526                 lwkt_serialize_exit(ifp->if_serializer);
1527                 ret = tsleep(IWI_FW_CMD_ACKED(sc), 0, "iwicmd", hz);
1528                 crit_exit();
1529                 lwkt_serialize_enter(ifp->if_serializer);
1530         } else {
1531                 CSR_WRITE_4(sc, IWI_CSR_CMD_WRITE_INDEX, sc->cmd_cur);
1532                 ret = 0;
1533         }
1534
1535         return ret; 
1536 }
1537
1538 static int
1539 iwi_tx_start(struct ifnet *ifp, struct mbuf *m0, struct ieee80211_node *ni)
1540 {
1541         struct iwi_softc *sc = ifp->if_softc;
1542         struct ieee80211com *ic = &sc->sc_ic;
1543         struct ieee80211_frame *wh;
1544         struct iwi_tx_buf *buf;
1545         struct iwi_tx_desc *desc;
1546         struct iwi_dma_mapping map;
1547         struct mbuf *mnew;
1548         u_int32_t id = 0;
1549         int error, i;
1550
1551         if (sc->sc_drvbpf != NULL) {
1552                 struct iwi_tx_radiotap_header *tap = &sc->sc_txtap;
1553
1554                 tap->wt_flags = 0;
1555                 tap->wt_chan_freq = htole16(ic->ic_bss->ni_chan->ic_freq);
1556                 tap->wt_chan_flags = htole16(ic->ic_bss->ni_chan->ic_flags);
1557
1558                 bpf_ptap(sc->sc_drvbpf, m0, tap, sc->sc_txtap_len);
1559         }
1560
1561         buf = &sc->tx_buf[sc->tx_cur];
1562         desc = &sc->tx_desc[sc->tx_cur];
1563
1564         wh = mtod(m0, struct ieee80211_frame *);
1565
1566         if ( (id = iwi_find_station( sc, wh->i_addr1 ) ) == 0xff )
1567                 id = iwi_cache_station( sc, wh->i_addr1 );
1568
1569         bzero( desc, sizeof (struct iwi_tx_desc) );
1570         desc->station_number = id;
1571
1572         /* trim IEEE802.11 header */
1573         m_adj(m0, sizeof (struct ieee80211_frame));
1574
1575         error = bus_dmamap_load_mbuf(sc->tx_buf_dmat, buf->map, m0,
1576             iwi_dma_map_buf, &map, BUS_DMA_NOWAIT);
1577         if (error != 0 && error != EFBIG) {
1578                 device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1579                     error);
1580                 m_freem(m0);
1581                 return error;
1582         }
1583         if (error != 0) {
1584                 mnew = m_defrag(m0, MB_DONTWAIT);
1585                 if (mnew == NULL) {
1586                         device_printf(sc->sc_dev,
1587                             "could not defragment mbuf\n");
1588                         m_freem(m0);
1589                         return ENOBUFS;
1590                 }
1591                 m0 = mnew;
1592
1593                 error = bus_dmamap_load_mbuf(sc->tx_buf_dmat, buf->map, m0,
1594                     iwi_dma_map_buf, &map, BUS_DMA_NOWAIT);
1595                 if (error != 0) {
1596                         device_printf(sc->sc_dev,
1597                             "could not map mbuf (error %d)\n", error);
1598                         m_freem(m0);
1599                         return error;
1600                 }
1601         }
1602
1603         buf->m = m0;
1604         buf->ni = ni;
1605
1606         desc->hdr.type = IWI_HDR_TYPE_DATA;
1607         desc->hdr.flags = IWI_HDR_FLAG_IRQ;
1608         desc->cmd = IWI_DATA_CMD_TX;
1609         desc->len = htole16(m0->m_pkthdr.len);
1610         desc->flags = 0;
1611         if (ic->ic_opmode == IEEE80211_M_IBSS) {
1612                 if (!IEEE80211_IS_MULTICAST(wh->i_addr1))
1613                         desc->flags |= IWI_DATA_FLAG_NEED_ACK;
1614         } else if (!IEEE80211_IS_MULTICAST(wh->i_addr3))
1615                 desc->flags |= IWI_DATA_FLAG_NEED_ACK;
1616
1617         if (ic->ic_flags & IEEE80211_F_WEPON) {
1618                 wh->i_fc[1] |= IEEE80211_FC1_WEP;
1619                 desc->wep_txkey = ic->ic_wep_txkey;
1620         } else
1621                 desc->flags |= IWI_DATA_FLAG_NO_WEP;
1622
1623         if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
1624                 desc->flags |= IWI_DATA_FLAG_SHPREAMBLE;
1625
1626         bcopy(wh, &desc->wh, sizeof (struct ieee80211_frame));
1627         desc->nseg = htole32(map.nseg);
1628         for (i = 0; i < map.nseg; i++) {
1629                 desc->seg_addr[i] = htole32(map.segs[i].ds_addr);
1630                 desc->seg_len[i]  = htole32(map.segs[i].ds_len);
1631         }
1632
1633         bus_dmamap_sync(sc->tx_buf_dmat, buf->map, BUS_DMASYNC_PREWRITE);
1634         bus_dmamap_sync(sc->tx_ring_dmat, sc->tx_ring_map,
1635             BUS_DMASYNC_PREWRITE);
1636
1637         DPRINTFN(5, ("TX!DATA!%u!%u\n", desc->len, desc->nseg));
1638
1639         /* Inform firmware about this new packet */
1640         sc->tx_queued++;
1641         sc->tx_cur = (sc->tx_cur + 1) % IWI_TX_RING_SIZE;
1642         CSR_WRITE_4(sc, IWI_CSR_TX1_WRITE_INDEX, sc->tx_cur);
1643
1644         return 0;
1645 }
1646
1647 static void
1648 iwi_start(struct ifnet *ifp)
1649 {
1650         struct iwi_softc *sc = ifp->if_softc;
1651         struct ieee80211com *ic = &sc->sc_ic;
1652         struct mbuf *m0;
1653         struct ieee80211_node *ni;
1654
1655         if (ic->ic_state != IEEE80211_S_RUN) {
1656                 return;
1657         }
1658
1659         for (;;) {
1660                 m0 = ifq_poll(&ifp->if_snd);
1661                 if (m0 == NULL)
1662                         break;
1663
1664                 if (sc->tx_queued >= IWI_TX_RING_SIZE - 4) {
1665                         ifp->if_flags |= IFF_OACTIVE;
1666                         break;
1667                 }
1668  
1669                 ifq_dequeue(&ifp->if_snd, m0);
1670
1671                 BPF_MTAP(ifp, m0);
1672
1673                 m0 = ieee80211_encap(ifp, m0, &ni);
1674                 if (m0 == NULL)
1675                         continue;
1676
1677                 if (ic->ic_rawbpf != NULL)
1678                         bpf_mtap(ic->ic_rawbpf, m0);
1679
1680                 if (iwi_tx_start(ifp, m0, ni) != 0) {
1681                         if (ni != NULL && ni != ic->ic_bss)
1682                                 ieee80211_free_node(ic, ni);
1683                         break;
1684                 }
1685
1686                 /* start watchdog timer */
1687                 sc->sc_tx_timer = 5;
1688                 ifp->if_timer = 1;
1689         }
1690
1691 }
1692
1693 static void
1694 iwi_watchdog(struct ifnet *ifp)
1695 {
1696         struct iwi_softc *sc = ifp->if_softc;
1697
1698         ifp->if_timer = 0;
1699
1700         if (sc->sc_tx_timer > 0) {
1701                 if (--sc->sc_tx_timer == 0) {
1702                         if_printf(ifp, "device timeout\n");
1703                         wakeup(IWI_FW_WAKE_MONITOR(sc));
1704                         return;
1705                 }
1706                 ifp->if_timer = 1;
1707         }
1708
1709         ieee80211_watchdog(ifp);
1710 }
1711
1712
1713 static int
1714 iwi_wi_ioctl_get(struct ifnet *ifp, caddr_t data)
1715 {
1716         struct wi_req           wreq;
1717         struct ifreq            *ifr;
1718         struct iwi_softc        *sc;
1719         int                     error;
1720
1721         sc = ifp->if_softc;
1722         ifr = (struct ifreq *)data;
1723         error = copyin(ifr->ifr_data, &wreq, sizeof(wreq));
1724         if (error)
1725                 return (error);
1726
1727         switch (wreq.wi_type) {
1728         case WI_RID_READ_APS:
1729                 ieee80211_begin_scan(ifp);
1730
1731                 crit_enter();
1732                 tsleep_interlock(IWI_FW_SCAN_COMPLETED(sc));
1733                 lwkt_serialize_exit(ifp->if_serializer);
1734                 tsleep(IWI_FW_SCAN_COMPLETED(sc), PCATCH, "ssidscan", hz * 2);
1735                 crit_exit();
1736                 lwkt_serialize_enter(ifp->if_serializer);
1737
1738                 ieee80211_end_scan(ifp);
1739                 break;
1740         default:
1741                 error = ENOTTY;
1742                 break;
1743         }
1744         return (error);
1745 }
1746
1747
1748
1749
1750 static int
1751 iwi_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data, struct ucred *cr)
1752 {
1753         struct iwi_softc *sc = ifp->if_softc;
1754         struct ifreq *ifr;
1755         struct ieee80211req *ireq;
1756         struct ifaddr *ifa;
1757         int error = 0;
1758
1759         switch (cmd) {
1760        case SIOCSIFADDR:
1761                 /*
1762                  * Handle this here instead of in net80211_ioctl.c
1763                  * so that we can lock the call to iwi_init().
1764                  */
1765                 ifa = (struct ifaddr *) data;
1766                 switch (ifa->ifa_addr->sa_family) {
1767 #ifdef INET
1768                 case AF_INET:
1769                         if ((ifp->if_flags & IFF_UP) == 0) {
1770                                 ifp->if_flags |= IFF_UP;
1771                                 ifp->if_init(ifp->if_softc);
1772                         }
1773                         arp_ifinit(ifp, ifa);
1774                         break;
1775 #endif
1776 #ifdef IPX
1777 #warning "IPX support has not been tested"
1778                 /*
1779                  * XXX - This code is probably wrong,
1780                  *       but has been copied many times.
1781                  */
1782                 case AF_IPX: {
1783                         struct ipx_addr *ina = &(IA_SIPX(ifa)->sipx_addr);
1784                         struct arpcom *ac = (struct arpcom *)ifp;
1785
1786                         if (ipx_nullhost(*ina))
1787                                 ina->x_host = *(union ipx_host *) ac->ac_enaddr;
1788                         else
1789                                 bcopy((caddr_t) ina->x_host.c_host,
1790                                       (caddr_t) ac->ac_enaddr,
1791                                       sizeof(ac->ac_enaddr));
1792                         /* fall thru... */
1793                 }
1794 #endif
1795                 default:
1796                         if ((ifp->if_flags & IFF_UP) == 0) {
1797                                 ifp->if_flags |= IFF_UP;
1798                                 ifp->if_init(ifp->if_softc);
1799                         }
1800                         break;
1801                 }
1802                 break;
1803
1804         case SIOCSIFFLAGS:
1805                 if (ifp->if_flags & IFF_UP) {
1806                         if (!(ifp->if_flags & IFF_RUNNING)) {
1807                                 iwi_init(sc);
1808                                 error = tsleep(IWI_FW_CMD_ACKED(sc), 0,
1809                                                  "iwirun", hz);
1810                         }
1811                 } else {
1812                         if (ifp->if_flags & IFF_RUNNING) {
1813                                 iwi_stop(sc);
1814                         }
1815                 }
1816                 break;
1817
1818         case SIOCSLOADFW:
1819         case SIOCSLOADIBSSFW:
1820                 /* only super-user can do that! */
1821                 if ((error = suser(curthread)) != 0)
1822                         break;
1823
1824                 ifr = (struct ifreq *)data;
1825                 error = iwi_cache_firmware(sc, ifr->ifr_data,
1826                                 (cmd == SIOCSLOADIBSSFW) ? 1 : 0);
1827                 break;
1828
1829         case SIOCSKILLFW:
1830                 /* only super-user can do that! */
1831                 if ((error = suser(curthread)) != 0)
1832                         break;
1833
1834                 ifp->if_flags &= ~IFF_UP;
1835                 iwi_stop(sc);
1836                 iwi_free_firmware(sc);
1837                 break;
1838
1839         case SIOCG80211:
1840                 ireq = (struct ieee80211req *)data;
1841                 switch (ireq->i_type) {
1842                 case IEEE80211_IOC_AUTHMODE:
1843                         ireq->i_val = sc->authmode;
1844                         break;
1845
1846                 default:
1847                         error = ieee80211_ioctl(ifp, cmd, data, cr);
1848                 }
1849                 break;
1850
1851         case SIOCS80211:
1852                 /* only super-user can do that! */
1853                 if ((error = suser(curthread)) != 0)
1854                         break;
1855
1856                 ireq = (struct ieee80211req *)data;
1857                 switch (ireq->i_type) {
1858                 case IEEE80211_IOC_AUTHMODE:
1859                         sc->authmode = ireq->i_val;
1860                         break;
1861
1862                 default:
1863                         error = ieee80211_ioctl(ifp, cmd, data, cr);
1864                 }
1865                 break;
1866         case SIOCGIFGENERIC:
1867                 if (sc->flags & IWI_FLAG_FW_INITED) {
1868                         error = iwi_wi_ioctl_get(ifp, data);
1869                         if (! error)
1870                                 error = ieee80211_ioctl(ifp, cmd, data, cr);
1871                 } else
1872                         error = ENOTTY;
1873                 if (error != ENOTTY)
1874                         break;
1875
1876         default:
1877                 error = ieee80211_ioctl(ifp, cmd, data, cr);
1878         }
1879
1880         if (error == ENETRESET) {
1881                 error = 0;
1882                 if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
1883                     (IFF_UP | IFF_RUNNING)) {
1884                         iwi_init(sc);
1885                         error = tsleep(IWI_FW_CMD_ACKED(sc), 0, "iwirun", hz);
1886                 }
1887         }
1888         return error;
1889 }
1890
1891 static int
1892 iwi_abort_scan( struct iwi_softc *sc  )
1893 {
1894         sc->flags |= IWI_FLAG_SCAN_ABORT;
1895         return iwi_cmd(sc, IWI_CMD_SCAN_ABORT, NULL, 0, 1);
1896 }
1897
1898 static void
1899 iwi_stop_master(struct iwi_softc *sc)
1900 {
1901         int ntries;
1902
1903         /*
1904          * If the master is busy scanning, we will occasionally 
1905          * timeout waiting for it (the master) to stop. Make the
1906          * 'stopping' process more robust by ceasing all scans
1907          * prior to asking for the stop.
1908          */
1909         if ( ( sc->flags & IWI_FLAG_SCANNING ) && 
1910              !( sc->flags & IWI_FLAG_RF_DISABLED ) ) {
1911                 struct ifnet *ifp = &sc->sc_ic.ic_if;
1912
1913                 ASSERT_SERIALIZED(ifp->if_serializer);
1914
1915                 iwi_abort_scan(sc);
1916                 if (( sc->flags & IWI_FLAG_SCAN_ABORT ) && 
1917                     !( sc->flags & IWI_FLAG_RF_DISABLED )) {
1918                         crit_enter();
1919                         tsleep_interlock(IWI_FW_SCAN_COMPLETED(sc));
1920                         lwkt_serialize_exit(ifp->if_serializer);
1921                         tsleep(IWI_FW_SCAN_COMPLETED(sc), 0, "iwiabr", hz);
1922                         crit_exit();
1923                         lwkt_serialize_enter(ifp->if_serializer);
1924                 }
1925         }
1926         /* Disable interrupts */
1927
1928         CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, 0);
1929
1930         CSR_WRITE_4(sc, IWI_CSR_RST, IWI_RST_STOP_MASTER);
1931         for (ntries = 0; ntries < 5; ntries++) {
1932                 if (CSR_READ_4(sc, IWI_CSR_RST) & IWI_RST_MASTER_DISABLED)
1933                         break;
1934                 DELAY(10);
1935         }
1936         if (ntries == 5 && sc->debug_level > 0) 
1937                 device_printf(sc->sc_dev, "timeout waiting for master\n");
1938
1939         CSR_WRITE_4(sc, IWI_CSR_RST, CSR_READ_4(sc, IWI_CSR_RST) |
1940             IWI_RST_PRINCETON_RESET);
1941
1942         sc->flags &= ~IWI_FLAG_FW_INITED;
1943 }
1944
1945 static int
1946 iwi_reset(struct iwi_softc *sc)
1947 {
1948         int i, ntries;
1949
1950         iwi_stop_master(sc);
1951
1952         /* Move adapter to D0 state */
1953         CSR_WRITE_4(sc, IWI_CSR_CTL, CSR_READ_4(sc, IWI_CSR_CTL) |
1954             IWI_CTL_INIT);
1955
1956         /* Initialize Phase-Locked Level  (PLL) */
1957         CSR_WRITE_4(sc, IWI_CSR_READ_INT, IWI_READ_INT_INIT_HOST);
1958
1959         /* Wait for clock stabilization */
1960         for (ntries = 0; ntries < 1000; ntries++) {
1961                 if (CSR_READ_4(sc, IWI_CSR_CTL) & IWI_CTL_CLOCK_READY)
1962                         break;
1963                 DELAY(200);
1964         }
1965         if (ntries == 1000) {
1966                 return EIO;
1967         }
1968
1969         CSR_WRITE_4(sc, IWI_CSR_RST, CSR_READ_4(sc, IWI_CSR_RST) |
1970             IWI_RST_SW_RESET);
1971
1972         DELAY(10);
1973
1974         CSR_WRITE_4(sc, IWI_CSR_CTL, CSR_READ_4(sc, IWI_CSR_CTL) |
1975             IWI_CTL_INIT);
1976
1977
1978         /* Clear NIC memory */
1979         CSR_WRITE_4(sc, IWI_CSR_AUTOINC_ADDR, 0);
1980
1981         for (i = 0; i < 0xc000; i++) {
1982                 CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, 0);
1983         }
1984
1985         sc->num_stations = 0;
1986         return 0;
1987 }
1988
1989 static int
1990 iwi_load_ucode(struct iwi_softc *sc, void *uc, int size)
1991 {
1992         u_int16_t *w;
1993         int ntries, i;
1994
1995         CSR_WRITE_4(sc, IWI_CSR_RST, CSR_READ_4(sc, IWI_CSR_RST) |
1996             IWI_RST_STOP_MASTER);
1997         for (ntries = 0; ntries < 5; ntries++) {
1998                 if (CSR_READ_4(sc, IWI_CSR_RST) & IWI_RST_MASTER_DISABLED)
1999                         break;
2000                 DELAY(10);
2001         }
2002         if (ntries == 5) {
2003                 device_printf(sc->sc_dev, "timeout waiting for master\n");
2004                 return EIO;
2005         }
2006
2007         MEM_WRITE_4(sc, 0x3000e0, 0x80000000);
2008         DELAY(5000);
2009         CSR_WRITE_4(sc, IWI_CSR_RST, CSR_READ_4(sc, IWI_CSR_RST) &
2010             ~IWI_RST_PRINCETON_RESET);
2011         DELAY(5000);
2012         MEM_WRITE_4(sc, 0x3000e0, 0);
2013         DELAY(1000);
2014         MEM_WRITE_4(sc, 0x300004, 1);
2015         DELAY(1000);
2016         MEM_WRITE_4(sc, 0x300004, 0);
2017         DELAY(1000);
2018         MEM_WRITE_1(sc, 0x200000, 0x00);
2019         MEM_WRITE_1(sc, 0x200000, 0x40);
2020         DELAY(1000);
2021
2022         /* Adapter is buggy, we must set the address for each word */
2023         for (w = uc; size > 0; w++, size -= 2)
2024                 MEM_WRITE_2(sc, 0x200010, *w);
2025
2026         MEM_WRITE_1(sc, 0x200000, 0x00);
2027         MEM_WRITE_1(sc, 0x200000, 0x80);
2028
2029         /* Wait until we get a response in the uc queue */
2030         for (ntries = 0; ntries < 100; ntries++) {
2031                 if (MEM_READ_1(sc, 0x200000) & 1)
2032                         break;
2033                 DELAY(100);
2034         }
2035         if (ntries == 100) {
2036                 device_printf(sc->sc_dev,
2037                     "timeout waiting for ucode to initialize\n");
2038                 return EIO;
2039         }
2040
2041         /* Empty the uc queue or the firmware will not initialize properly */
2042         for (i = 0; i < 7; i++)
2043                 MEM_READ_4(sc, 0x200004);
2044
2045         MEM_WRITE_1(sc, 0x200000, 0x00);
2046
2047         return 0;
2048 }
2049
2050 /* macro to handle unaligned little endian data in firmware image */
2051 #define GETLE32(p) ((p)[0] | (p)[1] << 8 | (p)[2] << 16 | (p)[3] << 24)
2052 static int
2053 iwi_load_firmware(struct iwi_softc *sc, void *fw, int size)
2054 {
2055         bus_dma_tag_t dmat;
2056         bus_dmamap_t map;
2057         bus_addr_t physaddr;
2058         void *virtaddr;
2059         u_char *p, *end;
2060         u_int32_t sentinel, ctl, src, dst, sum, len, mlen;
2061         int ntries, error = 0;
2062         struct ifnet *ifp = &sc->sc_ic.ic_if;
2063
2064         sc->flags &= ~(IWI_FLAG_FW_INITED);
2065
2066         /* Allocate DMA memory for storing firmware image */
2067         error = bus_dma_tag_create(sc->iwi_parent_tag, 1, 0, BUS_SPACE_MAXADDR_32BIT,
2068             BUS_SPACE_MAXADDR, NULL, NULL, size, 1, size, BUS_DMA_ALLOCNOW, &dmat);
2069         if (error != 0) {
2070                 device_printf(sc->sc_dev,
2071                     "could not create firmware DMA tag\n");
2072                 goto fail1;
2073         }
2074
2075         /*
2076          * We cannot map fw directly because of some hardware constraints on
2077          * the mapping address.
2078          */
2079         error = bus_dmamem_alloc(dmat, &virtaddr, BUS_DMA_WAITOK, &map);
2080         if (error != 0) {
2081                 device_printf(sc->sc_dev,
2082                     "could not allocate firmware DMA memory\n");
2083                 goto fail2;
2084         }
2085
2086         error = bus_dmamap_load(dmat, map, virtaddr, size, iwi_dma_map_addr,
2087             &physaddr, 0);
2088         if (error != 0) {
2089                 device_printf(sc->sc_dev, "could not load firmware DMA map\n");
2090                 goto fail3;
2091         }
2092
2093         /* Copy firmware image to DMA memory */
2094         bcopy(fw, virtaddr, size);
2095
2096         /* Make sure the adapter will get up-to-date values */
2097         bus_dmamap_sync(dmat, map, BUS_DMASYNC_PREWRITE);
2098
2099         /* Tell the adapter where the command blocks are stored */
2100         MEM_WRITE_4(sc, 0x3000a0, 0x27000);
2101
2102         /*
2103          * Store command blocks into adapter's internal memory using register
2104          * indirections. The adapter will read the firmware image through DMA
2105          * using information stored in command blocks.
2106          */
2107         src = physaddr;
2108         p = virtaddr;
2109         end = p + size;
2110         CSR_WRITE_4(sc, IWI_CSR_AUTOINC_ADDR, 0x27000);
2111
2112         while (p < end) {
2113                 dst = GETLE32(p); p += 4; src += 4;
2114                 len = GETLE32(p); p += 4; src += 4;
2115                 p += len;
2116
2117                 while (len > 0) {
2118                         mlen = min(len, IWI_CB_MAXDATALEN);
2119
2120                         ctl = IWI_CB_DEFAULT_CTL | mlen;
2121                         sum = ctl ^ src ^ dst;
2122
2123                         /* Write a command block */
2124                         CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, ctl);
2125                         CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, src);
2126                         CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, dst);
2127                         CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, sum);
2128
2129                         src += mlen;
2130                         dst += mlen;
2131                         len -= mlen;
2132                 }
2133         }
2134
2135         /* Write a fictive final command block (sentinel) */
2136         sentinel = CSR_READ_4(sc, IWI_CSR_AUTOINC_ADDR);
2137         CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, 0);
2138
2139         CSR_WRITE_4(sc, IWI_CSR_RST, CSR_READ_4(sc, IWI_CSR_RST) &
2140             ~(IWI_RST_MASTER_DISABLED | IWI_RST_STOP_MASTER));
2141
2142         /* Tell the adapter to start processing command blocks */
2143         MEM_WRITE_4(sc, 0x3000a4, 0x540100);
2144
2145         /* Wait until the adapter has processed all command blocks */
2146         for (ntries = 0; ntries < 400; ntries++) {
2147                 if (MEM_READ_4(sc, 0x3000d0) >= sentinel)
2148                         break;
2149                 DELAY(100);
2150         }
2151         if (ntries == 400) {
2152                 device_printf(sc->sc_dev,
2153                     "timeout processing command blocks\n");
2154                 error = EIO;
2155                 goto fail4;
2156         }
2157
2158
2159         /* We're done with command blocks processing */
2160         MEM_WRITE_4(sc, 0x3000a4, 0x540c00);
2161
2162         /* Allow interrupts so we know when the firmware is inited */
2163         CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, IWI_INTR_MASK);
2164
2165         /* Tell the adapter to initialize the firmware */
2166         crit_enter();
2167         CSR_WRITE_4(sc, IWI_CSR_RST, 0);
2168         CSR_WRITE_4(sc, IWI_CSR_CTL,
2169                     CSR_READ_4(sc, IWI_CSR_CTL) | IWI_CTL_ALLOW_STANDBY);
2170
2171         tsleep_interlock(IWI_FW_INITIALIZED(sc));
2172         lwkt_serialize_exit(ifp->if_serializer);
2173         error = tsleep(IWI_FW_INITIALIZED(sc), 0, "iwiini", hz);
2174         crit_exit();
2175         lwkt_serialize_enter(ifp->if_serializer);
2176         if (error != 0) {
2177                 device_printf(sc->sc_dev, "timeout waiting for firmware "
2178                     "initialization to complete\n");
2179                 goto fail4;
2180         }
2181
2182 fail4:  bus_dmamap_sync(dmat, map, BUS_DMASYNC_POSTWRITE);
2183         bus_dmamap_unload(dmat, map);
2184 fail3:  bus_dmamem_free(dmat, virtaddr, map);
2185 fail2:  bus_dma_tag_destroy(dmat);
2186 fail1:
2187         return error;
2188 }
2189
2190 /*
2191  * Store firmware into kernel memory so we can download it when we need to,
2192  * e.g when the adapter wakes up from suspend mode.
2193  */
2194 static int
2195 iwi_cache_firmware(struct iwi_softc *sc, void *data, int is_ibss)
2196 {
2197         struct iwi_firmware *kfw = &sc->fw;
2198         struct iwi_firmware ufw;
2199         int error;
2200
2201         iwi_free_firmware(sc);
2202
2203         /*
2204          * mutex(9): no mutexes should be held across functions which access
2205          * memory in userspace, such as copyin(9) [...]
2206          */
2207
2208         if ((error = copyin(data, &ufw, sizeof ufw)) != 0)
2209                 goto fail1;
2210
2211         kfw->boot_size  = ufw.boot_size;
2212         kfw->ucode_size = ufw.ucode_size;
2213         kfw->main_size  = ufw.main_size;
2214
2215         kfw->boot = malloc(kfw->boot_size, M_DEVBUF, M_WAITOK);
2216         if (kfw->boot == NULL) {
2217                 error = ENOMEM;
2218                 goto fail1;
2219         }
2220
2221         kfw->ucode = malloc(kfw->ucode_size, M_DEVBUF, M_WAITOK);
2222         if (kfw->ucode == NULL) {
2223                 error = ENOMEM;
2224                 goto fail2;
2225         }
2226
2227         kfw->main = malloc(kfw->main_size, M_DEVBUF, M_WAITOK);
2228         if (kfw->main == NULL) {
2229                 error = ENOMEM;
2230                 goto fail3;
2231         }
2232
2233         if ((error = copyin(ufw.boot, kfw->boot, kfw->boot_size)) != 0)
2234                 goto fail4;
2235
2236         if ((error = copyin(ufw.ucode, kfw->ucode, kfw->ucode_size)) != 0)
2237                 goto fail4;
2238
2239         if ((error = copyin(ufw.main, kfw->main, kfw->main_size)) != 0)
2240                 goto fail4;
2241
2242         DPRINTF(("Firmware cached: boot %u, ucode %u, main %u\n",
2243             kfw->boot_size, kfw->ucode_size, kfw->main_size));
2244
2245
2246         sc->flags |= IWI_FLAG_FW_CACHED;
2247         sc->flags |= is_ibss ? IWI_FLAG_FW_IBSS : 0;
2248         return 0;
2249
2250 fail4:  free(kfw->boot, M_DEVBUF);
2251 fail3:  free(kfw->ucode, M_DEVBUF);
2252 fail2:  free(kfw->main, M_DEVBUF);
2253 fail1:
2254
2255         return error;
2256 }
2257
2258 static void
2259 iwi_free_firmware(struct iwi_softc *sc)
2260 {
2261         if (!(sc->flags & IWI_FLAG_FW_CACHED))
2262                 return;
2263
2264         free(sc->fw.boot, M_DEVBUF);
2265         free(sc->fw.ucode, M_DEVBUF);
2266         free(sc->fw.main, M_DEVBUF);
2267
2268         sc->flags &= ~( IWI_FLAG_FW_CACHED | IWI_FLAG_FW_IBSS );
2269 }
2270
2271 static int
2272 iwi_adapter_config(struct iwi_softc *sc, int is_a, int cmd_wait)
2273 {
2274         struct iwi_configuration config;
2275
2276         bzero(&config, sizeof config);
2277         config.enable_multicast = 1;
2278         config.noise_reported = 1;
2279
2280         config.bg_autodetect = 
2281                 ( !(is_a) &&
2282                   ( sc->enable_bg_autodetect != 0 ) ) ? 1 : 0;  /* default: on  */
2283
2284         config.bluetooth_coexistence =
2285                 ( sc->enable_bt_coexist != 0 ) ? 1 : 0;         /* default: on  */
2286
2287         config.enable_cts_to_self =
2288                 ( sc->enable_cts_to_self > 0 ) ? 1 : 0;         /* default: off */
2289
2290         if (sc->antenna_diversity > 0 ) {                       /* default: BOTH */
2291                 switch( sc->antenna_diversity ) {
2292                         case 1: case 3:
2293                                 config.antenna_diversity = sc->antenna_diversity;
2294                 }
2295         }
2296
2297         config.disable_unicast_decryption =
2298                 ( sc->disable_unicast_decryption != 0 ) ? 1 : 0; /* default: on */
2299
2300         config.disable_multicast_decryption =
2301                 ( sc->disable_multicast_decryption != 0 ) ? 1 : 0;/* default: on */
2302
2303
2304         if ( sc->debug_level > 0 ) {
2305                 printf("config.bluetooth_coexistence = %d\n",
2306                          config.bluetooth_coexistence );
2307                 printf("config.bg_autodetect = %d\n",
2308                          config.bg_autodetect );
2309                 printf("config.enable_cts_to_self = %d\n",
2310                          config.enable_cts_to_self );
2311                 printf("config.antenna_diversity = %d\n",
2312                          config.antenna_diversity );
2313                 printf("config.disable_unicast_decryption = %d\n",
2314                          config.disable_unicast_decryption );
2315                 printf("config.disable_multicast_decryption = %d\n",
2316                          config.disable_multicast_decryption );
2317                 printf("config.neg_best_rates_first = %d\n",
2318                          sc->enable_neg_best_first );
2319         }
2320
2321         return iwi_cmd(sc, IWI_CMD_SET_CONFIGURATION, &config,
2322                  sizeof config, cmd_wait );
2323 }
2324
2325 static int
2326 iwi_config(struct iwi_softc *sc)
2327 {
2328         struct ieee80211com *ic = &sc->sc_ic;
2329         struct ifnet *ifp = &ic->ic_if;
2330         struct iwi_rateset rs;
2331         struct iwi_txpower power;
2332         struct ieee80211_wepkey *k;
2333         struct iwi_wep_key wepkey;
2334         u_int32_t data;
2335         int error, i;
2336
2337         IEEE80211_ADDR_COPY(ic->ic_myaddr, IF_LLADDR(ifp));
2338         DPRINTF(("Setting MAC address to %6D\n", ic->ic_myaddr, ":"));
2339         error = iwi_cmd(sc, IWI_CMD_SET_MAC_ADDRESS, ic->ic_myaddr,
2340             IEEE80211_ADDR_LEN, 0);
2341         if (error != 0)
2342                 return error;
2343
2344         DPRINTF(("Configuring adapter\n"));
2345         if ((error = iwi_adapter_config(sc, 1, 0)) != 0)
2346                 return error;
2347
2348         data = htole32(IWI_POWER_MODE_CAM);
2349         DPRINTF(("Setting power mode to %u\n", le32toh(data)));
2350         error = iwi_cmd(sc, IWI_CMD_SET_POWER_MODE, &data, sizeof data, 0);
2351         if (error != 0)
2352                 return error;
2353
2354         data = htole32(ic->ic_rtsthreshold);
2355         DPRINTF(("Setting RTS threshold to %u\n", le32toh(data)));
2356         error = iwi_cmd(sc, IWI_CMD_SET_RTS_THRESHOLD, &data, sizeof data, 0);
2357         if (error != 0)
2358                 return error;
2359
2360         if (ic->ic_opmode == IEEE80211_M_IBSS) {
2361                 power.mode = IWI_MODE_11B;
2362                 power.nchan = 11;
2363                 for (i = 0; i < 11; i++) {
2364                         power.chan[i].chan = i + 1;
2365                         power.chan[i].power = IWI_TXPOWER_MAX;
2366                 }
2367                 DPRINTF(("Setting .11b channels tx power\n"));
2368                 error = iwi_cmd(sc, IWI_CMD_SET_TX_POWER, &power, sizeof power,
2369                     0);
2370                 if (error != 0)
2371                         return error;
2372
2373                 power.mode = IWI_MODE_11G;
2374                 DPRINTF(("Setting .11g channels tx power\n"));
2375                 error = iwi_cmd(sc, IWI_CMD_SET_TX_POWER, &power, sizeof power,
2376                     0);
2377                 if (error != 0)
2378                         return error;
2379         }
2380
2381         rs.mode = IWI_MODE_11G;
2382         rs.type = IWI_RATESET_TYPE_SUPPORTED;
2383         rs.nrates = ic->ic_sup_rates[IEEE80211_MODE_11G].rs_nrates;
2384         bcopy(ic->ic_sup_rates[IEEE80211_MODE_11G].rs_rates, rs.rates,
2385             rs.nrates);
2386         DPRINTF(("Setting .11bg supported rates (%u)\n", rs.nrates));
2387         error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs, 0);
2388         if (error != 0)
2389                 return error;
2390
2391         rs.mode = IWI_MODE_11A;
2392         rs.type = IWI_RATESET_TYPE_SUPPORTED;
2393         rs.nrates = ic->ic_sup_rates[IEEE80211_MODE_11A].rs_nrates;
2394         bcopy(ic->ic_sup_rates[IEEE80211_MODE_11A].rs_rates, rs.rates,
2395             rs.nrates);
2396         DPRINTF(("Setting .11a supported rates (%u)\n", rs.nrates));
2397         error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs, 0);
2398         if (error != 0)
2399                 return error;
2400
2401         data = htole32(arc4random());
2402         DPRINTF(("Setting initialization vector to %u\n", le32toh(data)));
2403         error = iwi_cmd(sc, IWI_CMD_SET_IV, &data, sizeof data, 0);
2404         if (error != 0)
2405                 return error;
2406
2407         if (ic->ic_flags & IEEE80211_F_WEPON) {
2408                 k = ic->ic_nw_keys;
2409                 for (i = 0; i < IEEE80211_WEP_NKID; i++, k++) {
2410                         wepkey.cmd = IWI_WEP_KEY_CMD_SETKEY;
2411                         wepkey.idx = i;
2412                         wepkey.len = k->wk_len;
2413                         bzero(wepkey.key, sizeof wepkey.key);
2414                         bcopy(k->wk_key, wepkey.key, k->wk_len);
2415                         DPRINTF(("Setting wep key index %u len %u\n",
2416                             wepkey.idx, wepkey.len));
2417                         error = iwi_cmd(sc, IWI_CMD_SET_WEP_KEY, &wepkey,
2418                             sizeof wepkey, 0);
2419                         if (error != 0)
2420                                 return error;
2421                 }
2422         }
2423
2424         /* Enable adapter */
2425         DPRINTF(("Enabling adapter\n"));
2426         return iwi_cmd(sc, IWI_CMD_ENABLE, NULL, 0, 0);
2427 }
2428
2429 static int
2430 iwi_scan(struct iwi_softc *sc)
2431 {
2432         struct ieee80211com *ic = &sc->sc_ic;
2433         struct iwi_scan scan;
2434         u_int8_t *p;
2435         int i, count;
2436         int do_5ghz_scan = 0;
2437
2438         sc->scan_counter++; /* track the number of scans started */
2439
2440         sc->flags |= IWI_FLAG_SCANNING;
2441
2442         bzero(&scan, sizeof scan);
2443
2444         /*
2445          * Alternate two broadcast scans with
2446          * two broadcast/direct scans.
2447          */
2448         if ( sc->scan_counter & 2 ) {
2449                 scan.type = IWI_SCAN_TYPE_BROADCAST_AND_DIRECT;
2450                 scan.intval = htole16(100);
2451         } else {
2452                 scan.type = IWI_SCAN_TYPE_BROADCAST;
2453                 scan.intval = htole16(40);
2454         }
2455
2456         p = scan.channels;
2457
2458         /*
2459          * If we have .11a capable adapter, and
2460          *      - we are in .11a mode, or
2461          *      - we are in auto mode and this is an odd numbered scan
2462          * then do a 5GHz scan, otherwise do a 2GHz scan.
2463          */
2464         if ( ic->ic_sup_rates[IEEE80211_MODE_11A].rs_nrates > 0 ) {
2465                 if (( ic->ic_curmode == IEEE80211_MODE_11A ) ||
2466                     (( ic->ic_curmode == IEEE80211_MODE_AUTO ) &&
2467                      ( sc->scan_counter & 1)))
2468                         do_5ghz_scan = 1;
2469         }
2470         count = 0;
2471         if ( do_5ghz_scan ) {
2472                 DPRINTF(("Scanning 5GHz band\n"));
2473                 for (i = 0; i <= IEEE80211_CHAN_MAX; i++) {
2474                         if (IEEE80211_IS_CHAN_5GHZ(&ic->ic_channels[i]) &&
2475                                         isset(ic->ic_chan_active, i)) {
2476                                 *++p = i;
2477                                 count++;
2478                         }
2479                 }
2480                 *(p - count) = IWI_CHAN_5GHZ | count;
2481         } else {
2482                 DPRINTF(("Scanning 2GHz band\n"));
2483                 for (i = 0; i <= IEEE80211_CHAN_MAX; i++) {
2484                         if (IEEE80211_IS_CHAN_2GHZ(&ic->ic_channels[i]) &&
2485                                         isset(ic->ic_chan_active, i)) {
2486                                 *++p = i;
2487                                 count++;
2488                         }
2489                 }
2490                 *(p - count) = IWI_CHAN_2GHZ | count;
2491         }
2492         return iwi_cmd(sc, IWI_CMD_SCAN, &scan, sizeof scan, 1);
2493 }
2494
2495 static int
2496 iwi_auth_and_assoc(struct iwi_softc *sc)
2497 {
2498         struct ieee80211com *ic = &sc->sc_ic;
2499         struct ifnet *ifp = &ic->ic_if;
2500         struct ieee80211_node *ni = ic->ic_bss;
2501         struct iwi_rateset rs;
2502         u_int32_t data;
2503         int error, x;
2504
2505         if ( ( sc->flags & IWI_FLAG_FW_IBSS ) &&
2506              !( ni->ni_capinfo & IEEE80211_CAPINFO_IBSS ) ) {
2507                 return -1; /* IBSS F/W requires network ibss capability */
2508         }
2509
2510         DPRINTF(("Configuring adapter\n"));
2511         if ((error = iwi_adapter_config(sc, 
2512                 IEEE80211_IS_CHAN_5GHZ(ni->ni_chan), 1)) != 0)
2513                         return error;
2514
2515 #ifdef IWI_DEBUG
2516         if (sc->debug_level > 0) {
2517                 printf("Setting ESSID to ");
2518                 ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
2519                 printf("\n");
2520         }
2521 #endif
2522         error = iwi_cmd(sc, IWI_CMD_SET_ESSID, ni->ni_essid, ni->ni_esslen, 1);
2523         if (error != 0)
2524                 return error;
2525
2526         /* the rate set has already been "negotiated" */
2527         rs.mode = IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) ? IWI_MODE_11A :
2528             IWI_MODE_11G;
2529         rs.type = IWI_RATESET_TYPE_NEGOTIATED;
2530         rs.nrates = ni->ni_rates.rs_nrates;
2531         if ( sc->enable_neg_best_first != 1 ) {
2532                 bcopy(ni->ni_rates.rs_rates, rs.rates, rs.nrates);
2533         } else {
2534                 for ( x = 0 ; x < rs.nrates; x++ ) {
2535                         /*
2536                          * Present the firmware with the most favourable
2537                          * of the negotiated rates first. 
2538                          */
2539                         rs.rates[rs.nrates-x-1] = ni->ni_rates.rs_rates[x];
2540                 }
2541         }
2542
2543         if ( sc->debug_level > 0 ) {
2544                 printf("Setting negotiated rates (%u) : ", rs.nrates);
2545                 for ( x = 0 ; x < rs.nrates; x++ ) {
2546                         printf("%d ", rs.rates[x]);
2547                 }
2548                 printf("\n");
2549         }
2550
2551         error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs, 1);
2552         if (error != 0)
2553                 return error;
2554
2555         data = htole32(ni->ni_rssi);
2556         DPRINTF(("Setting sensitivity to %d\n", (int8_t)ni->ni_rssi));
2557         error = iwi_cmd(sc, IWI_CMD_SET_SENSITIVITY, &data, sizeof data, 1);
2558         if (error != 0)
2559                 return error;
2560
2561         bzero(&sc->assoc, sizeof sc->assoc);
2562         sc->assoc.mode = IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) ? IWI_MODE_11A :
2563             IWI_MODE_11G;
2564         sc->assoc.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
2565         if (sc->authmode == IEEE80211_AUTH_SHARED)
2566                 sc->assoc.auth = (ic->ic_wep_txkey << 4) | IWI_AUTH_SHARED;
2567         bcopy(ni->ni_tstamp, sc->assoc.tstamp, 8);
2568         sc->assoc.capinfo = htole16(ni->ni_capinfo);
2569         sc->assoc.lintval = htole16(ic->ic_lintval);
2570         sc->assoc.intval = htole16(ni->ni_intval);
2571         IEEE80211_ADDR_COPY(sc->assoc.bssid, ni->ni_bssid);
2572         if ( ic->ic_opmode == IEEE80211_M_IBSS )
2573                 IEEE80211_ADDR_COPY(sc->assoc.dst, ifp->if_broadcastaddr);
2574         else
2575                 IEEE80211_ADDR_COPY(sc->assoc.dst, ni->ni_bssid);
2576
2577         DPRINTF(("Trying to associate to %6D channel %u auth %u\n",
2578             sc->assoc.bssid, ":", sc->assoc.chan, sc->assoc.auth));
2579         return iwi_cmd(sc, IWI_CMD_ASSOCIATE, &sc->assoc, sizeof sc->assoc, 1);
2580 }
2581
2582 static void
2583 iwi_init(void *priv)
2584 {
2585         struct iwi_softc *sc = priv;
2586         struct ieee80211com *ic = &sc->sc_ic;
2587         struct ifnet *ifp = &ic->ic_if;
2588         struct iwi_firmware *fw = &sc->fw;
2589         int i;
2590
2591         /* exit immediately if firmware has not been ioctl'd */
2592         if (!(sc->flags & IWI_FLAG_FW_CACHED)) {
2593                 ifp->if_flags &= ~IFF_UP;
2594                 return;
2595         }
2596
2597         iwi_stop(sc);
2598
2599         if (iwi_reset(sc) != 0) {
2600                 device_printf(sc->sc_dev, "could not reset adapter\n");
2601                 goto fail;
2602         }
2603
2604         if (iwi_load_firmware(sc, fw->boot, fw->boot_size) != 0) {
2605                 device_printf(sc->sc_dev, "could not load boot firmware\n");
2606                 goto fail;
2607         }
2608
2609         if (iwi_load_ucode(sc, fw->ucode, fw->ucode_size) != 0) {
2610                 device_printf(sc->sc_dev, "could not load microcode\n");
2611                 goto fail;
2612         }
2613
2614         iwi_stop_master(sc);
2615
2616         sc->tx_cur = 0;
2617         sc->tx_queued = 0;
2618         sc->tx_old = IWI_TX_RING_SIZE - 1;
2619         sc->cmd_cur = 0;
2620         sc->rx_cur = IWI_RX_RING_SIZE - 1;
2621
2622         CSR_WRITE_4(sc, IWI_CSR_CMD_BASE, sc->cmd_ring_pa);
2623         CSR_WRITE_4(sc, IWI_CSR_CMD_SIZE, IWI_CMD_RING_SIZE);
2624         CSR_WRITE_4(sc, IWI_CSR_CMD_READ_INDEX, 0);
2625         CSR_WRITE_4(sc, IWI_CSR_CMD_WRITE_INDEX, sc->cmd_cur);
2626
2627         CSR_WRITE_4(sc, IWI_CSR_TX1_BASE, sc->tx_ring_pa);
2628         CSR_WRITE_4(sc, IWI_CSR_TX1_SIZE, IWI_TX_RING_SIZE);
2629         CSR_WRITE_4(sc, IWI_CSR_TX1_READ_INDEX, 0);
2630         CSR_WRITE_4(sc, IWI_CSR_TX1_WRITE_INDEX, sc->tx_cur);
2631
2632         CSR_WRITE_4(sc, IWI_CSR_TX2_BASE, sc->tx_ring_pa);
2633         CSR_WRITE_4(sc, IWI_CSR_TX2_SIZE, IWI_TX_RING_SIZE);
2634         CSR_WRITE_4(sc, IWI_CSR_TX2_READ_INDEX, 0);
2635         CSR_WRITE_4(sc, IWI_CSR_TX2_WRITE_INDEX, 0);
2636
2637         CSR_WRITE_4(sc, IWI_CSR_TX3_BASE, sc->tx_ring_pa);
2638         CSR_WRITE_4(sc, IWI_CSR_TX3_SIZE, IWI_TX_RING_SIZE);
2639         CSR_WRITE_4(sc, IWI_CSR_TX3_READ_INDEX, 0);
2640         CSR_WRITE_4(sc, IWI_CSR_TX3_WRITE_INDEX, 0);
2641
2642         CSR_WRITE_4(sc, IWI_CSR_TX4_BASE, sc->tx_ring_pa);
2643         CSR_WRITE_4(sc, IWI_CSR_TX4_SIZE, IWI_TX_RING_SIZE);
2644         CSR_WRITE_4(sc, IWI_CSR_TX4_READ_INDEX, 0);
2645         CSR_WRITE_4(sc, IWI_CSR_TX4_WRITE_INDEX, 0);
2646
2647         for (i = 0; i < IWI_RX_RING_SIZE; i++)
2648                 CSR_WRITE_4(sc, IWI_CSR_RX_BASE + i * 4,
2649                     sc->rx_buf[i].physaddr);
2650
2651         /*
2652          * Kick Rx
2653          */
2654         CSR_WRITE_4(sc, IWI_CSR_RX_WRITE_INDEX, sc->rx_cur);
2655         CSR_WRITE_4(sc, IWI_CSR_RX_READ_INDEX, 0);
2656
2657         if (iwi_load_firmware(sc, fw->main, fw->main_size) != 0) {
2658                 device_printf(sc->sc_dev, "could not load main firmware\n");
2659                 goto fail;
2660         }
2661
2662         /*
2663          * Force the opmode based on what firmware is loaded. This
2664          * stops folks from killing the firmware by asking it to
2665          * do something it doesn't support.
2666          */
2667         if ( ic->ic_opmode != IEEE80211_M_MONITOR ) {
2668                 ic->ic_opmode = ( sc->flags & IWI_FLAG_FW_IBSS )
2669                         ? IEEE80211_M_IBSS : IEEE80211_M_STA;
2670         }
2671
2672         sc->flags |= IWI_FLAG_FW_INITED;
2673
2674         sc->flags &= ~( IWI_FLAG_SCANNING |
2675                         IWI_FLAG_SCAN_COMPLETE |
2676                         IWI_FLAG_SCAN_ABORT |
2677                         IWI_FLAG_ASSOCIATED );
2678
2679         if (iwi_config(sc) != 0) {
2680                 device_printf(sc->sc_dev, "device configuration failed\n");
2681                 goto fail;
2682         }
2683
2684         if ( ic->ic_opmode != IEEE80211_M_MONITOR ) {
2685                 ieee80211_begin_scan(ifp);
2686                 ifp->if_flags &= ~IFF_OACTIVE;
2687                 ifp->if_flags |= IFF_RUNNING;
2688         } else {
2689                 ieee80211_begin_scan(ifp);
2690                 ifp->if_flags &= ~IFF_OACTIVE;
2691                 ifp->if_flags |= IFF_RUNNING;
2692         }
2693
2694         return;
2695
2696 fail:   
2697         if ( !(sc->flags & IWI_FLAG_RESET) )
2698                 ifp->if_flags &= ~IFF_UP;
2699         iwi_stop(sc);
2700 }
2701
2702 static void
2703 iwi_stop(void *priv)
2704 {
2705         struct iwi_softc *sc = priv;
2706         struct ieee80211com *ic = &sc->sc_ic;
2707         struct ifnet *ifp = &ic->ic_if;
2708         struct iwi_tx_buf *buf;
2709         int i;
2710
2711         iwi_stop_master(sc);
2712         CSR_WRITE_4(sc, IWI_CSR_RST, IWI_RST_SW_RESET);
2713
2714         /*
2715          * Release Tx buffers
2716          */
2717         for (i = 0; i < IWI_TX_RING_SIZE; i++) {
2718                 buf = &sc->tx_buf[i];
2719
2720                 if (buf->m != NULL) {
2721                         bus_dmamap_sync(sc->tx_buf_dmat, buf->map,
2722                             BUS_DMASYNC_POSTWRITE);
2723                         bus_dmamap_unload(sc->tx_buf_dmat, buf->map);
2724                         m_freem(buf->m);
2725                         buf->m = NULL;
2726
2727                         if (buf->ni != NULL) {
2728                                 if (buf->ni != ic->ic_bss)
2729                                         ieee80211_free_node(ic, buf->ni);
2730                                 buf->ni = NULL;
2731                         }
2732                 }
2733         }
2734
2735         ifp->if_timer = 0;
2736         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2737
2738         ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
2739 }
2740
2741 static int8_t
2742 iwi_cache_station(struct iwi_softc *sc, u_int8_t *mac)
2743 {
2744         int i, x, base, elemsize = sizeof(struct iwi_fw_station);
2745         for (i = 0; i < sc->num_stations; i++)
2746                 if (!memcmp(sc->stations[i], mac, IEEE80211_ADDR_LEN))
2747                         break;
2748         if (i == IWI_FW_MAX_STATIONS)
2749                 return 0xff;
2750         memcpy(sc->stations[i], mac, IEEE80211_ADDR_LEN);
2751         for (x = 0, base = IWI_STATION_TABLE + (i * elemsize) ; 
2752              x < IEEE80211_ADDR_LEN ; x++ ) {
2753                 CSR_WRITE_1(sc, base + x, mac[x]);
2754         }
2755         if ( (i + 1) > sc->num_stations )
2756                 sc->num_stations++;
2757         return i;
2758 }
2759
2760 static u_int8_t
2761 iwi_find_station(struct iwi_softc *sc, u_int8_t *mac)
2762 {
2763         u_int8_t i;
2764         for (i = 0; i < sc->num_stations; i++)
2765                 if (!memcmp(sc->stations[i], mac, IEEE80211_ADDR_LEN))
2766                         return i;
2767         return 0xff;
2768 }
2769
2770 static const char *
2771 iwi_error_desc(u_int32_t val)
2772 {
2773         switch (val) {
2774         case IWI_FW_ERROR_OK:
2775                 return "OK";
2776         case IWI_FW_ERROR_FAIL:
2777                 return "FAIL";
2778         case IWI_FW_ERROR_MEMORY_UNDERFLOW:
2779                 return "MEMORY_UNDERFLOW";
2780         case IWI_FW_ERROR_MEMORY_OVERFLOW:
2781                 return "MEMORY_OVERFLOW";
2782         case IWI_FW_ERROR_BAD_PARAM:
2783                 return "BAD_PARAMETER";
2784         case IWI_FW_ERROR_BAD_CHECKSUM:
2785                 return "BAD_CHECKSUM";
2786         case IWI_FW_ERROR_NMI_INTERRUPT:
2787                 return "NMI_INTERRUPT";
2788         case IWI_FW_ERROR_BAD_DATABASE:
2789                 return "BAD_DATABASE";
2790         case IWI_FW_ERROR_ALLOC_FAIL:
2791                 return "ALLOC_FAIL";
2792         case IWI_FW_ERROR_DMA_UNDERRUN:
2793                 return "DMA_UNDERRUN";
2794         case IWI_FW_ERROR_DMA_STATUS:
2795                 return "DMA_STATUS";
2796         case IWI_FW_ERROR_DINOSTATUS_ERROR:
2797                 return "DINOSTATUS_ERROR";
2798         case IWI_FW_ERROR_EEPROMSTATUS_ERROR:
2799                 return "EEPROMSTATUS_ERROR";
2800         case IWI_FW_ERROR_SYSASSERT:
2801                 return "SYSASSERT";
2802         case IWI_FW_ERROR_FATAL_ERROR:
2803                 return "FATAL";
2804         default:
2805                 return "UNKNOWN_ERROR";
2806         }
2807 }
2808
2809 static void
2810 iwi_dump_fw_event_log(struct iwi_softc *sc)
2811 {
2812         u_int32_t ev, time, data, i, count, base;
2813         base = CSR_READ_4(sc, IWI_FW_EVENT_LOG);
2814         count = MEM_READ_4(sc, base);
2815         if ( count > 0 && (sc->flags & IWI_FLAG_FW_INITED) ) {
2816                 printf("Reading %d event log entries from base address 0x%x.\n",
2817                         count,  base);
2818                 if (IWI_FW_EVENT_START_OFFSET <= count * IWI_FW_EVENT_ELEM_SIZE)
2819                         device_printf(sc->sc_dev,"Start IWI Event Log Dump:\n");
2820                 for (i = IWI_FW_EVENT_START_OFFSET;
2821                                 i <= count * IWI_FW_EVENT_ELEM_SIZE;
2822                                 i += IWI_FW_EVENT_ELEM_SIZE) {
2823                         ev = MEM_READ_4(sc, base + i);
2824                         time  = MEM_READ_4(sc, base + i + 1 * sizeof(u_int32_t));
2825                         data  = MEM_READ_4(sc, base + i + 2 * sizeof(u_int32_t));
2826                         printf("%d %8p %8.8d\n", time, (void *) data, ev);
2827                 }
2828         } else {
2829                 printf("There are no entries in the firmware event log.\n");
2830         }
2831 }
2832
2833 static void
2834 iwi_dump_fw_error_log(struct iwi_softc *sc)
2835 {
2836         u_int32_t i = 0;
2837         int32_t count, base;
2838         base = CSR_READ_4(sc, IWI_FW_ERROR_LOG);
2839         count = MEM_READ_4(sc, base);
2840         if ( count > 0 && (sc->flags & IWI_FLAG_FW_INITED) ) {
2841                 printf("Reading %d error log entries "
2842                     "from base address 0x%p.\n", count,  (void *)base);
2843                 for ( i = IWI_FW_ERROR_START_OFFSET; 
2844                         i <= count * IWI_FW_EVENT_ELEM_SIZE;
2845                         i += IWI_FW_ERROR_ELEM_SIZE ) {
2846                         u_int32_t elems;
2847                         printf("%15.15s",
2848                             iwi_error_desc(MEM_READ_4(sc, base + i)));
2849                         printf(" time(%8.8d)", MEM_READ_4(sc, base + i + 4));
2850                         for ( elems = 2 ; elems < 7 ; elems++ ) {
2851                                 printf(" %8p", (void *)
2852                                     MEM_READ_4(sc, base + i + (4 * elems)));
2853                         }
2854                         printf("\n");
2855                 }
2856         } 
2857 }
2858
2859 static int
2860 iwi_sysctl_cts_to_self(SYSCTL_HANDLER_ARGS)
2861 {
2862         struct iwi_softc *sc = (void *)arg1;
2863         int cts_to_self = sc->enable_cts_to_self;
2864         int error = sysctl_handle_int(oidp, &cts_to_self, 0, req);
2865
2866         (void)arg2; /* silence WARNS == 6 */
2867
2868         if ( !error && req->newptr && cts_to_self != sc->enable_cts_to_self ) {
2869                 switch ( cts_to_self ) {
2870                         case -1: case 0: case 1:
2871                                 sc->enable_cts_to_self = cts_to_self;
2872                                 error = iwi_adapter_config(sc, 0, 0);
2873                         break;
2874                 }
2875         }
2876         return error;
2877 }
2878
2879
2880 static int
2881 iwi_sysctl_antenna_diversity(SYSCTL_HANDLER_ARGS)
2882 {
2883         struct iwi_softc *sc = (void *)arg1;
2884         int antenna_diversity = sc->antenna_diversity;
2885         int error = sysctl_handle_int(oidp, &antenna_diversity, 0, req);
2886
2887         (void)arg2; /* silence WARNS == 6 */
2888
2889         if ( !error && req->newptr && antenna_diversity != sc->antenna_diversity ) {
2890                 switch ( antenna_diversity ) {
2891                         case 1: case 3: case 0: case -1:
2892                                 sc->antenna_diversity = antenna_diversity;
2893                                 error = iwi_adapter_config(sc, 0, 0);
2894                         break;
2895                 }
2896         }
2897         return error;
2898 }
2899
2900 static int
2901 iwi_sysctl_bg_autodetect(SYSCTL_HANDLER_ARGS)
2902 {
2903         struct iwi_softc *sc = (void *)arg1;
2904         int bg_autodetect = sc->enable_bg_autodetect;
2905         int error = sysctl_handle_int(oidp, &bg_autodetect, 0, req);
2906
2907         (void)arg2; /* silence WARNS == 6 */
2908
2909         if ( !error && req->newptr && bg_autodetect != sc->enable_bg_autodetect ) {
2910                 switch ( bg_autodetect ) {
2911                         case 1: case 0: case -1:
2912                                 sc->enable_bg_autodetect = bg_autodetect;
2913                                 error = iwi_adapter_config(sc, 0, 0);
2914                         break;
2915                 }
2916         }
2917         return error;
2918 }
2919
2920 static int
2921 iwi_sysctl_bt_coexist(SYSCTL_HANDLER_ARGS)
2922 {
2923         struct iwi_softc *sc = (void *)arg1;
2924         int bt_coexist = sc->enable_bt_coexist;
2925         int error = sysctl_handle_int(oidp, &bt_coexist, 0, req);
2926
2927         (void)arg2; /* silence WARNS == 6 */
2928
2929         if ( !error && req->newptr && bt_coexist != sc->enable_bt_coexist ) {
2930                 switch ( bt_coexist ) {
2931                         case 1: case 0: case -1:
2932                                 sc->enable_bt_coexist = bt_coexist;
2933                                 error = iwi_adapter_config(sc, 0, 0);
2934                         break;
2935                 }
2936         }
2937         return error;
2938 }
2939
2940 static int
2941 iwi_sysctl_dump_logs(SYSCTL_HANDLER_ARGS)
2942 {
2943         struct iwi_softc *sc = arg1;
2944         int result = -1;
2945         int error = sysctl_handle_int(oidp, &result, 0, req);
2946
2947         (void)arg2; /* silence WARNS == 6 */
2948
2949         if (!error && req->newptr && result == 1) {
2950                 iwi_dump_fw_event_log(sc);
2951                 iwi_dump_fw_error_log(sc);
2952         }
2953         return error;
2954 }
2955
2956 static int
2957 iwi_sysctl_stats(SYSCTL_HANDLER_ARGS)
2958 {
2959         struct iwi_softc *sc = arg1;
2960         u_int32_t size;
2961         struct iwi_dump_buffer dump;
2962
2963         (void)arg2; /* silence WARNS == 6 */
2964         (void)oidp; /* silence WARNS == 6 */
2965
2966         if (!(sc->flags & IWI_FLAG_FW_INITED)) {
2967                 bzero(dump.buf, sizeof dump.buf);
2968                 return SYSCTL_OUT(req, &dump, sizeof dump);
2969         }
2970
2971         size = min(CSR_READ_4(sc, IWI_CSR_TABLE0_SIZE), 128 - 1);
2972         CSR_READ_REGION_4(sc, IWI_CSR_TABLE0_BASE, &dump.buf[1], size);
2973
2974         return SYSCTL_OUT(req, &dump, sizeof dump);
2975 }
2976
2977 static int
2978 iwi_sysctl_radio(SYSCTL_HANDLER_ARGS)
2979 {
2980         struct iwi_softc *sc = arg1;
2981         int val;
2982
2983         (void)arg2; /* silence WARNS == 6 */
2984         (void)oidp; /* silence WARNS == 6 */
2985
2986         val = (CSR_READ_4(sc, IWI_CSR_IO) & IWI_IO_RADIO_ENABLED) ? 1 : 0;
2987         return SYSCTL_OUT(req, &val, sizeof val);
2988 }
2989
2990 static int
2991 iwi_sysctl_neg_best_rates_first(SYSCTL_HANDLER_ARGS)
2992 {
2993         struct iwi_softc *sc = arg1;
2994         int best_first = sc->enable_neg_best_first;
2995         int error = sysctl_handle_int(oidp, &best_first, 0, req);
2996
2997         (void)arg2; /* silence WARNS == 6 */
2998         (void)oidp; /* silence WARNS == 6 */
2999
3000         if ( !error && req->newptr && best_first != sc->enable_neg_best_first ) {
3001                 switch ( best_first ) {
3002                         case 1: case 0: case -1:
3003                                 sc->enable_neg_best_first = best_first;
3004                         break;
3005                 }
3006         }
3007         return error;
3008 }
3009
3010 static int
3011 iwi_sysctl_disable_unicast_decryption(SYSCTL_HANDLER_ARGS)
3012 {
3013         struct iwi_softc *sc = arg1;
3014         int disable_uni = sc->disable_unicast_decryption;
3015         int error = sysctl_handle_int(oidp, &disable_uni, 0, req);
3016
3017         (void)arg2; /* silence WARNS == 6 */
3018         (void)oidp; /* silence WARNS == 6 */
3019
3020         if (!error && req->newptr && disable_uni != sc->disable_unicast_decryption) {
3021                 switch ( disable_uni ) {
3022                         case 1: case 0: case -1:
3023                                 sc->disable_unicast_decryption = disable_uni;
3024                         break;
3025                 }
3026         }
3027         return error;
3028 }
3029
3030 static int
3031 iwi_sysctl_disable_multicast_decryption(SYSCTL_HANDLER_ARGS)
3032 {
3033         struct iwi_softc *sc = arg1;
3034         int disable_mul = sc->disable_multicast_decryption;
3035         int error = sysctl_handle_int(oidp, &disable_mul, 0, req);
3036
3037         (void)arg2; /* silence WARNS == 6 */
3038         (void)oidp; /* silence WARNS == 6 */
3039
3040         if (!error && req->newptr && disable_mul!=sc->disable_multicast_decryption){
3041                 switch ( disable_mul ) {
3042                         case 1: case 0: case -1:
3043                                 sc->disable_multicast_decryption = disable_mul;
3044                         break;
3045                 }
3046         }
3047         return error;
3048 }
3049
3050