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