bb6e1ddb4a57c8dba81f9c938b57f9a896035240
[safe/jmp/linux-2.6] / drivers / net / wireless / ath9k / main.c
1 /*
2  * Copyright (c) 2008 Atheros Communications Inc.
3  *
4  * Permission to use, copy, modify, and/or distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16
17 #include <linux/nl80211.h>
18 #include "ath9k.h"
19
20 #define ATH_PCI_VERSION "0.1"
21
22 static char *dev_info = "ath9k";
23
24 MODULE_AUTHOR("Atheros Communications");
25 MODULE_DESCRIPTION("Support for Atheros 802.11n wireless LAN cards.");
26 MODULE_SUPPORTED_DEVICE("Atheros 802.11n WLAN cards");
27 MODULE_LICENSE("Dual BSD/GPL");
28
29 static int modparam_nohwcrypt;
30 module_param_named(nohwcrypt, modparam_nohwcrypt, int, 0444);
31 MODULE_PARM_DESC(nohwcrypt, "Disable hardware encryption");
32
33 /* We use the hw_value as an index into our private channel structure */
34
35 #define CHAN2G(_freq, _idx)  { \
36         .center_freq = (_freq), \
37         .hw_value = (_idx), \
38         .max_power = 30, \
39 }
40
41 #define CHAN5G(_freq, _idx) { \
42         .band = IEEE80211_BAND_5GHZ, \
43         .center_freq = (_freq), \
44         .hw_value = (_idx), \
45         .max_power = 30, \
46 }
47
48 /* Some 2 GHz radios are actually tunable on 2312-2732
49  * on 5 MHz steps, we support the channels which we know
50  * we have calibration data for all cards though to make
51  * this static */
52 static struct ieee80211_channel ath9k_2ghz_chantable[] = {
53         CHAN2G(2412, 0), /* Channel 1 */
54         CHAN2G(2417, 1), /* Channel 2 */
55         CHAN2G(2422, 2), /* Channel 3 */
56         CHAN2G(2427, 3), /* Channel 4 */
57         CHAN2G(2432, 4), /* Channel 5 */
58         CHAN2G(2437, 5), /* Channel 6 */
59         CHAN2G(2442, 6), /* Channel 7 */
60         CHAN2G(2447, 7), /* Channel 8 */
61         CHAN2G(2452, 8), /* Channel 9 */
62         CHAN2G(2457, 9), /* Channel 10 */
63         CHAN2G(2462, 10), /* Channel 11 */
64         CHAN2G(2467, 11), /* Channel 12 */
65         CHAN2G(2472, 12), /* Channel 13 */
66         CHAN2G(2484, 13), /* Channel 14 */
67 };
68
69 /* Some 5 GHz radios are actually tunable on XXXX-YYYY
70  * on 5 MHz steps, we support the channels which we know
71  * we have calibration data for all cards though to make
72  * this static */
73 static struct ieee80211_channel ath9k_5ghz_chantable[] = {
74         /* _We_ call this UNII 1 */
75         CHAN5G(5180, 14), /* Channel 36 */
76         CHAN5G(5200, 15), /* Channel 40 */
77         CHAN5G(5220, 16), /* Channel 44 */
78         CHAN5G(5240, 17), /* Channel 48 */
79         /* _We_ call this UNII 2 */
80         CHAN5G(5260, 18), /* Channel 52 */
81         CHAN5G(5280, 19), /* Channel 56 */
82         CHAN5G(5300, 20), /* Channel 60 */
83         CHAN5G(5320, 21), /* Channel 64 */
84         /* _We_ call this "Middle band" */
85         CHAN5G(5500, 22), /* Channel 100 */
86         CHAN5G(5520, 23), /* Channel 104 */
87         CHAN5G(5540, 24), /* Channel 108 */
88         CHAN5G(5560, 25), /* Channel 112 */
89         CHAN5G(5580, 26), /* Channel 116 */
90         CHAN5G(5600, 27), /* Channel 120 */
91         CHAN5G(5620, 28), /* Channel 124 */
92         CHAN5G(5640, 29), /* Channel 128 */
93         CHAN5G(5660, 30), /* Channel 132 */
94         CHAN5G(5680, 31), /* Channel 136 */
95         CHAN5G(5700, 32), /* Channel 140 */
96         /* _We_ call this UNII 3 */
97         CHAN5G(5745, 33), /* Channel 149 */
98         CHAN5G(5765, 34), /* Channel 153 */
99         CHAN5G(5785, 35), /* Channel 157 */
100         CHAN5G(5805, 36), /* Channel 161 */
101         CHAN5G(5825, 37), /* Channel 165 */
102 };
103
104 static void ath_cache_conf_rate(struct ath_softc *sc,
105                                 struct ieee80211_conf *conf)
106 {
107         switch (conf->channel->band) {
108         case IEEE80211_BAND_2GHZ:
109                 if (conf_is_ht20(conf))
110                         sc->cur_rate_table =
111                           sc->hw_rate_table[ATH9K_MODE_11NG_HT20];
112                 else if (conf_is_ht40_minus(conf))
113                         sc->cur_rate_table =
114                           sc->hw_rate_table[ATH9K_MODE_11NG_HT40MINUS];
115                 else if (conf_is_ht40_plus(conf))
116                         sc->cur_rate_table =
117                           sc->hw_rate_table[ATH9K_MODE_11NG_HT40PLUS];
118                 else
119                         sc->cur_rate_table =
120                           sc->hw_rate_table[ATH9K_MODE_11G];
121                 break;
122         case IEEE80211_BAND_5GHZ:
123                 if (conf_is_ht20(conf))
124                         sc->cur_rate_table =
125                           sc->hw_rate_table[ATH9K_MODE_11NA_HT20];
126                 else if (conf_is_ht40_minus(conf))
127                         sc->cur_rate_table =
128                           sc->hw_rate_table[ATH9K_MODE_11NA_HT40MINUS];
129                 else if (conf_is_ht40_plus(conf))
130                         sc->cur_rate_table =
131                           sc->hw_rate_table[ATH9K_MODE_11NA_HT40PLUS];
132                 else
133                         sc->cur_rate_table =
134                           sc->hw_rate_table[ATH9K_MODE_11A];
135                 break;
136         default:
137                 BUG_ON(1);
138                 break;
139         }
140 }
141
142 static void ath_update_txpow(struct ath_softc *sc)
143 {
144         struct ath_hw *ah = sc->sc_ah;
145         u32 txpow;
146
147         if (sc->curtxpow != sc->config.txpowlimit) {
148                 ath9k_hw_set_txpowerlimit(ah, sc->config.txpowlimit);
149                 /* read back in case value is clamped */
150                 ath9k_hw_getcapability(ah, ATH9K_CAP_TXPOW, 1, &txpow);
151                 sc->curtxpow = txpow;
152         }
153 }
154
155 static u8 parse_mpdudensity(u8 mpdudensity)
156 {
157         /*
158          * 802.11n D2.0 defined values for "Minimum MPDU Start Spacing":
159          *   0 for no restriction
160          *   1 for 1/4 us
161          *   2 for 1/2 us
162          *   3 for 1 us
163          *   4 for 2 us
164          *   5 for 4 us
165          *   6 for 8 us
166          *   7 for 16 us
167          */
168         switch (mpdudensity) {
169         case 0:
170                 return 0;
171         case 1:
172         case 2:
173         case 3:
174                 /* Our lower layer calculations limit our precision to
175                    1 microsecond */
176                 return 1;
177         case 4:
178                 return 2;
179         case 5:
180                 return 4;
181         case 6:
182                 return 8;
183         case 7:
184                 return 16;
185         default:
186                 return 0;
187         }
188 }
189
190 static void ath_setup_rates(struct ath_softc *sc, enum ieee80211_band band)
191 {
192         struct ath_rate_table *rate_table = NULL;
193         struct ieee80211_supported_band *sband;
194         struct ieee80211_rate *rate;
195         int i, maxrates;
196
197         switch (band) {
198         case IEEE80211_BAND_2GHZ:
199                 rate_table = sc->hw_rate_table[ATH9K_MODE_11G];
200                 break;
201         case IEEE80211_BAND_5GHZ:
202                 rate_table = sc->hw_rate_table[ATH9K_MODE_11A];
203                 break;
204         default:
205                 break;
206         }
207
208         if (rate_table == NULL)
209                 return;
210
211         sband = &sc->sbands[band];
212         rate = sc->rates[band];
213
214         if (rate_table->rate_cnt > ATH_RATE_MAX)
215                 maxrates = ATH_RATE_MAX;
216         else
217                 maxrates = rate_table->rate_cnt;
218
219         for (i = 0; i < maxrates; i++) {
220                 rate[i].bitrate = rate_table->info[i].ratekbps / 100;
221                 rate[i].hw_value = rate_table->info[i].ratecode;
222                 if (rate_table->info[i].short_preamble) {
223                         rate[i].hw_value_short = rate_table->info[i].ratecode |
224                                 rate_table->info[i].short_preamble;
225                         rate[i].flags = IEEE80211_RATE_SHORT_PREAMBLE;
226                 }
227                 sband->n_bitrates++;
228
229                 DPRINTF(sc, ATH_DBG_CONFIG, "Rate: %2dMbps, ratecode: %2d\n",
230                         rate[i].bitrate / 10, rate[i].hw_value);
231         }
232 }
233
234 /*
235  * Set/change channels.  If the channel is really being changed, it's done
236  * by reseting the chip.  To accomplish this we must first cleanup any pending
237  * DMA, then restart stuff.
238 */
239 int ath_set_channel(struct ath_softc *sc, struct ieee80211_hw *hw,
240                     struct ath9k_channel *hchan)
241 {
242         struct ath_hw *ah = sc->sc_ah;
243         bool fastcc = true, stopped;
244         struct ieee80211_channel *channel = hw->conf.channel;
245         int r;
246
247         if (sc->sc_flags & SC_OP_INVALID)
248                 return -EIO;
249
250         ath9k_ps_wakeup(sc);
251
252         /*
253          * This is only performed if the channel settings have
254          * actually changed.
255          *
256          * To switch channels clear any pending DMA operations;
257          * wait long enough for the RX fifo to drain, reset the
258          * hardware at the new frequency, and then re-enable
259          * the relevant bits of the h/w.
260          */
261         ath9k_hw_set_interrupts(ah, 0);
262         ath_drain_all_txq(sc, false);
263         stopped = ath_stoprecv(sc);
264
265         /* XXX: do not flush receive queue here. We don't want
266          * to flush data frames already in queue because of
267          * changing channel. */
268
269         if (!stopped || (sc->sc_flags & SC_OP_FULL_RESET))
270                 fastcc = false;
271
272         DPRINTF(sc, ATH_DBG_CONFIG,
273                 "(%u MHz) -> (%u MHz), chanwidth: %d\n",
274                 sc->sc_ah->curchan->channel,
275                 channel->center_freq, sc->tx_chan_width);
276
277         spin_lock_bh(&sc->sc_resetlock);
278
279         r = ath9k_hw_reset(ah, hchan, fastcc);
280         if (r) {
281                 DPRINTF(sc, ATH_DBG_FATAL,
282                         "Unable to reset channel (%u Mhz) "
283                         "reset status %u\n",
284                         channel->center_freq, r);
285                 spin_unlock_bh(&sc->sc_resetlock);
286                 return r;
287         }
288         spin_unlock_bh(&sc->sc_resetlock);
289
290         sc->sc_flags &= ~SC_OP_CHAINMASK_UPDATE;
291         sc->sc_flags &= ~SC_OP_FULL_RESET;
292
293         if (ath_startrecv(sc) != 0) {
294                 DPRINTF(sc, ATH_DBG_FATAL,
295                         "Unable to restart recv logic\n");
296                 return -EIO;
297         }
298
299         ath_cache_conf_rate(sc, &hw->conf);
300         ath_update_txpow(sc);
301         ath9k_hw_set_interrupts(ah, sc->imask);
302         ath9k_ps_restore(sc);
303         return 0;
304 }
305
306 /*
307  *  This routine performs the periodic noise floor calibration function
308  *  that is used to adjust and optimize the chip performance.  This
309  *  takes environmental changes (location, temperature) into account.
310  *  When the task is complete, it reschedules itself depending on the
311  *  appropriate interval that was calculated.
312  */
313 static void ath_ani_calibrate(unsigned long data)
314 {
315         struct ath_softc *sc = (struct ath_softc *)data;
316         struct ath_hw *ah = sc->sc_ah;
317         bool longcal = false;
318         bool shortcal = false;
319         bool aniflag = false;
320         unsigned int timestamp = jiffies_to_msecs(jiffies);
321         u32 cal_interval, short_cal_interval;
322
323         short_cal_interval = (ah->opmode == NL80211_IFTYPE_AP) ?
324                 ATH_AP_SHORT_CALINTERVAL : ATH_STA_SHORT_CALINTERVAL;
325
326         /*
327         * don't calibrate when we're scanning.
328         * we are most likely not on our home channel.
329         */
330         if (sc->sc_flags & SC_OP_SCANNING)
331                 goto set_timer;
332
333         /* Long calibration runs independently of short calibration. */
334         if ((timestamp - sc->ani.longcal_timer) >= ATH_LONG_CALINTERVAL) {
335                 longcal = true;
336                 DPRINTF(sc, ATH_DBG_ANI, "longcal @%lu\n", jiffies);
337                 sc->ani.longcal_timer = timestamp;
338         }
339
340         /* Short calibration applies only while caldone is false */
341         if (!sc->ani.caldone) {
342                 if ((timestamp - sc->ani.shortcal_timer) >= short_cal_interval) {
343                         shortcal = true;
344                         DPRINTF(sc, ATH_DBG_ANI, "shortcal @%lu\n", jiffies);
345                         sc->ani.shortcal_timer = timestamp;
346                         sc->ani.resetcal_timer = timestamp;
347                 }
348         } else {
349                 if ((timestamp - sc->ani.resetcal_timer) >=
350                     ATH_RESTART_CALINTERVAL) {
351                         sc->ani.caldone = ath9k_hw_reset_calvalid(ah);
352                         if (sc->ani.caldone)
353                                 sc->ani.resetcal_timer = timestamp;
354                 }
355         }
356
357         /* Verify whether we must check ANI */
358         if ((timestamp - sc->ani.checkani_timer) >= ATH_ANI_POLLINTERVAL) {
359                 aniflag = true;
360                 sc->ani.checkani_timer = timestamp;
361         }
362
363         /* Skip all processing if there's nothing to do. */
364         if (longcal || shortcal || aniflag) {
365                 /* Call ANI routine if necessary */
366                 if (aniflag)
367                         ath9k_hw_ani_monitor(ah, &sc->nodestats, ah->curchan);
368
369                 /* Perform calibration if necessary */
370                 if (longcal || shortcal) {
371                         bool iscaldone = false;
372
373                         if (ath9k_hw_calibrate(ah, ah->curchan,
374                                                sc->rx_chainmask, longcal,
375                                                &iscaldone)) {
376                                 if (longcal)
377                                         sc->ani.noise_floor =
378                                                 ath9k_hw_getchan_noise(ah,
379                                                                ah->curchan);
380
381                                 DPRINTF(sc, ATH_DBG_ANI,
382                                         "calibrate chan %u/%x nf: %d\n",
383                                         ah->curchan->channel,
384                                         ah->curchan->channelFlags,
385                                         sc->ani.noise_floor);
386                         } else {
387                                 DPRINTF(sc, ATH_DBG_ANY,
388                                         "calibrate chan %u/%x failed\n",
389                                         ah->curchan->channel,
390                                         ah->curchan->channelFlags);
391                         }
392                         sc->ani.caldone = iscaldone;
393                 }
394         }
395
396 set_timer:
397         /*
398         * Set timer interval based on previous results.
399         * The interval must be the shortest necessary to satisfy ANI,
400         * short calibration and long calibration.
401         */
402         cal_interval = ATH_LONG_CALINTERVAL;
403         if (sc->sc_ah->config.enable_ani)
404                 cal_interval = min(cal_interval, (u32)ATH_ANI_POLLINTERVAL);
405         if (!sc->ani.caldone)
406                 cal_interval = min(cal_interval, (u32)short_cal_interval);
407
408         mod_timer(&sc->ani.timer, jiffies + msecs_to_jiffies(cal_interval));
409 }
410
411 /*
412  * Update tx/rx chainmask. For legacy association,
413  * hard code chainmask to 1x1, for 11n association, use
414  * the chainmask configuration, for bt coexistence, use
415  * the chainmask configuration even in legacy mode.
416  */
417 void ath_update_chainmask(struct ath_softc *sc, int is_ht)
418 {
419         sc->sc_flags |= SC_OP_CHAINMASK_UPDATE;
420         if (is_ht ||
421             (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_BT_COEX)) {
422                 sc->tx_chainmask = sc->sc_ah->caps.tx_chainmask;
423                 sc->rx_chainmask = sc->sc_ah->caps.rx_chainmask;
424         } else {
425                 sc->tx_chainmask = 1;
426                 sc->rx_chainmask = 1;
427         }
428
429         DPRINTF(sc, ATH_DBG_CONFIG, "tx chmask: %d, rx chmask: %d\n",
430                 sc->tx_chainmask, sc->rx_chainmask);
431 }
432
433 static void ath_node_attach(struct ath_softc *sc, struct ieee80211_sta *sta)
434 {
435         struct ath_node *an;
436
437         an = (struct ath_node *)sta->drv_priv;
438
439         if (sc->sc_flags & SC_OP_TXAGGR)
440                 ath_tx_node_init(sc, an);
441
442         an->maxampdu = 1 << (IEEE80211_HTCAP_MAXRXAMPDU_FACTOR +
443                              sta->ht_cap.ampdu_factor);
444         an->mpdudensity = parse_mpdudensity(sta->ht_cap.ampdu_density);
445 }
446
447 static void ath_node_detach(struct ath_softc *sc, struct ieee80211_sta *sta)
448 {
449         struct ath_node *an = (struct ath_node *)sta->drv_priv;
450
451         if (sc->sc_flags & SC_OP_TXAGGR)
452                 ath_tx_node_cleanup(sc, an);
453 }
454
455 static void ath9k_tasklet(unsigned long data)
456 {
457         struct ath_softc *sc = (struct ath_softc *)data;
458         u32 status = sc->intrstatus;
459
460         if (status & ATH9K_INT_FATAL) {
461                 /* need a chip reset */
462                 ath_reset(sc, false);
463                 return;
464         } else {
465
466                 if (status &
467                     (ATH9K_INT_RX | ATH9K_INT_RXEOL | ATH9K_INT_RXORN)) {
468                         spin_lock_bh(&sc->rx.rxflushlock);
469                         ath_rx_tasklet(sc, 0);
470                         spin_unlock_bh(&sc->rx.rxflushlock);
471                 }
472                 /* XXX: optimize this */
473                 if (status & ATH9K_INT_TX)
474                         ath_tx_tasklet(sc);
475         }
476
477         /* re-enable hardware interrupt */
478         ath9k_hw_set_interrupts(sc->sc_ah, sc->imask);
479 }
480
481 irqreturn_t ath_isr(int irq, void *dev)
482 {
483         struct ath_softc *sc = dev;
484         struct ath_hw *ah = sc->sc_ah;
485         enum ath9k_int status;
486         bool sched = false;
487
488         do {
489                 if (sc->sc_flags & SC_OP_INVALID) {
490                         /*
491                          * The hardware is not ready/present, don't
492                          * touch anything. Note this can happen early
493                          * on if the IRQ is shared.
494                          */
495                         return IRQ_NONE;
496                 }
497                 if (!ath9k_hw_intrpend(ah)) {   /* shared irq, not for us */
498                         return IRQ_NONE;
499                 }
500
501                 /*
502                  * Figure out the reason(s) for the interrupt.  Note
503                  * that the hal returns a pseudo-ISR that may include
504                  * bits we haven't explicitly enabled so we mask the
505                  * value to insure we only process bits we requested.
506                  */
507                 ath9k_hw_getisr(ah, &status);   /* NB: clears ISR too */
508
509                 status &= sc->imask;    /* discard unasked-for bits */
510
511                 /*
512                  * If there are no status bits set, then this interrupt was not
513                  * for me (should have been caught above).
514                  */
515                 if (!status)
516                         return IRQ_NONE;
517
518                 sc->intrstatus = status;
519                 ath9k_ps_wakeup(sc);
520
521                 if (status & ATH9K_INT_FATAL) {
522                         /* need a chip reset */
523                         sched = true;
524                 } else if (status & ATH9K_INT_RXORN) {
525                         /* need a chip reset */
526                         sched = true;
527                 } else {
528                         if (status & ATH9K_INT_SWBA) {
529                                 /* schedule a tasklet for beacon handling */
530                                 tasklet_schedule(&sc->bcon_tasklet);
531                         }
532                         if (status & ATH9K_INT_RXEOL) {
533                                 /*
534                                  * NB: the hardware should re-read the link when
535                                  *     RXE bit is written, but it doesn't work
536                                  *     at least on older hardware revs.
537                                  */
538                                 sched = true;
539                         }
540
541                         if (status & ATH9K_INT_TXURN)
542                                 /* bump tx trigger level */
543                                 ath9k_hw_updatetxtriglevel(ah, true);
544                         /* XXX: optimize this */
545                         if (status & ATH9K_INT_RX)
546                                 sched = true;
547                         if (status & ATH9K_INT_TX)
548                                 sched = true;
549                         if (status & ATH9K_INT_BMISS)
550                                 sched = true;
551                         /* carrier sense timeout */
552                         if (status & ATH9K_INT_CST)
553                                 sched = true;
554                         if (status & ATH9K_INT_MIB) {
555                                 /*
556                                  * Disable interrupts until we service the MIB
557                                  * interrupt; otherwise it will continue to
558                                  * fire.
559                                  */
560                                 ath9k_hw_set_interrupts(ah, 0);
561                                 /*
562                                  * Let the hal handle the event. We assume
563                                  * it will clear whatever condition caused
564                                  * the interrupt.
565                                  */
566                                 ath9k_hw_procmibevent(ah, &sc->nodestats);
567                                 ath9k_hw_set_interrupts(ah, sc->imask);
568                         }
569                         if (status & ATH9K_INT_TIM_TIMER) {
570                                 if (!(ah->caps.hw_caps &
571                                       ATH9K_HW_CAP_AUTOSLEEP)) {
572                                         /* Clear RxAbort bit so that we can
573                                          * receive frames */
574                                         ath9k_hw_setpower(ah, ATH9K_PM_AWAKE);
575                                         ath9k_hw_setrxabort(ah, 0);
576                                         sched = true;
577                                         sc->sc_flags |= SC_OP_WAIT_FOR_BEACON;
578                                 }
579                         }
580                         if (status & ATH9K_INT_TSFOOR) {
581                                 /* FIXME: Handle this interrupt for power save */
582                                 sched = true;
583                         }
584                 }
585                 ath9k_ps_restore(sc);
586         } while (0);
587
588         ath_debug_stat_interrupt(sc, status);
589
590         if (sched) {
591                 /* turn off every interrupt except SWBA */
592                 ath9k_hw_set_interrupts(ah, (sc->imask & ATH9K_INT_SWBA));
593                 tasklet_schedule(&sc->intr_tq);
594         }
595
596         return IRQ_HANDLED;
597 }
598
599 static u32 ath_get_extchanmode(struct ath_softc *sc,
600                                struct ieee80211_channel *chan,
601                                enum nl80211_channel_type channel_type)
602 {
603         u32 chanmode = 0;
604
605         switch (chan->band) {
606         case IEEE80211_BAND_2GHZ:
607                 switch(channel_type) {
608                 case NL80211_CHAN_NO_HT:
609                 case NL80211_CHAN_HT20:
610                         chanmode = CHANNEL_G_HT20;
611                         break;
612                 case NL80211_CHAN_HT40PLUS:
613                         chanmode = CHANNEL_G_HT40PLUS;
614                         break;
615                 case NL80211_CHAN_HT40MINUS:
616                         chanmode = CHANNEL_G_HT40MINUS;
617                         break;
618                 }
619                 break;
620         case IEEE80211_BAND_5GHZ:
621                 switch(channel_type) {
622                 case NL80211_CHAN_NO_HT:
623                 case NL80211_CHAN_HT20:
624                         chanmode = CHANNEL_A_HT20;
625                         break;
626                 case NL80211_CHAN_HT40PLUS:
627                         chanmode = CHANNEL_A_HT40PLUS;
628                         break;
629                 case NL80211_CHAN_HT40MINUS:
630                         chanmode = CHANNEL_A_HT40MINUS;
631                         break;
632                 }
633                 break;
634         default:
635                 break;
636         }
637
638         return chanmode;
639 }
640
641 static int ath_setkey_tkip(struct ath_softc *sc, u16 keyix, const u8 *key,
642                            struct ath9k_keyval *hk, const u8 *addr,
643                            bool authenticator)
644 {
645         const u8 *key_rxmic;
646         const u8 *key_txmic;
647
648         key_txmic = key + NL80211_TKIP_DATA_OFFSET_TX_MIC_KEY;
649         key_rxmic = key + NL80211_TKIP_DATA_OFFSET_RX_MIC_KEY;
650
651         if (addr == NULL) {
652                 /*
653                  * Group key installation - only two key cache entries are used
654                  * regardless of splitmic capability since group key is only
655                  * used either for TX or RX.
656                  */
657                 if (authenticator) {
658                         memcpy(hk->kv_mic, key_txmic, sizeof(hk->kv_mic));
659                         memcpy(hk->kv_txmic, key_txmic, sizeof(hk->kv_mic));
660                 } else {
661                         memcpy(hk->kv_mic, key_rxmic, sizeof(hk->kv_mic));
662                         memcpy(hk->kv_txmic, key_rxmic, sizeof(hk->kv_mic));
663                 }
664                 return ath9k_hw_set_keycache_entry(sc->sc_ah, keyix, hk, addr);
665         }
666         if (!sc->splitmic) {
667                 /* TX and RX keys share the same key cache entry. */
668                 memcpy(hk->kv_mic, key_rxmic, sizeof(hk->kv_mic));
669                 memcpy(hk->kv_txmic, key_txmic, sizeof(hk->kv_txmic));
670                 return ath9k_hw_set_keycache_entry(sc->sc_ah, keyix, hk, addr);
671         }
672
673         /* Separate key cache entries for TX and RX */
674
675         /* TX key goes at first index, RX key at +32. */
676         memcpy(hk->kv_mic, key_txmic, sizeof(hk->kv_mic));
677         if (!ath9k_hw_set_keycache_entry(sc->sc_ah, keyix, hk, NULL)) {
678                 /* TX MIC entry failed. No need to proceed further */
679                 DPRINTF(sc, ATH_DBG_KEYCACHE,
680                         "Setting TX MIC Key Failed\n");
681                 return 0;
682         }
683
684         memcpy(hk->kv_mic, key_rxmic, sizeof(hk->kv_mic));
685         /* XXX delete tx key on failure? */
686         return ath9k_hw_set_keycache_entry(sc->sc_ah, keyix + 32, hk, addr);
687 }
688
689 static int ath_reserve_key_cache_slot_tkip(struct ath_softc *sc)
690 {
691         int i;
692
693         for (i = IEEE80211_WEP_NKID; i < sc->keymax / 2; i++) {
694                 if (test_bit(i, sc->keymap) ||
695                     test_bit(i + 64, sc->keymap))
696                         continue; /* At least one part of TKIP key allocated */
697                 if (sc->splitmic &&
698                     (test_bit(i + 32, sc->keymap) ||
699                      test_bit(i + 64 + 32, sc->keymap)))
700                         continue; /* At least one part of TKIP key allocated */
701
702                 /* Found a free slot for a TKIP key */
703                 return i;
704         }
705         return -1;
706 }
707
708 static int ath_reserve_key_cache_slot(struct ath_softc *sc)
709 {
710         int i;
711
712         /* First, try to find slots that would not be available for TKIP. */
713         if (sc->splitmic) {
714                 for (i = IEEE80211_WEP_NKID; i < sc->keymax / 4; i++) {
715                         if (!test_bit(i, sc->keymap) &&
716                             (test_bit(i + 32, sc->keymap) ||
717                              test_bit(i + 64, sc->keymap) ||
718                              test_bit(i + 64 + 32, sc->keymap)))
719                                 return i;
720                         if (!test_bit(i + 32, sc->keymap) &&
721                             (test_bit(i, sc->keymap) ||
722                              test_bit(i + 64, sc->keymap) ||
723                              test_bit(i + 64 + 32, sc->keymap)))
724                                 return i + 32;
725                         if (!test_bit(i + 64, sc->keymap) &&
726                             (test_bit(i , sc->keymap) ||
727                              test_bit(i + 32, sc->keymap) ||
728                              test_bit(i + 64 + 32, sc->keymap)))
729                                 return i + 64;
730                         if (!test_bit(i + 64 + 32, sc->keymap) &&
731                             (test_bit(i, sc->keymap) ||
732                              test_bit(i + 32, sc->keymap) ||
733                              test_bit(i + 64, sc->keymap)))
734                                 return i + 64 + 32;
735                 }
736         } else {
737                 for (i = IEEE80211_WEP_NKID; i < sc->keymax / 2; i++) {
738                         if (!test_bit(i, sc->keymap) &&
739                             test_bit(i + 64, sc->keymap))
740                                 return i;
741                         if (test_bit(i, sc->keymap) &&
742                             !test_bit(i + 64, sc->keymap))
743                                 return i + 64;
744                 }
745         }
746
747         /* No partially used TKIP slots, pick any available slot */
748         for (i = IEEE80211_WEP_NKID; i < sc->keymax; i++) {
749                 /* Do not allow slots that could be needed for TKIP group keys
750                  * to be used. This limitation could be removed if we know that
751                  * TKIP will not be used. */
752                 if (i >= 64 && i < 64 + IEEE80211_WEP_NKID)
753                         continue;
754                 if (sc->splitmic) {
755                         if (i >= 32 && i < 32 + IEEE80211_WEP_NKID)
756                                 continue;
757                         if (i >= 64 + 32 && i < 64 + 32 + IEEE80211_WEP_NKID)
758                                 continue;
759                 }
760
761                 if (!test_bit(i, sc->keymap))
762                         return i; /* Found a free slot for a key */
763         }
764
765         /* No free slot found */
766         return -1;
767 }
768
769 static int ath_key_config(struct ath_softc *sc,
770                           struct ieee80211_vif *vif,
771                           struct ieee80211_sta *sta,
772                           struct ieee80211_key_conf *key)
773 {
774         struct ath9k_keyval hk;
775         const u8 *mac = NULL;
776         int ret = 0;
777         int idx;
778
779         memset(&hk, 0, sizeof(hk));
780
781         switch (key->alg) {
782         case ALG_WEP:
783                 hk.kv_type = ATH9K_CIPHER_WEP;
784                 break;
785         case ALG_TKIP:
786                 hk.kv_type = ATH9K_CIPHER_TKIP;
787                 break;
788         case ALG_CCMP:
789                 hk.kv_type = ATH9K_CIPHER_AES_CCM;
790                 break;
791         default:
792                 return -EOPNOTSUPP;
793         }
794
795         hk.kv_len = key->keylen;
796         memcpy(hk.kv_val, key->key, key->keylen);
797
798         if (!(key->flags & IEEE80211_KEY_FLAG_PAIRWISE)) {
799                 /* For now, use the default keys for broadcast keys. This may
800                  * need to change with virtual interfaces. */
801                 idx = key->keyidx;
802         } else if (key->keyidx) {
803                 if (WARN_ON(!sta))
804                         return -EOPNOTSUPP;
805                 mac = sta->addr;
806
807                 if (vif->type != NL80211_IFTYPE_AP) {
808                         /* Only keyidx 0 should be used with unicast key, but
809                          * allow this for client mode for now. */
810                         idx = key->keyidx;
811                 } else
812                         return -EIO;
813         } else {
814                 if (WARN_ON(!sta))
815                         return -EOPNOTSUPP;
816                 mac = sta->addr;
817
818                 if (key->alg == ALG_TKIP)
819                         idx = ath_reserve_key_cache_slot_tkip(sc);
820                 else
821                         idx = ath_reserve_key_cache_slot(sc);
822                 if (idx < 0)
823                         return -ENOSPC; /* no free key cache entries */
824         }
825
826         if (key->alg == ALG_TKIP)
827                 ret = ath_setkey_tkip(sc, idx, key->key, &hk, mac,
828                                       vif->type == NL80211_IFTYPE_AP);
829         else
830                 ret = ath9k_hw_set_keycache_entry(sc->sc_ah, idx, &hk, mac);
831
832         if (!ret)
833                 return -EIO;
834
835         set_bit(idx, sc->keymap);
836         if (key->alg == ALG_TKIP) {
837                 set_bit(idx + 64, sc->keymap);
838                 if (sc->splitmic) {
839                         set_bit(idx + 32, sc->keymap);
840                         set_bit(idx + 64 + 32, sc->keymap);
841                 }
842         }
843
844         return idx;
845 }
846
847 static void ath_key_delete(struct ath_softc *sc, struct ieee80211_key_conf *key)
848 {
849         ath9k_hw_keyreset(sc->sc_ah, key->hw_key_idx);
850         if (key->hw_key_idx < IEEE80211_WEP_NKID)
851                 return;
852
853         clear_bit(key->hw_key_idx, sc->keymap);
854         if (key->alg != ALG_TKIP)
855                 return;
856
857         clear_bit(key->hw_key_idx + 64, sc->keymap);
858         if (sc->splitmic) {
859                 clear_bit(key->hw_key_idx + 32, sc->keymap);
860                 clear_bit(key->hw_key_idx + 64 + 32, sc->keymap);
861         }
862 }
863
864 static void setup_ht_cap(struct ath_softc *sc,
865                          struct ieee80211_sta_ht_cap *ht_info)
866 {
867 #define ATH9K_HT_CAP_MAXRXAMPDU_65536 0x3       /* 2 ^ 16 */
868 #define ATH9K_HT_CAP_MPDUDENSITY_8 0x6          /* 8 usec */
869
870         ht_info->ht_supported = true;
871         ht_info->cap = IEEE80211_HT_CAP_SUP_WIDTH_20_40 |
872                        IEEE80211_HT_CAP_SM_PS |
873                        IEEE80211_HT_CAP_SGI_40 |
874                        IEEE80211_HT_CAP_DSSSCCK40;
875
876         ht_info->ampdu_factor = ATH9K_HT_CAP_MAXRXAMPDU_65536;
877         ht_info->ampdu_density = ATH9K_HT_CAP_MPDUDENSITY_8;
878
879         /* set up supported mcs set */
880         memset(&ht_info->mcs, 0, sizeof(ht_info->mcs));
881
882         switch(sc->rx_chainmask) {
883         case 1:
884                 ht_info->mcs.rx_mask[0] = 0xff;
885                 break;
886         case 3:
887         case 5:
888         case 7:
889         default:
890                 ht_info->mcs.rx_mask[0] = 0xff;
891                 ht_info->mcs.rx_mask[1] = 0xff;
892                 break;
893         }
894
895         ht_info->mcs.tx_params = IEEE80211_HT_MCS_TX_DEFINED;
896 }
897
898 static void ath9k_bss_assoc_info(struct ath_softc *sc,
899                                  struct ieee80211_vif *vif,
900                                  struct ieee80211_bss_conf *bss_conf)
901 {
902         struct ath_vif *avp = (void *)vif->drv_priv;
903
904         if (bss_conf->assoc) {
905                 DPRINTF(sc, ATH_DBG_CONFIG, "Bss Info ASSOC %d, bssid: %pM\n",
906                         bss_conf->aid, sc->curbssid);
907
908                 /* New association, store aid */
909                 if (avp->av_opmode == NL80211_IFTYPE_STATION) {
910                         sc->curaid = bss_conf->aid;
911                         ath9k_hw_write_associd(sc);
912                 }
913
914                 /* Configure the beacon */
915                 ath_beacon_config(sc, vif);
916
917                 /* Reset rssi stats */
918                 sc->nodestats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
919                 sc->nodestats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
920                 sc->nodestats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
921                 sc->nodestats.ns_avgtxrate = ATH_RATE_DUMMY_MARKER;
922
923                 /* Start ANI */
924                 mod_timer(&sc->ani.timer,
925                           jiffies + msecs_to_jiffies(ATH_ANI_POLLINTERVAL));
926         } else {
927                 DPRINTF(sc, ATH_DBG_CONFIG, "Bss Info DISSOC\n");
928                 sc->curaid = 0;
929         }
930 }
931
932 /********************************/
933 /*       LED functions          */
934 /********************************/
935
936 static void ath_led_blink_work(struct work_struct *work)
937 {
938         struct ath_softc *sc = container_of(work, struct ath_softc,
939                                             ath_led_blink_work.work);
940
941         if (!(sc->sc_flags & SC_OP_LED_ASSOCIATED))
942                 return;
943         ath9k_hw_set_gpio(sc->sc_ah, ATH_LED_PIN,
944                           (sc->sc_flags & SC_OP_LED_ON) ? 1 : 0);
945
946         queue_delayed_work(sc->hw->workqueue, &sc->ath_led_blink_work,
947                            (sc->sc_flags & SC_OP_LED_ON) ?
948                            msecs_to_jiffies(sc->led_off_duration) :
949                            msecs_to_jiffies(sc->led_on_duration));
950
951         sc->led_on_duration =
952                         max((ATH_LED_ON_DURATION_IDLE - sc->led_on_cnt), 25);
953         sc->led_off_duration =
954                         max((ATH_LED_OFF_DURATION_IDLE - sc->led_off_cnt), 10);
955         sc->led_on_cnt = sc->led_off_cnt = 0;
956         if (sc->sc_flags & SC_OP_LED_ON)
957                 sc->sc_flags &= ~SC_OP_LED_ON;
958         else
959                 sc->sc_flags |= SC_OP_LED_ON;
960 }
961
962 static void ath_led_brightness(struct led_classdev *led_cdev,
963                                enum led_brightness brightness)
964 {
965         struct ath_led *led = container_of(led_cdev, struct ath_led, led_cdev);
966         struct ath_softc *sc = led->sc;
967
968         switch (brightness) {
969         case LED_OFF:
970                 if (led->led_type == ATH_LED_ASSOC ||
971                     led->led_type == ATH_LED_RADIO) {
972                         ath9k_hw_set_gpio(sc->sc_ah, ATH_LED_PIN,
973                                 (led->led_type == ATH_LED_RADIO));
974                         sc->sc_flags &= ~SC_OP_LED_ASSOCIATED;
975                         if (led->led_type == ATH_LED_RADIO)
976                                 sc->sc_flags &= ~SC_OP_LED_ON;
977                 } else {
978                         sc->led_off_cnt++;
979                 }
980                 break;
981         case LED_FULL:
982                 if (led->led_type == ATH_LED_ASSOC) {
983                         sc->sc_flags |= SC_OP_LED_ASSOCIATED;
984                         queue_delayed_work(sc->hw->workqueue,
985                                            &sc->ath_led_blink_work, 0);
986                 } else if (led->led_type == ATH_LED_RADIO) {
987                         ath9k_hw_set_gpio(sc->sc_ah, ATH_LED_PIN, 0);
988                         sc->sc_flags |= SC_OP_LED_ON;
989                 } else {
990                         sc->led_on_cnt++;
991                 }
992                 break;
993         default:
994                 break;
995         }
996 }
997
998 static int ath_register_led(struct ath_softc *sc, struct ath_led *led,
999                             char *trigger)
1000 {
1001         int ret;
1002
1003         led->sc = sc;
1004         led->led_cdev.name = led->name;
1005         led->led_cdev.default_trigger = trigger;
1006         led->led_cdev.brightness_set = ath_led_brightness;
1007
1008         ret = led_classdev_register(wiphy_dev(sc->hw->wiphy), &led->led_cdev);
1009         if (ret)
1010                 DPRINTF(sc, ATH_DBG_FATAL,
1011                         "Failed to register led:%s", led->name);
1012         else
1013                 led->registered = 1;
1014         return ret;
1015 }
1016
1017 static void ath_unregister_led(struct ath_led *led)
1018 {
1019         if (led->registered) {
1020                 led_classdev_unregister(&led->led_cdev);
1021                 led->registered = 0;
1022         }
1023 }
1024
1025 static void ath_deinit_leds(struct ath_softc *sc)
1026 {
1027         cancel_delayed_work_sync(&sc->ath_led_blink_work);
1028         ath_unregister_led(&sc->assoc_led);
1029         sc->sc_flags &= ~SC_OP_LED_ASSOCIATED;
1030         ath_unregister_led(&sc->tx_led);
1031         ath_unregister_led(&sc->rx_led);
1032         ath_unregister_led(&sc->radio_led);
1033         ath9k_hw_set_gpio(sc->sc_ah, ATH_LED_PIN, 1);
1034 }
1035
1036 static void ath_init_leds(struct ath_softc *sc)
1037 {
1038         char *trigger;
1039         int ret;
1040
1041         /* Configure gpio 1 for output */
1042         ath9k_hw_cfg_output(sc->sc_ah, ATH_LED_PIN,
1043                             AR_GPIO_OUTPUT_MUX_AS_OUTPUT);
1044         /* LED off, active low */
1045         ath9k_hw_set_gpio(sc->sc_ah, ATH_LED_PIN, 1);
1046
1047         INIT_DELAYED_WORK(&sc->ath_led_blink_work, ath_led_blink_work);
1048
1049         trigger = ieee80211_get_radio_led_name(sc->hw);
1050         snprintf(sc->radio_led.name, sizeof(sc->radio_led.name),
1051                 "ath9k-%s::radio", wiphy_name(sc->hw->wiphy));
1052         ret = ath_register_led(sc, &sc->radio_led, trigger);
1053         sc->radio_led.led_type = ATH_LED_RADIO;
1054         if (ret)
1055                 goto fail;
1056
1057         trigger = ieee80211_get_assoc_led_name(sc->hw);
1058         snprintf(sc->assoc_led.name, sizeof(sc->assoc_led.name),
1059                 "ath9k-%s::assoc", wiphy_name(sc->hw->wiphy));
1060         ret = ath_register_led(sc, &sc->assoc_led, trigger);
1061         sc->assoc_led.led_type = ATH_LED_ASSOC;
1062         if (ret)
1063                 goto fail;
1064
1065         trigger = ieee80211_get_tx_led_name(sc->hw);
1066         snprintf(sc->tx_led.name, sizeof(sc->tx_led.name),
1067                 "ath9k-%s::tx", wiphy_name(sc->hw->wiphy));
1068         ret = ath_register_led(sc, &sc->tx_led, trigger);
1069         sc->tx_led.led_type = ATH_LED_TX;
1070         if (ret)
1071                 goto fail;
1072
1073         trigger = ieee80211_get_rx_led_name(sc->hw);
1074         snprintf(sc->rx_led.name, sizeof(sc->rx_led.name),
1075                 "ath9k-%s::rx", wiphy_name(sc->hw->wiphy));
1076         ret = ath_register_led(sc, &sc->rx_led, trigger);
1077         sc->rx_led.led_type = ATH_LED_RX;
1078         if (ret)
1079                 goto fail;
1080
1081         return;
1082
1083 fail:
1084         ath_deinit_leds(sc);
1085 }
1086
1087 #if defined(CONFIG_RFKILL) || defined(CONFIG_RFKILL_MODULE)
1088
1089 /*******************/
1090 /*      Rfkill     */
1091 /*******************/
1092
1093 void ath_radio_enable(struct ath_softc *sc)
1094 {
1095         struct ath_hw *ah = sc->sc_ah;
1096         struct ieee80211_channel *channel = sc->hw->conf.channel;
1097         int r;
1098
1099         ath9k_ps_wakeup(sc);
1100         spin_lock_bh(&sc->sc_resetlock);
1101
1102         r = ath9k_hw_reset(ah, ah->curchan, false);
1103
1104         if (r) {
1105                 DPRINTF(sc, ATH_DBG_FATAL,
1106                         "Unable to reset channel %u (%uMhz) ",
1107                         "reset status %u\n",
1108                         channel->center_freq, r);
1109         }
1110         spin_unlock_bh(&sc->sc_resetlock);
1111
1112         ath_update_txpow(sc);
1113         if (ath_startrecv(sc) != 0) {
1114                 DPRINTF(sc, ATH_DBG_FATAL,
1115                         "Unable to restart recv logic\n");
1116                 return;
1117         }
1118
1119         if (sc->sc_flags & SC_OP_BEACONS)
1120                 ath_beacon_config(sc, NULL);    /* restart beacons */
1121
1122         /* Re-Enable  interrupts */
1123         ath9k_hw_set_interrupts(ah, sc->imask);
1124
1125         /* Enable LED */
1126         ath9k_hw_cfg_output(ah, ATH_LED_PIN,
1127                             AR_GPIO_OUTPUT_MUX_AS_OUTPUT);
1128         ath9k_hw_set_gpio(ah, ATH_LED_PIN, 0);
1129
1130         ieee80211_wake_queues(sc->hw);
1131         ath9k_ps_restore(sc);
1132 }
1133
1134 void ath_radio_disable(struct ath_softc *sc)
1135 {
1136         struct ath_hw *ah = sc->sc_ah;
1137         struct ieee80211_channel *channel = sc->hw->conf.channel;
1138         int r;
1139
1140         ath9k_ps_wakeup(sc);
1141         ieee80211_stop_queues(sc->hw);
1142
1143         /* Disable LED */
1144         ath9k_hw_set_gpio(ah, ATH_LED_PIN, 1);
1145         ath9k_hw_cfg_gpio_input(ah, ATH_LED_PIN);
1146
1147         /* Disable interrupts */
1148         ath9k_hw_set_interrupts(ah, 0);
1149
1150         ath_drain_all_txq(sc, false);   /* clear pending tx frames */
1151         ath_stoprecv(sc);               /* turn off frame recv */
1152         ath_flushrecv(sc);              /* flush recv queue */
1153
1154         spin_lock_bh(&sc->sc_resetlock);
1155         r = ath9k_hw_reset(ah, ah->curchan, false);
1156         if (r) {
1157                 DPRINTF(sc, ATH_DBG_FATAL,
1158                         "Unable to reset channel %u (%uMhz) "
1159                         "reset status %u\n",
1160                         channel->center_freq, r);
1161         }
1162         spin_unlock_bh(&sc->sc_resetlock);
1163
1164         ath9k_hw_phy_disable(ah);
1165         ath9k_hw_setpower(ah, ATH9K_PM_FULL_SLEEP);
1166         ath9k_ps_restore(sc);
1167 }
1168
1169 static bool ath_is_rfkill_set(struct ath_softc *sc)
1170 {
1171         struct ath_hw *ah = sc->sc_ah;
1172
1173         return ath9k_hw_gpio_get(ah, ah->rfkill_gpio) ==
1174                                   ah->rfkill_polarity;
1175 }
1176
1177 /* h/w rfkill poll function */
1178 static void ath_rfkill_poll(struct work_struct *work)
1179 {
1180         struct ath_softc *sc = container_of(work, struct ath_softc,
1181                                             rf_kill.rfkill_poll.work);
1182         bool radio_on;
1183
1184         if (sc->sc_flags & SC_OP_INVALID)
1185                 return;
1186
1187         radio_on = !ath_is_rfkill_set(sc);
1188
1189         /*
1190          * enable/disable radio only when there is a
1191          * state change in RF switch
1192          */
1193         if (radio_on == !!(sc->sc_flags & SC_OP_RFKILL_HW_BLOCKED)) {
1194                 enum rfkill_state state;
1195
1196                 if (sc->sc_flags & SC_OP_RFKILL_SW_BLOCKED) {
1197                         state = radio_on ? RFKILL_STATE_SOFT_BLOCKED
1198                                 : RFKILL_STATE_HARD_BLOCKED;
1199                 } else if (radio_on) {
1200                         ath_radio_enable(sc);
1201                         state = RFKILL_STATE_UNBLOCKED;
1202                 } else {
1203                         ath_radio_disable(sc);
1204                         state = RFKILL_STATE_HARD_BLOCKED;
1205                 }
1206
1207                 if (state == RFKILL_STATE_HARD_BLOCKED)
1208                         sc->sc_flags |= SC_OP_RFKILL_HW_BLOCKED;
1209                 else
1210                         sc->sc_flags &= ~SC_OP_RFKILL_HW_BLOCKED;
1211
1212                 rfkill_force_state(sc->rf_kill.rfkill, state);
1213         }
1214
1215         queue_delayed_work(sc->hw->workqueue, &sc->rf_kill.rfkill_poll,
1216                            msecs_to_jiffies(ATH_RFKILL_POLL_INTERVAL));
1217 }
1218
1219 /* s/w rfkill handler */
1220 static int ath_sw_toggle_radio(void *data, enum rfkill_state state)
1221 {
1222         struct ath_softc *sc = data;
1223
1224         switch (state) {
1225         case RFKILL_STATE_SOFT_BLOCKED:
1226                 if (!(sc->sc_flags & (SC_OP_RFKILL_HW_BLOCKED |
1227                     SC_OP_RFKILL_SW_BLOCKED)))
1228                         ath_radio_disable(sc);
1229                 sc->sc_flags |= SC_OP_RFKILL_SW_BLOCKED;
1230                 return 0;
1231         case RFKILL_STATE_UNBLOCKED:
1232                 if ((sc->sc_flags & SC_OP_RFKILL_SW_BLOCKED)) {
1233                         sc->sc_flags &= ~SC_OP_RFKILL_SW_BLOCKED;
1234                         if (sc->sc_flags & SC_OP_RFKILL_HW_BLOCKED) {
1235                                 DPRINTF(sc, ATH_DBG_FATAL, "Can't turn on the"
1236                                         "radio as it is disabled by h/w\n");
1237                                 return -EPERM;
1238                         }
1239                         ath_radio_enable(sc);
1240                 }
1241                 return 0;
1242         default:
1243                 return -EINVAL;
1244         }
1245 }
1246
1247 /* Init s/w rfkill */
1248 static int ath_init_sw_rfkill(struct ath_softc *sc)
1249 {
1250         sc->rf_kill.rfkill = rfkill_allocate(wiphy_dev(sc->hw->wiphy),
1251                                              RFKILL_TYPE_WLAN);
1252         if (!sc->rf_kill.rfkill) {
1253                 DPRINTF(sc, ATH_DBG_FATAL, "Failed to allocate rfkill\n");
1254                 return -ENOMEM;
1255         }
1256
1257         snprintf(sc->rf_kill.rfkill_name, sizeof(sc->rf_kill.rfkill_name),
1258                 "ath9k-%s::rfkill", wiphy_name(sc->hw->wiphy));
1259         sc->rf_kill.rfkill->name = sc->rf_kill.rfkill_name;
1260         sc->rf_kill.rfkill->data = sc;
1261         sc->rf_kill.rfkill->toggle_radio = ath_sw_toggle_radio;
1262         sc->rf_kill.rfkill->state = RFKILL_STATE_UNBLOCKED;
1263         sc->rf_kill.rfkill->user_claim_unsupported = 1;
1264
1265         return 0;
1266 }
1267
1268 /* Deinitialize rfkill */
1269 static void ath_deinit_rfkill(struct ath_softc *sc)
1270 {
1271         if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_RFSILENT)
1272                 cancel_delayed_work_sync(&sc->rf_kill.rfkill_poll);
1273
1274         if (sc->sc_flags & SC_OP_RFKILL_REGISTERED) {
1275                 rfkill_unregister(sc->rf_kill.rfkill);
1276                 sc->sc_flags &= ~SC_OP_RFKILL_REGISTERED;
1277                 sc->rf_kill.rfkill = NULL;
1278         }
1279 }
1280
1281 static int ath_start_rfkill_poll(struct ath_softc *sc)
1282 {
1283         if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_RFSILENT)
1284                 queue_delayed_work(sc->hw->workqueue,
1285                                    &sc->rf_kill.rfkill_poll, 0);
1286
1287         if (!(sc->sc_flags & SC_OP_RFKILL_REGISTERED)) {
1288                 if (rfkill_register(sc->rf_kill.rfkill)) {
1289                         DPRINTF(sc, ATH_DBG_FATAL,
1290                                 "Unable to register rfkill\n");
1291                         rfkill_free(sc->rf_kill.rfkill);
1292
1293                         /* Deinitialize the device */
1294                         ath_cleanup(sc);
1295                         return -EIO;
1296                 } else {
1297                         sc->sc_flags |= SC_OP_RFKILL_REGISTERED;
1298                 }
1299         }
1300
1301         return 0;
1302 }
1303 #endif /* CONFIG_RFKILL */
1304
1305 void ath_cleanup(struct ath_softc *sc)
1306 {
1307         ath_detach(sc);
1308         free_irq(sc->irq, sc);
1309         ath_bus_cleanup(sc);
1310         kfree(sc->sec_wiphy);
1311         ieee80211_free_hw(sc->hw);
1312 }
1313
1314 void ath_detach(struct ath_softc *sc)
1315 {
1316         struct ieee80211_hw *hw = sc->hw;
1317         int i = 0;
1318
1319         ath9k_ps_wakeup(sc);
1320
1321         DPRINTF(sc, ATH_DBG_CONFIG, "Detach ATH hw\n");
1322
1323 #if defined(CONFIG_RFKILL) || defined(CONFIG_RFKILL_MODULE)
1324         ath_deinit_rfkill(sc);
1325 #endif
1326         ath_deinit_leds(sc);
1327         cancel_work_sync(&sc->chan_work);
1328
1329         for (i = 0; i < sc->num_sec_wiphy; i++) {
1330                 struct ath_wiphy *aphy = sc->sec_wiphy[i];
1331                 if (aphy == NULL)
1332                         continue;
1333                 sc->sec_wiphy[i] = NULL;
1334                 ieee80211_unregister_hw(aphy->hw);
1335                 ieee80211_free_hw(aphy->hw);
1336         }
1337         ieee80211_unregister_hw(hw);
1338         ath_rx_cleanup(sc);
1339         ath_tx_cleanup(sc);
1340
1341         tasklet_kill(&sc->intr_tq);
1342         tasklet_kill(&sc->bcon_tasklet);
1343
1344         if (!(sc->sc_flags & SC_OP_INVALID))
1345                 ath9k_hw_setpower(sc->sc_ah, ATH9K_PM_AWAKE);
1346
1347         /* cleanup tx queues */
1348         for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++)
1349                 if (ATH_TXQ_SETUP(sc, i))
1350                         ath_tx_cleanupq(sc, &sc->tx.txq[i]);
1351
1352         ath9k_hw_detach(sc->sc_ah);
1353         ath9k_exit_debug(sc);
1354         ath9k_ps_restore(sc);
1355 }
1356
1357 static int ath_init(u16 devid, struct ath_softc *sc)
1358 {
1359         struct ath_hw *ah = NULL;
1360         int status;
1361         int error = 0, i;
1362         int csz = 0;
1363
1364         /* XXX: hardware will not be ready until ath_open() being called */
1365         sc->sc_flags |= SC_OP_INVALID;
1366
1367         if (ath9k_init_debug(sc) < 0)
1368                 printk(KERN_ERR "Unable to create debugfs files\n");
1369
1370         spin_lock_init(&sc->wiphy_lock);
1371         spin_lock_init(&sc->sc_resetlock);
1372         mutex_init(&sc->mutex);
1373         tasklet_init(&sc->intr_tq, ath9k_tasklet, (unsigned long)sc);
1374         tasklet_init(&sc->bcon_tasklet, ath_beacon_tasklet,
1375                      (unsigned long)sc);
1376
1377         /*
1378          * Cache line size is used to size and align various
1379          * structures used to communicate with the hardware.
1380          */
1381         ath_read_cachesize(sc, &csz);
1382         /* XXX assert csz is non-zero */
1383         sc->cachelsz = csz << 2;        /* convert to bytes */
1384
1385         ah = ath9k_hw_attach(devid, sc, &status);
1386         if (ah == NULL) {
1387                 DPRINTF(sc, ATH_DBG_FATAL,
1388                         "Unable to attach hardware; HAL status %d\n", status);
1389                 error = -ENXIO;
1390                 goto bad;
1391         }
1392         sc->sc_ah = ah;
1393
1394         /* Get the hardware key cache size. */
1395         sc->keymax = ah->caps.keycache_size;
1396         if (sc->keymax > ATH_KEYMAX) {
1397                 DPRINTF(sc, ATH_DBG_KEYCACHE,
1398                         "Warning, using only %u entries in %u key cache\n",
1399                         ATH_KEYMAX, sc->keymax);
1400                 sc->keymax = ATH_KEYMAX;
1401         }
1402
1403         /*
1404          * Reset the key cache since some parts do not
1405          * reset the contents on initial power up.
1406          */
1407         for (i = 0; i < sc->keymax; i++)
1408                 ath9k_hw_keyreset(ah, (u16) i);
1409
1410         if (ath9k_regd_init(sc->sc_ah))
1411                 goto bad;
1412
1413         /* default to MONITOR mode */
1414         sc->sc_ah->opmode = NL80211_IFTYPE_MONITOR;
1415
1416         /* Setup rate tables */
1417
1418         ath_rate_attach(sc);
1419         ath_setup_rates(sc, IEEE80211_BAND_2GHZ);
1420         ath_setup_rates(sc, IEEE80211_BAND_5GHZ);
1421
1422         /*
1423          * Allocate hardware transmit queues: one queue for
1424          * beacon frames and one data queue for each QoS
1425          * priority.  Note that the hal handles reseting
1426          * these queues at the needed time.
1427          */
1428         sc->beacon.beaconq = ath_beaconq_setup(ah);
1429         if (sc->beacon.beaconq == -1) {
1430                 DPRINTF(sc, ATH_DBG_FATAL,
1431                         "Unable to setup a beacon xmit queue\n");
1432                 error = -EIO;
1433                 goto bad2;
1434         }
1435         sc->beacon.cabq = ath_txq_setup(sc, ATH9K_TX_QUEUE_CAB, 0);
1436         if (sc->beacon.cabq == NULL) {
1437                 DPRINTF(sc, ATH_DBG_FATAL,
1438                         "Unable to setup CAB xmit queue\n");
1439                 error = -EIO;
1440                 goto bad2;
1441         }
1442
1443         sc->config.cabqReadytime = ATH_CABQ_READY_TIME;
1444         ath_cabq_update(sc);
1445
1446         for (i = 0; i < ARRAY_SIZE(sc->tx.hwq_map); i++)
1447                 sc->tx.hwq_map[i] = -1;
1448
1449         /* Setup data queues */
1450         /* NB: ensure BK queue is the lowest priority h/w queue */
1451         if (!ath_tx_setup(sc, ATH9K_WME_AC_BK)) {
1452                 DPRINTF(sc, ATH_DBG_FATAL,
1453                         "Unable to setup xmit queue for BK traffic\n");
1454                 error = -EIO;
1455                 goto bad2;
1456         }
1457
1458         if (!ath_tx_setup(sc, ATH9K_WME_AC_BE)) {
1459                 DPRINTF(sc, ATH_DBG_FATAL,
1460                         "Unable to setup xmit queue for BE traffic\n");
1461                 error = -EIO;
1462                 goto bad2;
1463         }
1464         if (!ath_tx_setup(sc, ATH9K_WME_AC_VI)) {
1465                 DPRINTF(sc, ATH_DBG_FATAL,
1466                         "Unable to setup xmit queue for VI traffic\n");
1467                 error = -EIO;
1468                 goto bad2;
1469         }
1470         if (!ath_tx_setup(sc, ATH9K_WME_AC_VO)) {
1471                 DPRINTF(sc, ATH_DBG_FATAL,
1472                         "Unable to setup xmit queue for VO traffic\n");
1473                 error = -EIO;
1474                 goto bad2;
1475         }
1476
1477         /* Initializes the noise floor to a reasonable default value.
1478          * Later on this will be updated during ANI processing. */
1479
1480         sc->ani.noise_floor = ATH_DEFAULT_NOISE_FLOOR;
1481         setup_timer(&sc->ani.timer, ath_ani_calibrate, (unsigned long)sc);
1482
1483         if (ath9k_hw_getcapability(ah, ATH9K_CAP_CIPHER,
1484                                    ATH9K_CIPHER_TKIP, NULL)) {
1485                 /*
1486                  * Whether we should enable h/w TKIP MIC.
1487                  * XXX: if we don't support WME TKIP MIC, then we wouldn't
1488                  * report WMM capable, so it's always safe to turn on
1489                  * TKIP MIC in this case.
1490                  */
1491                 ath9k_hw_setcapability(sc->sc_ah, ATH9K_CAP_TKIP_MIC,
1492                                        0, 1, NULL);
1493         }
1494
1495         /*
1496          * Check whether the separate key cache entries
1497          * are required to handle both tx+rx MIC keys.
1498          * With split mic keys the number of stations is limited
1499          * to 27 otherwise 59.
1500          */
1501         if (ath9k_hw_getcapability(ah, ATH9K_CAP_CIPHER,
1502                                    ATH9K_CIPHER_TKIP, NULL)
1503             && ath9k_hw_getcapability(ah, ATH9K_CAP_CIPHER,
1504                                       ATH9K_CIPHER_MIC, NULL)
1505             && ath9k_hw_getcapability(ah, ATH9K_CAP_TKIP_SPLIT,
1506                                       0, NULL))
1507                 sc->splitmic = 1;
1508
1509         /* turn on mcast key search if possible */
1510         if (!ath9k_hw_getcapability(ah, ATH9K_CAP_MCAST_KEYSRCH, 0, NULL))
1511                 (void)ath9k_hw_setcapability(ah, ATH9K_CAP_MCAST_KEYSRCH, 1,
1512                                              1, NULL);
1513
1514         sc->config.txpowlimit = ATH_TXPOWER_MAX;
1515
1516         /* 11n Capabilities */
1517         if (ah->caps.hw_caps & ATH9K_HW_CAP_HT) {
1518                 sc->sc_flags |= SC_OP_TXAGGR;
1519                 sc->sc_flags |= SC_OP_RXAGGR;
1520         }
1521
1522         sc->tx_chainmask = ah->caps.tx_chainmask;
1523         sc->rx_chainmask = ah->caps.rx_chainmask;
1524
1525         ath9k_hw_setcapability(ah, ATH9K_CAP_DIVERSITY, 1, true, NULL);
1526         sc->rx.defant = ath9k_hw_getdefantenna(ah);
1527
1528         if (ah->caps.hw_caps & ATH9K_HW_CAP_BSSIDMASK)
1529                 memcpy(sc->bssidmask, ath_bcast_mac, ETH_ALEN);
1530
1531         sc->beacon.slottime = ATH9K_SLOT_TIME_9;        /* default to short slot time */
1532
1533         /* initialize beacon slots */
1534         for (i = 0; i < ARRAY_SIZE(sc->beacon.bslot); i++) {
1535                 sc->beacon.bslot[i] = NULL;
1536                 sc->beacon.bslot_aphy[i] = NULL;
1537         }
1538
1539         /* save MISC configurations */
1540         sc->config.swBeaconProcess = 1;
1541
1542         /* setup channels and rates */
1543
1544         sc->sbands[IEEE80211_BAND_2GHZ].channels = ath9k_2ghz_chantable;
1545         sc->sbands[IEEE80211_BAND_2GHZ].bitrates =
1546                 sc->rates[IEEE80211_BAND_2GHZ];
1547         sc->sbands[IEEE80211_BAND_2GHZ].band = IEEE80211_BAND_2GHZ;
1548         sc->sbands[IEEE80211_BAND_2GHZ].n_channels =
1549                 ARRAY_SIZE(ath9k_2ghz_chantable);
1550
1551         if (test_bit(ATH9K_MODE_11A, sc->sc_ah->caps.wireless_modes)) {
1552                 sc->sbands[IEEE80211_BAND_5GHZ].channels = ath9k_5ghz_chantable;
1553                 sc->sbands[IEEE80211_BAND_5GHZ].bitrates =
1554                         sc->rates[IEEE80211_BAND_5GHZ];
1555                 sc->sbands[IEEE80211_BAND_5GHZ].band = IEEE80211_BAND_5GHZ;
1556                 sc->sbands[IEEE80211_BAND_5GHZ].n_channels =
1557                         ARRAY_SIZE(ath9k_5ghz_chantable);
1558         }
1559
1560         if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_BT_COEX)
1561                 ath9k_hw_btcoex_enable(sc->sc_ah);
1562
1563         return 0;
1564 bad2:
1565         /* cleanup tx queues */
1566         for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++)
1567                 if (ATH_TXQ_SETUP(sc, i))
1568                         ath_tx_cleanupq(sc, &sc->tx.txq[i]);
1569 bad:
1570         if (ah)
1571                 ath9k_hw_detach(ah);
1572         ath9k_exit_debug(sc);
1573
1574         return error;
1575 }
1576
1577 void ath_set_hw_capab(struct ath_softc *sc, struct ieee80211_hw *hw)
1578 {
1579         hw->flags = IEEE80211_HW_RX_INCLUDES_FCS |
1580                 IEEE80211_HW_HOST_BROADCAST_PS_BUFFERING |
1581                 IEEE80211_HW_SIGNAL_DBM |
1582                 IEEE80211_HW_AMPDU_AGGREGATION |
1583                 IEEE80211_HW_SUPPORTS_PS |
1584                 IEEE80211_HW_PS_NULLFUNC_STACK;
1585
1586         if (AR_SREV_9160_10_OR_LATER(sc->sc_ah) || modparam_nohwcrypt)
1587                 hw->flags |= IEEE80211_HW_MFP_CAPABLE;
1588
1589         hw->wiphy->interface_modes =
1590                 BIT(NL80211_IFTYPE_AP) |
1591                 BIT(NL80211_IFTYPE_STATION) |
1592                 BIT(NL80211_IFTYPE_ADHOC);
1593
1594         hw->wiphy->reg_notifier = ath9k_reg_notifier;
1595         hw->wiphy->strict_regulatory = true;
1596
1597         hw->queues = 4;
1598         hw->max_rates = 4;
1599         hw->channel_change_time = 5000;
1600         hw->max_listen_interval = 10;
1601         hw->max_rate_tries = ATH_11N_TXMAXTRY;
1602         hw->sta_data_size = sizeof(struct ath_node);
1603         hw->vif_data_size = sizeof(struct ath_vif);
1604
1605         hw->rate_control_algorithm = "ath9k_rate_control";
1606
1607         hw->wiphy->bands[IEEE80211_BAND_2GHZ] =
1608                 &sc->sbands[IEEE80211_BAND_2GHZ];
1609         if (test_bit(ATH9K_MODE_11A, sc->sc_ah->caps.wireless_modes))
1610                 hw->wiphy->bands[IEEE80211_BAND_5GHZ] =
1611                         &sc->sbands[IEEE80211_BAND_5GHZ];
1612 }
1613
1614 int ath_attach(u16 devid, struct ath_softc *sc)
1615 {
1616         struct ieee80211_hw *hw = sc->hw;
1617         const struct ieee80211_regdomain *regd;
1618         int error = 0, i;
1619
1620         DPRINTF(sc, ATH_DBG_CONFIG, "Attach ATH hw\n");
1621
1622         error = ath_init(devid, sc);
1623         if (error != 0)
1624                 return error;
1625
1626         /* get mac address from hardware and set in mac80211 */
1627
1628         SET_IEEE80211_PERM_ADDR(hw, sc->sc_ah->macaddr);
1629
1630         ath_set_hw_capab(sc, hw);
1631
1632         if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_HT) {
1633                 setup_ht_cap(sc, &sc->sbands[IEEE80211_BAND_2GHZ].ht_cap);
1634                 if (test_bit(ATH9K_MODE_11A, sc->sc_ah->caps.wireless_modes))
1635                         setup_ht_cap(sc, &sc->sbands[IEEE80211_BAND_5GHZ].ht_cap);
1636         }
1637
1638         /* initialize tx/rx engine */
1639         error = ath_tx_init(sc, ATH_TXBUF);
1640         if (error != 0)
1641                 goto error_attach;
1642
1643         error = ath_rx_init(sc, ATH_RXBUF);
1644         if (error != 0)
1645                 goto error_attach;
1646
1647 #if defined(CONFIG_RFKILL) || defined(CONFIG_RFKILL_MODULE)
1648         /* Initialze h/w Rfkill */
1649         if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_RFSILENT)
1650                 INIT_DELAYED_WORK(&sc->rf_kill.rfkill_poll, ath_rfkill_poll);
1651
1652         /* Initialize s/w rfkill */
1653         error = ath_init_sw_rfkill(sc);
1654         if (error)
1655                 goto error_attach;
1656 #endif
1657
1658         if (ath9k_is_world_regd(sc->sc_ah)) {
1659                 /* Anything applied here (prior to wiphy registration) gets
1660                  * saved on the wiphy orig_* parameters */
1661                 regd = ath9k_world_regdomain(sc->sc_ah);
1662                 hw->wiphy->custom_regulatory = true;
1663                 hw->wiphy->strict_regulatory = false;
1664         } else {
1665                 /* This gets applied in the case of the absense of CRDA,
1666                  * it's our own custom world regulatory domain, similar to
1667                  * cfg80211's but we enable passive scanning */
1668                 regd = ath9k_default_world_regdomain();
1669         }
1670         wiphy_apply_custom_regulatory(hw->wiphy, regd);
1671         ath9k_reg_apply_radar_flags(hw->wiphy);
1672         ath9k_reg_apply_world_flags(hw->wiphy, REGDOM_SET_BY_INIT);
1673
1674         INIT_WORK(&sc->chan_work, ath9k_wiphy_chan_work);
1675
1676         error = ieee80211_register_hw(hw);
1677
1678         if (!ath9k_is_world_regd(sc->sc_ah)) {
1679                 error = regulatory_hint(hw->wiphy,
1680                         sc->sc_ah->regulatory.alpha2);
1681                 if (error)
1682                         goto error_attach;
1683         }
1684
1685         /* Initialize LED control */
1686         ath_init_leds(sc);
1687
1688
1689         return 0;
1690
1691 error_attach:
1692         /* cleanup tx queues */
1693         for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++)
1694                 if (ATH_TXQ_SETUP(sc, i))
1695                         ath_tx_cleanupq(sc, &sc->tx.txq[i]);
1696
1697         ath9k_hw_detach(sc->sc_ah);
1698         ath9k_exit_debug(sc);
1699
1700         return error;
1701 }
1702
1703 int ath_reset(struct ath_softc *sc, bool retry_tx)
1704 {
1705         struct ath_hw *ah = sc->sc_ah;
1706         struct ieee80211_hw *hw = sc->hw;
1707         int r;
1708
1709         ath9k_hw_set_interrupts(ah, 0);
1710         ath_drain_all_txq(sc, retry_tx);
1711         ath_stoprecv(sc);
1712         ath_flushrecv(sc);
1713
1714         spin_lock_bh(&sc->sc_resetlock);
1715         r = ath9k_hw_reset(ah, sc->sc_ah->curchan, false);
1716         if (r)
1717                 DPRINTF(sc, ATH_DBG_FATAL,
1718                         "Unable to reset hardware; reset status %u\n", r);
1719         spin_unlock_bh(&sc->sc_resetlock);
1720
1721         if (ath_startrecv(sc) != 0)
1722                 DPRINTF(sc, ATH_DBG_FATAL, "Unable to start recv logic\n");
1723
1724         /*
1725          * We may be doing a reset in response to a request
1726          * that changes the channel so update any state that
1727          * might change as a result.
1728          */
1729         ath_cache_conf_rate(sc, &hw->conf);
1730
1731         ath_update_txpow(sc);
1732
1733         if (sc->sc_flags & SC_OP_BEACONS)
1734                 ath_beacon_config(sc, NULL);    /* restart beacons */
1735
1736         ath9k_hw_set_interrupts(ah, sc->imask);
1737
1738         if (retry_tx) {
1739                 int i;
1740                 for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++) {
1741                         if (ATH_TXQ_SETUP(sc, i)) {
1742                                 spin_lock_bh(&sc->tx.txq[i].axq_lock);
1743                                 ath_txq_schedule(sc, &sc->tx.txq[i]);
1744                                 spin_unlock_bh(&sc->tx.txq[i].axq_lock);
1745                         }
1746                 }
1747         }
1748
1749         return r;
1750 }
1751
1752 /*
1753  *  This function will allocate both the DMA descriptor structure, and the
1754  *  buffers it contains.  These are used to contain the descriptors used
1755  *  by the system.
1756 */
1757 int ath_descdma_setup(struct ath_softc *sc, struct ath_descdma *dd,
1758                       struct list_head *head, const char *name,
1759                       int nbuf, int ndesc)
1760 {
1761 #define DS2PHYS(_dd, _ds)                                               \
1762         ((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
1763 #define ATH_DESC_4KB_BOUND_CHECK(_daddr) ((((_daddr) & 0xFFF) > 0xF7F) ? 1 : 0)
1764 #define ATH_DESC_4KB_BOUND_NUM_SKIPPED(_len) ((_len) / 4096)
1765
1766         struct ath_desc *ds;
1767         struct ath_buf *bf;
1768         int i, bsize, error;
1769
1770         DPRINTF(sc, ATH_DBG_CONFIG, "%s DMA: %u buffers %u desc/buf\n",
1771                 name, nbuf, ndesc);
1772
1773         /* ath_desc must be a multiple of DWORDs */
1774         if ((sizeof(struct ath_desc) % 4) != 0) {
1775                 DPRINTF(sc, ATH_DBG_FATAL, "ath_desc not DWORD aligned\n");
1776                 ASSERT((sizeof(struct ath_desc) % 4) == 0);
1777                 error = -ENOMEM;
1778                 goto fail;
1779         }
1780
1781         dd->dd_name = name;
1782         dd->dd_desc_len = sizeof(struct ath_desc) * nbuf * ndesc;
1783
1784         /*
1785          * Need additional DMA memory because we can't use
1786          * descriptors that cross the 4K page boundary. Assume
1787          * one skipped descriptor per 4K page.
1788          */
1789         if (!(sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_4KB_SPLITTRANS)) {
1790                 u32 ndesc_skipped =
1791                         ATH_DESC_4KB_BOUND_NUM_SKIPPED(dd->dd_desc_len);
1792                 u32 dma_len;
1793
1794                 while (ndesc_skipped) {
1795                         dma_len = ndesc_skipped * sizeof(struct ath_desc);
1796                         dd->dd_desc_len += dma_len;
1797
1798                         ndesc_skipped = ATH_DESC_4KB_BOUND_NUM_SKIPPED(dma_len);
1799                 };
1800         }
1801
1802         /* allocate descriptors */
1803         dd->dd_desc = dma_alloc_coherent(sc->dev, dd->dd_desc_len,
1804                                          &dd->dd_desc_paddr, GFP_ATOMIC);
1805         if (dd->dd_desc == NULL) {
1806                 error = -ENOMEM;
1807                 goto fail;
1808         }
1809         ds = dd->dd_desc;
1810         DPRINTF(sc, ATH_DBG_CONFIG, "%s DMA map: %p (%u) -> %llx (%u)\n",
1811                 dd->dd_name, ds, (u32) dd->dd_desc_len,
1812                 ito64(dd->dd_desc_paddr), /*XXX*/(u32) dd->dd_desc_len);
1813
1814         /* allocate buffers */
1815         bsize = sizeof(struct ath_buf) * nbuf;
1816         bf = kmalloc(bsize, GFP_KERNEL);
1817         if (bf == NULL) {
1818                 error = -ENOMEM;
1819                 goto fail2;
1820         }
1821         memset(bf, 0, bsize);
1822         dd->dd_bufptr = bf;
1823
1824         INIT_LIST_HEAD(head);
1825         for (i = 0; i < nbuf; i++, bf++, ds += ndesc) {
1826                 bf->bf_desc = ds;
1827                 bf->bf_daddr = DS2PHYS(dd, ds);
1828
1829                 if (!(sc->sc_ah->caps.hw_caps &
1830                       ATH9K_HW_CAP_4KB_SPLITTRANS)) {
1831                         /*
1832                          * Skip descriptor addresses which can cause 4KB
1833                          * boundary crossing (addr + length) with a 32 dword
1834                          * descriptor fetch.
1835                          */
1836                         while (ATH_DESC_4KB_BOUND_CHECK(bf->bf_daddr)) {
1837                                 ASSERT((caddr_t) bf->bf_desc <
1838                                        ((caddr_t) dd->dd_desc +
1839                                         dd->dd_desc_len));
1840
1841                                 ds += ndesc;
1842                                 bf->bf_desc = ds;
1843                                 bf->bf_daddr = DS2PHYS(dd, ds);
1844                         }
1845                 }
1846                 list_add_tail(&bf->list, head);
1847         }
1848         return 0;
1849 fail2:
1850         dma_free_coherent(sc->dev, dd->dd_desc_len, dd->dd_desc,
1851                           dd->dd_desc_paddr);
1852 fail:
1853         memset(dd, 0, sizeof(*dd));
1854         return error;
1855 #undef ATH_DESC_4KB_BOUND_CHECK
1856 #undef ATH_DESC_4KB_BOUND_NUM_SKIPPED
1857 #undef DS2PHYS
1858 }
1859
1860 void ath_descdma_cleanup(struct ath_softc *sc,
1861                          struct ath_descdma *dd,
1862                          struct list_head *head)
1863 {
1864         dma_free_coherent(sc->dev, dd->dd_desc_len, dd->dd_desc,
1865                           dd->dd_desc_paddr);
1866
1867         INIT_LIST_HEAD(head);
1868         kfree(dd->dd_bufptr);
1869         memset(dd, 0, sizeof(*dd));
1870 }
1871
1872 int ath_get_hal_qnum(u16 queue, struct ath_softc *sc)
1873 {
1874         int qnum;
1875
1876         switch (queue) {
1877         case 0:
1878                 qnum = sc->tx.hwq_map[ATH9K_WME_AC_VO];
1879                 break;
1880         case 1:
1881                 qnum = sc->tx.hwq_map[ATH9K_WME_AC_VI];
1882                 break;
1883         case 2:
1884                 qnum = sc->tx.hwq_map[ATH9K_WME_AC_BE];
1885                 break;
1886         case 3:
1887                 qnum = sc->tx.hwq_map[ATH9K_WME_AC_BK];
1888                 break;
1889         default:
1890                 qnum = sc->tx.hwq_map[ATH9K_WME_AC_BE];
1891                 break;
1892         }
1893
1894         return qnum;
1895 }
1896
1897 int ath_get_mac80211_qnum(u32 queue, struct ath_softc *sc)
1898 {
1899         int qnum;
1900
1901         switch (queue) {
1902         case ATH9K_WME_AC_VO:
1903                 qnum = 0;
1904                 break;
1905         case ATH9K_WME_AC_VI:
1906                 qnum = 1;
1907                 break;
1908         case ATH9K_WME_AC_BE:
1909                 qnum = 2;
1910                 break;
1911         case ATH9K_WME_AC_BK:
1912                 qnum = 3;
1913                 break;
1914         default:
1915                 qnum = -1;
1916                 break;
1917         }
1918
1919         return qnum;
1920 }
1921
1922 /* XXX: Remove me once we don't depend on ath9k_channel for all
1923  * this redundant data */
1924 void ath9k_update_ichannel(struct ath_softc *sc, struct ieee80211_hw *hw,
1925                            struct ath9k_channel *ichan)
1926 {
1927         struct ieee80211_channel *chan = hw->conf.channel;
1928         struct ieee80211_conf *conf = &hw->conf;
1929
1930         ichan->channel = chan->center_freq;
1931         ichan->chan = chan;
1932
1933         if (chan->band == IEEE80211_BAND_2GHZ) {
1934                 ichan->chanmode = CHANNEL_G;
1935                 ichan->channelFlags = CHANNEL_2GHZ | CHANNEL_OFDM;
1936         } else {
1937                 ichan->chanmode = CHANNEL_A;
1938                 ichan->channelFlags = CHANNEL_5GHZ | CHANNEL_OFDM;
1939         }
1940
1941         sc->tx_chan_width = ATH9K_HT_MACMODE_20;
1942
1943         if (conf_is_ht(conf)) {
1944                 if (conf_is_ht40(conf))
1945                         sc->tx_chan_width = ATH9K_HT_MACMODE_2040;
1946
1947                 ichan->chanmode = ath_get_extchanmode(sc, chan,
1948                                             conf->channel_type);
1949         }
1950 }
1951
1952 /**********************/
1953 /* mac80211 callbacks */
1954 /**********************/
1955
1956 static int ath9k_start(struct ieee80211_hw *hw)
1957 {
1958         struct ath_wiphy *aphy = hw->priv;
1959         struct ath_softc *sc = aphy->sc;
1960         struct ieee80211_channel *curchan = hw->conf.channel;
1961         struct ath9k_channel *init_channel;
1962         int r, pos;
1963
1964         DPRINTF(sc, ATH_DBG_CONFIG, "Starting driver with "
1965                 "initial channel: %d MHz\n", curchan->center_freq);
1966
1967         mutex_lock(&sc->mutex);
1968
1969         if (ath9k_wiphy_started(sc)) {
1970                 if (sc->chan_idx == curchan->hw_value) {
1971                         /*
1972                          * Already on the operational channel, the new wiphy
1973                          * can be marked active.
1974                          */
1975                         aphy->state = ATH_WIPHY_ACTIVE;
1976                         ieee80211_wake_queues(hw);
1977                 } else {
1978                         /*
1979                          * Another wiphy is on another channel, start the new
1980                          * wiphy in paused state.
1981                          */
1982                         aphy->state = ATH_WIPHY_PAUSED;
1983                         ieee80211_stop_queues(hw);
1984                 }
1985                 mutex_unlock(&sc->mutex);
1986                 return 0;
1987         }
1988         aphy->state = ATH_WIPHY_ACTIVE;
1989
1990         /* setup initial channel */
1991
1992         pos = curchan->hw_value;
1993
1994         sc->chan_idx = pos;
1995         init_channel = &sc->sc_ah->channels[pos];
1996         ath9k_update_ichannel(sc, hw, init_channel);
1997
1998         /* Reset SERDES registers */
1999         ath9k_hw_configpcipowersave(sc->sc_ah, 0);
2000
2001         /*
2002          * The basic interface to setting the hardware in a good
2003          * state is ``reset''.  On return the hardware is known to
2004          * be powered up and with interrupts disabled.  This must
2005          * be followed by initialization of the appropriate bits
2006          * and then setup of the interrupt mask.
2007          */
2008         spin_lock_bh(&sc->sc_resetlock);
2009         r = ath9k_hw_reset(sc->sc_ah, init_channel, false);
2010         if (r) {
2011                 DPRINTF(sc, ATH_DBG_FATAL,
2012                         "Unable to reset hardware; reset status %u "
2013                         "(freq %u MHz)\n", r,
2014                         curchan->center_freq);
2015                 spin_unlock_bh(&sc->sc_resetlock);
2016                 goto mutex_unlock;
2017         }
2018         spin_unlock_bh(&sc->sc_resetlock);
2019
2020         /*
2021          * This is needed only to setup initial state
2022          * but it's best done after a reset.
2023          */
2024         ath_update_txpow(sc);
2025
2026         /*
2027          * Setup the hardware after reset:
2028          * The receive engine is set going.
2029          * Frame transmit is handled entirely
2030          * in the frame output path; there's nothing to do
2031          * here except setup the interrupt mask.
2032          */
2033         if (ath_startrecv(sc) != 0) {
2034                 DPRINTF(sc, ATH_DBG_FATAL,
2035                         "Unable to start recv logic\n");
2036                 r = -EIO;
2037                 goto mutex_unlock;
2038         }
2039
2040         /* Setup our intr mask. */
2041         sc->imask = ATH9K_INT_RX | ATH9K_INT_TX
2042                 | ATH9K_INT_RXEOL | ATH9K_INT_RXORN
2043                 | ATH9K_INT_FATAL | ATH9K_INT_GLOBAL;
2044
2045         if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_GTT)
2046                 sc->imask |= ATH9K_INT_GTT;
2047
2048         if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_HT)
2049                 sc->imask |= ATH9K_INT_CST;
2050
2051         ath_cache_conf_rate(sc, &hw->conf);
2052
2053         sc->sc_flags &= ~SC_OP_INVALID;
2054
2055         /* Disable BMISS interrupt when we're not associated */
2056         sc->imask &= ~(ATH9K_INT_SWBA | ATH9K_INT_BMISS);
2057         ath9k_hw_set_interrupts(sc->sc_ah, sc->imask);
2058
2059         ieee80211_wake_queues(hw);
2060
2061 #if defined(CONFIG_RFKILL) || defined(CONFIG_RFKILL_MODULE)
2062         r = ath_start_rfkill_poll(sc);
2063 #endif
2064
2065 mutex_unlock:
2066         mutex_unlock(&sc->mutex);
2067
2068         return r;
2069 }
2070
2071 static int ath9k_tx(struct ieee80211_hw *hw,
2072                     struct sk_buff *skb)
2073 {
2074         struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
2075         struct ath_wiphy *aphy = hw->priv;
2076         struct ath_softc *sc = aphy->sc;
2077         struct ath_tx_control txctl;
2078         int hdrlen, padsize;
2079
2080         if (aphy->state != ATH_WIPHY_ACTIVE) {
2081                 printk(KERN_DEBUG "ath9k: %s: TX in unexpected wiphy state "
2082                        "%d\n", wiphy_name(hw->wiphy), aphy->state);
2083                 goto exit;
2084         }
2085
2086         memset(&txctl, 0, sizeof(struct ath_tx_control));
2087
2088         /*
2089          * As a temporary workaround, assign seq# here; this will likely need
2090          * to be cleaned up to work better with Beacon transmission and virtual
2091          * BSSes.
2092          */
2093         if (info->flags & IEEE80211_TX_CTL_ASSIGN_SEQ) {
2094                 struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data;
2095                 if (info->flags & IEEE80211_TX_CTL_FIRST_FRAGMENT)
2096                         sc->tx.seq_no += 0x10;
2097                 hdr->seq_ctrl &= cpu_to_le16(IEEE80211_SCTL_FRAG);
2098                 hdr->seq_ctrl |= cpu_to_le16(sc->tx.seq_no);
2099         }
2100
2101         /* Add the padding after the header if this is not already done */
2102         hdrlen = ieee80211_get_hdrlen_from_skb(skb);
2103         if (hdrlen & 3) {
2104                 padsize = hdrlen % 4;
2105                 if (skb_headroom(skb) < padsize)
2106                         return -1;
2107                 skb_push(skb, padsize);
2108                 memmove(skb->data, skb->data + padsize, hdrlen);
2109         }
2110
2111         /* Check if a tx queue is available */
2112
2113         txctl.txq = ath_test_get_txq(sc, skb);
2114         if (!txctl.txq)
2115                 goto exit;
2116
2117         DPRINTF(sc, ATH_DBG_XMIT, "transmitting packet, skb: %p\n", skb);
2118
2119         if (ath_tx_start(hw, skb, &txctl) != 0) {
2120                 DPRINTF(sc, ATH_DBG_XMIT, "TX failed\n");
2121                 goto exit;
2122         }
2123
2124         return 0;
2125 exit:
2126         dev_kfree_skb_any(skb);
2127         return 0;
2128 }
2129
2130 static void ath9k_stop(struct ieee80211_hw *hw)
2131 {
2132         struct ath_wiphy *aphy = hw->priv;
2133         struct ath_softc *sc = aphy->sc;
2134
2135         aphy->state = ATH_WIPHY_INACTIVE;
2136
2137         if (sc->sc_flags & SC_OP_INVALID) {
2138                 DPRINTF(sc, ATH_DBG_ANY, "Device not present\n");
2139                 return;
2140         }
2141
2142         mutex_lock(&sc->mutex);
2143
2144         ieee80211_stop_queues(hw);
2145
2146         if (ath9k_wiphy_started(sc)) {
2147                 mutex_unlock(&sc->mutex);
2148                 return; /* another wiphy still in use */
2149         }
2150
2151         /* make sure h/w will not generate any interrupt
2152          * before setting the invalid flag. */
2153         ath9k_hw_set_interrupts(sc->sc_ah, 0);
2154
2155         if (!(sc->sc_flags & SC_OP_INVALID)) {
2156                 ath_drain_all_txq(sc, false);
2157                 ath_stoprecv(sc);
2158                 ath9k_hw_phy_disable(sc->sc_ah);
2159         } else
2160                 sc->rx.rxlink = NULL;
2161
2162 #if defined(CONFIG_RFKILL) || defined(CONFIG_RFKILL_MODULE)
2163         if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_RFSILENT)
2164                 cancel_delayed_work_sync(&sc->rf_kill.rfkill_poll);
2165 #endif
2166         /* disable HAL and put h/w to sleep */
2167         ath9k_hw_disable(sc->sc_ah);
2168         ath9k_hw_configpcipowersave(sc->sc_ah, 1);
2169
2170         sc->sc_flags |= SC_OP_INVALID;
2171
2172         mutex_unlock(&sc->mutex);
2173
2174         DPRINTF(sc, ATH_DBG_CONFIG, "Driver halt\n");
2175 }
2176
2177 static int ath9k_add_interface(struct ieee80211_hw *hw,
2178                                struct ieee80211_if_init_conf *conf)
2179 {
2180         struct ath_wiphy *aphy = hw->priv;
2181         struct ath_softc *sc = aphy->sc;
2182         struct ath_vif *avp = (void *)conf->vif->drv_priv;
2183         enum nl80211_iftype ic_opmode = NL80211_IFTYPE_UNSPECIFIED;
2184         int ret = 0;
2185
2186         mutex_lock(&sc->mutex);
2187
2188         if (!(sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_BSSIDMASK) &&
2189             sc->nvifs > 0) {
2190                 ret = -ENOBUFS;
2191                 goto out;
2192         }
2193
2194         switch (conf->type) {
2195         case NL80211_IFTYPE_STATION:
2196                 ic_opmode = NL80211_IFTYPE_STATION;
2197                 break;
2198         case NL80211_IFTYPE_ADHOC:
2199                 if (sc->nbcnvifs >= ATH_BCBUF) {
2200                         ret = -ENOBUFS;
2201                         goto out;
2202                 }
2203                 ic_opmode = NL80211_IFTYPE_ADHOC;
2204                 break;
2205         case NL80211_IFTYPE_AP:
2206                 if (sc->nbcnvifs >= ATH_BCBUF) {
2207                         ret = -ENOBUFS;
2208                         goto out;
2209                 }
2210                 ic_opmode = NL80211_IFTYPE_AP;
2211                 break;
2212         default:
2213                 DPRINTF(sc, ATH_DBG_FATAL,
2214                         "Interface type %d not yet supported\n", conf->type);
2215                 ret = -EOPNOTSUPP;
2216                 goto out;
2217         }
2218
2219         DPRINTF(sc, ATH_DBG_CONFIG, "Attach a VIF of type: %d\n", ic_opmode);
2220
2221         /* Set the VIF opmode */
2222         avp->av_opmode = ic_opmode;
2223         avp->av_bslot = -1;
2224
2225         sc->nvifs++;
2226
2227         if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_BSSIDMASK)
2228                 ath9k_set_bssid_mask(hw);
2229
2230         if (sc->nvifs > 1)
2231                 goto out; /* skip global settings for secondary vif */
2232
2233         if (ic_opmode == NL80211_IFTYPE_AP) {
2234                 ath9k_hw_set_tsfadjust(sc->sc_ah, 1);
2235                 sc->sc_flags |= SC_OP_TSF_RESET;
2236         }
2237
2238         /* Set the device opmode */
2239         sc->sc_ah->opmode = ic_opmode;
2240
2241         /*
2242          * Enable MIB interrupts when there are hardware phy counters.
2243          * Note we only do this (at the moment) for station mode.
2244          */
2245         if ((conf->type == NL80211_IFTYPE_STATION) ||
2246             (conf->type == NL80211_IFTYPE_ADHOC)) {
2247                 if (ath9k_hw_phycounters(sc->sc_ah))
2248                         sc->imask |= ATH9K_INT_MIB;
2249                 sc->imask |= ATH9K_INT_TSFOOR;
2250         }
2251
2252         /*
2253          * Some hardware processes the TIM IE and fires an
2254          * interrupt when the TIM bit is set.  For hardware
2255          * that does, if not overridden by configuration,
2256          * enable the TIM interrupt when operating as station.
2257          */
2258         if ((sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_ENHANCEDPM) &&
2259             (conf->type == NL80211_IFTYPE_STATION) &&
2260             !sc->config.swBeaconProcess)
2261                 sc->imask |= ATH9K_INT_TIM;
2262
2263         ath9k_hw_set_interrupts(sc->sc_ah, sc->imask);
2264
2265         if (conf->type == NL80211_IFTYPE_AP) {
2266                 /* TODO: is this a suitable place to start ANI for AP mode? */
2267                 /* Start ANI */
2268                 mod_timer(&sc->ani.timer,
2269                           jiffies + msecs_to_jiffies(ATH_ANI_POLLINTERVAL));
2270         }
2271
2272 out:
2273         mutex_unlock(&sc->mutex);
2274         return ret;
2275 }
2276
2277 static void ath9k_remove_interface(struct ieee80211_hw *hw,
2278                                    struct ieee80211_if_init_conf *conf)
2279 {
2280         struct ath_wiphy *aphy = hw->priv;
2281         struct ath_softc *sc = aphy->sc;
2282         struct ath_vif *avp = (void *)conf->vif->drv_priv;
2283         int i;
2284
2285         DPRINTF(sc, ATH_DBG_CONFIG, "Detach Interface\n");
2286
2287         mutex_lock(&sc->mutex);
2288
2289         /* Stop ANI */
2290         del_timer_sync(&sc->ani.timer);
2291
2292         /* Reclaim beacon resources */
2293         if (sc->sc_ah->opmode == NL80211_IFTYPE_AP ||
2294             sc->sc_ah->opmode == NL80211_IFTYPE_ADHOC) {
2295                 ath9k_hw_stoptxdma(sc->sc_ah, sc->beacon.beaconq);
2296                 ath_beacon_return(sc, avp);
2297         }
2298
2299         sc->sc_flags &= ~SC_OP_BEACONS;
2300
2301         for (i = 0; i < ARRAY_SIZE(sc->beacon.bslot); i++) {
2302                 if (sc->beacon.bslot[i] == conf->vif) {
2303                         printk(KERN_DEBUG "%s: vif had allocated beacon "
2304                                "slot\n", __func__);
2305                         sc->beacon.bslot[i] = NULL;
2306                         sc->beacon.bslot_aphy[i] = NULL;
2307                 }
2308         }
2309
2310         sc->nvifs--;
2311
2312         mutex_unlock(&sc->mutex);
2313 }
2314
2315 static int ath9k_config(struct ieee80211_hw *hw, u32 changed)
2316 {
2317         struct ath_wiphy *aphy = hw->priv;
2318         struct ath_softc *sc = aphy->sc;
2319         struct ieee80211_conf *conf = &hw->conf;
2320
2321         mutex_lock(&sc->mutex);
2322
2323         if (changed & IEEE80211_CONF_CHANGE_PS) {
2324                 if (conf->flags & IEEE80211_CONF_PS) {
2325                         if ((sc->imask & ATH9K_INT_TIM_TIMER) == 0) {
2326                                 sc->imask |= ATH9K_INT_TIM_TIMER;
2327                                 ath9k_hw_set_interrupts(sc->sc_ah,
2328                                                 sc->imask);
2329                         }
2330                         ath9k_hw_setrxabort(sc->sc_ah, 1);
2331                         ath9k_hw_setpower(sc->sc_ah, ATH9K_PM_NETWORK_SLEEP);
2332                 } else {
2333                         ath9k_hw_setpower(sc->sc_ah, ATH9K_PM_AWAKE);
2334                         ath9k_hw_setrxabort(sc->sc_ah, 0);
2335                         sc->sc_flags &= ~SC_OP_WAIT_FOR_BEACON;
2336                         if (sc->imask & ATH9K_INT_TIM_TIMER) {
2337                                 sc->imask &= ~ATH9K_INT_TIM_TIMER;
2338                                 ath9k_hw_set_interrupts(sc->sc_ah,
2339                                                 sc->imask);
2340                         }
2341                 }
2342         }
2343
2344         if (changed & IEEE80211_CONF_CHANGE_CHANNEL) {
2345                 struct ieee80211_channel *curchan = hw->conf.channel;
2346                 int pos = curchan->hw_value;
2347
2348                 aphy->chan_idx = pos;
2349                 aphy->chan_is_ht = conf_is_ht(conf);
2350
2351                 /* TODO: do not change operation channel immediately if there
2352                  * are other virtual wiphys that use another channel. For now,
2353                  * we do the change immediately to allow mac80211-operated scan
2354                  * to work. Once the scan operation is moved into ath9k, we can
2355                  * just move the current aphy in PAUSED state if the channel is
2356                  * changed into something different from the current operation
2357                  * channel. */
2358                 ath9k_wiphy_pause_all_forced(sc, aphy);
2359
2360                 DPRINTF(sc, ATH_DBG_CONFIG, "Set channel: %d MHz\n",
2361                         curchan->center_freq);
2362
2363                 /* XXX: remove me eventualy */
2364                 ath9k_update_ichannel(sc, hw, &sc->sc_ah->channels[pos]);
2365
2366                 ath_update_chainmask(sc, conf_is_ht(conf));
2367
2368                 if (ath_set_channel(sc, hw, &sc->sc_ah->channels[pos]) < 0) {
2369                         DPRINTF(sc, ATH_DBG_FATAL, "Unable to set channel\n");
2370                         mutex_unlock(&sc->mutex);
2371                         return -EINVAL;
2372                 }
2373         }
2374
2375         if (changed & IEEE80211_CONF_CHANGE_POWER)
2376                 sc->config.txpowlimit = 2 * conf->power_level;
2377
2378         /*
2379          * The HW TSF has to be reset when the beacon interval changes.
2380          * We set the flag here, and ath_beacon_config_ap() would take this
2381          * into account when it gets called through the subsequent
2382          * config_interface() call - with IFCC_BEACON in the changed field.
2383          */
2384
2385         if (changed & IEEE80211_CONF_CHANGE_BEACON_INTERVAL)
2386                 sc->sc_flags |= SC_OP_TSF_RESET;
2387
2388         mutex_unlock(&sc->mutex);
2389
2390         return 0;
2391 }
2392
2393 static int ath9k_config_interface(struct ieee80211_hw *hw,
2394                                   struct ieee80211_vif *vif,
2395                                   struct ieee80211_if_conf *conf)
2396 {
2397         struct ath_wiphy *aphy = hw->priv;
2398         struct ath_softc *sc = aphy->sc;
2399         struct ath_hw *ah = sc->sc_ah;
2400         struct ath_vif *avp = (void *)vif->drv_priv;
2401         u32 rfilt = 0;
2402         int error, i;
2403
2404         mutex_lock(&sc->mutex);
2405
2406         /* TODO: Need to decide which hw opmode to use for multi-interface
2407          * cases */
2408         if (vif->type == NL80211_IFTYPE_AP &&
2409             ah->opmode != NL80211_IFTYPE_AP) {
2410                 ah->opmode = NL80211_IFTYPE_STATION;
2411                 ath9k_hw_setopmode(ah);
2412                 memcpy(sc->curbssid, sc->sc_ah->macaddr, ETH_ALEN);
2413                 sc->curaid = 0;
2414                 ath9k_hw_write_associd(sc);
2415                 /* Request full reset to get hw opmode changed properly */
2416                 sc->sc_flags |= SC_OP_FULL_RESET;
2417         }
2418
2419         if ((conf->changed & IEEE80211_IFCC_BSSID) &&
2420             !is_zero_ether_addr(conf->bssid)) {
2421                 switch (vif->type) {
2422                 case NL80211_IFTYPE_STATION:
2423                 case NL80211_IFTYPE_ADHOC:
2424                         /* Set BSSID */
2425                         memcpy(sc->curbssid, conf->bssid, ETH_ALEN);
2426                         memcpy(avp->bssid, conf->bssid, ETH_ALEN);
2427                         sc->curaid = 0;
2428                         ath9k_hw_write_associd(sc);
2429
2430                         /* Set aggregation protection mode parameters */
2431                         sc->config.ath_aggr_prot = 0;
2432
2433                         DPRINTF(sc, ATH_DBG_CONFIG,
2434                                 "RX filter 0x%x bssid %pM aid 0x%x\n",
2435                                 rfilt, sc->curbssid, sc->curaid);
2436
2437                         /* need to reconfigure the beacon */
2438                         sc->sc_flags &= ~SC_OP_BEACONS ;
2439
2440                         break;
2441                 default:
2442                         break;
2443                 }
2444         }
2445
2446         if ((vif->type == NL80211_IFTYPE_ADHOC) ||
2447             (vif->type == NL80211_IFTYPE_AP)) {
2448                 if ((conf->changed & IEEE80211_IFCC_BEACON) ||
2449                     (conf->changed & IEEE80211_IFCC_BEACON_ENABLED &&
2450                      conf->enable_beacon)) {
2451                         /*
2452                          * Allocate and setup the beacon frame.
2453                          *
2454                          * Stop any previous beacon DMA.  This may be
2455                          * necessary, for example, when an ibss merge
2456                          * causes reconfiguration; we may be called
2457                          * with beacon transmission active.
2458                          */
2459                         ath9k_hw_stoptxdma(sc->sc_ah, sc->beacon.beaconq);
2460
2461                         error = ath_beacon_alloc(aphy, vif);
2462                         if (error != 0) {
2463                                 mutex_unlock(&sc->mutex);
2464                                 return error;
2465                         }
2466
2467                         ath_beacon_config(sc, vif);
2468                 }
2469         }
2470
2471         /* Check for WLAN_CAPABILITY_PRIVACY ? */
2472         if ((avp->av_opmode != NL80211_IFTYPE_STATION)) {
2473                 for (i = 0; i < IEEE80211_WEP_NKID; i++)
2474                         if (ath9k_hw_keyisvalid(sc->sc_ah, (u16)i))
2475                                 ath9k_hw_keysetmac(sc->sc_ah,
2476                                                    (u16)i,
2477                                                    sc->curbssid);
2478         }
2479
2480         /* Only legacy IBSS for now */
2481         if (vif->type == NL80211_IFTYPE_ADHOC)
2482                 ath_update_chainmask(sc, 0);
2483
2484         mutex_unlock(&sc->mutex);
2485
2486         return 0;
2487 }
2488
2489 #define SUPPORTED_FILTERS                       \
2490         (FIF_PROMISC_IN_BSS |                   \
2491         FIF_ALLMULTI |                          \
2492         FIF_CONTROL |                           \
2493         FIF_OTHER_BSS |                         \
2494         FIF_BCN_PRBRESP_PROMISC |               \
2495         FIF_FCSFAIL)
2496
2497 /* FIXME: sc->sc_full_reset ? */
2498 static void ath9k_configure_filter(struct ieee80211_hw *hw,
2499                                    unsigned int changed_flags,
2500                                    unsigned int *total_flags,
2501                                    int mc_count,
2502                                    struct dev_mc_list *mclist)
2503 {
2504         struct ath_wiphy *aphy = hw->priv;
2505         struct ath_softc *sc = aphy->sc;
2506         u32 rfilt;
2507
2508         changed_flags &= SUPPORTED_FILTERS;
2509         *total_flags &= SUPPORTED_FILTERS;
2510
2511         sc->rx.rxfilter = *total_flags;
2512         rfilt = ath_calcrxfilter(sc);
2513         ath9k_hw_setrxfilter(sc->sc_ah, rfilt);
2514
2515         DPRINTF(sc, ATH_DBG_CONFIG, "Set HW RX filter: 0x%x\n", sc->rx.rxfilter);
2516 }
2517
2518 static void ath9k_sta_notify(struct ieee80211_hw *hw,
2519                              struct ieee80211_vif *vif,
2520                              enum sta_notify_cmd cmd,
2521                              struct ieee80211_sta *sta)
2522 {
2523         struct ath_wiphy *aphy = hw->priv;
2524         struct ath_softc *sc = aphy->sc;
2525
2526         switch (cmd) {
2527         case STA_NOTIFY_ADD:
2528                 ath_node_attach(sc, sta);
2529                 break;
2530         case STA_NOTIFY_REMOVE:
2531                 ath_node_detach(sc, sta);
2532                 break;
2533         default:
2534                 break;
2535         }
2536 }
2537
2538 static int ath9k_conf_tx(struct ieee80211_hw *hw, u16 queue,
2539                          const struct ieee80211_tx_queue_params *params)
2540 {
2541         struct ath_wiphy *aphy = hw->priv;
2542         struct ath_softc *sc = aphy->sc;
2543         struct ath9k_tx_queue_info qi;
2544         int ret = 0, qnum;
2545
2546         if (queue >= WME_NUM_AC)
2547                 return 0;
2548
2549         mutex_lock(&sc->mutex);
2550
2551         qi.tqi_aifs = params->aifs;
2552         qi.tqi_cwmin = params->cw_min;
2553         qi.tqi_cwmax = params->cw_max;
2554         qi.tqi_burstTime = params->txop;
2555         qnum = ath_get_hal_qnum(queue, sc);
2556
2557         DPRINTF(sc, ATH_DBG_CONFIG,
2558                 "Configure tx [queue/halq] [%d/%d],  "
2559                 "aifs: %d, cw_min: %d, cw_max: %d, txop: %d\n",
2560                 queue, qnum, params->aifs, params->cw_min,
2561                 params->cw_max, params->txop);
2562
2563         ret = ath_txq_update(sc, qnum, &qi);
2564         if (ret)
2565                 DPRINTF(sc, ATH_DBG_FATAL, "TXQ Update failed\n");
2566
2567         mutex_unlock(&sc->mutex);
2568
2569         return ret;
2570 }
2571
2572 static int ath9k_set_key(struct ieee80211_hw *hw,
2573                          enum set_key_cmd cmd,
2574                          struct ieee80211_vif *vif,
2575                          struct ieee80211_sta *sta,
2576                          struct ieee80211_key_conf *key)
2577 {
2578         struct ath_wiphy *aphy = hw->priv;
2579         struct ath_softc *sc = aphy->sc;
2580         int ret = 0;
2581
2582         if (modparam_nohwcrypt)
2583                 return -ENOSPC;
2584
2585         mutex_lock(&sc->mutex);
2586         ath9k_ps_wakeup(sc);
2587         DPRINTF(sc, ATH_DBG_KEYCACHE, "Set HW Key\n");
2588
2589         switch (cmd) {
2590         case SET_KEY:
2591                 ret = ath_key_config(sc, vif, sta, key);
2592                 if (ret >= 0) {
2593                         key->hw_key_idx = ret;
2594                         /* push IV and Michael MIC generation to stack */
2595                         key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
2596                         if (key->alg == ALG_TKIP)
2597                                 key->flags |= IEEE80211_KEY_FLAG_GENERATE_MMIC;
2598                         if (sc->sc_ah->sw_mgmt_crypto && key->alg == ALG_CCMP)
2599                                 key->flags |= IEEE80211_KEY_FLAG_SW_MGMT;
2600                         ret = 0;
2601                 }
2602                 break;
2603         case DISABLE_KEY:
2604                 ath_key_delete(sc, key);
2605                 break;
2606         default:
2607                 ret = -EINVAL;
2608         }
2609
2610         ath9k_ps_restore(sc);
2611         mutex_unlock(&sc->mutex);
2612
2613         return ret;
2614 }
2615
2616 static void ath9k_bss_info_changed(struct ieee80211_hw *hw,
2617                                    struct ieee80211_vif *vif,
2618                                    struct ieee80211_bss_conf *bss_conf,
2619                                    u32 changed)
2620 {
2621         struct ath_wiphy *aphy = hw->priv;
2622         struct ath_softc *sc = aphy->sc;
2623
2624         mutex_lock(&sc->mutex);
2625
2626         if (changed & BSS_CHANGED_ERP_PREAMBLE) {
2627                 DPRINTF(sc, ATH_DBG_CONFIG, "BSS Changed PREAMBLE %d\n",
2628                         bss_conf->use_short_preamble);
2629                 if (bss_conf->use_short_preamble)
2630                         sc->sc_flags |= SC_OP_PREAMBLE_SHORT;
2631                 else
2632                         sc->sc_flags &= ~SC_OP_PREAMBLE_SHORT;
2633         }
2634
2635         if (changed & BSS_CHANGED_ERP_CTS_PROT) {
2636                 DPRINTF(sc, ATH_DBG_CONFIG, "BSS Changed CTS PROT %d\n",
2637                         bss_conf->use_cts_prot);
2638                 if (bss_conf->use_cts_prot &&
2639                     hw->conf.channel->band != IEEE80211_BAND_5GHZ)
2640                         sc->sc_flags |= SC_OP_PROTECT_ENABLE;
2641                 else
2642                         sc->sc_flags &= ~SC_OP_PROTECT_ENABLE;
2643         }
2644
2645         if (changed & BSS_CHANGED_ASSOC) {
2646                 DPRINTF(sc, ATH_DBG_CONFIG, "BSS Changed ASSOC %d\n",
2647                         bss_conf->assoc);
2648                 ath9k_bss_assoc_info(sc, vif, bss_conf);
2649         }
2650
2651         mutex_unlock(&sc->mutex);
2652 }
2653
2654 static u64 ath9k_get_tsf(struct ieee80211_hw *hw)
2655 {
2656         u64 tsf;
2657         struct ath_wiphy *aphy = hw->priv;
2658         struct ath_softc *sc = aphy->sc;
2659
2660         mutex_lock(&sc->mutex);
2661         tsf = ath9k_hw_gettsf64(sc->sc_ah);
2662         mutex_unlock(&sc->mutex);
2663
2664         return tsf;
2665 }
2666
2667 static void ath9k_set_tsf(struct ieee80211_hw *hw, u64 tsf)
2668 {
2669         struct ath_wiphy *aphy = hw->priv;
2670         struct ath_softc *sc = aphy->sc;
2671
2672         mutex_lock(&sc->mutex);
2673         ath9k_hw_settsf64(sc->sc_ah, tsf);
2674         mutex_unlock(&sc->mutex);
2675 }
2676
2677 static void ath9k_reset_tsf(struct ieee80211_hw *hw)
2678 {
2679         struct ath_wiphy *aphy = hw->priv;
2680         struct ath_softc *sc = aphy->sc;
2681
2682         mutex_lock(&sc->mutex);
2683         ath9k_hw_reset_tsf(sc->sc_ah);
2684         mutex_unlock(&sc->mutex);
2685 }
2686
2687 static int ath9k_ampdu_action(struct ieee80211_hw *hw,
2688                               enum ieee80211_ampdu_mlme_action action,
2689                               struct ieee80211_sta *sta,
2690                               u16 tid, u16 *ssn)
2691 {
2692         struct ath_wiphy *aphy = hw->priv;
2693         struct ath_softc *sc = aphy->sc;
2694         int ret = 0;
2695
2696         switch (action) {
2697         case IEEE80211_AMPDU_RX_START:
2698                 if (!(sc->sc_flags & SC_OP_RXAGGR))
2699                         ret = -ENOTSUPP;
2700                 break;
2701         case IEEE80211_AMPDU_RX_STOP:
2702                 break;
2703         case IEEE80211_AMPDU_TX_START:
2704                 ret = ath_tx_aggr_start(sc, sta, tid, ssn);
2705                 if (ret < 0)
2706                         DPRINTF(sc, ATH_DBG_FATAL,
2707                                 "Unable to start TX aggregation\n");
2708                 else
2709                         ieee80211_start_tx_ba_cb_irqsafe(hw, sta->addr, tid);
2710                 break;
2711         case IEEE80211_AMPDU_TX_STOP:
2712                 ret = ath_tx_aggr_stop(sc, sta, tid);
2713                 if (ret < 0)
2714                         DPRINTF(sc, ATH_DBG_FATAL,
2715                                 "Unable to stop TX aggregation\n");
2716
2717                 ieee80211_stop_tx_ba_cb_irqsafe(hw, sta->addr, tid);
2718                 break;
2719         case IEEE80211_AMPDU_TX_RESUME:
2720                 ath_tx_aggr_resume(sc, sta, tid);
2721                 break;
2722         default:
2723                 DPRINTF(sc, ATH_DBG_FATAL, "Unknown AMPDU action\n");
2724         }
2725
2726         return ret;
2727 }
2728
2729 static void ath9k_sw_scan_start(struct ieee80211_hw *hw)
2730 {
2731         struct ath_wiphy *aphy = hw->priv;
2732         struct ath_softc *sc = aphy->sc;
2733
2734         mutex_lock(&sc->mutex);
2735         sc->sc_flags |= SC_OP_SCANNING;
2736         mutex_unlock(&sc->mutex);
2737 }
2738
2739 static void ath9k_sw_scan_complete(struct ieee80211_hw *hw)
2740 {
2741         struct ath_wiphy *aphy = hw->priv;
2742         struct ath_softc *sc = aphy->sc;
2743
2744         mutex_lock(&sc->mutex);
2745         sc->sc_flags &= ~SC_OP_SCANNING;
2746         mutex_unlock(&sc->mutex);
2747 }
2748
2749 struct ieee80211_ops ath9k_ops = {
2750         .tx                 = ath9k_tx,
2751         .start              = ath9k_start,
2752         .stop               = ath9k_stop,
2753         .add_interface      = ath9k_add_interface,
2754         .remove_interface   = ath9k_remove_interface,
2755         .config             = ath9k_config,
2756         .config_interface   = ath9k_config_interface,
2757         .configure_filter   = ath9k_configure_filter,
2758         .sta_notify         = ath9k_sta_notify,
2759         .conf_tx            = ath9k_conf_tx,
2760         .bss_info_changed   = ath9k_bss_info_changed,
2761         .set_key            = ath9k_set_key,
2762         .get_tsf            = ath9k_get_tsf,
2763         .set_tsf            = ath9k_set_tsf,
2764         .reset_tsf          = ath9k_reset_tsf,
2765         .ampdu_action       = ath9k_ampdu_action,
2766         .sw_scan_start      = ath9k_sw_scan_start,
2767         .sw_scan_complete   = ath9k_sw_scan_complete,
2768 };
2769
2770 static struct {
2771         u32 version;
2772         const char * name;
2773 } ath_mac_bb_names[] = {
2774         { AR_SREV_VERSION_5416_PCI,     "5416" },
2775         { AR_SREV_VERSION_5416_PCIE,    "5418" },
2776         { AR_SREV_VERSION_9100,         "9100" },
2777         { AR_SREV_VERSION_9160,         "9160" },
2778         { AR_SREV_VERSION_9280,         "9280" },
2779         { AR_SREV_VERSION_9285,         "9285" }
2780 };
2781
2782 static struct {
2783         u16 version;
2784         const char * name;
2785 } ath_rf_names[] = {
2786         { 0,                            "5133" },
2787         { AR_RAD5133_SREV_MAJOR,        "5133" },
2788         { AR_RAD5122_SREV_MAJOR,        "5122" },
2789         { AR_RAD2133_SREV_MAJOR,        "2133" },
2790         { AR_RAD2122_SREV_MAJOR,        "2122" }
2791 };
2792
2793 /*
2794  * Return the MAC/BB name. "????" is returned if the MAC/BB is unknown.
2795  */
2796 const char *
2797 ath_mac_bb_name(u32 mac_bb_version)
2798 {
2799         int i;
2800
2801         for (i=0; i<ARRAY_SIZE(ath_mac_bb_names); i++) {
2802                 if (ath_mac_bb_names[i].version == mac_bb_version) {
2803                         return ath_mac_bb_names[i].name;
2804                 }
2805         }
2806
2807         return "????";
2808 }
2809
2810 /*
2811  * Return the RF name. "????" is returned if the RF is unknown.
2812  */
2813 const char *
2814 ath_rf_name(u16 rf_version)
2815 {
2816         int i;
2817
2818         for (i=0; i<ARRAY_SIZE(ath_rf_names); i++) {
2819                 if (ath_rf_names[i].version == rf_version) {
2820                         return ath_rf_names[i].name;
2821                 }
2822         }
2823
2824         return "????";
2825 }
2826
2827 static int __init ath9k_init(void)
2828 {
2829         int error;
2830
2831         /* Register rate control algorithm */
2832         error = ath_rate_control_register();
2833         if (error != 0) {
2834                 printk(KERN_ERR
2835                         "ath9k: Unable to register rate control "
2836                         "algorithm: %d\n",
2837                         error);
2838                 goto err_out;
2839         }
2840
2841         error = ath_pci_init();
2842         if (error < 0) {
2843                 printk(KERN_ERR
2844                         "ath9k: No PCI devices found, driver not installed.\n");
2845                 error = -ENODEV;
2846                 goto err_rate_unregister;
2847         }
2848
2849         error = ath_ahb_init();
2850         if (error < 0) {
2851                 error = -ENODEV;
2852                 goto err_pci_exit;
2853         }
2854
2855         return 0;
2856
2857  err_pci_exit:
2858         ath_pci_exit();
2859
2860  err_rate_unregister:
2861         ath_rate_control_unregister();
2862  err_out:
2863         return error;
2864 }
2865 module_init(ath9k_init);
2866
2867 static void __exit ath9k_exit(void)
2868 {
2869         ath_ahb_exit();
2870         ath_pci_exit();
2871         ath_rate_control_unregister();
2872         printk(KERN_INFO "%s: Driver unloaded\n", dev_info);
2873 }
2874 module_exit(ath9k_exit);