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