a0810acc7d8439c576cba7768792d03bc0dc94c3
[openwrt.git] / package / ath9k / src / 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 = AH_FALSE;              /* enable outdoor use */
23
24 static const u_int8_t ath_bcast_mac[ETH_ALEN] =
25     { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
26
27 static u_int32_t ath_chainmask_sel_up_rssi_thres =
28         ATH_CHAINMASK_SEL_UP_RSSI_THRES;
29 static u_int32_t ath_chainmask_sel_down_rssi_thres =
30         ATH_CHAINMASK_SEL_DOWN_RSSI_THRES;
31 static u_int32_t ath_chainmask_sel_period =
32         ATH_CHAINMASK_SEL_TIMEOUT;
33
34 /* return bus cachesize in 4B word units */
35
36 static void bus_read_cachesize(struct ath_softc *sc, int *csz)
37 {
38         u_int8_t u8tmp;
39
40         pci_read_config_byte(sc->pdev, PCI_CACHE_LINE_SIZE, (u_int8_t *)&u8tmp);
41         *csz = (int)u8tmp;
42
43         /*
44          * This check was put in to avoid "unplesant" consequences if
45          * the bootrom has not fully initialized all PCI devices.
46          * Sometimes the cache line size register is not set
47          */
48
49         if (*csz == 0)
50                 *csz = DEFAULT_CACHELINE >> 2;   /* Use the default size */
51 }
52
53 /*
54  *  Set current operating mode
55  *
56  *  This function initializes and fills the rate table in the ATH object based
57  *  on the operating mode.  The blink rates are also set up here, although
58  *  they have been superceeded by the ath_led module.
59 */
60
61 static void ath_setcurmode(struct ath_softc *sc, enum wireless_mode mode)
62 {
63         const struct hal_rate_table *rt;
64         int i;
65
66         memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
67         rt = sc->sc_rates[mode];
68         KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
69
70         for (i = 0; i < rt->rateCount; i++)
71                 sc->sc_rixmap[rt->info[i].rateCode] = (u_int8_t) i;
72
73         memzero(sc->sc_hwmap, sizeof(sc->sc_hwmap));
74         for (i = 0; i < 256; i++) {
75                 u_int8_t ix = rt->rateCodeToIndex[i];
76
77                 if (ix == 0xff)
78                         continue;
79
80                 sc->sc_hwmap[i].ieeerate =
81                     rt->info[ix].dot11Rate & IEEE80211_RATE_VAL;
82                 sc->sc_hwmap[i].rateKbps = rt->info[ix].rateKbps;
83
84                 if (rt->info[ix].shortPreamble ||
85                     rt->info[ix].phy == PHY_OFDM) {
86                 }
87                 /* NB: this uses the last entry if the rate isn't found */
88                 /* XXX beware of overlow */
89         }
90         sc->sc_currates = rt;
91         sc->sc_curmode = mode;
92         /*
93          * All protection frames are transmited at 2Mb/s for
94          * 11g, otherwise at 1Mb/s.
95          * XXX select protection rate index from rate table.
96          */
97         sc->sc_protrix = (mode == WIRELESS_MODE_11g ? 1 : 0);
98         /* rate index used to send mgt frames */
99         sc->sc_minrateix = 0;
100 }
101
102 /*
103  *  Select Rate Table
104  *
105  *  Based on the wireless mode passed in, the rate table in the ATH object
106  *  is set to the mode specific rate table.  This also calls the callback
107  *  function to set the rate in the protocol layer object.
108 */
109
110 static int ath_rate_setup(struct ath_softc *sc, enum wireless_mode mode)
111 {
112         struct ath_hal *ah = sc->sc_ah;
113         const struct hal_rate_table *rt;
114
115         switch (mode) {
116         case WIRELESS_MODE_11a:
117                 sc->sc_rates[mode] =
118                         ath9k_hw_getratetable(ah, ATH9K_MODE_SEL_11A);
119                 break;
120         case WIRELESS_MODE_11b:
121                 sc->sc_rates[mode] =
122                         ath9k_hw_getratetable(ah, ATH9K_MODE_SEL_11B);
123                 break;
124         case WIRELESS_MODE_11g:
125                 sc->sc_rates[mode] =
126                         ath9k_hw_getratetable(ah, ATH9K_MODE_SEL_11G);
127                 break;
128         case WIRELESS_MODE_11NA_HT20:
129                 sc->sc_rates[mode] =
130                         ath9k_hw_getratetable(ah, ATH9K_MODE_SEL_11NA_HT20);
131                 break;
132         case WIRELESS_MODE_11NG_HT20:
133                 sc->sc_rates[mode] =
134                         ath9k_hw_getratetable(ah, ATH9K_MODE_SEL_11NG_HT20);
135                 break;
136         case WIRELESS_MODE_11NA_HT40PLUS:
137                 sc->sc_rates[mode] =
138                         ath9k_hw_getratetable(ah, ATH9K_MODE_SEL_11NA_HT40PLUS);
139                 break;
140         case WIRELESS_MODE_11NA_HT40MINUS:
141                 sc->sc_rates[mode] =
142                         ath9k_hw_getratetable(ah,
143                                 ATH9K_MODE_SEL_11NA_HT40MINUS);
144                 break;
145         case WIRELESS_MODE_11NG_HT40PLUS:
146                 sc->sc_rates[mode] =
147                         ath9k_hw_getratetable(ah, ATH9K_MODE_SEL_11NG_HT40PLUS);
148                 break;
149         case WIRELESS_MODE_11NG_HT40MINUS:
150                 sc->sc_rates[mode] =
151                         ath9k_hw_getratetable(ah,
152                                 ATH9K_MODE_SEL_11NG_HT40MINUS);
153                 break;
154         default:
155                 DPRINTF(sc, ATH_DEBUG_FATAL, "%s: invalid mode %u\n",
156                         __func__, mode);
157                 return 0;
158         }
159         rt = sc->sc_rates[mode];
160         if (rt == NULL)
161                 return 0;
162
163         /* setup rate set in 802.11 protocol layer */
164         ath_setup_rate(sc, mode, NORMAL_RATE, rt);
165
166         return 1;
167 }
168
169 /*
170  *  Set up channel list
171  *
172  *  Determines the proper set of channelflags based on the selected mode,
173  *  allocates a channel array, and passes it to the HAL for initialization.
174  *  If successful, the list is passed to the upper layer, then de-allocated.
175 */
176
177 static int ath_getchannels(struct ath_softc *sc,
178                            u_int cc,
179                            enum hal_bool outDoor,
180                            enum hal_bool xchanMode)
181 {
182         struct ath_hal *ah = sc->sc_ah;
183         struct hal_channel *chans;
184         int nchan;
185         u_int8_t regclassids[ATH_REGCLASSIDS_MAX];
186         u_int nregclass = 0;
187
188         chans = kmalloc(ATH_CHAN_MAX * sizeof(struct hal_channel), GFP_KERNEL);
189         if (chans == NULL) {
190                 DPRINTF(sc, ATH_DEBUG_FATAL,
191                         "%s: unable to allocate channel table\n", __func__);
192                 return -ENOMEM;
193         }
194
195         if (!ath9k_regd_init_channels(ah,
196                                       chans,
197                                       ATH_CHAN_MAX,
198                                       (u_int *)&nchan,
199                                       regclassids,
200                                       ATH_REGCLASSIDS_MAX,
201                                       &nregclass,
202                                       cc,
203                                       ATH9K_MODE_SEL_ALL,
204                                       outDoor,
205                                       xchanMode)) {
206                 u_int32_t rd = ah->ah_currentRD;
207
208                 DPRINTF(sc, ATH_DEBUG_FATAL,
209                         "%s: unable to collect channel list from hal; "
210                         "regdomain likely %u country code %u\n",
211                         __func__, rd, cc);
212                 kfree(chans);
213                 return -EINVAL;
214         }
215
216         ath_setup_channel_list(sc,
217                                CLIST_UPDATE,
218                                chans,
219                                nchan,
220                                regclassids,
221                                nregclass,
222                                CTRY_DEFAULT);
223
224         kfree(chans);
225         return 0;
226 }
227
228 /*
229  *  Determine mode from channel flags
230  *
231  *  This routine will provide the enumerated WIRELESSS_MODE value based
232  *  on the settings of the channel flags.  If ho valid set of flags
233  *  exist, the lowest mode (11b) is selected.
234 */
235
236 static enum wireless_mode ath_chan2mode(struct hal_channel *chan)
237 {
238         if ((chan->channelFlags & CHANNEL_A) == CHANNEL_A)
239                 return WIRELESS_MODE_11a;
240         else if ((chan->channelFlags & CHANNEL_G) == CHANNEL_G)
241                 return WIRELESS_MODE_11g;
242         else if ((chan->channelFlags & CHANNEL_B) == CHANNEL_B)
243                 return WIRELESS_MODE_11b;
244         else if ((chan->channelFlags & CHANNEL_A_HT20) == CHANNEL_A_HT20)
245                 return WIRELESS_MODE_11NA_HT20;
246         else if ((chan->channelFlags & CHANNEL_G_HT20) == CHANNEL_G_HT20)
247                 return WIRELESS_MODE_11NG_HT20;
248         else if ((chan->channelFlags & CHANNEL_A_HT40PLUS) ==
249                  CHANNEL_A_HT40PLUS)
250                 return WIRELESS_MODE_11NA_HT40PLUS;
251         else if ((chan->channelFlags & CHANNEL_A_HT40MINUS) ==
252                  CHANNEL_A_HT40MINUS)
253                 return WIRELESS_MODE_11NA_HT40MINUS;
254         else if ((chan->channelFlags & CHANNEL_G_HT40PLUS) ==
255                  CHANNEL_G_HT40PLUS)
256                 return WIRELESS_MODE_11NG_HT40PLUS;
257         else if ((chan->channelFlags & CHANNEL_G_HT40MINUS) ==
258                  CHANNEL_G_HT40MINUS)
259                 return WIRELESS_MODE_11NG_HT40MINUS;
260
261         /* NB: should not get here */
262         return WIRELESS_MODE_11b;
263 }
264
265 /*
266  *  Change Channels
267  *
268  *  Performs the actions to change the channel in the hardware, and set up
269  *  the current operating mode for the new channel.
270 */
271
272 static void ath_chan_change(struct ath_softc *sc, struct hal_channel *chan)
273 {
274         enum wireless_mode mode;
275
276         mode = ath_chan2mode(chan);
277
278         ath_rate_setup(sc, mode);
279         ath_setcurmode(sc, mode);
280 }
281
282 /*
283  * Stop the device, grabbing the top-level lock to protect
284  * against concurrent entry through ath_init (which can happen
285  * if another thread does a system call and the thread doing the
286  * stop is preempted).
287  */
288
289 static int ath_stop(struct ath_softc *sc)
290 {
291         struct ath_hal *ah = sc->sc_ah;
292
293         DPRINTF(sc, ATH_DEBUG_CONFIG, "%s: invalid %u\n",
294                 __func__, sc->sc_invalid);
295
296         /*
297          * Shutdown the hardware and driver:
298          *    stop output from above
299          *    reset 802.11 state machine
300          *      (sends station deassoc/deauth frames)
301          *    turn off timers
302          *    disable interrupts
303          *    clear transmit machinery
304          *    clear receive machinery
305          *    turn off the radio
306          *    reclaim beacon resources
307          *
308          * Note that some of this work is not possible if the
309          * hardware is gone (invalid).
310          */
311
312         if (!sc->sc_invalid)
313                 ath9k_hw_set_interrupts(ah, 0);
314         ath_draintxq(sc, AH_FALSE);
315         if (!sc->sc_invalid) {
316                 ath_stoprecv(sc);
317                 ath9k_hw_phy_disable(ah);
318         } else
319                 sc->sc_rxlink = NULL;
320
321         return 0;
322 }
323
324 /*
325  *  Start Scan
326  *
327  *  This function is called when starting a channel scan.  It will perform
328  *  power save wakeup processing, set the filter for the scan, and get the
329  *  chip ready to send broadcast packets out during the scan.
330 */
331
332 void ath_scan_start(struct ath_softc *sc)
333 {
334         struct ath_hal *ah = sc->sc_ah;
335         u_int32_t rfilt;
336         u_int32_t now = (u_int32_t) jiffies_to_msecs(get_timestamp());
337
338         sc->sc_scanning = 1;
339         rfilt = ath_calcrxfilter(sc);
340         ath9k_hw_setrxfilter(ah, rfilt);
341         ath9k_hw_write_associd(ah, ath_bcast_mac, 0);
342
343         /* Restore previous power management state. */
344
345         DPRINTF(sc, ATH_DEBUG_CONFIG, "%d.%03d | %s: RX filter 0x%x aid 0\n",
346                 now / 1000, now % 1000, __func__, rfilt);
347 }
348
349 /*
350  *  Scan End
351  *
352  *  This routine is called by the upper layer when the scan is completed.  This
353  *  will set the filters back to normal operating mode, set the BSSID to the
354  *  correct value, and restore the power save state.
355 */
356
357 void ath_scan_end(struct ath_softc *sc)
358 {
359         struct ath_hal *ah = sc->sc_ah;
360         u_int32_t rfilt;
361         u_int32_t now = (u_int32_t) jiffies_to_msecs(get_timestamp());
362
363         sc->sc_scanning = 0;
364         rfilt = ath_calcrxfilter(sc);
365         ath9k_hw_setrxfilter(ah, rfilt);
366         ath9k_hw_write_associd(ah, sc->sc_curbssid, sc->sc_curaid);
367
368         DPRINTF(sc, ATH_DEBUG_CONFIG, "%d.%03d | %s: RX filter 0x%x aid 0x%x\n",
369                 now / 1000, now % 1000, __func__, rfilt, sc->sc_curaid);
370 }
371
372 /*
373  * Set the current channel
374  *
375  * Set/change channels.  If the channel is really being changed, it's done
376  * by reseting the chip.  To accomplish this we must first cleanup any pending
377  * DMA, then restart stuff after a la ath_init.
378 */
379 int ath_set_channel(struct ath_softc *sc, struct hal_channel *hchan)
380 {
381         struct ath_hal *ah = sc->sc_ah;
382         enum hal_bool fastcc = AH_TRUE, stopped;
383         enum hal_ht_macmode ht_macmode;
384
385         if (sc->sc_invalid)     /* if the device is invalid or removed */
386                 return -EIO;
387
388         DPRINTF(sc, ATH_DEBUG_CONFIG,
389                 "%s: %u (%u MHz) -> %u (%u MHz), cflags:%x\n",
390                 __func__,
391                 ath9k_hw_mhz2ieee(ah, sc->sc_curchan.channel,
392                                   sc->sc_curchan.channelFlags),
393                 sc->sc_curchan.channel,
394                 ath9k_hw_mhz2ieee(ah, hchan->channel, hchan->channelFlags),
395                 hchan->channel, hchan->channelFlags);
396
397         ht_macmode = ath_cwm_macmode(sc);
398
399         if (hchan->channel != sc->sc_curchan.channel ||
400             hchan->channelFlags != sc->sc_curchan.channelFlags ||
401             sc->sc_update_chainmask || sc->sc_full_reset) {
402                 enum hal_status status;
403                 /*
404                  * This is only performed if the channel settings have
405                  * actually changed.
406                  *
407                  * To switch channels clear any pending DMA operations;
408                  * wait long enough for the RX fifo to drain, reset the
409                  * hardware at the new frequency, and then re-enable
410                  * the relevant bits of the h/w.
411                  */
412                 ath9k_hw_set_interrupts(ah, 0); /* disable interrupts */
413                 ath_draintxq(sc, AH_FALSE);     /* clear pending tx frames */
414                 stopped = ath_stoprecv(sc);     /* turn off frame recv */
415
416                 /* XXX: do not flush receive queue here. We don't want
417                  * to flush data frames already in queue because of
418                  * changing channel. */
419
420                 if (!stopped || sc->sc_full_reset)
421                         fastcc = AH_FALSE;
422
423                 spin_lock_bh(&sc->sc_resetlock);
424                 if (!ath9k_hw_reset(ah, sc->sc_opmode, hchan,
425                                         ht_macmode, sc->sc_tx_chainmask,
426                                         sc->sc_rx_chainmask,
427                                         sc->sc_ht_extprotspacing,
428                                         fastcc, &status)) {
429                         DPRINTF(sc, ATH_DEBUG_FATAL,
430                                 "%s: unable to reset channel %u (%uMhz) "
431                                 "flags 0x%x hal status %u\n", __func__,
432                                 ath9k_hw_mhz2ieee(ah, hchan->channel,
433                                                   hchan->channelFlags),
434                                 hchan->channel, hchan->channelFlags, status);
435                         spin_unlock_bh(&sc->sc_resetlock);
436                         return -EIO;
437                 }
438                 spin_unlock_bh(&sc->sc_resetlock);
439
440                 sc->sc_curchan = *hchan;
441                 sc->sc_update_chainmask = 0;
442                 sc->sc_full_reset = 0;
443
444                 /* Re-enable rx framework */
445                 if (ath_startrecv(sc) != 0) {
446                         DPRINTF(sc, ATH_DEBUG_FATAL,
447                                 "%s: unable to restart recv logic\n", __func__);
448                         return -EIO;
449                 }
450                 /*
451                  * Change channels and update the h/w rate map
452                  * if we're switching; e.g. 11a to 11b/g.
453                  */
454                 ath_chan_change(sc, hchan);
455                 ath_update_txpow(sc);   /* update tx power state */
456                 /*
457                  * Re-enable interrupts.
458                  */
459                 ath9k_hw_set_interrupts(ah, sc->sc_imask);
460         }
461         return 0;
462 }
463
464 /**********************/
465 /* Chainmask Handling */
466 /**********************/
467
468 static void ath_chainmask_sel_timertimeout(unsigned long data)
469 {
470         struct ath_chainmask_sel *cm = (struct ath_chainmask_sel *)data;
471         cm->switch_allowed = 1;
472 }
473
474 /* Start chainmask select timer */
475 static void ath_chainmask_sel_timerstart(struct ath_chainmask_sel *cm)
476 {
477         cm->switch_allowed = 0;
478         mod_timer(&cm->timer, ath_chainmask_sel_period);
479 }
480
481 /* Stop chainmask select timer */
482 static void ath_chainmask_sel_timerstop(struct ath_chainmask_sel *cm)
483 {
484         cm->switch_allowed = 0;
485         del_timer_sync(&cm->timer);
486 }
487
488 static void ath_chainmask_sel_init(struct ath_softc *sc, struct ath_node *an)
489 {
490         struct ath_chainmask_sel *cm = &an->an_chainmask_sel;
491
492         memzero(cm, sizeof(struct ath_chainmask_sel));
493
494         cm->cur_tx_mask = sc->sc_tx_chainmask;
495         cm->cur_rx_mask = sc->sc_rx_chainmask;
496         cm->tx_avgrssi = ATH_RSSI_DUMMY_MARKER;
497         setup_timer(&cm->timer,
498                 ath_chainmask_sel_timertimeout, (unsigned long) cm);
499 }
500
501 int ath_chainmask_sel_logic(struct ath_softc *sc, struct ath_node *an)
502 {
503         struct ath_chainmask_sel *cm = &an->an_chainmask_sel;
504
505         /*
506          * Disable auto-swtiching in one of the following if conditions.
507          * sc_chainmask_auto_sel is used for internal global auto-switching
508          * enabled/disabled setting
509          */
510         if ((sc->sc_no_tx_3_chains == AH_FALSE) ||
511             (sc->sc_config.chainmask_sel == AH_FALSE))
512                 cm->cur_tx_mask = sc->sc_tx_chainmask;
513                 return cm->cur_tx_mask;
514
515         if (cm->tx_avgrssi == ATH_RSSI_DUMMY_MARKER)
516                 return cm->cur_tx_mask;
517
518         if (cm->switch_allowed) {
519                 /* Switch down from tx 3 to tx 2. */
520                 if (cm->cur_tx_mask == ATH_CHAINMASK_SEL_3X3 &&
521                     ATH_RSSI_OUT(cm->tx_avgrssi) >=
522                     ath_chainmask_sel_down_rssi_thres) {
523                         cm->cur_tx_mask = sc->sc_tx_chainmask;
524
525                         /* Don't let another switch happen until
526                          * this timer expires */
527                         ath_chainmask_sel_timerstart(cm);
528                 }
529                 /* Switch up from tx 2 to 3. */
530                 else if (cm->cur_tx_mask == sc->sc_tx_chainmask &&
531                          ATH_RSSI_OUT(cm->tx_avgrssi) <=
532                          ath_chainmask_sel_up_rssi_thres) {
533                         cm->cur_tx_mask = ATH_CHAINMASK_SEL_3X3;
534
535                         /* Don't let another switch happen
536                          * until this timer expires */
537                         ath_chainmask_sel_timerstart(cm);
538                 }
539         }
540
541         return cm->cur_tx_mask;
542 }
543
544 /******************/
545 /* VAP management */
546 /******************/
547
548 /*
549  *  Down VAP instance
550  *
551  *  This routine will stop the indicated VAP and put it in a "down" state.
552  *  The down state is basically an initialization state that can be brought
553  *  back up by calling the opposite up routine.
554  *  This routine will bring the interface out of power save mode, set the
555  *  LED states, update the rate control processing, stop DMA transfers, and
556  *  set the VAP into the down state.
557 */
558
559 int ath_vap_down(struct ath_softc *sc, int if_id, u_int flags)
560 {
561         struct ath_hal *ah = sc->sc_ah;
562         struct ath_vap *avp;
563
564         avp = sc->sc_vaps[if_id];
565         if (avp == NULL) {
566                 DPRINTF(sc, ATH_DEBUG_FATAL, "%s: invalid interface id %u\n",
567                         __func__, if_id);
568                 return -EINVAL;
569         }
570
571 #ifdef CONFIG_SLOW_ANT_DIV
572         if (sc->sc_slowAntDiv)
573                 ath_slow_ant_div_stop(&sc->sc_antdiv);
574 #endif
575
576         /* update ratectrl about the new state */
577         ath_rate_newstate(sc, avp, 0);
578
579         /* Reclaim beacon resources */
580         if (sc->sc_opmode == HAL_M_HOSTAP || sc->sc_opmode == HAL_M_IBSS) {
581                 ath9k_hw_stoptxdma(ah, sc->sc_bhalq);
582                 ath_beacon_return(sc, avp);
583         }
584
585         if (flags & ATH_IF_HW_OFF) {
586                 sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
587                 ath9k_hw_set_interrupts(ah, sc->sc_imask & ~HAL_INT_GLOBAL);
588                 sc->sc_beacons = 0;
589         }
590
591         return 0;
592 }
593
594 /*
595  *  VAP in Listen mode
596  *
597  *  This routine brings the VAP out of the down state into a "listen" state
598  *  where it waits for association requests.  This is used in AP and AdHoc
599  *  modes.
600 */
601
602 int ath_vap_listen(struct ath_softc *sc, int if_id)
603 {
604         struct ath_hal *ah = sc->sc_ah;
605         struct ath_vap *avp;
606         u_int32_t rfilt = 0;
607         DECLARE_MAC_BUF(mac);
608
609         avp = sc->sc_vaps[if_id];
610         if (avp == NULL) {
611                 DPRINTF(sc, ATH_DEBUG_FATAL, "%s: invalid interface id %u\n",
612                         __func__, if_id);
613                 return -EINVAL;
614         }
615
616 #ifdef CONFIG_SLOW_ANT_DIV
617         if (sc->sc_slowAntDiv)
618                 ath_slow_ant_div_stop(&sc->sc_antdiv);
619 #endif
620
621         /* update ratectrl about the new state */
622         ath_rate_newstate(sc, avp, 0);
623
624         rfilt = ath_calcrxfilter(sc);
625         ath9k_hw_setrxfilter(ah, rfilt);
626
627         if (sc->sc_opmode == HAL_M_STA || sc->sc_opmode == HAL_M_IBSS) {
628                 memcpy(sc->sc_curbssid, ath_bcast_mac, ETH_ALEN);
629                 ath9k_hw_write_associd(ah, sc->sc_curbssid, sc->sc_curaid);
630         } else
631                 sc->sc_curaid = 0;
632
633         DPRINTF(sc, ATH_DEBUG_CONFIG,
634                 "%s: RX filter 0x%x bssid %s aid 0x%x\n",
635                 __func__, rfilt, print_mac(mac,
636                         sc->sc_curbssid), sc->sc_curaid);
637
638         /*
639          * XXXX
640          * Disable BMISS interrupt when we're not associated
641          */
642         ath9k_hw_set_interrupts(ah,
643                 sc->sc_imask & ~(HAL_INT_SWBA | HAL_INT_BMISS));
644         sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
645         /* need to reconfigure the beacons when it moves to RUN */
646         sc->sc_beacons = 0;
647
648         return 0;
649 }
650
651 int ath_vap_join(struct ath_softc *sc, int if_id,
652                  const u_int8_t bssid[ETH_ALEN], u_int flags)
653 {
654         struct ath_hal *ah = sc->sc_ah;
655         struct ath_vap *avp;
656         u_int32_t rfilt = 0;
657         DECLARE_MAC_BUF(mac);
658
659         avp = sc->sc_vaps[if_id];
660         if (avp == NULL) {
661                 DPRINTF(sc, ATH_DEBUG_FATAL, "%s: invalid interface id %u\n",
662                         __func__, if_id);
663                 return -EINVAL;
664         }
665
666         /* update ratectrl about the new state */
667         ath_rate_newstate(sc, avp, 0);
668
669         rfilt = ath_calcrxfilter(sc);
670         ath9k_hw_setrxfilter(ah, rfilt);
671
672         memcpy(sc->sc_curbssid, bssid, ETH_ALEN);
673         sc->sc_curaid = 0;
674         ath9k_hw_write_associd(ah, sc->sc_curbssid, sc->sc_curaid);
675
676         DPRINTF(sc, ATH_DEBUG_CONFIG,
677                 "%s: RX filter 0x%x bssid %s aid 0x%x\n",
678                 __func__, rfilt,
679                 print_mac(mac, sc->sc_curbssid), sc->sc_curaid);
680
681         /*
682          * Update tx/rx chainmask. For legacy association,
683          * hard code chainmask to 1x1, for 11n association, use
684          * the chainmask configuration.
685          */
686         sc->sc_update_chainmask = 1;
687         if (flags & ATH_IF_HT) {
688                 sc->sc_tx_chainmask = ah->ah_caps.halTxChainMask;
689                 sc->sc_rx_chainmask = ah->ah_caps.halRxChainMask;
690         } else {
691                 sc->sc_tx_chainmask = 1;
692                 sc->sc_rx_chainmask = 1;
693         }
694
695         /* Enable rx chain mask detection if configured to do so */
696
697         sc->sc_rx_chainmask_detect = 0;
698
699         /* Set aggregation protection mode parameters */
700
701         sc->sc_config.ath_aggr_prot = 0;
702
703         /*
704          * Reset our TSF so that its value is lower than the beacon that we are
705          * trying to catch. Only then hw will update its TSF register with the
706          * new beacon. Reset the TSF before setting the BSSID to avoid allowing
707          * in any frames that would update our TSF only to have us clear it
708          * immediately thereafter.
709          */
710         ath9k_hw_reset_tsf(ah);
711
712         /*
713          * XXXX
714          * Disable BMISS interrupt when we're not associated
715          */
716         ath9k_hw_set_interrupts(ah,
717                 sc->sc_imask & ~(HAL_INT_SWBA | HAL_INT_BMISS));
718         sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
719         /* need to reconfigure the beacons when it moves to RUN */
720         sc->sc_beacons = 0;
721
722         return 0;
723 }
724
725 int ath_vap_up(struct ath_softc *sc,
726                int if_id,
727                const u_int8_t bssid[ETH_ALEN],
728                u_int8_t aid, u_int flags)
729 {
730         struct ath_hal *ah = sc->sc_ah;
731         struct ath_vap *avp;
732         u_int32_t rfilt = 0;
733         int i, error = 0;
734         DECLARE_MAC_BUF(mac);
735
736         ASSERT(if_id != ATH_IF_ID_ANY);
737         avp = sc->sc_vaps[if_id];
738         if (avp == NULL) {
739                 DPRINTF(sc, ATH_DEBUG_FATAL, "%s: invalid interface id %u\n",
740                         __func__, if_id);
741                 return -EINVAL;
742         }
743
744         /* update ratectrl about the new state */
745         ath_rate_newstate(sc, avp, 1);
746
747         rfilt = ath_calcrxfilter(sc);
748         ath9k_hw_setrxfilter(ah, rfilt);
749
750         if (avp->av_opmode == HAL_M_STA || avp->av_opmode == HAL_M_IBSS) {
751                 memcpy(sc->sc_curbssid, bssid, ETH_ALEN);
752                 sc->sc_curaid = aid;
753                 ath9k_hw_write_associd(ah, sc->sc_curbssid, sc->sc_curaid);
754         }
755
756         DPRINTF(sc, ATH_DEBUG_CONFIG,
757                 "%s: RX filter 0x%x bssid %s aid 0x%x\n",
758                 __func__, rfilt,
759                 print_mac(mac, sc->sc_curbssid), sc->sc_curaid);
760
761         if ((avp->av_opmode != IEEE80211_IF_TYPE_STA) &&
762                 (flags & ATH_IF_PRIVACY)) {
763                 for (i = 0; i < IEEE80211_WEP_NKID; i++)
764                         if (ath9k_hw_keyisvalid(ah, (u_int16_t) i))
765                                 ath9k_hw_keysetmac(ah, (u_int16_t) i, bssid);
766         }
767
768         switch (avp->av_opmode) {
769         case HAL_M_HOSTAP:
770         case HAL_M_IBSS:
771                 /*
772                  * Allocate and setup the beacon frame.
773                  *
774                  * Stop any previous beacon DMA.  This may be
775                  * necessary, for example, when an ibss merge
776                  * causes reconfiguration; there will be a state
777                  * transition from RUN->RUN that means we may
778                  * be called with beacon transmission active.
779                  */
780                 ath9k_hw_stoptxdma(ah, sc->sc_bhalq);
781
782                 error = ath_beacon_alloc(sc, if_id);
783                 if (error != 0)
784                         goto bad;
785
786                 if (flags & ATH_IF_BEACON_ENABLE)
787                         sc->sc_beacons = 0;
788
789                 break;
790         case HAL_M_STA:
791                 /*
792                  * start rx chain mask detection if it is enabled.
793                  * Use the default chainmask as starting point.
794                  */
795                 if (sc->sc_rx_chainmask_detect) {
796                         if (flags & ATH_IF_HT)
797                                 sc->sc_rx_chainmask =
798                                         ah->ah_caps.halRxChainMask;
799                         else
800                                 sc->sc_rx_chainmask = 1;
801
802                         sc->sc_rx_chainmask_start = 1;
803                 }
804                 break;
805         default:
806                 break;
807         }
808         /* Moved beacon_config after dfs_wait check
809          * so that ath_beacon_config won't be called duing dfswait
810          * period - this will fix the beacon stuck afer DFS
811          * CAC period issue
812          * Configure the beacon and sleep timers. */
813
814         if (!sc->sc_beacons && !(flags & ATH_IF_BEACON_SYNC)) {
815                 ath_beacon_config(sc, if_id);
816                 sc->sc_beacons = 1;
817         }
818
819         /* Reset rssi stats; maybe not the best place... */
820         if (flags & ATH_IF_HW_ON) {
821                 sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
822                 sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
823                 sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
824                 sc->sc_halstats.ns_avgtxrate = ATH_RATE_DUMMY_MARKER;
825         }
826 bad:
827         return error;
828 }
829
830 int ath_vap_attach(struct ath_softc *sc,
831                    int if_id,
832                    struct ieee80211_vif *if_data,
833                    enum hal_opmode opmode,
834                    enum hal_opmode iv_opmode,
835                    int nostabeacons)
836 {
837         struct ath_vap *avp;
838
839         if (if_id >= ATH_BCBUF || sc->sc_vaps[if_id] != NULL) {
840                 DPRINTF(sc, ATH_DEBUG_FATAL,
841                         "%s: Invalid interface id = %u\n", __func__, if_id);
842                 return -EINVAL;
843         }
844
845         switch (opmode) {
846         case HAL_M_STA:
847                 sc->sc_nostabeacons = nostabeacons;
848                 break;
849         case HAL_M_IBSS:
850         case HAL_M_MONITOR:
851                 break;
852         case HAL_M_HOSTAP:
853                 /* copy nostabeacons - for WDS client */
854                 sc->sc_nostabeacons = nostabeacons;
855                 /* XXX not right, beacon buffer is allocated on RUN trans */
856                 if (list_empty(&sc->sc_bbuf))
857                         return -ENOMEM;
858                 break;
859         default:
860                 return -EINVAL;
861         }
862
863         /* create ath_vap */
864         avp = kmalloc(sizeof(struct ath_vap), GFP_KERNEL);
865         if (avp == NULL)
866                 return -ENOMEM;
867
868         memzero(avp, sizeof(struct ath_vap));
869         avp->av_if_data = if_data;
870         /* Set the VAP opmode */
871         avp->av_opmode = iv_opmode;
872         avp->av_bslot = -1;
873         INIT_LIST_HEAD(&avp->av_mcastq.axq_q);
874         INIT_LIST_HEAD(&avp->av_mcastq.axq_acq);
875         spin_lock_init(&avp->av_mcastq.axq_lock);
876         if (opmode == HAL_M_HOSTAP || opmode == HAL_M_IBSS) {
877                 if (sc->sc_hastsfadd) {
878                         /*
879                          * Multiple vaps are to transmit beacons and we
880                          * have h/w support for TSF adjusting; enable use
881                          * of staggered beacons.
882                          */
883                         /* XXX check for beacon interval too small */
884                         sc->sc_stagbeacons = 1;
885                 }
886         }
887         if (sc->sc_hastsfadd)
888                 ath9k_hw_set_tsfadjust(sc->sc_ah, sc->sc_stagbeacons);
889
890         sc->sc_vaps[if_id] = avp;
891         sc->sc_nvaps++;
892         /* Set the device opmode */
893         sc->sc_opmode = opmode;
894
895         /* default VAP configuration */
896         avp->av_config.av_fixed_rateset = IEEE80211_FIXED_RATE_NONE;
897         avp->av_config.av_fixed_retryset = 0x03030303;
898
899         return 0;
900 }
901
902 int ath_vap_detach(struct ath_softc *sc, int if_id)
903 {
904         struct ath_hal *ah = sc->sc_ah;
905         struct ath_vap *avp;
906
907         avp = sc->sc_vaps[if_id];
908         if (avp == NULL) {
909                 DPRINTF(sc, ATH_DEBUG_FATAL, "%s: invalid interface id %u\n",
910                         __func__, if_id);
911                 return -EINVAL;
912         }
913
914         /*
915          * Quiesce the hardware while we remove the vap.  In
916          * particular we need to reclaim all references to the
917          * vap state by any frames pending on the tx queues.
918          *
919          * XXX can we do this w/o affecting other vap's?
920          */
921         ath9k_hw_set_interrupts(ah, 0); /* disable interrupts */
922         ath_draintxq(sc, AH_FALSE);     /* stop xmit side */
923         ath_stoprecv(sc);       /* stop recv side */
924         ath_flushrecv(sc);      /* flush recv queue */
925
926         /* Reclaim any pending mcast bufs on the vap. */
927         ath_tx_draintxq(sc, &avp->av_mcastq, AH_FALSE);
928
929         if (sc->sc_opmode == HAL_M_HOSTAP && sc->sc_nostabeacons)
930                 sc->sc_nostabeacons = 0;
931
932         kfree(avp);
933         sc->sc_vaps[if_id] = NULL;
934         sc->sc_nvaps--;
935
936         /* restart H/W in case there are other VAPs */
937         if (sc->sc_nvaps) {
938                 /* Restart rx+tx machines if device is still running. */
939                 if (ath_startrecv(sc) != 0)     /* restart recv */
940                         DPRINTF(sc, ATH_DEBUG_FATAL,
941                                 "%s: unable to start recv logic\n", __func__);
942                 if (sc->sc_beacons)
943                         /* restart beacons */
944                         ath_beacon_config(sc, ATH_IF_ID_ANY);
945
946                 ath9k_hw_set_interrupts(ah, sc->sc_imask);
947         }
948         return 0;
949 }
950
951 int ath_vap_config(struct ath_softc *sc,
952         int if_id, struct ath_vap_config *if_config)
953 {
954         struct ath_vap *avp;
955
956         if (if_id >= ATH_BCBUF) {
957                 DPRINTF(sc, ATH_DEBUG_FATAL,
958                         "%s: Invalid interface id = %u\n", __func__, if_id);
959                 return -EINVAL;
960         }
961
962         avp = sc->sc_vaps[if_id];
963         ASSERT(avp != NULL);
964
965         if (avp)
966                 memcpy(&avp->av_config, if_config, sizeof(avp->av_config));
967
968         return 0;
969 }
970
971 /********/
972 /* Core */
973 /********/
974
975 int ath_open(struct ath_softc *sc, struct hal_channel *initial_chan)
976 {
977         struct ath_hal *ah = sc->sc_ah;
978         enum hal_status status;
979         int error = 0;
980         enum hal_ht_macmode ht_macmode = ath_cwm_macmode(sc);
981
982         DPRINTF(sc, ATH_DEBUG_CONFIG, "%s: mode %d\n", __func__, sc->sc_opmode);
983
984         /*
985          * Stop anything previously setup.  This is safe
986          * whether this is the first time through or not.
987          */
988         ath_stop(sc);
989
990         /* Initialize chanmask selection */
991         sc->sc_tx_chainmask = ah->ah_caps.halTxChainMask;
992         sc->sc_rx_chainmask = ah->ah_caps.halRxChainMask;
993
994         /* Reset SERDES registers */
995         ath9k_hw_configpcipowersave(ah, 0);
996
997         /*
998          * The basic interface to setting the hardware in a good
999          * state is ``reset''.  On return the hardware is known to
1000          * be powered up and with interrupts disabled.  This must
1001          * be followed by initialization of the appropriate bits
1002          * and then setup of the interrupt mask.
1003          */
1004         sc->sc_curchan = *initial_chan;
1005
1006         spin_lock_bh(&sc->sc_resetlock);
1007         if (!ath9k_hw_reset(ah, sc->sc_opmode, &sc->sc_curchan, ht_macmode,
1008                            sc->sc_tx_chainmask, sc->sc_rx_chainmask,
1009                            sc->sc_ht_extprotspacing, AH_FALSE, &status)) {
1010                 DPRINTF(sc, ATH_DEBUG_FATAL,
1011                         "%s: unable to reset hardware; hal status %u "
1012                         "(freq %u flags 0x%x)\n", __func__, status,
1013                         sc->sc_curchan.channel, sc->sc_curchan.channelFlags);
1014                 error = -EIO;
1015                 spin_unlock_bh(&sc->sc_resetlock);
1016                 goto done;
1017         }
1018         spin_unlock_bh(&sc->sc_resetlock);
1019         /*
1020          * This is needed only to setup initial state
1021          * but it's best done after a reset.
1022          */
1023         ath_update_txpow(sc);
1024
1025         /*
1026          * Setup the hardware after reset:
1027          * The receive engine is set going.
1028          * Frame transmit is handled entirely
1029          * in the frame output path; there's nothing to do
1030          * here except setup the interrupt mask.
1031          */
1032         if (ath_startrecv(sc) != 0) {
1033                 DPRINTF(sc, ATH_DEBUG_FATAL,
1034                         "%s: unable to start recv logic\n", __func__);
1035                 error = -EIO;
1036                 goto done;
1037         }
1038         /* Setup our intr mask. */
1039         sc->sc_imask = HAL_INT_RX | HAL_INT_TX
1040                 | HAL_INT_RXEOL | HAL_INT_RXORN
1041                 | HAL_INT_FATAL | HAL_INT_GLOBAL;
1042
1043         if (ah->ah_caps.halGTTSupport)
1044                 sc->sc_imask |= HAL_INT_GTT;
1045
1046         if (sc->sc_hashtsupport)
1047                 sc->sc_imask |= HAL_INT_CST;
1048
1049         /*
1050          * Enable MIB interrupts when there are hardware phy counters.
1051          * Note we only do this (at the moment) for station mode.
1052          */
1053         if (sc->sc_needmib &&
1054             ((sc->sc_opmode == HAL_M_STA) || (sc->sc_opmode == HAL_M_IBSS)))
1055                 sc->sc_imask |= HAL_INT_MIB;
1056         /*
1057          * Some hardware processes the TIM IE and fires an
1058          * interrupt when the TIM bit is set.  For hardware
1059          * that does, if not overridden by configuration,
1060          * enable the TIM interrupt when operating as station.
1061          */
1062         if (ah->ah_caps.halEnhancedPmSupport && sc->sc_opmode == HAL_M_STA &&
1063                 !sc->sc_config.swBeaconProcess)
1064                 sc->sc_imask |= HAL_INT_TIM;
1065         /*
1066          *  Don't enable interrupts here as we've not yet built our
1067          *  vap and node data structures, which will be needed as soon
1068          *  as we start receiving.
1069          */
1070         ath_chan_change(sc, initial_chan);
1071
1072         /* XXX: we must make sure h/w is ready and clear invalid flag
1073          * before turning on interrupt. */
1074         sc->sc_invalid = 0;
1075 done:
1076         return error;
1077 }
1078
1079 /*
1080  * Reset the hardware w/o losing operational state.  This is
1081  * basically a more efficient way of doing ath_stop, ath_init,
1082  * followed by state transitions to the current 802.11
1083  * operational state.  Used to recover from errors rx overrun
1084  * and to reset the hardware when rf gain settings must be reset.
1085  */
1086
1087 static int ath_reset_start(struct ath_softc *sc, u_int32_t flag)
1088 {
1089         struct ath_hal *ah = sc->sc_ah;
1090
1091         ath9k_hw_set_interrupts(ah, 0); /* disable interrupts */
1092         ath_draintxq(sc, flag & RESET_RETRY_TXQ);       /* stop xmit side */
1093         ath_stoprecv(sc);       /* stop recv side */
1094         ath_flushrecv(sc);      /* flush recv queue */
1095
1096         return 0;
1097 }
1098
1099 static int ath_reset_end(struct ath_softc *sc, u_int32_t flag)
1100 {
1101         struct ath_hal *ah = sc->sc_ah;
1102
1103         if (ath_startrecv(sc) != 0)     /* restart recv */
1104                 DPRINTF(sc, ATH_DEBUG_FATAL,
1105                         "%s: unable to start recv logic\n", __func__);
1106
1107         /*
1108          * We may be doing a reset in response to a request
1109          * that changes the channel so update any state that
1110          * might change as a result.
1111          */
1112         ath_chan_change(sc, &sc->sc_curchan);
1113
1114         ath_update_txpow(sc);   /* update tx power state */
1115
1116         if (sc->sc_beacons)
1117                 ath_beacon_config(sc, ATH_IF_ID_ANY);   /* restart beacons */
1118         ath9k_hw_set_interrupts(ah, sc->sc_imask);
1119
1120         /* Restart the txq */
1121         if (flag & RESET_RETRY_TXQ) {
1122                 int i;
1123                 for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
1124                         if (ATH_TXQ_SETUP(sc, i)) {
1125                                 spin_lock_bh(&sc->sc_txq[i].axq_lock);
1126                                 ath_txq_schedule(sc, &sc->sc_txq[i]);
1127                                 spin_unlock_bh(&sc->sc_txq[i].axq_lock);
1128                         }
1129                 }
1130         }
1131         return 0;
1132 }
1133
1134 int ath_reset(struct ath_softc *sc)
1135 {
1136         struct ath_hal *ah = sc->sc_ah;
1137         enum hal_status status;
1138         int error = 0;
1139         enum hal_ht_macmode ht_macmode = ath_cwm_macmode(sc);
1140
1141         /* NB: indicate channel change so we do a full reset */
1142         spin_lock_bh(&sc->sc_resetlock);
1143         if (!ath9k_hw_reset(ah, sc->sc_opmode, &sc->sc_curchan,
1144                            ht_macmode,
1145                            sc->sc_tx_chainmask, sc->sc_rx_chainmask,
1146                            sc->sc_ht_extprotspacing, AH_FALSE, &status)) {
1147                 DPRINTF(sc, ATH_DEBUG_FATAL,
1148                         "%s: unable to reset hardware; hal status %u\n",
1149                         __func__, status);
1150                 error = -EIO;
1151         }
1152         spin_unlock_bh(&sc->sc_resetlock);
1153
1154         return error;
1155 }
1156
1157 int ath_suspend(struct ath_softc *sc)
1158 {
1159         struct ath_hal *ah = sc->sc_ah;
1160
1161         /* No I/O if device has been surprise removed */
1162         if (sc->sc_invalid)
1163                 return -EIO;
1164
1165         /* Shut off the interrupt before setting sc->sc_invalid to '1' */
1166         ath9k_hw_set_interrupts(ah, 0);
1167
1168         /* XXX: we must make sure h/w will not generate any interrupt
1169          * before setting the invalid flag. */
1170         sc->sc_invalid = 1;
1171
1172         /* disable HAL and put h/w to sleep */
1173         ath9k_hw_disable(sc->sc_ah);
1174
1175         ath9k_hw_configpcipowersave(sc->sc_ah, 1);
1176
1177         return 0;
1178 }
1179
1180 /* Interrupt handler.  Most of the actual processing is deferred.
1181  * It's the caller's responsibility to ensure the chip is awake. */
1182
1183 int ath_intr(struct ath_softc *sc)
1184 {
1185         struct ath_hal *ah = sc->sc_ah;
1186         enum hal_int status;
1187         int sched = ATH_ISR_NOSCHED;
1188
1189         do {
1190                 if (sc->sc_invalid) {
1191                         /*
1192                          * The hardware is not ready/present, don't
1193                          * touch anything. Note this can happen early
1194                          * on if the IRQ is shared.
1195                          */
1196                         return ATH_ISR_NOTMINE;
1197                 }
1198                 if (!ath9k_hw_intrpend(ah)) {   /* shared irq, not for us */
1199                         return ATH_ISR_NOTMINE;
1200                 }
1201
1202                 /*
1203                  * Figure out the reason(s) for the interrupt.  Note
1204                  * that the hal returns a pseudo-ISR that may include
1205                  * bits we haven't explicitly enabled so we mask the
1206                  * value to insure we only process bits we requested.
1207                  */
1208                 ath9k_hw_getisr(ah, &status);   /* NB: clears ISR too */
1209
1210                 status &= sc->sc_imask; /* discard unasked-for bits */
1211
1212                 /*
1213                  * If there are no status bits set, then this interrupt was not
1214                  * for me (should have been caught above).
1215                  */
1216
1217                 if (!status)
1218                         return ATH_ISR_NOTMINE;
1219
1220                 sc->sc_intrstatus = status;
1221
1222                 if (status & HAL_INT_FATAL) {
1223                         /* need a chip reset */
1224                         sched = ATH_ISR_SCHED;
1225                 } else if (status & HAL_INT_RXORN) {
1226                         /* need a chip reset */
1227                         sched = ATH_ISR_SCHED;
1228                 } else {
1229                         if (status & HAL_INT_SWBA) {
1230                                 /* schedule a tasklet for beacon handling */
1231                                 tasklet_schedule(&sc->bcon_tasklet);
1232                         }
1233                         if (status & HAL_INT_RXEOL) {
1234                                 /*
1235                                  * NB: the hardware should re-read the link when
1236                                  *     RXE bit is written, but it doesn't work
1237                                  *     at least on older hardware revs.
1238                                  */
1239                                 sched = ATH_ISR_SCHED;
1240                         }
1241
1242                         if (status & HAL_INT_TXURN)
1243                                 /* bump tx trigger level */
1244                                 ath9k_hw_updatetxtriglevel(ah, AH_TRUE);
1245                         /* XXX: optimize this */
1246                         if (status & HAL_INT_RX)
1247                                 sched = ATH_ISR_SCHED;
1248                         if (status & HAL_INT_TX)
1249                                 sched = ATH_ISR_SCHED;
1250                         if (status & HAL_INT_BMISS)
1251                                 sched = ATH_ISR_SCHED;
1252                         /* carrier sense timeout */
1253                         if (status & HAL_INT_CST)
1254                                 sched = ATH_ISR_SCHED;
1255                         if (status & HAL_INT_MIB) {
1256                                 /*
1257                                  * Disable interrupts until we service the MIB
1258                                  * interrupt; otherwise it will continue to
1259                                  * fire.
1260                                  */
1261                                 ath9k_hw_set_interrupts(ah, 0);
1262                                 /*
1263                                  * Let the hal handle the event. We assume
1264                                  * it will clear whatever condition caused
1265                                  * the interrupt.
1266                                  */
1267                                 ath9k_hw_procmibevent(ah, &sc->sc_halstats);
1268                                 ath9k_hw_set_interrupts(ah, sc->sc_imask);
1269                         }
1270                         if (status & HAL_INT_TIM_TIMER) {
1271                                 if (!sc->sc_hasautosleep) {
1272                                         /* Clear RxAbort bit so that we can
1273                                          * receive frames */
1274                                         ath9k_hw_setrxabort(ah, 0);
1275                                         /* Set flag indicating we're waiting
1276                                          * for a beacon */
1277                                         sc->sc_waitbeacon = 1;
1278
1279                                         sched = ATH_ISR_SCHED;
1280                                 }
1281                         }
1282                 }
1283         } while (0);
1284
1285         if (sched == ATH_ISR_SCHED)
1286                 /* turn off every interrupt except SWBA */
1287                 ath9k_hw_set_interrupts(ah, (sc->sc_imask & HAL_INT_SWBA));
1288
1289         return sched;
1290
1291 }
1292
1293 /* Deferred interrupt processing  */
1294
1295 static void ath9k_tasklet(unsigned long data)
1296 {
1297         struct ath_softc *sc = (struct ath_softc *)data;
1298         u_int32_t status = sc->sc_intrstatus;
1299
1300         if (status & HAL_INT_FATAL) {
1301                 /* need a chip reset */
1302                 ath_internal_reset(sc);
1303                 return;
1304         } else {
1305
1306                 if (status & (HAL_INT_RX | HAL_INT_RXEOL | HAL_INT_RXORN)) {
1307                         /* XXX: fill me in */
1308                         /*
1309                         if (status & HAL_INT_RXORN) {
1310                         }
1311                         if (status & HAL_INT_RXEOL) {
1312                         }
1313                         */
1314                         spin_lock_bh(&sc->sc_rxflushlock);
1315                         ath_rx_tasklet(sc, 0);
1316                         spin_unlock_bh(&sc->sc_rxflushlock);
1317                 }
1318                 /* XXX: optimize this */
1319                 if (status & HAL_INT_TX)
1320                         ath_tx_tasklet(sc);
1321                 /* XXX: fill me in */
1322                 /*
1323                 if (status & HAL_INT_BMISS) {
1324                 }
1325                 if (status & (HAL_INT_TIM | HAL_INT_DTIMSYNC)) {
1326                         if (status & HAL_INT_TIM) {
1327                         }
1328                         if (status & HAL_INT_DTIMSYNC) {
1329                         }
1330                 }
1331                 */
1332         }
1333
1334         /* re-enable hardware interrupt */
1335         ath9k_hw_set_interrupts(sc->sc_ah, sc->sc_imask);
1336 }
1337
1338 void ath_set_macmode(struct ath_softc *sc, enum hal_ht_macmode macmode)
1339 {
1340         ath9k_hw_set11nmac2040(sc->sc_ah, macmode);
1341 }
1342
1343 int ath_init(u_int16_t devid, struct ath_softc *sc)
1344 {
1345         struct ath_hal *ah = NULL;
1346         enum hal_status status;
1347         int error = 0, i;
1348         int csz = 0;
1349         u_int32_t rd;
1350
1351         /* XXX: hardware will not be ready until ath_open() being called */
1352         sc->sc_invalid = 1;
1353
1354         sc->sc_debug = DBG_DEFAULT;
1355         DPRINTF(sc, ATH_DEBUG_CONFIG, "%s: devid 0x%x\n", __func__, devid);
1356
1357         /* Initialize tasklet */
1358         tasklet_init(&sc->intr_tq, ath9k_tasklet, (unsigned long)sc);
1359         tasklet_init(&sc->bcon_tasklet, ath9k_beacon_tasklet,
1360                      (unsigned long)sc);
1361
1362         /*
1363          * Cache line size is used to size and align various
1364          * structures used to communicate with the hardware.
1365          */
1366         bus_read_cachesize(sc, &csz);
1367         /* XXX assert csz is non-zero */
1368         sc->sc_cachelsz = csz << 2;     /* convert to bytes */
1369
1370         spin_lock_init(&sc->sc_resetlock);
1371
1372         ah = ath9k_hw_attach(devid, sc, sc->mem, &status);
1373         if (ah == NULL) {
1374                 DPRINTF(sc, ATH_DEBUG_FATAL,
1375                         "%s: unable to attach hardware; HAL status %u\n",
1376                         __func__, status);
1377                 error = -ENXIO;
1378                 goto bad;
1379         }
1380         sc->sc_ah = ah;
1381
1382         /* Get the chipset-specific aggr limit. */
1383         sc->sc_rtsaggrlimit = ah->ah_caps.halRtsAggrLimit;
1384
1385         /*
1386          * Check if the MAC has multi-rate retry support.
1387          * We do this by trying to setup a fake extended
1388          * descriptor.  MAC's that don't have support will
1389          * return false w/o doing anything.  MAC's that do
1390          * support it will return true w/o doing anything.
1391          *
1392          *  XXX This is lame.  Just query a hal property, Luke!
1393          */
1394         sc->sc_mrretry = ath9k_hw_setupxtxdesc(ah, NULL, 0, 0, 0, 0, 0, 0);
1395
1396         /*
1397          * Check if the device has hardware counters for PHY
1398          * errors.  If so we need to enable the MIB interrupt
1399          * so we can act on stat triggers.
1400          */
1401         if (ath9k_hw_phycounters(ah))
1402                 sc->sc_needmib = 1;
1403
1404         /* Get the hardware key cache size. */
1405         sc->sc_keymax = ah->ah_caps.halKeyCacheSize;
1406         if (sc->sc_keymax > ATH_KEYMAX) {
1407                 DPRINTF(sc, ATH_DEBUG_KEYCACHE,
1408                         "%s: Warning, using only %u entries in %u key cache\n",
1409                         __func__, ATH_KEYMAX, sc->sc_keymax);
1410                 sc->sc_keymax = ATH_KEYMAX;
1411         }
1412
1413         /*
1414          * Reset the key cache since some parts do not
1415          * reset the contents on initial power up.
1416          */
1417         for (i = 0; i < sc->sc_keymax; i++)
1418                 ath9k_hw_keyreset(ah, (u_int16_t) i);
1419         /*
1420          * Mark key cache slots associated with global keys
1421          * as in use.  If we knew TKIP was not to be used we
1422          * could leave the +32, +64, and +32+64 slots free.
1423          * XXX only for splitmic.
1424          */
1425         for (i = 0; i < IEEE80211_WEP_NKID; i++) {
1426                 set_bit(i, sc->sc_keymap);
1427                 set_bit(i + 32, sc->sc_keymap);
1428                 set_bit(i + 64, sc->sc_keymap);
1429                 set_bit(i + 32 + 64, sc->sc_keymap);
1430         }
1431         /*
1432          * Collect the channel list using the default country
1433          * code and including outdoor channels.  The 802.11 layer
1434          * is resposible for filtering this list based on settings
1435          * like the phy mode.
1436          */
1437         rd = ah->ah_currentRD;
1438
1439         error = ath_getchannels(sc,
1440                                 CTRY_DEFAULT,
1441                                 ath_outdoor,
1442                                 1);
1443         if (error)
1444                 goto bad;
1445
1446         /* default to STA mode */
1447         sc->sc_opmode = HAL_M_MONITOR;
1448
1449         /* Setup rate tables for all potential media types. */
1450         /* 11g encompasses b,g */
1451
1452         ath_rate_setup(sc, WIRELESS_MODE_11a);
1453         ath_rate_setup(sc, WIRELESS_MODE_11g);
1454
1455         /* NB: setup here so ath_rate_update is happy */
1456         ath_setcurmode(sc, WIRELESS_MODE_11a);
1457
1458         /*
1459          * Allocate hardware transmit queues: one queue for
1460          * beacon frames and one data queue for each QoS
1461          * priority.  Note that the hal handles reseting
1462          * these queues at the needed time.
1463          */
1464         sc->sc_bhalq = ath_beaconq_setup(ah);
1465         if (sc->sc_bhalq == -1) {
1466                 DPRINTF(sc, ATH_DEBUG_FATAL,
1467                         "%s: unable to setup a beacon xmit queue\n", __func__);
1468                 error = -EIO;
1469                 goto bad2;
1470         }
1471         sc->sc_cabq = ath_txq_setup(sc, HAL_TX_QUEUE_CAB, 0);
1472         if (sc->sc_cabq == NULL) {
1473                 DPRINTF(sc, ATH_DEBUG_FATAL,
1474                         "%s: unable to setup CAB xmit queue\n", __func__);
1475                 error = -EIO;
1476                 goto bad2;
1477         }
1478
1479         sc->sc_config.cabqReadytime = ATH_CABQ_READY_TIME;
1480         ath_cabq_update(sc);
1481
1482         for (i = 0; i < ARRAY_SIZE(sc->sc_haltype2q); i++)
1483                 sc->sc_haltype2q[i] = -1;
1484
1485         /* Setup data queues */
1486         /* NB: ensure BK queue is the lowest priority h/w queue */
1487         if (!ath_tx_setup(sc, HAL_WME_AC_BK)) {
1488                 DPRINTF(sc, ATH_DEBUG_FATAL,
1489                         "%s: unable to setup xmit queue for BK traffic\n",
1490                         __func__);
1491                 error = -EIO;
1492                 goto bad2;
1493         }
1494
1495         if (!ath_tx_setup(sc, HAL_WME_AC_BE)) {
1496                 DPRINTF(sc, ATH_DEBUG_FATAL,
1497                         "%s: unable to setup xmit queue for BE traffic\n",
1498                         __func__);
1499                 error = -EIO;
1500                 goto bad2;
1501         }
1502         if (!ath_tx_setup(sc, HAL_WME_AC_VI)) {
1503                 DPRINTF(sc, ATH_DEBUG_FATAL,
1504                         "%s: unable to setup xmit queue for VI traffic\n",
1505                         __func__);
1506                 error = -EIO;
1507                 goto bad2;
1508         }
1509         if (!ath_tx_setup(sc, HAL_WME_AC_VO)) {
1510                 DPRINTF(sc, ATH_DEBUG_FATAL,
1511                         "%s: unable to setup xmit queue for VO traffic\n",
1512                         __func__);
1513                 error = -EIO;
1514                 goto bad2;
1515         }
1516
1517         if (ah->ah_caps.halHTSupport)
1518                 sc->sc_hashtsupport = 1;
1519
1520         sc->sc_rc = ath_rate_attach(ah);
1521         if (sc->sc_rc == NULL) {
1522                 error = EIO;
1523                 goto bad2;
1524         }
1525
1526         if (ath9k_hw_getcapability(ah, HAL_CAP_CIPHER, HAL_CIPHER_TKIP, NULL)) {
1527                 /*
1528                  * Whether we should enable h/w TKIP MIC.
1529                  * XXX: if we don't support WME TKIP MIC, then we wouldn't
1530                  * report WMM capable, so it's always safe to turn on
1531                  * TKIP MIC in this case.
1532                  */
1533                 ath9k_hw_setcapability(sc->sc_ah, HAL_CAP_TKIP_MIC, 0, 1, NULL);
1534         }
1535         sc->sc_hasclrkey = ath9k_hw_getcapability(ah, HAL_CAP_CIPHER,
1536                                                   HAL_CIPHER_CLR, NULL);
1537
1538         /*
1539          * Check whether the separate key cache entries
1540          * are required to handle both tx+rx MIC keys.
1541          * With split mic keys the number of stations is limited
1542          * to 27 otherwise 59.
1543          */
1544         if (ath9k_hw_getcapability(ah, HAL_CAP_CIPHER, HAL_CIPHER_TKIP, NULL)
1545             && ath9k_hw_getcapability(ah, HAL_CAP_CIPHER, HAL_CIPHER_MIC, NULL)
1546             && ath9k_hw_getcapability(ah, HAL_CAP_TKIP_SPLIT, 0, NULL))
1547                 sc->sc_splitmic = 1;
1548
1549         /* turn on mcast key search if possible */
1550         if (ath9k_hw_getcapability(ah, HAL_CAP_MCAST_KEYSRCH, 0, NULL)
1551                                         == HAL_OK)
1552                 (void)ath9k_hw_setcapability(ah, HAL_CAP_MCAST_KEYSRCH, 1,
1553                                              1, NULL);
1554
1555         sc->sc_config.txpowlimit = ATH_TXPOWER_MAX;
1556         sc->sc_config.txpowlimit_override = 0;
1557
1558         /* 11n Capabilities */
1559         if (sc->sc_hashtsupport) {
1560                 sc->sc_txaggr = 1;
1561                 sc->sc_rxaggr = 1;
1562         }
1563
1564         /* Check for misc other capabilities. */
1565         sc->sc_hasbmask = ah->ah_caps.halBssIdMaskSupport ? 1 : 0;
1566         sc->sc_hastsfadd =
1567                 ath9k_hw_getcapability(ah, HAL_CAP_TSF_ADJUST, 0, NULL);
1568
1569         /*
1570          * If we cannot transmit on three chains, prevent chain mask
1571          * selection logic from switching between 2x2 and 3x3 chain
1572          * masks based on RSSI.
1573          */
1574         sc->sc_no_tx_3_chains =
1575             (ah->ah_caps.halTxChainMask == ATH_CHAINMASK_SEL_3X3) ?
1576                 AH_TRUE : AH_FALSE;
1577         sc->sc_config.chainmask_sel = sc->sc_no_tx_3_chains;
1578
1579         sc->sc_tx_chainmask = ah->ah_caps.halTxChainMask;
1580         sc->sc_rx_chainmask = ah->ah_caps.halRxChainMask;
1581
1582         /* Configuration for rx chain detection */
1583         sc->sc_rxchaindetect_ref = 0;
1584         sc->sc_rxchaindetect_thresh5GHz = 35;
1585         sc->sc_rxchaindetect_thresh2GHz = 35;
1586         sc->sc_rxchaindetect_delta5GHz = 30;
1587         sc->sc_rxchaindetect_delta2GHz = 30;
1588
1589         /*
1590          * Query the hal about antenna support
1591          * Enable rx fast diversity if hal has support
1592          */
1593         if (ath9k_hw_getcapability(ah, HAL_CAP_DIVERSITY, 0, NULL)) {
1594                 sc->sc_hasdiversity = 1;
1595                 ath9k_hw_setcapability(ah, HAL_CAP_DIVERSITY,
1596                         1, AH_TRUE, NULL);
1597                 sc->sc_diversity = 1;
1598         } else {
1599                 sc->sc_hasdiversity = 0;
1600                 sc->sc_diversity = 0;
1601                 ath9k_hw_setcapability(ah, HAL_CAP_DIVERSITY,
1602                         1, AH_FALSE, NULL);
1603         }
1604         sc->sc_defant = ath9k_hw_getdefantenna(ah);
1605
1606         /*
1607          * Not all chips have the VEOL support we want to
1608          * use with IBSS beacons; check here for it.
1609          */
1610         sc->sc_hasveol = ah->ah_caps.halVEOLSupport;
1611
1612         ath9k_hw_getmac(ah, sc->sc_myaddr);
1613         if (sc->sc_hasbmask) {
1614                 ath9k_hw_getbssidmask(ah, sc->sc_bssidmask);
1615                 ATH_SET_VAP_BSSID_MASK(sc->sc_bssidmask);
1616                 ath9k_hw_setbssidmask(ah, sc->sc_bssidmask);
1617         }
1618         sc->sc_hasautosleep = ah->ah_caps.halAutoSleepSupport;
1619         sc->sc_waitbeacon = 0;
1620         sc->sc_slottime = HAL_SLOT_TIME_9;      /* default to short slot time */
1621
1622         /* initialize beacon slots */
1623         for (i = 0; i < ARRAY_SIZE(sc->sc_bslot); i++)
1624                 sc->sc_bslot[i] = ATH_IF_ID_ANY;
1625
1626         /* save MISC configurations */
1627         sc->sc_config.swBeaconProcess = 1;
1628
1629 #ifdef CONFIG_SLOW_ANT_DIV
1630         sc->sc_slowAntDiv = 1;
1631         /* range is 40 - 255, we use something in the middle */
1632         ath_slow_ant_div_init(&sc->sc_antdiv, sc, 0x127);
1633 #else
1634         sc->sc_slowAntDiv = 0;
1635 #endif
1636
1637         return 0;
1638 bad2:
1639         /* cleanup tx queues */
1640         for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
1641                 if (ATH_TXQ_SETUP(sc, i))
1642                         ath_tx_cleanupq(sc, &sc->sc_txq[i]);
1643 bad:
1644         if (ah)
1645                 ath9k_hw_detach(ah);
1646         return error;
1647 }
1648
1649 void ath_deinit(struct ath_softc *sc)
1650 {
1651         struct ath_hal *ah = sc->sc_ah;
1652         int i;
1653
1654         DPRINTF(sc, ATH_DEBUG_CONFIG, "%s\n", __func__);
1655
1656         ath_stop(sc);
1657         if (!sc->sc_invalid)
1658                 ath9k_hw_setpower(sc->sc_ah, HAL_PM_AWAKE);
1659         ath_rate_detach(sc->sc_rc);
1660         /* cleanup tx queues */
1661         for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
1662                 if (ATH_TXQ_SETUP(sc, i))
1663                         ath_tx_cleanupq(sc, &sc->sc_txq[i]);
1664         ath9k_hw_detach(ah);
1665 }
1666
1667 /*******************/
1668 /* Node Management */
1669 /*******************/
1670
1671 struct ath_node *ath_node_attach(struct ath_softc *sc, u8 *addr, int if_id)
1672 {
1673         struct ath_vap *avp;
1674         struct ath_node *an;
1675         DECLARE_MAC_BUF(mac);
1676
1677         avp = sc->sc_vaps[if_id];
1678         ASSERT(avp != NULL);
1679
1680         /* mac80211 sta_notify callback is from an IRQ context, so no sleep */
1681         an = kmalloc(sizeof(struct ath_node), GFP_ATOMIC);
1682         if (an == NULL)
1683                 return NULL;
1684         memzero(an, sizeof(*an));
1685
1686         an->an_sc = sc;
1687         memcpy(an->an_addr, addr, ETH_ALEN);
1688         atomic_set(&an->an_refcnt, 1);
1689
1690         /* set up per-node tx/rx state */
1691         ath_tx_node_init(sc, an);
1692         ath_rx_node_init(sc, an);
1693
1694         ath_chainmask_sel_init(sc, an);
1695         ath_chainmask_sel_timerstart(&an->an_chainmask_sel);
1696         list_add(&an->list, &sc->node_list);
1697
1698         DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p for: %s\n",
1699                 __func__, an, print_mac(mac, addr));
1700
1701         return an;
1702 }
1703
1704 void ath_node_detach(struct ath_softc *sc, struct ath_node *an, bool bh_flag)
1705 {
1706         unsigned long flags;
1707
1708         DECLARE_MAC_BUF(mac);
1709
1710         ath_chainmask_sel_timerstop(&an->an_chainmask_sel);
1711         an->an_flags |= ATH_NODE_CLEAN;
1712         ath_tx_node_cleanup(sc, an, bh_flag);
1713         ath_rx_node_cleanup(sc, an);
1714
1715         ath_tx_node_free(sc, an);
1716         ath_rx_node_free(sc, an);
1717
1718         spin_lock_irqsave(&sc->node_lock, flags);
1719
1720         list_del(&an->list);
1721
1722         spin_unlock_irqrestore(&sc->node_lock, flags);
1723
1724         DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p for: %s\n",
1725                 __func__, an, print_mac(mac, an->an_addr));
1726
1727         kfree(an);
1728 }
1729
1730 /* Finds a node and increases the refcnt if found */
1731
1732 struct ath_node *ath_node_get(struct ath_softc *sc, u8 *addr)
1733 {
1734         struct ath_node *an = NULL, *an_found = NULL;
1735
1736         if (list_empty(&sc->node_list)) /* FIXME */
1737                 goto out;
1738         list_for_each_entry(an, &sc->node_list, list) {
1739                 if (!compare_ether_addr(an->an_addr, addr)) {
1740                         atomic_inc(&an->an_refcnt);
1741                         an_found = an;
1742                         break;
1743                 }
1744         }
1745 out:
1746         return an_found;
1747 }
1748
1749 /* Decrements the refcnt and if it drops to zero, detach the node */
1750
1751 void ath_node_put(struct ath_softc *sc, struct ath_node *an, bool bh_flag)
1752 {
1753         if (atomic_dec_and_test(&an->an_refcnt))
1754                 ath_node_detach(sc, an, bh_flag);
1755 }
1756
1757 /* Finds a node, doesn't increment refcnt. Caller must hold sc->node_lock */
1758 struct ath_node *ath_node_find(struct ath_softc *sc, u8 *addr)
1759 {
1760         struct ath_node *an = NULL, *an_found = NULL;
1761
1762         if (list_empty(&sc->node_list))
1763                 return NULL;
1764
1765         list_for_each_entry(an, &sc->node_list, list)
1766                 if (!compare_ether_addr(an->an_addr, addr)) {
1767                         an_found = an;
1768                         break;
1769                 }
1770
1771         return an_found;
1772 }
1773
1774 /*
1775  * Set up New Node
1776  *
1777  * Setup driver-specific state for a newly associated node.  This routine
1778  * really only applies if compression or XR are enabled, there is no code
1779  * covering any other cases.
1780 */
1781
1782 void ath_newassoc(struct ath_softc *sc,
1783         struct ath_node *an, int isnew, int isuapsd)
1784 {
1785         int tidno;
1786
1787         /* if station reassociates, tear down the aggregation state. */
1788         if (!isnew) {
1789                 for (tidno = 0; tidno < WME_NUM_TID; tidno++) {
1790                         if (sc->sc_txaggr)
1791                                 ath_tx_aggr_teardown(sc, an, tidno);
1792                         if (sc->sc_rxaggr)
1793                                 ath_rx_aggr_teardown(sc, an, tidno);
1794                 }
1795         }
1796         an->an_flags = 0;
1797 }
1798
1799 /**************/
1800 /* Encryption */
1801 /**************/
1802 void ath_key_reset(struct ath_softc *sc, u_int16_t keyix, int freeslot)
1803 {
1804         ath9k_hw_keyreset(sc->sc_ah, keyix);
1805         if (freeslot)
1806                 clear_bit(keyix, sc->sc_keymap);
1807 }
1808
1809 int ath_keyset(struct ath_softc *sc,
1810                u_int16_t keyix,
1811                struct hal_keyval *hk,
1812                const u_int8_t mac[ETH_ALEN])
1813 {
1814         enum hal_bool status;
1815
1816         status = ath9k_hw_set_keycache_entry(sc->sc_ah,
1817                 keyix, hk, mac, AH_FALSE);
1818
1819         return status != AH_FALSE;
1820 }
1821
1822 /***********************/
1823 /* TX Power/Regulatory */
1824 /***********************/
1825
1826 /*
1827  *  Set Transmit power in HAL
1828  *
1829  *  This routine makes the actual HAL calls to set the new transmit power
1830  *  limit.
1831 */
1832
1833 void ath_update_txpow(struct ath_softc *sc)
1834 {
1835         struct ath_hal *ah = sc->sc_ah;
1836         u_int32_t txpow;
1837
1838         if (sc->sc_curtxpow != sc->sc_config.txpowlimit) {
1839                 ath9k_hw_set_txpowerlimit(ah, sc->sc_config.txpowlimit);
1840                 /* read back in case value is clamped */
1841                 ath9k_hw_getcapability(ah, HAL_CAP_TXPOW, 1, &txpow);
1842                 sc->sc_curtxpow = txpow;
1843         }
1844 }
1845
1846 /* Return the current country and domain information */
1847 void ath_get_currentCountry(struct ath_softc *sc,
1848         struct hal_country_entry *ctry)
1849 {
1850         ath9k_regd_get_current_country(sc->sc_ah, ctry);
1851
1852         /* If HAL not specific yet, since it is band dependent,
1853          * use the one we passed in. */
1854         if (ctry->countryCode == CTRY_DEFAULT) {
1855                 ctry->iso[0] = 0;
1856                 ctry->iso[1] = 0;
1857         } else if (ctry->iso[0] && ctry->iso[1]) {
1858                 if (!ctry->iso[2]) {
1859                         if (ath_outdoor)
1860                                 ctry->iso[2] = 'O';
1861                         else
1862                                 ctry->iso[2] = 'I';
1863                 }
1864         }
1865 }
1866
1867 /**************************/
1868 /* Slow Antenna Diversity */
1869 /**************************/
1870
1871 void ath_slow_ant_div_init(struct ath_antdiv *antdiv,
1872                            struct ath_softc *sc,
1873                            int32_t rssitrig)
1874 {
1875         int trig;
1876
1877         /* antdivf_rssitrig can range from 40 - 0xff */
1878         trig = (rssitrig > 0xff) ? 0xff : rssitrig;
1879         trig = (rssitrig < 40) ? 40 : rssitrig;
1880
1881         antdiv->antdiv_sc = sc;
1882         antdiv->antdivf_rssitrig = trig;
1883 }
1884
1885 void ath_slow_ant_div_start(struct ath_antdiv *antdiv,
1886                             u_int8_t num_antcfg,
1887                             const u_int8_t *bssid)
1888 {
1889         antdiv->antdiv_num_antcfg =
1890                 num_antcfg < ATH_ANT_DIV_MAX_CFG ?
1891                 num_antcfg : ATH_ANT_DIV_MAX_CFG;
1892         antdiv->antdiv_state = ATH_ANT_DIV_IDLE;
1893         antdiv->antdiv_curcfg = 0;
1894         antdiv->antdiv_bestcfg = 0;
1895         antdiv->antdiv_laststatetsf = 0;
1896
1897         memcpy(antdiv->antdiv_bssid, bssid, sizeof(antdiv->antdiv_bssid));
1898
1899         antdiv->antdiv_start = 1;
1900 }
1901
1902 void ath_slow_ant_div_stop(struct ath_antdiv *antdiv)
1903 {
1904         antdiv->antdiv_start = 0;
1905 }
1906
1907 static int32_t ath_find_max_val(int32_t *val,
1908         u_int8_t num_val, u_int8_t *max_index)
1909 {
1910         u_int32_t MaxVal = *val++;
1911         u_int32_t cur_index = 0;
1912
1913         *max_index = 0;
1914         while (++cur_index < num_val) {
1915                 if (*val > MaxVal) {
1916                         MaxVal = *val;
1917                         *max_index = cur_index;
1918                 }
1919
1920                 val++;
1921         }
1922
1923         return MaxVal;
1924 }
1925
1926 void ath_slow_ant_div(struct ath_antdiv *antdiv,
1927                       struct ieee80211_hdr *hdr,
1928                       struct ath_rx_status *rx_stats)
1929 {
1930         struct ath_softc *sc = antdiv->antdiv_sc;
1931         struct ath_hal *ah = sc->sc_ah;
1932         u_int64_t curtsf = 0;
1933         u_int8_t bestcfg, curcfg = antdiv->antdiv_curcfg;
1934         __le16 fc = hdr->frame_control;
1935
1936         if (antdiv->antdiv_start && ieee80211_is_beacon(fc)
1937             && !compare_ether_addr(hdr->addr3, antdiv->antdiv_bssid)) {
1938                 antdiv->antdiv_lastbrssi[curcfg] = rx_stats->rs_rssi;
1939                 antdiv->antdiv_lastbtsf[curcfg] = ath9k_hw_gettsf64(sc->sc_ah);
1940                 curtsf = antdiv->antdiv_lastbtsf[curcfg];
1941         } else {
1942                 return;
1943         }
1944
1945         switch (antdiv->antdiv_state) {
1946         case ATH_ANT_DIV_IDLE:
1947                 if ((antdiv->antdiv_lastbrssi[curcfg] <
1948                      antdiv->antdivf_rssitrig)
1949                     && ((curtsf - antdiv->antdiv_laststatetsf) >
1950                         ATH_ANT_DIV_MIN_IDLE_US)) {
1951
1952                         curcfg++;
1953                         if (curcfg == antdiv->antdiv_num_antcfg)
1954                                 curcfg = 0;
1955
1956                         if (HAL_OK == ath9k_hw_select_antconfig(ah, curcfg)) {
1957                                 antdiv->antdiv_bestcfg = antdiv->antdiv_curcfg;
1958                                 antdiv->antdiv_curcfg = curcfg;
1959                                 antdiv->antdiv_laststatetsf = curtsf;
1960                                 antdiv->antdiv_state = ATH_ANT_DIV_SCAN;
1961                         }
1962                 }
1963                 break;
1964
1965         case ATH_ANT_DIV_SCAN:
1966                 if ((curtsf - antdiv->antdiv_laststatetsf) <
1967                     ATH_ANT_DIV_MIN_SCAN_US)
1968                         break;
1969
1970                 curcfg++;
1971                 if (curcfg == antdiv->antdiv_num_antcfg)
1972                         curcfg = 0;
1973
1974                 if (curcfg == antdiv->antdiv_bestcfg) {
1975                         ath_find_max_val(antdiv->antdiv_lastbrssi,
1976                                    antdiv->antdiv_num_antcfg, &bestcfg);
1977                         if (HAL_OK == ath9k_hw_select_antconfig(ah, bestcfg)) {
1978                                 antdiv->antdiv_bestcfg = bestcfg;
1979                                 antdiv->antdiv_curcfg = bestcfg;
1980                                 antdiv->antdiv_laststatetsf = curtsf;
1981                                 antdiv->antdiv_state = ATH_ANT_DIV_IDLE;
1982                         }
1983                 } else {
1984                         if (HAL_OK == ath9k_hw_select_antconfig(ah, curcfg)) {
1985                                 antdiv->antdiv_curcfg = curcfg;
1986                                 antdiv->antdiv_laststatetsf = curtsf;
1987                                 antdiv->antdiv_state = ATH_ANT_DIV_SCAN;
1988                         }
1989                 }
1990
1991                 break;
1992         }
1993 }
1994
1995 /***********************/
1996 /* Descriptor Handling */
1997 /***********************/
1998
1999 /*
2000  *  Set up DMA descriptors
2001  *
2002  *  This function will allocate both the DMA descriptor structure, and the
2003  *  buffers it contains.  These are used to contain the descriptors used
2004  *  by the system.
2005 */
2006
2007 int ath_descdma_setup(struct ath_softc *sc,
2008                       struct ath_descdma *dd,
2009                       struct list_head *head,
2010                       const char *name,
2011                       int nbuf,
2012                       int ndesc)
2013 {
2014 #define DS2PHYS(_dd, _ds)                                               \
2015         ((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
2016 #define ATH_DESC_4KB_BOUND_CHECK(_daddr) ((((_daddr) & 0xFFF) > 0xF7F) ? 1 : 0)
2017 #define ATH_DESC_4KB_BOUND_NUM_SKIPPED(_len) ((_len) / 4096)
2018
2019         struct ath_desc *ds;
2020         struct ath_buf *bf;
2021         int i, bsize, error;
2022
2023         DPRINTF(sc, ATH_DEBUG_CONFIG, "%s: %s DMA: %u buffers %u desc/buf\n",
2024                 __func__, name, nbuf, ndesc);
2025
2026         /* ath_desc must be a multiple of DWORDs */
2027         if ((sizeof(struct ath_desc) % 4) != 0) {
2028                 DPRINTF(sc, ATH_DEBUG_FATAL, "%s: ath_desc not DWORD aligned\n",
2029                         __func__);
2030                 ASSERT((sizeof(struct ath_desc) % 4) == 0);
2031                 error = -ENOMEM;
2032                 goto fail;
2033         }
2034
2035         dd->dd_name = name;
2036         dd->dd_desc_len = sizeof(struct ath_desc) * nbuf * ndesc;
2037
2038         /*
2039          * Need additional DMA memory because we can't use
2040          * descriptors that cross the 4K page boundary. Assume
2041          * one skipped descriptor per 4K page.
2042          */
2043         if (!(sc->sc_ah->ah_caps.hal4kbSplitTransSupport)) {
2044                 u_int32_t ndesc_skipped =
2045                         ATH_DESC_4KB_BOUND_NUM_SKIPPED(dd->dd_desc_len);
2046                 u_int32_t dma_len;
2047
2048                 while (ndesc_skipped) {
2049                         dma_len = ndesc_skipped * sizeof(struct ath_desc);
2050                         dd->dd_desc_len += dma_len;
2051
2052                         ndesc_skipped = ATH_DESC_4KB_BOUND_NUM_SKIPPED(dma_len);
2053                 };
2054         }
2055
2056         /* allocate descriptors */
2057         dd->dd_desc = pci_alloc_consistent(sc->pdev,
2058                               dd->dd_desc_len,
2059                               &dd->dd_desc_paddr);
2060         if (dd->dd_desc == NULL) {
2061                 error = -ENOMEM;
2062                 goto fail;
2063         }
2064         ds = dd->dd_desc;
2065         DPRINTF(sc, ATH_DEBUG_CONFIG, "%s: %s DMA map: %p (%u) -> %llx (%u)\n",
2066                 __func__, dd->dd_name, ds, (u_int32_t) dd->dd_desc_len,
2067                 ito64(dd->dd_desc_paddr), /*XXX*/(u_int32_t) dd->dd_desc_len);
2068
2069         /* allocate buffers */
2070         bsize = sizeof(struct ath_buf) * nbuf;
2071         bf = kmalloc(bsize, GFP_KERNEL);
2072         if (bf == NULL) {
2073                 error = -ENOMEM;
2074                 goto fail2;
2075         }
2076         memzero(bf, bsize);
2077         dd->dd_bufptr = bf;
2078
2079         INIT_LIST_HEAD(head);
2080         for (i = 0; i < nbuf; i++, bf++, ds += ndesc) {
2081                 bf->bf_desc = ds;
2082                 bf->bf_daddr = DS2PHYS(dd, ds);
2083
2084                 if (!(sc->sc_ah->ah_caps.hal4kbSplitTransSupport)) {
2085                         /*
2086                          * Skip descriptor addresses which can cause 4KB
2087                          * boundary crossing (addr + length) with a 32 dword
2088                          * descriptor fetch.
2089                          */
2090                         while (ATH_DESC_4KB_BOUND_CHECK(bf->bf_daddr)) {
2091                                 ASSERT((caddr_t) bf->bf_desc <
2092                                        ((caddr_t) dd->dd_desc +
2093                                         dd->dd_desc_len));
2094
2095                                 ds += ndesc;
2096                                 bf->bf_desc = ds;
2097                                 bf->bf_daddr = DS2PHYS(dd, ds);
2098                         }
2099                 }
2100                 list_add_tail(&bf->list, head);
2101         }
2102         return 0;
2103 fail2:
2104         pci_free_consistent(sc->pdev,
2105                 dd->dd_desc_len, dd->dd_desc, dd->dd_desc_paddr);
2106 fail:
2107         memzero(dd, sizeof(*dd));
2108         return error;
2109 #undef ATH_DESC_4KB_BOUND_CHECK
2110 #undef ATH_DESC_4KB_BOUND_NUM_SKIPPED
2111 #undef DS2PHYS
2112 }
2113
2114 /*
2115  *  Cleanup DMA descriptors
2116  *
2117  *  This function will free the DMA block that was allocated for the descriptor
2118  *  pool.  Since this was allocated as one "chunk", it is freed in the same
2119  *  manner.
2120 */
2121
2122 void ath_descdma_cleanup(struct ath_softc *sc,
2123                          struct ath_descdma *dd,
2124                          struct list_head *head)
2125 {
2126         /* Free memory associated with descriptors */
2127         pci_free_consistent(sc->pdev,
2128                 dd->dd_desc_len, dd->dd_desc, dd->dd_desc_paddr);
2129
2130         INIT_LIST_HEAD(head);
2131         kfree(dd->dd_bufptr);
2132         memzero(dd, sizeof(*dd));
2133 }
2134
2135 /*************/
2136 /* Utilities */
2137 /*************/
2138
2139 void ath_internal_reset(struct ath_softc *sc)
2140 {
2141         ath_reset_start(sc, 0);
2142         ath_reset(sc);
2143         ath_reset_end(sc, 0);
2144 }
2145
2146 void ath_setrxfilter(struct ath_softc *sc)
2147 {
2148         u_int32_t rxfilt;
2149
2150         rxfilt = ath_calcrxfilter(sc);
2151         ath9k_hw_setrxfilter(sc->sc_ah, rxfilt);
2152 }
2153
2154 int ath_get_hal_qnum(u16 queue, struct ath_softc *sc)
2155 {
2156         int qnum;
2157
2158         switch (queue) {
2159         case 0:
2160                 qnum = sc->sc_haltype2q[HAL_WME_AC_VO];
2161                 break;
2162         case 1:
2163                 qnum = sc->sc_haltype2q[HAL_WME_AC_VI];
2164                 break;
2165         case 2:
2166                 qnum = sc->sc_haltype2q[HAL_WME_AC_BE];
2167                 break;
2168         case 3:
2169                 qnum = sc->sc_haltype2q[HAL_WME_AC_BK];
2170                 break;
2171         default:
2172                 qnum = sc->sc_haltype2q[HAL_WME_AC_BE];
2173                 break;
2174         }
2175
2176         return qnum;
2177 }
2178
2179 int ath_get_mac80211_qnum(u_int queue, struct ath_softc *sc)
2180 {
2181         int qnum;
2182
2183         switch (queue) {
2184         case HAL_WME_AC_VO:
2185                 qnum = 0;
2186                 break;
2187         case HAL_WME_AC_VI:
2188                 qnum = 1;
2189                 break;
2190         case HAL_WME_AC_BE:
2191                 qnum = 2;
2192                 break;
2193         case HAL_WME_AC_BK:
2194                 qnum = 3;
2195                 break;
2196         default:
2197                 qnum = -1;
2198                 break;
2199         }
2200
2201         return qnum;
2202 }
2203
2204
2205 /*
2206  *  Expand time stamp to TSF
2207  *
2208  *  Extend 15-bit time stamp from rx descriptor to
2209  *  a full 64-bit TSF using the current h/w TSF.
2210 */
2211
2212 u_int64_t ath_extend_tsf(struct ath_softc *sc, u_int32_t rstamp)
2213 {
2214         u_int64_t tsf;
2215
2216         tsf = ath9k_hw_gettsf64(sc->sc_ah);
2217         if ((tsf & 0x7fff) < rstamp)
2218                 tsf -= 0x8000;
2219         return (tsf & ~0x7fff) | rstamp;
2220 }
2221
2222 /*
2223  *  Set Default Antenna
2224  *
2225  *  Call into the HAL to set the default antenna to use.  Not really valid for
2226  *  MIMO technology.
2227 */
2228
2229 void ath_setdefantenna(void *context, u_int antenna)
2230 {
2231         struct ath_softc *sc = (struct ath_softc *)context;
2232         struct ath_hal *ah = sc->sc_ah;
2233
2234         /* XXX block beacon interrupts */
2235         ath9k_hw_setantenna(ah, antenna);
2236         sc->sc_defant = antenna;
2237         sc->sc_rxotherant = 0;
2238 }
2239
2240 /*
2241  * Set Slot Time
2242  *
2243  * This will wake up the chip if required, and set the slot time for the
2244  * frame (maximum transmit time).  Slot time is assumed to be already set
2245  * in the ATH object member sc_slottime
2246 */
2247
2248 void ath_setslottime(struct ath_softc *sc)
2249 {
2250         ath9k_hw_setslottime(sc->sc_ah, sc->sc_slottime);
2251         sc->sc_updateslot = OK;
2252 }