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