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