ath9k: Use bitfields for sc operations
[safe/jmp/linux-2.6] / drivers / net / wireless / ath9k / core.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  /* Implementation of the main "ATH" layer. */
18
19 #include "core.h"
20 #include "regd.h"
21
22 static int ath_outdoor;         /* enable outdoor use */
23
24 static u32 ath_chainmask_sel_up_rssi_thres =
25         ATH_CHAINMASK_SEL_UP_RSSI_THRES;
26 static u32 ath_chainmask_sel_down_rssi_thres =
27         ATH_CHAINMASK_SEL_DOWN_RSSI_THRES;
28 static u32 ath_chainmask_sel_period =
29         ATH_CHAINMASK_SEL_TIMEOUT;
30
31 /* return bus cachesize in 4B word units */
32
33 static void bus_read_cachesize(struct ath_softc *sc, int *csz)
34 {
35         u8 u8tmp;
36
37         pci_read_config_byte(sc->pdev, PCI_CACHE_LINE_SIZE, (u8 *)&u8tmp);
38         *csz = (int)u8tmp;
39
40         /*
41          * This check was put in to avoid "unplesant" consequences if
42          * the bootrom has not fully initialized all PCI devices.
43          * Sometimes the cache line size register is not set
44          */
45
46         if (*csz == 0)
47                 *csz = DEFAULT_CACHELINE >> 2;   /* Use the default size */
48 }
49
50 /*
51  *  Set current operating mode
52  *
53  *  This function initializes and fills the rate table in the ATH object based
54  *  on the operating mode.  The blink rates are also set up here, although
55  *  they have been superceeded by the ath_led module.
56 */
57
58 static void ath_setcurmode(struct ath_softc *sc, enum wireless_mode mode)
59 {
60         const struct ath9k_rate_table *rt;
61         int i;
62
63         memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
64         rt = ath9k_hw_getratetable(sc->sc_ah, mode);
65         BUG_ON(!rt);
66
67         for (i = 0; i < rt->rateCount; i++)
68                 sc->sc_rixmap[rt->info[i].rateCode] = (u8) i;
69
70         memzero(sc->sc_hwmap, sizeof(sc->sc_hwmap));
71         for (i = 0; i < 256; i++) {
72                 u8 ix = rt->rateCodeToIndex[i];
73
74                 if (ix == 0xff)
75                         continue;
76
77                 sc->sc_hwmap[i].ieeerate =
78                     rt->info[ix].dot11Rate & IEEE80211_RATE_VAL;
79                 sc->sc_hwmap[i].rateKbps = rt->info[ix].rateKbps;
80
81                 if (rt->info[ix].shortPreamble ||
82                     rt->info[ix].phy == PHY_OFDM) {
83                         /* XXX: Handle this */
84                 }
85
86                 /* NB: this uses the last entry if the rate isn't found */
87                 /* XXX beware of overlow */
88         }
89         sc->sc_currates = rt;
90         sc->sc_curmode = mode;
91         /*
92          * All protection frames are transmited at 2Mb/s for
93          * 11g, otherwise at 1Mb/s.
94          * XXX select protection rate index from rate table.
95          */
96         sc->sc_protrix = (mode == ATH9K_MODE_11G ? 1 : 0);
97 }
98
99 /*
100  * Set up rate table (legacy rates)
101  */
102 static void ath_setup_rates(struct ath_softc *sc, enum ieee80211_band band)
103 {
104         struct ath_hal *ah = sc->sc_ah;
105         const struct ath9k_rate_table *rt = NULL;
106         struct ieee80211_supported_band *sband;
107         struct ieee80211_rate *rate;
108         int i, maxrates;
109
110         switch (band) {
111         case IEEE80211_BAND_2GHZ:
112                 rt = ath9k_hw_getratetable(ah, ATH9K_MODE_11G);
113                 break;
114         case IEEE80211_BAND_5GHZ:
115                 rt = ath9k_hw_getratetable(ah, ATH9K_MODE_11A);
116                 break;
117         default:
118                 break;
119         }
120
121         if (rt == NULL)
122                 return;
123
124         sband = &sc->sbands[band];
125         rate = sc->rates[band];
126
127         if (rt->rateCount > ATH_RATE_MAX)
128                 maxrates = ATH_RATE_MAX;
129         else
130                 maxrates = rt->rateCount;
131
132         for (i = 0; i < maxrates; i++) {
133                 rate[i].bitrate = rt->info[i].rateKbps / 100;
134                 rate[i].hw_value = rt->info[i].rateCode;
135                 sband->n_bitrates++;
136                 DPRINTF(sc, ATH_DBG_CONFIG,
137                         "%s: Rate: %2dMbps, ratecode: %2d\n",
138                         __func__,
139                         rate[i].bitrate / 10,
140                         rate[i].hw_value);
141         }
142 }
143
144 /*
145  *  Set up channel list
146  */
147 static int ath_setup_channels(struct ath_softc *sc)
148 {
149         struct ath_hal *ah = sc->sc_ah;
150         int nchan, i, a = 0, b = 0;
151         u8 regclassids[ATH_REGCLASSIDS_MAX];
152         u32 nregclass = 0;
153         struct ieee80211_supported_band *band_2ghz;
154         struct ieee80211_supported_band *band_5ghz;
155         struct ieee80211_channel *chan_2ghz;
156         struct ieee80211_channel *chan_5ghz;
157         struct ath9k_channel *c;
158
159         /* Fill in ah->ah_channels */
160         if (!ath9k_regd_init_channels(ah,
161                                       ATH_CHAN_MAX,
162                                       (u32 *)&nchan,
163                                       regclassids,
164                                       ATH_REGCLASSIDS_MAX,
165                                       &nregclass,
166                                       CTRY_DEFAULT,
167                                       false,
168                                       1)) {
169                 u32 rd = ah->ah_currentRD;
170
171                 DPRINTF(sc, ATH_DBG_FATAL,
172                         "%s: unable to collect channel list; "
173                         "regdomain likely %u country code %u\n",
174                         __func__, rd, CTRY_DEFAULT);
175                 return -EINVAL;
176         }
177
178         band_2ghz = &sc->sbands[IEEE80211_BAND_2GHZ];
179         band_5ghz = &sc->sbands[IEEE80211_BAND_5GHZ];
180         chan_2ghz = sc->channels[IEEE80211_BAND_2GHZ];
181         chan_5ghz = sc->channels[IEEE80211_BAND_5GHZ];
182
183         for (i = 0; i < nchan; i++) {
184                 c = &ah->ah_channels[i];
185                 if (IS_CHAN_2GHZ(c)) {
186                         chan_2ghz[a].band = IEEE80211_BAND_2GHZ;
187                         chan_2ghz[a].center_freq = c->channel;
188                         chan_2ghz[a].max_power = c->maxTxPower;
189
190                         if (c->privFlags & CHANNEL_DISALLOW_ADHOC)
191                                 chan_2ghz[a].flags |=
192                                         IEEE80211_CHAN_NO_IBSS;
193                         if (c->channelFlags & CHANNEL_PASSIVE)
194                                 chan_2ghz[a].flags |=
195                                         IEEE80211_CHAN_PASSIVE_SCAN;
196
197                         band_2ghz->n_channels = ++a;
198
199                         DPRINTF(sc, ATH_DBG_CONFIG,
200                                 "%s: 2MHz channel: %d, "
201                                 "channelFlags: 0x%x\n",
202                                 __func__,
203                                 c->channel,
204                                 c->channelFlags);
205                 } else if (IS_CHAN_5GHZ(c)) {
206                         chan_5ghz[b].band = IEEE80211_BAND_5GHZ;
207                         chan_5ghz[b].center_freq = c->channel;
208                         chan_5ghz[b].max_power = c->maxTxPower;
209
210                         if (c->privFlags & CHANNEL_DISALLOW_ADHOC)
211                                 chan_5ghz[b].flags |=
212                                         IEEE80211_CHAN_NO_IBSS;
213                         if (c->channelFlags & CHANNEL_PASSIVE)
214                                 chan_5ghz[b].flags |=
215                                         IEEE80211_CHAN_PASSIVE_SCAN;
216
217                         band_5ghz->n_channels = ++b;
218
219                         DPRINTF(sc, ATH_DBG_CONFIG,
220                                 "%s: 5MHz channel: %d, "
221                                 "channelFlags: 0x%x\n",
222                                 __func__,
223                                 c->channel,
224                                 c->channelFlags);
225                 }
226         }
227
228         return 0;
229 }
230
231 /*
232  *  Determine mode from channel flags
233  *
234  *  This routine will provide the enumerated WIRELESSS_MODE value based
235  *  on the settings of the channel flags.  If ho valid set of flags
236  *  exist, the lowest mode (11b) is selected.
237 */
238
239 static enum wireless_mode ath_chan2mode(struct ath9k_channel *chan)
240 {
241         if (chan->chanmode == CHANNEL_A)
242                 return ATH9K_MODE_11A;
243         else if (chan->chanmode == CHANNEL_G)
244                 return ATH9K_MODE_11G;
245         else if (chan->chanmode == CHANNEL_B)
246                 return ATH9K_MODE_11B;
247         else if (chan->chanmode == CHANNEL_A_HT20)
248                 return ATH9K_MODE_11NA_HT20;
249         else if (chan->chanmode == CHANNEL_G_HT20)
250                 return ATH9K_MODE_11NG_HT20;
251         else if (chan->chanmode == CHANNEL_A_HT40PLUS)
252                 return ATH9K_MODE_11NA_HT40PLUS;
253         else if (chan->chanmode == CHANNEL_A_HT40MINUS)
254                 return ATH9K_MODE_11NA_HT40MINUS;
255         else if (chan->chanmode == CHANNEL_G_HT40PLUS)
256                 return ATH9K_MODE_11NG_HT40PLUS;
257         else if (chan->chanmode == CHANNEL_G_HT40MINUS)
258                 return ATH9K_MODE_11NG_HT40MINUS;
259
260         /* NB: should not get here */
261         return ATH9K_MODE_11B;
262 }
263
264 /*
265  * Stop the device, grabbing the top-level lock to protect
266  * against concurrent entry through ath_init (which can happen
267  * if another thread does a system call and the thread doing the
268  * stop is preempted).
269  */
270
271 static int ath_stop(struct ath_softc *sc)
272 {
273         struct ath_hal *ah = sc->sc_ah;
274
275         DPRINTF(sc, ATH_DBG_CONFIG, "%s: invalid %ld\n",
276                 __func__, sc->sc_flags & SC_OP_INVALID);
277
278         /*
279          * Shutdown the hardware and driver:
280          *    stop output from above
281          *    reset 802.11 state machine
282          *      (sends station deassoc/deauth frames)
283          *    turn off timers
284          *    disable interrupts
285          *    clear transmit machinery
286          *    clear receive machinery
287          *    turn off the radio
288          *    reclaim beacon resources
289          *
290          * Note that some of this work is not possible if the
291          * hardware is gone (invalid).
292          */
293
294         if (!(sc->sc_flags & SC_OP_INVALID))
295                 ath9k_hw_set_interrupts(ah, 0);
296         ath_draintxq(sc, false);
297         if (!(sc->sc_flags & SC_OP_INVALID)) {
298                 ath_stoprecv(sc);
299                 ath9k_hw_phy_disable(ah);
300         } else
301                 sc->sc_rxlink = NULL;
302
303         return 0;
304 }
305
306 /*
307  * Set the current channel
308  *
309  * Set/change channels.  If the channel is really being changed, it's done
310  * by reseting the chip.  To accomplish this we must first cleanup any pending
311  * DMA, then restart stuff after a la ath_init.
312 */
313 int ath_set_channel(struct ath_softc *sc, struct ath9k_channel *hchan)
314 {
315         struct ath_hal *ah = sc->sc_ah;
316         bool fastcc = true, stopped;
317         enum ath9k_ht_macmode ht_macmode;
318
319         if (sc->sc_flags & SC_OP_INVALID) /* the device is invalid or removed */
320                 return -EIO;
321
322         DPRINTF(sc, ATH_DBG_CONFIG,
323                 "%s: %u (%u MHz) -> %u (%u MHz), cflags:%x\n",
324                 __func__,
325                 ath9k_hw_mhz2ieee(ah, sc->sc_curchan.channel,
326                                   sc->sc_curchan.channelFlags),
327                 sc->sc_curchan.channel,
328                 ath9k_hw_mhz2ieee(ah, hchan->channel, hchan->channelFlags),
329                 hchan->channel, hchan->channelFlags);
330
331         ht_macmode = ath_cwm_macmode(sc);
332
333         if (hchan->channel != sc->sc_curchan.channel ||
334             hchan->channelFlags != sc->sc_curchan.channelFlags ||
335             (sc->sc_flags & SC_OP_CHAINMASK_UPDATE) ||
336             (sc->sc_flags & SC_OP_FULL_RESET)) {
337                 int status;
338                 /*
339                  * This is only performed if the channel settings have
340                  * actually changed.
341                  *
342                  * To switch channels clear any pending DMA operations;
343                  * wait long enough for the RX fifo to drain, reset the
344                  * hardware at the new frequency, and then re-enable
345                  * the relevant bits of the h/w.
346                  */
347                 ath9k_hw_set_interrupts(ah, 0); /* disable interrupts */
348                 ath_draintxq(sc, false);        /* clear pending tx frames */
349                 stopped = ath_stoprecv(sc);     /* turn off frame recv */
350
351                 /* XXX: do not flush receive queue here. We don't want
352                  * to flush data frames already in queue because of
353                  * changing channel. */
354
355                 if (!stopped || (sc->sc_flags & SC_OP_FULL_RESET))
356                         fastcc = false;
357
358                 spin_lock_bh(&sc->sc_resetlock);
359                 if (!ath9k_hw_reset(ah, hchan,
360                                         ht_macmode, sc->sc_tx_chainmask,
361                                         sc->sc_rx_chainmask,
362                                         sc->sc_ht_extprotspacing,
363                                         fastcc, &status)) {
364                         DPRINTF(sc, ATH_DBG_FATAL,
365                                 "%s: unable to reset channel %u (%uMhz) "
366                                 "flags 0x%x hal status %u\n", __func__,
367                                 ath9k_hw_mhz2ieee(ah, hchan->channel,
368                                                   hchan->channelFlags),
369                                 hchan->channel, hchan->channelFlags, status);
370                         spin_unlock_bh(&sc->sc_resetlock);
371                         return -EIO;
372                 }
373                 spin_unlock_bh(&sc->sc_resetlock);
374
375                 sc->sc_curchan = *hchan;
376                 sc->sc_flags &= ~SC_OP_CHAINMASK_UPDATE;
377                 sc->sc_flags &= ~SC_OP_FULL_RESET;
378
379                 /* Re-enable rx framework */
380                 if (ath_startrecv(sc) != 0) {
381                         DPRINTF(sc, ATH_DBG_FATAL,
382                                 "%s: unable to restart recv logic\n", __func__);
383                         return -EIO;
384                 }
385                 /*
386                  * Change channels and update the h/w rate map
387                  * if we're switching; e.g. 11a to 11b/g.
388                  */
389                 ath_setcurmode(sc, ath_chan2mode(hchan));
390
391                 ath_update_txpow(sc);   /* update tx power state */
392                 /*
393                  * Re-enable interrupts.
394                  */
395                 ath9k_hw_set_interrupts(ah, sc->sc_imask);
396         }
397         return 0;
398 }
399
400 /**********************/
401 /* Chainmask Handling */
402 /**********************/
403
404 static void ath_chainmask_sel_timertimeout(unsigned long data)
405 {
406         struct ath_chainmask_sel *cm = (struct ath_chainmask_sel *)data;
407         cm->switch_allowed = 1;
408 }
409
410 /* Start chainmask select timer */
411 static void ath_chainmask_sel_timerstart(struct ath_chainmask_sel *cm)
412 {
413         cm->switch_allowed = 0;
414         mod_timer(&cm->timer, ath_chainmask_sel_period);
415 }
416
417 /* Stop chainmask select timer */
418 static void ath_chainmask_sel_timerstop(struct ath_chainmask_sel *cm)
419 {
420         cm->switch_allowed = 0;
421         del_timer_sync(&cm->timer);
422 }
423
424 static void ath_chainmask_sel_init(struct ath_softc *sc, struct ath_node *an)
425 {
426         struct ath_chainmask_sel *cm = &an->an_chainmask_sel;
427
428         memzero(cm, sizeof(struct ath_chainmask_sel));
429
430         cm->cur_tx_mask = sc->sc_tx_chainmask;
431         cm->cur_rx_mask = sc->sc_rx_chainmask;
432         cm->tx_avgrssi = ATH_RSSI_DUMMY_MARKER;
433         setup_timer(&cm->timer,
434                 ath_chainmask_sel_timertimeout, (unsigned long) cm);
435 }
436
437 int ath_chainmask_sel_logic(struct ath_softc *sc, struct ath_node *an)
438 {
439         struct ath_chainmask_sel *cm = &an->an_chainmask_sel;
440
441         /*
442          * Disable auto-swtiching in one of the following if conditions.
443          * sc_chainmask_auto_sel is used for internal global auto-switching
444          * enabled/disabled setting
445          */
446         if (sc->sc_ah->ah_caps.tx_chainmask != ATH_CHAINMASK_SEL_3X3) {
447                 cm->cur_tx_mask = sc->sc_tx_chainmask;
448                 return cm->cur_tx_mask;
449         }
450
451         if (cm->tx_avgrssi == ATH_RSSI_DUMMY_MARKER)
452                 return cm->cur_tx_mask;
453
454         if (cm->switch_allowed) {
455                 /* Switch down from tx 3 to tx 2. */
456                 if (cm->cur_tx_mask == ATH_CHAINMASK_SEL_3X3 &&
457                     ATH_RSSI_OUT(cm->tx_avgrssi) >=
458                     ath_chainmask_sel_down_rssi_thres) {
459                         cm->cur_tx_mask = sc->sc_tx_chainmask;
460
461                         /* Don't let another switch happen until
462                          * this timer expires */
463                         ath_chainmask_sel_timerstart(cm);
464                 }
465                 /* Switch up from tx 2 to 3. */
466                 else if (cm->cur_tx_mask == sc->sc_tx_chainmask &&
467                          ATH_RSSI_OUT(cm->tx_avgrssi) <=
468                          ath_chainmask_sel_up_rssi_thres) {
469                         cm->cur_tx_mask = ATH_CHAINMASK_SEL_3X3;
470
471                         /* Don't let another switch happen
472                          * until this timer expires */
473                         ath_chainmask_sel_timerstart(cm);
474                 }
475         }
476
477         return cm->cur_tx_mask;
478 }
479
480 /*
481  * Update tx/rx chainmask. For legacy association,
482  * hard code chainmask to 1x1, for 11n association, use
483  * the chainmask configuration.
484  */
485
486 void ath_update_chainmask(struct ath_softc *sc, int is_ht)
487 {
488         sc->sc_flags |= SC_OP_CHAINMASK_UPDATE;
489         if (is_ht) {
490                 sc->sc_tx_chainmask = sc->sc_ah->ah_caps.tx_chainmask;
491                 sc->sc_rx_chainmask = sc->sc_ah->ah_caps.rx_chainmask;
492         } else {
493                 sc->sc_tx_chainmask = 1;
494                 sc->sc_rx_chainmask = 1;
495         }
496
497         DPRINTF(sc, ATH_DBG_CONFIG, "%s: tx chmask: %d, rx chmask: %d\n",
498                 __func__, sc->sc_tx_chainmask, sc->sc_rx_chainmask);
499 }
500
501 /******************/
502 /* VAP management */
503 /******************/
504
505 /*
506  *  VAP in Listen mode
507  *
508  *  This routine brings the VAP out of the down state into a "listen" state
509  *  where it waits for association requests.  This is used in AP and AdHoc
510  *  modes.
511 */
512
513 int ath_vap_listen(struct ath_softc *sc, int if_id)
514 {
515         struct ath_hal *ah = sc->sc_ah;
516         struct ath_vap *avp;
517         u32 rfilt = 0;
518         DECLARE_MAC_BUF(mac);
519
520         avp = sc->sc_vaps[if_id];
521         if (avp == NULL) {
522                 DPRINTF(sc, ATH_DBG_FATAL, "%s: invalid interface id %u\n",
523                         __func__, if_id);
524                 return -EINVAL;
525         }
526
527 #ifdef CONFIG_SLOW_ANT_DIV
528         ath_slow_ant_div_stop(&sc->sc_antdiv);
529 #endif
530
531         /* update ratectrl about the new state */
532         ath_rate_newstate(sc, avp);
533
534         rfilt = ath_calcrxfilter(sc);
535         ath9k_hw_setrxfilter(ah, rfilt);
536
537         if (sc->sc_ah->ah_opmode == ATH9K_M_STA ||
538             sc->sc_ah->ah_opmode == ATH9K_M_IBSS) {
539                 memcpy(sc->sc_curbssid, ath_bcast_mac, ETH_ALEN);
540                 ath9k_hw_write_associd(ah, sc->sc_curbssid, sc->sc_curaid);
541         } else
542                 sc->sc_curaid = 0;
543
544         DPRINTF(sc, ATH_DBG_CONFIG,
545                 "%s: RX filter 0x%x bssid %s aid 0x%x\n",
546                 __func__, rfilt, print_mac(mac,
547                         sc->sc_curbssid), sc->sc_curaid);
548
549         /*
550          * XXXX
551          * Disable BMISS interrupt when we're not associated
552          */
553         ath9k_hw_set_interrupts(ah,
554                 sc->sc_imask & ~(ATH9K_INT_SWBA | ATH9K_INT_BMISS));
555         sc->sc_imask &= ~(ATH9K_INT_SWBA | ATH9K_INT_BMISS);
556         /* need to reconfigure the beacons when it moves to RUN */
557         sc->sc_flags &= ~SC_OP_BEACONS;
558
559         return 0;
560 }
561
562 int ath_vap_attach(struct ath_softc *sc,
563                    int if_id,
564                    struct ieee80211_vif *if_data,
565                    enum ath9k_opmode opmode)
566 {
567         struct ath_vap *avp;
568
569         if (if_id >= ATH_BCBUF || sc->sc_vaps[if_id] != NULL) {
570                 DPRINTF(sc, ATH_DBG_FATAL,
571                         "%s: Invalid interface id = %u\n", __func__, if_id);
572                 return -EINVAL;
573         }
574
575         switch (opmode) {
576         case ATH9K_M_STA:
577         case ATH9K_M_IBSS:
578         case ATH9K_M_MONITOR:
579                 break;
580         case ATH9K_M_HOSTAP:
581                 /* XXX not right, beacon buffer is allocated on RUN trans */
582                 if (list_empty(&sc->sc_bbuf))
583                         return -ENOMEM;
584                 break;
585         default:
586                 return -EINVAL;
587         }
588
589         /* create ath_vap */
590         avp = kmalloc(sizeof(struct ath_vap), GFP_KERNEL);
591         if (avp == NULL)
592                 return -ENOMEM;
593
594         memzero(avp, sizeof(struct ath_vap));
595         avp->av_if_data = if_data;
596         /* Set the VAP opmode */
597         avp->av_opmode = opmode;
598         avp->av_bslot = -1;
599         INIT_LIST_HEAD(&avp->av_mcastq.axq_q);
600         INIT_LIST_HEAD(&avp->av_mcastq.axq_acq);
601         spin_lock_init(&avp->av_mcastq.axq_lock);
602
603         ath9k_hw_set_tsfadjust(sc->sc_ah, 1);
604
605         sc->sc_vaps[if_id] = avp;
606         sc->sc_nvaps++;
607         /* Set the device opmode */
608         sc->sc_ah->ah_opmode = opmode;
609
610         /* default VAP configuration */
611         avp->av_config.av_fixed_rateset = IEEE80211_FIXED_RATE_NONE;
612         avp->av_config.av_fixed_retryset = 0x03030303;
613
614         return 0;
615 }
616
617 int ath_vap_detach(struct ath_softc *sc, int if_id)
618 {
619         struct ath_hal *ah = sc->sc_ah;
620         struct ath_vap *avp;
621
622         avp = sc->sc_vaps[if_id];
623         if (avp == NULL) {
624                 DPRINTF(sc, ATH_DBG_FATAL, "%s: invalid interface id %u\n",
625                         __func__, if_id);
626                 return -EINVAL;
627         }
628
629         /*
630          * Quiesce the hardware while we remove the vap.  In
631          * particular we need to reclaim all references to the
632          * vap state by any frames pending on the tx queues.
633          *
634          * XXX can we do this w/o affecting other vap's?
635          */
636         ath9k_hw_set_interrupts(ah, 0); /* disable interrupts */
637         ath_draintxq(sc, false);        /* stop xmit side */
638         ath_stoprecv(sc);       /* stop recv side */
639         ath_flushrecv(sc);      /* flush recv queue */
640
641         /* Reclaim any pending mcast bufs on the vap. */
642         ath_tx_draintxq(sc, &avp->av_mcastq, false);
643
644         kfree(avp);
645         sc->sc_vaps[if_id] = NULL;
646         sc->sc_nvaps--;
647
648         return 0;
649 }
650
651 int ath_vap_config(struct ath_softc *sc,
652         int if_id, struct ath_vap_config *if_config)
653 {
654         struct ath_vap *avp;
655
656         if (if_id >= ATH_BCBUF) {
657                 DPRINTF(sc, ATH_DBG_FATAL,
658                         "%s: Invalid interface id = %u\n", __func__, if_id);
659                 return -EINVAL;
660         }
661
662         avp = sc->sc_vaps[if_id];
663         ASSERT(avp != NULL);
664
665         if (avp)
666                 memcpy(&avp->av_config, if_config, sizeof(avp->av_config));
667
668         return 0;
669 }
670
671 /********/
672 /* Core */
673 /********/
674
675 int ath_open(struct ath_softc *sc, struct ath9k_channel *initial_chan)
676 {
677         struct ath_hal *ah = sc->sc_ah;
678         int status;
679         int error = 0;
680         enum ath9k_ht_macmode ht_macmode = ath_cwm_macmode(sc);
681
682         DPRINTF(sc, ATH_DBG_CONFIG, "%s: mode %d\n",
683                 __func__, sc->sc_ah->ah_opmode);
684
685         /*
686          * Stop anything previously setup.  This is safe
687          * whether this is the first time through or not.
688          */
689         ath_stop(sc);
690
691         /* Initialize chanmask selection */
692         sc->sc_tx_chainmask = ah->ah_caps.tx_chainmask;
693         sc->sc_rx_chainmask = ah->ah_caps.rx_chainmask;
694
695         /* Reset SERDES registers */
696         ath9k_hw_configpcipowersave(ah, 0);
697
698         /*
699          * The basic interface to setting the hardware in a good
700          * state is ``reset''.  On return the hardware is known to
701          * be powered up and with interrupts disabled.  This must
702          * be followed by initialization of the appropriate bits
703          * and then setup of the interrupt mask.
704          */
705         sc->sc_curchan = *initial_chan;
706
707         spin_lock_bh(&sc->sc_resetlock);
708         if (!ath9k_hw_reset(ah, &sc->sc_curchan, ht_macmode,
709                            sc->sc_tx_chainmask, sc->sc_rx_chainmask,
710                            sc->sc_ht_extprotspacing, false, &status)) {
711                 DPRINTF(sc, ATH_DBG_FATAL,
712                         "%s: unable to reset hardware; hal status %u "
713                         "(freq %u flags 0x%x)\n", __func__, status,
714                         sc->sc_curchan.channel, sc->sc_curchan.channelFlags);
715                 error = -EIO;
716                 spin_unlock_bh(&sc->sc_resetlock);
717                 goto done;
718         }
719         spin_unlock_bh(&sc->sc_resetlock);
720         /*
721          * This is needed only to setup initial state
722          * but it's best done after a reset.
723          */
724         ath_update_txpow(sc);
725
726         /*
727          * Setup the hardware after reset:
728          * The receive engine is set going.
729          * Frame transmit is handled entirely
730          * in the frame output path; there's nothing to do
731          * here except setup the interrupt mask.
732          */
733         if (ath_startrecv(sc) != 0) {
734                 DPRINTF(sc, ATH_DBG_FATAL,
735                         "%s: unable to start recv logic\n", __func__);
736                 error = -EIO;
737                 goto done;
738         }
739         /* Setup our intr mask. */
740         sc->sc_imask = ATH9K_INT_RX | ATH9K_INT_TX
741                 | ATH9K_INT_RXEOL | ATH9K_INT_RXORN
742                 | ATH9K_INT_FATAL | ATH9K_INT_GLOBAL;
743
744         if (ah->ah_caps.hw_caps & ATH9K_HW_CAP_GTT)
745                 sc->sc_imask |= ATH9K_INT_GTT;
746
747         if (ah->ah_caps.hw_caps & ATH9K_HW_CAP_HT)
748                 sc->sc_imask |= ATH9K_INT_CST;
749
750         /*
751          * Enable MIB interrupts when there are hardware phy counters.
752          * Note we only do this (at the moment) for station mode.
753          */
754         if (ath9k_hw_phycounters(ah) &&
755             ((sc->sc_ah->ah_opmode == ATH9K_M_STA) ||
756              (sc->sc_ah->ah_opmode == ATH9K_M_IBSS)))
757                 sc->sc_imask |= ATH9K_INT_MIB;
758         /*
759          * Some hardware processes the TIM IE and fires an
760          * interrupt when the TIM bit is set.  For hardware
761          * that does, if not overridden by configuration,
762          * enable the TIM interrupt when operating as station.
763          */
764         if ((ah->ah_caps.hw_caps & ATH9K_HW_CAP_ENHANCEDPM) &&
765             (sc->sc_ah->ah_opmode == ATH9K_M_STA) &&
766             !sc->sc_config.swBeaconProcess)
767                 sc->sc_imask |= ATH9K_INT_TIM;
768         /*
769          *  Don't enable interrupts here as we've not yet built our
770          *  vap and node data structures, which will be needed as soon
771          *  as we start receiving.
772          */
773         ath_setcurmode(sc, ath_chan2mode(initial_chan));
774
775         /* XXX: we must make sure h/w is ready and clear invalid flag
776          * before turning on interrupt. */
777         sc->sc_flags &= ~SC_OP_INVALID;
778 done:
779         return error;
780 }
781
782 int ath_reset(struct ath_softc *sc, bool retry_tx)
783 {
784         struct ath_hal *ah = sc->sc_ah;
785         int status;
786         int error = 0;
787         enum ath9k_ht_macmode ht_macmode = ath_cwm_macmode(sc);
788
789         ath9k_hw_set_interrupts(ah, 0); /* disable interrupts */
790         ath_draintxq(sc, retry_tx);     /* stop xmit */
791         ath_stoprecv(sc);               /* stop recv */
792         ath_flushrecv(sc);              /* flush recv queue */
793
794         /* Reset chip */
795         spin_lock_bh(&sc->sc_resetlock);
796         if (!ath9k_hw_reset(ah, &sc->sc_curchan,
797                            ht_macmode,
798                            sc->sc_tx_chainmask, sc->sc_rx_chainmask,
799                            sc->sc_ht_extprotspacing, false, &status)) {
800                 DPRINTF(sc, ATH_DBG_FATAL,
801                         "%s: unable to reset hardware; hal status %u\n",
802                         __func__, status);
803                 error = -EIO;
804         }
805         spin_unlock_bh(&sc->sc_resetlock);
806
807         if (ath_startrecv(sc) != 0)     /* restart recv */
808                 DPRINTF(sc, ATH_DBG_FATAL,
809                         "%s: unable to start recv logic\n", __func__);
810
811         /*
812          * We may be doing a reset in response to a request
813          * that changes the channel so update any state that
814          * might change as a result.
815          */
816         ath_setcurmode(sc, ath_chan2mode(&sc->sc_curchan));
817
818         ath_update_txpow(sc);
819
820         if (sc->sc_flags & SC_OP_BEACONS)
821                 ath_beacon_config(sc, ATH_IF_ID_ANY);   /* restart beacons */
822
823         ath9k_hw_set_interrupts(ah, sc->sc_imask);
824
825         /* Restart the txq */
826         if (retry_tx) {
827                 int i;
828                 for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++) {
829                         if (ATH_TXQ_SETUP(sc, i)) {
830                                 spin_lock_bh(&sc->sc_txq[i].axq_lock);
831                                 ath_txq_schedule(sc, &sc->sc_txq[i]);
832                                 spin_unlock_bh(&sc->sc_txq[i].axq_lock);
833                         }
834                 }
835         }
836
837         return error;
838 }
839
840 int ath_suspend(struct ath_softc *sc)
841 {
842         struct ath_hal *ah = sc->sc_ah;
843
844         /* No I/O if device has been surprise removed */
845         if (sc->sc_flags & SC_OP_INVALID)
846                 return -EIO;
847
848         /* Shut off the interrupt before setting sc->sc_invalid to '1' */
849         ath9k_hw_set_interrupts(ah, 0);
850
851         /* XXX: we must make sure h/w will not generate any interrupt
852          * before setting the invalid flag. */
853         sc->sc_flags |= SC_OP_INVALID;
854
855         /* disable HAL and put h/w to sleep */
856         ath9k_hw_disable(sc->sc_ah);
857
858         ath9k_hw_configpcipowersave(sc->sc_ah, 1);
859
860         return 0;
861 }
862
863 /* Interrupt handler.  Most of the actual processing is deferred.
864  * It's the caller's responsibility to ensure the chip is awake. */
865
866 irqreturn_t ath_isr(int irq, void *dev)
867 {
868         struct ath_softc *sc = dev;
869         struct ath_hal *ah = sc->sc_ah;
870         enum ath9k_int status;
871         bool sched = false;
872
873         do {
874                 if (sc->sc_flags & SC_OP_INVALID) {
875                         /*
876                          * The hardware is not ready/present, don't
877                          * touch anything. Note this can happen early
878                          * on if the IRQ is shared.
879                          */
880                         return IRQ_NONE;
881                 }
882                 if (!ath9k_hw_intrpend(ah)) {   /* shared irq, not for us */
883                         return IRQ_NONE;
884                 }
885
886                 /*
887                  * Figure out the reason(s) for the interrupt.  Note
888                  * that the hal returns a pseudo-ISR that may include
889                  * bits we haven't explicitly enabled so we mask the
890                  * value to insure we only process bits we requested.
891                  */
892                 ath9k_hw_getisr(ah, &status);   /* NB: clears ISR too */
893
894                 status &= sc->sc_imask; /* discard unasked-for bits */
895
896                 /*
897                  * If there are no status bits set, then this interrupt was not
898                  * for me (should have been caught above).
899                  */
900
901                 if (!status)
902                         return IRQ_NONE;
903
904                 sc->sc_intrstatus = status;
905
906                 if (status & ATH9K_INT_FATAL) {
907                         /* need a chip reset */
908                         sched = true;
909                 } else if (status & ATH9K_INT_RXORN) {
910                         /* need a chip reset */
911                         sched = true;
912                 } else {
913                         if (status & ATH9K_INT_SWBA) {
914                                 /* schedule a tasklet for beacon handling */
915                                 tasklet_schedule(&sc->bcon_tasklet);
916                         }
917                         if (status & ATH9K_INT_RXEOL) {
918                                 /*
919                                  * NB: the hardware should re-read the link when
920                                  *     RXE bit is written, but it doesn't work
921                                  *     at least on older hardware revs.
922                                  */
923                                 sched = true;
924                         }
925
926                         if (status & ATH9K_INT_TXURN)
927                                 /* bump tx trigger level */
928                                 ath9k_hw_updatetxtriglevel(ah, true);
929                         /* XXX: optimize this */
930                         if (status & ATH9K_INT_RX)
931                                 sched = true;
932                         if (status & ATH9K_INT_TX)
933                                 sched = true;
934                         if (status & ATH9K_INT_BMISS)
935                                 sched = true;
936                         /* carrier sense timeout */
937                         if (status & ATH9K_INT_CST)
938                                 sched = true;
939                         if (status & ATH9K_INT_MIB) {
940                                 /*
941                                  * Disable interrupts until we service the MIB
942                                  * interrupt; otherwise it will continue to
943                                  * fire.
944                                  */
945                                 ath9k_hw_set_interrupts(ah, 0);
946                                 /*
947                                  * Let the hal handle the event. We assume
948                                  * it will clear whatever condition caused
949                                  * the interrupt.
950                                  */
951                                 ath9k_hw_procmibevent(ah, &sc->sc_halstats);
952                                 ath9k_hw_set_interrupts(ah, sc->sc_imask);
953                         }
954                         if (status & ATH9K_INT_TIM_TIMER) {
955                                 if (!(ah->ah_caps.hw_caps &
956                                       ATH9K_HW_CAP_AUTOSLEEP)) {
957                                         /* Clear RxAbort bit so that we can
958                                          * receive frames */
959                                         ath9k_hw_setrxabort(ah, 0);
960                                         sched = true;
961                                 }
962                         }
963                 }
964         } while (0);
965
966         if (sched) {
967                 /* turn off every interrupt except SWBA */
968                 ath9k_hw_set_interrupts(ah, (sc->sc_imask & ATH9K_INT_SWBA));
969                 tasklet_schedule(&sc->intr_tq);
970         }
971
972         return IRQ_HANDLED;
973 }
974
975 /* Deferred interrupt processing  */
976
977 static void ath9k_tasklet(unsigned long data)
978 {
979         struct ath_softc *sc = (struct ath_softc *)data;
980         u32 status = sc->sc_intrstatus;
981
982         if (status & ATH9K_INT_FATAL) {
983                 /* need a chip reset */
984                 ath_reset(sc, false);
985                 return;
986         } else {
987
988                 if (status &
989                     (ATH9K_INT_RX | ATH9K_INT_RXEOL | ATH9K_INT_RXORN)) {
990                         /* XXX: fill me in */
991                         /*
992                         if (status & ATH9K_INT_RXORN) {
993                         }
994                         if (status & ATH9K_INT_RXEOL) {
995                         }
996                         */
997                         spin_lock_bh(&sc->sc_rxflushlock);
998                         ath_rx_tasklet(sc, 0);
999                         spin_unlock_bh(&sc->sc_rxflushlock);
1000                 }
1001                 /* XXX: optimize this */
1002                 if (status & ATH9K_INT_TX)
1003                         ath_tx_tasklet(sc);
1004                 /* XXX: fill me in */
1005                 /*
1006                 if (status & ATH9K_INT_BMISS) {
1007                 }
1008                 if (status & (ATH9K_INT_TIM | ATH9K_INT_DTIMSYNC)) {
1009                         if (status & ATH9K_INT_TIM) {
1010                         }
1011                         if (status & ATH9K_INT_DTIMSYNC) {
1012                         }
1013                 }
1014                 */
1015         }
1016
1017         /* re-enable hardware interrupt */
1018         ath9k_hw_set_interrupts(sc->sc_ah, sc->sc_imask);
1019 }
1020
1021 int ath_init(u16 devid, struct ath_softc *sc)
1022 {
1023         struct ath_hal *ah = NULL;
1024         int status;
1025         int error = 0, i;
1026         int csz = 0;
1027         u32 rd;
1028
1029         /* XXX: hardware will not be ready until ath_open() being called */
1030         sc->sc_flags |= SC_OP_INVALID;
1031
1032         sc->sc_debug = DBG_DEFAULT;
1033         DPRINTF(sc, ATH_DBG_CONFIG, "%s: devid 0x%x\n", __func__, devid);
1034
1035         /* Initialize tasklet */
1036         tasklet_init(&sc->intr_tq, ath9k_tasklet, (unsigned long)sc);
1037         tasklet_init(&sc->bcon_tasklet, ath9k_beacon_tasklet,
1038                      (unsigned long)sc);
1039
1040         /*
1041          * Cache line size is used to size and align various
1042          * structures used to communicate with the hardware.
1043          */
1044         bus_read_cachesize(sc, &csz);
1045         /* XXX assert csz is non-zero */
1046         sc->sc_cachelsz = csz << 2;     /* convert to bytes */
1047
1048         spin_lock_init(&sc->sc_resetlock);
1049
1050         ah = ath9k_hw_attach(devid, sc, sc->mem, &status);
1051         if (ah == NULL) {
1052                 DPRINTF(sc, ATH_DBG_FATAL,
1053                         "%s: unable to attach hardware; HAL status %u\n",
1054                         __func__, status);
1055                 error = -ENXIO;
1056                 goto bad;
1057         }
1058         sc->sc_ah = ah;
1059
1060         /* Get the chipset-specific aggr limit. */
1061         sc->sc_rtsaggrlimit = ah->ah_caps.rts_aggr_limit;
1062
1063         /* Get the hardware key cache size. */
1064         sc->sc_keymax = ah->ah_caps.keycache_size;
1065         if (sc->sc_keymax > ATH_KEYMAX) {
1066                 DPRINTF(sc, ATH_DBG_KEYCACHE,
1067                         "%s: Warning, using only %u entries in %u key cache\n",
1068                         __func__, ATH_KEYMAX, sc->sc_keymax);
1069                 sc->sc_keymax = ATH_KEYMAX;
1070         }
1071
1072         /*
1073          * Reset the key cache since some parts do not
1074          * reset the contents on initial power up.
1075          */
1076         for (i = 0; i < sc->sc_keymax; i++)
1077                 ath9k_hw_keyreset(ah, (u16) i);
1078         /*
1079          * Mark key cache slots associated with global keys
1080          * as in use.  If we knew TKIP was not to be used we
1081          * could leave the +32, +64, and +32+64 slots free.
1082          * XXX only for splitmic.
1083          */
1084         for (i = 0; i < IEEE80211_WEP_NKID; i++) {
1085                 set_bit(i, sc->sc_keymap);
1086                 set_bit(i + 32, sc->sc_keymap);
1087                 set_bit(i + 64, sc->sc_keymap);
1088                 set_bit(i + 32 + 64, sc->sc_keymap);
1089         }
1090         /*
1091          * Collect the channel list using the default country
1092          * code and including outdoor channels.  The 802.11 layer
1093          * is resposible for filtering this list based on settings
1094          * like the phy mode.
1095          */
1096         rd = ah->ah_currentRD;
1097
1098         error = ath_setup_channels(sc);
1099         if (error)
1100                 goto bad;
1101
1102         /* default to STA mode */
1103         sc->sc_ah->ah_opmode = ATH9K_M_MONITOR;
1104
1105         /* Setup rate tables */
1106
1107         ath_setup_rates(sc, IEEE80211_BAND_2GHZ);
1108         ath_setup_rates(sc, IEEE80211_BAND_5GHZ);
1109
1110         /* NB: setup here so ath_rate_update is happy */
1111         ath_setcurmode(sc, ATH9K_MODE_11A);
1112
1113         /*
1114          * Allocate hardware transmit queues: one queue for
1115          * beacon frames and one data queue for each QoS
1116          * priority.  Note that the hal handles reseting
1117          * these queues at the needed time.
1118          */
1119         sc->sc_bhalq = ath_beaconq_setup(ah);
1120         if (sc->sc_bhalq == -1) {
1121                 DPRINTF(sc, ATH_DBG_FATAL,
1122                         "%s: unable to setup a beacon xmit queue\n", __func__);
1123                 error = -EIO;
1124                 goto bad2;
1125         }
1126         sc->sc_cabq = ath_txq_setup(sc, ATH9K_TX_QUEUE_CAB, 0);
1127         if (sc->sc_cabq == NULL) {
1128                 DPRINTF(sc, ATH_DBG_FATAL,
1129                         "%s: unable to setup CAB xmit queue\n", __func__);
1130                 error = -EIO;
1131                 goto bad2;
1132         }
1133
1134         sc->sc_config.cabqReadytime = ATH_CABQ_READY_TIME;
1135         ath_cabq_update(sc);
1136
1137         for (i = 0; i < ARRAY_SIZE(sc->sc_haltype2q); i++)
1138                 sc->sc_haltype2q[i] = -1;
1139
1140         /* Setup data queues */
1141         /* NB: ensure BK queue is the lowest priority h/w queue */
1142         if (!ath_tx_setup(sc, ATH9K_WME_AC_BK)) {
1143                 DPRINTF(sc, ATH_DBG_FATAL,
1144                         "%s: unable to setup xmit queue for BK traffic\n",
1145                         __func__);
1146                 error = -EIO;
1147                 goto bad2;
1148         }
1149
1150         if (!ath_tx_setup(sc, ATH9K_WME_AC_BE)) {
1151                 DPRINTF(sc, ATH_DBG_FATAL,
1152                         "%s: unable to setup xmit queue for BE traffic\n",
1153                         __func__);
1154                 error = -EIO;
1155                 goto bad2;
1156         }
1157         if (!ath_tx_setup(sc, ATH9K_WME_AC_VI)) {
1158                 DPRINTF(sc, ATH_DBG_FATAL,
1159                         "%s: unable to setup xmit queue for VI traffic\n",
1160                         __func__);
1161                 error = -EIO;
1162                 goto bad2;
1163         }
1164         if (!ath_tx_setup(sc, ATH9K_WME_AC_VO)) {
1165                 DPRINTF(sc, ATH_DBG_FATAL,
1166                         "%s: unable to setup xmit queue for VO traffic\n",
1167                         __func__);
1168                 error = -EIO;
1169                 goto bad2;
1170         }
1171
1172         sc->sc_rc = ath_rate_attach(ah);
1173         if (sc->sc_rc == NULL) {
1174                 error = EIO;
1175                 goto bad2;
1176         }
1177
1178         if (ath9k_hw_getcapability(ah, ATH9K_CAP_CIPHER,
1179                                    ATH9K_CIPHER_TKIP, NULL)) {
1180                 /*
1181                  * Whether we should enable h/w TKIP MIC.
1182                  * XXX: if we don't support WME TKIP MIC, then we wouldn't
1183                  * report WMM capable, so it's always safe to turn on
1184                  * TKIP MIC in this case.
1185                  */
1186                 ath9k_hw_setcapability(sc->sc_ah, ATH9K_CAP_TKIP_MIC,
1187                                        0, 1, NULL);
1188         }
1189
1190         /*
1191          * Check whether the separate key cache entries
1192          * are required to handle both tx+rx MIC keys.
1193          * With split mic keys the number of stations is limited
1194          * to 27 otherwise 59.
1195          */
1196         if (ath9k_hw_getcapability(ah, ATH9K_CAP_CIPHER,
1197                                    ATH9K_CIPHER_TKIP, NULL)
1198             && ath9k_hw_getcapability(ah, ATH9K_CAP_CIPHER,
1199                                       ATH9K_CIPHER_MIC, NULL)
1200             && ath9k_hw_getcapability(ah, ATH9K_CAP_TKIP_SPLIT,
1201                                       0, NULL))
1202                 sc->sc_splitmic = 1;
1203
1204         /* turn on mcast key search if possible */
1205         if (!ath9k_hw_getcapability(ah, ATH9K_CAP_MCAST_KEYSRCH, 0, NULL))
1206                 (void)ath9k_hw_setcapability(ah, ATH9K_CAP_MCAST_KEYSRCH, 1,
1207                                              1, NULL);
1208
1209         sc->sc_config.txpowlimit = ATH_TXPOWER_MAX;
1210         sc->sc_config.txpowlimit_override = 0;
1211
1212         /* 11n Capabilities */
1213         if (ah->ah_caps.hw_caps & ATH9K_HW_CAP_HT) {
1214                 sc->sc_flags |= SC_OP_TXAGGR;
1215                 sc->sc_flags |= SC_OP_RXAGGR;
1216         }
1217
1218         sc->sc_tx_chainmask = ah->ah_caps.tx_chainmask;
1219         sc->sc_rx_chainmask = ah->ah_caps.rx_chainmask;
1220
1221         /* Configuration for rx chain detection */
1222         sc->sc_rxchaindetect_ref = 0;
1223         sc->sc_rxchaindetect_thresh5GHz = 35;
1224         sc->sc_rxchaindetect_thresh2GHz = 35;
1225         sc->sc_rxchaindetect_delta5GHz = 30;
1226         sc->sc_rxchaindetect_delta2GHz = 30;
1227
1228         ath9k_hw_setcapability(ah, ATH9K_CAP_DIVERSITY, 1, true, NULL);
1229         sc->sc_defant = ath9k_hw_getdefantenna(ah);
1230
1231         ath9k_hw_getmac(ah, sc->sc_myaddr);
1232         if (ah->ah_caps.hw_caps & ATH9K_HW_CAP_BSSIDMASK) {
1233                 ath9k_hw_getbssidmask(ah, sc->sc_bssidmask);
1234                 ATH_SET_VAP_BSSID_MASK(sc->sc_bssidmask);
1235                 ath9k_hw_setbssidmask(ah, sc->sc_bssidmask);
1236         }
1237         sc->sc_slottime = ATH9K_SLOT_TIME_9;    /* default to short slot time */
1238
1239         /* initialize beacon slots */
1240         for (i = 0; i < ARRAY_SIZE(sc->sc_bslot); i++)
1241                 sc->sc_bslot[i] = ATH_IF_ID_ANY;
1242
1243         /* save MISC configurations */
1244         sc->sc_config.swBeaconProcess = 1;
1245
1246 #ifdef CONFIG_SLOW_ANT_DIV
1247         /* range is 40 - 255, we use something in the middle */
1248         ath_slow_ant_div_init(&sc->sc_antdiv, sc, 0x127);
1249 #endif
1250
1251         return 0;
1252 bad2:
1253         /* cleanup tx queues */
1254         for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++)
1255                 if (ATH_TXQ_SETUP(sc, i))
1256                         ath_tx_cleanupq(sc, &sc->sc_txq[i]);
1257 bad:
1258         if (ah)
1259                 ath9k_hw_detach(ah);
1260         return error;
1261 }
1262
1263 void ath_deinit(struct ath_softc *sc)
1264 {
1265         struct ath_hal *ah = sc->sc_ah;
1266         int i;
1267
1268         DPRINTF(sc, ATH_DBG_CONFIG, "%s\n", __func__);
1269
1270         ath_stop(sc);
1271         if (!(sc->sc_flags & SC_OP_INVALID))
1272                 ath9k_hw_setpower(sc->sc_ah, ATH9K_PM_AWAKE);
1273         ath_rate_detach(sc->sc_rc);
1274         /* cleanup tx queues */
1275         for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++)
1276                 if (ATH_TXQ_SETUP(sc, i))
1277                         ath_tx_cleanupq(sc, &sc->sc_txq[i]);
1278         ath9k_hw_detach(ah);
1279 }
1280
1281 /*******************/
1282 /* Node Management */
1283 /*******************/
1284
1285 struct ath_node *ath_node_attach(struct ath_softc *sc, u8 *addr, int if_id)
1286 {
1287         struct ath_vap *avp;
1288         struct ath_node *an;
1289         DECLARE_MAC_BUF(mac);
1290
1291         avp = sc->sc_vaps[if_id];
1292         ASSERT(avp != NULL);
1293
1294         /* mac80211 sta_notify callback is from an IRQ context, so no sleep */
1295         an = kmalloc(sizeof(struct ath_node), GFP_ATOMIC);
1296         if (an == NULL)
1297                 return NULL;
1298         memzero(an, sizeof(*an));
1299
1300         an->an_sc = sc;
1301         memcpy(an->an_addr, addr, ETH_ALEN);
1302         atomic_set(&an->an_refcnt, 1);
1303
1304         /* set up per-node tx/rx state */
1305         ath_tx_node_init(sc, an);
1306         ath_rx_node_init(sc, an);
1307
1308         ath_chainmask_sel_init(sc, an);
1309         ath_chainmask_sel_timerstart(&an->an_chainmask_sel);
1310         list_add(&an->list, &sc->node_list);
1311
1312         return an;
1313 }
1314
1315 void ath_node_detach(struct ath_softc *sc, struct ath_node *an, bool bh_flag)
1316 {
1317         unsigned long flags;
1318
1319         DECLARE_MAC_BUF(mac);
1320
1321         ath_chainmask_sel_timerstop(&an->an_chainmask_sel);
1322         an->an_flags |= ATH_NODE_CLEAN;
1323         ath_tx_node_cleanup(sc, an, bh_flag);
1324         ath_rx_node_cleanup(sc, an);
1325
1326         ath_tx_node_free(sc, an);
1327         ath_rx_node_free(sc, an);
1328
1329         spin_lock_irqsave(&sc->node_lock, flags);
1330
1331         list_del(&an->list);
1332
1333         spin_unlock_irqrestore(&sc->node_lock, flags);
1334
1335         kfree(an);
1336 }
1337
1338 /* Finds a node and increases the refcnt if found */
1339
1340 struct ath_node *ath_node_get(struct ath_softc *sc, u8 *addr)
1341 {
1342         struct ath_node *an = NULL, *an_found = NULL;
1343
1344         if (list_empty(&sc->node_list)) /* FIXME */
1345                 goto out;
1346         list_for_each_entry(an, &sc->node_list, list) {
1347                 if (!compare_ether_addr(an->an_addr, addr)) {
1348                         atomic_inc(&an->an_refcnt);
1349                         an_found = an;
1350                         break;
1351                 }
1352         }
1353 out:
1354         return an_found;
1355 }
1356
1357 /* Decrements the refcnt and if it drops to zero, detach the node */
1358
1359 void ath_node_put(struct ath_softc *sc, struct ath_node *an, bool bh_flag)
1360 {
1361         if (atomic_dec_and_test(&an->an_refcnt))
1362                 ath_node_detach(sc, an, bh_flag);
1363 }
1364
1365 /* Finds a node, doesn't increment refcnt. Caller must hold sc->node_lock */
1366 struct ath_node *ath_node_find(struct ath_softc *sc, u8 *addr)
1367 {
1368         struct ath_node *an = NULL, *an_found = NULL;
1369
1370         if (list_empty(&sc->node_list))
1371                 return NULL;
1372
1373         list_for_each_entry(an, &sc->node_list, list)
1374                 if (!compare_ether_addr(an->an_addr, addr)) {
1375                         an_found = an;
1376                         break;
1377                 }
1378
1379         return an_found;
1380 }
1381
1382 /*
1383  * Set up New Node
1384  *
1385  * Setup driver-specific state for a newly associated node.  This routine
1386  * really only applies if compression or XR are enabled, there is no code
1387  * covering any other cases.
1388 */
1389
1390 void ath_newassoc(struct ath_softc *sc,
1391         struct ath_node *an, int isnew, int isuapsd)
1392 {
1393         int tidno;
1394
1395         /* if station reassociates, tear down the aggregation state. */
1396         if (!isnew) {
1397                 for (tidno = 0; tidno < WME_NUM_TID; tidno++) {
1398                         if (sc->sc_flags & SC_OP_TXAGGR)
1399                                 ath_tx_aggr_teardown(sc, an, tidno);
1400                         if (sc->sc_flags & SC_OP_RXAGGR)
1401                                 ath_rx_aggr_teardown(sc, an, tidno);
1402                 }
1403         }
1404         an->an_flags = 0;
1405 }
1406
1407 /**************/
1408 /* Encryption */
1409 /**************/
1410
1411 void ath_key_reset(struct ath_softc *sc, u16 keyix, int freeslot)
1412 {
1413         ath9k_hw_keyreset(sc->sc_ah, keyix);
1414         if (freeslot)
1415                 clear_bit(keyix, sc->sc_keymap);
1416 }
1417
1418 int ath_keyset(struct ath_softc *sc,
1419                u16 keyix,
1420                struct ath9k_keyval *hk,
1421                const u8 mac[ETH_ALEN])
1422 {
1423         bool status;
1424
1425         status = ath9k_hw_set_keycache_entry(sc->sc_ah,
1426                 keyix, hk, mac, false);
1427
1428         return status != false;
1429 }
1430
1431 /***********************/
1432 /* TX Power/Regulatory */
1433 /***********************/
1434
1435 /*
1436  *  Set Transmit power in HAL
1437  *
1438  *  This routine makes the actual HAL calls to set the new transmit power
1439  *  limit.
1440 */
1441
1442 void ath_update_txpow(struct ath_softc *sc)
1443 {
1444         struct ath_hal *ah = sc->sc_ah;
1445         u32 txpow;
1446
1447         if (sc->sc_curtxpow != sc->sc_config.txpowlimit) {
1448                 ath9k_hw_set_txpowerlimit(ah, sc->sc_config.txpowlimit);
1449                 /* read back in case value is clamped */
1450                 ath9k_hw_getcapability(ah, ATH9K_CAP_TXPOW, 1, &txpow);
1451                 sc->sc_curtxpow = txpow;
1452         }
1453 }
1454
1455 /* Return the current country and domain information */
1456 void ath_get_currentCountry(struct ath_softc *sc,
1457         struct ath9k_country_entry *ctry)
1458 {
1459         ath9k_regd_get_current_country(sc->sc_ah, ctry);
1460
1461         /* If HAL not specific yet, since it is band dependent,
1462          * use the one we passed in. */
1463         if (ctry->countryCode == CTRY_DEFAULT) {
1464                 ctry->iso[0] = 0;
1465                 ctry->iso[1] = 0;
1466         } else if (ctry->iso[0] && ctry->iso[1]) {
1467                 if (!ctry->iso[2]) {
1468                         if (ath_outdoor)
1469                                 ctry->iso[2] = 'O';
1470                         else
1471                                 ctry->iso[2] = 'I';
1472                 }
1473         }
1474 }
1475
1476 /**************************/
1477 /* Slow Antenna Diversity */
1478 /**************************/
1479
1480 void ath_slow_ant_div_init(struct ath_antdiv *antdiv,
1481                            struct ath_softc *sc,
1482                            int32_t rssitrig)
1483 {
1484         int trig;
1485
1486         /* antdivf_rssitrig can range from 40 - 0xff */
1487         trig = (rssitrig > 0xff) ? 0xff : rssitrig;
1488         trig = (rssitrig < 40) ? 40 : rssitrig;
1489
1490         antdiv->antdiv_sc = sc;
1491         antdiv->antdivf_rssitrig = trig;
1492 }
1493
1494 void ath_slow_ant_div_start(struct ath_antdiv *antdiv,
1495                             u8 num_antcfg,
1496                             const u8 *bssid)
1497 {
1498         antdiv->antdiv_num_antcfg =
1499                 num_antcfg < ATH_ANT_DIV_MAX_CFG ?
1500                 num_antcfg : ATH_ANT_DIV_MAX_CFG;
1501         antdiv->antdiv_state = ATH_ANT_DIV_IDLE;
1502         antdiv->antdiv_curcfg = 0;
1503         antdiv->antdiv_bestcfg = 0;
1504         antdiv->antdiv_laststatetsf = 0;
1505
1506         memcpy(antdiv->antdiv_bssid, bssid, sizeof(antdiv->antdiv_bssid));
1507
1508         antdiv->antdiv_start = 1;
1509 }
1510
1511 void ath_slow_ant_div_stop(struct ath_antdiv *antdiv)
1512 {
1513         antdiv->antdiv_start = 0;
1514 }
1515
1516 static int32_t ath_find_max_val(int32_t *val,
1517         u8 num_val, u8 *max_index)
1518 {
1519         u32 MaxVal = *val++;
1520         u32 cur_index = 0;
1521
1522         *max_index = 0;
1523         while (++cur_index < num_val) {
1524                 if (*val > MaxVal) {
1525                         MaxVal = *val;
1526                         *max_index = cur_index;
1527                 }
1528
1529                 val++;
1530         }
1531
1532         return MaxVal;
1533 }
1534
1535 void ath_slow_ant_div(struct ath_antdiv *antdiv,
1536                       struct ieee80211_hdr *hdr,
1537                       struct ath_rx_status *rx_stats)
1538 {
1539         struct ath_softc *sc = antdiv->antdiv_sc;
1540         struct ath_hal *ah = sc->sc_ah;
1541         u64 curtsf = 0;
1542         u8 bestcfg, curcfg = antdiv->antdiv_curcfg;
1543         __le16 fc = hdr->frame_control;
1544
1545         if (antdiv->antdiv_start && ieee80211_is_beacon(fc)
1546             && !compare_ether_addr(hdr->addr3, antdiv->antdiv_bssid)) {
1547                 antdiv->antdiv_lastbrssi[curcfg] = rx_stats->rs_rssi;
1548                 antdiv->antdiv_lastbtsf[curcfg] = ath9k_hw_gettsf64(sc->sc_ah);
1549                 curtsf = antdiv->antdiv_lastbtsf[curcfg];
1550         } else {
1551                 return;
1552         }
1553
1554         switch (antdiv->antdiv_state) {
1555         case ATH_ANT_DIV_IDLE:
1556                 if ((antdiv->antdiv_lastbrssi[curcfg] <
1557                      antdiv->antdivf_rssitrig)
1558                     && ((curtsf - antdiv->antdiv_laststatetsf) >
1559                         ATH_ANT_DIV_MIN_IDLE_US)) {
1560
1561                         curcfg++;
1562                         if (curcfg == antdiv->antdiv_num_antcfg)
1563                                 curcfg = 0;
1564
1565                         if (!ath9k_hw_select_antconfig(ah, curcfg)) {
1566                                 antdiv->antdiv_bestcfg = antdiv->antdiv_curcfg;
1567                                 antdiv->antdiv_curcfg = curcfg;
1568                                 antdiv->antdiv_laststatetsf = curtsf;
1569                                 antdiv->antdiv_state = ATH_ANT_DIV_SCAN;
1570                         }
1571                 }
1572                 break;
1573
1574         case ATH_ANT_DIV_SCAN:
1575                 if ((curtsf - antdiv->antdiv_laststatetsf) <
1576                     ATH_ANT_DIV_MIN_SCAN_US)
1577                         break;
1578
1579                 curcfg++;
1580                 if (curcfg == antdiv->antdiv_num_antcfg)
1581                         curcfg = 0;
1582
1583                 if (curcfg == antdiv->antdiv_bestcfg) {
1584                         ath_find_max_val(antdiv->antdiv_lastbrssi,
1585                                    antdiv->antdiv_num_antcfg, &bestcfg);
1586                         if (!ath9k_hw_select_antconfig(ah, bestcfg)) {
1587                                 antdiv->antdiv_bestcfg = bestcfg;
1588                                 antdiv->antdiv_curcfg = bestcfg;
1589                                 antdiv->antdiv_laststatetsf = curtsf;
1590                                 antdiv->antdiv_state = ATH_ANT_DIV_IDLE;
1591                         }
1592                 } else {
1593                         if (!ath9k_hw_select_antconfig(ah, curcfg)) {
1594                                 antdiv->antdiv_curcfg = curcfg;
1595                                 antdiv->antdiv_laststatetsf = curtsf;
1596                                 antdiv->antdiv_state = ATH_ANT_DIV_SCAN;
1597                         }
1598                 }
1599
1600                 break;
1601         }
1602 }
1603
1604 /***********************/
1605 /* Descriptor Handling */
1606 /***********************/
1607
1608 /*
1609  *  Set up DMA descriptors
1610  *
1611  *  This function will allocate both the DMA descriptor structure, and the
1612  *  buffers it contains.  These are used to contain the descriptors used
1613  *  by the system.
1614 */
1615
1616 int ath_descdma_setup(struct ath_softc *sc,
1617                       struct ath_descdma *dd,
1618                       struct list_head *head,
1619                       const char *name,
1620                       int nbuf,
1621                       int ndesc)
1622 {
1623 #define DS2PHYS(_dd, _ds)                                               \
1624         ((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
1625 #define ATH_DESC_4KB_BOUND_CHECK(_daddr) ((((_daddr) & 0xFFF) > 0xF7F) ? 1 : 0)
1626 #define ATH_DESC_4KB_BOUND_NUM_SKIPPED(_len) ((_len) / 4096)
1627
1628         struct ath_desc *ds;
1629         struct ath_buf *bf;
1630         int i, bsize, error;
1631
1632         DPRINTF(sc, ATH_DBG_CONFIG, "%s: %s DMA: %u buffers %u desc/buf\n",
1633                 __func__, name, nbuf, ndesc);
1634
1635         /* ath_desc must be a multiple of DWORDs */
1636         if ((sizeof(struct ath_desc) % 4) != 0) {
1637                 DPRINTF(sc, ATH_DBG_FATAL, "%s: ath_desc not DWORD aligned\n",
1638                         __func__);
1639                 ASSERT((sizeof(struct ath_desc) % 4) == 0);
1640                 error = -ENOMEM;
1641                 goto fail;
1642         }
1643
1644         dd->dd_name = name;
1645         dd->dd_desc_len = sizeof(struct ath_desc) * nbuf * ndesc;
1646
1647         /*
1648          * Need additional DMA memory because we can't use
1649          * descriptors that cross the 4K page boundary. Assume
1650          * one skipped descriptor per 4K page.
1651          */
1652         if (!(sc->sc_ah->ah_caps.hw_caps & ATH9K_HW_CAP_4KB_SPLITTRANS)) {
1653                 u32 ndesc_skipped =
1654                         ATH_DESC_4KB_BOUND_NUM_SKIPPED(dd->dd_desc_len);
1655                 u32 dma_len;
1656
1657                 while (ndesc_skipped) {
1658                         dma_len = ndesc_skipped * sizeof(struct ath_desc);
1659                         dd->dd_desc_len += dma_len;
1660
1661                         ndesc_skipped = ATH_DESC_4KB_BOUND_NUM_SKIPPED(dma_len);
1662                 };
1663         }
1664
1665         /* allocate descriptors */
1666         dd->dd_desc = pci_alloc_consistent(sc->pdev,
1667                               dd->dd_desc_len,
1668                               &dd->dd_desc_paddr);
1669         if (dd->dd_desc == NULL) {
1670                 error = -ENOMEM;
1671                 goto fail;
1672         }
1673         ds = dd->dd_desc;
1674         DPRINTF(sc, ATH_DBG_CONFIG, "%s: %s DMA map: %p (%u) -> %llx (%u)\n",
1675                 __func__, dd->dd_name, ds, (u32) dd->dd_desc_len,
1676                 ito64(dd->dd_desc_paddr), /*XXX*/(u32) dd->dd_desc_len);
1677
1678         /* allocate buffers */
1679         bsize = sizeof(struct ath_buf) * nbuf;
1680         bf = kmalloc(bsize, GFP_KERNEL);
1681         if (bf == NULL) {
1682                 error = -ENOMEM;
1683                 goto fail2;
1684         }
1685         memzero(bf, bsize);
1686         dd->dd_bufptr = bf;
1687
1688         INIT_LIST_HEAD(head);
1689         for (i = 0; i < nbuf; i++, bf++, ds += ndesc) {
1690                 bf->bf_desc = ds;
1691                 bf->bf_daddr = DS2PHYS(dd, ds);
1692
1693                 if (!(sc->sc_ah->ah_caps.hw_caps &
1694                       ATH9K_HW_CAP_4KB_SPLITTRANS)) {
1695                         /*
1696                          * Skip descriptor addresses which can cause 4KB
1697                          * boundary crossing (addr + length) with a 32 dword
1698                          * descriptor fetch.
1699                          */
1700                         while (ATH_DESC_4KB_BOUND_CHECK(bf->bf_daddr)) {
1701                                 ASSERT((caddr_t) bf->bf_desc <
1702                                        ((caddr_t) dd->dd_desc +
1703                                         dd->dd_desc_len));
1704
1705                                 ds += ndesc;
1706                                 bf->bf_desc = ds;
1707                                 bf->bf_daddr = DS2PHYS(dd, ds);
1708                         }
1709                 }
1710                 list_add_tail(&bf->list, head);
1711         }
1712         return 0;
1713 fail2:
1714         pci_free_consistent(sc->pdev,
1715                 dd->dd_desc_len, dd->dd_desc, dd->dd_desc_paddr);
1716 fail:
1717         memzero(dd, sizeof(*dd));
1718         return error;
1719 #undef ATH_DESC_4KB_BOUND_CHECK
1720 #undef ATH_DESC_4KB_BOUND_NUM_SKIPPED
1721 #undef DS2PHYS
1722 }
1723
1724 /*
1725  *  Cleanup DMA descriptors
1726  *
1727  *  This function will free the DMA block that was allocated for the descriptor
1728  *  pool.  Since this was allocated as one "chunk", it is freed in the same
1729  *  manner.
1730 */
1731
1732 void ath_descdma_cleanup(struct ath_softc *sc,
1733                          struct ath_descdma *dd,
1734                          struct list_head *head)
1735 {
1736         /* Free memory associated with descriptors */
1737         pci_free_consistent(sc->pdev,
1738                 dd->dd_desc_len, dd->dd_desc, dd->dd_desc_paddr);
1739
1740         INIT_LIST_HEAD(head);
1741         kfree(dd->dd_bufptr);
1742         memzero(dd, sizeof(*dd));
1743 }
1744
1745 /*************/
1746 /* Utilities */
1747 /*************/
1748
1749 int ath_get_hal_qnum(u16 queue, struct ath_softc *sc)
1750 {
1751         int qnum;
1752
1753         switch (queue) {
1754         case 0:
1755                 qnum = sc->sc_haltype2q[ATH9K_WME_AC_VO];
1756                 break;
1757         case 1:
1758                 qnum = sc->sc_haltype2q[ATH9K_WME_AC_VI];
1759                 break;
1760         case 2:
1761                 qnum = sc->sc_haltype2q[ATH9K_WME_AC_BE];
1762                 break;
1763         case 3:
1764                 qnum = sc->sc_haltype2q[ATH9K_WME_AC_BK];
1765                 break;
1766         default:
1767                 qnum = sc->sc_haltype2q[ATH9K_WME_AC_BE];
1768                 break;
1769         }
1770
1771         return qnum;
1772 }
1773
1774 int ath_get_mac80211_qnum(u32 queue, struct ath_softc *sc)
1775 {
1776         int qnum;
1777
1778         switch (queue) {
1779         case ATH9K_WME_AC_VO:
1780                 qnum = 0;
1781                 break;
1782         case ATH9K_WME_AC_VI:
1783                 qnum = 1;
1784                 break;
1785         case ATH9K_WME_AC_BE:
1786                 qnum = 2;
1787                 break;
1788         case ATH9K_WME_AC_BK:
1789                 qnum = 3;
1790                 break;
1791         default:
1792                 qnum = -1;
1793                 break;
1794         }
1795
1796         return qnum;
1797 }
1798
1799
1800 /*
1801  *  Expand time stamp to TSF
1802  *
1803  *  Extend 15-bit time stamp from rx descriptor to
1804  *  a full 64-bit TSF using the current h/w TSF.
1805 */
1806
1807 u64 ath_extend_tsf(struct ath_softc *sc, u32 rstamp)
1808 {
1809         u64 tsf;
1810
1811         tsf = ath9k_hw_gettsf64(sc->sc_ah);
1812         if ((tsf & 0x7fff) < rstamp)
1813                 tsf -= 0x8000;
1814         return (tsf & ~0x7fff) | rstamp;
1815 }
1816
1817 /*
1818  *  Set Default Antenna
1819  *
1820  *  Call into the HAL to set the default antenna to use.  Not really valid for
1821  *  MIMO technology.
1822 */
1823
1824 void ath_setdefantenna(void *context, u32 antenna)
1825 {
1826         struct ath_softc *sc = (struct ath_softc *)context;
1827         struct ath_hal *ah = sc->sc_ah;
1828
1829         /* XXX block beacon interrupts */
1830         ath9k_hw_setantenna(ah, antenna);
1831         sc->sc_defant = antenna;
1832         sc->sc_rxotherant = 0;
1833 }
1834
1835 /*
1836  * Set Slot Time
1837  *
1838  * This will wake up the chip if required, and set the slot time for the
1839  * frame (maximum transmit time).  Slot time is assumed to be already set
1840  * in the ATH object member sc_slottime
1841 */
1842
1843 void ath_setslottime(struct ath_softc *sc)
1844 {
1845         ath9k_hw_setslottime(sc->sc_ah, sc->sc_slottime);
1846         sc->sc_updateslot = OK;
1847 }