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