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