xref: /titanic_44/usr/src/uts/common/io/ath/ath_main.c (revision 94501b61e12c24a6ea3abf427022ca0d4a302f3b)
1 /*
2  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  */
5 
6 /*
7  * Copyright (c) 2002-2004 Sam Leffler, Errno Consulting
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer,
15  * without modification.
16  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
17  * similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
18  * redistribution must be conditioned upon including a substantially
19  * similar Disclaimer requirement for further binary redistribution.
20  * 3. Neither the names of the above-listed copyright holders nor the names
21  * of any contributors may be used to endorse or promote products derived
22  * from this software without specific prior written permission.
23  *
24  * NO WARRANTY
25  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27  * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
28  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
29  * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
30  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
33  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
35  * THE POSSIBILITY OF SUCH DAMAGES.
36  *
37  */
38 
39 #pragma ident	"%Z%%M%	%I%	%E% SMI"
40 
41 /*
42  * Driver for the Atheros Wireless LAN controller.
43  *
44  * The Atheros driver calls into net80211 module for IEEE80211 protocol
45  * management functionalities. The driver includes a LLD(Low Level Driver)
46  * part to implement H/W related operations.
47  * The following is the high level structure of ath driver.
48  * (The arrows between modules indicate function call direction.)
49  *
50  *
51  *                                                  |
52  *                                                  | GLD thread
53  *                                                  V
54  *         ==================  =========================================
55  *         |                |  |[1]                                    |
56  *         |                |  |  GLDv3 Callback functions registered  |
57  *         |   Net80211     |  =========================       by      |
58  *         |    module      |          |               |     driver    |
59  *         |                |          V               |               |
60  *         |                |========================  |               |
61  *         |   Functions exported by net80211       |  |               |
62  *         |                                        |  |               |
63  *         ==========================================  =================
64  *                         |                                  |
65  *                         V                                  |
66  *         +----------------------------------+               |
67  *         |[2]                               |               |
68  *         |    Net80211 Callback functions   |               |
69  *         |      registered by LLD           |               |
70  *         +----------------------------------+               |
71  *                         |                                  |
72  *                         V                                  v
73  *         +-----------------------------------------------------------+
74  *         |[3]                                                        |
75  *         |                LLD Internal functions                     |
76  *         |                                                           |
77  *         +-----------------------------------------------------------+
78  *                                    ^
79  *                                    | Software interrupt thread
80  *                                    |
81  *
82  * The short description of each module is as below:
83  *      Module 1: GLD callback functions, which are intercepting the calls from
84  *                GLD to LLD.
85  *      Module 2: Net80211 callback functions registered by LLD, which
86  *                calls into LLD for H/W related functions needed by net80211.
87  *      Module 3: LLD Internal functions, which are responsible for allocing
88  *                descriptor/buffer, handling interrupt and other H/W
89  *                operations.
90  *
91  * All functions are running in 3 types of thread:
92  * 1. GLD callbacks threads, such as ioctl, intr, etc.
93  * 2. Clock interruptt thread which is responsible for scan, rate control and
94  *    calibration.
95  * 3. Software Interrupt thread originated in LLD.
96  *
97  * The lock strategy is as below:
98  * There have 4 queues for tx, each queue has one asc_txqlock[i] to
99  *      prevent conflicts access to queue resource from different thread.
100  *
101  * All the transmit buffers are contained in asc_txbuf which are
102  *      protected by asc_txbuflock.
103  *
104  * Each receive buffers are contained in asc_rxbuf which are protected
105  *      by asc_rxbuflock.
106  *
107  * In ath struct, asc_genlock is a general lock, protecting most other
108  *      operational data in ath_softc struct and HAL accesses.
109  *      It is acquired by the interupt handler and most "mode-ctrl" routines.
110  *
111  * Any of the locks can be acquired singly, but where multiple
112  * locks are acquired, they *must* be in the order:
113  *    asc_genlock >> asc_txqlock[i] >> asc_txbuflock >> asc_rxbuflock
114  */
115 
116 #include <sys/param.h>
117 #include <sys/types.h>
118 #include <sys/signal.h>
119 #include <sys/stream.h>
120 #include <sys/termio.h>
121 #include <sys/errno.h>
122 #include <sys/file.h>
123 #include <sys/cmn_err.h>
124 #include <sys/stropts.h>
125 #include <sys/strsubr.h>
126 #include <sys/strtty.h>
127 #include <sys/kbio.h>
128 #include <sys/cred.h>
129 #include <sys/stat.h>
130 #include <sys/consdev.h>
131 #include <sys/kmem.h>
132 #include <sys/modctl.h>
133 #include <sys/ddi.h>
134 #include <sys/sunddi.h>
135 #include <sys/pci.h>
136 #include <sys/errno.h>
137 #include <sys/mac.h>
138 #include <sys/dlpi.h>
139 #include <sys/ethernet.h>
140 #include <sys/list.h>
141 #include <sys/byteorder.h>
142 #include <sys/strsun.h>
143 #include <sys/policy.h>
144 #include <inet/common.h>
145 #include <inet/nd.h>
146 #include <inet/mi.h>
147 #include <inet/wifi_ioctl.h>
148 #include <sys/mac_wifi.h>
149 #include "ath_hal.h"
150 #include "ath_impl.h"
151 #include "ath_aux.h"
152 #include "ath_rate.h"
153 
154 #define	ATH_MAX_RSSI	63	/* max rssi */
155 
156 extern void ath_halfix_init(void);
157 extern void ath_halfix_finit(void);
158 extern int32_t ath_getset(ath_t *asc, mblk_t *mp, uint32_t cmd);
159 
160 /*
161  * PIO access attributes for registers
162  */
163 static ddi_device_acc_attr_t ath_reg_accattr = {
164 	DDI_DEVICE_ATTR_V0,
165 	DDI_STRUCTURE_LE_ACC,
166 	DDI_STRICTORDER_ACC
167 };
168 
169 /*
170  * DMA access attributes for descriptors: NOT to be byte swapped.
171  */
172 static ddi_device_acc_attr_t ath_desc_accattr = {
173 	DDI_DEVICE_ATTR_V0,
174 	DDI_STRUCTURE_LE_ACC,
175 	DDI_STRICTORDER_ACC
176 };
177 
178 /*
179  * Describes the chip's DMA engine
180  */
181 static ddi_dma_attr_t dma_attr = {
182 	DMA_ATTR_V0,			/* dma_attr version */
183 	0x0000000000000000ull,		/* dma_attr_addr_lo */
184 	0xFFFFFFFFFFFFFFFFull,		/* dma_attr_addr_hi */
185 	0x00000000FFFFFFFFull,		/* dma_attr_count_max */
186 	0x0000000000000001ull,		/* dma_attr_align */
187 	0x00000FFF,			/* dma_attr_burstsizes */
188 	0x00000001,			/* dma_attr_minxfer */
189 	0x000000000000FFFFull,		/* dma_attr_maxxfer */
190 	0xFFFFFFFFFFFFFFFFull,		/* dma_attr_seg */
191 	1,				/* dma_attr_sgllen */
192 	0x00000001,			/* dma_attr_granular */
193 	0				/* dma_attr_flags */
194 };
195 
196 static kmutex_t ath_loglock;
197 static void *ath_soft_state_p = NULL;
198 static int ath_dwelltime = 150;		/* scan interval, ms */
199 
200 static int	ath_m_stat(void *,  uint_t, uint64_t *);
201 static int	ath_m_start(void *);
202 static void	ath_m_stop(void *);
203 static int	ath_m_promisc(void *, boolean_t);
204 static int	ath_m_multicst(void *, boolean_t, const uint8_t *);
205 static int	ath_m_unicst(void *, const uint8_t *);
206 static mblk_t	*ath_m_tx(void *, mblk_t *);
207 static void	ath_m_ioctl(void *, queue_t *, mblk_t *);
208 static mac_callbacks_t ath_m_callbacks = {
209 	MC_IOCTL,
210 	ath_m_stat,
211 	ath_m_start,
212 	ath_m_stop,
213 	ath_m_promisc,
214 	ath_m_multicst,
215 	ath_m_unicst,
216 	ath_m_tx,
217 	NULL,		/* mc_resources; */
218 	ath_m_ioctl,
219 	NULL		/* mc_getcapab */
220 };
221 
222 /*
223  * Available debug flags:
224  * ATH_DBG_INIT, ATH_DBG_GLD, ATH_DBG_HAL, ATH_DBG_INT, ATH_DBG_ATTACH,
225  * ATH_DBG_DETACH, ATH_DBG_AUX, ATH_DBG_WIFICFG, ATH_DBG_OSDEP
226  */
227 uint32_t ath_dbg_flags = 0;
228 
229 /*
230  * Exception/warning cases not leading to panic.
231  */
232 void
233 ath_problem(const int8_t *fmt, ...)
234 {
235 	va_list args;
236 
237 	mutex_enter(&ath_loglock);
238 
239 	va_start(args, fmt);
240 	vcmn_err(CE_WARN, fmt, args);
241 	va_end(args);
242 
243 	mutex_exit(&ath_loglock);
244 }
245 
246 /*
247  * Normal log information independent of debug.
248  */
249 void
250 ath_log(const int8_t *fmt, ...)
251 {
252 	va_list args;
253 
254 	mutex_enter(&ath_loglock);
255 
256 	va_start(args, fmt);
257 	vcmn_err(CE_CONT, fmt, args);
258 	va_end(args);
259 
260 	mutex_exit(&ath_loglock);
261 }
262 
263 void
264 ath_dbg(uint32_t dbg_flags, const int8_t *fmt, ...)
265 {
266 	va_list args;
267 
268 	if (dbg_flags & ath_dbg_flags) {
269 		mutex_enter(&ath_loglock);
270 		va_start(args, fmt);
271 		vcmn_err(CE_CONT, fmt, args);
272 		va_end(args);
273 		mutex_exit(&ath_loglock);
274 	}
275 }
276 
277 void
278 ath_setup_desc(ath_t *asc, struct ath_buf *bf)
279 {
280 	struct ath_desc *ds;
281 
282 	ds = bf->bf_desc;
283 	ds->ds_link = bf->bf_daddr;
284 	ds->ds_data = bf->bf_dma.cookie.dmac_address;
285 	ds->ds_vdata = bf->bf_dma.mem_va;
286 	ATH_HAL_SETUPRXDESC(asc->asc_ah, ds,
287 	    bf->bf_dma.alength,		/* buffer size */
288 	    0);
289 
290 	if (asc->asc_rxlink != NULL)
291 		*asc->asc_rxlink = bf->bf_daddr;
292 	asc->asc_rxlink = &ds->ds_link;
293 }
294 
295 
296 /*
297  * Allocate an area of memory and a DMA handle for accessing it
298  */
299 static int
300 ath_alloc_dma_mem(dev_info_t *devinfo, size_t memsize,
301 	ddi_device_acc_attr_t *attr_p, uint_t alloc_flags,
302 	uint_t bind_flags, dma_area_t *dma_p)
303 {
304 	int err;
305 
306 	/*
307 	 * Allocate handle
308 	 */
309 	err = ddi_dma_alloc_handle(devinfo, &dma_attr,
310 		DDI_DMA_SLEEP, NULL, &dma_p->dma_hdl);
311 	if (err != DDI_SUCCESS)
312 		return (DDI_FAILURE);
313 
314 	/*
315 	 * Allocate memory
316 	 */
317 	err = ddi_dma_mem_alloc(dma_p->dma_hdl, memsize, attr_p,
318 	    alloc_flags, DDI_DMA_SLEEP, NULL, &dma_p->mem_va,
319 	    &dma_p->alength, &dma_p->acc_hdl);
320 	if (err != DDI_SUCCESS)
321 		return (DDI_FAILURE);
322 
323 	/*
324 	 * Bind the two together
325 	 */
326 	err = ddi_dma_addr_bind_handle(dma_p->dma_hdl, NULL,
327 		dma_p->mem_va, dma_p->alength, bind_flags,
328 		DDI_DMA_SLEEP, NULL, &dma_p->cookie, &dma_p->ncookies);
329 	if (err != DDI_DMA_MAPPED)
330 		return (DDI_FAILURE);
331 
332 	dma_p->nslots = ~0U;
333 	dma_p->size = ~0U;
334 	dma_p->token = ~0U;
335 	dma_p->offset = 0;
336 	return (DDI_SUCCESS);
337 }
338 
339 /*
340  * Free one allocated area of DMAable memory
341  */
342 static void
343 ath_free_dma_mem(dma_area_t *dma_p)
344 {
345 	if (dma_p->dma_hdl != NULL) {
346 		(void) ddi_dma_unbind_handle(dma_p->dma_hdl);
347 		if (dma_p->acc_hdl != NULL) {
348 			ddi_dma_mem_free(&dma_p->acc_hdl);
349 			dma_p->acc_hdl = NULL;
350 		}
351 		ddi_dma_free_handle(&dma_p->dma_hdl);
352 		dma_p->ncookies = 0;
353 		dma_p->dma_hdl = NULL;
354 	}
355 }
356 
357 
358 static int
359 ath_desc_alloc(dev_info_t *devinfo, ath_t *asc)
360 {
361 	int i, err;
362 	size_t size;
363 	struct ath_desc *ds;
364 	struct ath_buf *bf;
365 
366 	size = sizeof (struct ath_desc) * (ATH_TXBUF + ATH_RXBUF);
367 
368 	err = ath_alloc_dma_mem(devinfo, size, &ath_desc_accattr,
369 	    DDI_DMA_CONSISTENT, DDI_DMA_RDWR | DDI_DMA_CONSISTENT,
370 	    &asc->asc_desc_dma);
371 
372 	/* virtual address of the first descriptor */
373 	asc->asc_desc = (struct ath_desc *)asc->asc_desc_dma.mem_va;
374 
375 	ds = asc->asc_desc;
376 	ATH_DEBUG((ATH_DBG_INIT, "ath: ath_desc_alloc(): DMA map: "
377 	    "%p (%d) -> %p\n",
378 	    asc->asc_desc, asc->asc_desc_dma.alength,
379 	    asc->asc_desc_dma.cookie.dmac_address));
380 
381 	/* allocate data structures to describe TX/RX DMA buffers */
382 	asc->asc_vbuflen = sizeof (struct ath_buf) * (ATH_TXBUF + ATH_RXBUF);
383 	bf = (struct ath_buf *)kmem_zalloc(asc->asc_vbuflen, KM_SLEEP);
384 	asc->asc_vbufptr = bf;
385 
386 	/* DMA buffer size for each TX/RX packet */
387 	asc->asc_dmabuf_size = roundup(1000 + sizeof (struct ieee80211_frame) +
388 	    IEEE80211_MTU + IEEE80211_CRC_LEN +
389 	    (IEEE80211_WEP_IVLEN + IEEE80211_WEP_KIDLEN +
390 	    IEEE80211_WEP_CRCLEN), asc->asc_cachelsz);
391 
392 	/* create RX buffer list and allocate DMA memory */
393 	list_create(&asc->asc_rxbuf_list, sizeof (struct ath_buf),
394 	    offsetof(struct ath_buf, bf_node));
395 	for (i = 0; i < ATH_RXBUF; i++, bf++, ds++) {
396 		bf->bf_desc = ds;
397 		bf->bf_daddr = asc->asc_desc_dma.cookie.dmac_address +
398 		    ((caddr_t)ds - (caddr_t)asc->asc_desc);
399 		list_insert_tail(&asc->asc_rxbuf_list, bf);
400 
401 		/* alloc DMA memory */
402 		err = ath_alloc_dma_mem(devinfo, asc->asc_dmabuf_size,
403 		    &ath_desc_accattr,
404 		    DDI_DMA_STREAMING, DDI_DMA_READ | DDI_DMA_STREAMING,
405 		    &bf->bf_dma);
406 		if (err != DDI_SUCCESS)
407 			return (err);
408 	}
409 
410 	/* create TX buffer list and allocate DMA memory */
411 	list_create(&asc->asc_txbuf_list, sizeof (struct ath_buf),
412 	    offsetof(struct ath_buf, bf_node));
413 	for (i = 0; i < ATH_TXBUF; i++, bf++, ds++) {
414 		bf->bf_desc = ds;
415 		bf->bf_daddr = asc->asc_desc_dma.cookie.dmac_address +
416 		    ((caddr_t)ds - (caddr_t)asc->asc_desc);
417 		list_insert_tail(&asc->asc_txbuf_list, bf);
418 
419 		/* alloc DMA memory */
420 		err = ath_alloc_dma_mem(devinfo, asc->asc_dmabuf_size,
421 		    &ath_desc_accattr,
422 		    DDI_DMA_STREAMING, DDI_DMA_STREAMING, &bf->bf_dma);
423 		if (err != DDI_SUCCESS)
424 			return (err);
425 	}
426 
427 	return (DDI_SUCCESS);
428 }
429 
430 static void
431 ath_desc_free(ath_t *asc)
432 {
433 	struct ath_buf *bf;
434 
435 	/* Free TX DMA buffer */
436 	bf = list_head(&asc->asc_txbuf_list);
437 	while (bf != NULL) {
438 		ath_free_dma_mem(&bf->bf_dma);
439 		list_remove(&asc->asc_txbuf_list, bf);
440 		bf = list_head(&asc->asc_txbuf_list);
441 	}
442 	list_destroy(&asc->asc_txbuf_list);
443 
444 	/* Free RX DMA uffer */
445 	bf = list_head(&asc->asc_rxbuf_list);
446 	while (bf != NULL) {
447 		ath_free_dma_mem(&bf->bf_dma);
448 		list_remove(&asc->asc_rxbuf_list, bf);
449 		bf = list_head(&asc->asc_rxbuf_list);
450 	}
451 	list_destroy(&asc->asc_rxbuf_list);
452 
453 	/* Free descriptor DMA buffer */
454 	ath_free_dma_mem(&asc->asc_desc_dma);
455 
456 	kmem_free((void *)asc->asc_vbufptr, asc->asc_vbuflen);
457 	asc->asc_vbufptr = NULL;
458 }
459 
460 static void
461 ath_printrxbuf(struct ath_buf *bf, int32_t done)
462 {
463 	struct ath_desc *ds = bf->bf_desc;
464 
465 	ATH_DEBUG((ATH_DBG_RECV, "ath: R (%p %p) %08x %08x %08x "
466 	    "%08x %08x %08x %c\n",
467 	    ds, bf->bf_daddr,
468 	    ds->ds_link, ds->ds_data,
469 	    ds->ds_ctl0, ds->ds_ctl1,
470 	    ds->ds_hw[0], ds->ds_hw[1],
471 	    !done ? ' ' : (ds->ds_rxstat.rs_status == 0) ? '*' : '!'));
472 }
473 
474 static void
475 ath_rx_handler(ath_t *asc)
476 {
477 	ieee80211com_t *ic = (ieee80211com_t *)asc;
478 	struct ath_buf *bf;
479 	struct ath_hal *ah = asc->asc_ah;
480 	struct ath_desc *ds;
481 	mblk_t *rx_mp;
482 	struct ieee80211_frame *wh;
483 	int32_t len, loop = 1;
484 	uint8_t phyerr;
485 	HAL_STATUS status;
486 	HAL_NODE_STATS hal_node_stats;
487 	struct ieee80211_node *in;
488 
489 	do {
490 		mutex_enter(&asc->asc_rxbuflock);
491 		bf = list_head(&asc->asc_rxbuf_list);
492 		if (bf == NULL) {
493 			ATH_DEBUG((ATH_DBG_RECV, "ath: ath_rx_handler(): "
494 			    "no buffer\n"));
495 			mutex_exit(&asc->asc_rxbuflock);
496 			break;
497 		}
498 		ASSERT(bf->bf_dma.cookie.dmac_address != NULL);
499 		ds = bf->bf_desc;
500 		if (ds->ds_link == bf->bf_daddr) {
501 			/*
502 			 * Never process the self-linked entry at the end,
503 			 * this may be met at heavy load.
504 			 */
505 			mutex_exit(&asc->asc_rxbuflock);
506 			break;
507 		}
508 
509 		status = ATH_HAL_RXPROCDESC(ah, ds,
510 		    bf->bf_daddr,
511 		    ATH_PA2DESC(asc, ds->ds_link));
512 		if (status == HAL_EINPROGRESS) {
513 			mutex_exit(&asc->asc_rxbuflock);
514 			break;
515 		}
516 		list_remove(&asc->asc_rxbuf_list, bf);
517 		mutex_exit(&asc->asc_rxbuflock);
518 
519 		if (ds->ds_rxstat.rs_status != 0) {
520 			if (ds->ds_rxstat.rs_status & HAL_RXERR_CRC)
521 				asc->asc_stats.ast_rx_crcerr++;
522 			if (ds->ds_rxstat.rs_status & HAL_RXERR_FIFO)
523 				asc->asc_stats.ast_rx_fifoerr++;
524 			if (ds->ds_rxstat.rs_status & HAL_RXERR_DECRYPT)
525 				asc->asc_stats.ast_rx_badcrypt++;
526 			if (ds->ds_rxstat.rs_status & HAL_RXERR_PHY) {
527 				asc->asc_stats.ast_rx_phyerr++;
528 				phyerr = ds->ds_rxstat.rs_phyerr & 0x1f;
529 				asc->asc_stats.ast_rx_phy[phyerr]++;
530 			}
531 			goto rx_next;
532 		}
533 		len = ds->ds_rxstat.rs_datalen;
534 
535 		/* less than sizeof(struct ieee80211_frame) */
536 		if (len < 20) {
537 			asc->asc_stats.ast_rx_tooshort++;
538 			goto rx_next;
539 		}
540 
541 		if ((rx_mp = allocb(asc->asc_dmabuf_size, BPRI_MED)) == NULL) {
542 			ath_problem("ath: ath_rx_handler(): "
543 			    "allocing mblk buffer failed.\n");
544 			return;
545 		}
546 
547 		ATH_DMA_SYNC(bf->bf_dma, DDI_DMA_SYNC_FORCPU);
548 		bcopy(bf->bf_dma.mem_va, rx_mp->b_rptr, len);
549 
550 		rx_mp->b_wptr += len;
551 		wh = (struct ieee80211_frame *)rx_mp->b_rptr;
552 		if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
553 		    IEEE80211_FC0_TYPE_CTL) {
554 			/*
555 			 * Ignore control frame received in promisc mode.
556 			 */
557 			freemsg(rx_mp);
558 			goto rx_next;
559 		}
560 		/* Remove the CRC at the end of IEEE80211 frame */
561 		rx_mp->b_wptr -= IEEE80211_CRC_LEN;
562 #ifdef DEBUG
563 		ath_printrxbuf(bf, status == HAL_OK);
564 #endif /* DEBUG */
565 		/*
566 		 * Locate the node for sender, track state, and then
567 		 * pass the (referenced) node up to the 802.11 layer
568 		 * for its use.
569 		 */
570 		in = ieee80211_find_rxnode(ic, wh);
571 
572 		/*
573 		 * Send frame up for processing.
574 		 */
575 		(void) ieee80211_input(ic, rx_mp, in,
576 		    ds->ds_rxstat.rs_rssi,
577 		    ds->ds_rxstat.rs_tstamp);
578 
579 		ieee80211_free_node(in);
580 
581 rx_next:
582 		mutex_enter(&asc->asc_rxbuflock);
583 		list_insert_tail(&asc->asc_rxbuf_list, bf);
584 		mutex_exit(&asc->asc_rxbuflock);
585 		ath_setup_desc(asc, bf);
586 	} while (loop);
587 
588 	/* rx signal state monitoring */
589 	ATH_HAL_RXMONITOR(ah, &hal_node_stats, &asc->asc_curchan);
590 }
591 
592 static void
593 ath_printtxbuf(struct ath_buf *bf, int done)
594 {
595 	struct ath_desc *ds = bf->bf_desc;
596 
597 	ATH_DEBUG((ATH_DBG_SEND, "ath: T(%p %p) %08x %08x %08x %08x %08x"
598 	    " %08x %08x %08x %c\n",
599 	    ds, bf->bf_daddr,
600 	    ds->ds_link, ds->ds_data,
601 	    ds->ds_ctl0, ds->ds_ctl1,
602 	    ds->ds_hw[0], ds->ds_hw[1], ds->ds_hw[2], ds->ds_hw[3],
603 	    !done ? ' ' : (ds->ds_txstat.ts_status == 0) ? '*' : '!'));
604 }
605 
606 /*
607  * The input parameter mp has following assumption:
608  * For data packets, GLDv3 mac_wifi plugin allocates and fills the
609  * ieee80211 header. For management packets, net80211 allocates and
610  * fills the ieee80211 header. In both cases, enough spaces in the
611  * header are left for encryption option.
612  */
613 static int32_t
614 ath_tx_start(ath_t *asc, struct ieee80211_node *in, struct ath_buf *bf,
615     mblk_t *mp)
616 {
617 	ieee80211com_t *ic = (ieee80211com_t *)asc;
618 	struct ieee80211_frame *wh;
619 	struct ath_hal *ah = asc->asc_ah;
620 	uint32_t subtype, flags, ctsduration;
621 	int32_t keyix, iswep, hdrlen, pktlen, mblen, mbslen, try0;
622 	uint8_t rix, cix, txrate, ctsrate;
623 	struct ath_desc *ds;
624 	struct ath_txq *txq;
625 	HAL_PKT_TYPE atype;
626 	const HAL_RATE_TABLE *rt;
627 	HAL_BOOL shortPreamble;
628 	struct ath_node *an;
629 	caddr_t dest;
630 
631 	/*
632 	 * CRC are added by H/W, not encaped by driver,
633 	 * but we must count it in pkt length.
634 	 */
635 	pktlen = IEEE80211_CRC_LEN;
636 
637 	wh = (struct ieee80211_frame *)mp->b_rptr;
638 	iswep = wh->i_fc[1] & IEEE80211_FC1_WEP;
639 	keyix = HAL_TXKEYIX_INVALID;
640 	hdrlen = sizeof (struct ieee80211_frame);
641 	if (iswep != 0) {
642 		const struct ieee80211_cipher *cip;
643 		struct ieee80211_key *k;
644 
645 		/*
646 		 * Construct the 802.11 header+trailer for an encrypted
647 		 * frame. The only reason this can fail is because of an
648 		 * unknown or unsupported cipher/key type.
649 		 */
650 		k = ieee80211_crypto_encap(ic, mp);
651 		if (k == NULL) {
652 			ATH_DEBUG((ATH_DBG_AUX, "crypto_encap failed\n"));
653 			/*
654 			 * This can happen when the key is yanked after the
655 			 * frame was queued.  Just discard the frame; the
656 			 * 802.11 layer counts failures and provides
657 			 * debugging/diagnostics.
658 			 */
659 			return (EIO);
660 		}
661 		cip = k->wk_cipher;
662 		/*
663 		 * Adjust the packet + header lengths for the crypto
664 		 * additions and calculate the h/w key index.  When
665 		 * a s/w mic is done the frame will have had any mic
666 		 * added to it prior to entry so m0->m_pkthdr.len above will
667 		 * account for it. Otherwise we need to add it to the
668 		 * packet length.
669 		 */
670 		hdrlen += cip->ic_header;
671 		pktlen += cip->ic_header + cip->ic_trailer;
672 		if ((k->wk_flags & IEEE80211_KEY_SWMIC) == 0)
673 			pktlen += cip->ic_miclen;
674 		keyix = k->wk_keyix;
675 
676 		/* packet header may have moved, reset our local pointer */
677 		wh = (struct ieee80211_frame *)mp->b_rptr;
678 	}
679 
680 	dest = bf->bf_dma.mem_va;
681 	for (; mp != NULL; mp = mp->b_cont) {
682 		mblen = MBLKL(mp);
683 		bcopy(mp->b_rptr, dest, mblen);
684 		dest += mblen;
685 	}
686 	mbslen = dest - bf->bf_dma.mem_va;
687 	pktlen += mbslen;
688 
689 	bf->bf_in = in;
690 
691 	/* setup descriptors */
692 	ds = bf->bf_desc;
693 	rt = asc->asc_currates;
694 	ASSERT(rt != NULL);
695 
696 	/*
697 	 * The 802.11 layer marks whether or not we should
698 	 * use short preamble based on the current mode and
699 	 * negotiated parameters.
700 	 */
701 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
702 	    (in->in_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)) {
703 		shortPreamble = AH_TRUE;
704 		asc->asc_stats.ast_tx_shortpre++;
705 	} else {
706 		shortPreamble = AH_FALSE;
707 	}
708 
709 	an = ATH_NODE(in);
710 
711 	/*
712 	 * Calculate Atheros packet type from IEEE80211 packet header
713 	 * and setup for rate calculations.
714 	 */
715 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
716 	case IEEE80211_FC0_TYPE_MGT:
717 		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
718 		if (subtype == IEEE80211_FC0_SUBTYPE_BEACON)
719 			atype = HAL_PKT_TYPE_BEACON;
720 		else if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
721 			atype = HAL_PKT_TYPE_PROBE_RESP;
722 		else if (subtype == IEEE80211_FC0_SUBTYPE_ATIM)
723 			atype = HAL_PKT_TYPE_ATIM;
724 		else
725 			atype = HAL_PKT_TYPE_NORMAL;
726 		rix = 0;	/* lowest rate */
727 		try0 = ATH_TXMAXTRY;
728 		if (shortPreamble)
729 			txrate = an->an_tx_mgtratesp;
730 		else
731 			txrate = an->an_tx_mgtrate;
732 		/* force all ctl frames to highest queue */
733 		txq = asc->asc_ac2q[WME_AC_VO];
734 		break;
735 	case IEEE80211_FC0_TYPE_CTL:
736 		atype = HAL_PKT_TYPE_PSPOLL;
737 		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
738 		rix = 0;	/* lowest rate */
739 		try0 = ATH_TXMAXTRY;
740 		if (shortPreamble)
741 			txrate = an->an_tx_mgtratesp;
742 		else
743 			txrate = an->an_tx_mgtrate;
744 		/* force all ctl frames to highest queue */
745 		txq = asc->asc_ac2q[WME_AC_VO];
746 		break;
747 	case IEEE80211_FC0_TYPE_DATA:
748 		atype = HAL_PKT_TYPE_NORMAL;
749 		rix = an->an_tx_rix0;
750 		try0 = an->an_tx_try0;
751 		if (shortPreamble)
752 			txrate = an->an_tx_rate0sp;
753 		else
754 			txrate = an->an_tx_rate0;
755 		/* Always use background queue */
756 		txq = asc->asc_ac2q[WME_AC_BK];
757 		break;
758 	default:
759 		/* Unknown 802.11 frame */
760 		asc->asc_stats.ast_tx_invalid++;
761 		return (1);
762 	}
763 	/*
764 	 * Calculate miscellaneous flags.
765 	 */
766 	flags = HAL_TXDESC_CLRDMASK;
767 	if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {
768 		flags |= HAL_TXDESC_NOACK;	/* no ack on broad/multicast */
769 		asc->asc_stats.ast_tx_noack++;
770 	} else if (pktlen > ic->ic_rtsthreshold) {
771 		flags |= HAL_TXDESC_RTSENA;	/* RTS based on frame length */
772 		asc->asc_stats.ast_tx_rts++;
773 	}
774 
775 	/*
776 	 * Calculate duration.  This logically belongs in the 802.11
777 	 * layer but it lacks sufficient information to calculate it.
778 	 */
779 	if ((flags & HAL_TXDESC_NOACK) == 0 &&
780 	    (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) !=
781 	    IEEE80211_FC0_TYPE_CTL) {
782 		uint16_t dur;
783 		dur = ath_hal_computetxtime(ah, rt, IEEE80211_ACK_SIZE,
784 		    rix, shortPreamble);
785 		*(uint16_t *)wh->i_dur = LE_16(dur);
786 	}
787 
788 	/*
789 	 * Calculate RTS/CTS rate and duration if needed.
790 	 */
791 	ctsduration = 0;
792 	if (flags & (HAL_TXDESC_RTSENA|HAL_TXDESC_CTSENA)) {
793 		/*
794 		 * CTS transmit rate is derived from the transmit rate
795 		 * by looking in the h/w rate table.  We must also factor
796 		 * in whether or not a short preamble is to be used.
797 		 */
798 		cix = rt->info[rix].controlRate;
799 		ctsrate = rt->info[cix].rateCode;
800 		if (shortPreamble)
801 			ctsrate |= rt->info[cix].shortPreamble;
802 		/*
803 		 * Compute the transmit duration based on the size
804 		 * of an ACK frame.  We call into the HAL to do the
805 		 * computation since it depends on the characteristics
806 		 * of the actual PHY being used.
807 		 */
808 		if (flags & HAL_TXDESC_RTSENA) {	/* SIFS + CTS */
809 			ctsduration += ath_hal_computetxtime(ah,
810 			    rt, IEEE80211_ACK_SIZE, cix, shortPreamble);
811 		}
812 		/* SIFS + data */
813 		ctsduration += ath_hal_computetxtime(ah,
814 		    rt, pktlen, rix, shortPreamble);
815 		if ((flags & HAL_TXDESC_NOACK) == 0) {	/* SIFS + ACK */
816 			ctsduration += ath_hal_computetxtime(ah,
817 			    rt, IEEE80211_ACK_SIZE, cix, shortPreamble);
818 		}
819 	} else
820 		ctsrate = 0;
821 
822 	if (++txq->axq_intrcnt >= ATH_TXINTR_PERIOD) {
823 		flags |= HAL_TXDESC_INTREQ;
824 		txq->axq_intrcnt = 0;
825 	}
826 
827 	/*
828 	 * Formulate first tx descriptor with tx controls.
829 	 */
830 	ATH_HAL_SETUPTXDESC(ah, ds,
831 	    pktlen,			/* packet length */
832 	    hdrlen,			/* header length */
833 	    atype,			/* Atheros packet type */
834 	    MIN(in->in_txpower, 60),	/* txpower */
835 	    txrate, try0,		/* series 0 rate/tries */
836 	    keyix,			/* key cache index */
837 	    an->an_tx_antenna,		/* antenna mode */
838 	    flags,			/* flags */
839 	    ctsrate,			/* rts/cts rate */
840 	    ctsduration);		/* rts/cts duration */
841 	bf->bf_flags = flags;
842 
843 	ATH_DEBUG((ATH_DBG_SEND, "ath: ath_xmit(): to %s totlen=%d "
844 	    "an->an_tx_rate1sp=%d tx_rate2sp=%d tx_rate3sp=%d "
845 	    "qnum=%d rix=%d sht=%d dur = %d\n",
846 	    ieee80211_macaddr_sprintf(wh->i_addr1), mbslen, an->an_tx_rate1sp,
847 	    an->an_tx_rate2sp, an->an_tx_rate3sp,
848 	    txq->axq_qnum, rix, shortPreamble, *(uint16_t *)wh->i_dur));
849 
850 	/*
851 	 * Setup the multi-rate retry state only when we're
852 	 * going to use it.  This assumes ath_hal_setuptxdesc
853 	 * initializes the descriptors (so we don't have to)
854 	 * when the hardware supports multi-rate retry and
855 	 * we don't use it.
856 	 */
857 	if (try0 != ATH_TXMAXTRY)
858 		ATH_HAL_SETUPXTXDESC(ah, ds,
859 		    an->an_tx_rate1sp, 2,	/* series 1 */
860 		    an->an_tx_rate2sp, 2,	/* series 2 */
861 		    an->an_tx_rate3sp, 2);	/* series 3 */
862 
863 	ds->ds_link = 0;
864 	ds->ds_data = bf->bf_dma.cookie.dmac_address;
865 	ATH_HAL_FILLTXDESC(ah, ds,
866 	    mbslen,		/* segment length */
867 	    AH_TRUE,		/* first segment */
868 	    AH_TRUE,		/* last segment */
869 	    ds);		/* first descriptor */
870 
871 	ATH_DMA_SYNC(bf->bf_dma, DDI_DMA_SYNC_FORDEV);
872 
873 	mutex_enter(&txq->axq_lock);
874 	list_insert_tail(&txq->axq_list, bf);
875 	if (txq->axq_link == NULL) {
876 		ATH_HAL_PUTTXBUF(ah, txq->axq_qnum, bf->bf_daddr);
877 	} else {
878 		*txq->axq_link = bf->bf_daddr;
879 	}
880 	txq->axq_link = &ds->ds_link;
881 	mutex_exit(&txq->axq_lock);
882 
883 	ATH_HAL_TXSTART(ah, txq->axq_qnum);
884 
885 	ic->ic_stats.is_tx_frags++;
886 	ic->ic_stats.is_tx_bytes += pktlen;
887 
888 	return (0);
889 }
890 
891 /*
892  * Transmit a management frame.  On failure we reclaim the skbuff.
893  * Note that management frames come directly from the 802.11 layer
894  * and do not honor the send queue flow control.  Need to investigate
895  * using priority queueing so management frames can bypass data.
896  */
897 static int
898 ath_xmit(ieee80211com_t *ic, mblk_t *mp, uint8_t type)
899 {
900 	ath_t *asc = (ath_t *)ic;
901 	struct ath_hal *ah = asc->asc_ah;
902 	struct ieee80211_node *in = NULL;
903 	struct ath_buf *bf = NULL;
904 	struct ieee80211_frame *wh;
905 	int error = 0;
906 
907 	ASSERT(mp->b_next == NULL);
908 
909 	/* Grab a TX buffer */
910 	mutex_enter(&asc->asc_txbuflock);
911 	bf = list_head(&asc->asc_txbuf_list);
912 	if (bf != NULL)
913 		list_remove(&asc->asc_txbuf_list, bf);
914 	if (list_empty(&asc->asc_txbuf_list)) {
915 		ATH_DEBUG((ATH_DBG_SEND, "ath: ath_mgmt_send(): "
916 		    "stop queue\n"));
917 		asc->asc_stats.ast_tx_qstop++;
918 	}
919 	mutex_exit(&asc->asc_txbuflock);
920 	if (bf == NULL) {
921 		ATH_DEBUG((ATH_DBG_SEND, "ath: ath_mgmt_send(): discard, "
922 		    "no xmit buf\n"));
923 		ic->ic_stats.is_tx_nobuf++;
924 		if ((type & IEEE80211_FC0_TYPE_MASK) ==
925 		    IEEE80211_FC0_TYPE_DATA) {
926 			asc->asc_stats.ast_tx_nobuf++;
927 			mutex_enter(&asc->asc_resched_lock);
928 			asc->asc_resched_needed = B_TRUE;
929 			mutex_exit(&asc->asc_resched_lock);
930 		} else {
931 			asc->asc_stats.ast_tx_nobufmgt++;
932 			freemsg(mp);
933 		}
934 		return (ENOMEM);
935 	}
936 
937 	wh = (struct ieee80211_frame *)mp->b_rptr;
938 
939 	/* Locate node */
940 	in = ieee80211_find_txnode(ic,  wh->i_addr1);
941 	if (in == NULL) {
942 		error = EIO;
943 		goto bad;
944 	}
945 
946 	in->in_inact = 0;
947 	switch (type & IEEE80211_FC0_TYPE_MASK) {
948 	case IEEE80211_FC0_TYPE_DATA:
949 		(void) ieee80211_encap(ic, mp, in);
950 		break;
951 	default:
952 		if ((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
953 		    IEEE80211_FC0_SUBTYPE_PROBE_RESP) {
954 			/* fill time stamp */
955 			uint64_t tsf;
956 			uint32_t *tstamp;
957 
958 			tsf = ATH_HAL_GETTSF64(ah);
959 			/* adjust 100us delay to xmit */
960 			tsf += 100;
961 			tstamp = (uint32_t *)&wh[1];
962 			tstamp[0] = LE_32(tsf & 0xffffffff);
963 			tstamp[1] = LE_32(tsf >> 32);
964 		}
965 		asc->asc_stats.ast_tx_mgmt++;
966 		break;
967 	}
968 
969 	error = ath_tx_start(asc, in, bf, mp);
970 	if (error != 0) {
971 bad:
972 		ic->ic_stats.is_tx_failed++;
973 		if (bf != NULL) {
974 			mutex_enter(&asc->asc_txbuflock);
975 			list_insert_tail(&asc->asc_txbuf_list, bf);
976 			mutex_exit(&asc->asc_txbuflock);
977 		}
978 	}
979 	if (in != NULL)
980 		ieee80211_free_node(in);
981 	if ((type & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_DATA ||
982 	    error == 0) {
983 		freemsg(mp);
984 	}
985 
986 	return (error);
987 }
988 
989 static mblk_t *
990 ath_m_tx(void *arg, mblk_t *mp)
991 {
992 	ath_t *asc = arg;
993 	ieee80211com_t *ic = (ieee80211com_t *)asc;
994 	mblk_t *next;
995 
996 	/*
997 	 * No data frames go out unless we're associated; this
998 	 * should not happen as the 802.11 layer does not enable
999 	 * the xmit queue until we enter the RUN state.
1000 	 */
1001 	if (ic->ic_state != IEEE80211_S_RUN) {
1002 		ATH_DEBUG((ATH_DBG_SEND, "ath: ath_m_tx(): "
1003 		    "discard, state %u\n", ic->ic_state));
1004 		asc->asc_stats.ast_tx_discard ++;
1005 		return (mp);
1006 	}
1007 
1008 	while (mp != NULL) {
1009 		next = mp->b_next;
1010 		mp->b_next = NULL;
1011 
1012 		if (ath_xmit(ic, mp, IEEE80211_FC0_TYPE_DATA) != 0) {
1013 			mp->b_next = next;
1014 			break;
1015 		}
1016 		mp = next;
1017 	}
1018 
1019 	return (mp);
1020 
1021 }
1022 
1023 static int
1024 ath_tx_processq(ath_t *asc, struct ath_txq *txq)
1025 {
1026 	ieee80211com_t *ic = (ieee80211com_t *)asc;
1027 	struct ath_hal *ah = asc->asc_ah;
1028 	struct ath_buf *bf;
1029 	struct ath_desc *ds;
1030 	struct ieee80211_node *in;
1031 	int32_t sr, lr, nacked = 0;
1032 	HAL_STATUS status;
1033 	struct ath_node *an;
1034 
1035 	for (;;) {
1036 		mutex_enter(&txq->axq_lock);
1037 		bf = list_head(&txq->axq_list);
1038 		if (bf == NULL) {
1039 			txq->axq_link = NULL;
1040 			mutex_exit(&txq->axq_lock);
1041 			break;
1042 		}
1043 		ds = bf->bf_desc;	/* last decriptor */
1044 		status = ATH_HAL_TXPROCDESC(ah, ds);
1045 #ifdef DEBUG
1046 		ath_printtxbuf(bf, status == HAL_OK);
1047 #endif
1048 		if (status == HAL_EINPROGRESS) {
1049 			mutex_exit(&txq->axq_lock);
1050 			break;
1051 		}
1052 		list_remove(&txq->axq_list, bf);
1053 		mutex_exit(&txq->axq_lock);
1054 		in = bf->bf_in;
1055 		if (in != NULL) {
1056 			an = ATH_NODE(in);
1057 			/* Successful transmition */
1058 			if (ds->ds_txstat.ts_status == 0) {
1059 				an->an_tx_ok++;
1060 				an->an_tx_antenna =
1061 				    ds->ds_txstat.ts_antenna;
1062 				if (ds->ds_txstat.ts_rate &
1063 				    HAL_TXSTAT_ALTRATE)
1064 					asc->asc_stats.ast_tx_altrate++;
1065 				asc->asc_stats.ast_tx_rssidelta =
1066 				    ds->ds_txstat.ts_rssi -
1067 				    asc->asc_stats.ast_tx_rssi;
1068 				asc->asc_stats.ast_tx_rssi =
1069 				    ds->ds_txstat.ts_rssi;
1070 			} else {
1071 				an->an_tx_err++;
1072 				if (ds->ds_txstat.ts_status &
1073 				    HAL_TXERR_XRETRY)
1074 					asc->asc_stats.
1075 					    ast_tx_xretries++;
1076 				if (ds->ds_txstat.ts_status &
1077 				    HAL_TXERR_FIFO)
1078 					asc->asc_stats.ast_tx_fifoerr++;
1079 				if (ds->ds_txstat.ts_status &
1080 				    HAL_TXERR_FILT)
1081 					asc->asc_stats.
1082 					    ast_tx_filtered++;
1083 				an->an_tx_antenna = 0;	/* invalidate */
1084 			}
1085 			sr = ds->ds_txstat.ts_shortretry;
1086 			lr = ds->ds_txstat.ts_longretry;
1087 			asc->asc_stats.ast_tx_shortretry += sr;
1088 			asc->asc_stats.ast_tx_longretry += lr;
1089 			/*
1090 			 * Hand the descriptor to the rate control algorithm.
1091 			 */
1092 			if ((ds->ds_txstat.ts_status & HAL_TXERR_FILT) == 0 &&
1093 			    (bf->bf_flags & HAL_TXDESC_NOACK) == 0) {
1094 				/*
1095 				 * If frame was ack'd update the last rx time
1096 				 * used to workaround phantom bmiss interrupts.
1097 				 */
1098 				if (ds->ds_txstat.ts_status == 0) {
1099 					nacked++;
1100 					an->an_tx_ok++;
1101 				} else {
1102 					an->an_tx_err++;
1103 				}
1104 				an->an_tx_retr += sr + lr;
1105 			}
1106 		}
1107 		bf->bf_in = NULL;
1108 		mutex_enter(&asc->asc_txbuflock);
1109 		list_insert_tail(&asc->asc_txbuf_list, bf);
1110 		mutex_exit(&asc->asc_txbuflock);
1111 		/*
1112 		 * Reschedule stalled outbound packets
1113 		 */
1114 		mutex_enter(&asc->asc_resched_lock);
1115 		if (asc->asc_resched_needed) {
1116 			asc->asc_resched_needed = B_FALSE;
1117 			mac_tx_update(ic->ic_mach);
1118 		}
1119 		mutex_exit(&asc->asc_resched_lock);
1120 	}
1121 	return (nacked);
1122 }
1123 
1124 
1125 static void
1126 ath_tx_handler(ath_t *asc)
1127 {
1128 	int i;
1129 
1130 	/*
1131 	 * Process each active queue.
1132 	 */
1133 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
1134 		if (ATH_TXQ_SETUP(asc, i)) {
1135 			(void) ath_tx_processq(asc, &asc->asc_txq[i]);
1136 		}
1137 	}
1138 }
1139 
1140 static struct ieee80211_node *
1141 ath_node_alloc(ieee80211com_t *ic)
1142 {
1143 	struct ath_node *an;
1144 	ath_t *asc = (ath_t *)ic;
1145 
1146 	an = kmem_zalloc(sizeof (struct ath_node), KM_SLEEP);
1147 	ath_rate_update(asc, &an->an_node, 0);
1148 	return (&an->an_node);
1149 }
1150 
1151 static void
1152 ath_node_free(struct ieee80211_node *in)
1153 {
1154 	ieee80211com_t *ic = in->in_ic;
1155 	ath_t *asc = (ath_t *)ic;
1156 	struct ath_buf *bf;
1157 	struct ath_txq *txq;
1158 	int32_t i;
1159 
1160 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
1161 		if (ATH_TXQ_SETUP(asc, i)) {
1162 			txq = &asc->asc_txq[i];
1163 			mutex_enter(&txq->axq_lock);
1164 			bf = list_head(&txq->axq_list);
1165 			while (bf != NULL) {
1166 				if (bf->bf_in == in) {
1167 					bf->bf_in = NULL;
1168 				}
1169 				bf = list_next(&txq->axq_list, bf);
1170 			}
1171 			mutex_exit(&txq->axq_lock);
1172 		}
1173 	}
1174 	ic->ic_node_cleanup(in);
1175 	kmem_free(in, sizeof (struct ath_node));
1176 }
1177 
1178 static void
1179 ath_next_scan(void *arg)
1180 {
1181 	ieee80211com_t *ic = arg;
1182 	ath_t *asc = (ath_t *)ic;
1183 
1184 	asc->asc_scan_timer = 0;
1185 	if (ic->ic_state == IEEE80211_S_SCAN) {
1186 		asc->asc_scan_timer = timeout(ath_next_scan, (void *)asc,
1187 		    drv_usectohz(ath_dwelltime * 1000));
1188 		ieee80211_next_scan(ic);
1189 	}
1190 }
1191 
1192 static void
1193 ath_stop_scantimer(ath_t *asc)
1194 {
1195 	timeout_id_t tmp_id = 0;
1196 
1197 	while ((asc->asc_scan_timer != 0) && (tmp_id != asc->asc_scan_timer)) {
1198 		tmp_id = asc->asc_scan_timer;
1199 		(void) untimeout(tmp_id);
1200 	}
1201 	asc->asc_scan_timer = 0;
1202 }
1203 
1204 static int32_t
1205 ath_newstate(ieee80211com_t *ic, enum ieee80211_state nstate, int arg)
1206 {
1207 	ath_t *asc = (ath_t *)ic;
1208 	struct ath_hal *ah = asc->asc_ah;
1209 	struct ieee80211_node *in;
1210 	int32_t i, error;
1211 	uint8_t *bssid;
1212 	uint32_t rfilt;
1213 	enum ieee80211_state ostate;
1214 
1215 	static const HAL_LED_STATE leds[] = {
1216 	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
1217 	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
1218 	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
1219 	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
1220 	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
1221 	};
1222 	if (!ATH_IS_RUNNING(asc))
1223 		return (0);
1224 
1225 	ostate = ic->ic_state;
1226 	if (nstate != IEEE80211_S_SCAN)
1227 		ath_stop_scantimer(asc);
1228 
1229 	ATH_LOCK(asc);
1230 	ATH_HAL_SETLEDSTATE(ah, leds[nstate]);	/* set LED */
1231 
1232 	if (nstate == IEEE80211_S_INIT) {
1233 		asc->asc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
1234 		ATH_HAL_INTRSET(ah, asc->asc_imask &~ HAL_INT_GLOBAL);
1235 		ATH_UNLOCK(asc);
1236 		goto done;
1237 	}
1238 	in = ic->ic_bss;
1239 	error = ath_chan_set(asc, ic->ic_curchan);
1240 	if (error != 0) {
1241 		if (nstate != IEEE80211_S_SCAN) {
1242 			ATH_UNLOCK(asc);
1243 			ieee80211_reset_chan(ic);
1244 			goto bad;
1245 		}
1246 	}
1247 
1248 	rfilt = ath_calcrxfilter(asc);
1249 	if (nstate == IEEE80211_S_SCAN)
1250 		bssid = ic->ic_macaddr;
1251 	else
1252 		bssid = in->in_bssid;
1253 	ATH_HAL_SETRXFILTER(ah, rfilt);
1254 
1255 	if (nstate == IEEE80211_S_RUN && ic->ic_opmode != IEEE80211_M_IBSS)
1256 		ATH_HAL_SETASSOCID(ah, bssid, in->in_associd);
1257 	else
1258 		ATH_HAL_SETASSOCID(ah, bssid, 0);
1259 	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
1260 		for (i = 0; i < IEEE80211_WEP_NKID; i++) {
1261 			if (ATH_HAL_KEYISVALID(ah, i))
1262 				ATH_HAL_KEYSETMAC(ah, i, bssid);
1263 		}
1264 	}
1265 
1266 	if ((nstate == IEEE80211_S_RUN) &&
1267 	    (ostate != IEEE80211_S_RUN)) {
1268 		/* Configure the beacon and sleep timers. */
1269 		ath_beacon_config(asc);
1270 	} else {
1271 		asc->asc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
1272 		ATH_HAL_INTRSET(ah, asc->asc_imask);
1273 	}
1274 	/*
1275 	 * Reset the rate control state.
1276 	 */
1277 	ath_rate_ctl_reset(asc, nstate);
1278 
1279 	if (nstate == IEEE80211_S_RUN && (ostate != IEEE80211_S_RUN)) {
1280 		nvlist_t *attr_list = NULL;
1281 		sysevent_id_t eid;
1282 		int32_t err = 0;
1283 		char *str_name = "ATH";
1284 		char str_value[256] = {0};
1285 
1286 		ATH_DEBUG((ATH_DBG_80211, "ath: ath new state(RUN): "
1287 		    "ic_flags=0x%08x iv=%d"
1288 		    " bssid=%s capinfo=0x%04x chan=%d\n",
1289 		    ic->ic_flags,
1290 		    in->in_intval,
1291 		    ieee80211_macaddr_sprintf(in->in_bssid),
1292 		    in->in_capinfo,
1293 		    ieee80211_chan2ieee(ic, in->in_chan)));
1294 
1295 		(void) sprintf(str_value, "%s%s%d", "-i ",
1296 		    ddi_driver_name(asc->asc_dev),
1297 		    ddi_get_instance(asc->asc_dev));
1298 		if (nvlist_alloc(&attr_list,
1299 		    NV_UNIQUE_NAME_TYPE, KM_SLEEP) == 0) {
1300 			err = nvlist_add_string(attr_list,
1301 			    str_name, str_value);
1302 			if (err != DDI_SUCCESS)
1303 				ATH_DEBUG((ATH_DBG_80211, "ath: "
1304 				    "ath_new_state: error log event\n"));
1305 			err = ddi_log_sysevent(asc->asc_dev,
1306 			    DDI_VENDOR_SUNW, "class",
1307 			    "subclass", attr_list,
1308 			    &eid, DDI_NOSLEEP);
1309 			if (err != DDI_SUCCESS)
1310 				ATH_DEBUG((ATH_DBG_80211, "ath: "
1311 				    "ath_new_state(): error log event\n"));
1312 			nvlist_free(attr_list);
1313 		}
1314 	}
1315 
1316 	ATH_UNLOCK(asc);
1317 done:
1318 	/*
1319 	 * Invoke the parent method to complete the work.
1320 	 */
1321 	error = asc->asc_newstate(ic, nstate, arg);
1322 	/*
1323 	 * Finally, start any timers.
1324 	 */
1325 	if (nstate == IEEE80211_S_RUN) {
1326 		ieee80211_start_watchdog(ic, 1);
1327 	} else if ((nstate == IEEE80211_S_SCAN) && (ostate != nstate)) {
1328 		/* start ap/neighbor scan timer */
1329 		ASSERT(asc->asc_scan_timer == 0);
1330 		asc->asc_scan_timer = timeout(ath_next_scan, (void *)asc,
1331 		    drv_usectohz(ath_dwelltime * 1000));
1332 	}
1333 bad:
1334 	return (error);
1335 }
1336 
1337 /*
1338  * Periodically recalibrate the PHY to account
1339  * for temperature/environment changes.
1340  */
1341 static void
1342 ath_calibrate(ath_t *asc)
1343 {
1344 	struct ath_hal *ah = asc->asc_ah;
1345 	HAL_BOOL iqcaldone;
1346 
1347 	asc->asc_stats.ast_per_cal++;
1348 
1349 	if (ATH_HAL_GETRFGAIN(ah) == HAL_RFGAIN_NEED_CHANGE) {
1350 		/*
1351 		 * Rfgain is out of bounds, reset the chip
1352 		 * to load new gain values.
1353 		 */
1354 		ATH_DEBUG((ATH_DBG_HAL, "ath: ath_calibrate(): "
1355 		    "Need change RFgain\n"));
1356 		asc->asc_stats.ast_per_rfgain++;
1357 		(void) ath_reset(&asc->asc_isc);
1358 	}
1359 	if (!ATH_HAL_CALIBRATE(ah, &asc->asc_curchan, &iqcaldone)) {
1360 		ATH_DEBUG((ATH_DBG_HAL, "ath: ath_calibrate(): "
1361 		    "calibration of channel %u failed\n",
1362 		    asc->asc_curchan.channel));
1363 		asc->asc_stats.ast_per_calfail++;
1364 	}
1365 }
1366 
1367 static void
1368 ath_watchdog(void *arg)
1369 {
1370 	ath_t *asc = arg;
1371 	ieee80211com_t *ic = &asc->asc_isc;
1372 	int ntimer = 0;
1373 
1374 	ATH_LOCK(asc);
1375 	ic->ic_watchdog_timer = 0;
1376 	if (!ATH_IS_RUNNING(asc)) {
1377 		ATH_UNLOCK(asc);
1378 		return;
1379 	}
1380 
1381 	if (ic->ic_state == IEEE80211_S_RUN) {
1382 		/* periodic recalibration */
1383 		ath_calibrate(asc);
1384 
1385 		/*
1386 		 * Start the background rate control thread if we
1387 		 * are not configured to use a fixed xmit rate.
1388 		 */
1389 		if (ic->ic_fixed_rate == IEEE80211_FIXED_RATE_NONE) {
1390 			asc->asc_stats.ast_rate_calls ++;
1391 			if (ic->ic_opmode == IEEE80211_M_STA)
1392 				ath_rate_ctl(ic, ic->ic_bss);
1393 			else
1394 				ieee80211_iterate_nodes(&ic->ic_sta,
1395 				    ath_rate_cb, asc);
1396 		}
1397 
1398 		ntimer = 1;
1399 	}
1400 	ATH_UNLOCK(asc);
1401 
1402 	ieee80211_watchdog(ic);
1403 	if (ntimer != 0)
1404 		ieee80211_start_watchdog(ic, ntimer);
1405 }
1406 
1407 static uint_t
1408 ath_intr(caddr_t arg)
1409 {
1410 	ath_t *asc = (ath_t *)arg;
1411 	struct ath_hal *ah = asc->asc_ah;
1412 	HAL_INT status;
1413 	ieee80211com_t *ic = (ieee80211com_t *)asc;
1414 
1415 	ATH_LOCK(asc);
1416 
1417 	if (!ATH_IS_RUNNING(asc)) {
1418 		/*
1419 		 * The hardware is not ready/present, don't touch anything.
1420 		 * Note this can happen early on if the IRQ is shared.
1421 		 */
1422 		ATH_UNLOCK(asc);
1423 		return (DDI_INTR_UNCLAIMED);
1424 	}
1425 
1426 	if (!ATH_HAL_INTRPEND(ah)) {	/* shared irq, not for us */
1427 		ATH_UNLOCK(asc);
1428 		return (DDI_INTR_UNCLAIMED);
1429 	}
1430 
1431 	ATH_HAL_GETISR(ah, &status);
1432 	status &= asc->asc_imask;
1433 	if (status & HAL_INT_FATAL) {
1434 		asc->asc_stats.ast_hardware++;
1435 		goto reset;
1436 	} else if (status & HAL_INT_RXORN) {
1437 		asc->asc_stats.ast_rxorn++;
1438 		goto reset;
1439 	} else {
1440 		if (status & HAL_INT_RXEOL) {
1441 			asc->asc_stats.ast_rxeol++;
1442 			asc->asc_rxlink = NULL;
1443 		}
1444 		if (status & HAL_INT_TXURN) {
1445 			asc->asc_stats.ast_txurn++;
1446 			ATH_HAL_UPDATETXTRIGLEVEL(ah, AH_TRUE);
1447 		}
1448 
1449 		if (status & HAL_INT_RX) {
1450 			asc->asc_rx_pend = 1;
1451 			ddi_trigger_softintr(asc->asc_softint_id);
1452 		}
1453 		if (status & HAL_INT_TX) {
1454 			ath_tx_handler(asc);
1455 		}
1456 		ATH_UNLOCK(asc);
1457 
1458 		if (status & HAL_INT_SWBA) {
1459 			/* This will occur only in Host-AP or Ad-Hoc mode */
1460 			return (DDI_INTR_CLAIMED);
1461 		}
1462 		if (status & HAL_INT_BMISS) {
1463 			if (ic->ic_state == IEEE80211_S_RUN) {
1464 				(void) ieee80211_new_state(ic,
1465 				    IEEE80211_S_ASSOC, -1);
1466 			}
1467 		}
1468 	}
1469 
1470 	return (DDI_INTR_CLAIMED);
1471 reset:
1472 	(void) ath_reset(ic);
1473 	ATH_UNLOCK(asc);
1474 	return (DDI_INTR_CLAIMED);
1475 }
1476 
1477 static uint_t
1478 ath_softint_handler(caddr_t data)
1479 {
1480 	ath_t *asc = (ath_t *)data;
1481 
1482 	/*
1483 	 * Check if the soft interrupt is triggered by another
1484 	 * driver at the same level.
1485 	 */
1486 	ATH_LOCK(asc);
1487 	if (asc->asc_rx_pend) { /* Soft interrupt for this driver */
1488 		asc->asc_rx_pend = 0;
1489 		ATH_UNLOCK(asc);
1490 		ath_rx_handler(asc);
1491 		return (DDI_INTR_CLAIMED);
1492 	}
1493 	ATH_UNLOCK(asc);
1494 	return (DDI_INTR_UNCLAIMED);
1495 }
1496 
1497 /*
1498  * following are gld callback routine
1499  * ath_gld_send, ath_gld_ioctl, ath_gld_gstat
1500  * are listed in other corresponding sections.
1501  * reset the hardware w/o losing operational state.  this is
1502  * basically a more efficient way of doing ath_gld_stop, ath_gld_start,
1503  * followed by state transitions to the current 802.11
1504  * operational state.  used to recover from errors rx overrun
1505  * and to reset the hardware when rf gain settings must be reset.
1506  */
1507 
1508 static void
1509 ath_stop_locked(ath_t *asc)
1510 {
1511 	ieee80211com_t *ic = (ieee80211com_t *)asc;
1512 	struct ath_hal *ah = asc->asc_ah;
1513 
1514 	ATH_LOCK_ASSERT(asc);
1515 	/*
1516 	 * Shutdown the hardware and driver:
1517 	 *    reset 802.11 state machine
1518 	 *    turn off timers
1519 	 *    disable interrupts
1520 	 *    turn off the radio
1521 	 *    clear transmit machinery
1522 	 *    clear receive machinery
1523 	 *    drain and release tx queues
1524 	 *    reclaim beacon resources
1525 	 *    power down hardware
1526 	 *
1527 	 * Note that some of this work is not possible if the
1528 	 * hardware is gone (invalid).
1529 	 */
1530 	ATH_UNLOCK(asc);
1531 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
1532 	ieee80211_stop_watchdog(ic);
1533 	ATH_LOCK(asc);
1534 	ATH_HAL_INTRSET(ah, 0);
1535 	ath_draintxq(asc);
1536 	if (ATH_IS_RUNNING(asc)) {
1537 		ath_stoprecv(asc);
1538 		ATH_HAL_PHYDISABLE(ah);
1539 	} else {
1540 		asc->asc_rxlink = NULL;
1541 	}
1542 }
1543 
1544 static void
1545 ath_m_stop(void *arg)
1546 {
1547 	ath_t *asc = arg;
1548 	struct ath_hal *ah = asc->asc_ah;
1549 
1550 	ATH_LOCK(asc);
1551 	ath_stop_locked(asc);
1552 	ATH_HAL_SETPOWER(ah, HAL_PM_AWAKE);
1553 	asc->asc_invalid = 1;
1554 	ATH_UNLOCK(asc);
1555 }
1556 
1557 int
1558 ath_m_start(void *arg)
1559 {
1560 	ath_t *asc = arg;
1561 	ieee80211com_t *ic = (ieee80211com_t *)asc;
1562 	struct ath_hal *ah = asc->asc_ah;
1563 	HAL_STATUS status;
1564 
1565 	ATH_LOCK(asc);
1566 	/*
1567 	 * Stop anything previously setup.  This is safe
1568 	 * whether this is the first time through or not.
1569 	 */
1570 	ath_stop_locked(asc);
1571 
1572 	/*
1573 	 * The basic interface to setting the hardware in a good
1574 	 * state is ``reset''.  On return the hardware is known to
1575 	 * be powered up and with interrupts disabled.  This must
1576 	 * be followed by initialization of the appropriate bits
1577 	 * and then setup of the interrupt mask.
1578 	 */
1579 	asc->asc_curchan.channel = ic->ic_curchan->ich_freq;
1580 	asc->asc_curchan.channelFlags = ath_chan2flags(ic, ic->ic_curchan);
1581 	if (!ATH_HAL_RESET(ah, (HAL_OPMODE)ic->ic_opmode,
1582 	    &asc->asc_curchan, AH_FALSE, &status)) {
1583 		ATH_DEBUG((ATH_DBG_HAL, "ath: ath_m_start(): "
1584 		    "reset hardware failed, hal status %u\n", status));
1585 		ATH_UNLOCK(asc);
1586 		return (ENOTACTIVE);
1587 	}
1588 
1589 	(void) ath_startrecv(asc);
1590 
1591 	/*
1592 	 * Enable interrupts.
1593 	 */
1594 	asc->asc_imask = HAL_INT_RX | HAL_INT_TX
1595 	    | HAL_INT_RXEOL | HAL_INT_RXORN
1596 	    | HAL_INT_FATAL | HAL_INT_GLOBAL;
1597 	ATH_HAL_INTRSET(ah, asc->asc_imask);
1598 
1599 	ic->ic_state = IEEE80211_S_INIT;
1600 
1601 	/*
1602 	 * The hardware should be ready to go now so it's safe
1603 	 * to kick the 802.11 state machine as it's likely to
1604 	 * immediately call back to us to send mgmt frames.
1605 	 */
1606 	ath_chan_change(asc, ic->ic_curchan);
1607 	asc->asc_invalid = 0;
1608 	ATH_UNLOCK(asc);
1609 	return (0);
1610 }
1611 
1612 
1613 static int
1614 ath_m_unicst(void *arg, const uint8_t *macaddr)
1615 {
1616 	ath_t *asc = arg;
1617 	struct ath_hal *ah = asc->asc_ah;
1618 
1619 	ATH_DEBUG((ATH_DBG_GLD, "ath: ath_gld_saddr(): "
1620 	    "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n",
1621 	    macaddr[0], macaddr[1], macaddr[2],
1622 	    macaddr[3], macaddr[4], macaddr[5]));
1623 
1624 	ATH_LOCK(asc);
1625 	IEEE80211_ADDR_COPY(asc->asc_isc.ic_macaddr, macaddr);
1626 	ATH_HAL_SETMAC(ah, asc->asc_isc.ic_macaddr);
1627 
1628 	(void) ath_reset(&asc->asc_isc);
1629 	ATH_UNLOCK(asc);
1630 	return (0);
1631 }
1632 
1633 static int
1634 ath_m_promisc(void *arg, boolean_t on)
1635 {
1636 	ath_t *asc = arg;
1637 	struct ath_hal *ah = asc->asc_ah;
1638 	uint32_t rfilt;
1639 
1640 	ATH_LOCK(asc);
1641 	rfilt = ATH_HAL_GETRXFILTER(ah);
1642 	if (on)
1643 		rfilt |= HAL_RX_FILTER_PROM;
1644 	else
1645 		rfilt &= ~HAL_RX_FILTER_PROM;
1646 	ATH_HAL_SETRXFILTER(ah, rfilt);
1647 	ATH_UNLOCK(asc);
1648 
1649 	return (0);
1650 }
1651 
1652 static int
1653 ath_m_multicst(void *arg, boolean_t add, const uint8_t *mca)
1654 {
1655 	ath_t *asc = arg;
1656 	struct ath_hal *ah = asc->asc_ah;
1657 	uint32_t mfilt[2], val, rfilt;
1658 	uint8_t pos;
1659 
1660 	ATH_LOCK(asc);
1661 	rfilt = ATH_HAL_GETRXFILTER(ah);
1662 
1663 	/* disable multicast */
1664 	if (!add) {
1665 		ATH_HAL_SETRXFILTER(ah, rfilt & (~HAL_RX_FILTER_MCAST));
1666 		ATH_UNLOCK(asc);
1667 		return (0);
1668 	}
1669 
1670 	/* enable multicast */
1671 	ATH_HAL_SETRXFILTER(ah, rfilt | HAL_RX_FILTER_MCAST);
1672 
1673 	mfilt[0] = mfilt[1] = 0;
1674 
1675 	/* calculate XOR of eight 6bit values */
1676 	val = ATH_LE_READ_4(mca + 0);
1677 	pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
1678 	val = ATH_LE_READ_4(mca + 3);
1679 	pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
1680 	pos &= 0x3f;
1681 	mfilt[pos / 32] |= (1 << (pos % 32));
1682 	ATH_HAL_SETMCASTFILTER(ah, mfilt[0], mfilt[1]);
1683 
1684 	ATH_UNLOCK(asc);
1685 	return (0);
1686 }
1687 
1688 static void
1689 ath_m_ioctl(void *arg, queue_t *wq, mblk_t *mp)
1690 {
1691 	ath_t *asc = arg;
1692 	int32_t err;
1693 
1694 	err = ieee80211_ioctl(&asc->asc_isc, wq, mp);
1695 	ATH_LOCK(asc);
1696 	if (err == ENETRESET) {
1697 		if (ATH_IS_RUNNING(asc)) {
1698 			ATH_UNLOCK(asc);
1699 			(void) ath_m_start(asc);
1700 			(void) ieee80211_new_state(&asc->asc_isc,
1701 			    IEEE80211_S_SCAN, -1);
1702 			ATH_LOCK(asc);
1703 		}
1704 	}
1705 	ATH_UNLOCK(asc);
1706 }
1707 
1708 static int
1709 ath_m_stat(void *arg, uint_t stat, uint64_t *val)
1710 {
1711 	ath_t *asc = arg;
1712 	ieee80211com_t *ic = (ieee80211com_t *)asc;
1713 	struct ieee80211_node *in = ic->ic_bss;
1714 	struct ieee80211_rateset *rs = &in->in_rates;
1715 
1716 	ATH_LOCK(asc);
1717 	switch (stat) {
1718 	case MAC_STAT_IFSPEED:
1719 		*val = (rs->ir_rates[in->in_txrate] & IEEE80211_RATE_VAL) / 2 *
1720 		    1000000ull;
1721 		break;
1722 	case MAC_STAT_NOXMTBUF:
1723 		*val = asc->asc_stats.ast_tx_nobuf +
1724 		    asc->asc_stats.ast_tx_nobufmgt;
1725 		break;
1726 	case MAC_STAT_IERRORS:
1727 		*val = asc->asc_stats.ast_rx_tooshort;
1728 		break;
1729 	case MAC_STAT_OERRORS:
1730 		*val = asc->asc_stats.ast_tx_fifoerr +
1731 		    asc->asc_stats.ast_tx_xretries;
1732 		break;
1733 	case MAC_STAT_RBYTES:
1734 		*val = ic->ic_stats.is_rx_bytes;
1735 		break;
1736 	case MAC_STAT_IPACKETS:
1737 		*val = ic->ic_stats.is_rx_frags;
1738 		break;
1739 	case MAC_STAT_OBYTES:
1740 		*val = ic->ic_stats.is_tx_bytes;
1741 		break;
1742 	case MAC_STAT_OPACKETS:
1743 		*val = ic->ic_stats.is_tx_frags;
1744 		break;
1745 	case WIFI_STAT_TX_FAILED:
1746 		*val = asc->asc_stats.ast_tx_fifoerr +
1747 			asc->asc_stats.ast_tx_xretries;
1748 		break;
1749 	case WIFI_STAT_TX_RETRANS:
1750 		*val = asc->asc_stats.ast_tx_xretries;
1751 		break;
1752 	case WIFI_STAT_FCS_ERRORS:
1753 		*val = asc->asc_stats.ast_rx_crcerr;
1754 		break;
1755 	case WIFI_STAT_WEP_ERRORS:
1756 		*val = asc->asc_stats.ast_rx_badcrypt;
1757 		break;
1758 	case WIFI_STAT_TX_FRAGS:
1759 	case WIFI_STAT_MCAST_TX:
1760 	case WIFI_STAT_RTS_SUCCESS:
1761 	case WIFI_STAT_RTS_FAILURE:
1762 	case WIFI_STAT_ACK_FAILURE:
1763 	case WIFI_STAT_RX_FRAGS:
1764 	case WIFI_STAT_MCAST_RX:
1765 	case WIFI_STAT_RX_DUPS:
1766 		ATH_UNLOCK(asc);
1767 		return (ieee80211_stat(ic, stat, val));
1768 	default:
1769 		ATH_UNLOCK(asc);
1770 		return (ENOTSUP);
1771 	}
1772 	ATH_UNLOCK(asc);
1773 
1774 	return (0);
1775 }
1776 
1777 static int
1778 ath_attach(dev_info_t *devinfo, ddi_attach_cmd_t cmd)
1779 {
1780 	ath_t *asc;
1781 	ieee80211com_t *ic;
1782 	struct ath_hal *ah;
1783 	uint8_t csz;
1784 	HAL_STATUS status;
1785 	caddr_t regs;
1786 	uint32_t i, val;
1787 	uint16_t vendor_id, device_id, command;
1788 	const char *athname;
1789 	int32_t ath_countrycode = CTRY_DEFAULT;	/* country code */
1790 	int32_t err, ath_regdomain = 0; /* regulatory domain */
1791 	char strbuf[32];
1792 	int instance;
1793 	wifi_data_t wd = { 0 };
1794 	mac_register_t *macp;
1795 
1796 	if (cmd != DDI_ATTACH)
1797 		return (DDI_FAILURE);
1798 
1799 	instance = ddi_get_instance(devinfo);
1800 	if (ddi_soft_state_zalloc(ath_soft_state_p, instance) != DDI_SUCCESS) {
1801 		ATH_DEBUG((ATH_DBG_ATTACH, "ath: ath_attach(): "
1802 		    "Unable to alloc softstate\n"));
1803 		return (DDI_FAILURE);
1804 	}
1805 
1806 	asc = ddi_get_soft_state(ath_soft_state_p, ddi_get_instance(devinfo));
1807 	ic = (ieee80211com_t *)asc;
1808 	asc->asc_dev = devinfo;
1809 
1810 	mutex_init(&asc->asc_genlock, NULL, MUTEX_DRIVER, NULL);
1811 	mutex_init(&asc->asc_txbuflock, NULL, MUTEX_DRIVER, NULL);
1812 	mutex_init(&asc->asc_rxbuflock, NULL, MUTEX_DRIVER, NULL);
1813 	mutex_init(&asc->asc_resched_lock, NULL, MUTEX_DRIVER, NULL);
1814 
1815 	err = pci_config_setup(devinfo, &asc->asc_cfg_handle);
1816 	if (err != DDI_SUCCESS) {
1817 		ATH_DEBUG((ATH_DBG_ATTACH, "ath: ath_attach(): "
1818 		    "pci_config_setup() failed"));
1819 		goto attach_fail0;
1820 	}
1821 
1822 	csz = pci_config_get8(asc->asc_cfg_handle, PCI_CONF_CACHE_LINESZ);
1823 	asc->asc_cachelsz = csz << 2;
1824 	vendor_id = pci_config_get16(asc->asc_cfg_handle, PCI_CONF_VENID);
1825 	device_id = pci_config_get16(asc->asc_cfg_handle, PCI_CONF_DEVID);
1826 	ATH_DEBUG((ATH_DBG_ATTACH, "ath: ath_attach(): vendor 0x%x, "
1827 	    "device id 0x%x, cache size %d\n", vendor_id, device_id, csz));
1828 
1829 	athname = ath_hal_probe(vendor_id, device_id);
1830 	ATH_DEBUG((ATH_DBG_ATTACH, "ath: ath_attach(): athname: %s\n",
1831 	    athname ? athname : "Atheros ???"));
1832 
1833 	/*
1834 	 * Enable response to memory space accesses,
1835 	 * and enabe bus master.
1836 	 */
1837 	command = PCI_COMM_MAE | PCI_COMM_ME;
1838 	pci_config_put16(asc->asc_cfg_handle, PCI_CONF_COMM, command);
1839 	ATH_DEBUG((ATH_DBG_ATTACH, "ath: ath_attach(): "
1840 	    "set command reg to 0x%x \n", command));
1841 
1842 	pci_config_put8(asc->asc_cfg_handle, PCI_CONF_LATENCY_TIMER, 0xa8);
1843 	val = pci_config_get32(asc->asc_cfg_handle, 0x40);
1844 	if ((val & 0x0000ff00) != 0)
1845 		pci_config_put32(asc->asc_cfg_handle, 0x40, val & 0xffff00ff);
1846 
1847 	err = ddi_regs_map_setup(devinfo, 1,
1848 	    &regs, 0, 0, &ath_reg_accattr, &asc->asc_io_handle);
1849 	ATH_DEBUG((ATH_DBG_ATTACH, "ath: ath_attach(): "
1850 	    "regs map1 = %x err=%d\n", regs, err));
1851 	if (err != DDI_SUCCESS) {
1852 		ATH_DEBUG((ATH_DBG_ATTACH, "ath: ath_attach(): "
1853 		    "ddi_regs_map_setup() failed"));
1854 		goto attach_fail1;
1855 	}
1856 
1857 	ah = ath_hal_attach(device_id, asc, 0, regs, &status);
1858 	if (ah == NULL) {
1859 		ATH_DEBUG((ATH_DBG_ATTACH, "ath: ath_attach(): "
1860 		    "unable to attach hw; HAL status %u\n", status));
1861 		goto attach_fail2;
1862 	}
1863 	ATH_HAL_INTRSET(ah, 0);
1864 	asc->asc_ah = ah;
1865 
1866 	if (ah->ah_abi != HAL_ABI_VERSION) {
1867 		ATH_DEBUG((ATH_DBG_ATTACH, "ath: ath_attach(): "
1868 		    "HAL ABI mismatch detected (0x%x != 0x%x)\n",
1869 		    ah->ah_abi, HAL_ABI_VERSION));
1870 		goto attach_fail3;
1871 	}
1872 
1873 	ATH_DEBUG((ATH_DBG_ATTACH, "ath: ath_attach(): "
1874 	    "HAL ABI version 0x%x\n", ah->ah_abi));
1875 	ATH_DEBUG((ATH_DBG_ATTACH, "ath: ath_attach(): "
1876 	    "HAL mac version %d.%d, phy version %d.%d\n",
1877 	    ah->ah_macVersion, ah->ah_macRev,
1878 	    ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf));
1879 	if (ah->ah_analog5GhzRev)
1880 		ATH_DEBUG((ATH_DBG_ATTACH, "ath: ath_attach(): "
1881 		    "HAL 5ghz radio version %d.%d\n",
1882 		    ah->ah_analog5GhzRev >> 4,
1883 		    ah->ah_analog5GhzRev & 0xf));
1884 	if (ah->ah_analog2GhzRev)
1885 		ATH_DEBUG((ATH_DBG_ATTACH, "ath: ath_attach(): "
1886 		    "HAL 2ghz radio version %d.%d\n",
1887 		    ah->ah_analog2GhzRev >> 4,
1888 		    ah->ah_analog2GhzRev & 0xf));
1889 
1890 	/*
1891 	 * Check if the MAC has multi-rate retry support.
1892 	 * We do this by trying to setup a fake extended
1893 	 * descriptor.  MAC's that don't have support will
1894 	 * return false w/o doing anything.  MAC's that do
1895 	 * support it will return true w/o doing anything.
1896 	 */
1897 	asc->asc_mrretry = ATH_HAL_SETUPXTXDESC(ah, NULL, 0, 0, 0, 0, 0, 0);
1898 	ATH_DEBUG((ATH_DBG_ATTACH, "ath: ath_attach(): "
1899 	    "multi rate retry support=%x\n",
1900 	    asc->asc_mrretry));
1901 
1902 	ATH_HAL_GETREGDOMAIN(ah, (uint32_t *)&ath_regdomain);
1903 	ATH_HAL_GETCOUNTRYCODE(ah, &ath_countrycode);
1904 	/*
1905 	 * Collect the channel list using the default country
1906 	 * code and including outdoor channels.  The 802.11 layer
1907 	 * is resposible for filtering this list to a set of
1908 	 * channels that it considers ok to use.
1909 	 */
1910 	asc->asc_have11g = 0;
1911 
1912 	/* enable outdoor use, enable extended channels */
1913 	err = ath_getchannels(asc, ath_countrycode, AH_FALSE, AH_TRUE);
1914 	if (err != 0)
1915 		goto attach_fail3;
1916 
1917 	/*
1918 	 * Setup rate tables for all potential media types.
1919 	 */
1920 	ath_rate_setup(asc, IEEE80211_MODE_11A);
1921 	ath_rate_setup(asc, IEEE80211_MODE_11B);
1922 	ath_rate_setup(asc, IEEE80211_MODE_11G);
1923 	ath_rate_setup(asc, IEEE80211_MODE_TURBO_A);
1924 
1925 	/* Setup here so ath_rate_update is happy */
1926 	ath_setcurmode(asc, IEEE80211_MODE_11A);
1927 
1928 	err = ath_desc_alloc(devinfo, asc);
1929 	if (err != DDI_SUCCESS) {
1930 		ATH_DEBUG((ATH_DBG_ATTACH, "ath: ath_attach(): "
1931 		    "failed to allocate descriptors: %d\n", err));
1932 		goto attach_fail3;
1933 	}
1934 
1935 	/* Setup transmit queues in the HAL */
1936 	if (ath_txq_setup(asc))
1937 		goto attach_fail4;
1938 
1939 	ATH_HAL_GETMAC(ah, ic->ic_macaddr);
1940 
1941 	/*
1942 	 * Initialize pointers to device specific functions which
1943 	 * will be used by the generic layer.
1944 	 */
1945 	/* 11g support is identified when we fetch the channel set */
1946 	if (asc->asc_have11g)
1947 		ic->ic_caps |= IEEE80211_C_SHPREAMBLE;
1948 	/*
1949 	 * Query the hal to figure out h/w crypto support.
1950 	 */
1951 	if (ATH_HAL_CIPHERSUPPORTED(ah, HAL_CIPHER_WEP))
1952 		ic->ic_caps |= IEEE80211_C_WEP;
1953 	if (ATH_HAL_CIPHERSUPPORTED(ah, HAL_CIPHER_AES_OCB))
1954 		ic->ic_caps |= IEEE80211_C_AES;
1955 	if (ATH_HAL_CIPHERSUPPORTED(ah, HAL_CIPHER_AES_CCM))
1956 		ic->ic_caps |= IEEE80211_C_AES_CCM;
1957 	if (ATH_HAL_CIPHERSUPPORTED(ah, HAL_CIPHER_CKIP)) {
1958 		ic->ic_caps |= IEEE80211_C_CKIP;
1959 		/*
1960 		 * Check if h/w does the MIC and/or whether the
1961 		 * separate key cache entries are required to
1962 		 * handle both tx+rx MIC keys.
1963 		 */
1964 		if (ATH_HAL_CIPHERSUPPORTED(ah, HAL_CIPHER_MIC))
1965 			ic->ic_caps |= IEEE80211_C_TKIPMIC;
1966 		if (ATH_HAL_TKIPSPLIT(ah))
1967 			asc->asc_splitmic = 1;
1968 	}
1969 	asc->asc_hasclrkey = ATH_HAL_CIPHERSUPPORTED(ah, HAL_CIPHER_CLR);
1970 	ic->ic_phytype = IEEE80211_T_OFDM;
1971 	ic->ic_opmode = IEEE80211_M_STA;
1972 	ic->ic_state = IEEE80211_S_INIT;
1973 	ic->ic_maxrssi = ATH_MAX_RSSI;
1974 	ic->ic_set_shortslot = ath_set_shortslot;
1975 	ic->ic_xmit = ath_xmit;
1976 	ieee80211_attach(ic);
1977 
1978 	/* Override 80211 default routines */
1979 	ic->ic_reset = ath_reset;
1980 	asc->asc_newstate = ic->ic_newstate;
1981 	ic->ic_newstate = ath_newstate;
1982 	ic->ic_watchdog = ath_watchdog;
1983 	ic->ic_node_alloc = ath_node_alloc;
1984 	ic->ic_node_free = ath_node_free;
1985 	ic->ic_crypto.cs_key_alloc = ath_key_alloc;
1986 	ic->ic_crypto.cs_key_delete = ath_key_delete;
1987 	ic->ic_crypto.cs_key_set = ath_key_set;
1988 	ieee80211_media_init(ic);
1989 
1990 	asc->asc_rx_pend = 0;
1991 	ATH_HAL_INTRSET(ah, 0);
1992 	err = ddi_add_softintr(devinfo, DDI_SOFTINT_LOW,
1993 	    &asc->asc_softint_id, NULL, 0, ath_softint_handler, (caddr_t)asc);
1994 	if (err != DDI_SUCCESS) {
1995 		ATH_DEBUG((ATH_DBG_ATTACH, "ath: ath_attach(): "
1996 		    "ddi_add_softintr() failed\n"));
1997 		goto attach_fail5;
1998 	}
1999 
2000 	if (ddi_get_iblock_cookie(devinfo, 0, &asc->asc_iblock)
2001 	    != DDI_SUCCESS) {
2002 		ATH_DEBUG((ATH_DBG_ATTACH, "ath: ath_attach(): "
2003 		    "Can not get iblock cookie for INT\n"));
2004 		goto attach_fail6;
2005 	}
2006 
2007 	if (ddi_add_intr(devinfo, 0, NULL, NULL, ath_intr,
2008 	    (caddr_t)asc) != DDI_SUCCESS) {
2009 		ATH_DEBUG((ATH_DBG_ATTACH, "ath: ath_attach(): "
2010 		    "Can not set intr for ATH driver\n"));
2011 		goto attach_fail6;
2012 	}
2013 
2014 	/*
2015 	 * Provide initial settings for the WiFi plugin; whenever this
2016 	 * information changes, we need to call mac_plugindata_update()
2017 	 */
2018 	wd.wd_opmode = ic->ic_opmode;
2019 	wd.wd_secalloc = WIFI_SEC_NONE;
2020 	IEEE80211_ADDR_COPY(wd.wd_bssid, ic->ic_bss->in_bssid);
2021 
2022 	if ((macp = mac_alloc(MAC_VERSION)) == NULL) {
2023 		ATH_DEBUG((ATH_DBG_ATTACH, "ath: ath_attach(): "
2024 		    "MAC version mismatch\n"));
2025 		goto attach_fail7;
2026 	}
2027 
2028 	macp->m_type_ident	= MAC_PLUGIN_IDENT_WIFI;
2029 	macp->m_driver		= asc;
2030 	macp->m_dip		= devinfo;
2031 	macp->m_src_addr	= ic->ic_macaddr;
2032 	macp->m_callbacks	= &ath_m_callbacks;
2033 	macp->m_min_sdu		= 0;
2034 	macp->m_max_sdu		= IEEE80211_MTU;
2035 	macp->m_pdata		= &wd;
2036 	macp->m_pdata_size	= sizeof (wd);
2037 
2038 	err = mac_register(macp, &ic->ic_mach);
2039 	mac_free(macp);
2040 	if (err != 0) {
2041 		ATH_DEBUG((ATH_DBG_ATTACH, "ath: ath_attach(): "
2042 		    "mac_register err %x\n", err));
2043 		goto attach_fail7;
2044 	}
2045 
2046 	/* Create minor node of type DDI_NT_NET_WIFI */
2047 	(void) snprintf(strbuf, sizeof (strbuf), "%s%d",
2048 	    ATH_NODENAME, instance);
2049 	err = ddi_create_minor_node(devinfo, strbuf, S_IFCHR,
2050 	    instance + 1, DDI_NT_NET_WIFI, 0);
2051 	if (err != DDI_SUCCESS)
2052 		ATH_DEBUG((ATH_DBG_ATTACH, "WARN: ath: ath_attach(): "
2053 		    "Create minor node failed - %d\n", err));
2054 
2055 	mac_link_update(ic->ic_mach, LINK_STATE_DOWN);
2056 	asc->asc_invalid = 1;
2057 	return (DDI_SUCCESS);
2058 attach_fail7:
2059 	ddi_remove_intr(devinfo, 0, asc->asc_iblock);
2060 attach_fail6:
2061 	ddi_remove_softintr(asc->asc_softint_id);
2062 attach_fail5:
2063 	(void) ieee80211_detach(ic);
2064 attach_fail4:
2065 	ath_desc_free(asc);
2066 attach_fail3:
2067 	ah->ah_detach(asc->asc_ah);
2068 attach_fail2:
2069 	ddi_regs_map_free(&asc->asc_io_handle);
2070 attach_fail1:
2071 	pci_config_teardown(&asc->asc_cfg_handle);
2072 attach_fail0:
2073 	asc->asc_invalid = 1;
2074 	mutex_destroy(&asc->asc_txbuflock);
2075 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
2076 		if (ATH_TXQ_SETUP(asc, i)) {
2077 			struct ath_txq *txq = &asc->asc_txq[i];
2078 			mutex_destroy(&txq->axq_lock);
2079 		}
2080 	}
2081 	mutex_destroy(&asc->asc_rxbuflock);
2082 	mutex_destroy(&asc->asc_genlock);
2083 	mutex_destroy(&asc->asc_resched_lock);
2084 	ddi_soft_state_free(ath_soft_state_p, instance);
2085 
2086 	return (DDI_FAILURE);
2087 }
2088 
2089 static int32_t
2090 ath_detach(dev_info_t *devinfo, ddi_detach_cmd_t cmd)
2091 {
2092 	ath_t *asc;
2093 
2094 	asc = ddi_get_soft_state(ath_soft_state_p, ddi_get_instance(devinfo));
2095 	ASSERT(asc != NULL);
2096 
2097 	if (cmd != DDI_DETACH)
2098 		return (DDI_FAILURE);
2099 
2100 	ath_stop_scantimer(asc);
2101 
2102 	/* disable interrupts */
2103 	ATH_HAL_INTRSET(asc->asc_ah, 0);
2104 
2105 	/*
2106 	 * Unregister from the MAC layer subsystem
2107 	 */
2108 	if (mac_unregister(asc->asc_isc.ic_mach) != 0)
2109 		return (DDI_FAILURE);
2110 
2111 	/* free intterrupt resources */
2112 	ddi_remove_intr(devinfo, 0, asc->asc_iblock);
2113 	ddi_remove_softintr(asc->asc_softint_id);
2114 
2115 	/*
2116 	 * NB: the order of these is important:
2117 	 * o call the 802.11 layer before detaching the hal to
2118 	 *   insure callbacks into the driver to delete global
2119 	 *   key cache entries can be handled
2120 	 * o reclaim the tx queue data structures after calling
2121 	 *   the 802.11 layer as we'll get called back to reclaim
2122 	 *   node state and potentially want to use them
2123 	 * o to cleanup the tx queues the hal is called, so detach
2124 	 *   it last
2125 	 */
2126 	ieee80211_detach(&asc->asc_isc);
2127 	ath_desc_free(asc);
2128 	ath_txq_cleanup(asc);
2129 	asc->asc_ah->ah_detach(asc->asc_ah);
2130 
2131 	/* free io handle */
2132 	ddi_regs_map_free(&asc->asc_io_handle);
2133 	pci_config_teardown(&asc->asc_cfg_handle);
2134 
2135 	/* destroy locks */
2136 	mutex_destroy(&asc->asc_rxbuflock);
2137 	mutex_destroy(&asc->asc_genlock);
2138 	mutex_destroy(&asc->asc_resched_lock);
2139 
2140 	ddi_remove_minor_node(devinfo, NULL);
2141 	ddi_soft_state_free(ath_soft_state_p, ddi_get_instance(devinfo));
2142 
2143 	return (DDI_SUCCESS);
2144 }
2145 
2146 DDI_DEFINE_STREAM_OPS(ath_dev_ops, nulldev, nulldev, ath_attach, ath_detach,
2147     nodev, NULL, D_MP, NULL);
2148 
2149 static struct modldrv ath_modldrv = {
2150 	&mod_driverops,		/* Type of module.  This one is a driver */
2151 	"ath driver 1.2/HAL 0.9.17.2",	/* short description */
2152 	&ath_dev_ops		/* driver specific ops */
2153 };
2154 
2155 static struct modlinkage modlinkage = {
2156 	MODREV_1, (void *)&ath_modldrv, NULL
2157 };
2158 
2159 
2160 int
2161 _info(struct modinfo *modinfop)
2162 {
2163 	return (mod_info(&modlinkage, modinfop));
2164 }
2165 
2166 int
2167 _init(void)
2168 {
2169 	int status;
2170 
2171 	status = ddi_soft_state_init(&ath_soft_state_p, sizeof (ath_t), 1);
2172 	if (status != 0)
2173 		return (status);
2174 
2175 	mutex_init(&ath_loglock, NULL, MUTEX_DRIVER, NULL);
2176 	ath_halfix_init();
2177 	mac_init_ops(&ath_dev_ops, "ath");
2178 	status = mod_install(&modlinkage);
2179 	if (status != 0) {
2180 		mac_fini_ops(&ath_dev_ops);
2181 		ath_halfix_finit();
2182 		mutex_destroy(&ath_loglock);
2183 		ddi_soft_state_fini(&ath_soft_state_p);
2184 	}
2185 
2186 	return (status);
2187 }
2188 
2189 int
2190 _fini(void)
2191 {
2192 	int status;
2193 
2194 	status = mod_remove(&modlinkage);
2195 	if (status == 0) {
2196 		mac_fini_ops(&ath_dev_ops);
2197 		ath_halfix_finit();
2198 		mutex_destroy(&ath_loglock);
2199 		ddi_soft_state_fini(&ath_soft_state_p);
2200 	}
2201 	return (status);
2202 }
2203