]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/net/wireless/ath/ath5k/base.c
ath5k: Cleanup opmode setting logic.
[karo-tx-linux.git] / drivers / net / wireless / ath / ath5k / base.c
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 #include <linux/module.h>
44 #include <linux/delay.h>
45 #include <linux/hardirq.h>
46 #include <linux/if.h>
47 #include <linux/io.h>
48 #include <linux/netdevice.h>
49 #include <linux/cache.h>
50 #include <linux/pci.h>
51 #include <linux/pci-aspm.h>
52 #include <linux/ethtool.h>
53 #include <linux/uaccess.h>
54 #include <linux/slab.h>
55 #include <linux/etherdevice.h>
56
57 #include <net/ieee80211_radiotap.h>
58
59 #include <asm/unaligned.h>
60
61 #include "base.h"
62 #include "reg.h"
63 #include "debug.h"
64 #include "ani.h"
65 #include "../debug.h"
66
67 static int modparam_nohwcrypt;
68 module_param_named(nohwcrypt, modparam_nohwcrypt, bool, S_IRUGO);
69 MODULE_PARM_DESC(nohwcrypt, "Disable hardware encryption.");
70
71 static int modparam_all_channels;
72 module_param_named(all_channels, modparam_all_channels, bool, S_IRUGO);
73 MODULE_PARM_DESC(all_channels, "Expose all channels the device can use.");
74
75 /* Module info */
76 MODULE_AUTHOR("Jiri Slaby");
77 MODULE_AUTHOR("Nick Kossifidis");
78 MODULE_DESCRIPTION("Support for 5xxx series of Atheros 802.11 wireless LAN cards.");
79 MODULE_SUPPORTED_DEVICE("Atheros 5xxx WLAN cards");
80 MODULE_LICENSE("Dual BSD/GPL");
81 MODULE_VERSION("0.6.0 (EXPERIMENTAL)");
82
83 static int ath5k_reset(struct ath5k_softc *sc, struct ieee80211_channel *chan);
84 static int ath5k_beacon_update(struct ieee80211_hw *hw,
85                 struct ieee80211_vif *vif);
86 static void ath5k_beacon_update_timers(struct ath5k_softc *sc, u64 bc_tsf);
87
88 /* Known PCI ids */
89 static DEFINE_PCI_DEVICE_TABLE(ath5k_pci_id_table) = {
90         { PCI_VDEVICE(ATHEROS, 0x0207) }, /* 5210 early */
91         { PCI_VDEVICE(ATHEROS, 0x0007) }, /* 5210 */
92         { PCI_VDEVICE(ATHEROS, 0x0011) }, /* 5311 - this is on AHB bus !*/
93         { PCI_VDEVICE(ATHEROS, 0x0012) }, /* 5211 */
94         { PCI_VDEVICE(ATHEROS, 0x0013) }, /* 5212 */
95         { PCI_VDEVICE(3COM_2,  0x0013) }, /* 3com 5212 */
96         { PCI_VDEVICE(3COM,    0x0013) }, /* 3com 3CRDAG675 5212 */
97         { PCI_VDEVICE(ATHEROS, 0x1014) }, /* IBM minipci 5212 */
98         { PCI_VDEVICE(ATHEROS, 0x0014) }, /* 5212 combatible */
99         { PCI_VDEVICE(ATHEROS, 0x0015) }, /* 5212 combatible */
100         { PCI_VDEVICE(ATHEROS, 0x0016) }, /* 5212 combatible */
101         { PCI_VDEVICE(ATHEROS, 0x0017) }, /* 5212 combatible */
102         { PCI_VDEVICE(ATHEROS, 0x0018) }, /* 5212 combatible */
103         { PCI_VDEVICE(ATHEROS, 0x0019) }, /* 5212 combatible */
104         { PCI_VDEVICE(ATHEROS, 0x001a) }, /* 2413 Griffin-lite */
105         { PCI_VDEVICE(ATHEROS, 0x001b) }, /* 5413 Eagle */
106         { PCI_VDEVICE(ATHEROS, 0x001c) }, /* PCI-E cards */
107         { PCI_VDEVICE(ATHEROS, 0x001d) }, /* 2417 Nala */
108         { 0 }
109 };
110 MODULE_DEVICE_TABLE(pci, ath5k_pci_id_table);
111
112 /* Known SREVs */
113 static const struct ath5k_srev_name srev_names[] = {
114         { "5210",       AR5K_VERSION_MAC,       AR5K_SREV_AR5210 },
115         { "5311",       AR5K_VERSION_MAC,       AR5K_SREV_AR5311 },
116         { "5311A",      AR5K_VERSION_MAC,       AR5K_SREV_AR5311A },
117         { "5311B",      AR5K_VERSION_MAC,       AR5K_SREV_AR5311B },
118         { "5211",       AR5K_VERSION_MAC,       AR5K_SREV_AR5211 },
119         { "5212",       AR5K_VERSION_MAC,       AR5K_SREV_AR5212 },
120         { "5213",       AR5K_VERSION_MAC,       AR5K_SREV_AR5213 },
121         { "5213A",      AR5K_VERSION_MAC,       AR5K_SREV_AR5213A },
122         { "2413",       AR5K_VERSION_MAC,       AR5K_SREV_AR2413 },
123         { "2414",       AR5K_VERSION_MAC,       AR5K_SREV_AR2414 },
124         { "5424",       AR5K_VERSION_MAC,       AR5K_SREV_AR5424 },
125         { "5413",       AR5K_VERSION_MAC,       AR5K_SREV_AR5413 },
126         { "5414",       AR5K_VERSION_MAC,       AR5K_SREV_AR5414 },
127         { "2415",       AR5K_VERSION_MAC,       AR5K_SREV_AR2415 },
128         { "5416",       AR5K_VERSION_MAC,       AR5K_SREV_AR5416 },
129         { "5418",       AR5K_VERSION_MAC,       AR5K_SREV_AR5418 },
130         { "2425",       AR5K_VERSION_MAC,       AR5K_SREV_AR2425 },
131         { "2417",       AR5K_VERSION_MAC,       AR5K_SREV_AR2417 },
132         { "xxxxx",      AR5K_VERSION_MAC,       AR5K_SREV_UNKNOWN },
133         { "5110",       AR5K_VERSION_RAD,       AR5K_SREV_RAD_5110 },
134         { "5111",       AR5K_VERSION_RAD,       AR5K_SREV_RAD_5111 },
135         { "5111A",      AR5K_VERSION_RAD,       AR5K_SREV_RAD_5111A },
136         { "2111",       AR5K_VERSION_RAD,       AR5K_SREV_RAD_2111 },
137         { "5112",       AR5K_VERSION_RAD,       AR5K_SREV_RAD_5112 },
138         { "5112A",      AR5K_VERSION_RAD,       AR5K_SREV_RAD_5112A },
139         { "5112B",      AR5K_VERSION_RAD,       AR5K_SREV_RAD_5112B },
140         { "2112",       AR5K_VERSION_RAD,       AR5K_SREV_RAD_2112 },
141         { "2112A",      AR5K_VERSION_RAD,       AR5K_SREV_RAD_2112A },
142         { "2112B",      AR5K_VERSION_RAD,       AR5K_SREV_RAD_2112B },
143         { "2413",       AR5K_VERSION_RAD,       AR5K_SREV_RAD_2413 },
144         { "5413",       AR5K_VERSION_RAD,       AR5K_SREV_RAD_5413 },
145         { "2316",       AR5K_VERSION_RAD,       AR5K_SREV_RAD_2316 },
146         { "2317",       AR5K_VERSION_RAD,       AR5K_SREV_RAD_2317 },
147         { "5424",       AR5K_VERSION_RAD,       AR5K_SREV_RAD_5424 },
148         { "5133",       AR5K_VERSION_RAD,       AR5K_SREV_RAD_5133 },
149         { "xxxxx",      AR5K_VERSION_RAD,       AR5K_SREV_UNKNOWN },
150 };
151
152 static const struct ieee80211_rate ath5k_rates[] = {
153         { .bitrate = 10,
154           .hw_value = ATH5K_RATE_CODE_1M, },
155         { .bitrate = 20,
156           .hw_value = ATH5K_RATE_CODE_2M,
157           .hw_value_short = ATH5K_RATE_CODE_2M | AR5K_SET_SHORT_PREAMBLE,
158           .flags = IEEE80211_RATE_SHORT_PREAMBLE },
159         { .bitrate = 55,
160           .hw_value = ATH5K_RATE_CODE_5_5M,
161           .hw_value_short = ATH5K_RATE_CODE_5_5M | AR5K_SET_SHORT_PREAMBLE,
162           .flags = IEEE80211_RATE_SHORT_PREAMBLE },
163         { .bitrate = 110,
164           .hw_value = ATH5K_RATE_CODE_11M,
165           .hw_value_short = ATH5K_RATE_CODE_11M | AR5K_SET_SHORT_PREAMBLE,
166           .flags = IEEE80211_RATE_SHORT_PREAMBLE },
167         { .bitrate = 60,
168           .hw_value = ATH5K_RATE_CODE_6M,
169           .flags = 0 },
170         { .bitrate = 90,
171           .hw_value = ATH5K_RATE_CODE_9M,
172           .flags = 0 },
173         { .bitrate = 120,
174           .hw_value = ATH5K_RATE_CODE_12M,
175           .flags = 0 },
176         { .bitrate = 180,
177           .hw_value = ATH5K_RATE_CODE_18M,
178           .flags = 0 },
179         { .bitrate = 240,
180           .hw_value = ATH5K_RATE_CODE_24M,
181           .flags = 0 },
182         { .bitrate = 360,
183           .hw_value = ATH5K_RATE_CODE_36M,
184           .flags = 0 },
185         { .bitrate = 480,
186           .hw_value = ATH5K_RATE_CODE_48M,
187           .flags = 0 },
188         { .bitrate = 540,
189           .hw_value = ATH5K_RATE_CODE_54M,
190           .flags = 0 },
191         /* XR missing */
192 };
193
194 static inline void ath5k_txbuf_free_skb(struct ath5k_softc *sc,
195                                 struct ath5k_buf *bf)
196 {
197         BUG_ON(!bf);
198         if (!bf->skb)
199                 return;
200         pci_unmap_single(sc->pdev, bf->skbaddr, bf->skb->len,
201                         PCI_DMA_TODEVICE);
202         dev_kfree_skb_any(bf->skb);
203         bf->skb = NULL;
204         bf->skbaddr = 0;
205         bf->desc->ds_data = 0;
206 }
207
208 static inline void ath5k_rxbuf_free_skb(struct ath5k_softc *sc,
209                                 struct ath5k_buf *bf)
210 {
211         struct ath5k_hw *ah = sc->ah;
212         struct ath_common *common = ath5k_hw_common(ah);
213
214         BUG_ON(!bf);
215         if (!bf->skb)
216                 return;
217         pci_unmap_single(sc->pdev, bf->skbaddr, common->rx_bufsize,
218                         PCI_DMA_FROMDEVICE);
219         dev_kfree_skb_any(bf->skb);
220         bf->skb = NULL;
221         bf->skbaddr = 0;
222         bf->desc->ds_data = 0;
223 }
224
225
226 static inline u64 ath5k_extend_tsf(struct ath5k_hw *ah, u32 rstamp)
227 {
228         u64 tsf = ath5k_hw_get_tsf64(ah);
229
230         if ((tsf & 0x7fff) < rstamp)
231                 tsf -= 0x8000;
232
233         return (tsf & ~0x7fff) | rstamp;
234 }
235
236 static const char *
237 ath5k_chip_name(enum ath5k_srev_type type, u_int16_t val)
238 {
239         const char *name = "xxxxx";
240         unsigned int i;
241
242         for (i = 0; i < ARRAY_SIZE(srev_names); i++) {
243                 if (srev_names[i].sr_type != type)
244                         continue;
245
246                 if ((val & 0xf0) == srev_names[i].sr_val)
247                         name = srev_names[i].sr_name;
248
249                 if ((val & 0xff) == srev_names[i].sr_val) {
250                         name = srev_names[i].sr_name;
251                         break;
252                 }
253         }
254
255         return name;
256 }
257 static unsigned int ath5k_ioread32(void *hw_priv, u32 reg_offset)
258 {
259         struct ath5k_hw *ah = (struct ath5k_hw *) hw_priv;
260         return ath5k_hw_reg_read(ah, reg_offset);
261 }
262
263 static void ath5k_iowrite32(void *hw_priv, u32 val, u32 reg_offset)
264 {
265         struct ath5k_hw *ah = (struct ath5k_hw *) hw_priv;
266         ath5k_hw_reg_write(ah, val, reg_offset);
267 }
268
269 static const struct ath_ops ath5k_common_ops = {
270         .read = ath5k_ioread32,
271         .write = ath5k_iowrite32,
272 };
273
274 /***********************\
275 * Driver Initialization *
276 \***********************/
277
278 static int ath5k_reg_notifier(struct wiphy *wiphy, struct regulatory_request *request)
279 {
280         struct ieee80211_hw *hw = wiphy_to_ieee80211_hw(wiphy);
281         struct ath5k_softc *sc = hw->priv;
282         struct ath_regulatory *regulatory = ath5k_hw_regulatory(sc->ah);
283
284         return ath_reg_notifier_apply(wiphy, request, regulatory);
285 }
286
287 /********************\
288 * Channel/mode setup *
289 \********************/
290
291 /*
292  * Convert IEEE channel number to MHz frequency.
293  */
294 static inline short
295 ath5k_ieee2mhz(short chan)
296 {
297         if (chan <= 14 || chan >= 27)
298                 return ieee80211chan2mhz(chan);
299         else
300                 return 2212 + chan * 20;
301 }
302
303 /*
304  * Returns true for the channel numbers used without all_channels modparam.
305  */
306 static bool ath5k_is_standard_channel(short chan)
307 {
308         return ((chan <= 14) ||
309                 /* UNII 1,2 */
310                 ((chan & 3) == 0 && chan >= 36 && chan <= 64) ||
311                 /* midband */
312                 ((chan & 3) == 0 && chan >= 100 && chan <= 140) ||
313                 /* UNII-3 */
314                 ((chan & 3) == 1 && chan >= 149 && chan <= 165));
315 }
316
317 static unsigned int
318 ath5k_copy_channels(struct ath5k_hw *ah,
319                 struct ieee80211_channel *channels,
320                 unsigned int mode,
321                 unsigned int max)
322 {
323         unsigned int i, count, size, chfreq, freq, ch;
324
325         if (!test_bit(mode, ah->ah_modes))
326                 return 0;
327
328         switch (mode) {
329         case AR5K_MODE_11A:
330         case AR5K_MODE_11A_TURBO:
331                 /* 1..220, but 2GHz frequencies are filtered by check_channel */
332                 size = 220 ;
333                 chfreq = CHANNEL_5GHZ;
334                 break;
335         case AR5K_MODE_11B:
336         case AR5K_MODE_11G:
337         case AR5K_MODE_11G_TURBO:
338                 size = 26;
339                 chfreq = CHANNEL_2GHZ;
340                 break;
341         default:
342                 ATH5K_WARN(ah->ah_sc, "bad mode, not copying channels\n");
343                 return 0;
344         }
345
346         for (i = 0, count = 0; i < size && max > 0; i++) {
347                 ch = i + 1 ;
348                 freq = ath5k_ieee2mhz(ch);
349
350                 /* Check if channel is supported by the chipset */
351                 if (!ath5k_channel_ok(ah, freq, chfreq))
352                         continue;
353
354                 if (!modparam_all_channels && !ath5k_is_standard_channel(ch))
355                         continue;
356
357                 /* Write channel info and increment counter */
358                 channels[count].center_freq = freq;
359                 channels[count].band = (chfreq == CHANNEL_2GHZ) ?
360                         IEEE80211_BAND_2GHZ : IEEE80211_BAND_5GHZ;
361                 switch (mode) {
362                 case AR5K_MODE_11A:
363                 case AR5K_MODE_11G:
364                         channels[count].hw_value = chfreq | CHANNEL_OFDM;
365                         break;
366                 case AR5K_MODE_11A_TURBO:
367                 case AR5K_MODE_11G_TURBO:
368                         channels[count].hw_value = chfreq |
369                                 CHANNEL_OFDM | CHANNEL_TURBO;
370                         break;
371                 case AR5K_MODE_11B:
372                         channels[count].hw_value = CHANNEL_B;
373                 }
374
375                 count++;
376                 max--;
377         }
378
379         return count;
380 }
381
382 static void
383 ath5k_setup_rate_idx(struct ath5k_softc *sc, struct ieee80211_supported_band *b)
384 {
385         u8 i;
386
387         for (i = 0; i < AR5K_MAX_RATES; i++)
388                 sc->rate_idx[b->band][i] = -1;
389
390         for (i = 0; i < b->n_bitrates; i++) {
391                 sc->rate_idx[b->band][b->bitrates[i].hw_value] = i;
392                 if (b->bitrates[i].hw_value_short)
393                         sc->rate_idx[b->band][b->bitrates[i].hw_value_short] = i;
394         }
395 }
396
397 static int
398 ath5k_setup_bands(struct ieee80211_hw *hw)
399 {
400         struct ath5k_softc *sc = hw->priv;
401         struct ath5k_hw *ah = sc->ah;
402         struct ieee80211_supported_band *sband;
403         int max_c, count_c = 0;
404         int i;
405
406         BUILD_BUG_ON(ARRAY_SIZE(sc->sbands) < IEEE80211_NUM_BANDS);
407         max_c = ARRAY_SIZE(sc->channels);
408
409         /* 2GHz band */
410         sband = &sc->sbands[IEEE80211_BAND_2GHZ];
411         sband->band = IEEE80211_BAND_2GHZ;
412         sband->bitrates = &sc->rates[IEEE80211_BAND_2GHZ][0];
413
414         if (test_bit(AR5K_MODE_11G, sc->ah->ah_capabilities.cap_mode)) {
415                 /* G mode */
416                 memcpy(sband->bitrates, &ath5k_rates[0],
417                        sizeof(struct ieee80211_rate) * 12);
418                 sband->n_bitrates = 12;
419
420                 sband->channels = sc->channels;
421                 sband->n_channels = ath5k_copy_channels(ah, sband->channels,
422                                         AR5K_MODE_11G, max_c);
423
424                 hw->wiphy->bands[IEEE80211_BAND_2GHZ] = sband;
425                 count_c = sband->n_channels;
426                 max_c -= count_c;
427         } else if (test_bit(AR5K_MODE_11B, sc->ah->ah_capabilities.cap_mode)) {
428                 /* B mode */
429                 memcpy(sband->bitrates, &ath5k_rates[0],
430                        sizeof(struct ieee80211_rate) * 4);
431                 sband->n_bitrates = 4;
432
433                 /* 5211 only supports B rates and uses 4bit rate codes
434                  * (e.g normally we have 0x1B for 1M, but on 5211 we have 0x0B)
435                  * fix them up here:
436                  */
437                 if (ah->ah_version == AR5K_AR5211) {
438                         for (i = 0; i < 4; i++) {
439                                 sband->bitrates[i].hw_value =
440                                         sband->bitrates[i].hw_value & 0xF;
441                                 sband->bitrates[i].hw_value_short =
442                                         sband->bitrates[i].hw_value_short & 0xF;
443                         }
444                 }
445
446                 sband->channels = sc->channels;
447                 sband->n_channels = ath5k_copy_channels(ah, sband->channels,
448                                         AR5K_MODE_11B, max_c);
449
450                 hw->wiphy->bands[IEEE80211_BAND_2GHZ] = sband;
451                 count_c = sband->n_channels;
452                 max_c -= count_c;
453         }
454         ath5k_setup_rate_idx(sc, sband);
455
456         /* 5GHz band, A mode */
457         if (test_bit(AR5K_MODE_11A, sc->ah->ah_capabilities.cap_mode)) {
458                 sband = &sc->sbands[IEEE80211_BAND_5GHZ];
459                 sband->band = IEEE80211_BAND_5GHZ;
460                 sband->bitrates = &sc->rates[IEEE80211_BAND_5GHZ][0];
461
462                 memcpy(sband->bitrates, &ath5k_rates[4],
463                        sizeof(struct ieee80211_rate) * 8);
464                 sband->n_bitrates = 8;
465
466                 sband->channels = &sc->channels[count_c];
467                 sband->n_channels = ath5k_copy_channels(ah, sband->channels,
468                                         AR5K_MODE_11A, max_c);
469
470                 hw->wiphy->bands[IEEE80211_BAND_5GHZ] = sband;
471         }
472         ath5k_setup_rate_idx(sc, sband);
473
474         ath5k_debug_dump_bands(sc);
475
476         return 0;
477 }
478
479 /*
480  * Set/change channels. We always reset the chip.
481  * To accomplish this we must first cleanup any pending DMA,
482  * then restart stuff after a la  ath5k_init.
483  *
484  * Called with sc->lock.
485  */
486 static int
487 ath5k_chan_set(struct ath5k_softc *sc, struct ieee80211_channel *chan)
488 {
489         ATH5K_DBG(sc, ATH5K_DEBUG_RESET,
490                   "channel set, resetting (%u -> %u MHz)\n",
491                   sc->curchan->center_freq, chan->center_freq);
492
493         /*
494          * To switch channels clear any pending DMA operations;
495          * wait long enough for the RX fifo to drain, reset the
496          * hardware at the new frequency, and then re-enable
497          * the relevant bits of the h/w.
498          */
499         return ath5k_reset(sc, chan);
500 }
501
502 static void
503 ath5k_setcurmode(struct ath5k_softc *sc, unsigned int mode)
504 {
505         sc->curmode = mode;
506
507         if (mode == AR5K_MODE_11A) {
508                 sc->curband = &sc->sbands[IEEE80211_BAND_5GHZ];
509         } else {
510                 sc->curband = &sc->sbands[IEEE80211_BAND_2GHZ];
511         }
512 }
513
514 struct ath_vif_iter_data {
515         const u8        *hw_macaddr;
516         u8              mask[ETH_ALEN];
517         u8              active_mac[ETH_ALEN]; /* first active MAC */
518         bool            need_set_hw_addr;
519         bool            found_active;
520         bool            any_assoc;
521         enum nl80211_iftype opmode;
522 };
523
524 static void ath_vif_iter(void *data, u8 *mac, struct ieee80211_vif *vif)
525 {
526         struct ath_vif_iter_data *iter_data = data;
527         int i;
528         struct ath5k_vif *avf = (void *)vif->drv_priv;
529
530         if (iter_data->hw_macaddr)
531                 for (i = 0; i < ETH_ALEN; i++)
532                         iter_data->mask[i] &=
533                                 ~(iter_data->hw_macaddr[i] ^ mac[i]);
534
535         if (!iter_data->found_active) {
536                 iter_data->found_active = true;
537                 memcpy(iter_data->active_mac, mac, ETH_ALEN);
538         }
539
540         if (iter_data->need_set_hw_addr && iter_data->hw_macaddr)
541                 if (compare_ether_addr(iter_data->hw_macaddr, mac) == 0)
542                         iter_data->need_set_hw_addr = false;
543
544         if (!iter_data->any_assoc) {
545                 if (avf->assoc)
546                         iter_data->any_assoc = true;
547         }
548
549         /* Calculate combined mode - when APs are active, operate in AP mode.
550          * Otherwise use the mode of the new interface. This can currently
551          * only deal with combinations of APs and STAs. Only one ad-hoc
552          * interfaces is allowed.
553          */
554         if (avf->opmode == NL80211_IFTYPE_AP)
555                 iter_data->opmode = NL80211_IFTYPE_AP;
556         else
557                 if (iter_data->opmode == NL80211_IFTYPE_UNSPECIFIED)
558                         iter_data->opmode = avf->opmode;
559 }
560
561 static void ath5k_update_bssid_mask_and_opmode(struct ath5k_softc *sc,
562                                                struct ieee80211_vif *vif)
563 {
564         struct ath_common *common = ath5k_hw_common(sc->ah);
565         struct ath_vif_iter_data iter_data;
566
567         /*
568          * Use the hardware MAC address as reference, the hardware uses it
569          * together with the BSSID mask when matching addresses.
570          */
571         iter_data.hw_macaddr = common->macaddr;
572         memset(&iter_data.mask, 0xff, ETH_ALEN);
573         iter_data.found_active = false;
574         iter_data.need_set_hw_addr = true;
575         iter_data.opmode = NL80211_IFTYPE_UNSPECIFIED;
576
577         if (vif)
578                 ath_vif_iter(&iter_data, vif->addr, vif);
579
580         /* Get list of all active MAC addresses */
581         ieee80211_iterate_active_interfaces_atomic(sc->hw, ath_vif_iter,
582                                                    &iter_data);
583         memcpy(sc->bssidmask, iter_data.mask, ETH_ALEN);
584
585         sc->opmode = iter_data.opmode;
586         if (sc->opmode == NL80211_IFTYPE_UNSPECIFIED)
587                 /* Nothing active, default to station mode */
588                 sc->opmode = NL80211_IFTYPE_STATION;
589
590         ath5k_hw_set_opmode(sc->ah, sc->opmode);
591         ATH5K_DBG(sc, ATH5K_DEBUG_MODE, "mode setup opmode %d (%s)\n",
592                   sc->opmode, ath_opmode_to_string(sc->opmode));
593
594         if (iter_data.need_set_hw_addr && iter_data.found_active)
595                 ath5k_hw_set_lladdr(sc->ah, iter_data.active_mac);
596
597         if (ath5k_hw_hasbssidmask(sc->ah))
598                 ath5k_hw_set_bssid_mask(sc->ah, sc->bssidmask);
599 }
600
601 static void
602 ath5k_mode_setup(struct ath5k_softc *sc, struct ieee80211_vif *vif)
603 {
604         struct ath5k_hw *ah = sc->ah;
605         u32 rfilt;
606
607         /* configure rx filter */
608         rfilt = sc->filter_flags;
609         ath5k_hw_set_rx_filter(ah, rfilt);
610         ATH5K_DBG(sc, ATH5K_DEBUG_MODE, "RX filter 0x%x\n", rfilt);
611
612         ath5k_update_bssid_mask_and_opmode(sc, vif);
613 }
614
615 static inline int
616 ath5k_hw_to_driver_rix(struct ath5k_softc *sc, int hw_rix)
617 {
618         int rix;
619
620         /* return base rate on errors */
621         if (WARN(hw_rix < 0 || hw_rix >= AR5K_MAX_RATES,
622                         "hw_rix out of bounds: %x\n", hw_rix))
623                 return 0;
624
625         rix = sc->rate_idx[sc->curband->band][hw_rix];
626         if (WARN(rix < 0, "invalid hw_rix: %x\n", hw_rix))
627                 rix = 0;
628
629         return rix;
630 }
631
632 /***************\
633 * Buffers setup *
634 \***************/
635
636 static
637 struct sk_buff *ath5k_rx_skb_alloc(struct ath5k_softc *sc, dma_addr_t *skb_addr)
638 {
639         struct ath_common *common = ath5k_hw_common(sc->ah);
640         struct sk_buff *skb;
641
642         /*
643          * Allocate buffer with headroom_needed space for the
644          * fake physical layer header at the start.
645          */
646         skb = ath_rxbuf_alloc(common,
647                               common->rx_bufsize,
648                               GFP_ATOMIC);
649
650         if (!skb) {
651                 ATH5K_ERR(sc, "can't alloc skbuff of size %u\n",
652                                 common->rx_bufsize);
653                 return NULL;
654         }
655
656         *skb_addr = pci_map_single(sc->pdev,
657                                    skb->data, common->rx_bufsize,
658                                    PCI_DMA_FROMDEVICE);
659         if (unlikely(pci_dma_mapping_error(sc->pdev, *skb_addr))) {
660                 ATH5K_ERR(sc, "%s: DMA mapping failed\n", __func__);
661                 dev_kfree_skb(skb);
662                 return NULL;
663         }
664         return skb;
665 }
666
667 static int
668 ath5k_rxbuf_setup(struct ath5k_softc *sc, struct ath5k_buf *bf)
669 {
670         struct ath5k_hw *ah = sc->ah;
671         struct sk_buff *skb = bf->skb;
672         struct ath5k_desc *ds;
673         int ret;
674
675         if (!skb) {
676                 skb = ath5k_rx_skb_alloc(sc, &bf->skbaddr);
677                 if (!skb)
678                         return -ENOMEM;
679                 bf->skb = skb;
680         }
681
682         /*
683          * Setup descriptors.  For receive we always terminate
684          * the descriptor list with a self-linked entry so we'll
685          * not get overrun under high load (as can happen with a
686          * 5212 when ANI processing enables PHY error frames).
687          *
688          * To ensure the last descriptor is self-linked we create
689          * each descriptor as self-linked and add it to the end.  As
690          * each additional descriptor is added the previous self-linked
691          * entry is "fixed" naturally.  This should be safe even
692          * if DMA is happening.  When processing RX interrupts we
693          * never remove/process the last, self-linked, entry on the
694          * descriptor list.  This ensures the hardware always has
695          * someplace to write a new frame.
696          */
697         ds = bf->desc;
698         ds->ds_link = bf->daddr;        /* link to self */
699         ds->ds_data = bf->skbaddr;
700         ret = ath5k_hw_setup_rx_desc(ah, ds, ah->common.rx_bufsize, 0);
701         if (ret) {
702                 ATH5K_ERR(sc, "%s: could not setup RX desc\n", __func__);
703                 return ret;
704         }
705
706         if (sc->rxlink != NULL)
707                 *sc->rxlink = bf->daddr;
708         sc->rxlink = &ds->ds_link;
709         return 0;
710 }
711
712 static enum ath5k_pkt_type get_hw_packet_type(struct sk_buff *skb)
713 {
714         struct ieee80211_hdr *hdr;
715         enum ath5k_pkt_type htype;
716         __le16 fc;
717
718         hdr = (struct ieee80211_hdr *)skb->data;
719         fc = hdr->frame_control;
720
721         if (ieee80211_is_beacon(fc))
722                 htype = AR5K_PKT_TYPE_BEACON;
723         else if (ieee80211_is_probe_resp(fc))
724                 htype = AR5K_PKT_TYPE_PROBE_RESP;
725         else if (ieee80211_is_atim(fc))
726                 htype = AR5K_PKT_TYPE_ATIM;
727         else if (ieee80211_is_pspoll(fc))
728                 htype = AR5K_PKT_TYPE_PSPOLL;
729         else
730                 htype = AR5K_PKT_TYPE_NORMAL;
731
732         return htype;
733 }
734
735 static int
736 ath5k_txbuf_setup(struct ath5k_softc *sc, struct ath5k_buf *bf,
737                   struct ath5k_txq *txq, int padsize)
738 {
739         struct ath5k_hw *ah = sc->ah;
740         struct ath5k_desc *ds = bf->desc;
741         struct sk_buff *skb = bf->skb;
742         struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
743         unsigned int pktlen, flags, keyidx = AR5K_TXKEYIX_INVALID;
744         struct ieee80211_rate *rate;
745         unsigned int mrr_rate[3], mrr_tries[3];
746         int i, ret;
747         u16 hw_rate;
748         u16 cts_rate = 0;
749         u16 duration = 0;
750         u8 rc_flags;
751
752         flags = AR5K_TXDESC_INTREQ | AR5K_TXDESC_CLRDMASK;
753
754         /* XXX endianness */
755         bf->skbaddr = pci_map_single(sc->pdev, skb->data, skb->len,
756                         PCI_DMA_TODEVICE);
757
758         rate = ieee80211_get_tx_rate(sc->hw, info);
759         if (!rate) {
760                 ret = -EINVAL;
761                 goto err_unmap;
762         }
763
764         if (info->flags & IEEE80211_TX_CTL_NO_ACK)
765                 flags |= AR5K_TXDESC_NOACK;
766
767         rc_flags = info->control.rates[0].flags;
768         hw_rate = (rc_flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE) ?
769                 rate->hw_value_short : rate->hw_value;
770
771         pktlen = skb->len;
772
773         /* FIXME: If we are in g mode and rate is a CCK rate
774          * subtract ah->ah_txpower.txp_cck_ofdm_pwr_delta
775          * from tx power (value is in dB units already) */
776         if (info->control.hw_key) {
777                 keyidx = info->control.hw_key->hw_key_idx;
778                 pktlen += info->control.hw_key->icv_len;
779         }
780         if (rc_flags & IEEE80211_TX_RC_USE_RTS_CTS) {
781                 flags |= AR5K_TXDESC_RTSENA;
782                 cts_rate = ieee80211_get_rts_cts_rate(sc->hw, info)->hw_value;
783                 duration = le16_to_cpu(ieee80211_rts_duration(sc->hw,
784                         info->control.vif, pktlen, info));
785         }
786         if (rc_flags & IEEE80211_TX_RC_USE_CTS_PROTECT) {
787                 flags |= AR5K_TXDESC_CTSENA;
788                 cts_rate = ieee80211_get_rts_cts_rate(sc->hw, info)->hw_value;
789                 duration = le16_to_cpu(ieee80211_ctstoself_duration(sc->hw,
790                         info->control.vif, pktlen, info));
791         }
792         ret = ah->ah_setup_tx_desc(ah, ds, pktlen,
793                 ieee80211_get_hdrlen_from_skb(skb), padsize,
794                 get_hw_packet_type(skb),
795                 (sc->power_level * 2),
796                 hw_rate,
797                 info->control.rates[0].count, keyidx, ah->ah_tx_ant, flags,
798                 cts_rate, duration);
799         if (ret)
800                 goto err_unmap;
801
802         memset(mrr_rate, 0, sizeof(mrr_rate));
803         memset(mrr_tries, 0, sizeof(mrr_tries));
804         for (i = 0; i < 3; i++) {
805                 rate = ieee80211_get_alt_retry_rate(sc->hw, info, i);
806                 if (!rate)
807                         break;
808
809                 mrr_rate[i] = rate->hw_value;
810                 mrr_tries[i] = info->control.rates[i + 1].count;
811         }
812
813         ath5k_hw_setup_mrr_tx_desc(ah, ds,
814                 mrr_rate[0], mrr_tries[0],
815                 mrr_rate[1], mrr_tries[1],
816                 mrr_rate[2], mrr_tries[2]);
817
818         ds->ds_link = 0;
819         ds->ds_data = bf->skbaddr;
820
821         spin_lock_bh(&txq->lock);
822         list_add_tail(&bf->list, &txq->q);
823         txq->txq_len++;
824         if (txq->link == NULL) /* is this first packet? */
825                 ath5k_hw_set_txdp(ah, txq->qnum, bf->daddr);
826         else /* no, so only link it */
827                 *txq->link = bf->daddr;
828
829         txq->link = &ds->ds_link;
830         ath5k_hw_start_tx_dma(ah, txq->qnum);
831         mmiowb();
832         spin_unlock_bh(&txq->lock);
833
834         return 0;
835 err_unmap:
836         pci_unmap_single(sc->pdev, bf->skbaddr, skb->len, PCI_DMA_TODEVICE);
837         return ret;
838 }
839
840 /*******************\
841 * Descriptors setup *
842 \*******************/
843
844 static int
845 ath5k_desc_alloc(struct ath5k_softc *sc, struct pci_dev *pdev)
846 {
847         struct ath5k_desc *ds;
848         struct ath5k_buf *bf;
849         dma_addr_t da;
850         unsigned int i;
851         int ret;
852
853         /* allocate descriptors */
854         sc->desc_len = sizeof(struct ath5k_desc) *
855                         (ATH_TXBUF + ATH_RXBUF + ATH_BCBUF + 1);
856         sc->desc = pci_alloc_consistent(pdev, sc->desc_len, &sc->desc_daddr);
857         if (sc->desc == NULL) {
858                 ATH5K_ERR(sc, "can't allocate descriptors\n");
859                 ret = -ENOMEM;
860                 goto err;
861         }
862         ds = sc->desc;
863         da = sc->desc_daddr;
864         ATH5K_DBG(sc, ATH5K_DEBUG_ANY, "DMA map: %p (%zu) -> %llx\n",
865                 ds, sc->desc_len, (unsigned long long)sc->desc_daddr);
866
867         bf = kcalloc(1 + ATH_TXBUF + ATH_RXBUF + ATH_BCBUF,
868                         sizeof(struct ath5k_buf), GFP_KERNEL);
869         if (bf == NULL) {
870                 ATH5K_ERR(sc, "can't allocate bufptr\n");
871                 ret = -ENOMEM;
872                 goto err_free;
873         }
874         sc->bufptr = bf;
875
876         INIT_LIST_HEAD(&sc->rxbuf);
877         for (i = 0; i < ATH_RXBUF; i++, bf++, ds++, da += sizeof(*ds)) {
878                 bf->desc = ds;
879                 bf->daddr = da;
880                 list_add_tail(&bf->list, &sc->rxbuf);
881         }
882
883         INIT_LIST_HEAD(&sc->txbuf);
884         sc->txbuf_len = ATH_TXBUF;
885         for (i = 0; i < ATH_TXBUF; i++, bf++, ds++,
886                         da += sizeof(*ds)) {
887                 bf->desc = ds;
888                 bf->daddr = da;
889                 list_add_tail(&bf->list, &sc->txbuf);
890         }
891
892         /* beacon buffers */
893         INIT_LIST_HEAD(&sc->bcbuf);
894         for (i = 0; i < ATH_BCBUF; i++, bf++, ds++, da += sizeof(*ds)) {
895                 bf->desc = ds;
896                 bf->daddr = da;
897                 list_add_tail(&bf->list, &sc->bcbuf);
898         }
899
900         return 0;
901 err_free:
902         pci_free_consistent(pdev, sc->desc_len, sc->desc, sc->desc_daddr);
903 err:
904         sc->desc = NULL;
905         return ret;
906 }
907
908 static void
909 ath5k_desc_free(struct ath5k_softc *sc, struct pci_dev *pdev)
910 {
911         struct ath5k_buf *bf;
912
913         list_for_each_entry(bf, &sc->txbuf, list)
914                 ath5k_txbuf_free_skb(sc, bf);
915         list_for_each_entry(bf, &sc->rxbuf, list)
916                 ath5k_rxbuf_free_skb(sc, bf);
917         list_for_each_entry(bf, &sc->bcbuf, list)
918                 ath5k_txbuf_free_skb(sc, bf);
919
920         /* Free memory associated with all descriptors */
921         pci_free_consistent(pdev, sc->desc_len, sc->desc, sc->desc_daddr);
922         sc->desc = NULL;
923         sc->desc_daddr = 0;
924
925         kfree(sc->bufptr);
926         sc->bufptr = NULL;
927 }
928
929
930 /**************\
931 * Queues setup *
932 \**************/
933
934 static struct ath5k_txq *
935 ath5k_txq_setup(struct ath5k_softc *sc,
936                 int qtype, int subtype)
937 {
938         struct ath5k_hw *ah = sc->ah;
939         struct ath5k_txq *txq;
940         struct ath5k_txq_info qi = {
941                 .tqi_subtype = subtype,
942                 /* XXX: default values not correct for B and XR channels,
943                  * but who cares? */
944                 .tqi_aifs = AR5K_TUNE_AIFS,
945                 .tqi_cw_min = AR5K_TUNE_CWMIN,
946                 .tqi_cw_max = AR5K_TUNE_CWMAX
947         };
948         int qnum;
949
950         /*
951          * Enable interrupts only for EOL and DESC conditions.
952          * We mark tx descriptors to receive a DESC interrupt
953          * when a tx queue gets deep; otherwise we wait for the
954          * EOL to reap descriptors.  Note that this is done to
955          * reduce interrupt load and this only defers reaping
956          * descriptors, never transmitting frames.  Aside from
957          * reducing interrupts this also permits more concurrency.
958          * The only potential downside is if the tx queue backs
959          * up in which case the top half of the kernel may backup
960          * due to a lack of tx descriptors.
961          */
962         qi.tqi_flags = AR5K_TXQ_FLAG_TXEOLINT_ENABLE |
963                                 AR5K_TXQ_FLAG_TXDESCINT_ENABLE;
964         qnum = ath5k_hw_setup_tx_queue(ah, qtype, &qi);
965         if (qnum < 0) {
966                 /*
967                  * NB: don't print a message, this happens
968                  * normally on parts with too few tx queues
969                  */
970                 return ERR_PTR(qnum);
971         }
972         if (qnum >= ARRAY_SIZE(sc->txqs)) {
973                 ATH5K_ERR(sc, "hw qnum %u out of range, max %tu!\n",
974                         qnum, ARRAY_SIZE(sc->txqs));
975                 ath5k_hw_release_tx_queue(ah, qnum);
976                 return ERR_PTR(-EINVAL);
977         }
978         txq = &sc->txqs[qnum];
979         if (!txq->setup) {
980                 txq->qnum = qnum;
981                 txq->link = NULL;
982                 INIT_LIST_HEAD(&txq->q);
983                 spin_lock_init(&txq->lock);
984                 txq->setup = true;
985                 txq->txq_len = 0;
986                 txq->txq_poll_mark = false;
987                 txq->txq_stuck = 0;
988         }
989         return &sc->txqs[qnum];
990 }
991
992 static int
993 ath5k_beaconq_setup(struct ath5k_hw *ah)
994 {
995         struct ath5k_txq_info qi = {
996                 /* XXX: default values not correct for B and XR channels,
997                  * but who cares? */
998                 .tqi_aifs = AR5K_TUNE_AIFS,
999                 .tqi_cw_min = AR5K_TUNE_CWMIN,
1000                 .tqi_cw_max = AR5K_TUNE_CWMAX,
1001                 /* NB: for dynamic turbo, don't enable any other interrupts */
1002                 .tqi_flags = AR5K_TXQ_FLAG_TXDESCINT_ENABLE
1003         };
1004
1005         return ath5k_hw_setup_tx_queue(ah, AR5K_TX_QUEUE_BEACON, &qi);
1006 }
1007
1008 static int
1009 ath5k_beaconq_config(struct ath5k_softc *sc)
1010 {
1011         struct ath5k_hw *ah = sc->ah;
1012         struct ath5k_txq_info qi;
1013         int ret;
1014
1015         ret = ath5k_hw_get_tx_queueprops(ah, sc->bhalq, &qi);
1016         if (ret)
1017                 goto err;
1018
1019         if (sc->opmode == NL80211_IFTYPE_AP ||
1020                 sc->opmode == NL80211_IFTYPE_MESH_POINT) {
1021                 /*
1022                  * Always burst out beacon and CAB traffic
1023                  * (aifs = cwmin = cwmax = 0)
1024                  */
1025                 qi.tqi_aifs = 0;
1026                 qi.tqi_cw_min = 0;
1027                 qi.tqi_cw_max = 0;
1028         } else if (sc->opmode == NL80211_IFTYPE_ADHOC) {
1029                 /*
1030                  * Adhoc mode; backoff between 0 and (2 * cw_min).
1031                  */
1032                 qi.tqi_aifs = 0;
1033                 qi.tqi_cw_min = 0;
1034                 qi.tqi_cw_max = 2 * AR5K_TUNE_CWMIN;
1035         }
1036
1037         ATH5K_DBG(sc, ATH5K_DEBUG_BEACON,
1038                 "beacon queueprops tqi_aifs:%d tqi_cw_min:%d tqi_cw_max:%d\n",
1039                 qi.tqi_aifs, qi.tqi_cw_min, qi.tqi_cw_max);
1040
1041         ret = ath5k_hw_set_tx_queueprops(ah, sc->bhalq, &qi);
1042         if (ret) {
1043                 ATH5K_ERR(sc, "%s: unable to update parameters for beacon "
1044                         "hardware queue!\n", __func__);
1045                 goto err;
1046         }
1047         ret = ath5k_hw_reset_tx_queue(ah, sc->bhalq); /* push to h/w */
1048         if (ret)
1049                 goto err;
1050
1051         /* reconfigure cabq with ready time to 80% of beacon_interval */
1052         ret = ath5k_hw_get_tx_queueprops(ah, AR5K_TX_QUEUE_ID_CAB, &qi);
1053         if (ret)
1054                 goto err;
1055
1056         qi.tqi_ready_time = (sc->bintval * 80) / 100;
1057         ret = ath5k_hw_set_tx_queueprops(ah, AR5K_TX_QUEUE_ID_CAB, &qi);
1058         if (ret)
1059                 goto err;
1060
1061         ret = ath5k_hw_reset_tx_queue(ah, AR5K_TX_QUEUE_ID_CAB);
1062 err:
1063         return ret;
1064 }
1065
1066 static void
1067 ath5k_txq_drainq(struct ath5k_softc *sc, struct ath5k_txq *txq)
1068 {
1069         struct ath5k_buf *bf, *bf0;
1070
1071         /*
1072          * NB: this assumes output has been stopped and
1073          *     we do not need to block ath5k_tx_tasklet
1074          */
1075         spin_lock_bh(&txq->lock);
1076         list_for_each_entry_safe(bf, bf0, &txq->q, list) {
1077                 ath5k_debug_printtxbuf(sc, bf);
1078
1079                 ath5k_txbuf_free_skb(sc, bf);
1080
1081                 spin_lock_bh(&sc->txbuflock);
1082                 list_move_tail(&bf->list, &sc->txbuf);
1083                 sc->txbuf_len++;
1084                 txq->txq_len--;
1085                 spin_unlock_bh(&sc->txbuflock);
1086         }
1087         txq->link = NULL;
1088         txq->txq_poll_mark = false;
1089         spin_unlock_bh(&txq->lock);
1090 }
1091
1092 /*
1093  * Drain the transmit queues and reclaim resources.
1094  */
1095 static void
1096 ath5k_txq_cleanup(struct ath5k_softc *sc)
1097 {
1098         struct ath5k_hw *ah = sc->ah;
1099         unsigned int i;
1100
1101         /* XXX return value */
1102         if (likely(!test_bit(ATH_STAT_INVALID, sc->status))) {
1103                 /* don't touch the hardware if marked invalid */
1104                 ath5k_hw_stop_tx_dma(ah, sc->bhalq);
1105                 ATH5K_DBG(sc, ATH5K_DEBUG_RESET, "beacon queue %x\n",
1106                         ath5k_hw_get_txdp(ah, sc->bhalq));
1107                 for (i = 0; i < ARRAY_SIZE(sc->txqs); i++)
1108                         if (sc->txqs[i].setup) {
1109                                 ath5k_hw_stop_tx_dma(ah, sc->txqs[i].qnum);
1110                                 ATH5K_DBG(sc, ATH5K_DEBUG_RESET, "txq [%u] %x, "
1111                                         "link %p\n",
1112                                         sc->txqs[i].qnum,
1113                                         ath5k_hw_get_txdp(ah,
1114                                                         sc->txqs[i].qnum),
1115                                         sc->txqs[i].link);
1116                         }
1117         }
1118
1119         for (i = 0; i < ARRAY_SIZE(sc->txqs); i++)
1120                 if (sc->txqs[i].setup)
1121                         ath5k_txq_drainq(sc, &sc->txqs[i]);
1122 }
1123
1124 static void
1125 ath5k_txq_release(struct ath5k_softc *sc)
1126 {
1127         struct ath5k_txq *txq = sc->txqs;
1128         unsigned int i;
1129
1130         for (i = 0; i < ARRAY_SIZE(sc->txqs); i++, txq++)
1131                 if (txq->setup) {
1132                         ath5k_hw_release_tx_queue(sc->ah, txq->qnum);
1133                         txq->setup = false;
1134                 }
1135 }
1136
1137
1138 /*************\
1139 * RX Handling *
1140 \*************/
1141
1142 /*
1143  * Enable the receive h/w following a reset.
1144  */
1145 static int
1146 ath5k_rx_start(struct ath5k_softc *sc)
1147 {
1148         struct ath5k_hw *ah = sc->ah;
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(sc, ATH5K_DEBUG_RESET, "cachelsz %u rx_bufsize %u\n",
1156                   common->cachelsz, common->rx_bufsize);
1157
1158         spin_lock_bh(&sc->rxbuflock);
1159         sc->rxlink = NULL;
1160         list_for_each_entry(bf, &sc->rxbuf, list) {
1161                 ret = ath5k_rxbuf_setup(sc, bf);
1162                 if (ret != 0) {
1163                         spin_unlock_bh(&sc->rxbuflock);
1164                         goto err;
1165                 }
1166         }
1167         bf = list_first_entry(&sc->rxbuf, struct ath5k_buf, list);
1168         ath5k_hw_set_rxdp(ah, bf->daddr);
1169         spin_unlock_bh(&sc->rxbuflock);
1170
1171         ath5k_hw_start_rx_dma(ah);      /* enable recv descriptors */
1172         ath5k_mode_setup(sc, 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 h/w in preparation for a reset.
1182  */
1183 static void
1184 ath5k_rx_stop(struct ath5k_softc *sc)
1185 {
1186         struct ath5k_hw *ah = sc->ah;
1187
1188         ath5k_hw_stop_rx_pcu(ah);       /* disable PCU */
1189         ath5k_hw_set_rx_filter(ah, 0);  /* clear recv filter */
1190         ath5k_hw_stop_rx_dma(ah);       /* disable DMA engine */
1191
1192         ath5k_debug_printrxbuffs(sc, ah);
1193 }
1194
1195 static unsigned int
1196 ath5k_rx_decrypted(struct ath5k_softc *sc, struct sk_buff *skb,
1197                    struct ath5k_rx_status *rs)
1198 {
1199         struct ath5k_hw *ah = sc->ah;
1200         struct ath_common *common = ath5k_hw_common(ah);
1201         struct ieee80211_hdr *hdr = (void *)skb->data;
1202         unsigned int keyix, hlen;
1203
1204         if (!(rs->rs_status & AR5K_RXERR_DECRYPT) &&
1205                         rs->rs_keyix != AR5K_RXKEYIX_INVALID)
1206                 return RX_FLAG_DECRYPTED;
1207
1208         /* Apparently when a default key is used to decrypt the packet
1209            the hw does not set the index used to decrypt.  In such cases
1210            get the index from the packet. */
1211         hlen = ieee80211_hdrlen(hdr->frame_control);
1212         if (ieee80211_has_protected(hdr->frame_control) &&
1213             !(rs->rs_status & AR5K_RXERR_DECRYPT) &&
1214             skb->len >= hlen + 4) {
1215                 keyix = skb->data[hlen + 3] >> 6;
1216
1217                 if (test_bit(keyix, common->keymap))
1218                         return RX_FLAG_DECRYPTED;
1219         }
1220
1221         return 0;
1222 }
1223
1224
1225 static void
1226 ath5k_check_ibss_tsf(struct ath5k_softc *sc, struct sk_buff *skb,
1227                      struct ieee80211_rx_status *rxs)
1228 {
1229         struct ath_common *common = ath5k_hw_common(sc->ah);
1230         u64 tsf, bc_tstamp;
1231         u32 hw_tu;
1232         struct ieee80211_mgmt *mgmt = (struct ieee80211_mgmt *)skb->data;
1233
1234         if (ieee80211_is_beacon(mgmt->frame_control) &&
1235             le16_to_cpu(mgmt->u.beacon.capab_info) & WLAN_CAPABILITY_IBSS &&
1236             memcmp(mgmt->bssid, common->curbssid, ETH_ALEN) == 0) {
1237                 /*
1238                  * Received an IBSS beacon with the same BSSID. Hardware *must*
1239                  * have updated the local TSF. We have to work around various
1240                  * hardware bugs, though...
1241                  */
1242                 tsf = ath5k_hw_get_tsf64(sc->ah);
1243                 bc_tstamp = le64_to_cpu(mgmt->u.beacon.timestamp);
1244                 hw_tu = TSF_TO_TU(tsf);
1245
1246                 ATH5K_DBG_UNLIMIT(sc, ATH5K_DEBUG_BEACON,
1247                         "beacon %llx mactime %llx (diff %lld) tsf now %llx\n",
1248                         (unsigned long long)bc_tstamp,
1249                         (unsigned long long)rxs->mactime,
1250                         (unsigned long long)(rxs->mactime - bc_tstamp),
1251                         (unsigned long long)tsf);
1252
1253                 /*
1254                  * Sometimes the HW will give us a wrong tstamp in the rx
1255                  * status, causing the timestamp extension to go wrong.
1256                  * (This seems to happen especially with beacon frames bigger
1257                  * than 78 byte (incl. FCS))
1258                  * But we know that the receive timestamp must be later than the
1259                  * timestamp of the beacon since HW must have synced to that.
1260                  *
1261                  * NOTE: here we assume mactime to be after the frame was
1262                  * received, not like mac80211 which defines it at the start.
1263                  */
1264                 if (bc_tstamp > rxs->mactime) {
1265                         ATH5K_DBG_UNLIMIT(sc, ATH5K_DEBUG_BEACON,
1266                                 "fixing mactime from %llx to %llx\n",
1267                                 (unsigned long long)rxs->mactime,
1268                                 (unsigned long long)tsf);
1269                         rxs->mactime = tsf;
1270                 }
1271
1272                 /*
1273                  * Local TSF might have moved higher than our beacon timers,
1274                  * in that case we have to update them to continue sending
1275                  * beacons. This also takes care of synchronizing beacon sending
1276                  * times with other stations.
1277                  */
1278                 if (hw_tu >= sc->nexttbtt)
1279                         ath5k_beacon_update_timers(sc, bc_tstamp);
1280
1281                 /* Check if the beacon timers are still correct, because a TSF
1282                  * update might have created a window between them - for a
1283                  * longer description see the comment of this function: */
1284                 if (!ath5k_hw_check_beacon_timers(sc->ah, sc->bintval)) {
1285                         ath5k_beacon_update_timers(sc, bc_tstamp);
1286                         ATH5K_DBG_UNLIMIT(sc, ATH5K_DEBUG_BEACON,
1287                                 "fixed beacon timers after beacon receive\n");
1288                 }
1289         }
1290 }
1291
1292 static void
1293 ath5k_update_beacon_rssi(struct ath5k_softc *sc, struct sk_buff *skb, int rssi)
1294 {
1295         struct ieee80211_mgmt *mgmt = (struct ieee80211_mgmt *)skb->data;
1296         struct ath5k_hw *ah = sc->ah;
1297         struct ath_common *common = ath5k_hw_common(ah);
1298
1299         /* only beacons from our BSSID */
1300         if (!ieee80211_is_beacon(mgmt->frame_control) ||
1301             memcmp(mgmt->bssid, common->curbssid, ETH_ALEN) != 0)
1302                 return;
1303
1304         ah->ah_beacon_rssi_avg = ath5k_moving_average(ah->ah_beacon_rssi_avg,
1305                                                       rssi);
1306
1307         /* in IBSS mode we should keep RSSI statistics per neighbour */
1308         /* le16_to_cpu(mgmt->u.beacon.capab_info) & WLAN_CAPABILITY_IBSS */
1309 }
1310
1311 /*
1312  * Compute padding position. skb must contain an IEEE 802.11 frame
1313  */
1314 static int ath5k_common_padpos(struct sk_buff *skb)
1315 {
1316         struct ieee80211_hdr * hdr = (struct ieee80211_hdr *)skb->data;
1317         __le16 frame_control = hdr->frame_control;
1318         int padpos = 24;
1319
1320         if (ieee80211_has_a4(frame_control)) {
1321                 padpos += ETH_ALEN;
1322         }
1323         if (ieee80211_is_data_qos(frame_control)) {
1324                 padpos += IEEE80211_QOS_CTL_LEN;
1325         }
1326
1327         return padpos;
1328 }
1329
1330 /*
1331  * This function expects an 802.11 frame and returns the number of
1332  * bytes added, or -1 if we don't have enough header room.
1333  */
1334 static int ath5k_add_padding(struct sk_buff *skb)
1335 {
1336         int padpos = ath5k_common_padpos(skb);
1337         int padsize = padpos & 3;
1338
1339         if (padsize && skb->len>padpos) {
1340
1341                 if (skb_headroom(skb) < padsize)
1342                         return -1;
1343
1344                 skb_push(skb, padsize);
1345                 memmove(skb->data, skb->data+padsize, padpos);
1346                 return padsize;
1347         }
1348
1349         return 0;
1350 }
1351
1352 /*
1353  * The MAC header is padded to have 32-bit boundary if the
1354  * packet payload is non-zero. The general calculation for
1355  * padsize would take into account odd header lengths:
1356  * padsize = 4 - (hdrlen & 3); however, since only
1357  * even-length headers are used, padding can only be 0 or 2
1358  * bytes and we can optimize this a bit.  We must not try to
1359  * remove padding from short control frames that do not have a
1360  * payload.
1361  *
1362  * This function expects an 802.11 frame and returns the number of
1363  * bytes removed.
1364  */
1365 static int ath5k_remove_padding(struct sk_buff *skb)
1366 {
1367         int padpos = ath5k_common_padpos(skb);
1368         int padsize = padpos & 3;
1369
1370         if (padsize && skb->len>=padpos+padsize) {
1371                 memmove(skb->data + padsize, skb->data, padpos);
1372                 skb_pull(skb, padsize);
1373                 return padsize;
1374         }
1375
1376         return 0;
1377 }
1378
1379 static void
1380 ath5k_receive_frame(struct ath5k_softc *sc, struct sk_buff *skb,
1381                     struct ath5k_rx_status *rs)
1382 {
1383         struct ieee80211_rx_status *rxs;
1384
1385         ath5k_remove_padding(skb);
1386
1387         rxs = IEEE80211_SKB_RXCB(skb);
1388
1389         rxs->flag = 0;
1390         if (unlikely(rs->rs_status & AR5K_RXERR_MIC))
1391                 rxs->flag |= RX_FLAG_MMIC_ERROR;
1392
1393         /*
1394          * always extend the mac timestamp, since this information is
1395          * also needed for proper IBSS merging.
1396          *
1397          * XXX: it might be too late to do it here, since rs_tstamp is
1398          * 15bit only. that means TSF extension has to be done within
1399          * 32768usec (about 32ms). it might be necessary to move this to
1400          * the interrupt handler, like it is done in madwifi.
1401          *
1402          * Unfortunately we don't know when the hardware takes the rx
1403          * timestamp (beginning of phy frame, data frame, end of rx?).
1404          * The only thing we know is that it is hardware specific...
1405          * On AR5213 it seems the rx timestamp is at the end of the
1406          * frame, but i'm not sure.
1407          *
1408          * NOTE: mac80211 defines mactime at the beginning of the first
1409          * data symbol. Since we don't have any time references it's
1410          * impossible to comply to that. This affects IBSS merge only
1411          * right now, so it's not too bad...
1412          */
1413         rxs->mactime = ath5k_extend_tsf(sc->ah, rs->rs_tstamp);
1414         rxs->flag |= RX_FLAG_TSFT;
1415
1416         rxs->freq = sc->curchan->center_freq;
1417         rxs->band = sc->curband->band;
1418
1419         rxs->signal = sc->ah->ah_noise_floor + rs->rs_rssi;
1420
1421         rxs->antenna = rs->rs_antenna;
1422
1423         if (rs->rs_antenna > 0 && rs->rs_antenna < 5)
1424                 sc->stats.antenna_rx[rs->rs_antenna]++;
1425         else
1426                 sc->stats.antenna_rx[0]++; /* invalid */
1427
1428         rxs->rate_idx = ath5k_hw_to_driver_rix(sc, rs->rs_rate);
1429         rxs->flag |= ath5k_rx_decrypted(sc, skb, rs);
1430
1431         if (rxs->rate_idx >= 0 && rs->rs_rate ==
1432             sc->curband->bitrates[rxs->rate_idx].hw_value_short)
1433                 rxs->flag |= RX_FLAG_SHORTPRE;
1434
1435         ath5k_debug_dump_skb(sc, skb, "RX  ", 0);
1436
1437         ath5k_update_beacon_rssi(sc, skb, rs->rs_rssi);
1438
1439         /* check beacons in IBSS mode */
1440         if (sc->opmode == NL80211_IFTYPE_ADHOC)
1441                 ath5k_check_ibss_tsf(sc, skb, rxs);
1442
1443         ieee80211_rx(sc->hw, skb);
1444 }
1445
1446 /** ath5k_frame_receive_ok() - Do we want to receive this frame or not?
1447  *
1448  * Check if we want to further process this frame or not. Also update
1449  * statistics. Return true if we want this frame, false if not.
1450  */
1451 static bool
1452 ath5k_receive_frame_ok(struct ath5k_softc *sc, struct ath5k_rx_status *rs)
1453 {
1454         sc->stats.rx_all_count++;
1455         sc->stats.rx_bytes_count += rs->rs_datalen;
1456
1457         if (unlikely(rs->rs_status)) {
1458                 if (rs->rs_status & AR5K_RXERR_CRC)
1459                         sc->stats.rxerr_crc++;
1460                 if (rs->rs_status & AR5K_RXERR_FIFO)
1461                         sc->stats.rxerr_fifo++;
1462                 if (rs->rs_status & AR5K_RXERR_PHY) {
1463                         sc->stats.rxerr_phy++;
1464                         if (rs->rs_phyerr > 0 && rs->rs_phyerr < 32)
1465                                 sc->stats.rxerr_phy_code[rs->rs_phyerr]++;
1466                         return false;
1467                 }
1468                 if (rs->rs_status & AR5K_RXERR_DECRYPT) {
1469                         /*
1470                          * Decrypt error.  If the error occurred
1471                          * because there was no hardware key, then
1472                          * let the frame through so the upper layers
1473                          * can process it.  This is necessary for 5210
1474                          * parts which have no way to setup a ``clear''
1475                          * key cache entry.
1476                          *
1477                          * XXX do key cache faulting
1478                          */
1479                         sc->stats.rxerr_decrypt++;
1480                         if (rs->rs_keyix == AR5K_RXKEYIX_INVALID &&
1481                             !(rs->rs_status & AR5K_RXERR_CRC))
1482                                 return true;
1483                 }
1484                 if (rs->rs_status & AR5K_RXERR_MIC) {
1485                         sc->stats.rxerr_mic++;
1486                         return true;
1487                 }
1488
1489                 /* reject any frames with non-crypto errors */
1490                 if (rs->rs_status & ~(AR5K_RXERR_DECRYPT))
1491                         return false;
1492         }
1493
1494         if (unlikely(rs->rs_more)) {
1495                 sc->stats.rxerr_jumbo++;
1496                 return false;
1497         }
1498         return true;
1499 }
1500
1501 static void
1502 ath5k_tasklet_rx(unsigned long data)
1503 {
1504         struct ath5k_rx_status rs = {};
1505         struct sk_buff *skb, *next_skb;
1506         dma_addr_t next_skb_addr;
1507         struct ath5k_softc *sc = (void *)data;
1508         struct ath5k_hw *ah = sc->ah;
1509         struct ath_common *common = ath5k_hw_common(ah);
1510         struct ath5k_buf *bf;
1511         struct ath5k_desc *ds;
1512         int ret;
1513
1514         spin_lock(&sc->rxbuflock);
1515         if (list_empty(&sc->rxbuf)) {
1516                 ATH5K_WARN(sc, "empty rx buf pool\n");
1517                 goto unlock;
1518         }
1519         do {
1520                 bf = list_first_entry(&sc->rxbuf, struct ath5k_buf, list);
1521                 BUG_ON(bf->skb == NULL);
1522                 skb = bf->skb;
1523                 ds = bf->desc;
1524
1525                 /* bail if HW is still using self-linked descriptor */
1526                 if (ath5k_hw_get_rxdp(sc->ah) == bf->daddr)
1527                         break;
1528
1529                 ret = sc->ah->ah_proc_rx_desc(sc->ah, ds, &rs);
1530                 if (unlikely(ret == -EINPROGRESS))
1531                         break;
1532                 else if (unlikely(ret)) {
1533                         ATH5K_ERR(sc, "error in processing rx descriptor\n");
1534                         sc->stats.rxerr_proc++;
1535                         break;
1536                 }
1537
1538                 if (ath5k_receive_frame_ok(sc, &rs)) {
1539                         next_skb = ath5k_rx_skb_alloc(sc, &next_skb_addr);
1540
1541                         /*
1542                          * If we can't replace bf->skb with a new skb under
1543                          * memory pressure, just skip this packet
1544                          */
1545                         if (!next_skb)
1546                                 goto next;
1547
1548                         pci_unmap_single(sc->pdev, bf->skbaddr,
1549                                          common->rx_bufsize,
1550                                          PCI_DMA_FROMDEVICE);
1551
1552                         skb_put(skb, rs.rs_datalen);
1553
1554                         ath5k_receive_frame(sc, skb, &rs);
1555
1556                         bf->skb = next_skb;
1557                         bf->skbaddr = next_skb_addr;
1558                 }
1559 next:
1560                 list_move_tail(&bf->list, &sc->rxbuf);
1561         } while (ath5k_rxbuf_setup(sc, bf) == 0);
1562 unlock:
1563         spin_unlock(&sc->rxbuflock);
1564 }
1565
1566
1567 /*************\
1568 * TX Handling *
1569 \*************/
1570
1571 static int ath5k_tx_queue(struct ieee80211_hw *hw, struct sk_buff *skb,
1572                           struct ath5k_txq *txq)
1573 {
1574         struct ath5k_softc *sc = hw->priv;
1575         struct ath5k_buf *bf;
1576         unsigned long flags;
1577         int padsize;
1578
1579         ath5k_debug_dump_skb(sc, skb, "TX  ", 1);
1580
1581         /*
1582          * The hardware expects the header padded to 4 byte boundaries.
1583          * If this is not the case, we add the padding after the header.
1584          */
1585         padsize = ath5k_add_padding(skb);
1586         if (padsize < 0) {
1587                 ATH5K_ERR(sc, "tx hdrlen not %%4: not enough"
1588                           " headroom to pad");
1589                 goto drop_packet;
1590         }
1591
1592         if (txq->txq_len >= ATH5K_TXQ_LEN_MAX)
1593                 ieee80211_stop_queue(hw, txq->qnum);
1594
1595         spin_lock_irqsave(&sc->txbuflock, flags);
1596         if (list_empty(&sc->txbuf)) {
1597                 ATH5K_ERR(sc, "no further txbuf available, dropping packet\n");
1598                 spin_unlock_irqrestore(&sc->txbuflock, flags);
1599                 ieee80211_stop_queues(hw);
1600                 goto drop_packet;
1601         }
1602         bf = list_first_entry(&sc->txbuf, struct ath5k_buf, list);
1603         list_del(&bf->list);
1604         sc->txbuf_len--;
1605         if (list_empty(&sc->txbuf))
1606                 ieee80211_stop_queues(hw);
1607         spin_unlock_irqrestore(&sc->txbuflock, flags);
1608
1609         bf->skb = skb;
1610
1611         if (ath5k_txbuf_setup(sc, bf, txq, padsize)) {
1612                 bf->skb = NULL;
1613                 spin_lock_irqsave(&sc->txbuflock, flags);
1614                 list_add_tail(&bf->list, &sc->txbuf);
1615                 sc->txbuf_len++;
1616                 spin_unlock_irqrestore(&sc->txbuflock, flags);
1617                 goto drop_packet;
1618         }
1619         return NETDEV_TX_OK;
1620
1621 drop_packet:
1622         dev_kfree_skb_any(skb);
1623         return NETDEV_TX_OK;
1624 }
1625
1626 static void
1627 ath5k_tx_frame_completed(struct ath5k_softc *sc, struct sk_buff *skb,
1628                          struct ath5k_tx_status *ts)
1629 {
1630         struct ieee80211_tx_info *info;
1631         int i;
1632
1633         sc->stats.tx_all_count++;
1634         sc->stats.tx_bytes_count += skb->len;
1635         info = IEEE80211_SKB_CB(skb);
1636
1637         ieee80211_tx_info_clear_status(info);
1638         for (i = 0; i < 4; i++) {
1639                 struct ieee80211_tx_rate *r =
1640                         &info->status.rates[i];
1641
1642                 if (ts->ts_rate[i]) {
1643                         r->idx = ath5k_hw_to_driver_rix(sc, ts->ts_rate[i]);
1644                         r->count = ts->ts_retry[i];
1645                 } else {
1646                         r->idx = -1;
1647                         r->count = 0;
1648                 }
1649         }
1650
1651         /* count the successful attempt as well */
1652         info->status.rates[ts->ts_final_idx].count++;
1653
1654         if (unlikely(ts->ts_status)) {
1655                 sc->stats.ack_fail++;
1656                 if (ts->ts_status & AR5K_TXERR_FILT) {
1657                         info->flags |= IEEE80211_TX_STAT_TX_FILTERED;
1658                         sc->stats.txerr_filt++;
1659                 }
1660                 if (ts->ts_status & AR5K_TXERR_XRETRY)
1661                         sc->stats.txerr_retry++;
1662                 if (ts->ts_status & AR5K_TXERR_FIFO)
1663                         sc->stats.txerr_fifo++;
1664         } else {
1665                 info->flags |= IEEE80211_TX_STAT_ACK;
1666                 info->status.ack_signal = ts->ts_rssi;
1667         }
1668
1669         /*
1670         * Remove MAC header padding before giving the frame
1671         * back to mac80211.
1672         */
1673         ath5k_remove_padding(skb);
1674
1675         if (ts->ts_antenna > 0 && ts->ts_antenna < 5)
1676                 sc->stats.antenna_tx[ts->ts_antenna]++;
1677         else
1678                 sc->stats.antenna_tx[0]++; /* invalid */
1679
1680         ieee80211_tx_status(sc->hw, skb);
1681 }
1682
1683 static void
1684 ath5k_tx_processq(struct ath5k_softc *sc, struct ath5k_txq *txq)
1685 {
1686         struct ath5k_tx_status ts = {};
1687         struct ath5k_buf *bf, *bf0;
1688         struct ath5k_desc *ds;
1689         struct sk_buff *skb;
1690         int ret;
1691
1692         spin_lock(&txq->lock);
1693         list_for_each_entry_safe(bf, bf0, &txq->q, list) {
1694
1695                 txq->txq_poll_mark = false;
1696
1697                 /* skb might already have been processed last time. */
1698                 if (bf->skb != NULL) {
1699                         ds = bf->desc;
1700
1701                         ret = sc->ah->ah_proc_tx_desc(sc->ah, ds, &ts);
1702                         if (unlikely(ret == -EINPROGRESS))
1703                                 break;
1704                         else if (unlikely(ret)) {
1705                                 ATH5K_ERR(sc,
1706                                         "error %d while processing "
1707                                         "queue %u\n", ret, txq->qnum);
1708                                 break;
1709                         }
1710
1711                         skb = bf->skb;
1712                         bf->skb = NULL;
1713                         pci_unmap_single(sc->pdev, bf->skbaddr, skb->len,
1714                                         PCI_DMA_TODEVICE);
1715                         ath5k_tx_frame_completed(sc, skb, &ts);
1716                 }
1717
1718                 /*
1719                  * It's possible that the hardware can say the buffer is
1720                  * completed when it hasn't yet loaded the ds_link from
1721                  * host memory and moved on.
1722                  * Always keep the last descriptor to avoid HW races...
1723                  */
1724                 if (ath5k_hw_get_txdp(sc->ah, txq->qnum) != bf->daddr) {
1725                         spin_lock(&sc->txbuflock);
1726                         list_move_tail(&bf->list, &sc->txbuf);
1727                         sc->txbuf_len++;
1728                         txq->txq_len--;
1729                         spin_unlock(&sc->txbuflock);
1730                 }
1731         }
1732         spin_unlock(&txq->lock);
1733         if (txq->txq_len < ATH5K_TXQ_LEN_LOW && txq->qnum < 4)
1734                 ieee80211_wake_queue(sc->hw, txq->qnum);
1735 }
1736
1737 static void
1738 ath5k_tasklet_tx(unsigned long data)
1739 {
1740         int i;
1741         struct ath5k_softc *sc = (void *)data;
1742
1743         for (i=0; i < AR5K_NUM_TX_QUEUES; i++)
1744                 if (sc->txqs[i].setup && (sc->ah->ah_txq_isr & BIT(i)))
1745                         ath5k_tx_processq(sc, &sc->txqs[i]);
1746 }
1747
1748
1749 /*****************\
1750 * Beacon handling *
1751 \*****************/
1752
1753 /*
1754  * Setup the beacon frame for transmit.
1755  */
1756 static int
1757 ath5k_beacon_setup(struct ath5k_softc *sc, struct ath5k_buf *bf)
1758 {
1759         struct sk_buff *skb = bf->skb;
1760         struct  ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
1761         struct ath5k_hw *ah = sc->ah;
1762         struct ath5k_desc *ds;
1763         int ret = 0;
1764         u8 antenna;
1765         u32 flags;
1766         const int padsize = 0;
1767
1768         bf->skbaddr = pci_map_single(sc->pdev, skb->data, skb->len,
1769                         PCI_DMA_TODEVICE);
1770         ATH5K_DBG(sc, ATH5K_DEBUG_BEACON, "skb %p [data %p len %u] "
1771                         "skbaddr %llx\n", skb, skb->data, skb->len,
1772                         (unsigned long long)bf->skbaddr);
1773         if (pci_dma_mapping_error(sc->pdev, bf->skbaddr)) {
1774                 ATH5K_ERR(sc, "beacon DMA mapping failed\n");
1775                 return -EIO;
1776         }
1777
1778         ds = bf->desc;
1779         antenna = ah->ah_tx_ant;
1780
1781         flags = AR5K_TXDESC_NOACK;
1782         if (sc->opmode == NL80211_IFTYPE_ADHOC && ath5k_hw_hasveol(ah)) {
1783                 ds->ds_link = bf->daddr;        /* self-linked */
1784                 flags |= AR5K_TXDESC_VEOL;
1785         } else
1786                 ds->ds_link = 0;
1787
1788         /*
1789          * If we use multiple antennas on AP and use
1790          * the Sectored AP scenario, switch antenna every
1791          * 4 beacons to make sure everybody hears our AP.
1792          * When a client tries to associate, hw will keep
1793          * track of the tx antenna to be used for this client
1794          * automaticaly, based on ACKed packets.
1795          *
1796          * Note: AP still listens and transmits RTS on the
1797          * default antenna which is supposed to be an omni.
1798          *
1799          * Note2: On sectored scenarios it's possible to have
1800          * multiple antennas (1 omni -- the default -- and 14
1801          * sectors), so if we choose to actually support this
1802          * mode, we need to allow the user to set how many antennas
1803          * we have and tweak the code below to send beacons
1804          * on all of them.
1805          */
1806         if (ah->ah_ant_mode == AR5K_ANTMODE_SECTOR_AP)
1807                 antenna = sc->bsent & 4 ? 2 : 1;
1808
1809
1810         /* FIXME: If we are in g mode and rate is a CCK rate
1811          * subtract ah->ah_txpower.txp_cck_ofdm_pwr_delta
1812          * from tx power (value is in dB units already) */
1813         ds->ds_data = bf->skbaddr;
1814         ret = ah->ah_setup_tx_desc(ah, ds, skb->len,
1815                         ieee80211_get_hdrlen_from_skb(skb), padsize,
1816                         AR5K_PKT_TYPE_BEACON, (sc->power_level * 2),
1817                         ieee80211_get_tx_rate(sc->hw, info)->hw_value,
1818                         1, AR5K_TXKEYIX_INVALID,
1819                         antenna, flags, 0, 0);
1820         if (ret)
1821                 goto err_unmap;
1822
1823         return 0;
1824 err_unmap:
1825         pci_unmap_single(sc->pdev, bf->skbaddr, skb->len, PCI_DMA_TODEVICE);
1826         return ret;
1827 }
1828
1829 /*
1830  * Updates the beacon that is sent by ath5k_beacon_send.  For adhoc,
1831  * this is called only once at config_bss time, for AP we do it every
1832  * SWBA interrupt so that the TIM will reflect buffered frames.
1833  *
1834  * Called with the beacon lock.
1835  */
1836 static int
1837 ath5k_beacon_update(struct ieee80211_hw *hw, struct ieee80211_vif *vif)
1838 {
1839         int ret;
1840         struct ath5k_softc *sc = hw->priv;
1841         struct ath5k_vif *avf = (void *)vif->drv_priv;
1842         struct sk_buff *skb;
1843
1844         if (WARN_ON(!vif)) {
1845                 ret = -EINVAL;
1846                 goto out;
1847         }
1848
1849         skb = ieee80211_beacon_get(hw, vif);
1850
1851         if (!skb) {
1852                 ret = -ENOMEM;
1853                 goto out;
1854         }
1855
1856         ath5k_debug_dump_skb(sc, skb, "BC  ", 1);
1857
1858         ath5k_txbuf_free_skb(sc, avf->bbuf);
1859         avf->bbuf->skb = skb;
1860         ret = ath5k_beacon_setup(sc, avf->bbuf);
1861         if (ret)
1862                 avf->bbuf->skb = NULL;
1863 out:
1864         return ret;
1865 }
1866
1867 /*
1868  * Transmit a beacon frame at SWBA.  Dynamic updates to the
1869  * frame contents are done as needed and the slot time is
1870  * also adjusted based on current state.
1871  *
1872  * This is called from software irq context (beacontq tasklets)
1873  * or user context from ath5k_beacon_config.
1874  */
1875 static void
1876 ath5k_beacon_send(struct ath5k_softc *sc)
1877 {
1878         struct ath5k_hw *ah = sc->ah;
1879         struct ieee80211_vif *vif;
1880         struct ath5k_vif *avf;
1881         struct ath5k_buf *bf;
1882         struct sk_buff *skb;
1883
1884         ATH5K_DBG_UNLIMIT(sc, ATH5K_DEBUG_BEACON, "in beacon_send\n");
1885
1886         /*
1887          * Check if the previous beacon has gone out.  If
1888          * not, don't don't try to post another: skip this
1889          * period and wait for the next.  Missed beacons
1890          * indicate a problem and should not occur.  If we
1891          * miss too many consecutive beacons reset the device.
1892          */
1893         if (unlikely(ath5k_hw_num_tx_pending(ah, sc->bhalq) != 0)) {
1894                 sc->bmisscount++;
1895                 ATH5K_DBG(sc, ATH5K_DEBUG_BEACON,
1896                         "missed %u consecutive beacons\n", sc->bmisscount);
1897                 if (sc->bmisscount > 10) {      /* NB: 10 is a guess */
1898                         ATH5K_DBG(sc, ATH5K_DEBUG_BEACON,
1899                                 "stuck beacon time (%u missed)\n",
1900                                 sc->bmisscount);
1901                         ATH5K_DBG(sc, ATH5K_DEBUG_RESET,
1902                                   "stuck beacon, resetting\n");
1903                         ieee80211_queue_work(sc->hw, &sc->reset_work);
1904                 }
1905                 return;
1906         }
1907         if (unlikely(sc->bmisscount != 0)) {
1908                 ATH5K_DBG(sc, ATH5K_DEBUG_BEACON,
1909                         "resume beacon xmit after %u misses\n",
1910                         sc->bmisscount);
1911                 sc->bmisscount = 0;
1912         }
1913
1914         if (sc->opmode == NL80211_IFTYPE_AP && sc->num_ap_vifs > 1) {
1915                 u64 tsf = ath5k_hw_get_tsf64(ah);
1916                 u32 tsftu = TSF_TO_TU(tsf);
1917                 int slot = ((tsftu % sc->bintval) * ATH_BCBUF) / sc->bintval;
1918                 vif = sc->bslot[(slot + 1) % ATH_BCBUF];
1919                 ATH5K_DBG(sc, ATH5K_DEBUG_BEACON,
1920                         "tsf %llx tsftu %x intval %u slot %u vif %p\n",
1921                         (unsigned long long)tsf, tsftu, sc->bintval, slot, vif);
1922         } else /* only one interface */
1923                 vif = sc->bslot[0];
1924
1925         if (!vif)
1926                 return;
1927
1928         avf = (void *)vif->drv_priv;
1929         bf = avf->bbuf;
1930         if (unlikely(bf->skb == NULL || sc->opmode == NL80211_IFTYPE_STATION ||
1931                         sc->opmode == NL80211_IFTYPE_MONITOR)) {
1932                 ATH5K_WARN(sc, "bf=%p bf_skb=%p\n", bf, bf ? bf->skb : NULL);
1933                 return;
1934         }
1935
1936         /*
1937          * Stop any current dma and put the new frame on the queue.
1938          * This should never fail since we check above that no frames
1939          * are still pending on the queue.
1940          */
1941         if (unlikely(ath5k_hw_stop_tx_dma(ah, sc->bhalq))) {
1942                 ATH5K_WARN(sc, "beacon queue %u didn't start/stop ?\n", sc->bhalq);
1943                 /* NB: hw still stops DMA, so proceed */
1944         }
1945
1946         /* refresh the beacon for AP mode */
1947         if (sc->opmode == NL80211_IFTYPE_AP)
1948                 ath5k_beacon_update(sc->hw, vif);
1949
1950         ath5k_hw_set_txdp(ah, sc->bhalq, bf->daddr);
1951         ath5k_hw_start_tx_dma(ah, sc->bhalq);
1952         ATH5K_DBG(sc, ATH5K_DEBUG_BEACON, "TXDP[%u] = %llx (%p)\n",
1953                 sc->bhalq, (unsigned long long)bf->daddr, bf->desc);
1954
1955         skb = ieee80211_get_buffered_bc(sc->hw, vif);
1956         while (skb) {
1957                 ath5k_tx_queue(sc->hw, skb, sc->cabq);
1958                 skb = ieee80211_get_buffered_bc(sc->hw, vif);
1959         }
1960
1961         sc->bsent++;
1962 }
1963
1964 /**
1965  * ath5k_beacon_update_timers - update beacon timers
1966  *
1967  * @sc: struct ath5k_softc pointer we are operating on
1968  * @bc_tsf: the timestamp of the beacon. 0 to reset the TSF. -1 to perform a
1969  *          beacon timer update based on the current HW TSF.
1970  *
1971  * Calculate the next target beacon transmit time (TBTT) based on the timestamp
1972  * of a received beacon or the current local hardware TSF and write it to the
1973  * beacon timer registers.
1974  *
1975  * This is called in a variety of situations, e.g. when a beacon is received,
1976  * when a TSF update has been detected, but also when an new IBSS is created or
1977  * when we otherwise know we have to update the timers, but we keep it in this
1978  * function to have it all together in one place.
1979  */
1980 static void
1981 ath5k_beacon_update_timers(struct ath5k_softc *sc, u64 bc_tsf)
1982 {
1983         struct ath5k_hw *ah = sc->ah;
1984         u32 nexttbtt, intval, hw_tu, bc_tu;
1985         u64 hw_tsf;
1986
1987         intval = sc->bintval & AR5K_BEACON_PERIOD;
1988         if (sc->opmode == NL80211_IFTYPE_AP && sc->num_ap_vifs > 1) {
1989                 intval /= ATH_BCBUF;    /* staggered multi-bss beacons */
1990                 if (intval < 15)
1991                         ATH5K_WARN(sc, "intval %u is too low, min 15\n",
1992                                    intval);
1993         }
1994         if (WARN_ON(!intval))
1995                 return;
1996
1997         /* beacon TSF converted to TU */
1998         bc_tu = TSF_TO_TU(bc_tsf);
1999
2000         /* current TSF converted to TU */
2001         hw_tsf = ath5k_hw_get_tsf64(ah);
2002         hw_tu = TSF_TO_TU(hw_tsf);
2003
2004 #define FUDGE AR5K_TUNE_SW_BEACON_RESP + 3
2005         /* We use FUDGE to make sure the next TBTT is ahead of the current TU.
2006          * Since we later substract AR5K_TUNE_SW_BEACON_RESP (10) in the timer
2007          * configuration we need to make sure it is bigger than that. */
2008
2009         if (bc_tsf == -1) {
2010                 /*
2011                  * no beacons received, called internally.
2012                  * just need to refresh timers based on HW TSF.
2013                  */
2014                 nexttbtt = roundup(hw_tu + FUDGE, intval);
2015         } else if (bc_tsf == 0) {
2016                 /*
2017                  * no beacon received, probably called by ath5k_reset_tsf().
2018                  * reset TSF to start with 0.
2019                  */
2020                 nexttbtt = intval;
2021                 intval |= AR5K_BEACON_RESET_TSF;
2022         } else if (bc_tsf > hw_tsf) {
2023                 /*
2024                  * beacon received, SW merge happend but HW TSF not yet updated.
2025                  * not possible to reconfigure timers yet, but next time we
2026                  * receive a beacon with the same BSSID, the hardware will
2027                  * automatically update the TSF and then we need to reconfigure
2028                  * the timers.
2029                  */
2030                 ATH5K_DBG_UNLIMIT(sc, ATH5K_DEBUG_BEACON,
2031                         "need to wait for HW TSF sync\n");
2032                 return;
2033         } else {
2034                 /*
2035                  * most important case for beacon synchronization between STA.
2036                  *
2037                  * beacon received and HW TSF has been already updated by HW.
2038                  * update next TBTT based on the TSF of the beacon, but make
2039                  * sure it is ahead of our local TSF timer.
2040                  */
2041                 nexttbtt = bc_tu + roundup(hw_tu + FUDGE - bc_tu, intval);
2042         }
2043 #undef FUDGE
2044
2045         sc->nexttbtt = nexttbtt;
2046
2047         intval |= AR5K_BEACON_ENA;
2048         ath5k_hw_init_beacon(ah, nexttbtt, intval);
2049
2050         /*
2051          * debugging output last in order to preserve the time critical aspect
2052          * of this function
2053          */
2054         if (bc_tsf == -1)
2055                 ATH5K_DBG_UNLIMIT(sc, ATH5K_DEBUG_BEACON,
2056                         "reconfigured timers based on HW TSF\n");
2057         else if (bc_tsf == 0)
2058                 ATH5K_DBG_UNLIMIT(sc, ATH5K_DEBUG_BEACON,
2059                         "reset HW TSF and timers\n");
2060         else
2061                 ATH5K_DBG_UNLIMIT(sc, ATH5K_DEBUG_BEACON,
2062                         "updated timers based on beacon TSF\n");
2063
2064         ATH5K_DBG_UNLIMIT(sc, ATH5K_DEBUG_BEACON,
2065                           "bc_tsf %llx hw_tsf %llx bc_tu %u hw_tu %u nexttbtt %u\n",
2066                           (unsigned long long) bc_tsf,
2067                           (unsigned long long) hw_tsf, bc_tu, hw_tu, nexttbtt);
2068         ATH5K_DBG_UNLIMIT(sc, ATH5K_DEBUG_BEACON, "intval %u %s %s\n",
2069                 intval & AR5K_BEACON_PERIOD,
2070                 intval & AR5K_BEACON_ENA ? "AR5K_BEACON_ENA" : "",
2071                 intval & AR5K_BEACON_RESET_TSF ? "AR5K_BEACON_RESET_TSF" : "");
2072 }
2073
2074 /**
2075  * ath5k_beacon_config - Configure the beacon queues and interrupts
2076  *
2077  * @sc: struct ath5k_softc pointer we are operating on
2078  *
2079  * In IBSS mode we use a self-linked tx descriptor if possible. We enable SWBA
2080  * interrupts to detect TSF updates only.
2081  */
2082 static void
2083 ath5k_beacon_config(struct ath5k_softc *sc)
2084 {
2085         struct ath5k_hw *ah = sc->ah;
2086         unsigned long flags;
2087
2088         spin_lock_irqsave(&sc->block, flags);
2089         sc->bmisscount = 0;
2090         sc->imask &= ~(AR5K_INT_BMISS | AR5K_INT_SWBA);
2091
2092         if (sc->enable_beacon) {
2093                 /*
2094                  * In IBSS mode we use a self-linked tx descriptor and let the
2095                  * hardware send the beacons automatically. We have to load it
2096                  * only once here.
2097                  * We use the SWBA interrupt only to keep track of the beacon
2098                  * timers in order to detect automatic TSF updates.
2099                  */
2100                 ath5k_beaconq_config(sc);
2101
2102                 sc->imask |= AR5K_INT_SWBA;
2103
2104                 if (sc->opmode == NL80211_IFTYPE_ADHOC) {
2105                         if (ath5k_hw_hasveol(ah))
2106                                 ath5k_beacon_send(sc);
2107                 } else
2108                         ath5k_beacon_update_timers(sc, -1);
2109         } else {
2110                 ath5k_hw_stop_tx_dma(sc->ah, sc->bhalq);
2111         }
2112
2113         ath5k_hw_set_imr(ah, sc->imask);
2114         mmiowb();
2115         spin_unlock_irqrestore(&sc->block, flags);
2116 }
2117
2118 static void ath5k_tasklet_beacon(unsigned long data)
2119 {
2120         struct ath5k_softc *sc = (struct ath5k_softc *) data;
2121
2122         /*
2123          * Software beacon alert--time to send a beacon.
2124          *
2125          * In IBSS mode we use this interrupt just to
2126          * keep track of the next TBTT (target beacon
2127          * transmission time) in order to detect wether
2128          * automatic TSF updates happened.
2129          */
2130         if (sc->opmode == NL80211_IFTYPE_ADHOC) {
2131                 /* XXX: only if VEOL suppported */
2132                 u64 tsf = ath5k_hw_get_tsf64(sc->ah);
2133                 sc->nexttbtt += sc->bintval;
2134                 ATH5K_DBG(sc, ATH5K_DEBUG_BEACON,
2135                                 "SWBA nexttbtt: %x hw_tu: %x "
2136                                 "TSF: %llx\n",
2137                                 sc->nexttbtt,
2138                                 TSF_TO_TU(tsf),
2139                                 (unsigned long long) tsf);
2140         } else {
2141                 spin_lock(&sc->block);
2142                 ath5k_beacon_send(sc);
2143                 spin_unlock(&sc->block);
2144         }
2145 }
2146
2147
2148 /********************\
2149 * Interrupt handling *
2150 \********************/
2151
2152 static void
2153 ath5k_intr_calibration_poll(struct ath5k_hw *ah)
2154 {
2155         if (time_is_before_eq_jiffies(ah->ah_cal_next_ani) &&
2156             !(ah->ah_cal_mask & AR5K_CALIBRATION_FULL)) {
2157                 /* run ANI only when full calibration is not active */
2158                 ah->ah_cal_next_ani = jiffies +
2159                         msecs_to_jiffies(ATH5K_TUNE_CALIBRATION_INTERVAL_ANI);
2160                 tasklet_schedule(&ah->ah_sc->ani_tasklet);
2161
2162         } else if (time_is_before_eq_jiffies(ah->ah_cal_next_full)) {
2163                 ah->ah_cal_next_full = jiffies +
2164                         msecs_to_jiffies(ATH5K_TUNE_CALIBRATION_INTERVAL_FULL);
2165                 tasklet_schedule(&ah->ah_sc->calib);
2166         }
2167         /* we could use SWI to generate enough interrupts to meet our
2168          * calibration interval requirements, if necessary:
2169          * AR5K_REG_ENABLE_BITS(ah, AR5K_CR, AR5K_CR_SWI); */
2170 }
2171
2172 static irqreturn_t
2173 ath5k_intr(int irq, void *dev_id)
2174 {
2175         struct ath5k_softc *sc = dev_id;
2176         struct ath5k_hw *ah = sc->ah;
2177         enum ath5k_int status;
2178         unsigned int counter = 1000;
2179
2180         if (unlikely(test_bit(ATH_STAT_INVALID, sc->status) ||
2181                                 !ath5k_hw_is_intr_pending(ah)))
2182                 return IRQ_NONE;
2183
2184         do {
2185                 ath5k_hw_get_isr(ah, &status);          /* NB: clears IRQ too */
2186                 ATH5K_DBG(sc, ATH5K_DEBUG_INTR, "status 0x%x/0x%x\n",
2187                                 status, sc->imask);
2188                 if (unlikely(status & AR5K_INT_FATAL)) {
2189                         /*
2190                          * Fatal errors are unrecoverable.
2191                          * Typically these are caused by DMA errors.
2192                          */
2193                         ATH5K_DBG(sc, ATH5K_DEBUG_RESET,
2194                                   "fatal int, resetting\n");
2195                         ieee80211_queue_work(sc->hw, &sc->reset_work);
2196                 } else if (unlikely(status & AR5K_INT_RXORN)) {
2197                         /*
2198                          * Receive buffers are full. Either the bus is busy or
2199                          * the CPU is not fast enough to process all received
2200                          * frames.
2201                          * Older chipsets need a reset to come out of this
2202                          * condition, but we treat it as RX for newer chips.
2203                          * We don't know exactly which versions need a reset -
2204                          * this guess is copied from the HAL.
2205                          */
2206                         sc->stats.rxorn_intr++;
2207                         if (ah->ah_mac_srev < AR5K_SREV_AR5212) {
2208                                 ATH5K_DBG(sc, ATH5K_DEBUG_RESET,
2209                                           "rx overrun, resetting\n");
2210                                 ieee80211_queue_work(sc->hw, &sc->reset_work);
2211                         }
2212                         else
2213                                 tasklet_schedule(&sc->rxtq);
2214                 } else {
2215                         if (status & AR5K_INT_SWBA) {
2216                                 tasklet_hi_schedule(&sc->beacontq);
2217                         }
2218                         if (status & AR5K_INT_RXEOL) {
2219                                 /*
2220                                 * NB: the hardware should re-read the link when
2221                                 *     RXE bit is written, but it doesn't work at
2222                                 *     least on older hardware revs.
2223                                 */
2224                                 sc->stats.rxeol_intr++;
2225                         }
2226                         if (status & AR5K_INT_TXURN) {
2227                                 /* bump tx trigger level */
2228                                 ath5k_hw_update_tx_triglevel(ah, true);
2229                         }
2230                         if (status & (AR5K_INT_RXOK | AR5K_INT_RXERR))
2231                                 tasklet_schedule(&sc->rxtq);
2232                         if (status & (AR5K_INT_TXOK | AR5K_INT_TXDESC
2233                                         | AR5K_INT_TXERR | AR5K_INT_TXEOL))
2234                                 tasklet_schedule(&sc->txtq);
2235                         if (status & AR5K_INT_BMISS) {
2236                                 /* TODO */
2237                         }
2238                         if (status & AR5K_INT_MIB) {
2239                                 sc->stats.mib_intr++;
2240                                 ath5k_hw_update_mib_counters(ah);
2241                                 ath5k_ani_mib_intr(ah);
2242                         }
2243                         if (status & AR5K_INT_GPIO)
2244                                 tasklet_schedule(&sc->rf_kill.toggleq);
2245
2246                 }
2247         } while (ath5k_hw_is_intr_pending(ah) && --counter > 0);
2248
2249         if (unlikely(!counter))
2250                 ATH5K_WARN(sc, "too many interrupts, giving up for now\n");
2251
2252         ath5k_intr_calibration_poll(ah);
2253
2254         return IRQ_HANDLED;
2255 }
2256
2257 /*
2258  * Periodically recalibrate the PHY to account
2259  * for temperature/environment changes.
2260  */
2261 static void
2262 ath5k_tasklet_calibrate(unsigned long data)
2263 {
2264         struct ath5k_softc *sc = (void *)data;
2265         struct ath5k_hw *ah = sc->ah;
2266
2267         /* Only full calibration for now */
2268         ah->ah_cal_mask |= AR5K_CALIBRATION_FULL;
2269
2270         ATH5K_DBG(sc, ATH5K_DEBUG_CALIBRATE, "channel %u/%x\n",
2271                 ieee80211_frequency_to_channel(sc->curchan->center_freq),
2272                 sc->curchan->hw_value);
2273
2274         if (ath5k_hw_gainf_calibrate(ah) == AR5K_RFGAIN_NEED_CHANGE) {
2275                 /*
2276                  * Rfgain is out of bounds, reset the chip
2277                  * to load new gain values.
2278                  */
2279                 ATH5K_DBG(sc, ATH5K_DEBUG_RESET, "calibration, resetting\n");
2280                 ieee80211_queue_work(sc->hw, &sc->reset_work);
2281         }
2282         if (ath5k_hw_phy_calibrate(ah, sc->curchan))
2283                 ATH5K_ERR(sc, "calibration of channel %u failed\n",
2284                         ieee80211_frequency_to_channel(
2285                                 sc->curchan->center_freq));
2286
2287         /* Noise floor calibration interrupts rx/tx path while I/Q calibration
2288          * doesn't.
2289          * TODO: We should stop TX here, so that it doesn't interfere.
2290          * Note that stopping the queues is not enough to stop TX! */
2291         if (time_is_before_eq_jiffies(ah->ah_cal_next_nf)) {
2292                 ah->ah_cal_next_nf = jiffies +
2293                         msecs_to_jiffies(ATH5K_TUNE_CALIBRATION_INTERVAL_NF);
2294                 ath5k_hw_update_noise_floor(ah);
2295         }
2296
2297         ah->ah_cal_mask &= ~AR5K_CALIBRATION_FULL;
2298 }
2299
2300
2301 static void
2302 ath5k_tasklet_ani(unsigned long data)
2303 {
2304         struct ath5k_softc *sc = (void *)data;
2305         struct ath5k_hw *ah = sc->ah;
2306
2307         ah->ah_cal_mask |= AR5K_CALIBRATION_ANI;
2308         ath5k_ani_calibration(ah);
2309         ah->ah_cal_mask &= ~AR5K_CALIBRATION_ANI;
2310 }
2311
2312
2313 static void
2314 ath5k_tx_complete_poll_work(struct work_struct *work)
2315 {
2316         struct ath5k_softc *sc = container_of(work, struct ath5k_softc,
2317                         tx_complete_work.work);
2318         struct ath5k_txq *txq;
2319         int i;
2320         bool needreset = false;
2321
2322         for (i = 0; i < ARRAY_SIZE(sc->txqs); i++) {
2323                 if (sc->txqs[i].setup) {
2324                         txq = &sc->txqs[i];
2325                         spin_lock_bh(&txq->lock);
2326                         if (txq->txq_len > 1) {
2327                                 if (txq->txq_poll_mark) {
2328                                         ATH5K_DBG(sc, ATH5K_DEBUG_XMIT,
2329                                                   "TX queue stuck %d\n",
2330                                                   txq->qnum);
2331                                         needreset = true;
2332                                         txq->txq_stuck++;
2333                                         spin_unlock_bh(&txq->lock);
2334                                         break;
2335                                 } else {
2336                                         txq->txq_poll_mark = true;
2337                                 }
2338                         }
2339                         spin_unlock_bh(&txq->lock);
2340                 }
2341         }
2342
2343         if (needreset) {
2344                 ATH5K_DBG(sc, ATH5K_DEBUG_RESET,
2345                           "TX queues stuck, resetting\n");
2346                 ath5k_reset(sc, sc->curchan);
2347         }
2348
2349         ieee80211_queue_delayed_work(sc->hw, &sc->tx_complete_work,
2350                 msecs_to_jiffies(ATH5K_TX_COMPLETE_POLL_INT));
2351 }
2352
2353
2354 /*************************\
2355 * Initialization routines *
2356 \*************************/
2357
2358 static int
2359 ath5k_stop_locked(struct ath5k_softc *sc)
2360 {
2361         struct ath5k_hw *ah = sc->ah;
2362
2363         ATH5K_DBG(sc, ATH5K_DEBUG_RESET, "invalid %u\n",
2364                         test_bit(ATH_STAT_INVALID, sc->status));
2365
2366         /*
2367          * Shutdown the hardware and driver:
2368          *    stop output from above
2369          *    disable interrupts
2370          *    turn off timers
2371          *    turn off the radio
2372          *    clear transmit machinery
2373          *    clear receive machinery
2374          *    drain and release tx queues
2375          *    reclaim beacon resources
2376          *    power down hardware
2377          *
2378          * Note that some of this work is not possible if the
2379          * hardware is gone (invalid).
2380          */
2381         ieee80211_stop_queues(sc->hw);
2382
2383         if (!test_bit(ATH_STAT_INVALID, sc->status)) {
2384                 ath5k_led_off(sc);
2385                 ath5k_hw_set_imr(ah, 0);
2386                 synchronize_irq(sc->pdev->irq);
2387         }
2388         ath5k_txq_cleanup(sc);
2389         if (!test_bit(ATH_STAT_INVALID, sc->status)) {
2390                 ath5k_rx_stop(sc);
2391                 ath5k_hw_phy_disable(ah);
2392         }
2393
2394         return 0;
2395 }
2396
2397 static int
2398 ath5k_init(struct ath5k_softc *sc)
2399 {
2400         struct ath5k_hw *ah = sc->ah;
2401         struct ath_common *common = ath5k_hw_common(ah);
2402         int ret, i;
2403
2404         mutex_lock(&sc->lock);
2405
2406         ATH5K_DBG(sc, ATH5K_DEBUG_RESET, "mode %d\n", sc->opmode);
2407
2408         /*
2409          * Stop anything previously setup.  This is safe
2410          * no matter this is the first time through or not.
2411          */
2412         ath5k_stop_locked(sc);
2413
2414         /*
2415          * The basic interface to setting the hardware in a good
2416          * state is ``reset''.  On return the hardware is known to
2417          * be powered up and with interrupts disabled.  This must
2418          * be followed by initialization of the appropriate bits
2419          * and then setup of the interrupt mask.
2420          */
2421         sc->curchan = sc->hw->conf.channel;
2422         sc->curband = &sc->sbands[sc->curchan->band];
2423         sc->imask = AR5K_INT_RXOK | AR5K_INT_RXERR | AR5K_INT_RXEOL |
2424                 AR5K_INT_RXORN | AR5K_INT_TXDESC | AR5K_INT_TXEOL |
2425                 AR5K_INT_FATAL | AR5K_INT_GLOBAL | AR5K_INT_MIB;
2426
2427         ret = ath5k_reset(sc, NULL);
2428         if (ret)
2429                 goto done;
2430
2431         ath5k_rfkill_hw_start(ah);
2432
2433         /*
2434          * Reset the key cache since some parts do not reset the
2435          * contents on initial power up or resume from suspend.
2436          */
2437         for (i = 0; i < common->keymax; i++)
2438                 ath_hw_keyreset(common, (u16) i);
2439
2440         ath5k_hw_set_ack_bitrate_high(ah, true);
2441
2442         for (i = 0; i < ARRAY_SIZE(sc->bslot); i++)
2443                 sc->bslot[i] = NULL;
2444
2445         ret = 0;
2446 done:
2447         mmiowb();
2448         mutex_unlock(&sc->lock);
2449
2450         ieee80211_queue_delayed_work(sc->hw, &sc->tx_complete_work,
2451                         msecs_to_jiffies(ATH5K_TX_COMPLETE_POLL_INT));
2452
2453         return ret;
2454 }
2455
2456 static void stop_tasklets(struct ath5k_softc *sc)
2457 {
2458         tasklet_kill(&sc->rxtq);
2459         tasklet_kill(&sc->txtq);
2460         tasklet_kill(&sc->calib);
2461         tasklet_kill(&sc->beacontq);
2462         tasklet_kill(&sc->ani_tasklet);
2463 }
2464
2465 /*
2466  * Stop the device, grabbing the top-level lock to protect
2467  * against concurrent entry through ath5k_init (which can happen
2468  * if another thread does a system call and the thread doing the
2469  * stop is preempted).
2470  */
2471 static int
2472 ath5k_stop_hw(struct ath5k_softc *sc)
2473 {
2474         int ret;
2475
2476         mutex_lock(&sc->lock);
2477         ret = ath5k_stop_locked(sc);
2478         if (ret == 0 && !test_bit(ATH_STAT_INVALID, sc->status)) {
2479                 /*
2480                  * Don't set the card in full sleep mode!
2481                  *
2482                  * a) When the device is in this state it must be carefully
2483                  * woken up or references to registers in the PCI clock
2484                  * domain may freeze the bus (and system).  This varies
2485                  * by chip and is mostly an issue with newer parts
2486                  * (madwifi sources mentioned srev >= 0x78) that go to
2487                  * sleep more quickly.
2488                  *
2489                  * b) On older chips full sleep results a weird behaviour
2490                  * during wakeup. I tested various cards with srev < 0x78
2491                  * and they don't wake up after module reload, a second
2492                  * module reload is needed to bring the card up again.
2493                  *
2494                  * Until we figure out what's going on don't enable
2495                  * full chip reset on any chip (this is what Legacy HAL
2496                  * and Sam's HAL do anyway). Instead Perform a full reset
2497                  * on the device (same as initial state after attach) and
2498                  * leave it idle (keep MAC/BB on warm reset) */
2499                 ret = ath5k_hw_on_hold(sc->ah);
2500
2501                 ATH5K_DBG(sc, ATH5K_DEBUG_RESET,
2502                                 "putting device to sleep\n");
2503         }
2504
2505         mmiowb();
2506         mutex_unlock(&sc->lock);
2507
2508         stop_tasklets(sc);
2509
2510         cancel_delayed_work_sync(&sc->tx_complete_work);
2511
2512         ath5k_rfkill_hw_stop(sc->ah);
2513
2514         return ret;
2515 }
2516
2517 /*
2518  * Reset the hardware.  If chan is not NULL, then also pause rx/tx
2519  * and change to the given channel.
2520  *
2521  * This should be called with sc->lock.
2522  */
2523 static int
2524 ath5k_reset(struct ath5k_softc *sc, struct ieee80211_channel *chan)
2525 {
2526         struct ath5k_hw *ah = sc->ah;
2527         int ret;
2528
2529         ATH5K_DBG(sc, ATH5K_DEBUG_RESET, "resetting\n");
2530
2531         ath5k_hw_set_imr(ah, 0);
2532         synchronize_irq(sc->pdev->irq);
2533         stop_tasklets(sc);
2534
2535         if (chan) {
2536                 ath5k_txq_cleanup(sc);
2537                 ath5k_rx_stop(sc);
2538
2539                 sc->curchan = chan;
2540                 sc->curband = &sc->sbands[chan->band];
2541         }
2542         ret = ath5k_hw_reset(ah, sc->opmode, sc->curchan, chan != NULL);
2543         if (ret) {
2544                 ATH5K_ERR(sc, "can't reset hardware (%d)\n", ret);
2545                 goto err;
2546         }
2547
2548         ret = ath5k_rx_start(sc);
2549         if (ret) {
2550                 ATH5K_ERR(sc, "can't start recv logic\n");
2551                 goto err;
2552         }
2553
2554         ath5k_ani_init(ah, ah->ah_sc->ani_state.ani_mode);
2555
2556         ah->ah_cal_next_full = jiffies;
2557         ah->ah_cal_next_ani = jiffies;
2558         ah->ah_cal_next_nf = jiffies;
2559
2560         /*
2561          * Change channels and update the h/w rate map if we're switching;
2562          * e.g. 11a to 11b/g.
2563          *
2564          * We may be doing a reset in response to an ioctl that changes the
2565          * channel so update any state that might change as a result.
2566          *
2567          * XXX needed?
2568          */
2569 /*      ath5k_chan_change(sc, c); */
2570
2571         ath5k_beacon_config(sc);
2572         /* intrs are enabled by ath5k_beacon_config */
2573
2574         ieee80211_wake_queues(sc->hw);
2575
2576         return 0;
2577 err:
2578         return ret;
2579 }
2580
2581 static void ath5k_reset_work(struct work_struct *work)
2582 {
2583         struct ath5k_softc *sc = container_of(work, struct ath5k_softc,
2584                 reset_work);
2585
2586         mutex_lock(&sc->lock);
2587         ath5k_reset(sc, sc->curchan);
2588         mutex_unlock(&sc->lock);
2589 }
2590
2591 static int
2592 ath5k_attach(struct pci_dev *pdev, struct ieee80211_hw *hw)
2593 {
2594         struct ath5k_softc *sc = hw->priv;
2595         struct ath5k_hw *ah = sc->ah;
2596         struct ath_regulatory *regulatory = ath5k_hw_regulatory(ah);
2597         struct ath5k_txq *txq;
2598         u8 mac[ETH_ALEN] = {};
2599         int ret;
2600
2601         ATH5K_DBG(sc, ATH5K_DEBUG_ANY, "devid 0x%x\n", pdev->device);
2602
2603         /*
2604          * Check if the MAC has multi-rate retry support.
2605          * We do this by trying to setup a fake extended
2606          * descriptor.  MACs that don't have support will
2607          * return false w/o doing anything.  MACs that do
2608          * support it will return true w/o doing anything.
2609          */
2610         ret = ath5k_hw_setup_mrr_tx_desc(ah, NULL, 0, 0, 0, 0, 0, 0);
2611
2612         if (ret < 0)
2613                 goto err;
2614         if (ret > 0)
2615                 __set_bit(ATH_STAT_MRRETRY, sc->status);
2616
2617         /*
2618          * Collect the channel list.  The 802.11 layer
2619          * is resposible for filtering this list based
2620          * on settings like the phy mode and regulatory
2621          * domain restrictions.
2622          */
2623         ret = ath5k_setup_bands(hw);
2624         if (ret) {
2625                 ATH5K_ERR(sc, "can't get channels\n");
2626                 goto err;
2627         }
2628
2629         /* NB: setup here so ath5k_rate_update is happy */
2630         if (test_bit(AR5K_MODE_11A, ah->ah_modes))
2631                 ath5k_setcurmode(sc, AR5K_MODE_11A);
2632         else
2633                 ath5k_setcurmode(sc, AR5K_MODE_11B);
2634
2635         /*
2636          * Allocate tx+rx descriptors and populate the lists.
2637          */
2638         ret = ath5k_desc_alloc(sc, pdev);
2639         if (ret) {
2640                 ATH5K_ERR(sc, "can't allocate descriptors\n");
2641                 goto err;
2642         }
2643
2644         /*
2645          * Allocate hardware transmit queues: one queue for
2646          * beacon frames and one data queue for each QoS
2647          * priority.  Note that hw functions handle resetting
2648          * these queues at the needed time.
2649          */
2650         ret = ath5k_beaconq_setup(ah);
2651         if (ret < 0) {
2652                 ATH5K_ERR(sc, "can't setup a beacon xmit queue\n");
2653                 goto err_desc;
2654         }
2655         sc->bhalq = ret;
2656         sc->cabq = ath5k_txq_setup(sc, AR5K_TX_QUEUE_CAB, 0);
2657         if (IS_ERR(sc->cabq)) {
2658                 ATH5K_ERR(sc, "can't setup cab queue\n");
2659                 ret = PTR_ERR(sc->cabq);
2660                 goto err_bhal;
2661         }
2662
2663         /* This order matches mac80211's queue priority, so we can
2664          * directly use the mac80211 queue number without any mapping */
2665         txq = ath5k_txq_setup(sc, AR5K_TX_QUEUE_DATA, AR5K_WME_AC_VO);
2666         if (IS_ERR(txq)) {
2667                 ATH5K_ERR(sc, "can't setup xmit queue\n");
2668                 ret = PTR_ERR(txq);
2669                 goto err_queues;
2670         }
2671         txq = ath5k_txq_setup(sc, AR5K_TX_QUEUE_DATA, AR5K_WME_AC_VI);
2672         if (IS_ERR(txq)) {
2673                 ATH5K_ERR(sc, "can't setup xmit queue\n");
2674                 ret = PTR_ERR(txq);
2675                 goto err_queues;
2676         }
2677         txq = ath5k_txq_setup(sc, AR5K_TX_QUEUE_DATA, AR5K_WME_AC_BE);
2678         if (IS_ERR(txq)) {
2679                 ATH5K_ERR(sc, "can't setup xmit queue\n");
2680                 ret = PTR_ERR(txq);
2681                 goto err_queues;
2682         }
2683         txq = ath5k_txq_setup(sc, AR5K_TX_QUEUE_DATA, AR5K_WME_AC_BK);
2684         if (IS_ERR(txq)) {
2685                 ATH5K_ERR(sc, "can't setup xmit queue\n");
2686                 ret = PTR_ERR(txq);
2687                 goto err_queues;
2688         }
2689         hw->queues = 4;
2690
2691         tasklet_init(&sc->rxtq, ath5k_tasklet_rx, (unsigned long)sc);
2692         tasklet_init(&sc->txtq, ath5k_tasklet_tx, (unsigned long)sc);
2693         tasklet_init(&sc->calib, ath5k_tasklet_calibrate, (unsigned long)sc);
2694         tasklet_init(&sc->beacontq, ath5k_tasklet_beacon, (unsigned long)sc);
2695         tasklet_init(&sc->ani_tasklet, ath5k_tasklet_ani, (unsigned long)sc);
2696
2697         INIT_WORK(&sc->reset_work, ath5k_reset_work);
2698         INIT_DELAYED_WORK(&sc->tx_complete_work, ath5k_tx_complete_poll_work);
2699
2700         ret = ath5k_eeprom_read_mac(ah, mac);
2701         if (ret) {
2702                 ATH5K_ERR(sc, "unable to read address from EEPROM: 0x%04x\n",
2703                         sc->pdev->device);
2704                 goto err_queues;
2705         }
2706
2707         SET_IEEE80211_PERM_ADDR(hw, mac);
2708         memcpy(&sc->lladdr, mac, ETH_ALEN);
2709         /* All MAC address bits matter for ACKs */
2710         ath5k_update_bssid_mask_and_opmode(sc, NULL);
2711
2712         regulatory->current_rd = ah->ah_capabilities.cap_eeprom.ee_regdomain;
2713         ret = ath_regd_init(regulatory, hw->wiphy, ath5k_reg_notifier);
2714         if (ret) {
2715                 ATH5K_ERR(sc, "can't initialize regulatory system\n");
2716                 goto err_queues;
2717         }
2718
2719         ret = ieee80211_register_hw(hw);
2720         if (ret) {
2721                 ATH5K_ERR(sc, "can't register ieee80211 hw\n");
2722                 goto err_queues;
2723         }
2724
2725         if (!ath_is_world_regd(regulatory))
2726                 regulatory_hint(hw->wiphy, regulatory->alpha2);
2727
2728         ath5k_init_leds(sc);
2729
2730         ath5k_sysfs_register(sc);
2731
2732         return 0;
2733 err_queues:
2734         ath5k_txq_release(sc);
2735 err_bhal:
2736         ath5k_hw_release_tx_queue(ah, sc->bhalq);
2737 err_desc:
2738         ath5k_desc_free(sc, pdev);
2739 err:
2740         return ret;
2741 }
2742
2743 static void
2744 ath5k_detach(struct pci_dev *pdev, struct ieee80211_hw *hw)
2745 {
2746         struct ath5k_softc *sc = hw->priv;
2747
2748         /*
2749          * NB: the order of these is important:
2750          * o call the 802.11 layer before detaching ath5k_hw to
2751          *   ensure callbacks into the driver to delete global
2752          *   key cache entries can be handled
2753          * o reclaim the tx queue data structures after calling
2754          *   the 802.11 layer as we'll get called back to reclaim
2755          *   node state and potentially want to use them
2756          * o to cleanup the tx queues the hal is called, so detach
2757          *   it last
2758          * XXX: ??? detach ath5k_hw ???
2759          * Other than that, it's straightforward...
2760          */
2761         ieee80211_unregister_hw(hw);
2762         ath5k_desc_free(sc, pdev);
2763         ath5k_txq_release(sc);
2764         ath5k_hw_release_tx_queue(sc->ah, sc->bhalq);
2765         ath5k_unregister_leds(sc);
2766
2767         ath5k_sysfs_unregister(sc);
2768         /*
2769          * NB: can't reclaim these until after ieee80211_ifdetach
2770          * returns because we'll get called back to reclaim node
2771          * state and potentially want to use them.
2772          */
2773 }
2774
2775 /********************\
2776 * Mac80211 functions *
2777 \********************/
2778
2779 static int
2780 ath5k_tx(struct ieee80211_hw *hw, struct sk_buff *skb)
2781 {
2782         struct ath5k_softc *sc = hw->priv;
2783         u16 qnum = skb_get_queue_mapping(skb);
2784
2785         if (WARN_ON(qnum >= sc->ah->ah_capabilities.cap_queues.q_tx_num)) {
2786                 dev_kfree_skb_any(skb);
2787                 return 0;
2788         }
2789
2790         return ath5k_tx_queue(hw, skb, &sc->txqs[qnum]);
2791 }
2792
2793 static int ath5k_start(struct ieee80211_hw *hw)
2794 {
2795         return ath5k_init(hw->priv);
2796 }
2797
2798 static void ath5k_stop(struct ieee80211_hw *hw)
2799 {
2800         ath5k_stop_hw(hw->priv);
2801 }
2802
2803 static int ath5k_add_interface(struct ieee80211_hw *hw,
2804                 struct ieee80211_vif *vif)
2805 {
2806         struct ath5k_softc *sc = hw->priv;
2807         int ret;
2808         struct ath5k_vif *avf = (void *)vif->drv_priv;
2809
2810         mutex_lock(&sc->lock);
2811
2812         if ((vif->type == NL80211_IFTYPE_AP ||
2813              vif->type == NL80211_IFTYPE_ADHOC)
2814             && (sc->num_ap_vifs + sc->num_adhoc_vifs) >= ATH_BCBUF) {
2815                 ret = -ELNRNG;
2816                 goto end;
2817         }
2818
2819         /* Don't allow other interfaces if one ad-hoc is configured.
2820          * TODO: Fix the problems with ad-hoc and multiple other interfaces.
2821          * We would need to operate the HW in ad-hoc mode to allow TSF updates
2822          * for the IBSS, but this breaks with additional AP or STA interfaces
2823          * at the moment. */
2824         if (sc->num_adhoc_vifs ||
2825             (sc->nvifs && vif->type == NL80211_IFTYPE_ADHOC)) {
2826                 ATH5K_ERR(sc, "Only one single ad-hoc interface is allowed.\n");
2827                 ret = -ELNRNG;
2828                 goto end;
2829         }
2830
2831         switch (vif->type) {
2832         case NL80211_IFTYPE_AP:
2833         case NL80211_IFTYPE_STATION:
2834         case NL80211_IFTYPE_ADHOC:
2835         case NL80211_IFTYPE_MESH_POINT:
2836                 avf->opmode = vif->type;
2837                 break;
2838         default:
2839                 ret = -EOPNOTSUPP;
2840                 goto end;
2841         }
2842
2843         sc->nvifs++;
2844         ATH5K_DBG(sc, ATH5K_DEBUG_MODE, "add interface mode %d\n", avf->opmode);
2845
2846         /* Assign the vap/adhoc to a beacon xmit slot. */
2847         if ((avf->opmode == NL80211_IFTYPE_AP) ||
2848             (avf->opmode == NL80211_IFTYPE_ADHOC)) {
2849                 int slot;
2850
2851                 WARN_ON(list_empty(&sc->bcbuf));
2852                 avf->bbuf = list_first_entry(&sc->bcbuf, struct ath5k_buf,
2853                                              list);
2854                 list_del(&avf->bbuf->list);
2855
2856                 avf->bslot = 0;
2857                 for (slot = 0; slot < ATH_BCBUF; slot++) {
2858                         if (!sc->bslot[slot]) {
2859                                 avf->bslot = slot;
2860                                 break;
2861                         }
2862                 }
2863                 BUG_ON(sc->bslot[avf->bslot] != NULL);
2864                 sc->bslot[avf->bslot] = vif;
2865                 if (avf->opmode == NL80211_IFTYPE_AP)
2866                         sc->num_ap_vifs++;
2867                 else
2868                         sc->num_adhoc_vifs++;
2869         }
2870
2871         /* Any MAC address is fine, all others are included through the
2872          * filter.
2873          */
2874         memcpy(&sc->lladdr, vif->addr, ETH_ALEN);
2875         ath5k_hw_set_lladdr(sc->ah, vif->addr);
2876
2877         memcpy(&avf->lladdr, vif->addr, ETH_ALEN);
2878
2879         ath5k_mode_setup(sc, vif);
2880
2881         ret = 0;
2882 end:
2883         mutex_unlock(&sc->lock);
2884         return ret;
2885 }
2886
2887 static void
2888 ath5k_remove_interface(struct ieee80211_hw *hw,
2889                         struct ieee80211_vif *vif)
2890 {
2891         struct ath5k_softc *sc = hw->priv;
2892         struct ath5k_vif *avf = (void *)vif->drv_priv;
2893         unsigned int i;
2894
2895         mutex_lock(&sc->lock);
2896         sc->nvifs--;
2897
2898         if (avf->bbuf) {
2899                 ath5k_txbuf_free_skb(sc, avf->bbuf);
2900                 list_add_tail(&avf->bbuf->list, &sc->bcbuf);
2901                 for (i = 0; i < ATH_BCBUF; i++) {
2902                         if (sc->bslot[i] == vif) {
2903                                 sc->bslot[i] = NULL;
2904                                 break;
2905                         }
2906                 }
2907                 avf->bbuf = NULL;
2908         }
2909         if (avf->opmode == NL80211_IFTYPE_AP)
2910                 sc->num_ap_vifs--;
2911         else if (avf->opmode == NL80211_IFTYPE_ADHOC)
2912                 sc->num_adhoc_vifs--;
2913
2914         ath5k_update_bssid_mask_and_opmode(sc, NULL);
2915         mutex_unlock(&sc->lock);
2916 }
2917
2918 /*
2919  * TODO: Phy disable/diversity etc
2920  */
2921 static int
2922 ath5k_config(struct ieee80211_hw *hw, u32 changed)
2923 {
2924         struct ath5k_softc *sc = hw->priv;
2925         struct ath5k_hw *ah = sc->ah;
2926         struct ieee80211_conf *conf = &hw->conf;
2927         int ret = 0;
2928
2929         mutex_lock(&sc->lock);
2930
2931         if (changed & IEEE80211_CONF_CHANGE_CHANNEL) {
2932                 ret = ath5k_chan_set(sc, conf->channel);
2933                 if (ret < 0)
2934                         goto unlock;
2935         }
2936
2937         if ((changed & IEEE80211_CONF_CHANGE_POWER) &&
2938         (sc->power_level != conf->power_level)) {
2939                 sc->power_level = conf->power_level;
2940
2941                 /* Half dB steps */
2942                 ath5k_hw_set_txpower_limit(ah, (conf->power_level * 2));
2943         }
2944
2945         /* TODO:
2946          * 1) Move this on config_interface and handle each case
2947          * separately eg. when we have only one STA vif, use
2948          * AR5K_ANTMODE_SINGLE_AP
2949          *
2950          * 2) Allow the user to change antenna mode eg. when only
2951          * one antenna is present
2952          *
2953          * 3) Allow the user to set default/tx antenna when possible
2954          *
2955          * 4) Default mode should handle 90% of the cases, together
2956          * with fixed a/b and single AP modes we should be able to
2957          * handle 99%. Sectored modes are extreme cases and i still
2958          * haven't found a usage for them. If we decide to support them,
2959          * then we must allow the user to set how many tx antennas we
2960          * have available
2961          */
2962         ath5k_hw_set_antenna_mode(ah, ah->ah_ant_mode);
2963
2964 unlock:
2965         mutex_unlock(&sc->lock);
2966         return ret;
2967 }
2968
2969 static u64 ath5k_prepare_multicast(struct ieee80211_hw *hw,
2970                                    struct netdev_hw_addr_list *mc_list)
2971 {
2972         u32 mfilt[2], val;
2973         u8 pos;
2974         struct netdev_hw_addr *ha;
2975
2976         mfilt[0] = 0;
2977         mfilt[1] = 1;
2978
2979         netdev_hw_addr_list_for_each(ha, mc_list) {
2980                 /* calculate XOR of eight 6-bit values */
2981                 val = get_unaligned_le32(ha->addr + 0);
2982                 pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2983                 val = get_unaligned_le32(ha->addr + 3);
2984                 pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2985                 pos &= 0x3f;
2986                 mfilt[pos / 32] |= (1 << (pos % 32));
2987                 /* XXX: we might be able to just do this instead,
2988                 * but not sure, needs testing, if we do use this we'd
2989                 * neet to inform below to not reset the mcast */
2990                 /* ath5k_hw_set_mcast_filterindex(ah,
2991                  *      ha->addr[5]); */
2992         }
2993
2994         return ((u64)(mfilt[1]) << 32) | mfilt[0];
2995 }
2996
2997 static bool ath_any_vif_assoc(struct ath5k_softc *sc)
2998 {
2999         struct ath_vif_iter_data iter_data;
3000         iter_data.hw_macaddr = NULL;
3001         iter_data.any_assoc = false;
3002         iter_data.need_set_hw_addr = false;
3003         iter_data.found_active = true;
3004
3005         ieee80211_iterate_active_interfaces_atomic(sc->hw, ath_vif_iter,
3006                                                    &iter_data);
3007         return iter_data.any_assoc;
3008 }
3009
3010 #define SUPPORTED_FIF_FLAGS \
3011         FIF_PROMISC_IN_BSS |  FIF_ALLMULTI | FIF_FCSFAIL | \
3012         FIF_PLCPFAIL | FIF_CONTROL | FIF_OTHER_BSS | \
3013         FIF_BCN_PRBRESP_PROMISC
3014 /*
3015  * o always accept unicast, broadcast, and multicast traffic
3016  * o multicast traffic for all BSSIDs will be enabled if mac80211
3017  *   says it should be
3018  * o maintain current state of phy ofdm or phy cck error reception.
3019  *   If the hardware detects any of these type of errors then
3020  *   ath5k_hw_get_rx_filter() will pass to us the respective
3021  *   hardware filters to be able to receive these type of frames.
3022  * o probe request frames are accepted only when operating in
3023  *   hostap, adhoc, or monitor modes
3024  * o enable promiscuous mode according to the interface state
3025  * o accept beacons:
3026  *   - when operating in adhoc mode so the 802.11 layer creates
3027  *     node table entries for peers,
3028  *   - when operating in station mode for collecting rssi data when
3029  *     the station is otherwise quiet, or
3030  *   - when scanning
3031  */
3032 static void ath5k_configure_filter(struct ieee80211_hw *hw,
3033                 unsigned int changed_flags,
3034                 unsigned int *new_flags,
3035                 u64 multicast)
3036 {
3037         struct ath5k_softc *sc = hw->priv;
3038         struct ath5k_hw *ah = sc->ah;
3039         u32 mfilt[2], rfilt;
3040
3041         mutex_lock(&sc->lock);
3042
3043         mfilt[0] = multicast;
3044         mfilt[1] = multicast >> 32;
3045
3046         /* Only deal with supported flags */
3047         changed_flags &= SUPPORTED_FIF_FLAGS;
3048         *new_flags &= SUPPORTED_FIF_FLAGS;
3049
3050         /* If HW detects any phy or radar errors, leave those filters on.
3051          * Also, always enable Unicast, Broadcasts and Multicast
3052          * XXX: move unicast, bssid broadcasts and multicast to mac80211 */
3053         rfilt = (ath5k_hw_get_rx_filter(ah) & (AR5K_RX_FILTER_PHYERR)) |
3054                 (AR5K_RX_FILTER_UCAST | AR5K_RX_FILTER_BCAST |
3055                 AR5K_RX_FILTER_MCAST);
3056
3057         if (changed_flags & (FIF_PROMISC_IN_BSS | FIF_OTHER_BSS)) {
3058                 if (*new_flags & FIF_PROMISC_IN_BSS) {
3059                         __set_bit(ATH_STAT_PROMISC, sc->status);
3060                 } else {
3061                         __clear_bit(ATH_STAT_PROMISC, sc->status);
3062                 }
3063         }
3064
3065         if (test_bit(ATH_STAT_PROMISC, sc->status))
3066                 rfilt |= AR5K_RX_FILTER_PROM;
3067
3068         /* Note, AR5K_RX_FILTER_MCAST is already enabled */
3069         if (*new_flags & FIF_ALLMULTI) {
3070                 mfilt[0] =  ~0;
3071                 mfilt[1] =  ~0;
3072         }
3073
3074         /* This is the best we can do */
3075         if (*new_flags & (FIF_FCSFAIL | FIF_PLCPFAIL))
3076                 rfilt |= AR5K_RX_FILTER_PHYERR;
3077
3078         /* FIF_BCN_PRBRESP_PROMISC really means to enable beacons
3079         * and probes for any BSSID */
3080         if ((*new_flags & FIF_BCN_PRBRESP_PROMISC) || (sc->nvifs > 1))
3081                 rfilt |= AR5K_RX_FILTER_BEACON;
3082
3083         /* FIF_CONTROL doc says that if FIF_PROMISC_IN_BSS is not
3084          * set we should only pass on control frames for this
3085          * station. This needs testing. I believe right now this
3086          * enables *all* control frames, which is OK.. but
3087          * but we should see if we can improve on granularity */
3088         if (*new_flags & FIF_CONTROL)
3089                 rfilt |= AR5K_RX_FILTER_CONTROL;
3090
3091         /* Additional settings per mode -- this is per ath5k */
3092
3093         /* XXX move these to mac80211, and add a beacon IFF flag to mac80211 */
3094
3095         switch (sc->opmode) {
3096         case NL80211_IFTYPE_MESH_POINT:
3097                 rfilt |= AR5K_RX_FILTER_CONTROL |
3098                          AR5K_RX_FILTER_BEACON |
3099                          AR5K_RX_FILTER_PROBEREQ |
3100                          AR5K_RX_FILTER_PROM;
3101                 break;
3102         case NL80211_IFTYPE_AP:
3103         case NL80211_IFTYPE_ADHOC:
3104                 rfilt |= AR5K_RX_FILTER_PROBEREQ |
3105                          AR5K_RX_FILTER_BEACON;
3106                 break;
3107         case NL80211_IFTYPE_STATION:
3108                 if (sc->assoc)
3109                         rfilt |= AR5K_RX_FILTER_BEACON;
3110         default:
3111                 break;
3112         }
3113
3114         /* Set filters */
3115         ath5k_hw_set_rx_filter(ah, rfilt);
3116
3117         /* Set multicast bits */
3118         ath5k_hw_set_mcast_filter(ah, mfilt[0], mfilt[1]);
3119         /* Set the cached hw filter flags, this will later actually
3120          * be set in HW */
3121         sc->filter_flags = rfilt;
3122
3123         mutex_unlock(&sc->lock);
3124 }
3125
3126 static int
3127 ath5k_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd,
3128               struct ieee80211_vif *vif, struct ieee80211_sta *sta,
3129               struct ieee80211_key_conf *key)
3130 {
3131         struct ath5k_softc *sc = hw->priv;
3132         struct ath5k_hw *ah = sc->ah;
3133         struct ath_common *common = ath5k_hw_common(ah);
3134         int ret = 0;
3135
3136         if (modparam_nohwcrypt)
3137                 return -EOPNOTSUPP;
3138
3139         switch (key->cipher) {
3140         case WLAN_CIPHER_SUITE_WEP40:
3141         case WLAN_CIPHER_SUITE_WEP104:
3142         case WLAN_CIPHER_SUITE_TKIP:
3143                 break;
3144         case WLAN_CIPHER_SUITE_CCMP:
3145                 if (common->crypt_caps & ATH_CRYPT_CAP_CIPHER_AESCCM)
3146                         break;
3147                 return -EOPNOTSUPP;
3148         default:
3149                 WARN_ON(1);
3150                 return -EINVAL;
3151         }
3152
3153         mutex_lock(&sc->lock);
3154
3155         switch (cmd) {
3156         case SET_KEY:
3157                 ret = ath_key_config(common, vif, sta, key);
3158                 if (ret >= 0) {
3159                         key->hw_key_idx = ret;
3160                         /* push IV and Michael MIC generation to stack */
3161                         key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
3162                         if (key->cipher == WLAN_CIPHER_SUITE_TKIP)
3163                                 key->flags |= IEEE80211_KEY_FLAG_GENERATE_MMIC;
3164                         if (key->cipher == WLAN_CIPHER_SUITE_CCMP)
3165                                 key->flags |= IEEE80211_KEY_FLAG_SW_MGMT;
3166                         ret = 0;
3167                 }
3168                 break;
3169         case DISABLE_KEY:
3170                 ath_key_delete(common, key);
3171                 break;
3172         default:
3173                 ret = -EINVAL;
3174         }
3175
3176         mmiowb();
3177         mutex_unlock(&sc->lock);
3178         return ret;
3179 }
3180
3181 static int
3182 ath5k_get_stats(struct ieee80211_hw *hw,
3183                 struct ieee80211_low_level_stats *stats)
3184 {
3185         struct ath5k_softc *sc = hw->priv;
3186
3187         /* Force update */
3188         ath5k_hw_update_mib_counters(sc->ah);
3189
3190         stats->dot11ACKFailureCount = sc->stats.ack_fail;
3191         stats->dot11RTSFailureCount = sc->stats.rts_fail;
3192         stats->dot11RTSSuccessCount = sc->stats.rts_ok;
3193         stats->dot11FCSErrorCount = sc->stats.fcs_error;
3194
3195         return 0;
3196 }
3197
3198 static int ath5k_get_survey(struct ieee80211_hw *hw, int idx,
3199                 struct survey_info *survey)
3200 {
3201         struct ath5k_softc *sc = hw->priv;
3202         struct ieee80211_conf *conf = &hw->conf;
3203         struct ath_common *common = ath5k_hw_common(sc->ah);
3204         struct ath_cycle_counters *cc = &common->cc_survey;
3205         unsigned int div = common->clockrate * 1000;
3206
3207         if (idx != 0)
3208                 return -ENOENT;
3209
3210         survey->channel = conf->channel;
3211         survey->filled = SURVEY_INFO_NOISE_DBM;
3212         survey->noise = sc->ah->ah_noise_floor;
3213
3214         spin_lock_bh(&common->cc_lock);
3215         ath_hw_cycle_counters_update(common);
3216         if (cc->cycles > 0) {
3217                 survey->filled |= SURVEY_INFO_CHANNEL_TIME |
3218                         SURVEY_INFO_CHANNEL_TIME_BUSY |
3219                         SURVEY_INFO_CHANNEL_TIME_RX |
3220                         SURVEY_INFO_CHANNEL_TIME_TX;
3221                 survey->channel_time += cc->cycles / div;
3222                 survey->channel_time_busy += cc->rx_busy / div;
3223                 survey->channel_time_rx += cc->rx_frame / div;
3224                 survey->channel_time_tx += cc->tx_frame / div;
3225         }
3226         memset(cc, 0, sizeof(*cc));
3227         spin_unlock_bh(&common->cc_lock);
3228
3229         return 0;
3230 }
3231
3232 static u64
3233 ath5k_get_tsf(struct ieee80211_hw *hw)
3234 {
3235         struct ath5k_softc *sc = hw->priv;
3236
3237         return ath5k_hw_get_tsf64(sc->ah);
3238 }
3239
3240 static void
3241 ath5k_set_tsf(struct ieee80211_hw *hw, u64 tsf)
3242 {
3243         struct ath5k_softc *sc = hw->priv;
3244
3245         ath5k_hw_set_tsf64(sc->ah, tsf);
3246 }
3247
3248 static void
3249 ath5k_reset_tsf(struct ieee80211_hw *hw)
3250 {
3251         struct ath5k_softc *sc = hw->priv;
3252
3253         /*
3254          * in IBSS mode we need to update the beacon timers too.
3255          * this will also reset the TSF if we call it with 0
3256          */
3257         if (sc->opmode == NL80211_IFTYPE_ADHOC)
3258                 ath5k_beacon_update_timers(sc, 0);
3259         else
3260                 ath5k_hw_reset_tsf(sc->ah);
3261 }
3262
3263 static void
3264 set_beacon_filter(struct ieee80211_hw *hw, bool enable)
3265 {
3266         struct ath5k_softc *sc = hw->priv;
3267         struct ath5k_hw *ah = sc->ah;
3268         u32 rfilt;
3269         rfilt = ath5k_hw_get_rx_filter(ah);
3270         if (enable)
3271                 rfilt |= AR5K_RX_FILTER_BEACON;
3272         else
3273                 rfilt &= ~AR5K_RX_FILTER_BEACON;
3274         ath5k_hw_set_rx_filter(ah, rfilt);
3275         sc->filter_flags = rfilt;
3276 }
3277
3278 static void ath5k_bss_info_changed(struct ieee80211_hw *hw,
3279                                     struct ieee80211_vif *vif,
3280                                     struct ieee80211_bss_conf *bss_conf,
3281                                     u32 changes)
3282 {
3283         struct ath5k_vif *avf = (void *)vif->drv_priv;
3284         struct ath5k_softc *sc = hw->priv;
3285         struct ath5k_hw *ah = sc->ah;
3286         struct ath_common *common = ath5k_hw_common(ah);
3287         unsigned long flags;
3288
3289         mutex_lock(&sc->lock);
3290
3291         if (changes & BSS_CHANGED_BSSID) {
3292                 /* Cache for later use during resets */
3293                 memcpy(common->curbssid, bss_conf->bssid, ETH_ALEN);
3294                 common->curaid = 0;
3295                 ath5k_hw_set_bssid(ah);
3296                 mmiowb();
3297         }
3298
3299         if (changes & BSS_CHANGED_BEACON_INT)
3300                 sc->bintval = bss_conf->beacon_int;
3301
3302         if (changes & BSS_CHANGED_ASSOC) {
3303                 avf->assoc = bss_conf->assoc;
3304                 if (bss_conf->assoc)
3305                         sc->assoc = bss_conf->assoc;
3306                 else
3307                         sc->assoc = ath_any_vif_assoc(sc);
3308
3309                 if (sc->opmode == NL80211_IFTYPE_STATION)
3310                         set_beacon_filter(hw, sc->assoc);
3311                 ath5k_hw_set_ledstate(sc->ah, sc->assoc ?
3312                         AR5K_LED_ASSOC : AR5K_LED_INIT);
3313                 if (bss_conf->assoc) {
3314                         ATH5K_DBG(sc, ATH5K_DEBUG_ANY,
3315                                   "Bss Info ASSOC %d, bssid: %pM\n",
3316                                   bss_conf->aid, common->curbssid);
3317                         common->curaid = bss_conf->aid;
3318                         ath5k_hw_set_bssid(ah);
3319                         /* Once ANI is available you would start it here */
3320                 }
3321         }
3322
3323         if (changes & BSS_CHANGED_BEACON) {
3324                 spin_lock_irqsave(&sc->block, flags);
3325                 ath5k_beacon_update(hw, vif);
3326                 spin_unlock_irqrestore(&sc->block, flags);
3327         }
3328
3329         if (changes & BSS_CHANGED_BEACON_ENABLED)
3330                 sc->enable_beacon = bss_conf->enable_beacon;
3331
3332         if (changes & (BSS_CHANGED_BEACON | BSS_CHANGED_BEACON_ENABLED |
3333                        BSS_CHANGED_BEACON_INT))
3334                 ath5k_beacon_config(sc);
3335
3336         mutex_unlock(&sc->lock);
3337 }
3338
3339 static void ath5k_sw_scan_start(struct ieee80211_hw *hw)
3340 {
3341         struct ath5k_softc *sc = hw->priv;
3342         if (!sc->assoc)
3343                 ath5k_hw_set_ledstate(sc->ah, AR5K_LED_SCAN);
3344 }
3345
3346 static void ath5k_sw_scan_complete(struct ieee80211_hw *hw)
3347 {
3348         struct ath5k_softc *sc = hw->priv;
3349         ath5k_hw_set_ledstate(sc->ah, sc->assoc ?
3350                 AR5K_LED_ASSOC : AR5K_LED_INIT);
3351 }
3352
3353 /**
3354  * ath5k_set_coverage_class - Set IEEE 802.11 coverage class
3355  *
3356  * @hw: struct ieee80211_hw pointer
3357  * @coverage_class: IEEE 802.11 coverage class number
3358  *
3359  * Mac80211 callback. Sets slot time, ACK timeout and CTS timeout for given
3360  * coverage class. The values are persistent, they are restored after device
3361  * reset.
3362  */
3363 static void ath5k_set_coverage_class(struct ieee80211_hw *hw, u8 coverage_class)
3364 {
3365         struct ath5k_softc *sc = hw->priv;
3366
3367         mutex_lock(&sc->lock);
3368         ath5k_hw_set_coverage_class(sc->ah, coverage_class);
3369         mutex_unlock(&sc->lock);
3370 }
3371
3372 static int ath5k_conf_tx(struct ieee80211_hw *hw, u16 queue,
3373                          const struct ieee80211_tx_queue_params *params)
3374 {
3375         struct ath5k_softc *sc = hw->priv;
3376         struct ath5k_hw *ah = sc->ah;
3377         struct ath5k_txq_info qi;
3378         int ret = 0;
3379
3380         if (queue >= ah->ah_capabilities.cap_queues.q_tx_num)
3381                 return 0;
3382
3383         mutex_lock(&sc->lock);
3384
3385         ath5k_hw_get_tx_queueprops(ah, queue, &qi);
3386
3387         qi.tqi_aifs = params->aifs;
3388         qi.tqi_cw_min = params->cw_min;
3389         qi.tqi_cw_max = params->cw_max;
3390         qi.tqi_burst_time = params->txop;
3391
3392         ATH5K_DBG(sc, ATH5K_DEBUG_ANY,
3393                   "Configure tx [queue %d],  "
3394                   "aifs: %d, cw_min: %d, cw_max: %d, txop: %d\n",
3395                   queue, params->aifs, params->cw_min,
3396                   params->cw_max, params->txop);
3397
3398         if (ath5k_hw_set_tx_queueprops(ah, queue, &qi)) {
3399                 ATH5K_ERR(sc,
3400                           "Unable to update hardware queue %u!\n", queue);
3401                 ret = -EIO;
3402         } else
3403                 ath5k_hw_reset_tx_queue(ah, queue);
3404
3405         mutex_unlock(&sc->lock);
3406
3407         return ret;
3408 }
3409
3410 static int ath5k_set_antenna(struct ieee80211_hw *hw, u32 tx_ant, u32 rx_ant)
3411 {
3412         struct ath5k_softc *sc = hw->priv;
3413
3414         if (tx_ant == 1 && rx_ant == 1)
3415                 ath5k_hw_set_antenna_mode(sc->ah, AR5K_ANTMODE_FIXED_A);
3416         else if (tx_ant == 2 && rx_ant == 2)
3417                 ath5k_hw_set_antenna_mode(sc->ah, AR5K_ANTMODE_FIXED_B);
3418         else if ((tx_ant & 3) == 3 && (rx_ant & 3) == 3)
3419                 ath5k_hw_set_antenna_mode(sc->ah, AR5K_ANTMODE_DEFAULT);
3420         else
3421                 return -EINVAL;
3422         return 0;
3423 }
3424
3425 static int ath5k_get_antenna(struct ieee80211_hw *hw, u32 *tx_ant, u32 *rx_ant)
3426 {
3427         struct ath5k_softc *sc = hw->priv;
3428
3429         switch (sc->ah->ah_ant_mode) {
3430         case AR5K_ANTMODE_FIXED_A:
3431                 *tx_ant = 1; *rx_ant = 1; break;
3432         case AR5K_ANTMODE_FIXED_B:
3433                 *tx_ant = 2; *rx_ant = 2; break;
3434         case AR5K_ANTMODE_DEFAULT:
3435                 *tx_ant = 3; *rx_ant = 3; break;
3436         }
3437         return 0;
3438 }
3439
3440 static const struct ieee80211_ops ath5k_hw_ops = {
3441         .tx             = ath5k_tx,
3442         .start          = ath5k_start,
3443         .stop           = ath5k_stop,
3444         .add_interface  = ath5k_add_interface,
3445         .remove_interface = ath5k_remove_interface,
3446         .config         = ath5k_config,
3447         .prepare_multicast = ath5k_prepare_multicast,
3448         .configure_filter = ath5k_configure_filter,
3449         .set_key        = ath5k_set_key,
3450         .get_stats      = ath5k_get_stats,
3451         .get_survey     = ath5k_get_survey,
3452         .conf_tx        = ath5k_conf_tx,
3453         .get_tsf        = ath5k_get_tsf,
3454         .set_tsf        = ath5k_set_tsf,
3455         .reset_tsf      = ath5k_reset_tsf,
3456         .bss_info_changed = ath5k_bss_info_changed,
3457         .sw_scan_start  = ath5k_sw_scan_start,
3458         .sw_scan_complete = ath5k_sw_scan_complete,
3459         .set_coverage_class = ath5k_set_coverage_class,
3460         .set_antenna    = ath5k_set_antenna,
3461         .get_antenna    = ath5k_get_antenna,
3462 };
3463
3464 /********************\
3465 * PCI Initialization *
3466 \********************/
3467
3468 static int __devinit
3469 ath5k_pci_probe(struct pci_dev *pdev,
3470                 const struct pci_device_id *id)
3471 {
3472         void __iomem *mem;
3473         struct ath5k_softc *sc;
3474         struct ath_common *common;
3475         struct ieee80211_hw *hw;
3476         int ret;
3477         u8 csz;
3478
3479         /*
3480          * L0s needs to be disabled on all ath5k cards.
3481          *
3482          * For distributions shipping with CONFIG_PCIEASPM (this will be enabled
3483          * by default in the future in 2.6.36) this will also mean both L1 and
3484          * L0s will be disabled when a pre 1.1 PCIe device is detected. We do
3485          * know L1 works correctly even for all ath5k pre 1.1 PCIe devices
3486          * though but cannot currently undue the effect of a blacklist, for
3487          * details you can read pcie_aspm_sanity_check() and see how it adjusts
3488          * the device link capability.
3489          *
3490          * It may be possible in the future to implement some PCI API to allow
3491          * drivers to override blacklists for pre 1.1 PCIe but for now it is
3492          * best to accept that both L0s and L1 will be disabled completely for
3493          * distributions shipping with CONFIG_PCIEASPM rather than having this
3494          * issue present. Motivation for adding this new API will be to help
3495          * with power consumption for some of these devices.
3496          */
3497         pci_disable_link_state(pdev, PCIE_LINK_STATE_L0S);
3498
3499         ret = pci_enable_device(pdev);
3500         if (ret) {
3501                 dev_err(&pdev->dev, "can't enable device\n");
3502                 goto err;
3503         }
3504
3505         /* XXX 32-bit addressing only */
3506         ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
3507         if (ret) {
3508                 dev_err(&pdev->dev, "32-bit DMA not available\n");
3509                 goto err_dis;
3510         }
3511
3512         /*
3513          * Cache line size is used to size and align various
3514          * structures used to communicate with the hardware.
3515          */
3516         pci_read_config_byte(pdev, PCI_CACHE_LINE_SIZE, &csz);
3517         if (csz == 0) {
3518                 /*
3519                  * Linux 2.4.18 (at least) writes the cache line size
3520                  * register as a 16-bit wide register which is wrong.
3521                  * We must have this setup properly for rx buffer
3522                  * DMA to work so force a reasonable value here if it
3523                  * comes up zero.
3524                  */
3525                 csz = L1_CACHE_BYTES >> 2;
3526                 pci_write_config_byte(pdev, PCI_CACHE_LINE_SIZE, csz);
3527         }
3528         /*
3529          * The default setting of latency timer yields poor results,
3530          * set it to the value used by other systems.  It may be worth
3531          * tweaking this setting more.
3532          */
3533         pci_write_config_byte(pdev, PCI_LATENCY_TIMER, 0xa8);
3534
3535         /* Enable bus mastering */
3536         pci_set_master(pdev);
3537
3538         /*
3539          * Disable the RETRY_TIMEOUT register (0x41) to keep
3540          * PCI Tx retries from interfering with C3 CPU state.
3541          */
3542         pci_write_config_byte(pdev, 0x41, 0);
3543
3544         ret = pci_request_region(pdev, 0, "ath5k");
3545         if (ret) {
3546                 dev_err(&pdev->dev, "cannot reserve PCI memory region\n");
3547                 goto err_dis;
3548         }
3549
3550         mem = pci_iomap(pdev, 0, 0);
3551         if (!mem) {
3552                 dev_err(&pdev->dev, "cannot remap PCI memory region\n") ;
3553                 ret = -EIO;
3554                 goto err_reg;
3555         }
3556
3557         /*
3558          * Allocate hw (mac80211 main struct)
3559          * and hw->priv (driver private data)
3560          */
3561         hw = ieee80211_alloc_hw(sizeof(*sc), &ath5k_hw_ops);
3562         if (hw == NULL) {
3563                 dev_err(&pdev->dev, "cannot allocate ieee80211_hw\n");
3564                 ret = -ENOMEM;
3565                 goto err_map;
3566         }
3567
3568         dev_info(&pdev->dev, "registered as '%s'\n", wiphy_name(hw->wiphy));
3569
3570         /* Initialize driver private data */
3571         SET_IEEE80211_DEV(hw, &pdev->dev);
3572         hw->flags = IEEE80211_HW_RX_INCLUDES_FCS |
3573                     IEEE80211_HW_HOST_BROADCAST_PS_BUFFERING |
3574                     IEEE80211_HW_SIGNAL_DBM;
3575
3576         hw->wiphy->interface_modes =
3577                 BIT(NL80211_IFTYPE_AP) |
3578                 BIT(NL80211_IFTYPE_STATION) |
3579                 BIT(NL80211_IFTYPE_ADHOC) |
3580                 BIT(NL80211_IFTYPE_MESH_POINT);
3581
3582         hw->extra_tx_headroom = 2;
3583         hw->channel_change_time = 5000;
3584         sc = hw->priv;
3585         sc->hw = hw;
3586         sc->pdev = pdev;
3587
3588         /*
3589          * Mark the device as detached to avoid processing
3590          * interrupts until setup is complete.
3591          */
3592         __set_bit(ATH_STAT_INVALID, sc->status);
3593
3594         sc->iobase = mem; /* So we can unmap it on detach */
3595         sc->opmode = NL80211_IFTYPE_STATION;
3596         sc->bintval = 1000;
3597         mutex_init(&sc->lock);
3598         spin_lock_init(&sc->rxbuflock);
3599         spin_lock_init(&sc->txbuflock);
3600         spin_lock_init(&sc->block);
3601
3602         /* Set private data */
3603         pci_set_drvdata(pdev, sc);
3604
3605         /* Setup interrupt handler */
3606         ret = request_irq(pdev->irq, ath5k_intr, IRQF_SHARED, "ath", sc);
3607         if (ret) {
3608                 ATH5K_ERR(sc, "request_irq failed\n");
3609                 goto err_free;
3610         }
3611
3612         /* If we passed the test, malloc an ath5k_hw struct */
3613         sc->ah = kzalloc(sizeof(struct ath5k_hw), GFP_KERNEL);
3614         if (!sc->ah) {
3615                 ret = -ENOMEM;
3616                 ATH5K_ERR(sc, "out of memory\n");
3617                 goto err_irq;
3618         }
3619
3620         sc->ah->ah_sc = sc;
3621         sc->ah->ah_iobase = sc->iobase;
3622         common = ath5k_hw_common(sc->ah);
3623         common->ops = &ath5k_common_ops;
3624         common->ah = sc->ah;
3625         common->hw = hw;
3626         common->cachelsz = csz << 2; /* convert to bytes */
3627         spin_lock_init(&common->cc_lock);
3628
3629         /* Initialize device */
3630         ret = ath5k_hw_attach(sc);
3631         if (ret) {
3632                 goto err_free_ah;
3633         }
3634
3635         /* set up multi-rate retry capabilities */
3636         if (sc->ah->ah_version == AR5K_AR5212) {
3637                 hw->max_rates = 4;
3638                 hw->max_rate_tries = 11;
3639         }
3640
3641         hw->vif_data_size = sizeof(struct ath5k_vif);
3642
3643         /* Finish private driver data initialization */
3644         ret = ath5k_attach(pdev, hw);
3645         if (ret)
3646                 goto err_ah;
3647
3648         ATH5K_INFO(sc, "Atheros AR%s chip found (MAC: 0x%x, PHY: 0x%x)\n",
3649                         ath5k_chip_name(AR5K_VERSION_MAC, sc->ah->ah_mac_srev),
3650                                         sc->ah->ah_mac_srev,
3651                                         sc->ah->ah_phy_revision);
3652
3653         if (!sc->ah->ah_single_chip) {
3654                 /* Single chip radio (!RF5111) */
3655                 if (sc->ah->ah_radio_5ghz_revision &&
3656                         !sc->ah->ah_radio_2ghz_revision) {
3657                         /* No 5GHz support -> report 2GHz radio */
3658                         if (!test_bit(AR5K_MODE_11A,
3659                                 sc->ah->ah_capabilities.cap_mode)) {
3660                                 ATH5K_INFO(sc, "RF%s 2GHz radio found (0x%x)\n",
3661                                         ath5k_chip_name(AR5K_VERSION_RAD,
3662                                                 sc->ah->ah_radio_5ghz_revision),
3663                                                 sc->ah->ah_radio_5ghz_revision);
3664                         /* No 2GHz support (5110 and some
3665                          * 5Ghz only cards) -> report 5Ghz radio */
3666                         } else if (!test_bit(AR5K_MODE_11B,
3667                                 sc->ah->ah_capabilities.cap_mode)) {
3668                                 ATH5K_INFO(sc, "RF%s 5GHz radio found (0x%x)\n",
3669                                         ath5k_chip_name(AR5K_VERSION_RAD,
3670                                                 sc->ah->ah_radio_5ghz_revision),
3671                                                 sc->ah->ah_radio_5ghz_revision);
3672                         /* Multiband radio */
3673                         } else {
3674                                 ATH5K_INFO(sc, "RF%s multiband radio found"
3675                                         " (0x%x)\n",
3676                                         ath5k_chip_name(AR5K_VERSION_RAD,
3677                                                 sc->ah->ah_radio_5ghz_revision),
3678                                                 sc->ah->ah_radio_5ghz_revision);
3679                         }
3680                 }
3681                 /* Multi chip radio (RF5111 - RF2111) ->
3682                  * report both 2GHz/5GHz radios */
3683                 else if (sc->ah->ah_radio_5ghz_revision &&
3684                                 sc->ah->ah_radio_2ghz_revision){
3685                         ATH5K_INFO(sc, "RF%s 5GHz radio found (0x%x)\n",
3686                                 ath5k_chip_name(AR5K_VERSION_RAD,
3687                                         sc->ah->ah_radio_5ghz_revision),
3688                                         sc->ah->ah_radio_5ghz_revision);
3689                         ATH5K_INFO(sc, "RF%s 2GHz radio found (0x%x)\n",
3690                                 ath5k_chip_name(AR5K_VERSION_RAD,
3691                                         sc->ah->ah_radio_2ghz_revision),
3692                                         sc->ah->ah_radio_2ghz_revision);
3693                 }
3694         }
3695
3696         ath5k_debug_init_device(sc);
3697
3698         /* ready to process interrupts */
3699         __clear_bit(ATH_STAT_INVALID, sc->status);
3700
3701         return 0;
3702 err_ah:
3703         ath5k_hw_detach(sc->ah);
3704 err_free_ah:
3705         kfree(sc->ah);
3706 err_irq:
3707         free_irq(pdev->irq, sc);
3708 err_free:
3709         ieee80211_free_hw(hw);
3710 err_map:
3711         pci_iounmap(pdev, mem);
3712 err_reg:
3713         pci_release_region(pdev, 0);
3714 err_dis:
3715         pci_disable_device(pdev);
3716 err:
3717         return ret;
3718 }
3719
3720 static void __devexit
3721 ath5k_pci_remove(struct pci_dev *pdev)
3722 {
3723         struct ath5k_softc *sc = pci_get_drvdata(pdev);
3724
3725         ath5k_debug_finish_device(sc);
3726         ath5k_detach(pdev, sc->hw);
3727         ath5k_hw_detach(sc->ah);
3728         kfree(sc->ah);
3729         free_irq(pdev->irq, sc);
3730         pci_iounmap(pdev, sc->iobase);
3731         pci_release_region(pdev, 0);
3732         pci_disable_device(pdev);
3733         ieee80211_free_hw(sc->hw);
3734 }
3735
3736 #ifdef CONFIG_PM_SLEEP
3737 static int ath5k_pci_suspend(struct device *dev)
3738 {
3739         struct ath5k_softc *sc = pci_get_drvdata(to_pci_dev(dev));
3740
3741         ath5k_led_off(sc);
3742         return 0;
3743 }
3744
3745 static int ath5k_pci_resume(struct device *dev)
3746 {
3747         struct pci_dev *pdev = to_pci_dev(dev);
3748         struct ath5k_softc *sc = pci_get_drvdata(pdev);
3749
3750         /*
3751          * Suspend/Resume resets the PCI configuration space, so we have to
3752          * re-disable the RETRY_TIMEOUT register (0x41) to keep
3753          * PCI Tx retries from interfering with C3 CPU state
3754          */
3755         pci_write_config_byte(pdev, 0x41, 0);
3756
3757         ath5k_led_enable(sc);
3758         return 0;
3759 }
3760
3761 static SIMPLE_DEV_PM_OPS(ath5k_pm_ops, ath5k_pci_suspend, ath5k_pci_resume);
3762 #define ATH5K_PM_OPS    (&ath5k_pm_ops)
3763 #else
3764 #define ATH5K_PM_OPS    NULL
3765 #endif /* CONFIG_PM_SLEEP */
3766
3767 static struct pci_driver ath5k_pci_driver = {
3768         .name           = KBUILD_MODNAME,
3769         .id_table       = ath5k_pci_id_table,
3770         .probe          = ath5k_pci_probe,
3771         .remove         = __devexit_p(ath5k_pci_remove),
3772         .driver.pm      = ATH5K_PM_OPS,
3773 };
3774
3775 /*
3776  * Module init/exit functions
3777  */
3778 static int __init
3779 init_ath5k_pci(void)
3780 {
3781         int ret;
3782
3783         ret = pci_register_driver(&ath5k_pci_driver);
3784         if (ret) {
3785                 printk(KERN_ERR "ath5k_pci: can't register pci driver\n");
3786                 return ret;
3787         }
3788
3789         return 0;
3790 }
3791
3792 static void __exit
3793 exit_ath5k_pci(void)
3794 {
3795         pci_unregister_driver(&ath5k_pci_driver);
3796 }
3797
3798 module_init(init_ath5k_pci);
3799 module_exit(exit_ath5k_pci);