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