xref: /dflybsd-src/sys/dev/netif/wpi/if_wpi.c (revision 2e7bf158f373428dba2c765c927f14d9e94f00a4)
1 /*-
2  * Copyright (c) 2006,2007
3  *	Damien Bergamini <damien.bergamini@free.fr>
4  *	Benjamin Close <Benjamin.Close@clearchain.com>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  *
18  * $FreeBSD: src/sys/dev/wpi/if_wpi.c,v 1.27.2.2 2010/02/14 09:34:27 gavin Exp $
19  */
20 
21 #define VERSION "20071127"
22 
23 /*
24  * Driver for Intel PRO/Wireless 3945ABG 802.11 network adapters.
25  *
26  * The 3945ABG network adapter doesn't use traditional hardware as
27  * many other adaptors do. Instead at run time the eeprom is set into a known
28  * state and told to load boot firmware. The boot firmware loads an init and a
29  * main  binary firmware image into SRAM on the card via DMA.
30  * Once the firmware is loaded, the driver/hw then
31  * communicate by way of circular dma rings via the the SRAM to the firmware.
32  *
33  * There is 6 memory rings. 1 command ring, 1 rx data ring & 4 tx data rings.
34  * The 4 tx data rings allow for prioritization QoS.
35  *
36  * The rx data ring consists of 32 dma buffers. Two registers are used to
37  * indicate where in the ring the driver and the firmware are up to. The
38  * driver sets the initial read index (reg1) and the initial write index (reg2),
39  * the firmware updates the read index (reg1) on rx of a packet and fires an
40  * interrupt. The driver then processes the buffers starting at reg1 indicating
41  * to the firmware which buffers have been accessed by updating reg2. At the
42  * same time allocating new memory for the processed buffer.
43  *
44  * A similar thing happens with the tx rings. The difference is the firmware
45  * stop processing buffers once the queue is full and until confirmation
46  * of a successful transmition (tx_intr) has occurred.
47  *
48  * The command ring operates in the same manner as the tx queues.
49  *
50  * All communication direct to the card (ie eeprom) is classed as Stage1
51  * communication
52  *
53  * All communication via the firmware to the card is classed as State2.
54  * The firmware consists of 2 parts. A bootstrap firmware and a runtime
55  * firmware. The bootstrap firmware and runtime firmware are loaded
56  * from host memory via dma to the card then told to execute. From this point
57  * on the majority of communications between the driver and the card goes
58  * via the firmware.
59  */
60 
61 #include <sys/param.h>
62 #include <sys/sysctl.h>
63 #include <sys/sockio.h>
64 #include <sys/mbuf.h>
65 #include <sys/kernel.h>
66 #include <sys/socket.h>
67 #include <sys/systm.h>
68 #include <sys/malloc.h>
69 #include <sys/queue.h>
70 #include <sys/taskqueue.h>
71 #include <sys/module.h>
72 #include <sys/bus.h>
73 #include <sys/endian.h>
74 #include <sys/linker.h>
75 #include <sys/firmware.h>
76 
77 #include <sys/bus.h>
78 #include <sys/resource.h>
79 #include <sys/rman.h>
80 
81 #include <bus/pci/pcireg.h>
82 #include <bus/pci/pcivar.h>
83 
84 #include <net/bpf.h>
85 #include <net/if.h>
86 #include <net/if_arp.h>
87 #include <net/ifq_var.h>
88 #include <net/ethernet.h>
89 #include <net/if_dl.h>
90 #include <net/if_media.h>
91 #include <net/if_types.h>
92 
93 #include <netproto/802_11/ieee80211_var.h>
94 #include <netproto/802_11/ieee80211_radiotap.h>
95 #include <netproto/802_11/ieee80211_regdomain.h>
96 #include <netproto/802_11/ieee80211_ratectl.h>
97 
98 #include <netinet/in.h>
99 #include <netinet/in_systm.h>
100 #include <netinet/in_var.h>
101 #include <netinet/ip.h>
102 #include <netinet/if_ether.h>
103 
104 /* XXX: move elsewhere */
105 #define abs(x) (((x) < 0) ? -(x) : (x))
106 
107 #include "if_wpireg.h"
108 #include "if_wpivar.h"
109 
110 #define WPI_DEBUG
111 
112 #ifdef WPI_DEBUG
113 #define DPRINTF(x)	do { if (wpi_debug != 0) kprintf x; } while (0)
114 #define DPRINTFN(n, x)	do { if (wpi_debug & n) kprintf x; } while (0)
115 #define	WPI_DEBUG_SET	(wpi_debug != 0)
116 
117 enum {
118 	WPI_DEBUG_UNUSED	= 0x00000001,   /* Unused */
119 	WPI_DEBUG_HW		= 0x00000002,   /* Stage 1 (eeprom) debugging */
120 	WPI_DEBUG_TX		= 0x00000004,   /* Stage 2 TX intrp debugging*/
121 	WPI_DEBUG_RX		= 0x00000008,   /* Stage 2 RX intrp debugging */
122 	WPI_DEBUG_CMD		= 0x00000010,   /* Stage 2 CMD intrp debugging*/
123 	WPI_DEBUG_FIRMWARE	= 0x00000020,   /* firmware(9) loading debug  */
124 	WPI_DEBUG_DMA		= 0x00000040,   /* DMA (de)allocations/syncs  */
125 	WPI_DEBUG_SCANNING	= 0x00000080,   /* Stage 2 Scanning debugging */
126 	WPI_DEBUG_NOTIFY	= 0x00000100,   /* State 2 Noftif intr debug */
127 	WPI_DEBUG_TEMP		= 0x00000200,   /* TXPower/Temp Calibration */
128 	WPI_DEBUG_OPS		= 0x00000400,   /* wpi_ops taskq debug */
129 	WPI_DEBUG_WATCHDOG	= 0x00000800,   /* Watch dog debug */
130 	WPI_DEBUG_ANY		= 0xffffffff
131 };
132 
133 static int wpi_debug = 1;
134 SYSCTL_INT(_debug, OID_AUTO, wpi, CTLFLAG_RW, &wpi_debug, 0, "wpi debug level");
135 TUNABLE_INT("debug.wpi", &wpi_debug);
136 
137 #else
138 #define DPRINTF(x)
139 #define DPRINTFN(n, x)
140 #define WPI_DEBUG_SET	0
141 #endif
142 
143 struct wpi_ident {
144 	uint16_t	vendor;
145 	uint16_t	device;
146 	uint16_t	subdevice;
147 	const char	*name;
148 };
149 
150 static const struct wpi_ident wpi_ident_table[] = {
151 	/* The below entries support ABG regardless of the subid */
152 	{ 0x8086, 0x4222,    0x0, "Intel(R) PRO/Wireless 3945ABG" },
153 	{ 0x8086, 0x4227,    0x0, "Intel(R) PRO/Wireless 3945ABG" },
154 	/* The below entries only support BG */
155 	{ 0x8086, 0x4222, 0x1005, "Intel(R) PRO/Wireless 3945BG"  },
156 	{ 0x8086, 0x4222, 0x1034, "Intel(R) PRO/Wireless 3945BG"  },
157 	{ 0x8086, 0x4227, 0x1014, "Intel(R) PRO/Wireless 3945BG"  },
158 	{ 0x8086, 0x4222, 0x1044, "Intel(R) PRO/Wireless 3945BG"  },
159 	{ 0, 0, 0, NULL }
160 };
161 
162 static struct ieee80211vap *wpi_vap_create(struct ieee80211com *,
163 		    const char name[IFNAMSIZ], int unit, int opmode,
164 		    int flags, const uint8_t bssid[IEEE80211_ADDR_LEN],
165 		    const uint8_t mac[IEEE80211_ADDR_LEN]);
166 static void	wpi_vap_delete(struct ieee80211vap *);
167 static int	wpi_dma_contig_alloc(struct wpi_softc *, struct wpi_dma_info *,
168 		    void **, bus_size_t, bus_size_t, int);
169 static void	wpi_dma_contig_free(struct wpi_dma_info *);
170 static void	wpi_dma_map_addr(void *, bus_dma_segment_t *, int, int);
171 static int	wpi_alloc_shared(struct wpi_softc *);
172 static void	wpi_free_shared(struct wpi_softc *);
173 static int	wpi_alloc_rx_ring(struct wpi_softc *, struct wpi_rx_ring *);
174 static void	wpi_reset_rx_ring(struct wpi_softc *, struct wpi_rx_ring *);
175 static void	wpi_free_rx_ring(struct wpi_softc *, struct wpi_rx_ring *);
176 static int	wpi_alloc_tx_ring(struct wpi_softc *, struct wpi_tx_ring *,
177 		    int, int);
178 static void	wpi_reset_tx_ring(struct wpi_softc *, struct wpi_tx_ring *);
179 static void	wpi_free_tx_ring(struct wpi_softc *, struct wpi_tx_ring *);
180 static struct ieee80211_node *wpi_node_alloc(struct ieee80211vap *,
181 			    const uint8_t mac[IEEE80211_ADDR_LEN]);
182 static int	wpi_newstate(struct ieee80211vap *, enum ieee80211_state, int);
183 static void	wpi_mem_lock(struct wpi_softc *);
184 static void	wpi_mem_unlock(struct wpi_softc *);
185 static uint32_t	wpi_mem_read(struct wpi_softc *, uint16_t);
186 static void	wpi_mem_write(struct wpi_softc *, uint16_t, uint32_t);
187 static void	wpi_mem_write_region_4(struct wpi_softc *, uint16_t,
188 		    const uint32_t *, int);
189 static uint16_t	wpi_read_prom_data(struct wpi_softc *, uint32_t, void *, int);
190 static int	wpi_alloc_fwmem(struct wpi_softc *);
191 static void	wpi_free_fwmem(struct wpi_softc *);
192 static int	wpi_load_firmware(struct wpi_softc *);
193 static void	wpi_unload_firmware(struct wpi_softc *);
194 static int	wpi_load_microcode(struct wpi_softc *, const uint8_t *, int);
195 static void	wpi_rx_intr(struct wpi_softc *, struct wpi_rx_desc *,
196 		    struct wpi_rx_data *);
197 static void	wpi_tx_intr(struct wpi_softc *, struct wpi_rx_desc *);
198 static void	wpi_cmd_intr(struct wpi_softc *, struct wpi_rx_desc *);
199 static void	wpi_notif_intr(struct wpi_softc *);
200 static void	wpi_intr(void *);
201 static uint8_t	wpi_plcp_signal(int);
202 static void	wpi_watchdog(void *);
203 static int	wpi_tx_data(struct wpi_softc *, struct mbuf *,
204 		    struct ieee80211_node *, int);
205 static void	wpi_start(struct ifnet *);
206 static void	wpi_start_locked(struct ifnet *);
207 static int	wpi_raw_xmit(struct ieee80211_node *, struct mbuf *,
208 		    const struct ieee80211_bpf_params *);
209 static void	wpi_scan_start(struct ieee80211com *);
210 static void	wpi_scan_end(struct ieee80211com *);
211 static void	wpi_set_channel(struct ieee80211com *);
212 static void	wpi_scan_curchan(struct ieee80211_scan_state *, unsigned long);
213 static void	wpi_scan_mindwell(struct ieee80211_scan_state *);
214 static int	wpi_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
215 static void	wpi_read_eeprom(struct wpi_softc *,
216 		    uint8_t macaddr[IEEE80211_ADDR_LEN]);
217 static void	wpi_read_eeprom_channels(struct wpi_softc *, int);
218 static void	wpi_read_eeprom_group(struct wpi_softc *, int);
219 static int	wpi_cmd(struct wpi_softc *, int, const void *, int, int);
220 static int	wpi_wme_update(struct ieee80211com *);
221 static int	wpi_mrr_setup(struct wpi_softc *);
222 static void	wpi_set_led(struct wpi_softc *, uint8_t, uint8_t, uint8_t);
223 static void	wpi_enable_tsf(struct wpi_softc *, struct ieee80211_node *);
224 #if 0
225 static int	wpi_setup_beacon(struct wpi_softc *, struct ieee80211_node *);
226 #endif
227 static int	wpi_auth(struct wpi_softc *, struct ieee80211vap *);
228 static int	wpi_run(struct wpi_softc *, struct ieee80211vap *);
229 static int	wpi_scan(struct wpi_softc *);
230 static int	wpi_config(struct wpi_softc *);
231 static void	wpi_stop_master(struct wpi_softc *);
232 static int	wpi_power_up(struct wpi_softc *);
233 static int	wpi_reset(struct wpi_softc *);
234 static void	wpi_hwreset(void *, int);
235 static void	wpi_rfreset(void *, int);
236 static void	wpi_hw_config(struct wpi_softc *);
237 static void	wpi_init(void *);
238 static void	wpi_init_locked(struct wpi_softc *, int);
239 static void	wpi_stop(struct wpi_softc *);
240 static void	wpi_stop_locked(struct wpi_softc *);
241 
242 static void	wpi_newassoc(struct ieee80211_node *, int);
243 static int	wpi_set_txpower(struct wpi_softc *, struct ieee80211_channel *,
244 		    int);
245 static void	wpi_calib_timeout(void *);
246 static void	wpi_power_calibration(struct wpi_softc *, int);
247 static int	wpi_get_power_index(struct wpi_softc *,
248 		    struct wpi_power_group *, struct ieee80211_channel *, int);
249 #ifdef WPI_DEBUG
250 static const char *wpi_cmd_str(int);
251 #endif
252 static int wpi_probe(device_t);
253 static int wpi_attach(device_t);
254 static int wpi_detach(device_t);
255 static int wpi_shutdown(device_t);
256 static int wpi_suspend(device_t);
257 static int wpi_resume(device_t);
258 
259 
260 static device_method_t wpi_methods[] = {
261 	/* Device interface */
262 	DEVMETHOD(device_probe,		wpi_probe),
263 	DEVMETHOD(device_attach,	wpi_attach),
264 	DEVMETHOD(device_detach,	wpi_detach),
265 	DEVMETHOD(device_shutdown,	wpi_shutdown),
266 	DEVMETHOD(device_suspend,	wpi_suspend),
267 	DEVMETHOD(device_resume,	wpi_resume),
268 
269 	{ 0, 0 }
270 };
271 
272 static driver_t wpi_driver = {
273 	"wpi",
274 	wpi_methods,
275 	sizeof (struct wpi_softc)
276 };
277 
278 static devclass_t wpi_devclass;
279 
280 DRIVER_MODULE(wpi, pci, wpi_driver, wpi_devclass, 0, 0);
281 
282 static const uint8_t wpi_ridx_to_plcp[] = {
283 	/* OFDM: IEEE Std 802.11a-1999, pp. 14 Table 80 */
284 	/* R1-R4 (ral/ural is R4-R1) */
285 	0xd, 0xf, 0x5, 0x7, 0x9, 0xb, 0x1, 0x3,
286 	/* CCK: device-dependent */
287 	10, 20, 55, 110
288 };
289 static const uint8_t wpi_ridx_to_rate[] = {
290 	12, 18, 24, 36, 48, 72, 96, 108, /* OFDM */
291 	2, 4, 11, 22 /*CCK */
292 };
293 
294 
295 static int
296 wpi_probe(device_t dev)
297 {
298 	const struct wpi_ident *ident;
299 
300 	for (ident = wpi_ident_table; ident->name != NULL; ident++) {
301 		if (pci_get_vendor(dev) == ident->vendor &&
302 		    pci_get_device(dev) == ident->device) {
303 			device_set_desc(dev, ident->name);
304 			return 0;
305 		}
306 	}
307 	return ENXIO;
308 }
309 
310 /**
311  * Load the firmare image from disk to the allocated dma buffer.
312  * we also maintain the reference to the firmware pointer as there
313  * is times where we may need to reload the firmware but we are not
314  * in a context that can access the filesystem (ie taskq cause by restart)
315  *
316  * @return 0 on success, an errno on failure
317  */
318 static int
319 wpi_load_firmware(struct wpi_softc *sc)
320 {
321 	const struct firmware *fp;
322 	struct wpi_dma_info *dma = &sc->fw_dma;
323 	const struct wpi_firmware_hdr *hdr;
324 #if 0
325 	struct ifnet *ifp;
326 #endif
327 	const uint8_t *itext, *idata, *rtext, *rdata, *btext;
328 	uint32_t itextsz, idatasz, rtextsz, rdatasz, btextsz;
329 	int error;
330 
331 #if 0
332 	ifp = sc->sc_ifp;
333 #endif
334 	DPRINTFN(WPI_DEBUG_FIRMWARE,
335 	    ("Attempting Loading Firmware from wpi_fw module\n"));
336 
337 	WPI_UNLOCK(sc);
338 
339 #if 0
340 	lwkt_serialize_exit(ifp->if_serializer);
341 #endif
342 
343 #if 0
344 	if ((img = firmware_image_load("", dma->tag)) == NULL) {
345 		error = ENOENT;
346 		lwkt_serialize_enter(ifp->if_serializer);
347 		goto fail;
348 	}
349 #endif
350 
351 
352 	if (sc->fw_fp == NULL && (sc->fw_fp = firmware_get("wpifw")) == NULL) {
353 		device_printf(sc->sc_dev,
354 		    "could not load firmware image 'wpifw_fw'\n");
355 		error = ENOENT;
356 		WPI_LOCK(sc);
357 #if 0
358 		lwkt_serialize_enter(ifp->if_serializer);
359 #endif
360 		goto fail;
361 	}
362 
363 	fp = sc->fw_fp;
364 
365 #if 0
366 	lwkt_serialize_enter(ifp->if_serializer);
367 #endif
368 	WPI_LOCK(sc);
369 
370 
371 	/* Validate the firmware is minimum a particular version */
372 	if (fp->version < WPI_FW_MINVERSION) {
373 	    device_printf(sc->sc_dev,
374 			   "firmware version is too old. Need %d, got %d\n",
375 			   WPI_FW_MINVERSION,
376 			   fp->version);
377 	    error = ENXIO;
378 	    goto fail;
379 	}
380 #if 0
381 #endif
382 
383 	if (fp->datasize < sizeof (struct wpi_firmware_hdr)) {
384 		device_printf(sc->sc_dev,
385 		    "firmware file too short: %zu bytes\n", fp->datasize);
386 		error = ENXIO;
387 		goto fail;
388 	}
389 
390 	hdr = (const struct wpi_firmware_hdr *)fp->data;
391 
392 	/*     |  RUNTIME FIRMWARE   |    INIT FIRMWARE    | BOOT FW  |
393 	   |HDR|<--TEXT-->|<--DATA-->|<--TEXT-->|<--DATA-->|<--TEXT-->| */
394 
395 	rtextsz = le32toh(hdr->rtextsz);
396 	rdatasz = le32toh(hdr->rdatasz);
397 	itextsz = le32toh(hdr->itextsz);
398 	idatasz = le32toh(hdr->idatasz);
399 	btextsz = le32toh(hdr->btextsz);
400 
401 	/* check that all firmware segments are present */
402 	if (fp->datasize < sizeof (struct wpi_firmware_hdr) +
403 		rtextsz + rdatasz + itextsz + idatasz + btextsz) {
404 		device_printf(sc->sc_dev,
405 		    "firmware file too short: %zu bytes\n", fp->datasize);
406 		error = ENXIO; /* XXX appropriate error code? */
407 		goto fail;
408 	}
409 
410 	/* get pointers to firmware segments */
411 	rtext = (const uint8_t *)(hdr + 1);
412 	rdata = rtext + rtextsz;
413 	itext = rdata + rdatasz;
414 	idata = itext + itextsz;
415 	btext = idata + idatasz;
416 
417 	DPRINTFN(WPI_DEBUG_FIRMWARE,
418 	    ("Firmware Version: Major %d, Minor %d, Driver %d, \n"
419 	     "runtime (text: %u, data: %u) init (text: %u, data %u) boot (text %u)\n",
420 	     (le32toh(hdr->version) & 0xff000000) >> 24,
421 	     (le32toh(hdr->version) & 0x00ff0000) >> 16,
422 	     (le32toh(hdr->version) & 0x0000ffff),
423 	     rtextsz, rdatasz,
424 	     itextsz, idatasz, btextsz));
425 
426 	DPRINTFN(WPI_DEBUG_FIRMWARE,("rtext 0x%x\n", *(const uint32_t *)rtext));
427 	DPRINTFN(WPI_DEBUG_FIRMWARE,("rdata 0x%x\n", *(const uint32_t *)rdata));
428 	DPRINTFN(WPI_DEBUG_FIRMWARE,("itext 0x%x\n", *(const uint32_t *)itext));
429 	DPRINTFN(WPI_DEBUG_FIRMWARE,("idata 0x%x\n", *(const uint32_t *)idata));
430 	DPRINTFN(WPI_DEBUG_FIRMWARE,("btext 0x%x\n", *(const uint32_t *)btext));
431 
432 	/* sanity checks */
433 	if (rtextsz > WPI_FW_MAIN_TEXT_MAXSZ ||
434 	    rdatasz > WPI_FW_MAIN_DATA_MAXSZ ||
435 	    itextsz > WPI_FW_INIT_TEXT_MAXSZ ||
436 	    idatasz > WPI_FW_INIT_DATA_MAXSZ ||
437 	    btextsz > WPI_FW_BOOT_TEXT_MAXSZ ||
438 	    (btextsz & 3) != 0) {
439 		device_printf(sc->sc_dev, "firmware invalid\n");
440 		error = EINVAL;
441 		goto fail;
442 	}
443 
444 	/* copy initialization images into pre-allocated DMA-safe memory */
445 	memcpy(dma->vaddr, idata, idatasz);
446 	memcpy(dma->vaddr + WPI_FW_INIT_DATA_MAXSZ, itext, itextsz);
447 
448 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
449 
450 	/* tell adapter where to find initialization images */
451 	wpi_mem_lock(sc);
452 	wpi_mem_write(sc, WPI_MEM_DATA_BASE, dma->paddr);
453 	wpi_mem_write(sc, WPI_MEM_DATA_SIZE, idatasz);
454 	wpi_mem_write(sc, WPI_MEM_TEXT_BASE,
455 	    dma->paddr + WPI_FW_INIT_DATA_MAXSZ);
456 	wpi_mem_write(sc, WPI_MEM_TEXT_SIZE, itextsz);
457 	wpi_mem_unlock(sc);
458 
459 	/* load firmware boot code */
460 	if ((error = wpi_load_microcode(sc, btext, btextsz)) != 0) {
461 	    device_printf(sc->sc_dev, "Failed to load microcode\n");
462 	    goto fail;
463 	}
464 
465 	/* now press "execute" */
466 	WPI_WRITE(sc, WPI_RESET, 0);
467 
468 	/* wait at most one second for the first alive notification */
469 	if ((error = lksleep(sc, &sc->sc_lock, 0, "wpiinit", hz)) != 0) {
470 		device_printf(sc->sc_dev,
471 		    "timeout waiting for adapter to initialize\n");
472 		goto fail;
473 	}
474 
475 	/* copy runtime images into pre-allocated DMA-sage memory */
476 	memcpy(dma->vaddr, rdata, rdatasz);
477 	memcpy(dma->vaddr + WPI_FW_MAIN_DATA_MAXSZ, rtext, rtextsz);
478 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
479 
480 	/* tell adapter where to find runtime images */
481 	wpi_mem_lock(sc);
482 	wpi_mem_write(sc, WPI_MEM_DATA_BASE, dma->paddr);
483 	wpi_mem_write(sc, WPI_MEM_DATA_SIZE, rdatasz);
484 	wpi_mem_write(sc, WPI_MEM_TEXT_BASE,
485 	    dma->paddr + WPI_FW_MAIN_DATA_MAXSZ);
486 	wpi_mem_write(sc, WPI_MEM_TEXT_SIZE, WPI_FW_UPDATED | rtextsz);
487 	wpi_mem_unlock(sc);
488 
489 	/* wait at most one second for the first alive notification */
490 	if ((error = lksleep(sc, &sc->sc_lock, 0, "wpiinit", hz)) != 0) {
491 		device_printf(sc->sc_dev,
492 		    "timeout waiting for adapter to initialize2\n");
493 		goto fail;
494 	}
495 
496 	DPRINTFN(WPI_DEBUG_FIRMWARE,
497 	    ("Firmware loaded to driver successfully\n"));
498 /*
499 	sc->sc_fw_image = img;
500 */
501 	return error;
502 fail:
503 	wpi_unload_firmware(sc);
504 	return error;
505 }
506 
507 /**
508  * Free the referenced firmware image
509  */
510 static void
511 wpi_unload_firmware(struct wpi_softc *sc)
512 {
513 	struct ifnet *ifp;
514 	ifp = sc->sc_ifp;
515 
516 	if (sc->fw_fp) {
517 		WPI_UNLOCK(sc);
518 #if 0
519 		lwkt_serialize_exit(ifp->if_serializer);
520 #endif
521 		firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
522 #if 0
523 		firmware_image_unload(sc->sc_fw_image);
524 #endif
525 #if 0
526 		lwkt_serialize_enter(ifp->if_serializer);
527 #endif
528 		WPI_LOCK(sc);
529 		sc->fw_fp = NULL;
530 	}
531 }
532 
533 static int
534 wpi_attach(device_t dev)
535 {
536 	struct wpi_softc *sc = device_get_softc(dev);
537 	struct ifnet *ifp;
538 	struct ieee80211com *ic;
539 	int ac, error, supportsa = 1;
540 	uint32_t tmp;
541 	const struct wpi_ident *ident;
542 	uint8_t macaddr[IEEE80211_ADDR_LEN];
543 
544 	sc->sc_dev = dev;
545 
546 	if (bootverbose || WPI_DEBUG_SET)
547 	    device_printf(sc->sc_dev,"Driver Revision %s\n", VERSION);
548 
549 	/*
550 	 * Some card's only support 802.11b/g not a, check to see if
551 	 * this is one such card. A 0x0 in the subdevice table indicates
552 	 * the entire subdevice range is to be ignored.
553 	 */
554 	for (ident = wpi_ident_table; ident->name != NULL; ident++) {
555 		if (ident->subdevice &&
556 		    pci_get_subdevice(dev) == ident->subdevice) {
557 		    supportsa = 0;
558 		    break;
559 		}
560 	}
561 
562 	/* Create the tasks that can be queued */
563 	TASK_INIT(&sc->sc_restarttask, 0, wpi_hwreset, sc);
564 	TASK_INIT(&sc->sc_radiotask, 0, wpi_rfreset, sc);
565 
566 	WPI_LOCK_INIT(sc);
567 
568 	callout_init(&sc->calib_to);
569 	callout_init(&sc->watchdog_to);
570 
571 	if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
572 		device_printf(dev, "chip is in D%d power mode "
573 		    "-- setting to D0\n", pci_get_powerstate(dev));
574 		pci_set_powerstate(dev, PCI_POWERSTATE_D0);
575 	}
576 
577 	/* disable the retry timeout register */
578 	pci_write_config(dev, 0x41, 0, 1);
579 
580 	/* enable bus-mastering */
581 	pci_enable_busmaster(dev);
582 
583 	sc->mem_rid = PCIR_BAR(0);
584 	sc->mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &sc->mem_rid,
585 	    RF_ACTIVE);
586 	if (sc->mem == NULL) {
587 		device_printf(dev, "could not allocate memory resource\n");
588 		error = ENOMEM;
589 		goto fail;
590 	}
591 
592 	sc->sc_st = rman_get_bustag(sc->mem);
593 	sc->sc_sh = rman_get_bushandle(sc->mem);
594 
595 	sc->irq_rid = 0;
596 	sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->irq_rid,
597 	    RF_ACTIVE | RF_SHAREABLE);
598 	if (sc->irq == NULL) {
599 		device_printf(dev, "could not allocate interrupt resource\n");
600 		error = ENOMEM;
601 		goto fail;
602 	}
603 
604 	/*
605 	 * Allocate DMA memory for firmware transfers.
606 	 */
607 	if ((error = wpi_alloc_fwmem(sc)) != 0) {
608 		kprintf(": could not allocate firmware memory\n");
609 		error = ENOMEM;
610 		goto fail;
611 	}
612 
613 	/*
614 	 * Put adapter into a known state.
615 	 */
616 	if ((error = wpi_reset(sc)) != 0) {
617 		device_printf(dev, "could not reset adapter\n");
618 		goto fail;
619 	}
620 
621 	wpi_mem_lock(sc);
622 	tmp = wpi_mem_read(sc, WPI_MEM_PCIDEV);
623 	if (bootverbose || WPI_DEBUG_SET)
624 	    device_printf(sc->sc_dev, "Hardware Revision (0x%X)\n", tmp);
625 
626 	wpi_mem_unlock(sc);
627 
628 	/* Allocate shared page */
629 	if ((error = wpi_alloc_shared(sc)) != 0) {
630 		device_printf(dev, "could not allocate shared page\n");
631 		goto fail;
632 	}
633 
634 	/* tx data queues  - 4 for QoS purposes */
635 	for (ac = 0; ac < WME_NUM_AC; ac++) {
636 		error = wpi_alloc_tx_ring(sc, &sc->txq[ac], WPI_TX_RING_COUNT, ac);
637 		if (error != 0) {
638 		    device_printf(dev, "could not allocate Tx ring %d\n",ac);
639 		    goto fail;
640 		}
641 	}
642 
643 	/* command queue to talk to the card's firmware */
644 	error = wpi_alloc_tx_ring(sc, &sc->cmdq, WPI_CMD_RING_COUNT, 4);
645 	if (error != 0) {
646 		device_printf(dev, "could not allocate command ring\n");
647 		goto fail;
648 	}
649 
650 	/* receive data queue */
651 	error = wpi_alloc_rx_ring(sc, &sc->rxq);
652 	if (error != 0) {
653 		device_printf(dev, "could not allocate Rx ring\n");
654 		goto fail;
655 	}
656 
657 	ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
658 	if (ifp == NULL) {
659 		device_printf(dev, "can not if_alloc()\n");
660 		error = ENOMEM;
661 		goto fail;
662 	}
663 	ic = ifp->if_l2com;
664 
665 	ic->ic_ifp = ifp;
666 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
667 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
668 
669 	/* set device capabilities */
670 	ic->ic_caps =
671 		  IEEE80211_C_STA		/* station mode supported */
672 		| IEEE80211_C_MONITOR		/* monitor mode supported */
673 		| IEEE80211_C_TXPMGT		/* tx power management */
674 		| IEEE80211_C_SHSLOT		/* short slot time supported */
675 		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
676 		| IEEE80211_C_WPA		/* 802.11i */
677 /* XXX looks like WME is partly supported? */
678 #if 0
679 		| IEEE80211_C_IBSS		/* IBSS mode support */
680 		| IEEE80211_C_BGSCAN		/* capable of bg scanning */
681 		| IEEE80211_C_WME		/* 802.11e */
682 		| IEEE80211_C_HOSTAP		/* Host access point mode */
683 #endif
684 		;
685 
686 	/*
687 	 * Read in the eeprom and also setup the channels for
688 	 * net80211. We don't set the rates as net80211 does this for us
689 	 */
690 	wpi_read_eeprom(sc, macaddr);
691 
692 	if (bootverbose || WPI_DEBUG_SET) {
693 	    device_printf(sc->sc_dev, "Regulatory Domain: %.4s\n", sc->domain);
694 	    device_printf(sc->sc_dev, "Hardware Type: %c\n",
695 			  sc->type > 1 ? 'B': '?');
696 	    device_printf(sc->sc_dev, "Hardware Revision: %c\n",
697 			  ((le16toh(sc->rev) & 0xf0) == 0xd0) ? 'D': '?');
698 	    device_printf(sc->sc_dev, "SKU %s support 802.11a\n",
699 			  supportsa ? "does" : "does not");
700 
701 	    /* XXX hw_config uses the PCIDEV for the Hardware rev. Must check
702 	       what sc->rev really represents - benjsc 20070615 */
703 	}
704 
705 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
706 	ifp->if_softc = sc;
707 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
708 	ifp->if_init = wpi_init;
709 	ifp->if_ioctl = wpi_ioctl;
710 	ifp->if_start = wpi_start;
711 	ifq_set_maxlen(&ifp->if_snd, IFQ_MAXLEN);
712 	ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
713 	ifq_set_ready(&ifp->if_snd);
714 
715 	ieee80211_ifattach(ic, macaddr);
716 	/* override default methods */
717 	ic->ic_node_alloc = wpi_node_alloc;
718 	ic->ic_newassoc = wpi_newassoc;
719 	ic->ic_raw_xmit = wpi_raw_xmit;
720 	ic->ic_wme.wme_update = wpi_wme_update;
721 	ic->ic_scan_start = wpi_scan_start;
722 	ic->ic_scan_end = wpi_scan_end;
723 	ic->ic_set_channel = wpi_set_channel;
724 	ic->ic_scan_curchan = wpi_scan_curchan;
725 	ic->ic_scan_mindwell = wpi_scan_mindwell;
726 
727 	ic->ic_vap_create = wpi_vap_create;
728 	ic->ic_vap_delete = wpi_vap_delete;
729 
730 	ieee80211_radiotap_attach(ic,
731 	    &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap),
732 		WPI_TX_RADIOTAP_PRESENT,
733 	    &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
734 		WPI_RX_RADIOTAP_PRESENT);
735 
736 	/*
737 	 * Hook our interrupt after all initialization is complete.
738 	 */
739 	error = bus_setup_intr(dev, sc->irq, INTR_MPSAFE,
740 	    wpi_intr, sc, &sc->sc_ih, ifp->if_serializer);
741 	if (error != 0) {
742 		device_printf(dev, "could not set up interrupt\n");
743 		goto fail;
744 	}
745 
746 	if (bootverbose)
747 		ieee80211_announce(ic);
748 #ifdef XXX_DEBUG
749 	ieee80211_announce_channels(ic);
750 #endif
751 	return 0;
752 
753 fail:	wpi_detach(dev);
754 	return ENXIO;
755 }
756 
757 static int
758 wpi_detach(device_t dev)
759 {
760 	struct wpi_softc *sc = device_get_softc(dev);
761 	struct ifnet *ifp = sc->sc_ifp;
762 	struct ieee80211com *ic;
763 	int ac;
764 
765 	if (ifp != NULL) {
766 		ic = ifp->if_l2com;
767 
768 		ieee80211_draintask(ic, &sc->sc_restarttask);
769 		ieee80211_draintask(ic, &sc->sc_radiotask);
770 		wpi_stop(sc);
771 		callout_stop(&sc->watchdog_to);
772 		callout_stop(&sc->calib_to);
773 		ieee80211_ifdetach(ic);
774 	}
775 
776 	WPI_LOCK(sc);
777 	if (sc->txq[0].data_dmat) {
778 		for (ac = 0; ac < WME_NUM_AC; ac++)
779 			wpi_free_tx_ring(sc, &sc->txq[ac]);
780 
781 		wpi_free_tx_ring(sc, &sc->cmdq);
782 		wpi_free_rx_ring(sc, &sc->rxq);
783 		wpi_free_shared(sc);
784 	}
785 
786 	if (sc->fw_fp != NULL) {
787 		wpi_unload_firmware(sc);
788 	}
789 
790 	if (sc->fw_dma.tag)
791 		wpi_free_fwmem(sc);
792 	WPI_UNLOCK(sc);
793 
794 	if (sc->irq != NULL) {
795 		bus_teardown_intr(dev, sc->irq, sc->sc_ih);
796 		bus_release_resource(dev, SYS_RES_IRQ, sc->irq_rid, sc->irq);
797 	}
798 
799 	if (sc->mem != NULL)
800 		bus_release_resource(dev, SYS_RES_MEMORY, sc->mem_rid, sc->mem);
801 
802 	if (ifp != NULL)
803 		if_free(ifp);
804 
805 	WPI_LOCK_DESTROY(sc);
806 
807 	return 0;
808 }
809 
810 static struct ieee80211vap *
811 wpi_vap_create(struct ieee80211com *ic,
812 	const char name[IFNAMSIZ], int unit, int opmode, int flags,
813 	const uint8_t bssid[IEEE80211_ADDR_LEN],
814 	const uint8_t mac[IEEE80211_ADDR_LEN])
815 {
816 	struct wpi_vap *wvp;
817 	struct ieee80211vap *vap;
818 
819 	if (!TAILQ_EMPTY(&ic->ic_vaps))		/* only one at a time */
820 		return NULL;
821 	wvp = (struct wpi_vap *) kmalloc(sizeof(struct wpi_vap),
822 	    M_80211_VAP, M_NOWAIT | M_ZERO);
823 	if (wvp == NULL)
824 		return NULL;
825 	vap = &wvp->vap;
826 	ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid, mac);
827 	/* override with driver methods */
828 	wvp->newstate = vap->iv_newstate;
829 	vap->iv_newstate = wpi_newstate;
830 
831 	ieee80211_ratectl_init(vap);
832 
833 	/* complete setup */
834 	ieee80211_vap_attach(vap, ieee80211_media_change, ieee80211_media_status);
835 	ic->ic_opmode = opmode;
836 	return vap;
837 }
838 
839 static void
840 wpi_vap_delete(struct ieee80211vap *vap)
841 {
842 	struct wpi_vap *wvp = WPI_VAP(vap);
843 
844 	ieee80211_ratectl_deinit(vap);
845 	ieee80211_vap_detach(vap);
846 	kfree(wvp, M_80211_VAP);
847 }
848 
849 static void
850 wpi_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
851 {
852 	if (error != 0)
853 		return;
854 
855 	KASSERT(nsegs == 1, ("too many DMA segments, %d should be 1", nsegs));
856 
857 	*(bus_addr_t *)arg = segs[0].ds_addr;
858 }
859 
860 /*
861  * Allocates a contiguous block of dma memory of the requested size and
862  * alignment. Due to limitations of the FreeBSD dma subsystem as of 20071217,
863  * allocations greater than 4096 may fail. Hence if the requested alignment is
864  * greater we allocate 'alignment' size extra memory and shift the vaddr and
865  * paddr after the dma load. This bypasses the problem at the cost of a little
866  * more memory.
867  */
868 static int
869 wpi_dma_contig_alloc(struct wpi_softc *sc, struct wpi_dma_info *dma,
870     void **kvap, bus_size_t size, bus_size_t alignment, int flags)
871 {
872 	int error;
873 	bus_size_t align;
874 	bus_size_t reqsize;
875 
876 	DPRINTFN(WPI_DEBUG_DMA,
877 	    ("Size: %zd - alignment %zd\n", size, alignment));
878 
879 	dma->size = size;
880 	dma->tag = NULL;
881 
882 	if (alignment > 4096) {
883 		align = PAGE_SIZE;
884 		reqsize = size + alignment;
885 	} else {
886 		align = alignment;
887 		reqsize = size;
888 	}
889 	error = bus_dma_tag_create(dma->tag, align,
890 	    0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR,
891 	    NULL, NULL, reqsize,
892 	    1, reqsize, flags,
893 	    &dma->tag);
894 	if (error != 0) {
895 		device_printf(sc->sc_dev,
896 		    "could not create shared page DMA tag\n");
897 		goto fail;
898 	}
899 	error = bus_dmamem_alloc(dma->tag, (void **)&dma->vaddr_start,
900 	    flags | BUS_DMA_ZERO, &dma->map);
901 	if (error != 0) {
902 		device_printf(sc->sc_dev,
903 		    "could not allocate shared page DMA memory\n");
904 		goto fail;
905 	}
906 
907 	error = bus_dmamap_load(dma->tag, dma->map, dma->vaddr_start,
908 	    reqsize,  wpi_dma_map_addr, &dma->paddr_start, flags);
909 
910 	/* Save the original pointers so we can free all the memory */
911 	dma->paddr = dma->paddr_start;
912 	dma->vaddr = dma->vaddr_start;
913 
914 	/*
915 	 * Check the alignment and increment by 4096 until we get the
916 	 * requested alignment. Fail if can't obtain the alignment
917 	 * we requested.
918 	 */
919 	if ((dma->paddr & (alignment -1 )) != 0) {
920 		int i;
921 
922 		for (i = 0; i < alignment / 4096; i++) {
923 			if ((dma->paddr & (alignment - 1 )) == 0)
924 				break;
925 			dma->paddr += 4096;
926 			dma->vaddr += 4096;
927 		}
928 		if (i == alignment / 4096) {
929 			device_printf(sc->sc_dev,
930 			    "alignment requirement was not satisfied\n");
931 			goto fail;
932 		}
933 	}
934 
935 	if (error != 0) {
936 		device_printf(sc->sc_dev,
937 		    "could not load shared page DMA map\n");
938 		goto fail;
939 	}
940 
941 	if (kvap != NULL)
942 		*kvap = dma->vaddr;
943 
944 	return 0;
945 
946 fail:
947 	wpi_dma_contig_free(dma);
948 	return error;
949 }
950 
951 static void
952 wpi_dma_contig_free(struct wpi_dma_info *dma)
953 {
954 	if (dma->tag) {
955 		if (dma->map != NULL) {
956 			if (dma->paddr_start != 0) {
957 				bus_dmamap_sync(dma->tag, dma->map,
958 				    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
959 				bus_dmamap_unload(dma->tag, dma->map);
960 			}
961 			bus_dmamem_free(dma->tag, &dma->vaddr_start, dma->map);
962 		}
963 		bus_dma_tag_destroy(dma->tag);
964 	}
965 }
966 
967 /*
968  * Allocate a shared page between host and NIC.
969  */
970 static int
971 wpi_alloc_shared(struct wpi_softc *sc)
972 {
973 	int error;
974 
975 	error = wpi_dma_contig_alloc(sc, &sc->shared_dma,
976 	    (void **)&sc->shared, sizeof (struct wpi_shared),
977 	    PAGE_SIZE,
978 	    BUS_DMA_NOWAIT);
979 
980 	if (error != 0) {
981 		device_printf(sc->sc_dev,
982 		    "could not allocate shared area DMA memory\n");
983 	}
984 
985 	return error;
986 }
987 
988 static void
989 wpi_free_shared(struct wpi_softc *sc)
990 {
991 	wpi_dma_contig_free(&sc->shared_dma);
992 }
993 
994 static int
995 wpi_alloc_rx_ring(struct wpi_softc *sc, struct wpi_rx_ring *ring)
996 {
997 
998 	int i, error;
999 
1000 	ring->cur = 0;
1001 
1002 	error = wpi_dma_contig_alloc(sc, &ring->desc_dma,
1003 	    (void **)&ring->desc, WPI_RX_RING_COUNT * sizeof (uint32_t),
1004 	    WPI_RING_DMA_ALIGN, BUS_DMA_NOWAIT);
1005 
1006 	if (error != 0) {
1007 		device_printf(sc->sc_dev,
1008 		    "%s: could not allocate rx ring DMA memory, error %d\n",
1009 		    __func__, error);
1010 		goto fail;
1011 	}
1012 
1013         error = bus_dma_tag_create(ring->data_dmat, 1, 0,
1014 	    BUS_SPACE_MAXADDR_32BIT,
1015             BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES, 1,
1016             MCLBYTES, BUS_DMA_NOWAIT, &ring->data_dmat);
1017         if (error != 0) {
1018                 device_printf(sc->sc_dev,
1019 		    "%s: bus_dma_tag_create_failed, error %d\n",
1020 		    __func__, error);
1021                 goto fail;
1022         }
1023 
1024 	/*
1025 	 * Setup Rx buffers.
1026 	 */
1027 	for (i = 0; i < WPI_RX_RING_COUNT; i++) {
1028 		struct wpi_rx_data *data = &ring->data[i];
1029 		struct mbuf *m;
1030 		bus_addr_t paddr;
1031 
1032 		error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
1033 		if (error != 0) {
1034 			device_printf(sc->sc_dev,
1035 			    "%s: bus_dmamap_create failed, error %d\n",
1036 			    __func__, error);
1037 			goto fail;
1038 		}
1039 		m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1040 		if (m == NULL) {
1041 			device_printf(sc->sc_dev,
1042 			   "%s: could not allocate rx mbuf\n", __func__);
1043 			error = ENOMEM;
1044 			goto fail;
1045 		}
1046 		/* map page */
1047 		error = bus_dmamap_load(ring->data_dmat, data->map,
1048 		    mtod(m, caddr_t), MCLBYTES,
1049 		    wpi_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
1050 		if (error != 0 && error != EFBIG) {
1051 			device_printf(sc->sc_dev,
1052 			    "%s: bus_dmamap_load failed, error %d\n",
1053 			    __func__, error);
1054 			m_freem(m);
1055 			error = ENOMEM;	/* XXX unique code */
1056 			goto fail;
1057 		}
1058 		bus_dmamap_sync(ring->data_dmat, data->map,
1059 		    BUS_DMASYNC_PREWRITE);
1060 
1061 		data->m = m;
1062 		ring->desc[i] = htole32(paddr);
1063 	}
1064 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
1065 	    BUS_DMASYNC_PREWRITE);
1066 	return 0;
1067 fail:
1068 	wpi_free_rx_ring(sc, ring);
1069 	return error;
1070 }
1071 
1072 static void
1073 wpi_reset_rx_ring(struct wpi_softc *sc, struct wpi_rx_ring *ring)
1074 {
1075 	int ntries;
1076 
1077 	wpi_mem_lock(sc);
1078 
1079 	WPI_WRITE(sc, WPI_RX_CONFIG, 0);
1080 
1081 	for (ntries = 0; ntries < 100; ntries++) {
1082 		if (WPI_READ(sc, WPI_RX_STATUS) & WPI_RX_IDLE)
1083 			break;
1084 		DELAY(10);
1085 	}
1086 
1087 	wpi_mem_unlock(sc);
1088 
1089 #ifdef WPI_DEBUG
1090 	if (ntries == 100 && wpi_debug > 0)
1091 		device_printf(sc->sc_dev, "timeout resetting Rx ring\n");
1092 #endif
1093 
1094 	ring->cur = 0;
1095 }
1096 
1097 static void
1098 wpi_free_rx_ring(struct wpi_softc *sc, struct wpi_rx_ring *ring)
1099 {
1100 	int i;
1101 
1102 	wpi_dma_contig_free(&ring->desc_dma);
1103 
1104 	for (i = 0; i < WPI_RX_RING_COUNT; i++)
1105 		if (ring->data[i].m != NULL)
1106 			m_freem(ring->data[i].m);
1107 }
1108 
1109 static int
1110 wpi_alloc_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring, int count,
1111 	int qid)
1112 {
1113 	struct wpi_tx_data *data;
1114 	int i, error;
1115 
1116 	ring->qid = qid;
1117 	ring->count = count;
1118 	ring->queued = 0;
1119 	ring->cur = 0;
1120 	ring->data = NULL;
1121 
1122 	error = wpi_dma_contig_alloc(sc, &ring->desc_dma,
1123 		(void **)&ring->desc, count * sizeof (struct wpi_tx_desc),
1124 		WPI_RING_DMA_ALIGN, BUS_DMA_NOWAIT);
1125 
1126 	if (error != 0) {
1127 	    device_printf(sc->sc_dev, "could not allocate tx dma memory\n");
1128 	    goto fail;
1129 	}
1130 
1131 	/* update shared page with ring's base address */
1132 	sc->shared->txbase[qid] = htole32(ring->desc_dma.paddr);
1133 
1134 	error = wpi_dma_contig_alloc(sc, &ring->cmd_dma, (void **)&ring->cmd,
1135 		count * sizeof (struct wpi_tx_cmd), WPI_RING_DMA_ALIGN,
1136 		BUS_DMA_NOWAIT);
1137 
1138 	if (error != 0) {
1139 		device_printf(sc->sc_dev,
1140 		    "could not allocate tx command DMA memory\n");
1141 		goto fail;
1142 	}
1143 
1144 	ring->data = kmalloc(count * sizeof (struct wpi_tx_data), M_DEVBUF,
1145 	    M_NOWAIT | M_ZERO);
1146 	if (ring->data == NULL) {
1147 		device_printf(sc->sc_dev,
1148 		    "could not allocate tx data slots\n");
1149 		goto fail;
1150 	}
1151 
1152 	error = bus_dma_tag_create(ring->data_dmat, 1, 0,
1153 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
1154 	    WPI_MAX_SCATTER - 1, MCLBYTES, BUS_DMA_NOWAIT,
1155 	    &ring->data_dmat);
1156 	if (error != 0) {
1157 		device_printf(sc->sc_dev, "could not create data DMA tag\n");
1158 		goto fail;
1159 	}
1160 
1161 	for (i = 0; i < count; i++) {
1162 		data = &ring->data[i];
1163 
1164 		error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
1165 		if (error != 0) {
1166 			device_printf(sc->sc_dev,
1167 			    "could not create tx buf DMA map\n");
1168 			goto fail;
1169 		}
1170 		bus_dmamap_sync(ring->data_dmat, data->map,
1171 		    BUS_DMASYNC_PREWRITE);
1172 	}
1173 
1174 	return 0;
1175 
1176 fail:
1177 	wpi_free_tx_ring(sc, ring);
1178 	return error;
1179 }
1180 
1181 static void
1182 wpi_reset_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring)
1183 {
1184 	struct wpi_tx_data *data;
1185 	int i, ntries;
1186 
1187 	wpi_mem_lock(sc);
1188 
1189 	WPI_WRITE(sc, WPI_TX_CONFIG(ring->qid), 0);
1190 	for (ntries = 0; ntries < 100; ntries++) {
1191 		if (WPI_READ(sc, WPI_TX_STATUS) & WPI_TX_IDLE(ring->qid))
1192 			break;
1193 		DELAY(10);
1194 	}
1195 #ifdef WPI_DEBUG
1196 	if (ntries == 100 && wpi_debug > 0)
1197 		device_printf(sc->sc_dev, "timeout resetting Tx ring %d\n",
1198 		    ring->qid);
1199 #endif
1200 	wpi_mem_unlock(sc);
1201 
1202 	for (i = 0; i < ring->count; i++) {
1203 		data = &ring->data[i];
1204 
1205 		if (data->m != NULL) {
1206 			bus_dmamap_unload(ring->data_dmat, data->map);
1207 			m_freem(data->m);
1208 			data->m = NULL;
1209 		}
1210 	}
1211 
1212 	ring->queued = 0;
1213 	ring->cur = 0;
1214 }
1215 
1216 static void
1217 wpi_free_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring)
1218 {
1219 	struct wpi_tx_data *data;
1220 	int i;
1221 
1222 	wpi_dma_contig_free(&ring->desc_dma);
1223 	wpi_dma_contig_free(&ring->cmd_dma);
1224 
1225 	if (ring->data != NULL) {
1226 		for (i = 0; i < ring->count; i++) {
1227 			data = &ring->data[i];
1228 
1229 			if (data->m != NULL) {
1230 				bus_dmamap_sync(ring->data_dmat, data->map,
1231 				    BUS_DMASYNC_POSTWRITE);
1232 				bus_dmamap_unload(ring->data_dmat, data->map);
1233 				m_freem(data->m);
1234 				data->m = NULL;
1235 			}
1236 		}
1237 		kfree(ring->data, M_DEVBUF);
1238 	}
1239 
1240 	if (ring->data_dmat != NULL)
1241 		bus_dma_tag_destroy(ring->data_dmat);
1242 }
1243 
1244 static int
1245 wpi_shutdown(device_t dev)
1246 {
1247 	struct wpi_softc *sc = device_get_softc(dev);
1248 
1249 	WPI_LOCK(sc);
1250 	wpi_stop_locked(sc);
1251 	wpi_unload_firmware(sc);
1252 	WPI_UNLOCK(sc);
1253 
1254 	return 0;
1255 }
1256 
1257 static int
1258 wpi_suspend(device_t dev)
1259 {
1260 	struct wpi_softc *sc = device_get_softc(dev);
1261 
1262 	wpi_stop(sc);
1263 	return 0;
1264 }
1265 
1266 static int
1267 wpi_resume(device_t dev)
1268 {
1269 	struct wpi_softc *sc = device_get_softc(dev);
1270 	struct ifnet *ifp = sc->sc_ifp;
1271 
1272 	pci_write_config(dev, 0x41, 0, 1);
1273 
1274 	if (ifp->if_flags & IFF_UP) {
1275 		wpi_init(ifp->if_softc);
1276 		if (ifp->if_flags & IFF_RUNNING)
1277 			wpi_start(ifp);
1278 	}
1279 	return 0;
1280 }
1281 
1282 /* ARGSUSED */
1283 static struct ieee80211_node *
1284 wpi_node_alloc(struct ieee80211vap *vap __unused,
1285 	const uint8_t mac[IEEE80211_ADDR_LEN] __unused)
1286 {
1287 	struct wpi_node *wn;
1288 
1289 	wn = kmalloc(sizeof (struct wpi_node), M_80211_NODE, M_NOWAIT | M_ZERO);
1290 
1291 	return &wn->ni;
1292 }
1293 
1294 /**
1295  * Called by net80211 when ever there is a change to 80211 state machine
1296  */
1297 static int
1298 wpi_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
1299 {
1300 	struct wpi_vap *wvp = WPI_VAP(vap);
1301 	struct ieee80211com *ic = vap->iv_ic;
1302 	struct ifnet *ifp = ic->ic_ifp;
1303 	struct wpi_softc *sc = ifp->if_softc;
1304 	int error;
1305 
1306 	DPRINTF(("%s: %s -> %s flags 0x%x\n", __func__,
1307 		ieee80211_state_name[vap->iv_state],
1308 		ieee80211_state_name[nstate], sc->flags));
1309 
1310 	IEEE80211_UNLOCK(ic);
1311 	WPI_LOCK(sc);
1312 	if (nstate == IEEE80211_S_AUTH) {
1313 		/* The node must be registered in the firmware before auth */
1314 		error = wpi_auth(sc, vap);
1315 		if (error != 0) {
1316 			device_printf(sc->sc_dev,
1317 			    "%s: could not move to auth state, error %d\n",
1318 			    __func__, error);
1319 		}
1320 	}
1321 	if (nstate == IEEE80211_S_RUN && vap->iv_state != IEEE80211_S_RUN) {
1322 		error = wpi_run(sc, vap);
1323 		if (error != 0) {
1324 			device_printf(sc->sc_dev,
1325 			    "%s: could not move to run state, error %d\n",
1326 			    __func__, error);
1327 		}
1328 	}
1329 	if (nstate == IEEE80211_S_RUN) {
1330 		/* RUN -> RUN transition; just restart the timers */
1331 		wpi_calib_timeout(sc);
1332 		/* XXX split out rate control timer */
1333 	}
1334 	WPI_UNLOCK(sc);
1335 	IEEE80211_LOCK(ic);
1336 	return wvp->newstate(vap, nstate, arg);
1337 }
1338 
1339 /*
1340  * Grab exclusive access to NIC memory.
1341  */
1342 static void
1343 wpi_mem_lock(struct wpi_softc *sc)
1344 {
1345 	int ntries;
1346 	uint32_t tmp;
1347 
1348 	tmp = WPI_READ(sc, WPI_GPIO_CTL);
1349 	WPI_WRITE(sc, WPI_GPIO_CTL, tmp | WPI_GPIO_MAC);
1350 
1351 	/* spin until we actually get the lock */
1352 	for (ntries = 0; ntries < 100; ntries++) {
1353 		if ((WPI_READ(sc, WPI_GPIO_CTL) &
1354 			(WPI_GPIO_CLOCK | WPI_GPIO_SLEEP)) == WPI_GPIO_CLOCK)
1355 			break;
1356 		DELAY(10);
1357 	}
1358 	if (ntries == 100)
1359 		device_printf(sc->sc_dev, "could not lock memory\n");
1360 }
1361 
1362 /*
1363  * Release lock on NIC memory.
1364  */
1365 static void
1366 wpi_mem_unlock(struct wpi_softc *sc)
1367 {
1368 	uint32_t tmp = WPI_READ(sc, WPI_GPIO_CTL);
1369 	WPI_WRITE(sc, WPI_GPIO_CTL, tmp & ~WPI_GPIO_MAC);
1370 }
1371 
1372 static uint32_t
1373 wpi_mem_read(struct wpi_softc *sc, uint16_t addr)
1374 {
1375 	WPI_WRITE(sc, WPI_READ_MEM_ADDR, WPI_MEM_4 | addr);
1376 	return WPI_READ(sc, WPI_READ_MEM_DATA);
1377 }
1378 
1379 static void
1380 wpi_mem_write(struct wpi_softc *sc, uint16_t addr, uint32_t data)
1381 {
1382 	WPI_WRITE(sc, WPI_WRITE_MEM_ADDR, WPI_MEM_4 | addr);
1383 	WPI_WRITE(sc, WPI_WRITE_MEM_DATA, data);
1384 }
1385 
1386 static void
1387 wpi_mem_write_region_4(struct wpi_softc *sc, uint16_t addr,
1388     const uint32_t *data, int wlen)
1389 {
1390 	for (; wlen > 0; wlen--, data++, addr+=4)
1391 		wpi_mem_write(sc, addr, *data);
1392 }
1393 
1394 /*
1395  * Read data from the EEPROM.  We access EEPROM through the MAC instead of
1396  * using the traditional bit-bang method. Data is read up until len bytes have
1397  * been obtained.
1398  */
1399 static uint16_t
1400 wpi_read_prom_data(struct wpi_softc *sc, uint32_t addr, void *data, int len)
1401 {
1402 	int ntries;
1403 	uint32_t val;
1404 	uint8_t *out = data;
1405 
1406 	wpi_mem_lock(sc);
1407 
1408 	for (; len > 0; len -= 2, addr++) {
1409 		WPI_WRITE(sc, WPI_EEPROM_CTL, addr << 2);
1410 
1411 		for (ntries = 0; ntries < 10; ntries++) {
1412 			if ((val = WPI_READ(sc, WPI_EEPROM_CTL)) & WPI_EEPROM_READY)
1413 				break;
1414 			DELAY(5);
1415 		}
1416 
1417 		if (ntries == 10) {
1418 			device_printf(sc->sc_dev, "could not read EEPROM\n");
1419 			return ETIMEDOUT;
1420 		}
1421 
1422 		*out++= val >> 16;
1423 		if (len > 1)
1424 			*out ++= val >> 24;
1425 	}
1426 
1427 	wpi_mem_unlock(sc);
1428 
1429 	return 0;
1430 }
1431 
1432 /*
1433  * The firmware text and data segments are transferred to the NIC using DMA.
1434  * The driver just copies the firmware into DMA-safe memory and tells the NIC
1435  * where to find it.  Once the NIC has copied the firmware into its internal
1436  * memory, we can free our local copy in the driver.
1437  */
1438 static int
1439 wpi_load_microcode(struct wpi_softc *sc, const uint8_t *fw, int size)
1440 {
1441 	int error, ntries;
1442 
1443 	DPRINTFN(WPI_DEBUG_HW,("Loading microcode  size 0x%x\n", size));
1444 
1445 	size /= sizeof(uint32_t);
1446 
1447 	wpi_mem_lock(sc);
1448 
1449 	wpi_mem_write_region_4(sc, WPI_MEM_UCODE_BASE,
1450 	    (const uint32_t *)fw, size);
1451 
1452 	wpi_mem_write(sc, WPI_MEM_UCODE_SRC, 0);
1453 	wpi_mem_write(sc, WPI_MEM_UCODE_DST, WPI_FW_TEXT);
1454 	wpi_mem_write(sc, WPI_MEM_UCODE_SIZE, size);
1455 
1456 	/* run microcode */
1457 	wpi_mem_write(sc, WPI_MEM_UCODE_CTL, WPI_UC_RUN);
1458 
1459 	/* wait while the adapter is busy copying the firmware */
1460 	for (error = 0, ntries = 0; ntries < 1000; ntries++) {
1461 		uint32_t status = WPI_READ(sc, WPI_TX_STATUS);
1462 		DPRINTFN(WPI_DEBUG_HW,
1463 		    ("firmware status=0x%x, val=0x%x, result=0x%x\n", status,
1464 		     WPI_TX_IDLE(6), status & WPI_TX_IDLE(6)));
1465 		if (status & WPI_TX_IDLE(6)) {
1466 			DPRINTFN(WPI_DEBUG_HW,
1467 			    ("Status Match! - ntries = %d\n", ntries));
1468 			break;
1469 		}
1470 		DELAY(10);
1471 	}
1472 	if (ntries == 1000) {
1473 		device_printf(sc->sc_dev, "timeout transferring firmware\n");
1474 		error = ETIMEDOUT;
1475 	}
1476 
1477 	/* start the microcode executing */
1478 	wpi_mem_write(sc, WPI_MEM_UCODE_CTL, WPI_UC_ENABLE);
1479 
1480 	wpi_mem_unlock(sc);
1481 
1482 	return (error);
1483 }
1484 
1485 static void
1486 wpi_rx_intr(struct wpi_softc *sc, struct wpi_rx_desc *desc,
1487 	struct wpi_rx_data *data)
1488 {
1489 	struct ifnet *ifp = sc->sc_ifp;
1490 	struct ieee80211com *ic = ifp->if_l2com;
1491 	struct wpi_rx_ring *ring = &sc->rxq;
1492 	struct wpi_rx_stat *stat;
1493 	struct wpi_rx_head *head;
1494 	struct wpi_rx_tail *tail;
1495 	struct ieee80211_node *ni;
1496 	struct mbuf *m, *mnew;
1497 	bus_addr_t paddr;
1498 	int error;
1499 
1500 	stat = (struct wpi_rx_stat *)(desc + 1);
1501 
1502 	if (stat->len > WPI_STAT_MAXLEN) {
1503 		device_printf(sc->sc_dev, "invalid rx statistic header\n");
1504 		ifp->if_ierrors++;
1505 		return;
1506 	}
1507 
1508 	head = (struct wpi_rx_head *)((caddr_t)(stat + 1) + stat->len);
1509 	tail = (struct wpi_rx_tail *)((caddr_t)(head + 1) + le16toh(head->len));
1510 
1511 	DPRINTFN(WPI_DEBUG_RX, ("rx intr: idx=%d len=%d stat len=%d rssi=%d "
1512 	    "rate=%x chan=%d tstamp=%ju\n", ring->cur, le32toh(desc->len),
1513 	    le16toh(head->len), (int8_t)stat->rssi, head->rate, head->chan,
1514 	    (uintmax_t)le64toh(tail->tstamp)));
1515 
1516 	/* discard Rx frames with bad CRC early */
1517 	if ((le32toh(tail->flags) & WPI_RX_NOERROR) != WPI_RX_NOERROR) {
1518 		DPRINTFN(WPI_DEBUG_RX, ("%s: rx flags error %x\n", __func__,
1519 		    le32toh(tail->flags)));
1520 		ifp->if_ierrors++;
1521 		return;
1522 	}
1523 	if (le16toh(head->len) < sizeof (struct ieee80211_frame)) {
1524 		DPRINTFN(WPI_DEBUG_RX, ("%s: frame too short: %d\n", __func__,
1525 		    le16toh(head->len)));
1526 		ifp->if_ierrors++;
1527 		return;
1528 	}
1529 
1530 	/* XXX don't need mbuf, just dma buffer */
1531 	mnew = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1532 	if (mnew == NULL) {
1533 		DPRINTFN(WPI_DEBUG_RX, ("%s: no mbuf to restock ring\n",
1534 		    __func__));
1535 		ifp->if_ierrors++;
1536 		return;
1537 	}
1538 	error = bus_dmamap_load(ring->data_dmat, data->map,
1539 	    mtod(mnew, caddr_t), MCLBYTES,
1540 	    wpi_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
1541 	if (error != 0 && error != EFBIG) {
1542 		device_printf(sc->sc_dev,
1543 		    "%s: bus_dmamap_load failed, error %d\n", __func__, error);
1544 		m_freem(mnew);
1545 		ifp->if_ierrors++;
1546 		return;
1547 	}
1548 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1549 
1550 	/* finalize mbuf and swap in new one */
1551 	m = data->m;
1552 	m->m_pkthdr.rcvif = ifp;
1553 	m->m_data = (caddr_t)(head + 1);
1554 	m->m_pkthdr.len = m->m_len = le16toh(head->len);
1555 
1556 	data->m = mnew;
1557 	/* update Rx descriptor */
1558 	ring->desc[ring->cur] = htole32(paddr);
1559 
1560 	if (ieee80211_radiotap_active(ic)) {
1561 		struct wpi_rx_radiotap_header *tap = &sc->sc_rxtap;
1562 
1563 		tap->wr_flags = 0;
1564 		tap->wr_chan_freq =
1565 			htole16(ic->ic_channels[head->chan].ic_freq);
1566 		tap->wr_chan_flags =
1567 			htole16(ic->ic_channels[head->chan].ic_flags);
1568 		tap->wr_dbm_antsignal = (int8_t)(stat->rssi - WPI_RSSI_OFFSET);
1569 		tap->wr_dbm_antnoise = (int8_t)le16toh(stat->noise);
1570 		tap->wr_tsft = tail->tstamp;
1571 		tap->wr_antenna = (le16toh(head->flags) >> 4) & 0xf;
1572 		switch (head->rate) {
1573 		/* CCK rates */
1574 		case  10: tap->wr_rate =   2; break;
1575 		case  20: tap->wr_rate =   4; break;
1576 		case  55: tap->wr_rate =  11; break;
1577 		case 110: tap->wr_rate =  22; break;
1578 		/* OFDM rates */
1579 		case 0xd: tap->wr_rate =  12; break;
1580 		case 0xf: tap->wr_rate =  18; break;
1581 		case 0x5: tap->wr_rate =  24; break;
1582 		case 0x7: tap->wr_rate =  36; break;
1583 		case 0x9: tap->wr_rate =  48; break;
1584 		case 0xb: tap->wr_rate =  72; break;
1585 		case 0x1: tap->wr_rate =  96; break;
1586 		case 0x3: tap->wr_rate = 108; break;
1587 		/* unknown rate: should not happen */
1588 		default:  tap->wr_rate =   0;
1589 		}
1590 		if (le16toh(head->flags) & 0x4)
1591 			tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
1592 	}
1593 
1594 	WPI_UNLOCK(sc);
1595 
1596 	ni = ieee80211_find_rxnode(ic, mtod(m, struct ieee80211_frame_min *));
1597 	if (ni != NULL) {
1598 		(void) ieee80211_input(ni, m, stat->rssi, 0);
1599 		ieee80211_free_node(ni);
1600 	} else
1601 		(void) ieee80211_input_all(ic, m, stat->rssi, 0);
1602 
1603 	WPI_LOCK(sc);
1604 }
1605 
1606 static void
1607 wpi_tx_intr(struct wpi_softc *sc, struct wpi_rx_desc *desc)
1608 {
1609 	struct ifnet *ifp = sc->sc_ifp;
1610 	struct wpi_tx_ring *ring = &sc->txq[desc->qid & 0x3];
1611 	struct wpi_tx_data *txdata = &ring->data[desc->idx];
1612 	struct wpi_tx_stat *stat = (struct wpi_tx_stat *)(desc + 1);
1613 	struct ieee80211_node *ni = txdata->ni;
1614 	struct ieee80211vap *vap = ni->ni_vap;
1615 	int retrycnt = 0;
1616 
1617 	DPRINTFN(WPI_DEBUG_TX, ("tx done: qid=%d idx=%d retries=%d nkill=%d "
1618 	    "rate=%x duration=%d status=%x\n", desc->qid, desc->idx,
1619 	    stat->ntries, stat->nkill, stat->rate, le32toh(stat->duration),
1620 	    le32toh(stat->status)));
1621 
1622 	/*
1623 	 * Update rate control statistics for the node.
1624 	 * XXX we should not count mgmt frames since they're always sent at
1625 	 * the lowest available bit-rate.
1626 	 * XXX frames w/o ACK shouldn't be used either
1627 	 */
1628 	if (stat->ntries > 0) {
1629 		DPRINTFN(WPI_DEBUG_TX, ("%d retries\n", stat->ntries));
1630 		retrycnt = 1;
1631 	}
1632 	ieee80211_ratectl_tx_complete(vap, ni, IEEE80211_RATECTL_TX_SUCCESS,
1633 		&retrycnt, NULL);
1634 
1635 	/* XXX oerrors should only count errors !maxtries */
1636 	if ((le32toh(stat->status) & 0xff) != 1)
1637 		ifp->if_oerrors++;
1638 	else
1639 		ifp->if_opackets++;
1640 
1641 	bus_dmamap_sync(ring->data_dmat, txdata->map, BUS_DMASYNC_POSTWRITE);
1642 	bus_dmamap_unload(ring->data_dmat, txdata->map);
1643 	/* XXX handle M_TXCB? */
1644 	m_freem(txdata->m);
1645 	txdata->m = NULL;
1646 	ieee80211_free_node(txdata->ni);
1647 	txdata->ni = NULL;
1648 
1649 	ring->queued--;
1650 
1651 	sc->sc_tx_timer = 0;
1652 	ifp->if_flags &= ~IFF_OACTIVE;
1653 	wpi_start_locked(ifp);
1654 }
1655 
1656 static void
1657 wpi_cmd_intr(struct wpi_softc *sc, struct wpi_rx_desc *desc)
1658 {
1659 	struct wpi_tx_ring *ring = &sc->cmdq;
1660 	struct wpi_tx_data *data;
1661 
1662 	DPRINTFN(WPI_DEBUG_CMD, ("cmd notification qid=%x idx=%d flags=%x "
1663 				 "type=%s len=%d\n", desc->qid, desc->idx,
1664 				 desc->flags, wpi_cmd_str(desc->type),
1665 				 le32toh(desc->len)));
1666 
1667 	if ((desc->qid & 7) != 4)
1668 		return;	/* not a command ack */
1669 
1670 	data = &ring->data[desc->idx];
1671 
1672 	/* if the command was mapped in a mbuf, free it */
1673 	if (data->m != NULL) {
1674 		bus_dmamap_unload(ring->data_dmat, data->map);
1675 		m_freem(data->m);
1676 		data->m = NULL;
1677 	}
1678 
1679 	sc->flags &= ~WPI_FLAG_BUSY;
1680 	wakeup(&ring->cmd[desc->idx]);
1681 }
1682 
1683 static void
1684 wpi_notif_intr(struct wpi_softc *sc)
1685 {
1686 	struct ifnet *ifp = sc->sc_ifp;
1687 	struct ieee80211com *ic = ifp->if_l2com;
1688 	struct wpi_rx_desc *desc;
1689 	struct wpi_rx_data *data;
1690 	uint32_t hw;
1691 
1692 	hw = le32toh(sc->shared->next);
1693 	while (sc->rxq.cur != hw) {
1694 		data = &sc->rxq.data[sc->rxq.cur];
1695 		desc = (void *)data->m->m_ext.ext_buf;
1696 
1697 		DPRINTFN(WPI_DEBUG_NOTIFY,
1698 			 ("notify qid=%x idx=%d flags=%x type=%d len=%d\n",
1699 			  desc->qid,
1700 			  desc->idx,
1701 			  desc->flags,
1702 			  desc->type,
1703 			  le32toh(desc->len)));
1704 
1705 		if (!(desc->qid & 0x80))	/* reply to a command */
1706 			wpi_cmd_intr(sc, desc);
1707 
1708 		switch (desc->type) {
1709 		case WPI_RX_DONE:
1710 			/* a 802.11 frame was received */
1711 			wpi_rx_intr(sc, desc, data);
1712 			break;
1713 
1714 		case WPI_TX_DONE:
1715 			/* a 802.11 frame has been transmitted */
1716 			wpi_tx_intr(sc, desc);
1717 			break;
1718 
1719 		case WPI_UC_READY:
1720 		{
1721 			struct wpi_ucode_info *uc =
1722 				(struct wpi_ucode_info *)(desc + 1);
1723 
1724 			/* the microcontroller is ready */
1725 			DPRINTF(("microcode alive notification version %x "
1726 				"alive %x\n", le32toh(uc->version),
1727 				le32toh(uc->valid)));
1728 
1729 			if (le32toh(uc->valid) != 1) {
1730 				device_printf(sc->sc_dev,
1731 				    "microcontroller initialization failed\n");
1732 				wpi_stop_locked(sc);
1733 			}
1734 			break;
1735 		}
1736 		case WPI_STATE_CHANGED:
1737 		{
1738 			uint32_t *status = (uint32_t *)(desc + 1);
1739 
1740 			/* enabled/disabled notification */
1741 			DPRINTF(("state changed to %x\n", le32toh(*status)));
1742 
1743 			if (le32toh(*status) & 1) {
1744 				device_printf(sc->sc_dev,
1745 				    "Radio transmitter is switched off\n");
1746 				sc->flags |= WPI_FLAG_HW_RADIO_OFF;
1747 				ifp->if_flags &= ~IFF_RUNNING;
1748 				/* Disable firmware commands */
1749 				WPI_WRITE(sc, WPI_UCODE_SET, WPI_DISABLE_CMD);
1750 			}
1751 			break;
1752 		}
1753 		case WPI_START_SCAN:
1754 		{
1755 #ifdef WPI_DEBUG
1756 			struct wpi_start_scan *scan =
1757 				(struct wpi_start_scan *)(desc + 1);
1758 #endif
1759 
1760 			DPRINTFN(WPI_DEBUG_SCANNING,
1761 				 ("scanning channel %d status %x\n",
1762 			    scan->chan, le32toh(scan->status)));
1763 			break;
1764 		}
1765 		case WPI_STOP_SCAN:
1766 		{
1767 #ifdef WPI_DEBUG
1768 			struct wpi_stop_scan *scan =
1769 				(struct wpi_stop_scan *)(desc + 1);
1770 #endif
1771 			struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1772 
1773 			DPRINTFN(WPI_DEBUG_SCANNING,
1774 			    ("scan finished nchan=%d status=%d chan=%d\n",
1775 			     scan->nchan, scan->status, scan->chan));
1776 
1777 			sc->sc_scan_timer = 0;
1778 			ieee80211_scan_next(vap);
1779 			break;
1780 		}
1781 		case WPI_MISSED_BEACON:
1782 		{
1783 			struct wpi_missed_beacon *beacon =
1784 				(struct wpi_missed_beacon *)(desc + 1);
1785 			struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1786 
1787 			if (le32toh(beacon->consecutive) >=
1788 			    vap->iv_bmissthreshold) {
1789 				DPRINTF(("Beacon miss: %u >= %u\n",
1790 					 le32toh(beacon->consecutive),
1791 					 vap->iv_bmissthreshold));
1792 				ieee80211_beacon_miss(ic);
1793 			}
1794 			break;
1795 		}
1796 		}
1797 
1798 		sc->rxq.cur = (sc->rxq.cur + 1) % WPI_RX_RING_COUNT;
1799 	}
1800 
1801 	/* tell the firmware what we have processed */
1802 	hw = (hw == 0) ? WPI_RX_RING_COUNT - 1 : hw - 1;
1803 	WPI_WRITE(sc, WPI_RX_WIDX, hw & ~7);
1804 }
1805 
1806 static void
1807 wpi_intr(void *arg)
1808 {
1809 	struct wpi_softc *sc = arg;
1810 	uint32_t r;
1811 
1812 	WPI_LOCK(sc);
1813 
1814 	r = WPI_READ(sc, WPI_INTR);
1815 	if (r == 0 || r == 0xffffffff) {
1816 		WPI_UNLOCK(sc);
1817 		return;
1818 	}
1819 
1820 	/* disable interrupts */
1821 	WPI_WRITE(sc, WPI_MASK, 0);
1822 	/* ack interrupts */
1823 	WPI_WRITE(sc, WPI_INTR, r);
1824 
1825 	if (r & (WPI_SW_ERROR | WPI_HW_ERROR)) {
1826 		struct ifnet *ifp = sc->sc_ifp;
1827 		struct ieee80211com *ic = ifp->if_l2com;
1828 		struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1829 
1830 		device_printf(sc->sc_dev, "fatal firmware error\n");
1831 		DPRINTFN(6,("(%s)\n", (r & WPI_SW_ERROR) ? "(Software Error)" :
1832 				"(Hardware Error)"));
1833 		if (vap != NULL)
1834 			ieee80211_cancel_scan(vap);
1835 		ieee80211_runtask(ic, &sc->sc_restarttask);
1836 		sc->flags &= ~WPI_FLAG_BUSY;
1837 		WPI_UNLOCK(sc);
1838 		return;
1839 	}
1840 
1841 	if (r & WPI_RX_INTR)
1842 		wpi_notif_intr(sc);
1843 
1844 	if (r & WPI_ALIVE_INTR)	/* firmware initialized */
1845 		wakeup(sc);
1846 
1847 	/* re-enable interrupts */
1848 	if (sc->sc_ifp->if_flags & IFF_UP)
1849 		WPI_WRITE(sc, WPI_MASK, WPI_INTR_MASK);
1850 
1851 	WPI_UNLOCK(sc);
1852 }
1853 
1854 static uint8_t
1855 wpi_plcp_signal(int rate)
1856 {
1857 	switch (rate) {
1858 	/* CCK rates (returned values are device-dependent) */
1859 	case 2:		return 10;
1860 	case 4:		return 20;
1861 	case 11:	return 55;
1862 	case 22:	return 110;
1863 
1864 	/* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
1865 	/* R1-R4 (ral/ural is R4-R1) */
1866 	case 12:	return 0xd;
1867 	case 18:	return 0xf;
1868 	case 24:	return 0x5;
1869 	case 36:	return 0x7;
1870 	case 48:	return 0x9;
1871 	case 72:	return 0xb;
1872 	case 96:	return 0x1;
1873 	case 108:	return 0x3;
1874 
1875 	/* unsupported rates (should not get there) */
1876 	default:	return 0;
1877 	}
1878 }
1879 
1880 /* quickly determine if a given rate is CCK or OFDM */
1881 #define WPI_RATE_IS_OFDM(rate) ((rate) >= 12 && (rate) != 22)
1882 
1883 /*
1884  * Construct the data packet for a transmit buffer and acutally put
1885  * the buffer onto the transmit ring, kicking the card to process the
1886  * the buffer.
1887  */
1888 static int
1889 wpi_tx_data(struct wpi_softc *sc, struct mbuf *m0, struct ieee80211_node *ni,
1890 	int ac)
1891 {
1892 	struct ieee80211vap *vap = ni->ni_vap;
1893 	struct ifnet *ifp = sc->sc_ifp;
1894 	struct ieee80211com *ic = ifp->if_l2com;
1895 	const struct chanAccParams *cap = &ic->ic_wme.wme_chanParams;
1896 	struct wpi_tx_ring *ring = &sc->txq[ac];
1897 	struct wpi_tx_desc *desc;
1898 	struct wpi_tx_data *data;
1899 	struct wpi_tx_cmd *cmd;
1900 	struct wpi_cmd_data *tx;
1901 	struct ieee80211_frame *wh;
1902 	const struct ieee80211_txparam *tp;
1903 	struct ieee80211_key *k;
1904 	struct mbuf *mnew;
1905 	int i, error, nsegs, rate, hdrlen, ismcast;
1906 	bus_dma_segment_t segs[WPI_MAX_SCATTER];
1907 
1908 	desc = &ring->desc[ring->cur];
1909 	data = &ring->data[ring->cur];
1910 
1911 	wh = mtod(m0, struct ieee80211_frame *);
1912 
1913 	hdrlen = ieee80211_hdrsize(wh);
1914 	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
1915 
1916 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1917 		k = ieee80211_crypto_encap(ni, m0);
1918 		if (k == NULL) {
1919 			m_freem(m0);
1920 			return ENOBUFS;
1921 		}
1922 		/* packet header may have moved, reset our local pointer */
1923 		wh = mtod(m0, struct ieee80211_frame *);
1924 	}
1925 
1926 	cmd = &ring->cmd[ring->cur];
1927 	cmd->code = WPI_CMD_TX_DATA;
1928 	cmd->flags = 0;
1929 	cmd->qid = ring->qid;
1930 	cmd->idx = ring->cur;
1931 
1932 	tx = (struct wpi_cmd_data *)cmd->data;
1933 	tx->flags = htole32(WPI_TX_AUTO_SEQ);
1934 	tx->timeout = htole16(0);
1935 	tx->ofdm_mask = 0xff;
1936 	tx->cck_mask = 0x0f;
1937 	tx->lifetime = htole32(WPI_LIFETIME_INFINITE);
1938 	tx->id = ismcast ? WPI_ID_BROADCAST : WPI_ID_BSS;
1939 	tx->len = htole16(m0->m_pkthdr.len);
1940 
1941 	if (!ismcast) {
1942 		if ((ni->ni_flags & IEEE80211_NODE_QOS) == 0 ||
1943 		    !cap->cap_wmeParams[ac].wmep_noackPolicy)
1944 			tx->flags |= htole32(WPI_TX_NEED_ACK);
1945 		if (m0->m_pkthdr.len + IEEE80211_CRC_LEN > vap->iv_rtsthreshold) {
1946 			tx->flags |= htole32(WPI_TX_NEED_RTS|WPI_TX_FULL_TXOP);
1947 			tx->rts_ntries = 7;
1948 		}
1949 	}
1950 	/* pick a rate */
1951 	tp = &vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)];
1952 	if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_MGT) {
1953 		uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
1954 		/* tell h/w to set timestamp in probe responses */
1955 		if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1956 			tx->flags |= htole32(WPI_TX_INSERT_TSTAMP);
1957 		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
1958 		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
1959 			tx->timeout = htole16(3);
1960 		else
1961 			tx->timeout = htole16(2);
1962 		rate = tp->mgmtrate;
1963 	} else if (ismcast) {
1964 		rate = tp->mcastrate;
1965 	} else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE) {
1966 		rate = tp->ucastrate;
1967 	} else {
1968 		(void) ieee80211_ratectl_rate(ni, NULL, 0);
1969 		rate = ni->ni_txrate;
1970 	}
1971 	tx->rate = wpi_plcp_signal(rate);
1972 
1973 	/* be very persistant at sending frames out */
1974 #if 0
1975 	tx->data_ntries = tp->maxretry;
1976 #else
1977 	tx->data_ntries = 30;		/* XXX way too high */
1978 #endif
1979 
1980 	if (ieee80211_radiotap_active_vap(vap)) {
1981 		struct wpi_tx_radiotap_header *tap = &sc->sc_txtap;
1982 		tap->wt_flags = 0;
1983 		tap->wt_rate = rate;
1984 		tap->wt_hwqueue = ac;
1985 		if (wh->i_fc[1] & IEEE80211_FC1_WEP)
1986 			tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
1987 
1988 		ieee80211_radiotap_tx(vap, m0);
1989 	}
1990 
1991 	/* save and trim IEEE802.11 header */
1992 	m_copydata(m0, 0, hdrlen, (caddr_t)&tx->wh);
1993 	m_adj(m0, hdrlen);
1994 
1995 	error = bus_dmamap_load_mbuf_segment(ring->data_dmat, data->map, m0, segs,
1996 	    1, &nsegs, BUS_DMA_NOWAIT);
1997 	if (error != 0 && error != EFBIG) {
1998 		device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1999 		    error);
2000 		m_freem(m0);
2001 		return error;
2002 	}
2003 	if (error != 0) {
2004 		/* XXX use m_collapse */
2005 		mnew = m_defrag(m0, MB_DONTWAIT);
2006 		if (mnew == NULL) {
2007 			device_printf(sc->sc_dev,
2008 			    "could not defragment mbuf\n");
2009 			m_freem(m0);
2010 			return ENOBUFS;
2011 		}
2012 		m0 = mnew;
2013 
2014 		error = bus_dmamap_load_mbuf_segment(ring->data_dmat, data->map,
2015 		    m0, segs, 1, &nsegs, BUS_DMA_NOWAIT);
2016 		if (error != 0) {
2017 			device_printf(sc->sc_dev,
2018 			    "could not map mbuf (error %d)\n", error);
2019 			m_freem(m0);
2020 			return error;
2021 		}
2022 	}
2023 
2024 	data->m = m0;
2025 	data->ni = ni;
2026 
2027 	DPRINTFN(WPI_DEBUG_TX, ("sending data: qid=%d idx=%d len=%d nsegs=%d\n",
2028 	    ring->qid, ring->cur, m0->m_pkthdr.len, nsegs));
2029 
2030 	/* first scatter/gather segment is used by the tx data command */
2031 	desc->flags = htole32(WPI_PAD32(m0->m_pkthdr.len) << 28 |
2032 	    (1 + nsegs) << 24);
2033 	desc->segs[0].addr = htole32(ring->cmd_dma.paddr +
2034 	    ring->cur * sizeof (struct wpi_tx_cmd));
2035 	desc->segs[0].len  = htole32(4 + sizeof (struct wpi_cmd_data));
2036 	for (i = 1; i <= nsegs; i++) {
2037 		desc->segs[i].addr = htole32(segs[i - 1].ds_addr);
2038 		desc->segs[i].len  = htole32(segs[i - 1].ds_len);
2039 	}
2040 
2041 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
2042 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
2043 	    BUS_DMASYNC_PREWRITE);
2044 
2045 	ring->queued++;
2046 
2047 	/* kick ring */
2048 	ring->cur = (ring->cur + 1) % WPI_TX_RING_COUNT;
2049 	WPI_WRITE(sc, WPI_TX_WIDX, ring->qid << 8 | ring->cur);
2050 
2051 	return 0;
2052 }
2053 
2054 /**
2055  * Process data waiting to be sent on the IFNET output queue
2056  */
2057 static void
2058 wpi_start(struct ifnet *ifp)
2059 {
2060 	struct wpi_softc *sc = ifp->if_softc;
2061 
2062 	WPI_LOCK(sc);
2063 	wpi_start_locked(ifp);
2064 	WPI_UNLOCK(sc);
2065 }
2066 
2067 static void
2068 wpi_start_locked(struct ifnet *ifp)
2069 {
2070 	struct wpi_softc *sc = ifp->if_softc;
2071 	struct ieee80211_node *ni;
2072 	struct mbuf *m;
2073 	int ac;
2074 
2075 	WPI_LOCK_ASSERT(sc);
2076 
2077 	if ((ifp->if_flags & IFF_RUNNING) == 0) {
2078 		ifq_purge(&ifp->if_snd);
2079 		return;
2080 	}
2081 
2082 	for (;;) {
2083 		IF_DEQUEUE(&ifp->if_snd, m);
2084 		if (m == NULL)
2085 			break;
2086 		ac = M_WME_GETAC(m);
2087 		if (sc->txq[ac].queued > sc->txq[ac].count - 8) {
2088 			/* there is no place left in this ring */
2089 			ifq_prepend(&ifp->if_snd, m);
2090 			ifp->if_flags |= IFF_OACTIVE;
2091 			break;
2092 		}
2093 		ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
2094 		if (wpi_tx_data(sc, m, ni, ac) != 0) {
2095 			ieee80211_free_node(ni);
2096 			ifp->if_oerrors++;
2097 			break;
2098 		}
2099 		sc->sc_tx_timer = 5;
2100 	}
2101 }
2102 
2103 static int
2104 wpi_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
2105 	const struct ieee80211_bpf_params *params)
2106 {
2107 	struct ieee80211com *ic = ni->ni_ic;
2108 	struct ifnet *ifp = ic->ic_ifp;
2109 	struct wpi_softc *sc = ifp->if_softc;
2110 
2111 	/* prevent management frames from being sent if we're not ready */
2112 	if (!(ifp->if_flags & IFF_RUNNING)) {
2113 		m_freem(m);
2114 		ieee80211_free_node(ni);
2115 		return ENETDOWN;
2116 	}
2117 	WPI_LOCK(sc);
2118 
2119 	/* management frames go into ring 0 */
2120 	if (sc->txq[0].queued > sc->txq[0].count - 8) {
2121 		ifp->if_flags |= IFF_OACTIVE;
2122 		m_freem(m);
2123 		WPI_UNLOCK(sc);
2124 		ieee80211_free_node(ni);
2125 		return ENOBUFS;		/* XXX */
2126 	}
2127 
2128 	ifp->if_opackets++;
2129 	if (wpi_tx_data(sc, m, ni, 0) != 0)
2130 		goto bad;
2131 	sc->sc_tx_timer = 5;
2132 	callout_reset(&sc->watchdog_to, hz, wpi_watchdog, sc);
2133 
2134 	WPI_UNLOCK(sc);
2135 	return 0;
2136 bad:
2137 	ifp->if_oerrors++;
2138 	WPI_UNLOCK(sc);
2139 	ieee80211_free_node(ni);
2140 	return EIO;		/* XXX */
2141 }
2142 
2143 static int
2144 wpi_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data, struct ucred *cred)
2145 {
2146 	struct wpi_softc *sc = ifp->if_softc;
2147 	struct ieee80211com *ic = ifp->if_l2com;
2148 	struct ifreq *ifr = (struct ifreq *) data;
2149 	int error = 0, startall = 0;
2150 
2151 	switch (cmd) {
2152 	case SIOCSIFFLAGS:
2153 		WPI_LOCK(sc);
2154 		if ((ifp->if_flags & IFF_UP)) {
2155 			if (!(ifp->if_flags & IFF_RUNNING)) {
2156 				wpi_init_locked(sc, 0);
2157 				startall = 1;
2158 			}
2159 		} else if ((ifp->if_flags & IFF_RUNNING) ||
2160 			   (sc->flags & WPI_FLAG_HW_RADIO_OFF))
2161 			wpi_stop_locked(sc);
2162 		WPI_UNLOCK(sc);
2163 		if (startall)
2164 			ieee80211_start_all(ic);
2165 		break;
2166 	case SIOCGIFMEDIA:
2167 		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
2168 		break;
2169 	case SIOCGIFADDR:
2170 		error = ether_ioctl(ifp, cmd, data);
2171 		break;
2172 	default:
2173 		error = EINVAL;
2174 		break;
2175 	}
2176 	return error;
2177 }
2178 
2179 /*
2180  * Extract various information from EEPROM.
2181  */
2182 static void
2183 wpi_read_eeprom(struct wpi_softc *sc, uint8_t macaddr[IEEE80211_ADDR_LEN])
2184 {
2185 	int i;
2186 
2187 	/* read the hardware capabilities, revision and SKU type */
2188 	wpi_read_prom_data(sc, WPI_EEPROM_CAPABILITIES, &sc->cap,1);
2189 	wpi_read_prom_data(sc, WPI_EEPROM_REVISION, &sc->rev,2);
2190 	wpi_read_prom_data(sc, WPI_EEPROM_TYPE, &sc->type, 1);
2191 
2192 	/* read the regulatory domain */
2193 	wpi_read_prom_data(sc, WPI_EEPROM_DOMAIN, sc->domain, 4);
2194 
2195 	/* read in the hw MAC address */
2196 	wpi_read_prom_data(sc, WPI_EEPROM_MAC, macaddr, 6);
2197 
2198 	/* read the list of authorized channels */
2199 	for (i = 0; i < WPI_CHAN_BANDS_COUNT; i++)
2200 		wpi_read_eeprom_channels(sc,i);
2201 
2202 	/* read the power level calibration info for each group */
2203 	for (i = 0; i < WPI_POWER_GROUPS_COUNT; i++)
2204 		wpi_read_eeprom_group(sc,i);
2205 }
2206 
2207 /*
2208  * Send a command to the firmware.
2209  */
2210 static int
2211 wpi_cmd(struct wpi_softc *sc, int code, const void *buf, int size, int async)
2212 {
2213 	struct wpi_tx_ring *ring = &sc->cmdq;
2214 	struct wpi_tx_desc *desc;
2215 	struct wpi_tx_cmd *cmd;
2216 
2217 #ifdef WPI_DEBUG
2218 	if (!async) {
2219 		WPI_LOCK_ASSERT(sc);
2220 	}
2221 #endif
2222 
2223 	DPRINTFN(WPI_DEBUG_CMD,("wpi_cmd %d size %d async %d\n", code, size,
2224 		    async));
2225 
2226 	if (sc->flags & WPI_FLAG_BUSY) {
2227 		device_printf(sc->sc_dev, "%s: cmd %d not sent, busy\n",
2228 		    __func__, code);
2229 		return EAGAIN;
2230 	}
2231 	sc->flags|= WPI_FLAG_BUSY;
2232 
2233 	KASSERT(size <= sizeof cmd->data, ("command %d too large: %d bytes",
2234 	    code, size));
2235 
2236 	desc = &ring->desc[ring->cur];
2237 	cmd = &ring->cmd[ring->cur];
2238 
2239 	cmd->code = code;
2240 	cmd->flags = 0;
2241 	cmd->qid = ring->qid;
2242 	cmd->idx = ring->cur;
2243 	memcpy(cmd->data, buf, size);
2244 
2245 	desc->flags = htole32(WPI_PAD32(size) << 28 | 1 << 24);
2246 	desc->segs[0].addr = htole32(ring->cmd_dma.paddr +
2247 		ring->cur * sizeof (struct wpi_tx_cmd));
2248 	desc->segs[0].len  = htole32(4 + size);
2249 
2250 	/* kick cmd ring */
2251 	ring->cur = (ring->cur + 1) % WPI_CMD_RING_COUNT;
2252 	WPI_WRITE(sc, WPI_TX_WIDX, ring->qid << 8 | ring->cur);
2253 
2254 	if (async) {
2255 		sc->flags &= ~ WPI_FLAG_BUSY;
2256 		return 0;
2257 	}
2258 
2259 	return lksleep(cmd, &sc->sc_lock, 0, "wpicmd", hz);
2260 }
2261 
2262 static int
2263 wpi_wme_update(struct ieee80211com *ic)
2264 {
2265 #define WPI_EXP2(v)	htole16((1 << (v)) - 1)
2266 #define WPI_USEC(v)	htole16(IEEE80211_TXOP_TO_US(v))
2267 	struct wpi_softc *sc = ic->ic_ifp->if_softc;
2268 	const struct wmeParams *wmep;
2269 	struct wpi_wme_setup wme;
2270 	int ac;
2271 
2272 	/* don't override default WME values if WME is not actually enabled */
2273 	if (!(ic->ic_flags & IEEE80211_F_WME))
2274 		return 0;
2275 
2276 	wme.flags = 0;
2277 	for (ac = 0; ac < WME_NUM_AC; ac++) {
2278 		wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
2279 		wme.ac[ac].aifsn = wmep->wmep_aifsn;
2280 		wme.ac[ac].cwmin = WPI_EXP2(wmep->wmep_logcwmin);
2281 		wme.ac[ac].cwmax = WPI_EXP2(wmep->wmep_logcwmax);
2282 		wme.ac[ac].txop  = WPI_USEC(wmep->wmep_txopLimit);
2283 
2284 		DPRINTF(("setting WME for queue %d aifsn=%d cwmin=%d cwmax=%d "
2285 		    "txop=%d\n", ac, wme.ac[ac].aifsn, wme.ac[ac].cwmin,
2286 		    wme.ac[ac].cwmax, wme.ac[ac].txop));
2287 	}
2288 	return wpi_cmd(sc, WPI_CMD_SET_WME, &wme, sizeof wme, 1);
2289 #undef WPI_USEC
2290 #undef WPI_EXP2
2291 }
2292 
2293 /*
2294  * Configure h/w multi-rate retries.
2295  */
2296 static int
2297 wpi_mrr_setup(struct wpi_softc *sc)
2298 {
2299 	struct ifnet *ifp = sc->sc_ifp;
2300 	struct ieee80211com *ic = ifp->if_l2com;
2301 	struct wpi_mrr_setup mrr;
2302 	int i, error;
2303 
2304 	memset(&mrr, 0, sizeof (struct wpi_mrr_setup));
2305 
2306 	/* CCK rates (not used with 802.11a) */
2307 	for (i = WPI_CCK1; i <= WPI_CCK11; i++) {
2308 		mrr.rates[i].flags = 0;
2309 		mrr.rates[i].signal = wpi_ridx_to_plcp[i];
2310 		/* fallback to the immediate lower CCK rate (if any) */
2311 		mrr.rates[i].next = (i == WPI_CCK1) ? WPI_CCK1 : i - 1;
2312 		/* try one time at this rate before falling back to "next" */
2313 		mrr.rates[i].ntries = 1;
2314 	}
2315 
2316 	/* OFDM rates (not used with 802.11b) */
2317 	for (i = WPI_OFDM6; i <= WPI_OFDM54; i++) {
2318 		mrr.rates[i].flags = 0;
2319 		mrr.rates[i].signal = wpi_ridx_to_plcp[i];
2320 		/* fallback to the immediate lower OFDM rate (if any) */
2321 		/* we allow fallback from OFDM/6 to CCK/2 in 11b/g mode */
2322 		mrr.rates[i].next = (i == WPI_OFDM6) ?
2323 		    ((ic->ic_curmode == IEEE80211_MODE_11A) ?
2324 			WPI_OFDM6 : WPI_CCK2) :
2325 		    i - 1;
2326 		/* try one time at this rate before falling back to "next" */
2327 		mrr.rates[i].ntries = 1;
2328 	}
2329 
2330 	/* setup MRR for control frames */
2331 	mrr.which = htole32(WPI_MRR_CTL);
2332 	error = wpi_cmd(sc, WPI_CMD_MRR_SETUP, &mrr, sizeof mrr, 0);
2333 	if (error != 0) {
2334 		device_printf(sc->sc_dev,
2335 		    "could not setup MRR for control frames\n");
2336 		return error;
2337 	}
2338 
2339 	/* setup MRR for data frames */
2340 	mrr.which = htole32(WPI_MRR_DATA);
2341 	error = wpi_cmd(sc, WPI_CMD_MRR_SETUP, &mrr, sizeof mrr, 0);
2342 	if (error != 0) {
2343 		device_printf(sc->sc_dev,
2344 		    "could not setup MRR for data frames\n");
2345 		return error;
2346 	}
2347 
2348 	return 0;
2349 }
2350 
2351 static void
2352 wpi_set_led(struct wpi_softc *sc, uint8_t which, uint8_t off, uint8_t on)
2353 {
2354 	struct wpi_cmd_led led;
2355 
2356 	led.which = which;
2357 	led.unit = htole32(100000);	/* on/off in unit of 100ms */
2358 	led.off = off;
2359 	led.on = on;
2360 
2361 	(void)wpi_cmd(sc, WPI_CMD_SET_LED, &led, sizeof led, 1);
2362 }
2363 
2364 static void
2365 wpi_enable_tsf(struct wpi_softc *sc, struct ieee80211_node *ni)
2366 {
2367 	struct wpi_cmd_tsf tsf;
2368 	uint64_t val, mod;
2369 
2370 	memset(&tsf, 0, sizeof tsf);
2371 	memcpy(&tsf.tstamp, ni->ni_tstamp.data, 8);
2372 	tsf.bintval = htole16(ni->ni_intval);
2373 	tsf.lintval = htole16(10);
2374 
2375 	/* compute remaining time until next beacon */
2376 	val = (uint64_t)ni->ni_intval  * 1024;	/* msec -> usec */
2377 	mod = le64toh(tsf.tstamp) % val;
2378 	tsf.binitval = htole32((uint32_t)(val - mod));
2379 
2380 	if (wpi_cmd(sc, WPI_CMD_TSF, &tsf, sizeof tsf, 1) != 0)
2381 		device_printf(sc->sc_dev, "could not enable TSF\n");
2382 }
2383 
2384 #if 0
2385 /*
2386  * Build a beacon frame that the firmware will broadcast periodically in
2387  * IBSS or HostAP modes.
2388  */
2389 static int
2390 wpi_setup_beacon(struct wpi_softc *sc, struct ieee80211_node *ni)
2391 {
2392 	struct ifnet *ifp = sc->sc_ifp;
2393 	struct ieee80211com *ic = ifp->if_l2com;
2394 	struct wpi_tx_ring *ring = &sc->cmdq;
2395 	struct wpi_tx_desc *desc;
2396 	struct wpi_tx_data *data;
2397 	struct wpi_tx_cmd *cmd;
2398 	struct wpi_cmd_beacon *bcn;
2399 	struct ieee80211_beacon_offsets bo;
2400 	struct mbuf *m0;
2401 	bus_addr_t physaddr;
2402 	int error;
2403 
2404 	desc = &ring->desc[ring->cur];
2405 	data = &ring->data[ring->cur];
2406 
2407 	m0 = ieee80211_beacon_alloc(ic, ni, &bo);
2408 	if (m0 == NULL) {
2409 		device_printf(sc->sc_dev, "could not allocate beacon frame\n");
2410 		return ENOMEM;
2411 	}
2412 
2413 	cmd = &ring->cmd[ring->cur];
2414 	cmd->code = WPI_CMD_SET_BEACON;
2415 	cmd->flags = 0;
2416 	cmd->qid = ring->qid;
2417 	cmd->idx = ring->cur;
2418 
2419 	bcn = (struct wpi_cmd_beacon *)cmd->data;
2420 	memset(bcn, 0, sizeof (struct wpi_cmd_beacon));
2421 	bcn->id = WPI_ID_BROADCAST;
2422 	bcn->ofdm_mask = 0xff;
2423 	bcn->cck_mask = 0x0f;
2424 	bcn->lifetime = htole32(WPI_LIFETIME_INFINITE);
2425 	bcn->len = htole16(m0->m_pkthdr.len);
2426 	bcn->rate = (ic->ic_curmode == IEEE80211_MODE_11A) ?
2427 		wpi_plcp_signal(12) : wpi_plcp_signal(2);
2428 	bcn->flags = htole32(WPI_TX_AUTO_SEQ | WPI_TX_INSERT_TSTAMP);
2429 
2430 	/* save and trim IEEE802.11 header */
2431 	m_copydata(m0, 0, sizeof (struct ieee80211_frame), (caddr_t)&bcn->wh);
2432 	m_adj(m0, sizeof (struct ieee80211_frame));
2433 
2434 	/* assume beacon frame is contiguous */
2435 	error = bus_dmamap_load(ring->data_dmat, data->map, mtod(m0, void *),
2436 	    m0->m_pkthdr.len, wpi_dma_map_addr, &physaddr, 0);
2437 	if (error != 0) {
2438 		device_printf(sc->sc_dev, "could not map beacon\n");
2439 		m_freem(m0);
2440 		return error;
2441 	}
2442 
2443 	data->m = m0;
2444 
2445 	/* first scatter/gather segment is used by the beacon command */
2446 	desc->flags = htole32(WPI_PAD32(m0->m_pkthdr.len) << 28 | 2 << 24);
2447 	desc->segs[0].addr = htole32(ring->cmd_dma.paddr +
2448 		ring->cur * sizeof (struct wpi_tx_cmd));
2449 	desc->segs[0].len  = htole32(4 + sizeof (struct wpi_cmd_beacon));
2450 	desc->segs[1].addr = htole32(physaddr);
2451 	desc->segs[1].len  = htole32(m0->m_pkthdr.len);
2452 
2453 	/* kick cmd ring */
2454 	ring->cur = (ring->cur + 1) % WPI_CMD_RING_COUNT;
2455 	WPI_WRITE(sc, WPI_TX_WIDX, ring->qid << 8 | ring->cur);
2456 
2457 	return 0;
2458 }
2459 #endif
2460 
2461 static int
2462 wpi_auth(struct wpi_softc *sc, struct ieee80211vap *vap)
2463 {
2464 	struct ieee80211com *ic = vap->iv_ic;
2465 	struct ieee80211_node *ni = vap->iv_bss;
2466 	struct wpi_node_info node;
2467 	int error;
2468 
2469 
2470 	/* update adapter's configuration */
2471 	sc->config.associd = 0;
2472 	sc->config.filter &= ~htole32(WPI_FILTER_BSS);
2473 	IEEE80211_ADDR_COPY(sc->config.bssid, ni->ni_bssid);
2474 	sc->config.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
2475 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) {
2476 		sc->config.flags |= htole32(WPI_CONFIG_AUTO |
2477 		    WPI_CONFIG_24GHZ);
2478 	}
2479 	if (IEEE80211_IS_CHAN_A(ni->ni_chan)) {
2480 		sc->config.cck_mask  = 0;
2481 		sc->config.ofdm_mask = 0x15;
2482 	} else if (IEEE80211_IS_CHAN_B(ni->ni_chan)) {
2483 		sc->config.cck_mask  = 0x03;
2484 		sc->config.ofdm_mask = 0;
2485 	} else {
2486 		/* XXX assume 802.11b/g */
2487 		sc->config.cck_mask  = 0x0f;
2488 		sc->config.ofdm_mask = 0x15;
2489 	}
2490 
2491 	DPRINTF(("config chan %d flags %x cck %x ofdm %x\n", sc->config.chan,
2492 		sc->config.flags, sc->config.cck_mask, sc->config.ofdm_mask));
2493 	error = wpi_cmd(sc, WPI_CMD_CONFIGURE, &sc->config,
2494 		sizeof (struct wpi_config), 1);
2495 	if (error != 0) {
2496 		device_printf(sc->sc_dev, "could not configure\n");
2497 		return error;
2498 	}
2499 
2500 	/* configuration has changed, set Tx power accordingly */
2501 	if ((error = wpi_set_txpower(sc, ni->ni_chan, 1)) != 0) {
2502 		device_printf(sc->sc_dev, "could not set Tx power\n");
2503 		return error;
2504 	}
2505 
2506 	/* add default node */
2507 	memset(&node, 0, sizeof node);
2508 	IEEE80211_ADDR_COPY(node.bssid, ni->ni_bssid);
2509 	node.id = WPI_ID_BSS;
2510 	node.rate = (ic->ic_curmode == IEEE80211_MODE_11A) ?
2511 	    wpi_plcp_signal(12) : wpi_plcp_signal(2);
2512 	node.action = htole32(WPI_ACTION_SET_RATE);
2513 	node.antenna = WPI_ANTENNA_BOTH;
2514 	error = wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, 1);
2515 	if (error != 0)
2516 		device_printf(sc->sc_dev, "could not add BSS node\n");
2517 
2518 	return (error);
2519 }
2520 
2521 static int
2522 wpi_run(struct wpi_softc *sc, struct ieee80211vap *vap)
2523 {
2524 	struct ieee80211com *ic = vap->iv_ic;
2525 	struct ieee80211_node *ni = vap->iv_bss;
2526 	int error;
2527 
2528 	if (vap->iv_opmode == IEEE80211_M_MONITOR) {
2529 		/* link LED blinks while monitoring */
2530 		wpi_set_led(sc, WPI_LED_LINK, 5, 5);
2531 		return 0;
2532 	}
2533 
2534 	wpi_enable_tsf(sc, ni);
2535 
2536 	/* update adapter's configuration */
2537 	sc->config.associd = htole16(ni->ni_associd & ~0xc000);
2538 	/* short preamble/slot time are negotiated when associating */
2539 	sc->config.flags &= ~htole32(WPI_CONFIG_SHPREAMBLE |
2540 	    WPI_CONFIG_SHSLOT);
2541 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
2542 		sc->config.flags |= htole32(WPI_CONFIG_SHSLOT);
2543 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
2544 		sc->config.flags |= htole32(WPI_CONFIG_SHPREAMBLE);
2545 	sc->config.filter |= htole32(WPI_FILTER_BSS);
2546 
2547 	/* XXX put somewhere HC_QOS_SUPPORT_ASSOC + HC_IBSS_START */
2548 
2549 	DPRINTF(("config chan %d flags %x\n", sc->config.chan,
2550 		    sc->config.flags));
2551 	error = wpi_cmd(sc, WPI_CMD_CONFIGURE, &sc->config, sizeof (struct
2552 		    wpi_config), 1);
2553 	if (error != 0) {
2554 		device_printf(sc->sc_dev, "could not update configuration\n");
2555 		return error;
2556 	}
2557 
2558 	error = wpi_set_txpower(sc, ni->ni_chan, 1);
2559 	if (error != 0) {
2560 		device_printf(sc->sc_dev, "could set txpower\n");
2561 		return error;
2562 	}
2563 
2564 	/* link LED always on while associated */
2565 	wpi_set_led(sc, WPI_LED_LINK, 0, 1);
2566 
2567 	/* start automatic rate control timer */
2568 	callout_reset(&sc->calib_to, 60*hz, wpi_calib_timeout, sc);
2569 
2570 	return (error);
2571 }
2572 
2573 /*
2574  * Send a scan request to the firmware.  Since this command is huge, we map it
2575  * into a mbufcluster instead of using the pre-allocated set of commands. Note,
2576  * much of this code is similar to that in wpi_cmd but because we must manually
2577  * construct the probe & channels, we duplicate what's needed here. XXX In the
2578  * future, this function should be modified to use wpi_cmd to help cleanup the
2579  * code base.
2580  */
2581 static int
2582 wpi_scan(struct wpi_softc *sc)
2583 {
2584 	struct ifnet *ifp = sc->sc_ifp;
2585 	struct ieee80211com *ic = ifp->if_l2com;
2586 	struct ieee80211_scan_state *ss = ic->ic_scan;
2587 	struct wpi_tx_ring *ring = &sc->cmdq;
2588 	struct wpi_tx_desc *desc;
2589 	struct wpi_tx_data *data;
2590 	struct wpi_tx_cmd *cmd;
2591 	struct wpi_scan_hdr *hdr;
2592 	struct wpi_scan_chan *chan;
2593 	struct ieee80211_frame *wh;
2594 	struct ieee80211_rateset *rs;
2595 	struct ieee80211_channel *c;
2596 	enum ieee80211_phymode mode;
2597 	uint8_t *frm;
2598 	int nrates, pktlen, error, i, nssid;
2599 	bus_addr_t physaddr;
2600 
2601 	desc = &ring->desc[ring->cur];
2602 	data = &ring->data[ring->cur];
2603 
2604 	data->m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2605 	if (data->m == NULL) {
2606 		device_printf(sc->sc_dev,
2607 		    "could not allocate mbuf for scan command\n");
2608 		return ENOMEM;
2609 	}
2610 
2611 	cmd = mtod(data->m, struct wpi_tx_cmd *);
2612 	cmd->code = WPI_CMD_SCAN;
2613 	cmd->flags = 0;
2614 	cmd->qid = ring->qid;
2615 	cmd->idx = ring->cur;
2616 
2617 	hdr = (struct wpi_scan_hdr *)cmd->data;
2618 	memset(hdr, 0, sizeof(struct wpi_scan_hdr));
2619 
2620 	/*
2621 	 * Move to the next channel if no packets are received within 5 msecs
2622 	 * after sending the probe request (this helps to reduce the duration
2623 	 * of active scans).
2624 	 */
2625 	hdr->quiet = htole16(5);
2626 	hdr->threshold = htole16(1);
2627 
2628 	if (IEEE80211_IS_CHAN_A(ic->ic_curchan)) {
2629 		/* send probe requests at 6Mbps */
2630 		hdr->tx.rate = wpi_ridx_to_plcp[WPI_OFDM6];
2631 
2632 		/* Enable crc checking */
2633 		hdr->promotion = htole16(1);
2634 	} else {
2635 		hdr->flags = htole32(WPI_CONFIG_24GHZ | WPI_CONFIG_AUTO);
2636 		/* send probe requests at 1Mbps */
2637 		hdr->tx.rate = wpi_ridx_to_plcp[WPI_CCK1];
2638 	}
2639 	hdr->tx.id = WPI_ID_BROADCAST;
2640 	hdr->tx.lifetime = htole32(WPI_LIFETIME_INFINITE);
2641 	hdr->tx.flags = htole32(WPI_TX_AUTO_SEQ);
2642 
2643 	memset(hdr->scan_essids, 0, sizeof(hdr->scan_essids));
2644 	nssid = MIN(ss->ss_nssid, WPI_SCAN_MAX_ESSIDS);
2645 	for (i = 0; i < nssid; i++) {
2646 		hdr->scan_essids[i].id = IEEE80211_ELEMID_SSID;
2647 		hdr->scan_essids[i].esslen = MIN(ss->ss_ssid[i].len, 32);
2648 		memcpy(hdr->scan_essids[i].essid, ss->ss_ssid[i].ssid,
2649 		    hdr->scan_essids[i].esslen);
2650 #ifdef WPI_DEBUG
2651 		if (wpi_debug & WPI_DEBUG_SCANNING) {
2652 			kprintf("Scanning Essid: ");
2653 			ieee80211_print_essid(hdr->scan_essids[i].essid,
2654 			    hdr->scan_essids[i].esslen);
2655 			kprintf("\n");
2656 		}
2657 #endif
2658 	}
2659 
2660 	/*
2661 	 * Build a probe request frame.  Most of the following code is a
2662 	 * copy & paste of what is done in net80211.
2663 	 */
2664 	wh = (struct ieee80211_frame *)&hdr->scan_essids[4];
2665 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
2666 		IEEE80211_FC0_SUBTYPE_PROBE_REQ;
2667 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
2668 	IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
2669 	IEEE80211_ADDR_COPY(wh->i_addr2, IF_LLADDR(ifp));
2670 	IEEE80211_ADDR_COPY(wh->i_addr3, ifp->if_broadcastaddr);
2671 	*(u_int16_t *)&wh->i_dur[0] = 0;	/* filled by h/w */
2672 	*(u_int16_t *)&wh->i_seq[0] = 0;	/* filled by h/w */
2673 
2674 	frm = (uint8_t *)(wh + 1);
2675 
2676 	/* add essid IE, the hardware will fill this in for us */
2677 	*frm++ = IEEE80211_ELEMID_SSID;
2678 	*frm++ = 0;
2679 
2680 	mode = ieee80211_chan2mode(ic->ic_curchan);
2681 	rs = &ic->ic_sup_rates[mode];
2682 
2683 	/* add supported rates IE */
2684 	*frm++ = IEEE80211_ELEMID_RATES;
2685 	nrates = rs->rs_nrates;
2686 	if (nrates > IEEE80211_RATE_SIZE)
2687 		nrates = IEEE80211_RATE_SIZE;
2688 	*frm++ = nrates;
2689 	memcpy(frm, rs->rs_rates, nrates);
2690 	frm += nrates;
2691 
2692 	/* add supported xrates IE */
2693 	if (rs->rs_nrates > IEEE80211_RATE_SIZE) {
2694 		nrates = rs->rs_nrates - IEEE80211_RATE_SIZE;
2695 		*frm++ = IEEE80211_ELEMID_XRATES;
2696 		*frm++ = nrates;
2697 		memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates);
2698 		frm += nrates;
2699 	}
2700 
2701 	/* setup length of probe request */
2702 	hdr->tx.len = htole16(frm - (uint8_t *)wh);
2703 
2704 	/*
2705 	 * Construct information about the channel that we
2706 	 * want to scan. The firmware expects this to be directly
2707 	 * after the scan probe request
2708 	 */
2709 	c = ic->ic_curchan;
2710 	chan = (struct wpi_scan_chan *)frm;
2711 	chan->chan = ieee80211_chan2ieee(ic, c);
2712 	chan->flags = 0;
2713 	if (!(c->ic_flags & IEEE80211_CHAN_PASSIVE)) {
2714 		chan->flags |= WPI_CHAN_ACTIVE;
2715 		if (nssid != 0)
2716 			chan->flags |= WPI_CHAN_DIRECT;
2717 	}
2718 	chan->gain_dsp = 0x6e; /* Default level */
2719 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
2720 		chan->active = htole16(10);
2721 		chan->passive = htole16(ss->ss_maxdwell);
2722 		chan->gain_radio = 0x3b;
2723 	} else {
2724 		chan->active = htole16(20);
2725 		chan->passive = htole16(ss->ss_maxdwell);
2726 		chan->gain_radio = 0x28;
2727 	}
2728 
2729 	DPRINTFN(WPI_DEBUG_SCANNING,
2730 	    ("Scanning %u Passive: %d\n",
2731 	     chan->chan,
2732 	     c->ic_flags & IEEE80211_CHAN_PASSIVE));
2733 
2734 	hdr->nchan++;
2735 	chan++;
2736 
2737 	frm += sizeof (struct wpi_scan_chan);
2738 #if 0
2739 	// XXX All Channels....
2740 	for (c  = &ic->ic_channels[1];
2741 	     c <= &ic->ic_channels[IEEE80211_CHAN_MAX]; c++) {
2742 		if ((c->ic_flags & ic->ic_curchan->ic_flags) != ic->ic_curchan->ic_flags)
2743 			continue;
2744 
2745 		chan->chan = ieee80211_chan2ieee(ic, c);
2746 		chan->flags = 0;
2747 		if (!(c->ic_flags & IEEE80211_CHAN_PASSIVE)) {
2748 		    chan->flags |= WPI_CHAN_ACTIVE;
2749 		    if (ic->ic_des_ssid[0].len != 0)
2750 			chan->flags |= WPI_CHAN_DIRECT;
2751 		}
2752 		chan->gain_dsp = 0x6e; /* Default level */
2753 		if (IEEE80211_IS_CHAN_5GHZ(c)) {
2754 			chan->active = htole16(10);
2755 			chan->passive = htole16(110);
2756 			chan->gain_radio = 0x3b;
2757 		} else {
2758 			chan->active = htole16(20);
2759 			chan->passive = htole16(120);
2760 			chan->gain_radio = 0x28;
2761 		}
2762 
2763 		DPRINTFN(WPI_DEBUG_SCANNING,
2764 			 ("Scanning %u Passive: %d\n",
2765 			  chan->chan,
2766 			  c->ic_flags & IEEE80211_CHAN_PASSIVE));
2767 
2768 		hdr->nchan++;
2769 		chan++;
2770 
2771 		frm += sizeof (struct wpi_scan_chan);
2772 	}
2773 #endif
2774 
2775 	hdr->len = htole16(frm - (uint8_t *)hdr);
2776 	pktlen = frm - (uint8_t *)cmd;
2777 
2778 	error = bus_dmamap_load(ring->data_dmat, data->map, cmd, pktlen,
2779 	    wpi_dma_map_addr, &physaddr, BUS_DMA_NOWAIT);
2780 	if (error != 0) {
2781 		device_printf(sc->sc_dev, "could not map scan command\n");
2782 		m_freem(data->m);
2783 		data->m = NULL;
2784 		return error;
2785 	}
2786 
2787 	desc->flags = htole32(WPI_PAD32(pktlen) << 28 | 1 << 24);
2788 	desc->segs[0].addr = htole32(physaddr);
2789 	desc->segs[0].len  = htole32(pktlen);
2790 
2791 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
2792 	    BUS_DMASYNC_PREWRITE);
2793 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
2794 
2795 	/* kick cmd ring */
2796 	ring->cur = (ring->cur + 1) % WPI_CMD_RING_COUNT;
2797 	WPI_WRITE(sc, WPI_TX_WIDX, ring->qid << 8 | ring->cur);
2798 
2799 	sc->sc_scan_timer = 5;
2800 	return 0;	/* will be notified async. of failure/success */
2801 }
2802 
2803 /**
2804  * Configure the card to listen to a particular channel, this transisions the
2805  * card in to being able to receive frames from remote devices.
2806  */
2807 static int
2808 wpi_config(struct wpi_softc *sc)
2809 {
2810 	struct ifnet *ifp = sc->sc_ifp;
2811 	struct ieee80211com *ic = ifp->if_l2com;
2812 	struct wpi_power power;
2813 	struct wpi_bluetooth bluetooth;
2814 	struct wpi_node_info node;
2815 	int error;
2816 
2817 	/* set power mode */
2818 	memset(&power, 0, sizeof power);
2819 	power.flags = htole32(WPI_POWER_CAM|0x8);
2820 	error = wpi_cmd(sc, WPI_CMD_SET_POWER_MODE, &power, sizeof power, 0);
2821 	if (error != 0) {
2822 		device_printf(sc->sc_dev, "could not set power mode\n");
2823 		return error;
2824 	}
2825 
2826 	/* configure bluetooth coexistence */
2827 	memset(&bluetooth, 0, sizeof bluetooth);
2828 	bluetooth.flags = 3;
2829 	bluetooth.lead = 0xaa;
2830 	bluetooth.kill = 1;
2831 	error = wpi_cmd(sc, WPI_CMD_BLUETOOTH, &bluetooth, sizeof bluetooth,
2832 	    0);
2833 	if (error != 0) {
2834 		device_printf(sc->sc_dev,
2835 		    "could not configure bluetooth coexistence\n");
2836 		return error;
2837 	}
2838 
2839 	/* configure adapter */
2840 	memset(&sc->config, 0, sizeof (struct wpi_config));
2841 	IEEE80211_ADDR_COPY(sc->config.myaddr, IF_LLADDR(ifp));
2842 	/*set default channel*/
2843 	sc->config.chan = htole16(ieee80211_chan2ieee(ic, ic->ic_curchan));
2844 	sc->config.flags = htole32(WPI_CONFIG_TSF);
2845 	if (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan)) {
2846 		sc->config.flags |= htole32(WPI_CONFIG_AUTO |
2847 		    WPI_CONFIG_24GHZ);
2848 	}
2849 	sc->config.filter = 0;
2850 	switch (ic->ic_opmode) {
2851 	case IEEE80211_M_STA:
2852 	case IEEE80211_M_WDS:	/* No know setup, use STA for now */
2853 		sc->config.mode = WPI_MODE_STA;
2854 		sc->config.filter |= htole32(WPI_FILTER_MULTICAST);
2855 		break;
2856 	case IEEE80211_M_IBSS:
2857 	case IEEE80211_M_AHDEMO:
2858 		sc->config.mode = WPI_MODE_IBSS;
2859 		sc->config.filter |= htole32(WPI_FILTER_BEACON |
2860 					     WPI_FILTER_MULTICAST);
2861 		break;
2862 	case IEEE80211_M_HOSTAP:
2863 		sc->config.mode = WPI_MODE_HOSTAP;
2864 		break;
2865 	case IEEE80211_M_MONITOR:
2866 		sc->config.mode = WPI_MODE_MONITOR;
2867 		sc->config.filter |= htole32(WPI_FILTER_MULTICAST |
2868 			WPI_FILTER_CTL | WPI_FILTER_PROMISC);
2869 		break;
2870 	default:
2871 		device_printf(sc->sc_dev, "unknown opmode %d\n", ic->ic_opmode);
2872 		return EINVAL;
2873 	}
2874 	sc->config.cck_mask  = 0x0f;	/* not yet negotiated */
2875 	sc->config.ofdm_mask = 0xff;	/* not yet negotiated */
2876 	error = wpi_cmd(sc, WPI_CMD_CONFIGURE, &sc->config,
2877 		sizeof (struct wpi_config), 0);
2878 	if (error != 0) {
2879 		device_printf(sc->sc_dev, "configure command failed\n");
2880 		return error;
2881 	}
2882 
2883 	/* configuration has changed, set Tx power accordingly */
2884 	if ((error = wpi_set_txpower(sc, ic->ic_curchan, 0)) != 0) {
2885 	    device_printf(sc->sc_dev, "could not set Tx power\n");
2886 	    return error;
2887 	}
2888 
2889 	/* add broadcast node */
2890 	memset(&node, 0, sizeof node);
2891 	IEEE80211_ADDR_COPY(node.bssid, ifp->if_broadcastaddr);
2892 	node.id = WPI_ID_BROADCAST;
2893 	node.rate = wpi_plcp_signal(2);
2894 	error = wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, 0);
2895 	if (error != 0) {
2896 		device_printf(sc->sc_dev, "could not add broadcast node\n");
2897 		return error;
2898 	}
2899 
2900 	/* Setup rate scalling */
2901 	error = wpi_mrr_setup(sc);
2902 	if (error != 0) {
2903 		device_printf(sc->sc_dev, "could not setup MRR\n");
2904 		return error;
2905 	}
2906 
2907 	return 0;
2908 }
2909 
2910 static void
2911 wpi_stop_master(struct wpi_softc *sc)
2912 {
2913 	uint32_t tmp;
2914 	int ntries;
2915 
2916 	DPRINTFN(WPI_DEBUG_HW,("Disabling Firmware execution\n"));
2917 
2918 	tmp = WPI_READ(sc, WPI_RESET);
2919 	WPI_WRITE(sc, WPI_RESET, tmp | WPI_STOP_MASTER | WPI_NEVO_RESET);
2920 
2921 	tmp = WPI_READ(sc, WPI_GPIO_CTL);
2922 	if ((tmp & WPI_GPIO_PWR_STATUS) == WPI_GPIO_PWR_SLEEP)
2923 		return;	/* already asleep */
2924 
2925 	for (ntries = 0; ntries < 100; ntries++) {
2926 		if (WPI_READ(sc, WPI_RESET) & WPI_MASTER_DISABLED)
2927 			break;
2928 		DELAY(10);
2929 	}
2930 	if (ntries == 100) {
2931 		device_printf(sc->sc_dev, "timeout waiting for master\n");
2932 	}
2933 }
2934 
2935 static int
2936 wpi_power_up(struct wpi_softc *sc)
2937 {
2938 	uint32_t tmp;
2939 	int ntries;
2940 
2941 	wpi_mem_lock(sc);
2942 	tmp = wpi_mem_read(sc, WPI_MEM_POWER);
2943 	wpi_mem_write(sc, WPI_MEM_POWER, tmp & ~0x03000000);
2944 	wpi_mem_unlock(sc);
2945 
2946 	for (ntries = 0; ntries < 5000; ntries++) {
2947 		if (WPI_READ(sc, WPI_GPIO_STATUS) & WPI_POWERED)
2948 			break;
2949 		DELAY(10);
2950 	}
2951 	if (ntries == 5000) {
2952 		device_printf(sc->sc_dev,
2953 		    "timeout waiting for NIC to power up\n");
2954 		return ETIMEDOUT;
2955 	}
2956 	return 0;
2957 }
2958 
2959 static int
2960 wpi_reset(struct wpi_softc *sc)
2961 {
2962 	uint32_t tmp;
2963 	int ntries;
2964 
2965 	DPRINTFN(WPI_DEBUG_HW,
2966 	    ("Resetting the card - clearing any uploaded firmware\n"));
2967 
2968 	/* clear any pending interrupts */
2969 	WPI_WRITE(sc, WPI_INTR, 0xffffffff);
2970 
2971 	tmp = WPI_READ(sc, WPI_PLL_CTL);
2972 	WPI_WRITE(sc, WPI_PLL_CTL, tmp | WPI_PLL_INIT);
2973 
2974 	tmp = WPI_READ(sc, WPI_CHICKEN);
2975 	WPI_WRITE(sc, WPI_CHICKEN, tmp | WPI_CHICKEN_RXNOLOS);
2976 
2977 	tmp = WPI_READ(sc, WPI_GPIO_CTL);
2978 	WPI_WRITE(sc, WPI_GPIO_CTL, tmp | WPI_GPIO_INIT);
2979 
2980 	/* wait for clock stabilization */
2981 	for (ntries = 0; ntries < 25000; ntries++) {
2982 		if (WPI_READ(sc, WPI_GPIO_CTL) & WPI_GPIO_CLOCK)
2983 			break;
2984 		DELAY(10);
2985 	}
2986 	if (ntries == 25000) {
2987 		device_printf(sc->sc_dev,
2988 		    "timeout waiting for clock stabilization\n");
2989 		return ETIMEDOUT;
2990 	}
2991 
2992 	/* initialize EEPROM */
2993 	tmp = WPI_READ(sc, WPI_EEPROM_STATUS);
2994 
2995 	if ((tmp & WPI_EEPROM_VERSION) == 0) {
2996 		device_printf(sc->sc_dev, "EEPROM not found\n");
2997 		return EIO;
2998 	}
2999 	WPI_WRITE(sc, WPI_EEPROM_STATUS, tmp & ~WPI_EEPROM_LOCKED);
3000 
3001 	return 0;
3002 }
3003 
3004 static void
3005 wpi_hw_config(struct wpi_softc *sc)
3006 {
3007 	uint32_t rev, hw;
3008 
3009 	/* voodoo from the Linux "driver".. */
3010 	hw = WPI_READ(sc, WPI_HWCONFIG);
3011 
3012 	rev = pci_read_config(sc->sc_dev, PCIR_REVID, 1);
3013 	if ((rev & 0xc0) == 0x40)
3014 		hw |= WPI_HW_ALM_MB;
3015 	else if (!(rev & 0x80))
3016 		hw |= WPI_HW_ALM_MM;
3017 
3018 	if (sc->cap == 0x80)
3019 		hw |= WPI_HW_SKU_MRC;
3020 
3021 	hw &= ~WPI_HW_REV_D;
3022 	if ((le16toh(sc->rev) & 0xf0) == 0xd0)
3023 		hw |= WPI_HW_REV_D;
3024 
3025 	if (sc->type > 1)
3026 		hw |= WPI_HW_TYPE_B;
3027 
3028 	WPI_WRITE(sc, WPI_HWCONFIG, hw);
3029 }
3030 
3031 static void
3032 wpi_rfkill_resume(struct wpi_softc *sc)
3033 {
3034 	struct ifnet *ifp = sc->sc_ifp;
3035 	struct ieee80211com *ic = ifp->if_l2com;
3036 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3037 	int ntries;
3038 
3039 	/* enable firmware again */
3040 	WPI_WRITE(sc, WPI_UCODE_CLR, WPI_RADIO_OFF);
3041 	WPI_WRITE(sc, WPI_UCODE_CLR, WPI_DISABLE_CMD);
3042 
3043 	/* wait for thermal sensors to calibrate */
3044 	for (ntries = 0; ntries < 1000; ntries++) {
3045 		if ((sc->temp = (int)WPI_READ(sc, WPI_TEMPERATURE)) != 0)
3046 			break;
3047 		DELAY(10);
3048 	}
3049 
3050 	if (ntries == 1000) {
3051 		device_printf(sc->sc_dev,
3052 		    "timeout waiting for thermal calibration\n");
3053 		WPI_UNLOCK(sc);
3054 		return;
3055 	}
3056 	DPRINTFN(WPI_DEBUG_TEMP,("temperature %d\n", sc->temp));
3057 
3058 	if (wpi_config(sc) != 0) {
3059 		device_printf(sc->sc_dev, "device config failed\n");
3060 		WPI_UNLOCK(sc);
3061 		return;
3062 	}
3063 
3064 	ifp->if_flags &= ~IFF_OACTIVE;
3065 	ifp->if_flags |= IFF_RUNNING;
3066 	sc->flags &= ~WPI_FLAG_HW_RADIO_OFF;
3067 
3068 	if (vap != NULL) {
3069 		if ((ic->ic_flags & IEEE80211_F_SCAN) == 0) {
3070 			if (vap->iv_opmode != IEEE80211_M_MONITOR) {
3071 				ieee80211_beacon_miss(ic);
3072 				wpi_set_led(sc, WPI_LED_LINK, 0, 1);
3073 			} else
3074 				wpi_set_led(sc, WPI_LED_LINK, 5, 5);
3075 		} else {
3076 			ieee80211_scan_next(vap);
3077 			wpi_set_led(sc, WPI_LED_LINK, 20, 2);
3078 		}
3079 	}
3080 
3081 	callout_reset(&sc->watchdog_to, hz, wpi_watchdog, sc);
3082 }
3083 
3084 static void
3085 wpi_init_locked(struct wpi_softc *sc, int force)
3086 {
3087 	struct ifnet *ifp = sc->sc_ifp;
3088 	uint32_t tmp;
3089 	int ntries, qid;
3090 
3091 	wpi_stop_locked(sc);
3092 	(void)wpi_reset(sc);
3093 
3094 	wpi_mem_lock(sc);
3095 	wpi_mem_write(sc, WPI_MEM_CLOCK1, 0xa00);
3096 	DELAY(20);
3097 	tmp = wpi_mem_read(sc, WPI_MEM_PCIDEV);
3098 	wpi_mem_write(sc, WPI_MEM_PCIDEV, tmp | 0x800);
3099 	wpi_mem_unlock(sc);
3100 
3101 	(void)wpi_power_up(sc);
3102 	wpi_hw_config(sc);
3103 
3104 	/* init Rx ring */
3105 	wpi_mem_lock(sc);
3106 	WPI_WRITE(sc, WPI_RX_BASE, sc->rxq.desc_dma.paddr);
3107 	WPI_WRITE(sc, WPI_RX_RIDX_PTR, sc->shared_dma.paddr +
3108 	    offsetof(struct wpi_shared, next));
3109 	WPI_WRITE(sc, WPI_RX_WIDX, (WPI_RX_RING_COUNT - 1) & ~7);
3110 	WPI_WRITE(sc, WPI_RX_CONFIG, 0xa9601010);
3111 	wpi_mem_unlock(sc);
3112 
3113 	/* init Tx rings */
3114 	wpi_mem_lock(sc);
3115 	wpi_mem_write(sc, WPI_MEM_MODE, 2); /* bypass mode */
3116 	wpi_mem_write(sc, WPI_MEM_RA, 1);   /* enable RA0 */
3117 	wpi_mem_write(sc, WPI_MEM_TXCFG, 0x3f); /* enable all 6 Tx rings */
3118 	wpi_mem_write(sc, WPI_MEM_BYPASS1, 0x10000);
3119 	wpi_mem_write(sc, WPI_MEM_BYPASS2, 0x30002);
3120 	wpi_mem_write(sc, WPI_MEM_MAGIC4, 4);
3121 	wpi_mem_write(sc, WPI_MEM_MAGIC5, 5);
3122 
3123 	WPI_WRITE(sc, WPI_TX_BASE_PTR, sc->shared_dma.paddr);
3124 	WPI_WRITE(sc, WPI_MSG_CONFIG, 0xffff05a5);
3125 
3126 	for (qid = 0; qid < 6; qid++) {
3127 		WPI_WRITE(sc, WPI_TX_CTL(qid), 0);
3128 		WPI_WRITE(sc, WPI_TX_BASE(qid), 0);
3129 		WPI_WRITE(sc, WPI_TX_CONFIG(qid), 0x80200008);
3130 	}
3131 	wpi_mem_unlock(sc);
3132 
3133 	/* clear "radio off" and "disable command" bits (reversed logic) */
3134 	WPI_WRITE(sc, WPI_UCODE_CLR, WPI_RADIO_OFF);
3135 	WPI_WRITE(sc, WPI_UCODE_CLR, WPI_DISABLE_CMD);
3136 	sc->flags &= ~WPI_FLAG_HW_RADIO_OFF;
3137 
3138 	/* clear any pending interrupts */
3139 	WPI_WRITE(sc, WPI_INTR, 0xffffffff);
3140 
3141 	/* enable interrupts */
3142 	WPI_WRITE(sc, WPI_MASK, WPI_INTR_MASK);
3143 
3144 	WPI_WRITE(sc, WPI_UCODE_CLR, WPI_RADIO_OFF);
3145 	WPI_WRITE(sc, WPI_UCODE_CLR, WPI_RADIO_OFF);
3146 
3147 	if ((wpi_load_firmware(sc)) != 0) {
3148 	    device_printf(sc->sc_dev,
3149 		"A problem occurred loading the firmware to the driver\n");
3150 	    return;
3151 	}
3152 
3153 	/* At this point the firmware is up and running. If the hardware
3154 	 * RF switch is turned off thermal calibration will fail, though
3155 	 * the card is still happy to continue to accept commands, catch
3156 	 * this case and schedule a task to watch for it to be turned on.
3157 	 */
3158 	wpi_mem_lock(sc);
3159 	tmp = wpi_mem_read(sc, WPI_MEM_HW_RADIO_OFF);
3160 	wpi_mem_unlock(sc);
3161 
3162 	if (!(tmp & 0x1)) {
3163 		sc->flags |= WPI_FLAG_HW_RADIO_OFF;
3164 		device_printf(sc->sc_dev,"Radio Transmitter is switched off\n");
3165 		goto out;
3166 	}
3167 
3168 	/* wait for thermal sensors to calibrate */
3169 	for (ntries = 0; ntries < 1000; ntries++) {
3170 		if ((sc->temp = (int)WPI_READ(sc, WPI_TEMPERATURE)) != 0)
3171 			break;
3172 		DELAY(10);
3173 	}
3174 
3175 	if (ntries == 1000) {
3176 		device_printf(sc->sc_dev,
3177 		    "timeout waiting for thermal sensors calibration\n");
3178 		return;
3179 	}
3180 	DPRINTFN(WPI_DEBUG_TEMP,("temperature %d\n", sc->temp));
3181 
3182 	if (wpi_config(sc) != 0) {
3183 		device_printf(sc->sc_dev, "device config failed\n");
3184 		return;
3185 	}
3186 
3187 	ifp->if_flags &= ~IFF_OACTIVE;
3188 	ifp->if_flags |= IFF_RUNNING;
3189 out:
3190 	callout_reset(&sc->watchdog_to, hz, wpi_watchdog, sc);
3191 }
3192 
3193 static void
3194 wpi_init(void *arg)
3195 {
3196 	struct wpi_softc *sc = arg;
3197 	struct ifnet *ifp = sc->sc_ifp;
3198 	struct ieee80211com *ic = ifp->if_l2com;
3199 
3200 	WPI_LOCK(sc);
3201 	wpi_init_locked(sc, 0);
3202 	WPI_UNLOCK(sc);
3203 
3204 	if (ifp->if_flags & IFF_RUNNING)
3205 		ieee80211_start_all(ic);		/* start all vaps */
3206 }
3207 
3208 static void
3209 wpi_stop_locked(struct wpi_softc *sc)
3210 {
3211 	struct ifnet *ifp = sc->sc_ifp;
3212 	uint32_t tmp;
3213 	int ac;
3214 
3215 	sc->sc_tx_timer = 0;
3216 	sc->sc_scan_timer = 0;
3217 	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
3218 	sc->flags &= ~WPI_FLAG_HW_RADIO_OFF;
3219 	callout_stop(&sc->watchdog_to);
3220 	callout_stop(&sc->calib_to);
3221 
3222 
3223 	/* disable interrupts */
3224 	WPI_WRITE(sc, WPI_MASK, 0);
3225 	WPI_WRITE(sc, WPI_INTR, WPI_INTR_MASK);
3226 	WPI_WRITE(sc, WPI_INTR_STATUS, 0xff);
3227 	WPI_WRITE(sc, WPI_INTR_STATUS, 0x00070000);
3228 
3229 	wpi_mem_lock(sc);
3230 	wpi_mem_write(sc, WPI_MEM_MODE, 0);
3231 	wpi_mem_unlock(sc);
3232 
3233 	/* reset all Tx rings */
3234 	for (ac = 0; ac < 4; ac++)
3235 		wpi_reset_tx_ring(sc, &sc->txq[ac]);
3236 	wpi_reset_tx_ring(sc, &sc->cmdq);
3237 
3238 	/* reset Rx ring */
3239 	wpi_reset_rx_ring(sc, &sc->rxq);
3240 
3241 	wpi_mem_lock(sc);
3242 	wpi_mem_write(sc, WPI_MEM_CLOCK2, 0x200);
3243 	wpi_mem_unlock(sc);
3244 
3245 	DELAY(5);
3246 
3247 	wpi_stop_master(sc);
3248 
3249 	tmp = WPI_READ(sc, WPI_RESET);
3250 	WPI_WRITE(sc, WPI_RESET, tmp | WPI_SW_RESET);
3251 	sc->flags &= ~WPI_FLAG_BUSY;
3252 }
3253 
3254 static void
3255 wpi_stop(struct wpi_softc *sc)
3256 {
3257 	WPI_LOCK(sc);
3258 	wpi_stop_locked(sc);
3259 	WPI_UNLOCK(sc);
3260 }
3261 
3262 static void
3263 wpi_newassoc(struct ieee80211_node *ni, int isnew)
3264 {
3265 	/* XXX move */
3266 	ieee80211_ratectl_node_init(ni);
3267 }
3268 
3269 static void
3270 wpi_calib_timeout(void *arg)
3271 {
3272 	struct wpi_softc *sc = arg;
3273 	struct ifnet *ifp = sc->sc_ifp;
3274 	struct ieee80211com *ic = ifp->if_l2com;
3275 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3276 	int temp;
3277 
3278 	if (vap->iv_state != IEEE80211_S_RUN)
3279 		return;
3280 
3281 	/* update sensor data */
3282 	temp = (int)WPI_READ(sc, WPI_TEMPERATURE);
3283 	DPRINTFN(WPI_DEBUG_TEMP,("Temp in calibration is: %d\n", temp));
3284 
3285 	wpi_power_calibration(sc, temp);
3286 
3287 	callout_reset(&sc->calib_to, 60*hz, wpi_calib_timeout, sc);
3288 }
3289 
3290 /*
3291  * This function is called periodically (every 60 seconds) to adjust output
3292  * power to temperature changes.
3293  */
3294 static void
3295 wpi_power_calibration(struct wpi_softc *sc, int temp)
3296 {
3297 	struct ifnet *ifp = sc->sc_ifp;
3298 	struct ieee80211com *ic = ifp->if_l2com;
3299 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3300 
3301 	/* sanity-check read value */
3302 	if (temp < -260 || temp > 25) {
3303 		/* this can't be correct, ignore */
3304 		DPRINTFN(WPI_DEBUG_TEMP,
3305 		    ("out-of-range temperature reported: %d\n", temp));
3306 		return;
3307 	}
3308 
3309 	DPRINTFN(WPI_DEBUG_TEMP,("temperature %d->%d\n", sc->temp, temp));
3310 
3311 	/* adjust Tx power if need be */
3312 	if (abs(temp - sc->temp) <= 6)
3313 		return;
3314 
3315 	sc->temp = temp;
3316 
3317 	if (wpi_set_txpower(sc, vap->iv_bss->ni_chan, 1) != 0) {
3318 		/* just warn, too bad for the automatic calibration... */
3319 		device_printf(sc->sc_dev,"could not adjust Tx power\n");
3320 	}
3321 }
3322 
3323 /**
3324  * Read the eeprom to find out what channels are valid for the given
3325  * band and update net80211 with what we find.
3326  */
3327 static void
3328 wpi_read_eeprom_channels(struct wpi_softc *sc, int n)
3329 {
3330 	struct ifnet *ifp = sc->sc_ifp;
3331 	struct ieee80211com *ic = ifp->if_l2com;
3332 	const struct wpi_chan_band *band = &wpi_bands[n];
3333 	struct wpi_eeprom_chan channels[WPI_MAX_CHAN_PER_BAND];
3334 	struct ieee80211_channel *c;
3335 	int chan, i, passive;
3336 
3337 	wpi_read_prom_data(sc, band->addr, channels,
3338 	    band->nchan * sizeof (struct wpi_eeprom_chan));
3339 
3340 	for (i = 0; i < band->nchan; i++) {
3341 		if (!(channels[i].flags & WPI_EEPROM_CHAN_VALID)) {
3342 			DPRINTFN(WPI_DEBUG_HW,
3343 			    ("Channel Not Valid: %d, band %d\n",
3344 			     band->chan[i],n));
3345 			continue;
3346 		}
3347 
3348 		passive = 0;
3349 		chan = band->chan[i];
3350 		c = &ic->ic_channels[ic->ic_nchans++];
3351 
3352 		/* is active scan allowed on this channel? */
3353 		if (!(channels[i].flags & WPI_EEPROM_CHAN_ACTIVE)) {
3354 			passive = IEEE80211_CHAN_PASSIVE;
3355 		}
3356 
3357 		if (n == 0) {	/* 2GHz band */
3358 			c->ic_ieee = chan;
3359 			c->ic_freq = ieee80211_ieee2mhz(chan,
3360 			    IEEE80211_CHAN_2GHZ);
3361 			c->ic_flags = IEEE80211_CHAN_B | passive;
3362 
3363 			c = &ic->ic_channels[ic->ic_nchans++];
3364 			c->ic_ieee = chan;
3365 			c->ic_freq = ieee80211_ieee2mhz(chan,
3366 			    IEEE80211_CHAN_2GHZ);
3367 			c->ic_flags = IEEE80211_CHAN_G | passive;
3368 
3369 		} else {	/* 5GHz band */
3370 			/*
3371 			 * Some 3945ABG adapters support channels 7, 8, 11
3372 			 * and 12 in the 2GHz *and* 5GHz bands.
3373 			 * Because of limitations in our net80211(9) stack,
3374 			 * we can't support these channels in 5GHz band.
3375 			 * XXX not true; just need to map to proper frequency
3376 			 */
3377 			if (chan <= 14)
3378 				continue;
3379 
3380 			c->ic_ieee = chan;
3381 			c->ic_freq = ieee80211_ieee2mhz(chan,
3382 			    IEEE80211_CHAN_5GHZ);
3383 			c->ic_flags = IEEE80211_CHAN_A | passive;
3384 		}
3385 
3386 		/* save maximum allowed power for this channel */
3387 		sc->maxpwr[chan] = channels[i].maxpwr;
3388 
3389 #if 0
3390 		// XXX We can probably use this an get rid of maxpwr - ben 20070617
3391 		ic->ic_channels[chan].ic_maxpower = channels[i].maxpwr;
3392 		//ic->ic_channels[chan].ic_minpower...
3393 		//ic->ic_channels[chan].ic_maxregtxpower...
3394 #endif
3395 
3396 		DPRINTF(("adding chan %d (%dMHz) flags=0x%x maxpwr=%d"
3397 		    " passive=%d, offset %d\n", chan, c->ic_freq,
3398 		    channels[i].flags, sc->maxpwr[chan],
3399 		    (c->ic_flags & IEEE80211_CHAN_PASSIVE) != 0,
3400 		    ic->ic_nchans));
3401 	}
3402 }
3403 
3404 static void
3405 wpi_read_eeprom_group(struct wpi_softc *sc, int n)
3406 {
3407 	struct wpi_power_group *group = &sc->groups[n];
3408 	struct wpi_eeprom_group rgroup;
3409 	int i;
3410 
3411 	wpi_read_prom_data(sc, WPI_EEPROM_POWER_GRP + n * 32, &rgroup,
3412 	    sizeof rgroup);
3413 
3414 	/* save power group information */
3415 	group->chan   = rgroup.chan;
3416 	group->maxpwr = rgroup.maxpwr;
3417 	/* temperature at which the samples were taken */
3418 	group->temp   = (int16_t)le16toh(rgroup.temp);
3419 
3420 	DPRINTF(("power group %d: chan=%d maxpwr=%d temp=%d\n", n,
3421 		    group->chan, group->maxpwr, group->temp));
3422 
3423 	for (i = 0; i < WPI_SAMPLES_COUNT; i++) {
3424 		group->samples[i].index = rgroup.samples[i].index;
3425 		group->samples[i].power = rgroup.samples[i].power;
3426 
3427 		DPRINTF(("\tsample %d: index=%d power=%d\n", i,
3428 			    group->samples[i].index, group->samples[i].power));
3429 	}
3430 }
3431 
3432 /*
3433  * Update Tx power to match what is defined for channel `c'.
3434  */
3435 static int
3436 wpi_set_txpower(struct wpi_softc *sc, struct ieee80211_channel *c, int async)
3437 {
3438 	struct ifnet *ifp = sc->sc_ifp;
3439 	struct ieee80211com *ic = ifp->if_l2com;
3440 	struct wpi_power_group *group;
3441 	struct wpi_cmd_txpower txpower;
3442 	u_int chan;
3443 	int i;
3444 
3445 	/* get channel number */
3446 	chan = ieee80211_chan2ieee(ic, c);
3447 
3448 	/* find the power group to which this channel belongs */
3449 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
3450 		for (group = &sc->groups[1]; group < &sc->groups[4]; group++)
3451 			if (chan <= group->chan)
3452 				break;
3453 	} else
3454 		group = &sc->groups[0];
3455 
3456 	memset(&txpower, 0, sizeof txpower);
3457 	txpower.band = IEEE80211_IS_CHAN_5GHZ(c) ? 0 : 1;
3458 	txpower.channel = htole16(chan);
3459 
3460 	/* set Tx power for all OFDM and CCK rates */
3461 	for (i = 0; i <= 11 ; i++) {
3462 		/* retrieve Tx power for this channel/rate combination */
3463 		int idx = wpi_get_power_index(sc, group, c,
3464 		    wpi_ridx_to_rate[i]);
3465 
3466 		txpower.rates[i].rate = wpi_ridx_to_plcp[i];
3467 
3468 		if (IEEE80211_IS_CHAN_5GHZ(c)) {
3469 			txpower.rates[i].gain_radio = wpi_rf_gain_5ghz[idx];
3470 			txpower.rates[i].gain_dsp = wpi_dsp_gain_5ghz[idx];
3471 		} else {
3472 			txpower.rates[i].gain_radio = wpi_rf_gain_2ghz[idx];
3473 			txpower.rates[i].gain_dsp = wpi_dsp_gain_2ghz[idx];
3474 		}
3475 		DPRINTFN(WPI_DEBUG_TEMP,("chan %d/rate %d: power index %d\n",
3476 			    chan, wpi_ridx_to_rate[i], idx));
3477 	}
3478 
3479 	return wpi_cmd(sc, WPI_CMD_TXPOWER, &txpower, sizeof txpower, async);
3480 }
3481 
3482 /*
3483  * Determine Tx power index for a given channel/rate combination.
3484  * This takes into account the regulatory information from EEPROM and the
3485  * current temperature.
3486  */
3487 static int
3488 wpi_get_power_index(struct wpi_softc *sc, struct wpi_power_group *group,
3489     struct ieee80211_channel *c, int rate)
3490 {
3491 /* fixed-point arithmetic division using a n-bit fractional part */
3492 #define fdivround(a, b, n)      \
3493 	((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
3494 
3495 /* linear interpolation */
3496 #define interpolate(x, x1, y1, x2, y2, n)       \
3497 	((y1) + fdivround(((x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
3498 
3499 	struct ifnet *ifp = sc->sc_ifp;
3500 	struct ieee80211com *ic = ifp->if_l2com;
3501 	struct wpi_power_sample *sample;
3502 	int pwr, idx;
3503 	u_int chan;
3504 
3505 	/* get channel number */
3506 	chan = ieee80211_chan2ieee(ic, c);
3507 
3508 	/* default power is group's maximum power - 3dB */
3509 	pwr = group->maxpwr / 2;
3510 
3511 	/* decrease power for highest OFDM rates to reduce distortion */
3512 	switch (rate) {
3513 		case 72:	/* 36Mb/s */
3514 			pwr -= IEEE80211_IS_CHAN_2GHZ(c) ? 0 :  5;
3515 			break;
3516 		case 96:	/* 48Mb/s */
3517 			pwr -= IEEE80211_IS_CHAN_2GHZ(c) ? 7 : 10;
3518 			break;
3519 		case 108:	/* 54Mb/s */
3520 			pwr -= IEEE80211_IS_CHAN_2GHZ(c) ? 9 : 12;
3521 			break;
3522 	}
3523 
3524 	/* never exceed channel's maximum allowed Tx power */
3525 	pwr = min(pwr, sc->maxpwr[chan]);
3526 
3527 	/* retrieve power index into gain tables from samples */
3528 	for (sample = group->samples; sample < &group->samples[3]; sample++)
3529 		if (pwr > sample[1].power)
3530 			break;
3531 	/* fixed-point linear interpolation using a 19-bit fractional part */
3532 	idx = interpolate(pwr, sample[0].power, sample[0].index,
3533 	    sample[1].power, sample[1].index, 19);
3534 
3535 	/*
3536 	 *  Adjust power index based on current temperature
3537 	 *	- if colder than factory-calibrated: decreate output power
3538 	 *	- if warmer than factory-calibrated: increase output power
3539 	 */
3540 	idx -= (sc->temp - group->temp) * 11 / 100;
3541 
3542 	/* decrease power for CCK rates (-5dB) */
3543 	if (!WPI_RATE_IS_OFDM(rate))
3544 		idx += 10;
3545 
3546 	/* keep power index in a valid range */
3547 	if (idx < 0)
3548 		return 0;
3549 	if (idx > WPI_MAX_PWR_INDEX)
3550 		return WPI_MAX_PWR_INDEX;
3551 	return idx;
3552 
3553 #undef interpolate
3554 #undef fdivround
3555 }
3556 
3557 /**
3558  * Called by net80211 framework to indicate that a scan
3559  * is starting. This function doesn't actually do the scan,
3560  * wpi_scan_curchan starts things off. This function is more
3561  * of an early warning from the framework we should get ready
3562  * for the scan.
3563  */
3564 static void
3565 wpi_scan_start(struct ieee80211com *ic)
3566 {
3567 	struct ifnet *ifp = ic->ic_ifp;
3568 	struct wpi_softc *sc = ifp->if_softc;
3569 
3570 	WPI_LOCK(sc);
3571 	wpi_set_led(sc, WPI_LED_LINK, 20, 2);
3572 	WPI_UNLOCK(sc);
3573 }
3574 
3575 /**
3576  * Called by the net80211 framework, indicates that the
3577  * scan has ended. If there is a scan in progress on the card
3578  * then it should be aborted.
3579  */
3580 static void
3581 wpi_scan_end(struct ieee80211com *ic)
3582 {
3583 	/* XXX ignore */
3584 }
3585 
3586 /**
3587  * Called by the net80211 framework to indicate to the driver
3588  * that the channel should be changed
3589  */
3590 static void
3591 wpi_set_channel(struct ieee80211com *ic)
3592 {
3593 	struct ifnet *ifp = ic->ic_ifp;
3594 	struct wpi_softc *sc = ifp->if_softc;
3595 	int error;
3596 
3597 	/*
3598 	 * Only need to set the channel in Monitor mode. AP scanning and auth
3599 	 * are already taken care of by their respective firmware commands.
3600 	 */
3601 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
3602 		error = wpi_config(sc);
3603 		if (error != 0)
3604 			device_printf(sc->sc_dev,
3605 			    "error %d settting channel\n", error);
3606 	}
3607 }
3608 
3609 /**
3610  * Called by net80211 to indicate that we need to scan the current
3611  * channel. The channel is previously be set via the wpi_set_channel
3612  * callback.
3613  */
3614 static void
3615 wpi_scan_curchan(struct ieee80211_scan_state *ss, unsigned long maxdwell)
3616 {
3617 	struct ieee80211vap *vap = ss->ss_vap;
3618 	struct ifnet *ifp = vap->iv_ic->ic_ifp;
3619 	struct wpi_softc *sc = ifp->if_softc;
3620 
3621 	WPI_LOCK(sc);
3622 	if (wpi_scan(sc))
3623 		ieee80211_cancel_scan(vap);
3624 	WPI_UNLOCK(sc);
3625 }
3626 
3627 /**
3628  * Called by the net80211 framework to indicate
3629  * the minimum dwell time has been met, terminate the scan.
3630  * We don't actually terminate the scan as the firmware will notify
3631  * us when it's finished and we have no way to interrupt it.
3632  */
3633 static void
3634 wpi_scan_mindwell(struct ieee80211_scan_state *ss)
3635 {
3636 	/* NB: don't try to abort scan; wait for firmware to finish */
3637 }
3638 
3639 static void
3640 wpi_hwreset(void *arg, int pending)
3641 {
3642 	struct wpi_softc *sc = arg;
3643 
3644 	WPI_LOCK(sc);
3645 	wpi_init_locked(sc, 0);
3646 	WPI_UNLOCK(sc);
3647 }
3648 
3649 static void
3650 wpi_rfreset(void *arg, int pending)
3651 {
3652 	struct wpi_softc *sc = arg;
3653 
3654 	WPI_LOCK(sc);
3655 	wpi_rfkill_resume(sc);
3656 	WPI_UNLOCK(sc);
3657 }
3658 
3659 /*
3660  * Allocate DMA-safe memory for firmware transfer.
3661  */
3662 static int
3663 wpi_alloc_fwmem(struct wpi_softc *sc)
3664 {
3665 	/* allocate enough contiguous space to store text and data */
3666 	return wpi_dma_contig_alloc(sc, &sc->fw_dma, NULL,
3667 	    WPI_FW_MAIN_TEXT_MAXSZ + WPI_FW_MAIN_DATA_MAXSZ, 1,
3668 	    BUS_DMA_NOWAIT);
3669 }
3670 
3671 static void
3672 wpi_free_fwmem(struct wpi_softc *sc)
3673 {
3674 	wpi_dma_contig_free(&sc->fw_dma);
3675 }
3676 
3677 /**
3678  * Called every second, wpi_watchdog used by the watch dog timer
3679  * to check that the card is still alive
3680  */
3681 static void
3682 wpi_watchdog(void *arg)
3683 {
3684 	struct wpi_softc *sc = arg;
3685 	struct ifnet *ifp = sc->sc_ifp;
3686 	struct ieee80211com *ic = ifp->if_l2com;
3687 	uint32_t tmp;
3688 
3689 	DPRINTFN(WPI_DEBUG_WATCHDOG,("Watchdog: tick\n"));
3690 
3691 	if (sc->flags & WPI_FLAG_HW_RADIO_OFF) {
3692 		/* No need to lock firmware memory */
3693 		tmp = wpi_mem_read(sc, WPI_MEM_HW_RADIO_OFF);
3694 
3695 		if ((tmp & 0x1) == 0) {
3696 			/* Radio kill switch is still off */
3697 			callout_reset(&sc->watchdog_to, hz, wpi_watchdog, sc);
3698 			return;
3699 		}
3700 
3701 		device_printf(sc->sc_dev, "Hardware Switch Enabled\n");
3702 		ieee80211_runtask(ic, &sc->sc_radiotask);
3703 		return;
3704 	}
3705 
3706 	if (sc->sc_tx_timer > 0) {
3707 		if (--sc->sc_tx_timer == 0) {
3708 			device_printf(sc->sc_dev,"device timeout\n");
3709 			ifp->if_oerrors++;
3710 			ieee80211_runtask(ic, &sc->sc_restarttask);
3711 		}
3712 	}
3713 	if (sc->sc_scan_timer > 0) {
3714 		struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3715 		if (--sc->sc_scan_timer == 0 && vap != NULL) {
3716 			device_printf(sc->sc_dev,"scan timeout\n");
3717 			ieee80211_cancel_scan(vap);
3718 			ieee80211_runtask(ic, &sc->sc_restarttask);
3719 		}
3720 	}
3721 
3722 	if (ifp->if_flags & IFF_RUNNING)
3723 		callout_reset(&sc->watchdog_to, hz, wpi_watchdog, sc);
3724 }
3725 
3726 #ifdef WPI_DEBUG
3727 static const char *wpi_cmd_str(int cmd)
3728 {
3729 	switch (cmd) {
3730 	case WPI_DISABLE_CMD:	return "WPI_DISABLE_CMD";
3731 	case WPI_CMD_CONFIGURE:	return "WPI_CMD_CONFIGURE";
3732 	case WPI_CMD_ASSOCIATE:	return "WPI_CMD_ASSOCIATE";
3733 	case WPI_CMD_SET_WME:	return "WPI_CMD_SET_WME";
3734 	case WPI_CMD_TSF:	return "WPI_CMD_TSF";
3735 	case WPI_CMD_ADD_NODE:	return "WPI_CMD_ADD_NODE";
3736 	case WPI_CMD_TX_DATA:	return "WPI_CMD_TX_DATA";
3737 	case WPI_CMD_MRR_SETUP:	return "WPI_CMD_MRR_SETUP";
3738 	case WPI_CMD_SET_LED:	return "WPI_CMD_SET_LED";
3739 	case WPI_CMD_SET_POWER_MODE: return "WPI_CMD_SET_POWER_MODE";
3740 	case WPI_CMD_SCAN:	return "WPI_CMD_SCAN";
3741 	case WPI_CMD_SET_BEACON:return "WPI_CMD_SET_BEACON";
3742 	case WPI_CMD_TXPOWER:	return "WPI_CMD_TXPOWER";
3743 	case WPI_CMD_BLUETOOTH:	return "WPI_CMD_BLUETOOTH";
3744 
3745 	default:
3746 		KASSERT(1, ("Unknown Command: %d\n", cmd));
3747 		return "UNKNOWN CMD";	/* Make the compiler happy */
3748 	}
3749 }
3750 #endif
3751 
3752 MODULE_DEPEND(wpi, pci,  1, 1, 1);
3753 MODULE_DEPEND(wpi, wlan, 1, 1, 1);
3754 MODULE_DEPEND(wpi, firmware, 1, 1, 1);
3755 MODULE_DEPEND(wpi, wlan_amrr, 1, 1, 1);
3756 /*
3757 MODULE_DEPEND(wpi, wpifw_fw_fw, 1, 1, 1);
3758 MODULE_DEPEND(wpi, ath_rate, 1, 1, 1);
3759 */
3760