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