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