xref: /linux/drivers/net/wireless/ath/ath5k/base.c (revision a02001086bbfb4da35d1228bebc2f1b442db455f)
1 /*-
2  * Copyright (c) 2002-2005 Sam Leffler, Errno Consulting
3  * Copyright (c) 2004-2005 Atheros Communications, Inc.
4  * Copyright (c) 2006 Devicescape Software, Inc.
5  * Copyright (c) 2007 Jiri Slaby <jirislaby@gmail.com>
6  * Copyright (c) 2007 Luis R. Rodriguez <mcgrof@winlab.rutgers.edu>
7  *
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  * Alternatively, this software may be distributed under the terms of the
25  * GNU General Public License ("GPL") version 2 as published by the Free
26  * Software Foundation.
27  *
28  * NO WARRANTY
29  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31  * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
32  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
33  * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
34  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
35  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
36  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
37  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
39  * THE POSSIBILITY OF SUCH DAMAGES.
40  *
41  */
42 
43 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
44 
45 #include <linux/module.h>
46 #include <linux/delay.h>
47 #include <linux/dma-mapping.h>
48 #include <linux/hardirq.h>
49 #include <linux/if.h>
50 #include <linux/io.h>
51 #include <linux/netdevice.h>
52 #include <linux/cache.h>
53 #include <linux/ethtool.h>
54 #include <linux/uaccess.h>
55 #include <linux/slab.h>
56 #include <linux/etherdevice.h>
57 #include <linux/nl80211.h>
58 
59 #include <net/cfg80211.h>
60 #include <net/ieee80211_radiotap.h>
61 
62 #include <asm/unaligned.h>
63 
64 #include <net/mac80211.h>
65 #include "base.h"
66 #include "reg.h"
67 #include "debug.h"
68 #include "ani.h"
69 #include "ath5k.h"
70 #include "../regd.h"
71 
72 #define CREATE_TRACE_POINTS
73 #include "trace.h"
74 
75 bool ath5k_modparam_nohwcrypt;
76 module_param_named(nohwcrypt, ath5k_modparam_nohwcrypt, bool, S_IRUGO);
77 MODULE_PARM_DESC(nohwcrypt, "Disable hardware encryption.");
78 
79 static bool modparam_fastchanswitch;
80 module_param_named(fastchanswitch, modparam_fastchanswitch, bool, S_IRUGO);
81 MODULE_PARM_DESC(fastchanswitch, "Enable fast channel switching for AR2413/AR5413 radios.");
82 
83 static bool ath5k_modparam_no_hw_rfkill_switch;
84 module_param_named(no_hw_rfkill_switch, ath5k_modparam_no_hw_rfkill_switch,
85 								bool, S_IRUGO);
86 MODULE_PARM_DESC(no_hw_rfkill_switch, "Ignore the GPIO RFKill switch state");
87 
88 
89 /* Module info */
90 MODULE_AUTHOR("Jiri Slaby");
91 MODULE_AUTHOR("Nick Kossifidis");
92 MODULE_DESCRIPTION("Support for 5xxx series of Atheros 802.11 wireless LAN cards.");
93 MODULE_SUPPORTED_DEVICE("Atheros 5xxx WLAN cards");
94 MODULE_LICENSE("Dual BSD/GPL");
95 
96 static int ath5k_init(struct ieee80211_hw *hw);
97 static int ath5k_reset(struct ath5k_hw *ah, struct ieee80211_channel *chan,
98 								bool skip_pcu);
99 
100 /* Known SREVs */
101 static const struct ath5k_srev_name srev_names[] = {
102 	{ "5210",	AR5K_VERSION_MAC,	AR5K_SREV_AR5210 },
103 	{ "5311",	AR5K_VERSION_MAC,	AR5K_SREV_AR5311 },
104 	{ "5311A",	AR5K_VERSION_MAC,	AR5K_SREV_AR5311A },
105 	{ "5311B",	AR5K_VERSION_MAC,	AR5K_SREV_AR5311B },
106 	{ "5211",	AR5K_VERSION_MAC,	AR5K_SREV_AR5211 },
107 	{ "5212",	AR5K_VERSION_MAC,	AR5K_SREV_AR5212 },
108 	{ "5213",	AR5K_VERSION_MAC,	AR5K_SREV_AR5213 },
109 	{ "5213A",	AR5K_VERSION_MAC,	AR5K_SREV_AR5213A },
110 	{ "2413",	AR5K_VERSION_MAC,	AR5K_SREV_AR2413 },
111 	{ "2414",	AR5K_VERSION_MAC,	AR5K_SREV_AR2414 },
112 	{ "5424",	AR5K_VERSION_MAC,	AR5K_SREV_AR5424 },
113 	{ "5413",	AR5K_VERSION_MAC,	AR5K_SREV_AR5413 },
114 	{ "5414",	AR5K_VERSION_MAC,	AR5K_SREV_AR5414 },
115 	{ "2415",	AR5K_VERSION_MAC,	AR5K_SREV_AR2415 },
116 	{ "5416",	AR5K_VERSION_MAC,	AR5K_SREV_AR5416 },
117 	{ "5418",	AR5K_VERSION_MAC,	AR5K_SREV_AR5418 },
118 	{ "2425",	AR5K_VERSION_MAC,	AR5K_SREV_AR2425 },
119 	{ "2417",	AR5K_VERSION_MAC,	AR5K_SREV_AR2417 },
120 	{ "xxxxx",	AR5K_VERSION_MAC,	AR5K_SREV_UNKNOWN },
121 	{ "5110",	AR5K_VERSION_RAD,	AR5K_SREV_RAD_5110 },
122 	{ "5111",	AR5K_VERSION_RAD,	AR5K_SREV_RAD_5111 },
123 	{ "5111A",	AR5K_VERSION_RAD,	AR5K_SREV_RAD_5111A },
124 	{ "2111",	AR5K_VERSION_RAD,	AR5K_SREV_RAD_2111 },
125 	{ "5112",	AR5K_VERSION_RAD,	AR5K_SREV_RAD_5112 },
126 	{ "5112A",	AR5K_VERSION_RAD,	AR5K_SREV_RAD_5112A },
127 	{ "5112B",	AR5K_VERSION_RAD,	AR5K_SREV_RAD_5112B },
128 	{ "2112",	AR5K_VERSION_RAD,	AR5K_SREV_RAD_2112 },
129 	{ "2112A",	AR5K_VERSION_RAD,	AR5K_SREV_RAD_2112A },
130 	{ "2112B",	AR5K_VERSION_RAD,	AR5K_SREV_RAD_2112B },
131 	{ "2413",	AR5K_VERSION_RAD,	AR5K_SREV_RAD_2413 },
132 	{ "5413",	AR5K_VERSION_RAD,	AR5K_SREV_RAD_5413 },
133 	{ "5424",	AR5K_VERSION_RAD,	AR5K_SREV_RAD_5424 },
134 	{ "5133",	AR5K_VERSION_RAD,	AR5K_SREV_RAD_5133 },
135 	{ "xxxxx",	AR5K_VERSION_RAD,	AR5K_SREV_UNKNOWN },
136 };
137 
138 static const struct ieee80211_rate ath5k_rates[] = {
139 	{ .bitrate = 10,
140 	  .hw_value = ATH5K_RATE_CODE_1M, },
141 	{ .bitrate = 20,
142 	  .hw_value = ATH5K_RATE_CODE_2M,
143 	  .hw_value_short = ATH5K_RATE_CODE_2M | AR5K_SET_SHORT_PREAMBLE,
144 	  .flags = IEEE80211_RATE_SHORT_PREAMBLE },
145 	{ .bitrate = 55,
146 	  .hw_value = ATH5K_RATE_CODE_5_5M,
147 	  .hw_value_short = ATH5K_RATE_CODE_5_5M | AR5K_SET_SHORT_PREAMBLE,
148 	  .flags = IEEE80211_RATE_SHORT_PREAMBLE },
149 	{ .bitrate = 110,
150 	  .hw_value = ATH5K_RATE_CODE_11M,
151 	  .hw_value_short = ATH5K_RATE_CODE_11M | AR5K_SET_SHORT_PREAMBLE,
152 	  .flags = IEEE80211_RATE_SHORT_PREAMBLE },
153 	{ .bitrate = 60,
154 	  .hw_value = ATH5K_RATE_CODE_6M,
155 	  .flags = IEEE80211_RATE_SUPPORTS_5MHZ |
156 		   IEEE80211_RATE_SUPPORTS_10MHZ },
157 	{ .bitrate = 90,
158 	  .hw_value = ATH5K_RATE_CODE_9M,
159 	  .flags = IEEE80211_RATE_SUPPORTS_5MHZ |
160 		   IEEE80211_RATE_SUPPORTS_10MHZ },
161 	{ .bitrate = 120,
162 	  .hw_value = ATH5K_RATE_CODE_12M,
163 	  .flags = IEEE80211_RATE_SUPPORTS_5MHZ |
164 		   IEEE80211_RATE_SUPPORTS_10MHZ },
165 	{ .bitrate = 180,
166 	  .hw_value = ATH5K_RATE_CODE_18M,
167 	  .flags = IEEE80211_RATE_SUPPORTS_5MHZ |
168 		   IEEE80211_RATE_SUPPORTS_10MHZ },
169 	{ .bitrate = 240,
170 	  .hw_value = ATH5K_RATE_CODE_24M,
171 	  .flags = IEEE80211_RATE_SUPPORTS_5MHZ |
172 		   IEEE80211_RATE_SUPPORTS_10MHZ },
173 	{ .bitrate = 360,
174 	  .hw_value = ATH5K_RATE_CODE_36M,
175 	  .flags = IEEE80211_RATE_SUPPORTS_5MHZ |
176 		   IEEE80211_RATE_SUPPORTS_10MHZ },
177 	{ .bitrate = 480,
178 	  .hw_value = ATH5K_RATE_CODE_48M,
179 	  .flags = IEEE80211_RATE_SUPPORTS_5MHZ |
180 		   IEEE80211_RATE_SUPPORTS_10MHZ },
181 	{ .bitrate = 540,
182 	  .hw_value = ATH5K_RATE_CODE_54M,
183 	  .flags = IEEE80211_RATE_SUPPORTS_5MHZ |
184 		   IEEE80211_RATE_SUPPORTS_10MHZ },
185 };
186 
187 static inline u64 ath5k_extend_tsf(struct ath5k_hw *ah, u32 rstamp)
188 {
189 	u64 tsf = ath5k_hw_get_tsf64(ah);
190 
191 	if ((tsf & 0x7fff) < rstamp)
192 		tsf -= 0x8000;
193 
194 	return (tsf & ~0x7fff) | rstamp;
195 }
196 
197 const char *
198 ath5k_chip_name(enum ath5k_srev_type type, u_int16_t val)
199 {
200 	const char *name = "xxxxx";
201 	unsigned int i;
202 
203 	for (i = 0; i < ARRAY_SIZE(srev_names); i++) {
204 		if (srev_names[i].sr_type != type)
205 			continue;
206 
207 		if ((val & 0xf0) == srev_names[i].sr_val)
208 			name = srev_names[i].sr_name;
209 
210 		if ((val & 0xff) == srev_names[i].sr_val) {
211 			name = srev_names[i].sr_name;
212 			break;
213 		}
214 	}
215 
216 	return name;
217 }
218 static unsigned int ath5k_ioread32(void *hw_priv, u32 reg_offset)
219 {
220 	struct ath5k_hw *ah = (struct ath5k_hw *) hw_priv;
221 	return ath5k_hw_reg_read(ah, reg_offset);
222 }
223 
224 static void ath5k_iowrite32(void *hw_priv, u32 val, u32 reg_offset)
225 {
226 	struct ath5k_hw *ah = (struct ath5k_hw *) hw_priv;
227 	ath5k_hw_reg_write(ah, val, reg_offset);
228 }
229 
230 static const struct ath_ops ath5k_common_ops = {
231 	.read = ath5k_ioread32,
232 	.write = ath5k_iowrite32,
233 };
234 
235 /***********************\
236 * Driver Initialization *
237 \***********************/
238 
239 static void ath5k_reg_notifier(struct wiphy *wiphy,
240 			       struct regulatory_request *request)
241 {
242 	struct ieee80211_hw *hw = wiphy_to_ieee80211_hw(wiphy);
243 	struct ath5k_hw *ah = hw->priv;
244 	struct ath_regulatory *regulatory = ath5k_hw_regulatory(ah);
245 
246 	ath_reg_notifier_apply(wiphy, request, regulatory);
247 }
248 
249 /********************\
250 * Channel/mode setup *
251 \********************/
252 
253 /*
254  * Returns true for the channel numbers used.
255  */
256 #ifdef CONFIG_ATH5K_TEST_CHANNELS
257 static bool ath5k_is_standard_channel(short chan, enum ieee80211_band band)
258 {
259 	return true;
260 }
261 
262 #else
263 static bool ath5k_is_standard_channel(short chan, enum ieee80211_band band)
264 {
265 	if (band == IEEE80211_BAND_2GHZ && chan <= 14)
266 		return true;
267 
268 	return	/* UNII 1,2 */
269 		(((chan & 3) == 0 && chan >= 36 && chan <= 64) ||
270 		/* midband */
271 		((chan & 3) == 0 && chan >= 100 && chan <= 140) ||
272 		/* UNII-3 */
273 		((chan & 3) == 1 && chan >= 149 && chan <= 165) ||
274 		/* 802.11j 5.030-5.080 GHz (20MHz) */
275 		(chan == 8 || chan == 12 || chan == 16) ||
276 		/* 802.11j 4.9GHz (20MHz) */
277 		(chan == 184 || chan == 188 || chan == 192 || chan == 196));
278 }
279 #endif
280 
281 static unsigned int
282 ath5k_setup_channels(struct ath5k_hw *ah, struct ieee80211_channel *channels,
283 		unsigned int mode, unsigned int max)
284 {
285 	unsigned int count, size, freq, ch;
286 	enum ieee80211_band band;
287 
288 	switch (mode) {
289 	case AR5K_MODE_11A:
290 		/* 1..220, but 2GHz frequencies are filtered by check_channel */
291 		size = 220;
292 		band = IEEE80211_BAND_5GHZ;
293 		break;
294 	case AR5K_MODE_11B:
295 	case AR5K_MODE_11G:
296 		size = 26;
297 		band = IEEE80211_BAND_2GHZ;
298 		break;
299 	default:
300 		ATH5K_WARN(ah, "bad mode, not copying channels\n");
301 		return 0;
302 	}
303 
304 	count = 0;
305 	for (ch = 1; ch <= size && count < max; ch++) {
306 		freq = ieee80211_channel_to_frequency(ch, band);
307 
308 		if (freq == 0) /* mapping failed - not a standard channel */
309 			continue;
310 
311 		/* Write channel info, needed for ath5k_channel_ok() */
312 		channels[count].center_freq = freq;
313 		channels[count].band = band;
314 		channels[count].hw_value = mode;
315 
316 		/* Check if channel is supported by the chipset */
317 		if (!ath5k_channel_ok(ah, &channels[count]))
318 			continue;
319 
320 		if (!ath5k_is_standard_channel(ch, band))
321 			continue;
322 
323 		count++;
324 	}
325 
326 	return count;
327 }
328 
329 static void
330 ath5k_setup_rate_idx(struct ath5k_hw *ah, struct ieee80211_supported_band *b)
331 {
332 	u8 i;
333 
334 	for (i = 0; i < AR5K_MAX_RATES; i++)
335 		ah->rate_idx[b->band][i] = -1;
336 
337 	for (i = 0; i < b->n_bitrates; i++) {
338 		ah->rate_idx[b->band][b->bitrates[i].hw_value] = i;
339 		if (b->bitrates[i].hw_value_short)
340 			ah->rate_idx[b->band][b->bitrates[i].hw_value_short] = i;
341 	}
342 }
343 
344 static int
345 ath5k_setup_bands(struct ieee80211_hw *hw)
346 {
347 	struct ath5k_hw *ah = hw->priv;
348 	struct ieee80211_supported_band *sband;
349 	int max_c, count_c = 0;
350 	int i;
351 
352 	BUILD_BUG_ON(ARRAY_SIZE(ah->sbands) < IEEE80211_NUM_BANDS);
353 	max_c = ARRAY_SIZE(ah->channels);
354 
355 	/* 2GHz band */
356 	sband = &ah->sbands[IEEE80211_BAND_2GHZ];
357 	sband->band = IEEE80211_BAND_2GHZ;
358 	sband->bitrates = &ah->rates[IEEE80211_BAND_2GHZ][0];
359 
360 	if (test_bit(AR5K_MODE_11G, ah->ah_capabilities.cap_mode)) {
361 		/* G mode */
362 		memcpy(sband->bitrates, &ath5k_rates[0],
363 		       sizeof(struct ieee80211_rate) * 12);
364 		sband->n_bitrates = 12;
365 
366 		sband->channels = ah->channels;
367 		sband->n_channels = ath5k_setup_channels(ah, sband->channels,
368 					AR5K_MODE_11G, max_c);
369 
370 		hw->wiphy->bands[IEEE80211_BAND_2GHZ] = sband;
371 		count_c = sband->n_channels;
372 		max_c -= count_c;
373 	} else if (test_bit(AR5K_MODE_11B, ah->ah_capabilities.cap_mode)) {
374 		/* B mode */
375 		memcpy(sband->bitrates, &ath5k_rates[0],
376 		       sizeof(struct ieee80211_rate) * 4);
377 		sband->n_bitrates = 4;
378 
379 		/* 5211 only supports B rates and uses 4bit rate codes
380 		 * (e.g normally we have 0x1B for 1M, but on 5211 we have 0x0B)
381 		 * fix them up here:
382 		 */
383 		if (ah->ah_version == AR5K_AR5211) {
384 			for (i = 0; i < 4; i++) {
385 				sband->bitrates[i].hw_value =
386 					sband->bitrates[i].hw_value & 0xF;
387 				sband->bitrates[i].hw_value_short =
388 					sband->bitrates[i].hw_value_short & 0xF;
389 			}
390 		}
391 
392 		sband->channels = ah->channels;
393 		sband->n_channels = ath5k_setup_channels(ah, sband->channels,
394 					AR5K_MODE_11B, max_c);
395 
396 		hw->wiphy->bands[IEEE80211_BAND_2GHZ] = sband;
397 		count_c = sband->n_channels;
398 		max_c -= count_c;
399 	}
400 	ath5k_setup_rate_idx(ah, sband);
401 
402 	/* 5GHz band, A mode */
403 	if (test_bit(AR5K_MODE_11A, ah->ah_capabilities.cap_mode)) {
404 		sband = &ah->sbands[IEEE80211_BAND_5GHZ];
405 		sband->band = IEEE80211_BAND_5GHZ;
406 		sband->bitrates = &ah->rates[IEEE80211_BAND_5GHZ][0];
407 
408 		memcpy(sband->bitrates, &ath5k_rates[4],
409 		       sizeof(struct ieee80211_rate) * 8);
410 		sband->n_bitrates = 8;
411 
412 		sband->channels = &ah->channels[count_c];
413 		sband->n_channels = ath5k_setup_channels(ah, sband->channels,
414 					AR5K_MODE_11A, max_c);
415 
416 		hw->wiphy->bands[IEEE80211_BAND_5GHZ] = sband;
417 	}
418 	ath5k_setup_rate_idx(ah, sband);
419 
420 	ath5k_debug_dump_bands(ah);
421 
422 	return 0;
423 }
424 
425 /*
426  * Set/change channels. We always reset the chip.
427  * To accomplish this we must first cleanup any pending DMA,
428  * then restart stuff after a la  ath5k_init.
429  *
430  * Called with ah->lock.
431  */
432 int
433 ath5k_chan_set(struct ath5k_hw *ah, struct cfg80211_chan_def *chandef)
434 {
435 	ATH5K_DBG(ah, ATH5K_DEBUG_RESET,
436 		  "channel set, resetting (%u -> %u MHz)\n",
437 		  ah->curchan->center_freq, chandef->chan->center_freq);
438 
439 	switch (chandef->width) {
440 	case NL80211_CHAN_WIDTH_20:
441 	case NL80211_CHAN_WIDTH_20_NOHT:
442 		ah->ah_bwmode = AR5K_BWMODE_DEFAULT;
443 		break;
444 	case NL80211_CHAN_WIDTH_5:
445 		ah->ah_bwmode = AR5K_BWMODE_5MHZ;
446 		break;
447 	case NL80211_CHAN_WIDTH_10:
448 		ah->ah_bwmode = AR5K_BWMODE_10MHZ;
449 		break;
450 	default:
451 		WARN_ON(1);
452 		return -EINVAL;
453 	}
454 
455 	/*
456 	 * To switch channels clear any pending DMA operations;
457 	 * wait long enough for the RX fifo to drain, reset the
458 	 * hardware at the new frequency, and then re-enable
459 	 * the relevant bits of the h/w.
460 	 */
461 	return ath5k_reset(ah, chandef->chan, true);
462 }
463 
464 void ath5k_vif_iter(void *data, u8 *mac, struct ieee80211_vif *vif)
465 {
466 	struct ath5k_vif_iter_data *iter_data = data;
467 	int i;
468 	struct ath5k_vif *avf = (void *)vif->drv_priv;
469 
470 	if (iter_data->hw_macaddr)
471 		for (i = 0; i < ETH_ALEN; i++)
472 			iter_data->mask[i] &=
473 				~(iter_data->hw_macaddr[i] ^ mac[i]);
474 
475 	if (!iter_data->found_active) {
476 		iter_data->found_active = true;
477 		memcpy(iter_data->active_mac, mac, ETH_ALEN);
478 	}
479 
480 	if (iter_data->need_set_hw_addr && iter_data->hw_macaddr)
481 		if (ether_addr_equal(iter_data->hw_macaddr, mac))
482 			iter_data->need_set_hw_addr = false;
483 
484 	if (!iter_data->any_assoc) {
485 		if (avf->assoc)
486 			iter_data->any_assoc = true;
487 	}
488 
489 	/* Calculate combined mode - when APs are active, operate in AP mode.
490 	 * Otherwise use the mode of the new interface. This can currently
491 	 * only deal with combinations of APs and STAs. Only one ad-hoc
492 	 * interfaces is allowed.
493 	 */
494 	if (avf->opmode == NL80211_IFTYPE_AP)
495 		iter_data->opmode = NL80211_IFTYPE_AP;
496 	else {
497 		if (avf->opmode == NL80211_IFTYPE_STATION)
498 			iter_data->n_stas++;
499 		if (iter_data->opmode == NL80211_IFTYPE_UNSPECIFIED)
500 			iter_data->opmode = avf->opmode;
501 	}
502 }
503 
504 void
505 ath5k_update_bssid_mask_and_opmode(struct ath5k_hw *ah,
506 				   struct ieee80211_vif *vif)
507 {
508 	struct ath_common *common = ath5k_hw_common(ah);
509 	struct ath5k_vif_iter_data iter_data;
510 	u32 rfilt;
511 
512 	/*
513 	 * Use the hardware MAC address as reference, the hardware uses it
514 	 * together with the BSSID mask when matching addresses.
515 	 */
516 	iter_data.hw_macaddr = common->macaddr;
517 	memset(&iter_data.mask, 0xff, ETH_ALEN);
518 	iter_data.found_active = false;
519 	iter_data.need_set_hw_addr = true;
520 	iter_data.opmode = NL80211_IFTYPE_UNSPECIFIED;
521 	iter_data.n_stas = 0;
522 
523 	if (vif)
524 		ath5k_vif_iter(&iter_data, vif->addr, vif);
525 
526 	/* Get list of all active MAC addresses */
527 	ieee80211_iterate_active_interfaces_atomic(
528 		ah->hw, IEEE80211_IFACE_ITER_RESUME_ALL,
529 		ath5k_vif_iter, &iter_data);
530 	memcpy(ah->bssidmask, iter_data.mask, ETH_ALEN);
531 
532 	ah->opmode = iter_data.opmode;
533 	if (ah->opmode == NL80211_IFTYPE_UNSPECIFIED)
534 		/* Nothing active, default to station mode */
535 		ah->opmode = NL80211_IFTYPE_STATION;
536 
537 	ath5k_hw_set_opmode(ah, ah->opmode);
538 	ATH5K_DBG(ah, ATH5K_DEBUG_MODE, "mode setup opmode %d (%s)\n",
539 		  ah->opmode, ath_opmode_to_string(ah->opmode));
540 
541 	if (iter_data.need_set_hw_addr && iter_data.found_active)
542 		ath5k_hw_set_lladdr(ah, iter_data.active_mac);
543 
544 	if (ath5k_hw_hasbssidmask(ah))
545 		ath5k_hw_set_bssid_mask(ah, ah->bssidmask);
546 
547 	/* Set up RX Filter */
548 	if (iter_data.n_stas > 1) {
549 		/* If you have multiple STA interfaces connected to
550 		 * different APs, ARPs are not received (most of the time?)
551 		 * Enabling PROMISC appears to fix that problem.
552 		 */
553 		ah->filter_flags |= AR5K_RX_FILTER_PROM;
554 	}
555 
556 	rfilt = ah->filter_flags;
557 	ath5k_hw_set_rx_filter(ah, rfilt);
558 	ATH5K_DBG(ah, ATH5K_DEBUG_MODE, "RX filter 0x%x\n", rfilt);
559 }
560 
561 static inline int
562 ath5k_hw_to_driver_rix(struct ath5k_hw *ah, int hw_rix)
563 {
564 	int rix;
565 
566 	/* return base rate on errors */
567 	if (WARN(hw_rix < 0 || hw_rix >= AR5K_MAX_RATES,
568 			"hw_rix out of bounds: %x\n", hw_rix))
569 		return 0;
570 
571 	rix = ah->rate_idx[ah->curchan->band][hw_rix];
572 	if (WARN(rix < 0, "invalid hw_rix: %x\n", hw_rix))
573 		rix = 0;
574 
575 	return rix;
576 }
577 
578 /***************\
579 * Buffers setup *
580 \***************/
581 
582 static
583 struct sk_buff *ath5k_rx_skb_alloc(struct ath5k_hw *ah, dma_addr_t *skb_addr)
584 {
585 	struct ath_common *common = ath5k_hw_common(ah);
586 	struct sk_buff *skb;
587 
588 	/*
589 	 * Allocate buffer with headroom_needed space for the
590 	 * fake physical layer header at the start.
591 	 */
592 	skb = ath_rxbuf_alloc(common,
593 			      common->rx_bufsize,
594 			      GFP_ATOMIC);
595 
596 	if (!skb) {
597 		ATH5K_ERR(ah, "can't alloc skbuff of size %u\n",
598 				common->rx_bufsize);
599 		return NULL;
600 	}
601 
602 	*skb_addr = dma_map_single(ah->dev,
603 				   skb->data, common->rx_bufsize,
604 				   DMA_FROM_DEVICE);
605 
606 	if (unlikely(dma_mapping_error(ah->dev, *skb_addr))) {
607 		ATH5K_ERR(ah, "%s: DMA mapping failed\n", __func__);
608 		dev_kfree_skb(skb);
609 		return NULL;
610 	}
611 	return skb;
612 }
613 
614 static int
615 ath5k_rxbuf_setup(struct ath5k_hw *ah, struct ath5k_buf *bf)
616 {
617 	struct sk_buff *skb = bf->skb;
618 	struct ath5k_desc *ds;
619 	int ret;
620 
621 	if (!skb) {
622 		skb = ath5k_rx_skb_alloc(ah, &bf->skbaddr);
623 		if (!skb)
624 			return -ENOMEM;
625 		bf->skb = skb;
626 	}
627 
628 	/*
629 	 * Setup descriptors.  For receive we always terminate
630 	 * the descriptor list with a self-linked entry so we'll
631 	 * not get overrun under high load (as can happen with a
632 	 * 5212 when ANI processing enables PHY error frames).
633 	 *
634 	 * To ensure the last descriptor is self-linked we create
635 	 * each descriptor as self-linked and add it to the end.  As
636 	 * each additional descriptor is added the previous self-linked
637 	 * entry is "fixed" naturally.  This should be safe even
638 	 * if DMA is happening.  When processing RX interrupts we
639 	 * never remove/process the last, self-linked, entry on the
640 	 * descriptor list.  This ensures the hardware always has
641 	 * someplace to write a new frame.
642 	 */
643 	ds = bf->desc;
644 	ds->ds_link = bf->daddr;	/* link to self */
645 	ds->ds_data = bf->skbaddr;
646 	ret = ath5k_hw_setup_rx_desc(ah, ds, ah->common.rx_bufsize, 0);
647 	if (ret) {
648 		ATH5K_ERR(ah, "%s: could not setup RX desc\n", __func__);
649 		return ret;
650 	}
651 
652 	if (ah->rxlink != NULL)
653 		*ah->rxlink = bf->daddr;
654 	ah->rxlink = &ds->ds_link;
655 	return 0;
656 }
657 
658 static enum ath5k_pkt_type get_hw_packet_type(struct sk_buff *skb)
659 {
660 	struct ieee80211_hdr *hdr;
661 	enum ath5k_pkt_type htype;
662 	__le16 fc;
663 
664 	hdr = (struct ieee80211_hdr *)skb->data;
665 	fc = hdr->frame_control;
666 
667 	if (ieee80211_is_beacon(fc))
668 		htype = AR5K_PKT_TYPE_BEACON;
669 	else if (ieee80211_is_probe_resp(fc))
670 		htype = AR5K_PKT_TYPE_PROBE_RESP;
671 	else if (ieee80211_is_atim(fc))
672 		htype = AR5K_PKT_TYPE_ATIM;
673 	else if (ieee80211_is_pspoll(fc))
674 		htype = AR5K_PKT_TYPE_PSPOLL;
675 	else
676 		htype = AR5K_PKT_TYPE_NORMAL;
677 
678 	return htype;
679 }
680 
681 static struct ieee80211_rate *
682 ath5k_get_rate(const struct ieee80211_hw *hw,
683 	       const struct ieee80211_tx_info *info,
684 	       struct ath5k_buf *bf, int idx)
685 {
686 	/*
687 	* convert a ieee80211_tx_rate RC-table entry to
688 	* the respective ieee80211_rate struct
689 	*/
690 	if (bf->rates[idx].idx < 0) {
691 		return NULL;
692 	}
693 
694 	return &hw->wiphy->bands[info->band]->bitrates[ bf->rates[idx].idx ];
695 }
696 
697 static u16
698 ath5k_get_rate_hw_value(const struct ieee80211_hw *hw,
699 			const struct ieee80211_tx_info *info,
700 			struct ath5k_buf *bf, int idx)
701 {
702 	struct ieee80211_rate *rate;
703 	u16 hw_rate;
704 	u8 rc_flags;
705 
706 	rate = ath5k_get_rate(hw, info, bf, idx);
707 	if (!rate)
708 		return 0;
709 
710 	rc_flags = bf->rates[idx].flags;
711 	hw_rate = (rc_flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE) ?
712 		   rate->hw_value_short : rate->hw_value;
713 
714 	return hw_rate;
715 }
716 
717 static int
718 ath5k_txbuf_setup(struct ath5k_hw *ah, struct ath5k_buf *bf,
719 		  struct ath5k_txq *txq, int padsize,
720 		  struct ieee80211_tx_control *control)
721 {
722 	struct ath5k_desc *ds = bf->desc;
723 	struct sk_buff *skb = bf->skb;
724 	struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
725 	unsigned int pktlen, flags, keyidx = AR5K_TXKEYIX_INVALID;
726 	struct ieee80211_rate *rate;
727 	unsigned int mrr_rate[3], mrr_tries[3];
728 	int i, ret;
729 	u16 hw_rate;
730 	u16 cts_rate = 0;
731 	u16 duration = 0;
732 	u8 rc_flags;
733 
734 	flags = AR5K_TXDESC_INTREQ | AR5K_TXDESC_CLRDMASK;
735 
736 	/* XXX endianness */
737 	bf->skbaddr = dma_map_single(ah->dev, skb->data, skb->len,
738 			DMA_TO_DEVICE);
739 
740 	if (dma_mapping_error(ah->dev, bf->skbaddr))
741 		return -ENOSPC;
742 
743 	ieee80211_get_tx_rates(info->control.vif, (control) ? control->sta : NULL, skb, bf->rates,
744 			       ARRAY_SIZE(bf->rates));
745 
746 	rate = ath5k_get_rate(ah->hw, info, bf, 0);
747 
748 	if (!rate) {
749 		ret = -EINVAL;
750 		goto err_unmap;
751 	}
752 
753 	if (info->flags & IEEE80211_TX_CTL_NO_ACK)
754 		flags |= AR5K_TXDESC_NOACK;
755 
756 	rc_flags = info->control.rates[0].flags;
757 
758 	hw_rate = ath5k_get_rate_hw_value(ah->hw, info, bf, 0);
759 
760 	pktlen = skb->len;
761 
762 	/* FIXME: If we are in g mode and rate is a CCK rate
763 	 * subtract ah->ah_txpower.txp_cck_ofdm_pwr_delta
764 	 * from tx power (value is in dB units already) */
765 	if (info->control.hw_key) {
766 		keyidx = info->control.hw_key->hw_key_idx;
767 		pktlen += info->control.hw_key->icv_len;
768 	}
769 	if (rc_flags & IEEE80211_TX_RC_USE_RTS_CTS) {
770 		flags |= AR5K_TXDESC_RTSENA;
771 		cts_rate = ieee80211_get_rts_cts_rate(ah->hw, info)->hw_value;
772 		duration = le16_to_cpu(ieee80211_rts_duration(ah->hw,
773 			info->control.vif, pktlen, info));
774 	}
775 	if (rc_flags & IEEE80211_TX_RC_USE_CTS_PROTECT) {
776 		flags |= AR5K_TXDESC_CTSENA;
777 		cts_rate = ieee80211_get_rts_cts_rate(ah->hw, info)->hw_value;
778 		duration = le16_to_cpu(ieee80211_ctstoself_duration(ah->hw,
779 			info->control.vif, pktlen, info));
780 	}
781 
782 	ret = ah->ah_setup_tx_desc(ah, ds, pktlen,
783 		ieee80211_get_hdrlen_from_skb(skb), padsize,
784 		get_hw_packet_type(skb),
785 		(ah->ah_txpower.txp_requested * 2),
786 		hw_rate,
787 		bf->rates[0].count, keyidx, ah->ah_tx_ant, flags,
788 		cts_rate, duration);
789 	if (ret)
790 		goto err_unmap;
791 
792 	/* Set up MRR descriptor */
793 	if (ah->ah_capabilities.cap_has_mrr_support) {
794 		memset(mrr_rate, 0, sizeof(mrr_rate));
795 		memset(mrr_tries, 0, sizeof(mrr_tries));
796 
797 		for (i = 0; i < 3; i++) {
798 
799 			rate = ath5k_get_rate(ah->hw, info, bf, i);
800 			if (!rate)
801 				break;
802 
803 			mrr_rate[i] = ath5k_get_rate_hw_value(ah->hw, info, bf, i);
804 			mrr_tries[i] = bf->rates[i].count;
805 		}
806 
807 		ath5k_hw_setup_mrr_tx_desc(ah, ds,
808 			mrr_rate[0], mrr_tries[0],
809 			mrr_rate[1], mrr_tries[1],
810 			mrr_rate[2], mrr_tries[2]);
811 	}
812 
813 	ds->ds_link = 0;
814 	ds->ds_data = bf->skbaddr;
815 
816 	spin_lock_bh(&txq->lock);
817 	list_add_tail(&bf->list, &txq->q);
818 	txq->txq_len++;
819 	if (txq->link == NULL) /* is this first packet? */
820 		ath5k_hw_set_txdp(ah, txq->qnum, bf->daddr);
821 	else /* no, so only link it */
822 		*txq->link = bf->daddr;
823 
824 	txq->link = &ds->ds_link;
825 	ath5k_hw_start_tx_dma(ah, txq->qnum);
826 	mmiowb();
827 	spin_unlock_bh(&txq->lock);
828 
829 	return 0;
830 err_unmap:
831 	dma_unmap_single(ah->dev, bf->skbaddr, skb->len, DMA_TO_DEVICE);
832 	return ret;
833 }
834 
835 /*******************\
836 * Descriptors setup *
837 \*******************/
838 
839 static int
840 ath5k_desc_alloc(struct ath5k_hw *ah)
841 {
842 	struct ath5k_desc *ds;
843 	struct ath5k_buf *bf;
844 	dma_addr_t da;
845 	unsigned int i;
846 	int ret;
847 
848 	/* allocate descriptors */
849 	ah->desc_len = sizeof(struct ath5k_desc) *
850 			(ATH_TXBUF + ATH_RXBUF + ATH_BCBUF + 1);
851 
852 	ah->desc = dma_alloc_coherent(ah->dev, ah->desc_len,
853 				&ah->desc_daddr, GFP_KERNEL);
854 	if (ah->desc == NULL) {
855 		ATH5K_ERR(ah, "can't allocate descriptors\n");
856 		ret = -ENOMEM;
857 		goto err;
858 	}
859 	ds = ah->desc;
860 	da = ah->desc_daddr;
861 	ATH5K_DBG(ah, ATH5K_DEBUG_ANY, "DMA map: %p (%zu) -> %llx\n",
862 		ds, ah->desc_len, (unsigned long long)ah->desc_daddr);
863 
864 	bf = kcalloc(1 + ATH_TXBUF + ATH_RXBUF + ATH_BCBUF,
865 			sizeof(struct ath5k_buf), GFP_KERNEL);
866 	if (bf == NULL) {
867 		ATH5K_ERR(ah, "can't allocate bufptr\n");
868 		ret = -ENOMEM;
869 		goto err_free;
870 	}
871 	ah->bufptr = bf;
872 
873 	INIT_LIST_HEAD(&ah->rxbuf);
874 	for (i = 0; i < ATH_RXBUF; i++, bf++, ds++, da += sizeof(*ds)) {
875 		bf->desc = ds;
876 		bf->daddr = da;
877 		list_add_tail(&bf->list, &ah->rxbuf);
878 	}
879 
880 	INIT_LIST_HEAD(&ah->txbuf);
881 	ah->txbuf_len = ATH_TXBUF;
882 	for (i = 0; i < ATH_TXBUF; i++, bf++, ds++, da += sizeof(*ds)) {
883 		bf->desc = ds;
884 		bf->daddr = da;
885 		list_add_tail(&bf->list, &ah->txbuf);
886 	}
887 
888 	/* beacon buffers */
889 	INIT_LIST_HEAD(&ah->bcbuf);
890 	for (i = 0; i < ATH_BCBUF; i++, bf++, ds++, da += sizeof(*ds)) {
891 		bf->desc = ds;
892 		bf->daddr = da;
893 		list_add_tail(&bf->list, &ah->bcbuf);
894 	}
895 
896 	return 0;
897 err_free:
898 	dma_free_coherent(ah->dev, ah->desc_len, ah->desc, ah->desc_daddr);
899 err:
900 	ah->desc = NULL;
901 	return ret;
902 }
903 
904 void
905 ath5k_txbuf_free_skb(struct ath5k_hw *ah, struct ath5k_buf *bf)
906 {
907 	BUG_ON(!bf);
908 	if (!bf->skb)
909 		return;
910 	dma_unmap_single(ah->dev, bf->skbaddr, bf->skb->len,
911 			DMA_TO_DEVICE);
912 	ieee80211_free_txskb(ah->hw, bf->skb);
913 	bf->skb = NULL;
914 	bf->skbaddr = 0;
915 	bf->desc->ds_data = 0;
916 }
917 
918 void
919 ath5k_rxbuf_free_skb(struct ath5k_hw *ah, struct ath5k_buf *bf)
920 {
921 	struct ath_common *common = ath5k_hw_common(ah);
922 
923 	BUG_ON(!bf);
924 	if (!bf->skb)
925 		return;
926 	dma_unmap_single(ah->dev, bf->skbaddr, common->rx_bufsize,
927 			DMA_FROM_DEVICE);
928 	dev_kfree_skb_any(bf->skb);
929 	bf->skb = NULL;
930 	bf->skbaddr = 0;
931 	bf->desc->ds_data = 0;
932 }
933 
934 static void
935 ath5k_desc_free(struct ath5k_hw *ah)
936 {
937 	struct ath5k_buf *bf;
938 
939 	list_for_each_entry(bf, &ah->txbuf, list)
940 		ath5k_txbuf_free_skb(ah, bf);
941 	list_for_each_entry(bf, &ah->rxbuf, list)
942 		ath5k_rxbuf_free_skb(ah, bf);
943 	list_for_each_entry(bf, &ah->bcbuf, list)
944 		ath5k_txbuf_free_skb(ah, bf);
945 
946 	/* Free memory associated with all descriptors */
947 	dma_free_coherent(ah->dev, ah->desc_len, ah->desc, ah->desc_daddr);
948 	ah->desc = NULL;
949 	ah->desc_daddr = 0;
950 
951 	kfree(ah->bufptr);
952 	ah->bufptr = NULL;
953 }
954 
955 
956 /**************\
957 * Queues setup *
958 \**************/
959 
960 static struct ath5k_txq *
961 ath5k_txq_setup(struct ath5k_hw *ah,
962 		int qtype, int subtype)
963 {
964 	struct ath5k_txq *txq;
965 	struct ath5k_txq_info qi = {
966 		.tqi_subtype = subtype,
967 		/* XXX: default values not correct for B and XR channels,
968 		 * but who cares? */
969 		.tqi_aifs = AR5K_TUNE_AIFS,
970 		.tqi_cw_min = AR5K_TUNE_CWMIN,
971 		.tqi_cw_max = AR5K_TUNE_CWMAX
972 	};
973 	int qnum;
974 
975 	/*
976 	 * Enable interrupts only for EOL and DESC conditions.
977 	 * We mark tx descriptors to receive a DESC interrupt
978 	 * when a tx queue gets deep; otherwise we wait for the
979 	 * EOL to reap descriptors.  Note that this is done to
980 	 * reduce interrupt load and this only defers reaping
981 	 * descriptors, never transmitting frames.  Aside from
982 	 * reducing interrupts this also permits more concurrency.
983 	 * The only potential downside is if the tx queue backs
984 	 * up in which case the top half of the kernel may backup
985 	 * due to a lack of tx descriptors.
986 	 */
987 	qi.tqi_flags = AR5K_TXQ_FLAG_TXEOLINT_ENABLE |
988 				AR5K_TXQ_FLAG_TXDESCINT_ENABLE;
989 	qnum = ath5k_hw_setup_tx_queue(ah, qtype, &qi);
990 	if (qnum < 0) {
991 		/*
992 		 * NB: don't print a message, this happens
993 		 * normally on parts with too few tx queues
994 		 */
995 		return ERR_PTR(qnum);
996 	}
997 	txq = &ah->txqs[qnum];
998 	if (!txq->setup) {
999 		txq->qnum = qnum;
1000 		txq->link = NULL;
1001 		INIT_LIST_HEAD(&txq->q);
1002 		spin_lock_init(&txq->lock);
1003 		txq->setup = true;
1004 		txq->txq_len = 0;
1005 		txq->txq_max = ATH5K_TXQ_LEN_MAX;
1006 		txq->txq_poll_mark = false;
1007 		txq->txq_stuck = 0;
1008 	}
1009 	return &ah->txqs[qnum];
1010 }
1011 
1012 static int
1013 ath5k_beaconq_setup(struct ath5k_hw *ah)
1014 {
1015 	struct ath5k_txq_info qi = {
1016 		/* XXX: default values not correct for B and XR channels,
1017 		 * but who cares? */
1018 		.tqi_aifs = AR5K_TUNE_AIFS,
1019 		.tqi_cw_min = AR5K_TUNE_CWMIN,
1020 		.tqi_cw_max = AR5K_TUNE_CWMAX,
1021 		/* NB: for dynamic turbo, don't enable any other interrupts */
1022 		.tqi_flags = AR5K_TXQ_FLAG_TXDESCINT_ENABLE
1023 	};
1024 
1025 	return ath5k_hw_setup_tx_queue(ah, AR5K_TX_QUEUE_BEACON, &qi);
1026 }
1027 
1028 static int
1029 ath5k_beaconq_config(struct ath5k_hw *ah)
1030 {
1031 	struct ath5k_txq_info qi;
1032 	int ret;
1033 
1034 	ret = ath5k_hw_get_tx_queueprops(ah, ah->bhalq, &qi);
1035 	if (ret)
1036 		goto err;
1037 
1038 	if (ah->opmode == NL80211_IFTYPE_AP ||
1039 	    ah->opmode == NL80211_IFTYPE_MESH_POINT) {
1040 		/*
1041 		 * Always burst out beacon and CAB traffic
1042 		 * (aifs = cwmin = cwmax = 0)
1043 		 */
1044 		qi.tqi_aifs = 0;
1045 		qi.tqi_cw_min = 0;
1046 		qi.tqi_cw_max = 0;
1047 	} else if (ah->opmode == NL80211_IFTYPE_ADHOC) {
1048 		/*
1049 		 * Adhoc mode; backoff between 0 and (2 * cw_min).
1050 		 */
1051 		qi.tqi_aifs = 0;
1052 		qi.tqi_cw_min = 0;
1053 		qi.tqi_cw_max = 2 * AR5K_TUNE_CWMIN;
1054 	}
1055 
1056 	ATH5K_DBG(ah, ATH5K_DEBUG_BEACON,
1057 		"beacon queueprops tqi_aifs:%d tqi_cw_min:%d tqi_cw_max:%d\n",
1058 		qi.tqi_aifs, qi.tqi_cw_min, qi.tqi_cw_max);
1059 
1060 	ret = ath5k_hw_set_tx_queueprops(ah, ah->bhalq, &qi);
1061 	if (ret) {
1062 		ATH5K_ERR(ah, "%s: unable to update parameters for beacon "
1063 			"hardware queue!\n", __func__);
1064 		goto err;
1065 	}
1066 	ret = ath5k_hw_reset_tx_queue(ah, ah->bhalq); /* push to h/w */
1067 	if (ret)
1068 		goto err;
1069 
1070 	/* reconfigure cabq with ready time to 80% of beacon_interval */
1071 	ret = ath5k_hw_get_tx_queueprops(ah, AR5K_TX_QUEUE_ID_CAB, &qi);
1072 	if (ret)
1073 		goto err;
1074 
1075 	qi.tqi_ready_time = (ah->bintval * 80) / 100;
1076 	ret = ath5k_hw_set_tx_queueprops(ah, AR5K_TX_QUEUE_ID_CAB, &qi);
1077 	if (ret)
1078 		goto err;
1079 
1080 	ret = ath5k_hw_reset_tx_queue(ah, AR5K_TX_QUEUE_ID_CAB);
1081 err:
1082 	return ret;
1083 }
1084 
1085 /**
1086  * ath5k_drain_tx_buffs - Empty tx buffers
1087  *
1088  * @ah The &struct ath5k_hw
1089  *
1090  * Empty tx buffers from all queues in preparation
1091  * of a reset or during shutdown.
1092  *
1093  * NB:	this assumes output has been stopped and
1094  *	we do not need to block ath5k_tx_tasklet
1095  */
1096 static void
1097 ath5k_drain_tx_buffs(struct ath5k_hw *ah)
1098 {
1099 	struct ath5k_txq *txq;
1100 	struct ath5k_buf *bf, *bf0;
1101 	int i;
1102 
1103 	for (i = 0; i < ARRAY_SIZE(ah->txqs); i++) {
1104 		if (ah->txqs[i].setup) {
1105 			txq = &ah->txqs[i];
1106 			spin_lock_bh(&txq->lock);
1107 			list_for_each_entry_safe(bf, bf0, &txq->q, list) {
1108 				ath5k_debug_printtxbuf(ah, bf);
1109 
1110 				ath5k_txbuf_free_skb(ah, bf);
1111 
1112 				spin_lock(&ah->txbuflock);
1113 				list_move_tail(&bf->list, &ah->txbuf);
1114 				ah->txbuf_len++;
1115 				txq->txq_len--;
1116 				spin_unlock(&ah->txbuflock);
1117 			}
1118 			txq->link = NULL;
1119 			txq->txq_poll_mark = false;
1120 			spin_unlock_bh(&txq->lock);
1121 		}
1122 	}
1123 }
1124 
1125 static void
1126 ath5k_txq_release(struct ath5k_hw *ah)
1127 {
1128 	struct ath5k_txq *txq = ah->txqs;
1129 	unsigned int i;
1130 
1131 	for (i = 0; i < ARRAY_SIZE(ah->txqs); i++, txq++)
1132 		if (txq->setup) {
1133 			ath5k_hw_release_tx_queue(ah, txq->qnum);
1134 			txq->setup = false;
1135 		}
1136 }
1137 
1138 
1139 /*************\
1140 * RX Handling *
1141 \*************/
1142 
1143 /*
1144  * Enable the receive h/w following a reset.
1145  */
1146 static int
1147 ath5k_rx_start(struct ath5k_hw *ah)
1148 {
1149 	struct ath_common *common = ath5k_hw_common(ah);
1150 	struct ath5k_buf *bf;
1151 	int ret;
1152 
1153 	common->rx_bufsize = roundup(IEEE80211_MAX_FRAME_LEN, common->cachelsz);
1154 
1155 	ATH5K_DBG(ah, ATH5K_DEBUG_RESET, "cachelsz %u rx_bufsize %u\n",
1156 		  common->cachelsz, common->rx_bufsize);
1157 
1158 	spin_lock_bh(&ah->rxbuflock);
1159 	ah->rxlink = NULL;
1160 	list_for_each_entry(bf, &ah->rxbuf, list) {
1161 		ret = ath5k_rxbuf_setup(ah, bf);
1162 		if (ret != 0) {
1163 			spin_unlock_bh(&ah->rxbuflock);
1164 			goto err;
1165 		}
1166 	}
1167 	bf = list_first_entry(&ah->rxbuf, struct ath5k_buf, list);
1168 	ath5k_hw_set_rxdp(ah, bf->daddr);
1169 	spin_unlock_bh(&ah->rxbuflock);
1170 
1171 	ath5k_hw_start_rx_dma(ah);	/* enable recv descriptors */
1172 	ath5k_update_bssid_mask_and_opmode(ah, NULL); /* set filters, etc. */
1173 	ath5k_hw_start_rx_pcu(ah);	/* re-enable PCU/DMA engine */
1174 
1175 	return 0;
1176 err:
1177 	return ret;
1178 }
1179 
1180 /*
1181  * Disable the receive logic on PCU (DRU)
1182  * In preparation for a shutdown.
1183  *
1184  * Note: Doesn't stop rx DMA, ath5k_hw_dma_stop
1185  * does.
1186  */
1187 static void
1188 ath5k_rx_stop(struct ath5k_hw *ah)
1189 {
1190 
1191 	ath5k_hw_set_rx_filter(ah, 0);	/* clear recv filter */
1192 	ath5k_hw_stop_rx_pcu(ah);	/* disable PCU */
1193 
1194 	ath5k_debug_printrxbuffs(ah);
1195 }
1196 
1197 static unsigned int
1198 ath5k_rx_decrypted(struct ath5k_hw *ah, struct sk_buff *skb,
1199 		   struct ath5k_rx_status *rs)
1200 {
1201 	struct ath_common *common = ath5k_hw_common(ah);
1202 	struct ieee80211_hdr *hdr = (void *)skb->data;
1203 	unsigned int keyix, hlen;
1204 
1205 	if (!(rs->rs_status & AR5K_RXERR_DECRYPT) &&
1206 			rs->rs_keyix != AR5K_RXKEYIX_INVALID)
1207 		return RX_FLAG_DECRYPTED;
1208 
1209 	/* Apparently when a default key is used to decrypt the packet
1210 	   the hw does not set the index used to decrypt.  In such cases
1211 	   get the index from the packet. */
1212 	hlen = ieee80211_hdrlen(hdr->frame_control);
1213 	if (ieee80211_has_protected(hdr->frame_control) &&
1214 	    !(rs->rs_status & AR5K_RXERR_DECRYPT) &&
1215 	    skb->len >= hlen + 4) {
1216 		keyix = skb->data[hlen + 3] >> 6;
1217 
1218 		if (test_bit(keyix, common->keymap))
1219 			return RX_FLAG_DECRYPTED;
1220 	}
1221 
1222 	return 0;
1223 }
1224 
1225 
1226 static void
1227 ath5k_check_ibss_tsf(struct ath5k_hw *ah, struct sk_buff *skb,
1228 		     struct ieee80211_rx_status *rxs)
1229 {
1230 	u64 tsf, bc_tstamp;
1231 	u32 hw_tu;
1232 	struct ieee80211_mgmt *mgmt = (struct ieee80211_mgmt *)skb->data;
1233 
1234 	if (le16_to_cpu(mgmt->u.beacon.capab_info) & WLAN_CAPABILITY_IBSS) {
1235 		/*
1236 		 * Received an IBSS beacon with the same BSSID. Hardware *must*
1237 		 * have updated the local TSF. We have to work around various
1238 		 * hardware bugs, though...
1239 		 */
1240 		tsf = ath5k_hw_get_tsf64(ah);
1241 		bc_tstamp = le64_to_cpu(mgmt->u.beacon.timestamp);
1242 		hw_tu = TSF_TO_TU(tsf);
1243 
1244 		ATH5K_DBG_UNLIMIT(ah, ATH5K_DEBUG_BEACON,
1245 			"beacon %llx mactime %llx (diff %lld) tsf now %llx\n",
1246 			(unsigned long long)bc_tstamp,
1247 			(unsigned long long)rxs->mactime,
1248 			(unsigned long long)(rxs->mactime - bc_tstamp),
1249 			(unsigned long long)tsf);
1250 
1251 		/*
1252 		 * Sometimes the HW will give us a wrong tstamp in the rx
1253 		 * status, causing the timestamp extension to go wrong.
1254 		 * (This seems to happen especially with beacon frames bigger
1255 		 * than 78 byte (incl. FCS))
1256 		 * But we know that the receive timestamp must be later than the
1257 		 * timestamp of the beacon since HW must have synced to that.
1258 		 *
1259 		 * NOTE: here we assume mactime to be after the frame was
1260 		 * received, not like mac80211 which defines it at the start.
1261 		 */
1262 		if (bc_tstamp > rxs->mactime) {
1263 			ATH5K_DBG_UNLIMIT(ah, ATH5K_DEBUG_BEACON,
1264 				"fixing mactime from %llx to %llx\n",
1265 				(unsigned long long)rxs->mactime,
1266 				(unsigned long long)tsf);
1267 			rxs->mactime = tsf;
1268 		}
1269 
1270 		/*
1271 		 * Local TSF might have moved higher than our beacon timers,
1272 		 * in that case we have to update them to continue sending
1273 		 * beacons. This also takes care of synchronizing beacon sending
1274 		 * times with other stations.
1275 		 */
1276 		if (hw_tu >= ah->nexttbtt)
1277 			ath5k_beacon_update_timers(ah, bc_tstamp);
1278 
1279 		/* Check if the beacon timers are still correct, because a TSF
1280 		 * update might have created a window between them - for a
1281 		 * longer description see the comment of this function: */
1282 		if (!ath5k_hw_check_beacon_timers(ah, ah->bintval)) {
1283 			ath5k_beacon_update_timers(ah, bc_tstamp);
1284 			ATH5K_DBG_UNLIMIT(ah, ATH5K_DEBUG_BEACON,
1285 				"fixed beacon timers after beacon receive\n");
1286 		}
1287 	}
1288 }
1289 
1290 /*
1291  * Compute padding position. skb must contain an IEEE 802.11 frame
1292  */
1293 static int ath5k_common_padpos(struct sk_buff *skb)
1294 {
1295 	struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
1296 	__le16 frame_control = hdr->frame_control;
1297 	int padpos = 24;
1298 
1299 	if (ieee80211_has_a4(frame_control))
1300 		padpos += ETH_ALEN;
1301 
1302 	if (ieee80211_is_data_qos(frame_control))
1303 		padpos += IEEE80211_QOS_CTL_LEN;
1304 
1305 	return padpos;
1306 }
1307 
1308 /*
1309  * This function expects an 802.11 frame and returns the number of
1310  * bytes added, or -1 if we don't have enough header room.
1311  */
1312 static int ath5k_add_padding(struct sk_buff *skb)
1313 {
1314 	int padpos = ath5k_common_padpos(skb);
1315 	int padsize = padpos & 3;
1316 
1317 	if (padsize && skb->len > padpos) {
1318 
1319 		if (skb_headroom(skb) < padsize)
1320 			return -1;
1321 
1322 		skb_push(skb, padsize);
1323 		memmove(skb->data, skb->data + padsize, padpos);
1324 		return padsize;
1325 	}
1326 
1327 	return 0;
1328 }
1329 
1330 /*
1331  * The MAC header is padded to have 32-bit boundary if the
1332  * packet payload is non-zero. The general calculation for
1333  * padsize would take into account odd header lengths:
1334  * padsize = 4 - (hdrlen & 3); however, since only
1335  * even-length headers are used, padding can only be 0 or 2
1336  * bytes and we can optimize this a bit.  We must not try to
1337  * remove padding from short control frames that do not have a
1338  * payload.
1339  *
1340  * This function expects an 802.11 frame and returns the number of
1341  * bytes removed.
1342  */
1343 static int ath5k_remove_padding(struct sk_buff *skb)
1344 {
1345 	int padpos = ath5k_common_padpos(skb);
1346 	int padsize = padpos & 3;
1347 
1348 	if (padsize && skb->len >= padpos + padsize) {
1349 		memmove(skb->data + padsize, skb->data, padpos);
1350 		skb_pull(skb, padsize);
1351 		return padsize;
1352 	}
1353 
1354 	return 0;
1355 }
1356 
1357 static void
1358 ath5k_receive_frame(struct ath5k_hw *ah, struct sk_buff *skb,
1359 		    struct ath5k_rx_status *rs)
1360 {
1361 	struct ieee80211_rx_status *rxs;
1362 	struct ath_common *common = ath5k_hw_common(ah);
1363 
1364 	ath5k_remove_padding(skb);
1365 
1366 	rxs = IEEE80211_SKB_RXCB(skb);
1367 
1368 	rxs->flag = 0;
1369 	if (unlikely(rs->rs_status & AR5K_RXERR_MIC))
1370 		rxs->flag |= RX_FLAG_MMIC_ERROR;
1371 	if (unlikely(rs->rs_status & AR5K_RXERR_CRC))
1372 		rxs->flag |= RX_FLAG_FAILED_FCS_CRC;
1373 
1374 
1375 	/*
1376 	 * always extend the mac timestamp, since this information is
1377 	 * also needed for proper IBSS merging.
1378 	 *
1379 	 * XXX: it might be too late to do it here, since rs_tstamp is
1380 	 * 15bit only. that means TSF extension has to be done within
1381 	 * 32768usec (about 32ms). it might be necessary to move this to
1382 	 * the interrupt handler, like it is done in madwifi.
1383 	 */
1384 	rxs->mactime = ath5k_extend_tsf(ah, rs->rs_tstamp);
1385 	rxs->flag |= RX_FLAG_MACTIME_END;
1386 
1387 	rxs->freq = ah->curchan->center_freq;
1388 	rxs->band = ah->curchan->band;
1389 
1390 	rxs->signal = ah->ah_noise_floor + rs->rs_rssi;
1391 
1392 	rxs->antenna = rs->rs_antenna;
1393 
1394 	if (rs->rs_antenna > 0 && rs->rs_antenna < 5)
1395 		ah->stats.antenna_rx[rs->rs_antenna]++;
1396 	else
1397 		ah->stats.antenna_rx[0]++; /* invalid */
1398 
1399 	rxs->rate_idx = ath5k_hw_to_driver_rix(ah, rs->rs_rate);
1400 	rxs->flag |= ath5k_rx_decrypted(ah, skb, rs);
1401 	switch (ah->ah_bwmode) {
1402 	case AR5K_BWMODE_5MHZ:
1403 		rxs->flag |= RX_FLAG_5MHZ;
1404 		break;
1405 	case AR5K_BWMODE_10MHZ:
1406 		rxs->flag |= RX_FLAG_10MHZ;
1407 		break;
1408 	default:
1409 		break;
1410 	}
1411 
1412 	if (rs->rs_rate ==
1413 	    ah->sbands[ah->curchan->band].bitrates[rxs->rate_idx].hw_value_short)
1414 		rxs->flag |= RX_FLAG_SHORTPRE;
1415 
1416 	trace_ath5k_rx(ah, skb);
1417 
1418 	if (ath_is_mybeacon(common, (struct ieee80211_hdr *)skb->data)) {
1419 		ewma_add(&ah->ah_beacon_rssi_avg, rs->rs_rssi);
1420 
1421 		/* check beacons in IBSS mode */
1422 		if (ah->opmode == NL80211_IFTYPE_ADHOC)
1423 			ath5k_check_ibss_tsf(ah, skb, rxs);
1424 	}
1425 
1426 	ieee80211_rx(ah->hw, skb);
1427 }
1428 
1429 /** ath5k_frame_receive_ok() - Do we want to receive this frame or not?
1430  *
1431  * Check if we want to further process this frame or not. Also update
1432  * statistics. Return true if we want this frame, false if not.
1433  */
1434 static bool
1435 ath5k_receive_frame_ok(struct ath5k_hw *ah, struct ath5k_rx_status *rs)
1436 {
1437 	ah->stats.rx_all_count++;
1438 	ah->stats.rx_bytes_count += rs->rs_datalen;
1439 
1440 	if (unlikely(rs->rs_status)) {
1441 		unsigned int filters;
1442 
1443 		if (rs->rs_status & AR5K_RXERR_CRC)
1444 			ah->stats.rxerr_crc++;
1445 		if (rs->rs_status & AR5K_RXERR_FIFO)
1446 			ah->stats.rxerr_fifo++;
1447 		if (rs->rs_status & AR5K_RXERR_PHY) {
1448 			ah->stats.rxerr_phy++;
1449 			if (rs->rs_phyerr > 0 && rs->rs_phyerr < 32)
1450 				ah->stats.rxerr_phy_code[rs->rs_phyerr]++;
1451 
1452 			/*
1453 			 * Treat packets that underwent a CCK or OFDM reset as having a bad CRC.
1454 			 * These restarts happen when the radio resynchronizes to a stronger frame
1455 			 * while receiving a weaker frame. Here we receive the prefix of the weak
1456 			 * frame. Since these are incomplete packets, mark their CRC as invalid.
1457 			 */
1458 			if (rs->rs_phyerr == AR5K_RX_PHY_ERROR_OFDM_RESTART ||
1459 			    rs->rs_phyerr == AR5K_RX_PHY_ERROR_CCK_RESTART) {
1460 				rs->rs_status |= AR5K_RXERR_CRC;
1461 				rs->rs_status &= ~AR5K_RXERR_PHY;
1462 			} else {
1463 				return false;
1464 			}
1465 		}
1466 		if (rs->rs_status & AR5K_RXERR_DECRYPT) {
1467 			/*
1468 			 * Decrypt error.  If the error occurred
1469 			 * because there was no hardware key, then
1470 			 * let the frame through so the upper layers
1471 			 * can process it.  This is necessary for 5210
1472 			 * parts which have no way to setup a ``clear''
1473 			 * key cache entry.
1474 			 *
1475 			 * XXX do key cache faulting
1476 			 */
1477 			ah->stats.rxerr_decrypt++;
1478 			if (rs->rs_keyix == AR5K_RXKEYIX_INVALID &&
1479 			    !(rs->rs_status & AR5K_RXERR_CRC))
1480 				return true;
1481 		}
1482 		if (rs->rs_status & AR5K_RXERR_MIC) {
1483 			ah->stats.rxerr_mic++;
1484 			return true;
1485 		}
1486 
1487 		/*
1488 		 * Reject any frames with non-crypto errors, and take into account the
1489 		 * current FIF_* filters.
1490 		 */
1491 		filters = AR5K_RXERR_DECRYPT;
1492 		if (ah->fif_filter_flags & FIF_FCSFAIL)
1493 			filters |= AR5K_RXERR_CRC;
1494 
1495 		if (rs->rs_status & ~filters)
1496 			return false;
1497 	}
1498 
1499 	if (unlikely(rs->rs_more)) {
1500 		ah->stats.rxerr_jumbo++;
1501 		return false;
1502 	}
1503 	return true;
1504 }
1505 
1506 static void
1507 ath5k_set_current_imask(struct ath5k_hw *ah)
1508 {
1509 	enum ath5k_int imask;
1510 	unsigned long flags;
1511 
1512 	spin_lock_irqsave(&ah->irqlock, flags);
1513 	imask = ah->imask;
1514 	if (ah->rx_pending)
1515 		imask &= ~AR5K_INT_RX_ALL;
1516 	if (ah->tx_pending)
1517 		imask &= ~AR5K_INT_TX_ALL;
1518 	ath5k_hw_set_imr(ah, imask);
1519 	spin_unlock_irqrestore(&ah->irqlock, flags);
1520 }
1521 
1522 static void
1523 ath5k_tasklet_rx(unsigned long data)
1524 {
1525 	struct ath5k_rx_status rs = {};
1526 	struct sk_buff *skb, *next_skb;
1527 	dma_addr_t next_skb_addr;
1528 	struct ath5k_hw *ah = (void *)data;
1529 	struct ath_common *common = ath5k_hw_common(ah);
1530 	struct ath5k_buf *bf;
1531 	struct ath5k_desc *ds;
1532 	int ret;
1533 
1534 	spin_lock(&ah->rxbuflock);
1535 	if (list_empty(&ah->rxbuf)) {
1536 		ATH5K_WARN(ah, "empty rx buf pool\n");
1537 		goto unlock;
1538 	}
1539 	do {
1540 		bf = list_first_entry(&ah->rxbuf, struct ath5k_buf, list);
1541 		BUG_ON(bf->skb == NULL);
1542 		skb = bf->skb;
1543 		ds = bf->desc;
1544 
1545 		/* bail if HW is still using self-linked descriptor */
1546 		if (ath5k_hw_get_rxdp(ah) == bf->daddr)
1547 			break;
1548 
1549 		ret = ah->ah_proc_rx_desc(ah, ds, &rs);
1550 		if (unlikely(ret == -EINPROGRESS))
1551 			break;
1552 		else if (unlikely(ret)) {
1553 			ATH5K_ERR(ah, "error in processing rx descriptor\n");
1554 			ah->stats.rxerr_proc++;
1555 			break;
1556 		}
1557 
1558 		if (ath5k_receive_frame_ok(ah, &rs)) {
1559 			next_skb = ath5k_rx_skb_alloc(ah, &next_skb_addr);
1560 
1561 			/*
1562 			 * If we can't replace bf->skb with a new skb under
1563 			 * memory pressure, just skip this packet
1564 			 */
1565 			if (!next_skb)
1566 				goto next;
1567 
1568 			dma_unmap_single(ah->dev, bf->skbaddr,
1569 					 common->rx_bufsize,
1570 					 DMA_FROM_DEVICE);
1571 
1572 			skb_put(skb, rs.rs_datalen);
1573 
1574 			ath5k_receive_frame(ah, skb, &rs);
1575 
1576 			bf->skb = next_skb;
1577 			bf->skbaddr = next_skb_addr;
1578 		}
1579 next:
1580 		list_move_tail(&bf->list, &ah->rxbuf);
1581 	} while (ath5k_rxbuf_setup(ah, bf) == 0);
1582 unlock:
1583 	spin_unlock(&ah->rxbuflock);
1584 	ah->rx_pending = false;
1585 	ath5k_set_current_imask(ah);
1586 }
1587 
1588 
1589 /*************\
1590 * TX Handling *
1591 \*************/
1592 
1593 void
1594 ath5k_tx_queue(struct ieee80211_hw *hw, struct sk_buff *skb,
1595 	       struct ath5k_txq *txq, struct ieee80211_tx_control *control)
1596 {
1597 	struct ath5k_hw *ah = hw->priv;
1598 	struct ath5k_buf *bf;
1599 	unsigned long flags;
1600 	int padsize;
1601 
1602 	trace_ath5k_tx(ah, skb, txq);
1603 
1604 	/*
1605 	 * The hardware expects the header padded to 4 byte boundaries.
1606 	 * If this is not the case, we add the padding after the header.
1607 	 */
1608 	padsize = ath5k_add_padding(skb);
1609 	if (padsize < 0) {
1610 		ATH5K_ERR(ah, "tx hdrlen not %%4: not enough"
1611 			  " headroom to pad");
1612 		goto drop_packet;
1613 	}
1614 
1615 	if (txq->txq_len >= txq->txq_max &&
1616 	    txq->qnum <= AR5K_TX_QUEUE_ID_DATA_MAX)
1617 		ieee80211_stop_queue(hw, txq->qnum);
1618 
1619 	spin_lock_irqsave(&ah->txbuflock, flags);
1620 	if (list_empty(&ah->txbuf)) {
1621 		ATH5K_ERR(ah, "no further txbuf available, dropping packet\n");
1622 		spin_unlock_irqrestore(&ah->txbuflock, flags);
1623 		ieee80211_stop_queues(hw);
1624 		goto drop_packet;
1625 	}
1626 	bf = list_first_entry(&ah->txbuf, struct ath5k_buf, list);
1627 	list_del(&bf->list);
1628 	ah->txbuf_len--;
1629 	if (list_empty(&ah->txbuf))
1630 		ieee80211_stop_queues(hw);
1631 	spin_unlock_irqrestore(&ah->txbuflock, flags);
1632 
1633 	bf->skb = skb;
1634 
1635 	if (ath5k_txbuf_setup(ah, bf, txq, padsize, control)) {
1636 		bf->skb = NULL;
1637 		spin_lock_irqsave(&ah->txbuflock, flags);
1638 		list_add_tail(&bf->list, &ah->txbuf);
1639 		ah->txbuf_len++;
1640 		spin_unlock_irqrestore(&ah->txbuflock, flags);
1641 		goto drop_packet;
1642 	}
1643 	return;
1644 
1645 drop_packet:
1646 	ieee80211_free_txskb(hw, skb);
1647 }
1648 
1649 static void
1650 ath5k_tx_frame_completed(struct ath5k_hw *ah, struct sk_buff *skb,
1651 			 struct ath5k_txq *txq, struct ath5k_tx_status *ts,
1652 			 struct ath5k_buf *bf)
1653 {
1654 	struct ieee80211_tx_info *info;
1655 	u8 tries[3];
1656 	int i;
1657 	int size = 0;
1658 
1659 	ah->stats.tx_all_count++;
1660 	ah->stats.tx_bytes_count += skb->len;
1661 	info = IEEE80211_SKB_CB(skb);
1662 
1663 	size = min_t(int, sizeof(info->status.rates), sizeof(bf->rates));
1664 	memcpy(info->status.rates, bf->rates, size);
1665 
1666 	tries[0] = info->status.rates[0].count;
1667 	tries[1] = info->status.rates[1].count;
1668 	tries[2] = info->status.rates[2].count;
1669 
1670 	ieee80211_tx_info_clear_status(info);
1671 
1672 	for (i = 0; i < ts->ts_final_idx; i++) {
1673 		struct ieee80211_tx_rate *r =
1674 			&info->status.rates[i];
1675 
1676 		r->count = tries[i];
1677 	}
1678 
1679 	info->status.rates[ts->ts_final_idx].count = ts->ts_final_retry;
1680 	info->status.rates[ts->ts_final_idx + 1].idx = -1;
1681 
1682 	if (unlikely(ts->ts_status)) {
1683 		ah->stats.ack_fail++;
1684 		if (ts->ts_status & AR5K_TXERR_FILT) {
1685 			info->flags |= IEEE80211_TX_STAT_TX_FILTERED;
1686 			ah->stats.txerr_filt++;
1687 		}
1688 		if (ts->ts_status & AR5K_TXERR_XRETRY)
1689 			ah->stats.txerr_retry++;
1690 		if (ts->ts_status & AR5K_TXERR_FIFO)
1691 			ah->stats.txerr_fifo++;
1692 	} else {
1693 		info->flags |= IEEE80211_TX_STAT_ACK;
1694 		info->status.ack_signal = ts->ts_rssi;
1695 
1696 		/* count the successful attempt as well */
1697 		info->status.rates[ts->ts_final_idx].count++;
1698 	}
1699 
1700 	/*
1701 	* Remove MAC header padding before giving the frame
1702 	* back to mac80211.
1703 	*/
1704 	ath5k_remove_padding(skb);
1705 
1706 	if (ts->ts_antenna > 0 && ts->ts_antenna < 5)
1707 		ah->stats.antenna_tx[ts->ts_antenna]++;
1708 	else
1709 		ah->stats.antenna_tx[0]++; /* invalid */
1710 
1711 	trace_ath5k_tx_complete(ah, skb, txq, ts);
1712 	ieee80211_tx_status(ah->hw, skb);
1713 }
1714 
1715 static void
1716 ath5k_tx_processq(struct ath5k_hw *ah, struct ath5k_txq *txq)
1717 {
1718 	struct ath5k_tx_status ts = {};
1719 	struct ath5k_buf *bf, *bf0;
1720 	struct ath5k_desc *ds;
1721 	struct sk_buff *skb;
1722 	int ret;
1723 
1724 	spin_lock(&txq->lock);
1725 	list_for_each_entry_safe(bf, bf0, &txq->q, list) {
1726 
1727 		txq->txq_poll_mark = false;
1728 
1729 		/* skb might already have been processed last time. */
1730 		if (bf->skb != NULL) {
1731 			ds = bf->desc;
1732 
1733 			ret = ah->ah_proc_tx_desc(ah, ds, &ts);
1734 			if (unlikely(ret == -EINPROGRESS))
1735 				break;
1736 			else if (unlikely(ret)) {
1737 				ATH5K_ERR(ah,
1738 					"error %d while processing "
1739 					"queue %u\n", ret, txq->qnum);
1740 				break;
1741 			}
1742 
1743 			skb = bf->skb;
1744 			bf->skb = NULL;
1745 
1746 			dma_unmap_single(ah->dev, bf->skbaddr, skb->len,
1747 					DMA_TO_DEVICE);
1748 			ath5k_tx_frame_completed(ah, skb, txq, &ts, bf);
1749 		}
1750 
1751 		/*
1752 		 * It's possible that the hardware can say the buffer is
1753 		 * completed when it hasn't yet loaded the ds_link from
1754 		 * host memory and moved on.
1755 		 * Always keep the last descriptor to avoid HW races...
1756 		 */
1757 		if (ath5k_hw_get_txdp(ah, txq->qnum) != bf->daddr) {
1758 			spin_lock(&ah->txbuflock);
1759 			list_move_tail(&bf->list, &ah->txbuf);
1760 			ah->txbuf_len++;
1761 			txq->txq_len--;
1762 			spin_unlock(&ah->txbuflock);
1763 		}
1764 	}
1765 	spin_unlock(&txq->lock);
1766 	if (txq->txq_len < ATH5K_TXQ_LEN_LOW && txq->qnum < 4)
1767 		ieee80211_wake_queue(ah->hw, txq->qnum);
1768 }
1769 
1770 static void
1771 ath5k_tasklet_tx(unsigned long data)
1772 {
1773 	int i;
1774 	struct ath5k_hw *ah = (void *)data;
1775 
1776 	for (i = 0; i < AR5K_NUM_TX_QUEUES; i++)
1777 		if (ah->txqs[i].setup && (ah->ah_txq_isr_txok_all & BIT(i)))
1778 			ath5k_tx_processq(ah, &ah->txqs[i]);
1779 
1780 	ah->tx_pending = false;
1781 	ath5k_set_current_imask(ah);
1782 }
1783 
1784 
1785 /*****************\
1786 * Beacon handling *
1787 \*****************/
1788 
1789 /*
1790  * Setup the beacon frame for transmit.
1791  */
1792 static int
1793 ath5k_beacon_setup(struct ath5k_hw *ah, struct ath5k_buf *bf)
1794 {
1795 	struct sk_buff *skb = bf->skb;
1796 	struct	ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
1797 	struct ath5k_desc *ds;
1798 	int ret = 0;
1799 	u8 antenna;
1800 	u32 flags;
1801 	const int padsize = 0;
1802 
1803 	bf->skbaddr = dma_map_single(ah->dev, skb->data, skb->len,
1804 			DMA_TO_DEVICE);
1805 	ATH5K_DBG(ah, ATH5K_DEBUG_BEACON, "skb %p [data %p len %u] "
1806 			"skbaddr %llx\n", skb, skb->data, skb->len,
1807 			(unsigned long long)bf->skbaddr);
1808 
1809 	if (dma_mapping_error(ah->dev, bf->skbaddr)) {
1810 		ATH5K_ERR(ah, "beacon DMA mapping failed\n");
1811 		dev_kfree_skb_any(skb);
1812 		bf->skb = NULL;
1813 		return -EIO;
1814 	}
1815 
1816 	ds = bf->desc;
1817 	antenna = ah->ah_tx_ant;
1818 
1819 	flags = AR5K_TXDESC_NOACK;
1820 	if (ah->opmode == NL80211_IFTYPE_ADHOC && ath5k_hw_hasveol(ah)) {
1821 		ds->ds_link = bf->daddr;	/* self-linked */
1822 		flags |= AR5K_TXDESC_VEOL;
1823 	} else
1824 		ds->ds_link = 0;
1825 
1826 	/*
1827 	 * If we use multiple antennas on AP and use
1828 	 * the Sectored AP scenario, switch antenna every
1829 	 * 4 beacons to make sure everybody hears our AP.
1830 	 * When a client tries to associate, hw will keep
1831 	 * track of the tx antenna to be used for this client
1832 	 * automatically, based on ACKed packets.
1833 	 *
1834 	 * Note: AP still listens and transmits RTS on the
1835 	 * default antenna which is supposed to be an omni.
1836 	 *
1837 	 * Note2: On sectored scenarios it's possible to have
1838 	 * multiple antennas (1 omni -- the default -- and 14
1839 	 * sectors), so if we choose to actually support this
1840 	 * mode, we need to allow the user to set how many antennas
1841 	 * we have and tweak the code below to send beacons
1842 	 * on all of them.
1843 	 */
1844 	if (ah->ah_ant_mode == AR5K_ANTMODE_SECTOR_AP)
1845 		antenna = ah->bsent & 4 ? 2 : 1;
1846 
1847 
1848 	/* FIXME: If we are in g mode and rate is a CCK rate
1849 	 * subtract ah->ah_txpower.txp_cck_ofdm_pwr_delta
1850 	 * from tx power (value is in dB units already) */
1851 	ds->ds_data = bf->skbaddr;
1852 	ret = ah->ah_setup_tx_desc(ah, ds, skb->len,
1853 			ieee80211_get_hdrlen_from_skb(skb), padsize,
1854 			AR5K_PKT_TYPE_BEACON,
1855 			(ah->ah_txpower.txp_requested * 2),
1856 			ieee80211_get_tx_rate(ah->hw, info)->hw_value,
1857 			1, AR5K_TXKEYIX_INVALID,
1858 			antenna, flags, 0, 0);
1859 	if (ret)
1860 		goto err_unmap;
1861 
1862 	return 0;
1863 err_unmap:
1864 	dma_unmap_single(ah->dev, bf->skbaddr, skb->len, DMA_TO_DEVICE);
1865 	return ret;
1866 }
1867 
1868 /*
1869  * Updates the beacon that is sent by ath5k_beacon_send.  For adhoc,
1870  * this is called only once at config_bss time, for AP we do it every
1871  * SWBA interrupt so that the TIM will reflect buffered frames.
1872  *
1873  * Called with the beacon lock.
1874  */
1875 int
1876 ath5k_beacon_update(struct ieee80211_hw *hw, struct ieee80211_vif *vif)
1877 {
1878 	int ret;
1879 	struct ath5k_hw *ah = hw->priv;
1880 	struct ath5k_vif *avf;
1881 	struct sk_buff *skb;
1882 
1883 	if (WARN_ON(!vif)) {
1884 		ret = -EINVAL;
1885 		goto out;
1886 	}
1887 
1888 	skb = ieee80211_beacon_get(hw, vif);
1889 
1890 	if (!skb) {
1891 		ret = -ENOMEM;
1892 		goto out;
1893 	}
1894 
1895 	avf = (void *)vif->drv_priv;
1896 	ath5k_txbuf_free_skb(ah, avf->bbuf);
1897 	avf->bbuf->skb = skb;
1898 	ret = ath5k_beacon_setup(ah, avf->bbuf);
1899 out:
1900 	return ret;
1901 }
1902 
1903 /*
1904  * Transmit a beacon frame at SWBA.  Dynamic updates to the
1905  * frame contents are done as needed and the slot time is
1906  * also adjusted based on current state.
1907  *
1908  * This is called from software irq context (beacontq tasklets)
1909  * or user context from ath5k_beacon_config.
1910  */
1911 static void
1912 ath5k_beacon_send(struct ath5k_hw *ah)
1913 {
1914 	struct ieee80211_vif *vif;
1915 	struct ath5k_vif *avf;
1916 	struct ath5k_buf *bf;
1917 	struct sk_buff *skb;
1918 	int err;
1919 
1920 	ATH5K_DBG_UNLIMIT(ah, ATH5K_DEBUG_BEACON, "in beacon_send\n");
1921 
1922 	/*
1923 	 * Check if the previous beacon has gone out.  If
1924 	 * not, don't don't try to post another: skip this
1925 	 * period and wait for the next.  Missed beacons
1926 	 * indicate a problem and should not occur.  If we
1927 	 * miss too many consecutive beacons reset the device.
1928 	 */
1929 	if (unlikely(ath5k_hw_num_tx_pending(ah, ah->bhalq) != 0)) {
1930 		ah->bmisscount++;
1931 		ATH5K_DBG(ah, ATH5K_DEBUG_BEACON,
1932 			"missed %u consecutive beacons\n", ah->bmisscount);
1933 		if (ah->bmisscount > 10) {	/* NB: 10 is a guess */
1934 			ATH5K_DBG(ah, ATH5K_DEBUG_BEACON,
1935 				"stuck beacon time (%u missed)\n",
1936 				ah->bmisscount);
1937 			ATH5K_DBG(ah, ATH5K_DEBUG_RESET,
1938 				  "stuck beacon, resetting\n");
1939 			ieee80211_queue_work(ah->hw, &ah->reset_work);
1940 		}
1941 		return;
1942 	}
1943 	if (unlikely(ah->bmisscount != 0)) {
1944 		ATH5K_DBG(ah, ATH5K_DEBUG_BEACON,
1945 			"resume beacon xmit after %u misses\n",
1946 			ah->bmisscount);
1947 		ah->bmisscount = 0;
1948 	}
1949 
1950 	if ((ah->opmode == NL80211_IFTYPE_AP && ah->num_ap_vifs +
1951 			ah->num_mesh_vifs > 1) ||
1952 			ah->opmode == NL80211_IFTYPE_MESH_POINT) {
1953 		u64 tsf = ath5k_hw_get_tsf64(ah);
1954 		u32 tsftu = TSF_TO_TU(tsf);
1955 		int slot = ((tsftu % ah->bintval) * ATH_BCBUF) / ah->bintval;
1956 		vif = ah->bslot[(slot + 1) % ATH_BCBUF];
1957 		ATH5K_DBG(ah, ATH5K_DEBUG_BEACON,
1958 			"tsf %llx tsftu %x intval %u slot %u vif %p\n",
1959 			(unsigned long long)tsf, tsftu, ah->bintval, slot, vif);
1960 	} else /* only one interface */
1961 		vif = ah->bslot[0];
1962 
1963 	if (!vif)
1964 		return;
1965 
1966 	avf = (void *)vif->drv_priv;
1967 	bf = avf->bbuf;
1968 
1969 	/*
1970 	 * Stop any current dma and put the new frame on the queue.
1971 	 * This should never fail since we check above that no frames
1972 	 * are still pending on the queue.
1973 	 */
1974 	if (unlikely(ath5k_hw_stop_beacon_queue(ah, ah->bhalq))) {
1975 		ATH5K_WARN(ah, "beacon queue %u didn't start/stop ?\n", ah->bhalq);
1976 		/* NB: hw still stops DMA, so proceed */
1977 	}
1978 
1979 	/* refresh the beacon for AP or MESH mode */
1980 	if (ah->opmode == NL80211_IFTYPE_AP ||
1981 	    ah->opmode == NL80211_IFTYPE_MESH_POINT) {
1982 		err = ath5k_beacon_update(ah->hw, vif);
1983 		if (err)
1984 			return;
1985 	}
1986 
1987 	if (unlikely(bf->skb == NULL || ah->opmode == NL80211_IFTYPE_STATION ||
1988 		     ah->opmode == NL80211_IFTYPE_MONITOR)) {
1989 		ATH5K_WARN(ah, "bf=%p bf_skb=%p\n", bf, bf->skb);
1990 		return;
1991 	}
1992 
1993 	trace_ath5k_tx(ah, bf->skb, &ah->txqs[ah->bhalq]);
1994 
1995 	ath5k_hw_set_txdp(ah, ah->bhalq, bf->daddr);
1996 	ath5k_hw_start_tx_dma(ah, ah->bhalq);
1997 	ATH5K_DBG(ah, ATH5K_DEBUG_BEACON, "TXDP[%u] = %llx (%p)\n",
1998 		ah->bhalq, (unsigned long long)bf->daddr, bf->desc);
1999 
2000 	skb = ieee80211_get_buffered_bc(ah->hw, vif);
2001 	while (skb) {
2002 		ath5k_tx_queue(ah->hw, skb, ah->cabq, NULL);
2003 
2004 		if (ah->cabq->txq_len >= ah->cabq->txq_max)
2005 			break;
2006 
2007 		skb = ieee80211_get_buffered_bc(ah->hw, vif);
2008 	}
2009 
2010 	ah->bsent++;
2011 }
2012 
2013 /**
2014  * ath5k_beacon_update_timers - update beacon timers
2015  *
2016  * @ah: struct ath5k_hw pointer we are operating on
2017  * @bc_tsf: the timestamp of the beacon. 0 to reset the TSF. -1 to perform a
2018  *          beacon timer update based on the current HW TSF.
2019  *
2020  * Calculate the next target beacon transmit time (TBTT) based on the timestamp
2021  * of a received beacon or the current local hardware TSF and write it to the
2022  * beacon timer registers.
2023  *
2024  * This is called in a variety of situations, e.g. when a beacon is received,
2025  * when a TSF update has been detected, but also when an new IBSS is created or
2026  * when we otherwise know we have to update the timers, but we keep it in this
2027  * function to have it all together in one place.
2028  */
2029 void
2030 ath5k_beacon_update_timers(struct ath5k_hw *ah, u64 bc_tsf)
2031 {
2032 	u32 nexttbtt, intval, hw_tu, bc_tu;
2033 	u64 hw_tsf;
2034 
2035 	intval = ah->bintval & AR5K_BEACON_PERIOD;
2036 	if (ah->opmode == NL80211_IFTYPE_AP && ah->num_ap_vifs
2037 		+ ah->num_mesh_vifs > 1) {
2038 		intval /= ATH_BCBUF;	/* staggered multi-bss beacons */
2039 		if (intval < 15)
2040 			ATH5K_WARN(ah, "intval %u is too low, min 15\n",
2041 				   intval);
2042 	}
2043 	if (WARN_ON(!intval))
2044 		return;
2045 
2046 	/* beacon TSF converted to TU */
2047 	bc_tu = TSF_TO_TU(bc_tsf);
2048 
2049 	/* current TSF converted to TU */
2050 	hw_tsf = ath5k_hw_get_tsf64(ah);
2051 	hw_tu = TSF_TO_TU(hw_tsf);
2052 
2053 #define FUDGE (AR5K_TUNE_SW_BEACON_RESP + 3)
2054 	/* We use FUDGE to make sure the next TBTT is ahead of the current TU.
2055 	 * Since we later subtract AR5K_TUNE_SW_BEACON_RESP (10) in the timer
2056 	 * configuration we need to make sure it is bigger than that. */
2057 
2058 	if (bc_tsf == -1) {
2059 		/*
2060 		 * no beacons received, called internally.
2061 		 * just need to refresh timers based on HW TSF.
2062 		 */
2063 		nexttbtt = roundup(hw_tu + FUDGE, intval);
2064 	} else if (bc_tsf == 0) {
2065 		/*
2066 		 * no beacon received, probably called by ath5k_reset_tsf().
2067 		 * reset TSF to start with 0.
2068 		 */
2069 		nexttbtt = intval;
2070 		intval |= AR5K_BEACON_RESET_TSF;
2071 	} else if (bc_tsf > hw_tsf) {
2072 		/*
2073 		 * beacon received, SW merge happened but HW TSF not yet updated.
2074 		 * not possible to reconfigure timers yet, but next time we
2075 		 * receive a beacon with the same BSSID, the hardware will
2076 		 * automatically update the TSF and then we need to reconfigure
2077 		 * the timers.
2078 		 */
2079 		ATH5K_DBG_UNLIMIT(ah, ATH5K_DEBUG_BEACON,
2080 			"need to wait for HW TSF sync\n");
2081 		return;
2082 	} else {
2083 		/*
2084 		 * most important case for beacon synchronization between STA.
2085 		 *
2086 		 * beacon received and HW TSF has been already updated by HW.
2087 		 * update next TBTT based on the TSF of the beacon, but make
2088 		 * sure it is ahead of our local TSF timer.
2089 		 */
2090 		nexttbtt = bc_tu + roundup(hw_tu + FUDGE - bc_tu, intval);
2091 	}
2092 #undef FUDGE
2093 
2094 	ah->nexttbtt = nexttbtt;
2095 
2096 	intval |= AR5K_BEACON_ENA;
2097 	ath5k_hw_init_beacon_timers(ah, nexttbtt, intval);
2098 
2099 	/*
2100 	 * debugging output last in order to preserve the time critical aspect
2101 	 * of this function
2102 	 */
2103 	if (bc_tsf == -1)
2104 		ATH5K_DBG_UNLIMIT(ah, ATH5K_DEBUG_BEACON,
2105 			"reconfigured timers based on HW TSF\n");
2106 	else if (bc_tsf == 0)
2107 		ATH5K_DBG_UNLIMIT(ah, ATH5K_DEBUG_BEACON,
2108 			"reset HW TSF and timers\n");
2109 	else
2110 		ATH5K_DBG_UNLIMIT(ah, ATH5K_DEBUG_BEACON,
2111 			"updated timers based on beacon TSF\n");
2112 
2113 	ATH5K_DBG_UNLIMIT(ah, ATH5K_DEBUG_BEACON,
2114 			  "bc_tsf %llx hw_tsf %llx bc_tu %u hw_tu %u nexttbtt %u\n",
2115 			  (unsigned long long) bc_tsf,
2116 			  (unsigned long long) hw_tsf, bc_tu, hw_tu, nexttbtt);
2117 	ATH5K_DBG_UNLIMIT(ah, ATH5K_DEBUG_BEACON, "intval %u %s %s\n",
2118 		intval & AR5K_BEACON_PERIOD,
2119 		intval & AR5K_BEACON_ENA ? "AR5K_BEACON_ENA" : "",
2120 		intval & AR5K_BEACON_RESET_TSF ? "AR5K_BEACON_RESET_TSF" : "");
2121 }
2122 
2123 /**
2124  * ath5k_beacon_config - Configure the beacon queues and interrupts
2125  *
2126  * @ah: struct ath5k_hw pointer we are operating on
2127  *
2128  * In IBSS mode we use a self-linked tx descriptor if possible. We enable SWBA
2129  * interrupts to detect TSF updates only.
2130  */
2131 void
2132 ath5k_beacon_config(struct ath5k_hw *ah)
2133 {
2134 	spin_lock_bh(&ah->block);
2135 	ah->bmisscount = 0;
2136 	ah->imask &= ~(AR5K_INT_BMISS | AR5K_INT_SWBA);
2137 
2138 	if (ah->enable_beacon) {
2139 		/*
2140 		 * In IBSS mode we use a self-linked tx descriptor and let the
2141 		 * hardware send the beacons automatically. We have to load it
2142 		 * only once here.
2143 		 * We use the SWBA interrupt only to keep track of the beacon
2144 		 * timers in order to detect automatic TSF updates.
2145 		 */
2146 		ath5k_beaconq_config(ah);
2147 
2148 		ah->imask |= AR5K_INT_SWBA;
2149 
2150 		if (ah->opmode == NL80211_IFTYPE_ADHOC) {
2151 			if (ath5k_hw_hasveol(ah))
2152 				ath5k_beacon_send(ah);
2153 		} else
2154 			ath5k_beacon_update_timers(ah, -1);
2155 	} else {
2156 		ath5k_hw_stop_beacon_queue(ah, ah->bhalq);
2157 	}
2158 
2159 	ath5k_hw_set_imr(ah, ah->imask);
2160 	mmiowb();
2161 	spin_unlock_bh(&ah->block);
2162 }
2163 
2164 static void ath5k_tasklet_beacon(unsigned long data)
2165 {
2166 	struct ath5k_hw *ah = (struct ath5k_hw *) data;
2167 
2168 	/*
2169 	 * Software beacon alert--time to send a beacon.
2170 	 *
2171 	 * In IBSS mode we use this interrupt just to
2172 	 * keep track of the next TBTT (target beacon
2173 	 * transmission time) in order to detect whether
2174 	 * automatic TSF updates happened.
2175 	 */
2176 	if (ah->opmode == NL80211_IFTYPE_ADHOC) {
2177 		/* XXX: only if VEOL supported */
2178 		u64 tsf = ath5k_hw_get_tsf64(ah);
2179 		ah->nexttbtt += ah->bintval;
2180 		ATH5K_DBG(ah, ATH5K_DEBUG_BEACON,
2181 				"SWBA nexttbtt: %x hw_tu: %x "
2182 				"TSF: %llx\n",
2183 				ah->nexttbtt,
2184 				TSF_TO_TU(tsf),
2185 				(unsigned long long) tsf);
2186 	} else {
2187 		spin_lock(&ah->block);
2188 		ath5k_beacon_send(ah);
2189 		spin_unlock(&ah->block);
2190 	}
2191 }
2192 
2193 
2194 /********************\
2195 * Interrupt handling *
2196 \********************/
2197 
2198 static void
2199 ath5k_intr_calibration_poll(struct ath5k_hw *ah)
2200 {
2201 	if (time_is_before_eq_jiffies(ah->ah_cal_next_ani) &&
2202 	   !(ah->ah_cal_mask & AR5K_CALIBRATION_FULL) &&
2203 	   !(ah->ah_cal_mask & AR5K_CALIBRATION_SHORT)) {
2204 
2205 		/* Run ANI only when calibration is not active */
2206 
2207 		ah->ah_cal_next_ani = jiffies +
2208 			msecs_to_jiffies(ATH5K_TUNE_CALIBRATION_INTERVAL_ANI);
2209 		tasklet_schedule(&ah->ani_tasklet);
2210 
2211 	} else if (time_is_before_eq_jiffies(ah->ah_cal_next_short) &&
2212 		!(ah->ah_cal_mask & AR5K_CALIBRATION_FULL) &&
2213 		!(ah->ah_cal_mask & AR5K_CALIBRATION_SHORT)) {
2214 
2215 		/* Run calibration only when another calibration
2216 		 * is not running.
2217 		 *
2218 		 * Note: This is for both full/short calibration,
2219 		 * if it's time for a full one, ath5k_calibrate_work will deal
2220 		 * with it. */
2221 
2222 		ah->ah_cal_next_short = jiffies +
2223 			msecs_to_jiffies(ATH5K_TUNE_CALIBRATION_INTERVAL_SHORT);
2224 		ieee80211_queue_work(ah->hw, &ah->calib_work);
2225 	}
2226 	/* we could use SWI to generate enough interrupts to meet our
2227 	 * calibration interval requirements, if necessary:
2228 	 * AR5K_REG_ENABLE_BITS(ah, AR5K_CR, AR5K_CR_SWI); */
2229 }
2230 
2231 static void
2232 ath5k_schedule_rx(struct ath5k_hw *ah)
2233 {
2234 	ah->rx_pending = true;
2235 	tasklet_schedule(&ah->rxtq);
2236 }
2237 
2238 static void
2239 ath5k_schedule_tx(struct ath5k_hw *ah)
2240 {
2241 	ah->tx_pending = true;
2242 	tasklet_schedule(&ah->txtq);
2243 }
2244 
2245 static irqreturn_t
2246 ath5k_intr(int irq, void *dev_id)
2247 {
2248 	struct ath5k_hw *ah = dev_id;
2249 	enum ath5k_int status;
2250 	unsigned int counter = 1000;
2251 
2252 
2253 	/*
2254 	 * If hw is not ready (or detached) and we get an
2255 	 * interrupt, or if we have no interrupts pending
2256 	 * (that means it's not for us) skip it.
2257 	 *
2258 	 * NOTE: Group 0/1 PCI interface registers are not
2259 	 * supported on WiSOCs, so we can't check for pending
2260 	 * interrupts (ISR belongs to another register group
2261 	 * so we are ok).
2262 	 */
2263 	if (unlikely(test_bit(ATH_STAT_INVALID, ah->status) ||
2264 			((ath5k_get_bus_type(ah) != ATH_AHB) &&
2265 			!ath5k_hw_is_intr_pending(ah))))
2266 		return IRQ_NONE;
2267 
2268 	/** Main loop **/
2269 	do {
2270 		ath5k_hw_get_isr(ah, &status);	/* NB: clears IRQ too */
2271 
2272 		ATH5K_DBG(ah, ATH5K_DEBUG_INTR, "status 0x%x/0x%x\n",
2273 				status, ah->imask);
2274 
2275 		/*
2276 		 * Fatal hw error -> Log and reset
2277 		 *
2278 		 * Fatal errors are unrecoverable so we have to
2279 		 * reset the card. These errors include bus and
2280 		 * dma errors.
2281 		 */
2282 		if (unlikely(status & AR5K_INT_FATAL)) {
2283 
2284 			ATH5K_DBG(ah, ATH5K_DEBUG_RESET,
2285 				  "fatal int, resetting\n");
2286 			ieee80211_queue_work(ah->hw, &ah->reset_work);
2287 
2288 		/*
2289 		 * RX Overrun -> Count and reset if needed
2290 		 *
2291 		 * Receive buffers are full. Either the bus is busy or
2292 		 * the CPU is not fast enough to process all received
2293 		 * frames.
2294 		 */
2295 		} else if (unlikely(status & AR5K_INT_RXORN)) {
2296 
2297 			/*
2298 			 * Older chipsets need a reset to come out of this
2299 			 * condition, but we treat it as RX for newer chips.
2300 			 * We don't know exactly which versions need a reset
2301 			 * this guess is copied from the HAL.
2302 			 */
2303 			ah->stats.rxorn_intr++;
2304 
2305 			if (ah->ah_mac_srev < AR5K_SREV_AR5212) {
2306 				ATH5K_DBG(ah, ATH5K_DEBUG_RESET,
2307 					  "rx overrun, resetting\n");
2308 				ieee80211_queue_work(ah->hw, &ah->reset_work);
2309 			} else
2310 				ath5k_schedule_rx(ah);
2311 
2312 		} else {
2313 
2314 			/* Software Beacon Alert -> Schedule beacon tasklet */
2315 			if (status & AR5K_INT_SWBA)
2316 				tasklet_hi_schedule(&ah->beacontq);
2317 
2318 			/*
2319 			 * No more RX descriptors -> Just count
2320 			 *
2321 			 * NB: the hardware should re-read the link when
2322 			 *     RXE bit is written, but it doesn't work at
2323 			 *     least on older hardware revs.
2324 			 */
2325 			if (status & AR5K_INT_RXEOL)
2326 				ah->stats.rxeol_intr++;
2327 
2328 
2329 			/* TX Underrun -> Bump tx trigger level */
2330 			if (status & AR5K_INT_TXURN)
2331 				ath5k_hw_update_tx_triglevel(ah, true);
2332 
2333 			/* RX -> Schedule rx tasklet */
2334 			if (status & (AR5K_INT_RXOK | AR5K_INT_RXERR))
2335 				ath5k_schedule_rx(ah);
2336 
2337 			/* TX -> Schedule tx tasklet */
2338 			if (status & (AR5K_INT_TXOK
2339 					| AR5K_INT_TXDESC
2340 					| AR5K_INT_TXERR
2341 					| AR5K_INT_TXEOL))
2342 				ath5k_schedule_tx(ah);
2343 
2344 			/* Missed beacon -> TODO
2345 			if (status & AR5K_INT_BMISS)
2346 			*/
2347 
2348 			/* MIB event -> Update counters and notify ANI */
2349 			if (status & AR5K_INT_MIB) {
2350 				ah->stats.mib_intr++;
2351 				ath5k_hw_update_mib_counters(ah);
2352 				ath5k_ani_mib_intr(ah);
2353 			}
2354 
2355 			/* GPIO -> Notify RFKill layer */
2356 			if (status & AR5K_INT_GPIO)
2357 				tasklet_schedule(&ah->rf_kill.toggleq);
2358 
2359 		}
2360 
2361 		if (ath5k_get_bus_type(ah) == ATH_AHB)
2362 			break;
2363 
2364 	} while (ath5k_hw_is_intr_pending(ah) && --counter > 0);
2365 
2366 	/*
2367 	 * Until we handle rx/tx interrupts mask them on IMR
2368 	 *
2369 	 * NOTE: ah->(rx/tx)_pending are set when scheduling the tasklets
2370 	 * and unset after we 've handled the interrupts.
2371 	 */
2372 	if (ah->rx_pending || ah->tx_pending)
2373 		ath5k_set_current_imask(ah);
2374 
2375 	if (unlikely(!counter))
2376 		ATH5K_WARN(ah, "too many interrupts, giving up for now\n");
2377 
2378 	/* Fire up calibration poll */
2379 	ath5k_intr_calibration_poll(ah);
2380 
2381 	return IRQ_HANDLED;
2382 }
2383 
2384 /*
2385  * Periodically recalibrate the PHY to account
2386  * for temperature/environment changes.
2387  */
2388 static void
2389 ath5k_calibrate_work(struct work_struct *work)
2390 {
2391 	struct ath5k_hw *ah = container_of(work, struct ath5k_hw,
2392 		calib_work);
2393 
2394 	/* Should we run a full calibration ? */
2395 	if (time_is_before_eq_jiffies(ah->ah_cal_next_full)) {
2396 
2397 		ah->ah_cal_next_full = jiffies +
2398 			msecs_to_jiffies(ATH5K_TUNE_CALIBRATION_INTERVAL_FULL);
2399 		ah->ah_cal_mask |= AR5K_CALIBRATION_FULL;
2400 
2401 		ATH5K_DBG(ah, ATH5K_DEBUG_CALIBRATE,
2402 				"running full calibration\n");
2403 
2404 		if (ath5k_hw_gainf_calibrate(ah) == AR5K_RFGAIN_NEED_CHANGE) {
2405 			/*
2406 			 * Rfgain is out of bounds, reset the chip
2407 			 * to load new gain values.
2408 			 */
2409 			ATH5K_DBG(ah, ATH5K_DEBUG_RESET,
2410 					"got new rfgain, resetting\n");
2411 			ieee80211_queue_work(ah->hw, &ah->reset_work);
2412 		}
2413 	} else
2414 		ah->ah_cal_mask |= AR5K_CALIBRATION_SHORT;
2415 
2416 
2417 	ATH5K_DBG(ah, ATH5K_DEBUG_CALIBRATE, "channel %u/%x\n",
2418 		ieee80211_frequency_to_channel(ah->curchan->center_freq),
2419 		ah->curchan->hw_value);
2420 
2421 	if (ath5k_hw_phy_calibrate(ah, ah->curchan))
2422 		ATH5K_ERR(ah, "calibration of channel %u failed\n",
2423 			ieee80211_frequency_to_channel(
2424 				ah->curchan->center_freq));
2425 
2426 	/* Clear calibration flags */
2427 	if (ah->ah_cal_mask & AR5K_CALIBRATION_FULL)
2428 		ah->ah_cal_mask &= ~AR5K_CALIBRATION_FULL;
2429 	else if (ah->ah_cal_mask & AR5K_CALIBRATION_SHORT)
2430 		ah->ah_cal_mask &= ~AR5K_CALIBRATION_SHORT;
2431 }
2432 
2433 
2434 static void
2435 ath5k_tasklet_ani(unsigned long data)
2436 {
2437 	struct ath5k_hw *ah = (void *)data;
2438 
2439 	ah->ah_cal_mask |= AR5K_CALIBRATION_ANI;
2440 	ath5k_ani_calibration(ah);
2441 	ah->ah_cal_mask &= ~AR5K_CALIBRATION_ANI;
2442 }
2443 
2444 
2445 static void
2446 ath5k_tx_complete_poll_work(struct work_struct *work)
2447 {
2448 	struct ath5k_hw *ah = container_of(work, struct ath5k_hw,
2449 			tx_complete_work.work);
2450 	struct ath5k_txq *txq;
2451 	int i;
2452 	bool needreset = false;
2453 
2454 	if (!test_bit(ATH_STAT_STARTED, ah->status))
2455 		return;
2456 
2457 	mutex_lock(&ah->lock);
2458 
2459 	for (i = 0; i < ARRAY_SIZE(ah->txqs); i++) {
2460 		if (ah->txqs[i].setup) {
2461 			txq = &ah->txqs[i];
2462 			spin_lock_bh(&txq->lock);
2463 			if (txq->txq_len > 1) {
2464 				if (txq->txq_poll_mark) {
2465 					ATH5K_DBG(ah, ATH5K_DEBUG_XMIT,
2466 						  "TX queue stuck %d\n",
2467 						  txq->qnum);
2468 					needreset = true;
2469 					txq->txq_stuck++;
2470 					spin_unlock_bh(&txq->lock);
2471 					break;
2472 				} else {
2473 					txq->txq_poll_mark = true;
2474 				}
2475 			}
2476 			spin_unlock_bh(&txq->lock);
2477 		}
2478 	}
2479 
2480 	if (needreset) {
2481 		ATH5K_DBG(ah, ATH5K_DEBUG_RESET,
2482 			  "TX queues stuck, resetting\n");
2483 		ath5k_reset(ah, NULL, true);
2484 	}
2485 
2486 	mutex_unlock(&ah->lock);
2487 
2488 	ieee80211_queue_delayed_work(ah->hw, &ah->tx_complete_work,
2489 		msecs_to_jiffies(ATH5K_TX_COMPLETE_POLL_INT));
2490 }
2491 
2492 
2493 /*************************\
2494 * Initialization routines *
2495 \*************************/
2496 
2497 static const struct ieee80211_iface_limit if_limits[] = {
2498 	{ .max = 2048,	.types = BIT(NL80211_IFTYPE_STATION) },
2499 	{ .max = 4,	.types =
2500 #ifdef CONFIG_MAC80211_MESH
2501 				 BIT(NL80211_IFTYPE_MESH_POINT) |
2502 #endif
2503 				 BIT(NL80211_IFTYPE_AP) },
2504 };
2505 
2506 static const struct ieee80211_iface_combination if_comb = {
2507 	.limits = if_limits,
2508 	.n_limits = ARRAY_SIZE(if_limits),
2509 	.max_interfaces = 2048,
2510 	.num_different_channels = 1,
2511 };
2512 
2513 int
2514 ath5k_init_ah(struct ath5k_hw *ah, const struct ath_bus_ops *bus_ops)
2515 {
2516 	struct ieee80211_hw *hw = ah->hw;
2517 	struct ath_common *common;
2518 	int ret;
2519 	int csz;
2520 
2521 	/* Initialize driver private data */
2522 	SET_IEEE80211_DEV(hw, ah->dev);
2523 	hw->flags = IEEE80211_HW_RX_INCLUDES_FCS |
2524 			IEEE80211_HW_HOST_BROADCAST_PS_BUFFERING |
2525 			IEEE80211_HW_SIGNAL_DBM |
2526 			IEEE80211_HW_MFP_CAPABLE |
2527 			IEEE80211_HW_REPORTS_TX_ACK_STATUS |
2528 			IEEE80211_HW_SUPPORTS_RC_TABLE;
2529 
2530 	hw->wiphy->interface_modes =
2531 		BIT(NL80211_IFTYPE_AP) |
2532 		BIT(NL80211_IFTYPE_STATION) |
2533 		BIT(NL80211_IFTYPE_ADHOC) |
2534 		BIT(NL80211_IFTYPE_MESH_POINT);
2535 
2536 	hw->wiphy->iface_combinations = &if_comb;
2537 	hw->wiphy->n_iface_combinations = 1;
2538 
2539 	/* SW support for IBSS_RSN is provided by mac80211 */
2540 	hw->wiphy->flags |= WIPHY_FLAG_IBSS_RSN;
2541 
2542 	hw->wiphy->flags |= WIPHY_FLAG_SUPPORTS_5_10_MHZ;
2543 
2544 	/* both antennas can be configured as RX or TX */
2545 	hw->wiphy->available_antennas_tx = 0x3;
2546 	hw->wiphy->available_antennas_rx = 0x3;
2547 
2548 	hw->extra_tx_headroom = 2;
2549 
2550 	/*
2551 	 * Mark the device as detached to avoid processing
2552 	 * interrupts until setup is complete.
2553 	 */
2554 	__set_bit(ATH_STAT_INVALID, ah->status);
2555 
2556 	ah->opmode = NL80211_IFTYPE_STATION;
2557 	ah->bintval = 1000;
2558 	mutex_init(&ah->lock);
2559 	spin_lock_init(&ah->rxbuflock);
2560 	spin_lock_init(&ah->txbuflock);
2561 	spin_lock_init(&ah->block);
2562 	spin_lock_init(&ah->irqlock);
2563 
2564 	/* Setup interrupt handler */
2565 	ret = request_irq(ah->irq, ath5k_intr, IRQF_SHARED, "ath", ah);
2566 	if (ret) {
2567 		ATH5K_ERR(ah, "request_irq failed\n");
2568 		goto err;
2569 	}
2570 
2571 	common = ath5k_hw_common(ah);
2572 	common->ops = &ath5k_common_ops;
2573 	common->bus_ops = bus_ops;
2574 	common->ah = ah;
2575 	common->hw = hw;
2576 	common->priv = ah;
2577 	common->clockrate = 40;
2578 
2579 	/*
2580 	 * Cache line size is used to size and align various
2581 	 * structures used to communicate with the hardware.
2582 	 */
2583 	ath5k_read_cachesize(common, &csz);
2584 	common->cachelsz = csz << 2; /* convert to bytes */
2585 
2586 	spin_lock_init(&common->cc_lock);
2587 
2588 	/* Initialize device */
2589 	ret = ath5k_hw_init(ah);
2590 	if (ret)
2591 		goto err_irq;
2592 
2593 	/* Set up multi-rate retry capabilities */
2594 	if (ah->ah_capabilities.cap_has_mrr_support) {
2595 		hw->max_rates = 4;
2596 		hw->max_rate_tries = max(AR5K_INIT_RETRY_SHORT,
2597 					 AR5K_INIT_RETRY_LONG);
2598 	}
2599 
2600 	hw->vif_data_size = sizeof(struct ath5k_vif);
2601 
2602 	/* Finish private driver data initialization */
2603 	ret = ath5k_init(hw);
2604 	if (ret)
2605 		goto err_ah;
2606 
2607 	ATH5K_INFO(ah, "Atheros AR%s chip found (MAC: 0x%x, PHY: 0x%x)\n",
2608 			ath5k_chip_name(AR5K_VERSION_MAC, ah->ah_mac_srev),
2609 					ah->ah_mac_srev,
2610 					ah->ah_phy_revision);
2611 
2612 	if (!ah->ah_single_chip) {
2613 		/* Single chip radio (!RF5111) */
2614 		if (ah->ah_radio_5ghz_revision &&
2615 			!ah->ah_radio_2ghz_revision) {
2616 			/* No 5GHz support -> report 2GHz radio */
2617 			if (!test_bit(AR5K_MODE_11A,
2618 				ah->ah_capabilities.cap_mode)) {
2619 				ATH5K_INFO(ah, "RF%s 2GHz radio found (0x%x)\n",
2620 					ath5k_chip_name(AR5K_VERSION_RAD,
2621 						ah->ah_radio_5ghz_revision),
2622 						ah->ah_radio_5ghz_revision);
2623 			/* No 2GHz support (5110 and some
2624 			 * 5GHz only cards) -> report 5GHz radio */
2625 			} else if (!test_bit(AR5K_MODE_11B,
2626 				ah->ah_capabilities.cap_mode)) {
2627 				ATH5K_INFO(ah, "RF%s 5GHz radio found (0x%x)\n",
2628 					ath5k_chip_name(AR5K_VERSION_RAD,
2629 						ah->ah_radio_5ghz_revision),
2630 						ah->ah_radio_5ghz_revision);
2631 			/* Multiband radio */
2632 			} else {
2633 				ATH5K_INFO(ah, "RF%s multiband radio found"
2634 					" (0x%x)\n",
2635 					ath5k_chip_name(AR5K_VERSION_RAD,
2636 						ah->ah_radio_5ghz_revision),
2637 						ah->ah_radio_5ghz_revision);
2638 			}
2639 		}
2640 		/* Multi chip radio (RF5111 - RF2111) ->
2641 		 * report both 2GHz/5GHz radios */
2642 		else if (ah->ah_radio_5ghz_revision &&
2643 				ah->ah_radio_2ghz_revision) {
2644 			ATH5K_INFO(ah, "RF%s 5GHz radio found (0x%x)\n",
2645 				ath5k_chip_name(AR5K_VERSION_RAD,
2646 					ah->ah_radio_5ghz_revision),
2647 					ah->ah_radio_5ghz_revision);
2648 			ATH5K_INFO(ah, "RF%s 2GHz radio found (0x%x)\n",
2649 				ath5k_chip_name(AR5K_VERSION_RAD,
2650 					ah->ah_radio_2ghz_revision),
2651 					ah->ah_radio_2ghz_revision);
2652 		}
2653 	}
2654 
2655 	ath5k_debug_init_device(ah);
2656 
2657 	/* ready to process interrupts */
2658 	__clear_bit(ATH_STAT_INVALID, ah->status);
2659 
2660 	return 0;
2661 err_ah:
2662 	ath5k_hw_deinit(ah);
2663 err_irq:
2664 	free_irq(ah->irq, ah);
2665 err:
2666 	return ret;
2667 }
2668 
2669 static int
2670 ath5k_stop_locked(struct ath5k_hw *ah)
2671 {
2672 
2673 	ATH5K_DBG(ah, ATH5K_DEBUG_RESET, "invalid %u\n",
2674 			test_bit(ATH_STAT_INVALID, ah->status));
2675 
2676 	/*
2677 	 * Shutdown the hardware and driver:
2678 	 *    stop output from above
2679 	 *    disable interrupts
2680 	 *    turn off timers
2681 	 *    turn off the radio
2682 	 *    clear transmit machinery
2683 	 *    clear receive machinery
2684 	 *    drain and release tx queues
2685 	 *    reclaim beacon resources
2686 	 *    power down hardware
2687 	 *
2688 	 * Note that some of this work is not possible if the
2689 	 * hardware is gone (invalid).
2690 	 */
2691 	ieee80211_stop_queues(ah->hw);
2692 
2693 	if (!test_bit(ATH_STAT_INVALID, ah->status)) {
2694 		ath5k_led_off(ah);
2695 		ath5k_hw_set_imr(ah, 0);
2696 		synchronize_irq(ah->irq);
2697 		ath5k_rx_stop(ah);
2698 		ath5k_hw_dma_stop(ah);
2699 		ath5k_drain_tx_buffs(ah);
2700 		ath5k_hw_phy_disable(ah);
2701 	}
2702 
2703 	return 0;
2704 }
2705 
2706 int ath5k_start(struct ieee80211_hw *hw)
2707 {
2708 	struct ath5k_hw *ah = hw->priv;
2709 	struct ath_common *common = ath5k_hw_common(ah);
2710 	int ret, i;
2711 
2712 	mutex_lock(&ah->lock);
2713 
2714 	ATH5K_DBG(ah, ATH5K_DEBUG_RESET, "mode %d\n", ah->opmode);
2715 
2716 	/*
2717 	 * Stop anything previously setup.  This is safe
2718 	 * no matter this is the first time through or not.
2719 	 */
2720 	ath5k_stop_locked(ah);
2721 
2722 	/*
2723 	 * The basic interface to setting the hardware in a good
2724 	 * state is ``reset''.  On return the hardware is known to
2725 	 * be powered up and with interrupts disabled.  This must
2726 	 * be followed by initialization of the appropriate bits
2727 	 * and then setup of the interrupt mask.
2728 	 */
2729 	ah->curchan = ah->hw->conf.chandef.chan;
2730 	ah->imask = AR5K_INT_RXOK
2731 		| AR5K_INT_RXERR
2732 		| AR5K_INT_RXEOL
2733 		| AR5K_INT_RXORN
2734 		| AR5K_INT_TXDESC
2735 		| AR5K_INT_TXEOL
2736 		| AR5K_INT_FATAL
2737 		| AR5K_INT_GLOBAL
2738 		| AR5K_INT_MIB;
2739 
2740 	ret = ath5k_reset(ah, NULL, false);
2741 	if (ret)
2742 		goto done;
2743 
2744 	if (!ath5k_modparam_no_hw_rfkill_switch)
2745 		ath5k_rfkill_hw_start(ah);
2746 
2747 	/*
2748 	 * Reset the key cache since some parts do not reset the
2749 	 * contents on initial power up or resume from suspend.
2750 	 */
2751 	for (i = 0; i < common->keymax; i++)
2752 		ath_hw_keyreset(common, (u16) i);
2753 
2754 	/* Use higher rates for acks instead of base
2755 	 * rate */
2756 	ah->ah_ack_bitrate_high = true;
2757 
2758 	for (i = 0; i < ARRAY_SIZE(ah->bslot); i++)
2759 		ah->bslot[i] = NULL;
2760 
2761 	ret = 0;
2762 done:
2763 	mmiowb();
2764 	mutex_unlock(&ah->lock);
2765 
2766 	set_bit(ATH_STAT_STARTED, ah->status);
2767 	ieee80211_queue_delayed_work(ah->hw, &ah->tx_complete_work,
2768 			msecs_to_jiffies(ATH5K_TX_COMPLETE_POLL_INT));
2769 
2770 	return ret;
2771 }
2772 
2773 static void ath5k_stop_tasklets(struct ath5k_hw *ah)
2774 {
2775 	ah->rx_pending = false;
2776 	ah->tx_pending = false;
2777 	tasklet_kill(&ah->rxtq);
2778 	tasklet_kill(&ah->txtq);
2779 	tasklet_kill(&ah->beacontq);
2780 	tasklet_kill(&ah->ani_tasklet);
2781 }
2782 
2783 /*
2784  * Stop the device, grabbing the top-level lock to protect
2785  * against concurrent entry through ath5k_init (which can happen
2786  * if another thread does a system call and the thread doing the
2787  * stop is preempted).
2788  */
2789 void ath5k_stop(struct ieee80211_hw *hw)
2790 {
2791 	struct ath5k_hw *ah = hw->priv;
2792 	int ret;
2793 
2794 	mutex_lock(&ah->lock);
2795 	ret = ath5k_stop_locked(ah);
2796 	if (ret == 0 && !test_bit(ATH_STAT_INVALID, ah->status)) {
2797 		/*
2798 		 * Don't set the card in full sleep mode!
2799 		 *
2800 		 * a) When the device is in this state it must be carefully
2801 		 * woken up or references to registers in the PCI clock
2802 		 * domain may freeze the bus (and system).  This varies
2803 		 * by chip and is mostly an issue with newer parts
2804 		 * (madwifi sources mentioned srev >= 0x78) that go to
2805 		 * sleep more quickly.
2806 		 *
2807 		 * b) On older chips full sleep results a weird behaviour
2808 		 * during wakeup. I tested various cards with srev < 0x78
2809 		 * and they don't wake up after module reload, a second
2810 		 * module reload is needed to bring the card up again.
2811 		 *
2812 		 * Until we figure out what's going on don't enable
2813 		 * full chip reset on any chip (this is what Legacy HAL
2814 		 * and Sam's HAL do anyway). Instead Perform a full reset
2815 		 * on the device (same as initial state after attach) and
2816 		 * leave it idle (keep MAC/BB on warm reset) */
2817 		ret = ath5k_hw_on_hold(ah);
2818 
2819 		ATH5K_DBG(ah, ATH5K_DEBUG_RESET,
2820 				"putting device to sleep\n");
2821 	}
2822 
2823 	mmiowb();
2824 	mutex_unlock(&ah->lock);
2825 
2826 	ath5k_stop_tasklets(ah);
2827 
2828 	clear_bit(ATH_STAT_STARTED, ah->status);
2829 	cancel_delayed_work_sync(&ah->tx_complete_work);
2830 
2831 	if (!ath5k_modparam_no_hw_rfkill_switch)
2832 		ath5k_rfkill_hw_stop(ah);
2833 }
2834 
2835 /*
2836  * Reset the hardware.  If chan is not NULL, then also pause rx/tx
2837  * and change to the given channel.
2838  *
2839  * This should be called with ah->lock.
2840  */
2841 static int
2842 ath5k_reset(struct ath5k_hw *ah, struct ieee80211_channel *chan,
2843 							bool skip_pcu)
2844 {
2845 	struct ath_common *common = ath5k_hw_common(ah);
2846 	int ret, ani_mode;
2847 	bool fast;
2848 
2849 	ATH5K_DBG(ah, ATH5K_DEBUG_RESET, "resetting\n");
2850 
2851 	ath5k_hw_set_imr(ah, 0);
2852 	synchronize_irq(ah->irq);
2853 	ath5k_stop_tasklets(ah);
2854 
2855 	/* Save ani mode and disable ANI during
2856 	 * reset. If we don't we might get false
2857 	 * PHY error interrupts. */
2858 	ani_mode = ah->ani_state.ani_mode;
2859 	ath5k_ani_init(ah, ATH5K_ANI_MODE_OFF);
2860 
2861 	/* We are going to empty hw queues
2862 	 * so we should also free any remaining
2863 	 * tx buffers */
2864 	ath5k_drain_tx_buffs(ah);
2865 	if (chan)
2866 		ah->curchan = chan;
2867 
2868 	fast = ((chan != NULL) && modparam_fastchanswitch) ? 1 : 0;
2869 
2870 	ret = ath5k_hw_reset(ah, ah->opmode, ah->curchan, fast, skip_pcu);
2871 	if (ret) {
2872 		ATH5K_ERR(ah, "can't reset hardware (%d)\n", ret);
2873 		goto err;
2874 	}
2875 
2876 	ret = ath5k_rx_start(ah);
2877 	if (ret) {
2878 		ATH5K_ERR(ah, "can't start recv logic\n");
2879 		goto err;
2880 	}
2881 
2882 	ath5k_ani_init(ah, ani_mode);
2883 
2884 	/*
2885 	 * Set calibration intervals
2886 	 *
2887 	 * Note: We don't need to run calibration imediately
2888 	 * since some initial calibration is done on reset
2889 	 * even for fast channel switching. Also on scanning
2890 	 * this will get set again and again and it won't get
2891 	 * executed unless we connect somewhere and spend some
2892 	 * time on the channel (that's what calibration needs
2893 	 * anyway to be accurate).
2894 	 */
2895 	ah->ah_cal_next_full = jiffies +
2896 		msecs_to_jiffies(ATH5K_TUNE_CALIBRATION_INTERVAL_FULL);
2897 	ah->ah_cal_next_ani = jiffies +
2898 		msecs_to_jiffies(ATH5K_TUNE_CALIBRATION_INTERVAL_ANI);
2899 	ah->ah_cal_next_short = jiffies +
2900 		msecs_to_jiffies(ATH5K_TUNE_CALIBRATION_INTERVAL_SHORT);
2901 
2902 	ewma_init(&ah->ah_beacon_rssi_avg, 1024, 8);
2903 
2904 	/* clear survey data and cycle counters */
2905 	memset(&ah->survey, 0, sizeof(ah->survey));
2906 	spin_lock_bh(&common->cc_lock);
2907 	ath_hw_cycle_counters_update(common);
2908 	memset(&common->cc_survey, 0, sizeof(common->cc_survey));
2909 	memset(&common->cc_ani, 0, sizeof(common->cc_ani));
2910 	spin_unlock_bh(&common->cc_lock);
2911 
2912 	/*
2913 	 * Change channels and update the h/w rate map if we're switching;
2914 	 * e.g. 11a to 11b/g.
2915 	 *
2916 	 * We may be doing a reset in response to an ioctl that changes the
2917 	 * channel so update any state that might change as a result.
2918 	 *
2919 	 * XXX needed?
2920 	 */
2921 /*	ath5k_chan_change(ah, c); */
2922 
2923 	ath5k_beacon_config(ah);
2924 	/* intrs are enabled by ath5k_beacon_config */
2925 
2926 	ieee80211_wake_queues(ah->hw);
2927 
2928 	return 0;
2929 err:
2930 	return ret;
2931 }
2932 
2933 static void ath5k_reset_work(struct work_struct *work)
2934 {
2935 	struct ath5k_hw *ah = container_of(work, struct ath5k_hw,
2936 		reset_work);
2937 
2938 	mutex_lock(&ah->lock);
2939 	ath5k_reset(ah, NULL, true);
2940 	mutex_unlock(&ah->lock);
2941 }
2942 
2943 static int
2944 ath5k_init(struct ieee80211_hw *hw)
2945 {
2946 
2947 	struct ath5k_hw *ah = hw->priv;
2948 	struct ath_regulatory *regulatory = ath5k_hw_regulatory(ah);
2949 	struct ath5k_txq *txq;
2950 	u8 mac[ETH_ALEN] = {};
2951 	int ret;
2952 
2953 
2954 	/*
2955 	 * Collect the channel list.  The 802.11 layer
2956 	 * is responsible for filtering this list based
2957 	 * on settings like the phy mode and regulatory
2958 	 * domain restrictions.
2959 	 */
2960 	ret = ath5k_setup_bands(hw);
2961 	if (ret) {
2962 		ATH5K_ERR(ah, "can't get channels\n");
2963 		goto err;
2964 	}
2965 
2966 	/*
2967 	 * Allocate tx+rx descriptors and populate the lists.
2968 	 */
2969 	ret = ath5k_desc_alloc(ah);
2970 	if (ret) {
2971 		ATH5K_ERR(ah, "can't allocate descriptors\n");
2972 		goto err;
2973 	}
2974 
2975 	/*
2976 	 * Allocate hardware transmit queues: one queue for
2977 	 * beacon frames and one data queue for each QoS
2978 	 * priority.  Note that hw functions handle resetting
2979 	 * these queues at the needed time.
2980 	 */
2981 	ret = ath5k_beaconq_setup(ah);
2982 	if (ret < 0) {
2983 		ATH5K_ERR(ah, "can't setup a beacon xmit queue\n");
2984 		goto err_desc;
2985 	}
2986 	ah->bhalq = ret;
2987 	ah->cabq = ath5k_txq_setup(ah, AR5K_TX_QUEUE_CAB, 0);
2988 	if (IS_ERR(ah->cabq)) {
2989 		ATH5K_ERR(ah, "can't setup cab queue\n");
2990 		ret = PTR_ERR(ah->cabq);
2991 		goto err_bhal;
2992 	}
2993 
2994 	/* 5211 and 5212 usually support 10 queues but we better rely on the
2995 	 * capability information */
2996 	if (ah->ah_capabilities.cap_queues.q_tx_num >= 6) {
2997 		/* This order matches mac80211's queue priority, so we can
2998 		* directly use the mac80211 queue number without any mapping */
2999 		txq = ath5k_txq_setup(ah, AR5K_TX_QUEUE_DATA, AR5K_WME_AC_VO);
3000 		if (IS_ERR(txq)) {
3001 			ATH5K_ERR(ah, "can't setup xmit queue\n");
3002 			ret = PTR_ERR(txq);
3003 			goto err_queues;
3004 		}
3005 		txq = ath5k_txq_setup(ah, AR5K_TX_QUEUE_DATA, AR5K_WME_AC_VI);
3006 		if (IS_ERR(txq)) {
3007 			ATH5K_ERR(ah, "can't setup xmit queue\n");
3008 			ret = PTR_ERR(txq);
3009 			goto err_queues;
3010 		}
3011 		txq = ath5k_txq_setup(ah, AR5K_TX_QUEUE_DATA, AR5K_WME_AC_BE);
3012 		if (IS_ERR(txq)) {
3013 			ATH5K_ERR(ah, "can't setup xmit queue\n");
3014 			ret = PTR_ERR(txq);
3015 			goto err_queues;
3016 		}
3017 		txq = ath5k_txq_setup(ah, AR5K_TX_QUEUE_DATA, AR5K_WME_AC_BK);
3018 		if (IS_ERR(txq)) {
3019 			ATH5K_ERR(ah, "can't setup xmit queue\n");
3020 			ret = PTR_ERR(txq);
3021 			goto err_queues;
3022 		}
3023 		hw->queues = 4;
3024 	} else {
3025 		/* older hardware (5210) can only support one data queue */
3026 		txq = ath5k_txq_setup(ah, AR5K_TX_QUEUE_DATA, AR5K_WME_AC_BE);
3027 		if (IS_ERR(txq)) {
3028 			ATH5K_ERR(ah, "can't setup xmit queue\n");
3029 			ret = PTR_ERR(txq);
3030 			goto err_queues;
3031 		}
3032 		hw->queues = 1;
3033 	}
3034 
3035 	tasklet_init(&ah->rxtq, ath5k_tasklet_rx, (unsigned long)ah);
3036 	tasklet_init(&ah->txtq, ath5k_tasklet_tx, (unsigned long)ah);
3037 	tasklet_init(&ah->beacontq, ath5k_tasklet_beacon, (unsigned long)ah);
3038 	tasklet_init(&ah->ani_tasklet, ath5k_tasklet_ani, (unsigned long)ah);
3039 
3040 	INIT_WORK(&ah->reset_work, ath5k_reset_work);
3041 	INIT_WORK(&ah->calib_work, ath5k_calibrate_work);
3042 	INIT_DELAYED_WORK(&ah->tx_complete_work, ath5k_tx_complete_poll_work);
3043 
3044 	ret = ath5k_hw_common(ah)->bus_ops->eeprom_read_mac(ah, mac);
3045 	if (ret) {
3046 		ATH5K_ERR(ah, "unable to read address from EEPROM\n");
3047 		goto err_queues;
3048 	}
3049 
3050 	SET_IEEE80211_PERM_ADDR(hw, mac);
3051 	/* All MAC address bits matter for ACKs */
3052 	ath5k_update_bssid_mask_and_opmode(ah, NULL);
3053 
3054 	regulatory->current_rd = ah->ah_capabilities.cap_eeprom.ee_regdomain;
3055 	ret = ath_regd_init(regulatory, hw->wiphy, ath5k_reg_notifier);
3056 	if (ret) {
3057 		ATH5K_ERR(ah, "can't initialize regulatory system\n");
3058 		goto err_queues;
3059 	}
3060 
3061 	ret = ieee80211_register_hw(hw);
3062 	if (ret) {
3063 		ATH5K_ERR(ah, "can't register ieee80211 hw\n");
3064 		goto err_queues;
3065 	}
3066 
3067 	if (!ath_is_world_regd(regulatory))
3068 		regulatory_hint(hw->wiphy, regulatory->alpha2);
3069 
3070 	ath5k_init_leds(ah);
3071 
3072 	ath5k_sysfs_register(ah);
3073 
3074 	return 0;
3075 err_queues:
3076 	ath5k_txq_release(ah);
3077 err_bhal:
3078 	ath5k_hw_release_tx_queue(ah, ah->bhalq);
3079 err_desc:
3080 	ath5k_desc_free(ah);
3081 err:
3082 	return ret;
3083 }
3084 
3085 void
3086 ath5k_deinit_ah(struct ath5k_hw *ah)
3087 {
3088 	struct ieee80211_hw *hw = ah->hw;
3089 
3090 	/*
3091 	 * NB: the order of these is important:
3092 	 * o call the 802.11 layer before detaching ath5k_hw to
3093 	 *   ensure callbacks into the driver to delete global
3094 	 *   key cache entries can be handled
3095 	 * o reclaim the tx queue data structures after calling
3096 	 *   the 802.11 layer as we'll get called back to reclaim
3097 	 *   node state and potentially want to use them
3098 	 * o to cleanup the tx queues the hal is called, so detach
3099 	 *   it last
3100 	 * XXX: ??? detach ath5k_hw ???
3101 	 * Other than that, it's straightforward...
3102 	 */
3103 	ieee80211_unregister_hw(hw);
3104 	ath5k_desc_free(ah);
3105 	ath5k_txq_release(ah);
3106 	ath5k_hw_release_tx_queue(ah, ah->bhalq);
3107 	ath5k_unregister_leds(ah);
3108 
3109 	ath5k_sysfs_unregister(ah);
3110 	/*
3111 	 * NB: can't reclaim these until after ieee80211_ifdetach
3112 	 * returns because we'll get called back to reclaim node
3113 	 * state and potentially want to use them.
3114 	 */
3115 	ath5k_hw_deinit(ah);
3116 	free_irq(ah->irq, ah);
3117 }
3118 
3119 bool
3120 ath5k_any_vif_assoc(struct ath5k_hw *ah)
3121 {
3122 	struct ath5k_vif_iter_data iter_data;
3123 	iter_data.hw_macaddr = NULL;
3124 	iter_data.any_assoc = false;
3125 	iter_data.need_set_hw_addr = false;
3126 	iter_data.found_active = true;
3127 
3128 	ieee80211_iterate_active_interfaces_atomic(
3129 		ah->hw, IEEE80211_IFACE_ITER_RESUME_ALL,
3130 		ath5k_vif_iter, &iter_data);
3131 	return iter_data.any_assoc;
3132 }
3133 
3134 void
3135 ath5k_set_beacon_filter(struct ieee80211_hw *hw, bool enable)
3136 {
3137 	struct ath5k_hw *ah = hw->priv;
3138 	u32 rfilt;
3139 	rfilt = ath5k_hw_get_rx_filter(ah);
3140 	if (enable)
3141 		rfilt |= AR5K_RX_FILTER_BEACON;
3142 	else
3143 		rfilt &= ~AR5K_RX_FILTER_BEACON;
3144 	ath5k_hw_set_rx_filter(ah, rfilt);
3145 	ah->filter_flags = rfilt;
3146 }
3147 
3148 void _ath5k_printk(const struct ath5k_hw *ah, const char *level,
3149 		   const char *fmt, ...)
3150 {
3151 	struct va_format vaf;
3152 	va_list args;
3153 
3154 	va_start(args, fmt);
3155 
3156 	vaf.fmt = fmt;
3157 	vaf.va = &args;
3158 
3159 	if (ah && ah->hw)
3160 		printk("%s" pr_fmt("%s: %pV"),
3161 		       level, wiphy_name(ah->hw->wiphy), &vaf);
3162 	else
3163 		printk("%s" pr_fmt("%pV"), level, &vaf);
3164 
3165 	va_end(args);
3166 }
3167