netmap: d_poll -> d_kqfilter
[dragonfly.git] / sys / dev / netif / ath / hal / ath_hal / ar5211 / ar5211_reset.c
1 /*
2  * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
3  * Copyright (c) 2002-2006 Atheros Communications, Inc.
4  *
5  * Permission to use, copy, modify, and/or distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  *
17  * $FreeBSD: head/sys/dev/ath/ath_hal/ar5211/ar5211_reset.c 201758 2010-01-07 21:01:37Z mbr $
18  */
19 #include "opt_ah.h"
20
21 /*
22  * Chips specific device attachment and device info collection
23  * Connects Init Reg Vectors, EEPROM Data, and device Functions.
24  */
25 #include "ah.h"
26 #include "ah_internal.h"
27 #include "ah_devid.h"
28
29 #include "ar5211/ar5211.h"
30 #include "ar5211/ar5211reg.h"
31 #include "ar5211/ar5211phy.h"
32
33 #include "ah_eeprom_v3.h"
34
35 /* Add static register initialization vectors */
36 #include "ar5211/boss.ini"
37
38 /*
39  * Structure to hold 11b tuning information for Beanie/Sombrero
40  * 16 MHz mode, divider ratio = 198 = NP+S. N=16, S=4 or 6, P=12
41  */
42 typedef struct {
43         uint32_t        refClkSel;      /* reference clock, 1 for 16 MHz */
44         uint32_t        channelSelect;  /* P[7:4]S[3:0] bits */
45         uint16_t        channel5111;    /* 11a channel for 5111 */
46 } CHAN_INFO_2GHZ;
47
48 #define CI_2GHZ_INDEX_CORRECTION 19
49 static const CHAN_INFO_2GHZ chan2GHzData[] = {
50         { 1, 0x46, 96  },       /* 2312 -19 */
51         { 1, 0x46, 97  },       /* 2317 -18 */
52         { 1, 0x46, 98  },       /* 2322 -17 */
53         { 1, 0x46, 99  },       /* 2327 -16 */
54         { 1, 0x46, 100 },       /* 2332 -15 */
55         { 1, 0x46, 101 },       /* 2337 -14 */
56         { 1, 0x46, 102 },       /* 2342 -13 */
57         { 1, 0x46, 103 },       /* 2347 -12 */
58         { 1, 0x46, 104 },       /* 2352 -11 */
59         { 1, 0x46, 105 },       /* 2357 -10 */
60         { 1, 0x46, 106 },       /* 2362  -9 */
61         { 1, 0x46, 107 },       /* 2367  -8 */
62         { 1, 0x46, 108 },       /* 2372  -7 */
63         /* index -6 to 0 are pad to make this a nolookup table */
64         { 1, 0x46, 116 },       /*       -6 */
65         { 1, 0x46, 116 },       /*       -5 */
66         { 1, 0x46, 116 },       /*       -4 */
67         { 1, 0x46, 116 },       /*       -3 */
68         { 1, 0x46, 116 },       /*       -2 */
69         { 1, 0x46, 116 },       /*       -1 */
70         { 1, 0x46, 116 },       /*        0 */
71         { 1, 0x46, 116 },       /* 2412   1 */
72         { 1, 0x46, 117 },       /* 2417   2 */
73         { 1, 0x46, 118 },       /* 2422   3 */
74         { 1, 0x46, 119 },       /* 2427   4 */
75         { 1, 0x46, 120 },       /* 2432   5 */
76         { 1, 0x46, 121 },       /* 2437   6 */
77         { 1, 0x46, 122 },       /* 2442   7 */
78         { 1, 0x46, 123 },       /* 2447   8 */
79         { 1, 0x46, 124 },       /* 2452   9 */
80         { 1, 0x46, 125 },       /* 2457  10 */
81         { 1, 0x46, 126 },       /* 2462  11 */
82         { 1, 0x46, 127 },       /* 2467  12 */
83         { 1, 0x46, 128 },       /* 2472  13 */
84         { 1, 0x44, 124 },       /* 2484  14 */
85         { 1, 0x46, 136 },       /* 2512  15 */
86         { 1, 0x46, 140 },       /* 2532  16 */
87         { 1, 0x46, 144 },       /* 2552  17 */
88         { 1, 0x46, 148 },       /* 2572  18 */
89         { 1, 0x46, 152 },       /* 2592  19 */
90         { 1, 0x46, 156 },       /* 2612  20 */
91         { 1, 0x46, 160 },       /* 2632  21 */
92         { 1, 0x46, 164 },       /* 2652  22 */
93         { 1, 0x46, 168 },       /* 2672  23 */
94         { 1, 0x46, 172 },       /* 2692  24 */
95         { 1, 0x46, 176 },       /* 2712  25 */
96         { 1, 0x46, 180 }        /* 2732  26 */
97 };
98
99 /* Power timeouts in usec to wait for chip to wake-up. */
100 #define POWER_UP_TIME   2000
101
102 #define DELAY_PLL_SETTLE        300             /* 300 us */
103 #define DELAY_BASE_ACTIVATE     100             /* 100 us */
104
105 #define NUM_RATES       8
106
107 static HAL_BOOL ar5211SetResetReg(struct ath_hal *ah, uint32_t resetMask);
108 static HAL_BOOL ar5211SetChannel(struct ath_hal *,
109                 const struct ieee80211_channel *);
110 static int16_t ar5211RunNoiseFloor(struct ath_hal *,
111                 uint8_t runTime, int16_t startingNF);
112 static HAL_BOOL ar5211IsNfGood(struct ath_hal *,
113                 struct ieee80211_channel *chan);
114 static HAL_BOOL ar5211SetRf6and7(struct ath_hal *,
115                 const struct ieee80211_channel *chan);
116 static HAL_BOOL ar5211SetBoardValues(struct ath_hal *,
117                 const struct ieee80211_channel *chan);
118 static void ar5211SetPowerTable(struct ath_hal *,
119                 PCDACS_EEPROM *pSrcStruct, uint16_t channel);
120 static HAL_BOOL ar5211SetTransmitPower(struct ath_hal *,
121                 const struct ieee80211_channel *);
122 static void ar5211SetRateTable(struct ath_hal *,
123                 RD_EDGES_POWER *pRdEdgesPower, TRGT_POWER_INFO *pPowerInfo,
124                 uint16_t numChannels, const struct ieee80211_channel *chan);
125 static uint16_t ar5211GetScaledPower(uint16_t channel, uint16_t pcdacValue,
126                 const PCDACS_EEPROM *pSrcStruct);
127 static HAL_BOOL ar5211FindValueInList(uint16_t channel, uint16_t pcdacValue,
128                 const PCDACS_EEPROM *pSrcStruct, uint16_t *powerValue);
129 static uint16_t ar5211GetInterpolatedValue(uint16_t target,
130                 uint16_t srcLeft, uint16_t srcRight,
131                 uint16_t targetLeft, uint16_t targetRight, HAL_BOOL scaleUp);
132 static void ar5211GetLowerUpperValues(uint16_t value,
133                 const uint16_t *pList, uint16_t listSize,
134                 uint16_t *pLowerValue, uint16_t *pUpperValue);
135 static void ar5211GetLowerUpperPcdacs(uint16_t pcdac,
136                 uint16_t channel, const PCDACS_EEPROM *pSrcStruct,
137                 uint16_t *pLowerPcdac, uint16_t *pUpperPcdac);
138
139 static void ar5211SetRfgain(struct ath_hal *, const GAIN_VALUES *);
140 static void ar5211RequestRfgain(struct ath_hal *);
141 static HAL_BOOL ar5211InvalidGainReadback(struct ath_hal *, GAIN_VALUES *);
142 static HAL_BOOL ar5211IsGainAdjustNeeded(struct ath_hal *, const GAIN_VALUES *);
143 static int32_t ar5211AdjustGain(struct ath_hal *, GAIN_VALUES *);
144 static void ar5211SetOperatingMode(struct ath_hal *, int opmode);
145
146 /*
147  * Places the device in and out of reset and then places sane
148  * values in the registers based on EEPROM config, initialization
149  * vectors (as determined by the mode), and station configuration
150  *
151  * bChannelChange is used to preserve DMA/PCU registers across
152  * a HW Reset during channel change.
153  */
154 HAL_BOOL
155 ar5211Reset(struct ath_hal *ah, HAL_OPMODE opmode,
156         struct ieee80211_channel *chan, HAL_BOOL bChannelChange,
157         HAL_STATUS *status)
158 {
159 uint32_t softLedCfg, softLedState;
160 #define N(a)    (sizeof (a) /sizeof (a[0]))
161 #define FAIL(_code)     do { ecode = _code; goto bad; } while (0)
162         struct ath_hal_5211 *ahp = AH5211(ah);
163         HAL_CHANNEL_INTERNAL *ichan;
164         uint32_t i, ledstate;
165         HAL_STATUS ecode;
166         int q;
167
168         uint32_t                data, synthDelay;
169         uint32_t                macStaId1;    
170         uint16_t                modesIndex = 0, freqIndex = 0;
171         uint32_t                saveFrameSeqCount[AR_NUM_DCU];
172         uint32_t                saveTsfLow = 0, saveTsfHigh = 0;
173         uint32_t                saveDefAntenna;
174
175         HALDEBUG(ah, HAL_DEBUG_RESET,
176              "%s: opmode %u channel %u/0x%x %s channel\n",
177              __func__, opmode, chan->ic_freq, chan->ic_flags,
178              bChannelChange ? "change" : "same");
179
180         OS_MARK(ah, AH_MARK_RESET, bChannelChange);
181         /*
182          * Map public channel to private.
183          */
184         ichan = ath_hal_checkchannel(ah, chan);
185         if (ichan == AH_NULL)
186                 FAIL(HAL_EINVAL);
187         switch (opmode) {
188         case HAL_M_STA:
189         case HAL_M_IBSS:
190         case HAL_M_HOSTAP:
191         case HAL_M_MONITOR:
192                 break;
193         default:
194                 HALDEBUG(ah, HAL_DEBUG_ANY,
195                     "%s: invalid operating mode %u\n", __func__, opmode);
196                 FAIL(HAL_EINVAL);
197                 break;
198         }
199         HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER3);
200
201         /* Preserve certain DMA hardware registers on a channel change */
202         if (bChannelChange) {
203                 /*
204                  * Need to save/restore the TSF because of an issue
205                  * that accelerates the TSF during a chip reset.
206                  *
207                  * We could use system timer routines to more
208                  * accurately restore the TSF, but
209                  * 1. Timer routines on certain platforms are
210                  *      not accurate enough (e.g. 1 ms resolution).
211                  * 2. It would still not be accurate.
212                  *
213                  * The most important aspect of this workaround,
214                  * is that, after reset, the TSF is behind
215                  * other STAs TSFs.  This will allow the STA to
216                  * properly resynchronize its TSF in adhoc mode.
217                  */
218                 saveTsfLow  = OS_REG_READ(ah, AR_TSF_L32);
219                 saveTsfHigh = OS_REG_READ(ah, AR_TSF_U32);
220
221                 /* Read frame sequence count */
222                 if (AH_PRIVATE(ah)->ah_macVersion >= AR_SREV_VERSION_OAHU) {
223                         saveFrameSeqCount[0] = OS_REG_READ(ah, AR_D0_SEQNUM);
224                 } else {
225                         for (i = 0; i < AR_NUM_DCU; i++)
226                                 saveFrameSeqCount[i] = OS_REG_READ(ah, AR_DSEQNUM(i));
227                 }
228                 if (!IEEE80211_IS_CHAN_DFS(chan)) 
229                         chan->ic_state &= ~IEEE80211_CHANSTATE_CWINT;
230         }
231
232         /*
233          * Preserve the antenna on a channel change
234          */
235         saveDefAntenna = OS_REG_READ(ah, AR_DEF_ANTENNA);
236         if (saveDefAntenna == 0)
237                 saveDefAntenna = 1;
238
239         /* Save hardware flag before chip reset clears the register */
240         macStaId1 = OS_REG_READ(ah, AR_STA_ID1) & AR_STA_ID1_BASE_RATE_11B;
241
242         /* Save led state from pci config register */
243         ledstate = OS_REG_READ(ah, AR_PCICFG) &
244                 (AR_PCICFG_LEDCTL | AR_PCICFG_LEDMODE | AR_PCICFG_LEDBLINK |
245                  AR_PCICFG_LEDSLOW);
246         softLedCfg = OS_REG_READ(ah, AR_GPIOCR);
247         softLedState = OS_REG_READ(ah, AR_GPIODO);
248
249         if (!ar5211ChipReset(ah, chan)) {
250                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: chip reset failed\n", __func__);
251                 FAIL(HAL_EIO);
252         }
253
254         /* Setup the indices for the next set of register array writes */
255         if (IEEE80211_IS_CHAN_5GHZ(chan)) {
256                 freqIndex = 1;
257                 if (IEEE80211_IS_CHAN_TURBO(chan))
258                         modesIndex = 2;
259                 else if (IEEE80211_IS_CHAN_A(chan))
260                         modesIndex = 1;
261                 else {
262                         HALDEBUG(ah, HAL_DEBUG_ANY,
263                             "%s: invalid channel %u/0x%x\n",
264                             __func__, chan->ic_freq, chan->ic_flags);
265                         FAIL(HAL_EINVAL);
266                 }
267         } else {
268                 freqIndex = 2;
269                 if (IEEE80211_IS_CHAN_B(chan))
270                         modesIndex = 3;
271                 else if (IEEE80211_IS_CHAN_PUREG(chan))
272                         modesIndex = 4;
273                 else {
274                         HALDEBUG(ah, HAL_DEBUG_ANY,
275                             "%s: invalid channel %u/0x%x\n",
276                             __func__, chan->ic_freq, chan->ic_flags);
277                         FAIL(HAL_EINVAL);
278                 }
279         }
280
281         /* Set correct Baseband to analog shift setting to access analog chips. */
282         if (AH_PRIVATE(ah)->ah_macVersion >= AR_SREV_VERSION_OAHU) {
283                 OS_REG_WRITE(ah, AR_PHY_BASE, 0x00000007);
284         } else {
285                 OS_REG_WRITE(ah, AR_PHY_BASE, 0x00000047);
286         }
287
288         /* Write parameters specific to AR5211 */
289         if (AH_PRIVATE(ah)->ah_macVersion >= AR_SREV_VERSION_OAHU) {
290                 if (IEEE80211_IS_CHAN_2GHZ(chan) &&
291                     AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER3_1) {
292                         HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
293                         uint32_t ob2GHz, db2GHz;
294
295                         if (IEEE80211_IS_CHAN_CCK(chan)) {
296                                 ob2GHz = ee->ee_ob2GHz[0];
297                                 db2GHz = ee->ee_db2GHz[0];
298                         } else {
299                                 ob2GHz = ee->ee_ob2GHz[1];
300                                 db2GHz = ee->ee_db2GHz[1];
301                         }
302                         ob2GHz = ath_hal_reverseBits(ob2GHz, 3);
303                         db2GHz = ath_hal_reverseBits(db2GHz, 3);
304                         ar5211Mode2_4[25][freqIndex] =
305                                 (ar5211Mode2_4[25][freqIndex] & ~0xC0) |
306                                         ((ob2GHz << 6) & 0xC0);
307                         ar5211Mode2_4[26][freqIndex] =
308                                 (ar5211Mode2_4[26][freqIndex] & ~0x0F) |
309                                         (((ob2GHz >> 2) & 0x1) |
310                                          ((db2GHz << 1) & 0x0E));
311                 }
312                 for (i = 0; i < N(ar5211Mode2_4); i++)
313                         OS_REG_WRITE(ah, ar5211Mode2_4[i][0],
314                                 ar5211Mode2_4[i][freqIndex]);
315         }
316
317         /* Write the analog registers 6 and 7 before other config */
318         ar5211SetRf6and7(ah, chan);
319
320         /* Write registers that vary across all modes */
321         for (i = 0; i < N(ar5211Modes); i++)
322                 OS_REG_WRITE(ah, ar5211Modes[i][0], ar5211Modes[i][modesIndex]);
323
324         /* Write RFGain Parameters that differ between 2.4 and 5 GHz */
325         for (i = 0; i < N(ar5211BB_RfGain); i++)
326                 OS_REG_WRITE(ah, ar5211BB_RfGain[i][0], ar5211BB_RfGain[i][freqIndex]);
327
328         /* Write Common Array Parameters */
329         for (i = 0; i < N(ar5211Common); i++) {
330                 uint32_t reg = ar5211Common[i][0];
331                 /* On channel change, don't reset the PCU registers */
332                 if (!(bChannelChange && (0x8000 <= reg && reg < 0x9000)))
333                         OS_REG_WRITE(ah, reg, ar5211Common[i][1]);
334         }
335
336         /* Fix pre-AR5211 register values, this includes AR5311s. */
337         if (AH_PRIVATE(ah)->ah_macVersion < AR_SREV_VERSION_OAHU) {
338                 /*
339                  * The TX and RX latency values have changed locations
340                  * within the USEC register in AR5211.  Since they're
341                  * set via the .ini, for both AR5211 and AR5311, they
342                  * are written properly here for AR5311.
343                  */
344                 data = OS_REG_READ(ah, AR_USEC);
345                 /* Must be 0 for proper write in AR5311 */
346                 HALASSERT((data & 0x00700000) == 0);
347                 OS_REG_WRITE(ah, AR_USEC,
348                         (data & (AR_USEC_M | AR_USEC_32_M | AR5311_USEC_TX_LAT_M)) |
349                         ((29 << AR5311_USEC_RX_LAT_S) & AR5311_USEC_RX_LAT_M));
350                 /* The following registers exist only on AR5311. */
351                 OS_REG_WRITE(ah, AR5311_QDCLKGATE, 0);
352
353                 /* Set proper ADC & DAC delays for AR5311. */
354                 OS_REG_WRITE(ah, 0x00009878, 0x00000008);
355
356                 /* Enable the PCU FIFO corruption ECO on AR5311. */
357                 OS_REG_WRITE(ah, AR_DIAG_SW,
358                         OS_REG_READ(ah, AR_DIAG_SW) | AR5311_DIAG_SW_USE_ECO);
359         }
360
361         /* Restore certain DMA hardware registers on a channel change */
362         if (bChannelChange) {
363                 /* Restore TSF */
364                 OS_REG_WRITE(ah, AR_TSF_L32, saveTsfLow);
365                 OS_REG_WRITE(ah, AR_TSF_U32, saveTsfHigh);
366
367                 if (AH_PRIVATE(ah)->ah_macVersion >= AR_SREV_VERSION_OAHU) {
368                         OS_REG_WRITE(ah, AR_D0_SEQNUM, saveFrameSeqCount[0]);
369                 } else {
370                         for (i = 0; i < AR_NUM_DCU; i++)
371                                 OS_REG_WRITE(ah, AR_DSEQNUM(i), saveFrameSeqCount[i]);
372                 }
373         }
374
375         OS_REG_WRITE(ah, AR_STA_ID0, LE_READ_4(ahp->ah_macaddr));
376         OS_REG_WRITE(ah, AR_STA_ID1, LE_READ_2(ahp->ah_macaddr + 4)
377                 | macStaId1
378         );
379         ar5211SetOperatingMode(ah, opmode);
380
381         /* Restore previous led state */
382         OS_REG_WRITE(ah, AR_PCICFG, OS_REG_READ(ah, AR_PCICFG) | ledstate);
383         OS_REG_WRITE(ah, AR_GPIOCR, softLedCfg);
384         OS_REG_WRITE(ah, AR_GPIODO, softLedState);
385
386         /* Restore previous antenna */
387         OS_REG_WRITE(ah, AR_DEF_ANTENNA, saveDefAntenna);
388
389         OS_REG_WRITE(ah, AR_BSS_ID0, LE_READ_4(ahp->ah_bssid));
390         OS_REG_WRITE(ah, AR_BSS_ID1, LE_READ_2(ahp->ah_bssid + 4));
391
392         /* Restore bmiss rssi & count thresholds */
393         OS_REG_WRITE(ah, AR_RSSI_THR, ahp->ah_rssiThr);
394
395         OS_REG_WRITE(ah, AR_ISR, ~0);           /* cleared on write */
396
397         /*
398          * for pre-Production Oahu only.
399          * Disable clock gating in all DMA blocks. Helps when using
400          * 11B and AES but results in higher power consumption.
401          */
402         if (AH_PRIVATE(ah)->ah_macVersion == AR_SREV_VERSION_OAHU &&
403             AH_PRIVATE(ah)->ah_macRev < AR_SREV_OAHU_PROD) {
404                 OS_REG_WRITE(ah, AR_CFG,
405                         OS_REG_READ(ah, AR_CFG) | AR_CFG_CLK_GATE_DIS);
406         }
407
408         /* Setup the transmit power values. */
409         if (!ar5211SetTransmitPower(ah, chan)) {
410                 HALDEBUG(ah, HAL_DEBUG_ANY,
411                     "%s: error init'ing transmit power\n", __func__);
412                 FAIL(HAL_EIO);
413         }
414
415         /*
416          * Configurable OFDM spoofing for 11n compatibility; used
417          * only when operating in station mode.
418          */
419         if (opmode != HAL_M_HOSTAP &&
420             (AH_PRIVATE(ah)->ah_11nCompat & HAL_DIAG_11N_SERVICES) != 0) {
421                 /* NB: override the .ini setting */
422                 OS_REG_RMW_FIELD(ah, AR_PHY_FRAME_CTL,
423                         AR_PHY_FRAME_CTL_ERR_SERV,
424                         MS(AH_PRIVATE(ah)->ah_11nCompat, HAL_DIAG_11N_SERVICES)&1);
425         }
426
427         /* Setup board specific options for EEPROM version 3 */
428         ar5211SetBoardValues(ah, chan);
429
430         if (!ar5211SetChannel(ah, chan)) {
431                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: unable to set channel\n",
432                     __func__);
433                 FAIL(HAL_EIO);
434         }
435
436         /* Activate the PHY */
437         if (AH_PRIVATE(ah)->ah_devid == AR5211_FPGA11B &&
438             IEEE80211_IS_CHAN_2GHZ(chan))
439                 OS_REG_WRITE(ah, 0xd808, 0x502); /* required for FPGA */
440         OS_REG_WRITE(ah, AR_PHY_ACTIVE, AR_PHY_ACTIVE_EN);
441
442         /*
443          * Wait for the frequency synth to settle (synth goes on
444          * via AR_PHY_ACTIVE_EN).  Read the phy active delay register.
445          * Value is in 100ns increments.
446          */
447         data = OS_REG_READ(ah, AR_PHY_RX_DELAY) & AR_PHY_RX_DELAY_M;
448         if (IEEE80211_IS_CHAN_CCK(chan)) {
449                 synthDelay = (4 * data) / 22;
450         } else {
451                 synthDelay = data / 10;
452         }
453         /*
454          * There is an issue if the AP starts the calibration before
455          * the baseband timeout completes.  This could result in the
456          * rxclear false triggering.  Add an extra delay to ensure this
457          * this does not happen.
458          */
459         OS_DELAY(synthDelay + DELAY_BASE_ACTIVATE);
460
461         /* Calibrate the AGC and wait for completion. */
462         OS_REG_WRITE(ah, AR_PHY_AGC_CONTROL,
463                  OS_REG_READ(ah, AR_PHY_AGC_CONTROL) | AR_PHY_AGC_CONTROL_CAL);
464         (void) ath_hal_wait(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_CAL, 0);
465
466         /* Perform noise floor and set status */
467         if (!ar5211CalNoiseFloor(ah, chan)) {
468                 if (!IEEE80211_IS_CHAN_CCK(chan))
469                         chan->ic_state |= IEEE80211_CHANSTATE_CWINT;
470                 HALDEBUG(ah, HAL_DEBUG_ANY,
471                     "%s: noise floor calibration failed\n", __func__);
472                 FAIL(HAL_EIO);
473         }
474
475         /* Start IQ calibration w/ 2^(INIT_IQCAL_LOG_COUNT_MAX+1) samples */
476         if (ahp->ah_calibrationTime != 0) {
477                 OS_REG_WRITE(ah, AR_PHY_TIMING_CTRL4,
478                         AR_PHY_TIMING_CTRL4_DO_IQCAL | (INIT_IQCAL_LOG_COUNT_MAX << AR_PHY_TIMING_CTRL4_IQCAL_LOG_COUNT_MAX_S));
479                 ahp->ah_bIQCalibration = AH_TRUE;
480         }
481
482         /* set 1:1 QCU to DCU mapping for all queues */
483         for (q = 0; q < AR_NUM_DCU; q++)
484                 OS_REG_WRITE(ah, AR_DQCUMASK(q), 1<<q);
485
486         for (q = 0; q < HAL_NUM_TX_QUEUES; q++)
487                 ar5211ResetTxQueue(ah, q);
488
489         /* Setup QCU0 transmit interrupt masks (TX_ERR, TX_OK, TX_DESC, TX_URN) */
490         OS_REG_WRITE(ah, AR_IMR_S0,
491                  (AR_IMR_S0_QCU_TXOK & AR_QCU_0) |
492                  (AR_IMR_S0_QCU_TXDESC & (AR_QCU_0<<AR_IMR_S0_QCU_TXDESC_S)));
493         OS_REG_WRITE(ah, AR_IMR_S1, (AR_IMR_S1_QCU_TXERR & AR_QCU_0));
494         OS_REG_WRITE(ah, AR_IMR_S2, (AR_IMR_S2_QCU_TXURN & AR_QCU_0));
495
496         /*
497          * GBL_EIFS must always be written after writing
498          *              to any QCUMASK register.
499          */
500         OS_REG_WRITE(ah, AR_D_GBL_IFS_EIFS, OS_REG_READ(ah, AR_D_GBL_IFS_EIFS));
501
502         /* Now set up the Interrupt Mask Register and save it for future use */
503         OS_REG_WRITE(ah, AR_IMR, INIT_INTERRUPT_MASK);
504         ahp->ah_maskReg = INIT_INTERRUPT_MASK;
505
506         /* Enable bus error interrupts */
507         OS_REG_WRITE(ah, AR_IMR_S2, OS_REG_READ(ah, AR_IMR_S2) |
508                  AR_IMR_S2_MCABT | AR_IMR_S2_SSERR | AR_IMR_S2_DPERR);
509
510         /* Enable interrupts specific to AP */
511         if (opmode == HAL_M_HOSTAP) {
512                 OS_REG_WRITE(ah, AR_IMR, OS_REG_READ(ah, AR_IMR) | AR_IMR_MIB);
513                 ahp->ah_maskReg |= AR_IMR_MIB;
514         }
515
516         if (AH_PRIVATE(ah)->ah_rfkillEnabled)
517                 ar5211EnableRfKill(ah);
518
519         /*
520          * Writing to AR_BEACON will start timers. Hence it should
521          * be the last register to be written. Do not reset tsf, do
522          * not enable beacons at this point, but preserve other values
523          * like beaconInterval.
524          */
525         OS_REG_WRITE(ah, AR_BEACON,
526                 (OS_REG_READ(ah, AR_BEACON) &~ (AR_BEACON_EN | AR_BEACON_RESET_TSF)));
527
528         /* Restore user-specified slot time and timeouts */
529         if (ahp->ah_sifstime != (u_int) -1)
530                 ar5211SetSifsTime(ah, ahp->ah_sifstime);
531         if (ahp->ah_slottime != (u_int) -1)
532                 ar5211SetSlotTime(ah, ahp->ah_slottime);
533         if (ahp->ah_acktimeout != (u_int) -1)
534                 ar5211SetAckTimeout(ah, ahp->ah_acktimeout);
535         if (ahp->ah_ctstimeout != (u_int) -1)
536                 ar5211SetCTSTimeout(ah, ahp->ah_ctstimeout);
537         if (AH_PRIVATE(ah)->ah_diagreg != 0)
538                 OS_REG_WRITE(ah, AR_DIAG_SW, AH_PRIVATE(ah)->ah_diagreg);
539
540         AH_PRIVATE(ah)->ah_opmode = opmode;     /* record operating mode */
541
542         HALDEBUG(ah, HAL_DEBUG_RESET, "%s: done\n", __func__);
543
544         return AH_TRUE;
545 bad:
546         if (status != AH_NULL)
547                 *status = ecode;
548         return AH_FALSE;
549 #undef FAIL
550 #undef N
551 }
552
553 /*
554  * Places the PHY and Radio chips into reset.  A full reset
555  * must be called to leave this state.  The PCI/MAC/PCU are
556  * not placed into reset as we must receive interrupt to
557  * re-enable the hardware.
558  */
559 HAL_BOOL
560 ar5211PhyDisable(struct ath_hal *ah)
561 {
562         return ar5211SetResetReg(ah, AR_RC_BB);
563 }
564
565 /*
566  * Places all of hardware into reset
567  */
568 HAL_BOOL
569 ar5211Disable(struct ath_hal *ah)
570 {
571         if (!ar5211SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
572                 return AH_FALSE;
573         /*
574          * Reset the HW - PCI must be reset after the rest of the
575          * device has been reset.
576          */
577         if (!ar5211SetResetReg(ah, AR_RC_MAC | AR_RC_BB | AR_RC_PCI))
578                 return AH_FALSE;
579         OS_DELAY(2100);    /* 8245 @ 96Mhz hangs with 2000us. */
580
581         return AH_TRUE;
582 }
583
584 /*
585  * Places the hardware into reset and then pulls it out of reset
586  *
587  * Only write the PLL if we're changing to or from CCK mode
588  *
589  * Attach calls with channelFlags = 0, as the coldreset should have
590  * us in the correct mode and we cannot check the hwchannel flags.
591  */
592 HAL_BOOL
593 ar5211ChipReset(struct ath_hal *ah, const struct ieee80211_channel *chan)
594 {
595         if (!ar5211SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
596                 return AH_FALSE;
597
598         /* NB: called from attach with chan null */
599         if (chan != AH_NULL) {
600                 /* Set CCK and Turbo modes correctly */
601                 OS_REG_WRITE(ah, AR_PHY_TURBO, IEEE80211_IS_CHAN_TURBO(chan) ?
602                     AR_PHY_FC_TURBO_MODE | AR_PHY_FC_TURBO_SHORT : 0);
603                 if (IEEE80211_IS_CHAN_B(chan)) {
604                         OS_REG_WRITE(ah, AR5211_PHY_MODE,
605                             AR5211_PHY_MODE_CCK | AR5211_PHY_MODE_RF2GHZ);
606                         OS_REG_WRITE(ah, AR_PHY_PLL_CTL, AR_PHY_PLL_CTL_44);
607                         /* Wait for the PLL to settle */
608                         OS_DELAY(DELAY_PLL_SETTLE);
609                 } else if (AH_PRIVATE(ah)->ah_devid == AR5211_DEVID) {
610                         OS_REG_WRITE(ah, AR_PHY_PLL_CTL, AR_PHY_PLL_CTL_40);
611                         OS_DELAY(DELAY_PLL_SETTLE);
612                         OS_REG_WRITE(ah, AR5211_PHY_MODE,
613                             AR5211_PHY_MODE_OFDM | (IEEE80211_IS_CHAN_2GHZ(chan) ?
614                                 AR5211_PHY_MODE_RF2GHZ :
615                                 AR5211_PHY_MODE_RF5GHZ));
616                 }
617         }
618
619         /*
620          * Reset the HW - PCI must be reset after the rest of the
621          * device has been reset
622          */
623         if (!ar5211SetResetReg(ah, AR_RC_MAC | AR_RC_BB | AR_RC_PCI))
624                 return AH_FALSE;
625         OS_DELAY(2100);    /* 8245 @ 96Mhz hangs with 2000us. */
626
627         /* Bring out of sleep mode (AGAIN) */
628         if (!ar5211SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
629                 return AH_FALSE;
630
631         /* Clear warm reset register */
632         return ar5211SetResetReg(ah, 0);
633 }
634
635 /*
636  * Recalibrate the lower PHY chips to account for temperature/environment
637  * changes.
638  */
639 HAL_BOOL
640 ar5211PerCalibrationN(struct ath_hal *ah,  struct ieee80211_channel *chan,
641         u_int chainMask, HAL_BOOL longCal, HAL_BOOL *isCalDone)
642 {
643         struct ath_hal_5211 *ahp = AH5211(ah);
644         HAL_CHANNEL_INTERNAL *ichan;
645         int32_t qCoff, qCoffDenom;
646         uint32_t data;
647         int32_t iqCorrMeas;
648         int32_t iCoff, iCoffDenom;
649         uint32_t powerMeasQ, powerMeasI;
650
651         ichan = ath_hal_checkchannel(ah, chan);
652         if (ichan == AH_NULL) {
653                 HALDEBUG(ah, HAL_DEBUG_ANY,
654                     "%s: invalid channel %u/0x%x; no mapping\n",
655                     __func__, chan->ic_freq, chan->ic_flags);
656                 return AH_FALSE;
657         }
658         /* IQ calibration in progress. Check to see if it has finished. */
659         if (ahp->ah_bIQCalibration &&
660             !(OS_REG_READ(ah, AR_PHY_TIMING_CTRL4) & AR_PHY_TIMING_CTRL4_DO_IQCAL)) {
661                 /* IQ Calibration has finished. */
662                 ahp->ah_bIQCalibration = AH_FALSE;
663
664                 /* Read calibration results. */
665                 powerMeasI = OS_REG_READ(ah, AR_PHY_IQCAL_RES_PWR_MEAS_I);
666                 powerMeasQ = OS_REG_READ(ah, AR_PHY_IQCAL_RES_PWR_MEAS_Q);
667                 iqCorrMeas = OS_REG_READ(ah, AR_PHY_IQCAL_RES_IQ_CORR_MEAS);
668
669                 /*
670                  * Prescale these values to remove 64-bit operation requirement at the loss
671                  * of a little precision.
672                  */
673                 iCoffDenom = (powerMeasI / 2 + powerMeasQ / 2) / 128;
674                 qCoffDenom = powerMeasQ / 64;
675
676                 /* Protect against divide-by-0. */
677                 if (iCoffDenom != 0 && qCoffDenom != 0) {
678                         iCoff = (-iqCorrMeas) / iCoffDenom;
679                         /* IQCORR_Q_I_COFF is a signed 6 bit number */
680                         iCoff = iCoff & 0x3f;
681
682                         qCoff = ((int32_t)powerMeasI / qCoffDenom) - 64;
683                         /* IQCORR_Q_Q_COFF is a signed 5 bit number */
684                         qCoff = qCoff & 0x1f;
685
686                         HALDEBUG(ah, HAL_DEBUG_PERCAL, "powerMeasI = 0x%08x\n",
687                             powerMeasI);
688                         HALDEBUG(ah, HAL_DEBUG_PERCAL, "powerMeasQ = 0x%08x\n",
689                             powerMeasQ);
690                         HALDEBUG(ah, HAL_DEBUG_PERCAL, "iqCorrMeas = 0x%08x\n",
691                             iqCorrMeas);
692                         HALDEBUG(ah, HAL_DEBUG_PERCAL, "iCoff     = %d\n",
693                             iCoff);
694                         HALDEBUG(ah, HAL_DEBUG_PERCAL, "qCoff     = %d\n",
695                             qCoff);
696
697                         /* Write IQ */
698                         data  = OS_REG_READ(ah, AR_PHY_TIMING_CTRL4) |
699                                 AR_PHY_TIMING_CTRL4_IQCORR_ENABLE |
700                                 (((uint32_t)iCoff) << AR_PHY_TIMING_CTRL4_IQCORR_Q_I_COFF_S) |
701                                 ((uint32_t)qCoff);
702                         OS_REG_WRITE(ah, AR_PHY_TIMING_CTRL4, data);
703                 }
704         }
705         *isCalDone = !ahp->ah_bIQCalibration;
706
707         if (longCal) {
708                 /* Perform noise floor and set status */
709                 if (!ar5211IsNfGood(ah, chan)) {
710                         /* report up and clear internal state */
711                         chan->ic_state |= IEEE80211_CHANSTATE_CWINT;
712                         return AH_FALSE;
713                 }
714                 if (!ar5211CalNoiseFloor(ah, chan)) {
715                         /*
716                          * Delay 5ms before retrying the noise floor
717                          * just to make sure, as we are in an error
718                          * condition here.
719                          */
720                         OS_DELAY(5000);
721                         if (!ar5211CalNoiseFloor(ah, chan)) {
722                                 if (!IEEE80211_IS_CHAN_CCK(chan))
723                                         chan->ic_state |= IEEE80211_CHANSTATE_CWINT;
724                                 return AH_FALSE;
725                         }
726                 }
727                 ar5211RequestRfgain(ah);
728         }
729         return AH_TRUE;
730 }
731
732 HAL_BOOL
733 ar5211PerCalibration(struct ath_hal *ah, struct ieee80211_channel *chan,
734         HAL_BOOL *isIQdone)
735 {
736         return ar5211PerCalibrationN(ah,  chan, 0x1, AH_TRUE, isIQdone);
737 }
738
739 HAL_BOOL
740 ar5211ResetCalValid(struct ath_hal *ah, const struct ieee80211_channel *chan)
741 {
742         /* XXX */
743         return AH_TRUE;
744 }
745
746 /*
747  * Writes the given reset bit mask into the reset register
748  */
749 static HAL_BOOL
750 ar5211SetResetReg(struct ath_hal *ah, uint32_t resetMask)
751 {
752         uint32_t mask = resetMask ? resetMask : ~0;
753         HAL_BOOL rt;
754
755         (void) OS_REG_READ(ah, AR_RXDP);/* flush any pending MMR writes */
756         OS_REG_WRITE(ah, AR_RC, resetMask);
757
758         /* need to wait at least 128 clocks when reseting PCI before read */
759         OS_DELAY(15);
760
761         resetMask &= AR_RC_MAC | AR_RC_BB;
762         mask &= AR_RC_MAC | AR_RC_BB;
763         rt = ath_hal_wait(ah, AR_RC, mask, resetMask);
764         if ((resetMask & AR_RC_MAC) == 0) {
765                 if (isBigEndian()) {
766                         /*
767                          * Set CFG, little-endian for register
768                          * and descriptor accesses.
769                          */
770                         mask = INIT_CONFIG_STATUS |
771                                 AR_CFG_SWTD | AR_CFG_SWRD | AR_CFG_SWRG;
772                         OS_REG_WRITE(ah, AR_CFG, LE_READ_4(&mask));
773                 } else
774                         OS_REG_WRITE(ah, AR_CFG, INIT_CONFIG_STATUS);
775         }
776         return rt;
777 }
778
779 /*
780  * Takes the MHz channel value and sets the Channel value
781  *
782  * ASSUMES: Writes enabled to analog bus before AGC is active
783  *   or by disabling the AGC.
784  */
785 static HAL_BOOL
786 ar5211SetChannel(struct ath_hal *ah, const struct ieee80211_channel *chan)
787 {
788         uint32_t refClk, reg32, data2111;
789         int16_t chan5111, chanIEEE;
790
791         chanIEEE = chan->ic_ieee;
792         if (IEEE80211_IS_CHAN_2GHZ(chan)) {
793                 const CHAN_INFO_2GHZ* ci =
794                         &chan2GHzData[chanIEEE + CI_2GHZ_INDEX_CORRECTION];
795
796                 data2111 = ((ath_hal_reverseBits(ci->channelSelect, 8) & 0xff)
797                                 << 5)
798                          | (ci->refClkSel << 4);
799                 chan5111 = ci->channel5111;
800         } else {
801                 data2111 = 0;
802                 chan5111 = chanIEEE;
803         }
804
805         /* Rest of the code is common for 5 GHz and 2.4 GHz. */
806         if (chan5111 >= 145 || (chan5111 & 0x1)) {
807                 reg32 = ath_hal_reverseBits(chan5111 - 24, 8) & 0xFF;
808                 refClk = 1;
809         } else {
810                 reg32 = ath_hal_reverseBits(((chan5111 - 24) / 2), 8) & 0xFF;
811                 refClk = 0;
812         }
813
814         reg32 = (reg32 << 2) | (refClk << 1) | (1 << 10) | 0x1;
815         OS_REG_WRITE(ah, AR_PHY(0x27), ((data2111 & 0xff) << 8) | (reg32 & 0xff));
816         reg32 >>= 8;
817         OS_REG_WRITE(ah, AR_PHY(0x34), (data2111 & 0xff00) | (reg32 & 0xff));
818
819         AH_PRIVATE(ah)->ah_curchan = chan;
820         return AH_TRUE;
821 }
822
823 static int16_t
824 ar5211GetNoiseFloor(struct ath_hal *ah)
825 {
826         int16_t nf;
827
828         nf = (OS_REG_READ(ah, AR_PHY(25)) >> 19) & 0x1ff;
829         if (nf & 0x100)
830                 nf = 0 - ((nf ^ 0x1ff) + 1);
831         return nf;
832 }
833
834 /*
835  * Peform the noisefloor calibration for the length of time set
836  * in runTime (valid values 1 to 7)
837  *
838  * Returns: The NF value at the end of the given time (or 0 for failure)
839  */
840 int16_t
841 ar5211RunNoiseFloor(struct ath_hal *ah, uint8_t runTime, int16_t startingNF)
842 {
843         int i, searchTime;
844
845         HALASSERT(runTime <= 7);
846
847         /* Setup  noise floor run time and starting value */
848         OS_REG_WRITE(ah, AR_PHY(25),
849                 (OS_REG_READ(ah, AR_PHY(25)) & ~0xFFF) |
850                          ((runTime << 9) & 0xE00) | (startingNF & 0x1FF));
851         /* Calibrate the noise floor */
852         OS_REG_WRITE(ah, AR_PHY_AGC_CONTROL,
853                 OS_REG_READ(ah, AR_PHY_AGC_CONTROL) | AR_PHY_AGC_CONTROL_NF);
854
855         /* Compute the required amount of searchTime needed to finish NF */
856         if (runTime == 0) {
857                 /* 8 search windows * 6.4us each */
858                 searchTime = 8  * 7;
859         } else {
860                 /* 512 * runtime search windows * 6.4us each */
861                 searchTime = (runTime * 512)  * 7;
862         }
863
864         /*
865          * Do not read noise floor until it has been updated
866          *
867          * As a guesstimate - we may only get 1/60th the time on
868          * the air to see search windows  in a heavily congested
869          * network (40 us every 2400 us of time)
870          */
871         for (i = 0; i < 60; i++) {
872                 if ((OS_REG_READ(ah, AR_PHY_AGC_CONTROL) & AR_PHY_AGC_CONTROL_NF) == 0)
873                         break;
874                 OS_DELAY(searchTime);
875         }
876         if (i >= 60) {
877                 HALDEBUG(ah, HAL_DEBUG_NFCAL,
878                     "NF with runTime %d failed to end on channel %d\n",
879                     runTime, AH_PRIVATE(ah)->ah_curchan->ic_freq);
880                 HALDEBUG(ah, HAL_DEBUG_NFCAL,
881                     "  PHY NF Reg state:         0x%x\n",
882                     OS_REG_READ(ah, AR_PHY_AGC_CONTROL));
883                 HALDEBUG(ah, HAL_DEBUG_NFCAL,
884                     "  PHY Active Reg state: 0x%x\n",
885                     OS_REG_READ(ah, AR_PHY_ACTIVE));
886                 return 0;
887         }
888
889         return ar5211GetNoiseFloor(ah);
890 }
891
892 static HAL_BOOL
893 getNoiseFloorThresh(struct ath_hal *ah, const struct ieee80211_channel *chan,
894         int16_t *nft)
895 {
896         HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
897
898         switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
899         case IEEE80211_CHAN_A:
900                 *nft = ee->ee_noiseFloorThresh[0];
901                 break;
902         case IEEE80211_CHAN_B:
903                 *nft = ee->ee_noiseFloorThresh[1];
904                 break;
905         case IEEE80211_CHAN_PUREG:
906                 *nft = ee->ee_noiseFloorThresh[2];
907                 break;
908         default:
909                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
910                     __func__, chan->ic_flags);
911                 return AH_FALSE;
912         }
913         return AH_TRUE;
914 }
915
916 /*
917  * Read the NF and check it against the noise floor threshhold
918  *
919  * Returns: TRUE if the NF is good
920  */
921 static HAL_BOOL
922 ar5211IsNfGood(struct ath_hal *ah, struct ieee80211_channel *chan)
923 {
924         HAL_CHANNEL_INTERNAL *ichan = ath_hal_checkchannel(ah, chan);
925         int16_t nf, nfThresh;
926
927         if (!getNoiseFloorThresh(ah, chan, &nfThresh))
928                 return AH_FALSE;
929         if (OS_REG_READ(ah, AR_PHY_AGC_CONTROL) & AR_PHY_AGC_CONTROL_NF) {
930                 HALDEBUG(ah, HAL_DEBUG_ANY,
931                     "%s: NF did not complete in calibration window\n", __func__);
932         }
933         nf = ar5211GetNoiseFloor(ah);
934         if (nf > nfThresh) {
935                 HALDEBUG(ah, HAL_DEBUG_ANY,
936                     "%s: noise floor failed; detected %u, threshold %u\n",
937                     __func__, nf, nfThresh);
938                 /*
939                  * NB: Don't discriminate 2.4 vs 5Ghz, if this
940                  *     happens it indicates a problem regardless
941                  *     of the band.
942                  */
943                 chan->ic_state |= IEEE80211_CHANSTATE_CWINT;
944         }
945         ichan->rawNoiseFloor = nf;
946         return (nf <= nfThresh);
947 }
948
949 /*
950  * Peform the noisefloor calibration and check for any constant channel
951  * interference.
952  *
953  * NOTE: preAR5211 have a lengthy carrier wave detection process - hence
954  * it is if'ed for MKK regulatory domain only.
955  *
956  * Returns: TRUE for a successful noise floor calibration; else FALSE
957  */
958 HAL_BOOL
959 ar5211CalNoiseFloor(struct ath_hal *ah, const struct ieee80211_channel *chan)
960 {
961 #define N(a)    (sizeof (a) / sizeof (a[0]))
962         /* Check for Carrier Wave interference in MKK regulatory zone */
963         if (AH_PRIVATE(ah)->ah_macVersion < AR_SREV_VERSION_OAHU &&
964             (chan->ic_flags & CHANNEL_NFCREQUIRED)) {
965                 static const uint8_t runtime[3] = { 0, 2, 7 };
966                 HAL_CHANNEL_INTERNAL *ichan = ath_hal_checkchannel(ah, chan);
967                 int16_t nf, nfThresh;
968                 int i;
969
970                 if (!getNoiseFloorThresh(ah, chan, &nfThresh))
971                         return AH_FALSE;
972                 /*
973                  * Run a quick noise floor that will hopefully
974                  * complete (decrease delay time).
975                  */
976                 for (i = 0; i < N(runtime); i++) {
977                         nf = ar5211RunNoiseFloor(ah, runtime[i], 0);
978                         if (nf > nfThresh) {
979                                 HALDEBUG(ah, HAL_DEBUG_ANY,
980                                     "%s: run failed with %u > threshold %u "
981                                     "(runtime %u)\n", __func__,
982                                     nf, nfThresh, runtime[i]);
983                                 ichan->rawNoiseFloor = 0;
984                         } else
985                                 ichan->rawNoiseFloor = nf;
986                 }
987                 return (i <= N(runtime));
988         } else {
989                 /* Calibrate the noise floor */
990                 OS_REG_WRITE(ah, AR_PHY_AGC_CONTROL,
991                         OS_REG_READ(ah, AR_PHY_AGC_CONTROL) |
992                                  AR_PHY_AGC_CONTROL_NF);
993         }
994         return AH_TRUE;
995 #undef N
996 }
997
998 /*
999  * Adjust NF based on statistical values for 5GHz frequencies.
1000  */
1001 int16_t
1002 ar5211GetNfAdjust(struct ath_hal *ah, const HAL_CHANNEL_INTERNAL *c)
1003 {
1004         static const struct {
1005                 uint16_t freqLow;
1006                 int16_t   adjust;
1007         } adjust5111[] = {
1008                 { 5790, 11 },   /* NB: ordered high -> low */
1009                 { 5730, 10 },
1010                 { 5690,  9 },
1011                 { 5660,  8 },
1012                 { 5610,  7 },
1013                 { 5530,  5 },
1014                 { 5450,  4 },
1015                 { 5379,  2 },
1016                 { 5209,  0 },   /* XXX? bogus but doesn't matter */
1017                 {    0,  1 },
1018         };
1019         int i;
1020
1021         for (i = 0; c->channel <= adjust5111[i].freqLow; i++)
1022                 ;
1023         /* NB: placeholder for 5111's less severe requirement */
1024         return adjust5111[i].adjust / 3;
1025 }
1026
1027 /*
1028  * Reads EEPROM header info from device structure and programs
1029  * analog registers 6 and 7
1030  *
1031  * REQUIRES: Access to the analog device
1032  */
1033 static HAL_BOOL
1034 ar5211SetRf6and7(struct ath_hal *ah, const struct ieee80211_channel *chan)
1035 {
1036 #define N(a)    (sizeof (a) / sizeof (a[0]))
1037         uint16_t freq = ath_hal_gethwchannel(ah, chan);
1038         HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1039         struct ath_hal_5211 *ahp = AH5211(ah);
1040         uint16_t rfXpdGain, rfPloSel, rfPwdXpd;
1041         uint16_t tempOB, tempDB;
1042         uint16_t freqIndex;
1043         int i;
1044
1045         freqIndex = IEEE80211_IS_CHAN_2GHZ(chan) ? 2 : 1;
1046
1047         /*
1048          * TODO: This array mode correspondes with the index used
1049          *       during the read.
1050          * For readability, this should be changed to an enum or #define
1051          */
1052         switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
1053         case IEEE80211_CHAN_A:
1054                 if (freq > 4000 && freq < 5260) {
1055                         tempOB = ee->ee_ob1;
1056                         tempDB = ee->ee_db1;
1057                 } else if (freq >= 5260 && freq < 5500) {
1058                         tempOB = ee->ee_ob2;
1059                         tempDB = ee->ee_db2;
1060                 } else if (freq >= 5500 && freq < 5725) {
1061                         tempOB = ee->ee_ob3;
1062                         tempDB = ee->ee_db3;
1063                 } else if (freq >= 5725) {
1064                         tempOB = ee->ee_ob4;
1065                         tempDB = ee->ee_db4;
1066                 } else {
1067                         /* XXX panic?? */
1068                         tempOB = tempDB = 0;
1069                 }
1070
1071                 rfXpdGain = ee->ee_xgain[0];
1072                 rfPloSel  = ee->ee_xpd[0];
1073                 rfPwdXpd  = !ee->ee_xpd[0];
1074
1075                 ar5211Rf6n7[5][freqIndex]  =
1076                         (ar5211Rf6n7[5][freqIndex] & ~0x10000000) |
1077                                 (ee->ee_cornerCal.pd84<< 28);
1078                 ar5211Rf6n7[6][freqIndex]  =
1079                         (ar5211Rf6n7[6][freqIndex] & ~0x04000000) |
1080                                 (ee->ee_cornerCal.pd90 << 26);
1081                 ar5211Rf6n7[21][freqIndex] =
1082                         (ar5211Rf6n7[21][freqIndex] & ~0x08) |
1083                                 (ee->ee_cornerCal.gSel << 3);
1084                 break;
1085         case IEEE80211_CHAN_B:
1086                 tempOB = ee->ee_obFor24;
1087                 tempDB = ee->ee_dbFor24;
1088                 rfXpdGain = ee->ee_xgain[1];
1089                 rfPloSel  = ee->ee_xpd[1];
1090                 rfPwdXpd  = !ee->ee_xpd[1];
1091                 break;
1092         case IEEE80211_CHAN_PUREG:
1093                 tempOB = ee->ee_obFor24g;
1094                 tempDB = ee->ee_dbFor24g;
1095                 rfXpdGain = ee->ee_xgain[2];
1096                 rfPloSel  = ee->ee_xpd[2];
1097                 rfPwdXpd  = !ee->ee_xpd[2];
1098                 break;
1099         default:
1100                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
1101                     __func__, chan->ic_flags);
1102                 return AH_FALSE;
1103         }
1104
1105         HALASSERT(1 <= tempOB && tempOB <= 5);
1106         HALASSERT(1 <= tempDB && tempDB <= 5);
1107
1108         /* Set rfXpdGain and rfPwdXpd */
1109         ar5211Rf6n7[11][freqIndex] =  (ar5211Rf6n7[11][freqIndex] & ~0xC0) |
1110                 (((ath_hal_reverseBits(rfXpdGain, 4) << 7) | (rfPwdXpd << 6)) & 0xC0);
1111         ar5211Rf6n7[12][freqIndex] =  (ar5211Rf6n7[12][freqIndex] & ~0x07) |
1112                 ((ath_hal_reverseBits(rfXpdGain, 4) >> 1) & 0x07);
1113
1114         /* Set OB */
1115         ar5211Rf6n7[12][freqIndex] =  (ar5211Rf6n7[12][freqIndex] & ~0x80) |
1116                 ((ath_hal_reverseBits(tempOB, 3) << 7) & 0x80);
1117         ar5211Rf6n7[13][freqIndex] =  (ar5211Rf6n7[13][freqIndex] & ~0x03) |
1118                 ((ath_hal_reverseBits(tempOB, 3) >> 1) & 0x03);
1119
1120         /* Set DB */
1121         ar5211Rf6n7[13][freqIndex] =  (ar5211Rf6n7[13][freqIndex] & ~0x1C) |
1122                 ((ath_hal_reverseBits(tempDB, 3) << 2) & 0x1C);
1123
1124         /* Set rfPloSel */
1125         ar5211Rf6n7[17][freqIndex] =  (ar5211Rf6n7[17][freqIndex] & ~0x08) |
1126                 ((rfPloSel << 3) & 0x08);
1127
1128         /* Write the Rf registers 6 & 7 */
1129         for (i = 0; i < N(ar5211Rf6n7); i++)
1130                 OS_REG_WRITE(ah, ar5211Rf6n7[i][0], ar5211Rf6n7[i][freqIndex]);
1131
1132         /* Now that we have reprogrammed rfgain value, clear the flag. */
1133         ahp->ah_rfgainState = RFGAIN_INACTIVE;
1134
1135         return AH_TRUE;
1136 #undef N
1137 }
1138
1139 HAL_BOOL
1140 ar5211SetAntennaSwitchInternal(struct ath_hal *ah, HAL_ANT_SETTING settings,
1141         const struct ieee80211_channel *chan)
1142 {
1143 #define ANT_SWITCH_TABLE1       0x9960
1144 #define ANT_SWITCH_TABLE2       0x9964
1145         HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1146         struct ath_hal_5211 *ahp = AH5211(ah);
1147         uint32_t antSwitchA, antSwitchB;
1148         int ix;
1149
1150         switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
1151         case IEEE80211_CHAN_A:          ix = 0; break;
1152         case IEEE80211_CHAN_B:          ix = 1; break;
1153         case IEEE80211_CHAN_PUREG:      ix = 2; break;
1154         default:
1155                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
1156                     __func__, chan->ic_flags);
1157                 return AH_FALSE;
1158         }
1159
1160         antSwitchA =  ee->ee_antennaControl[1][ix]
1161                    | (ee->ee_antennaControl[2][ix] << 6)
1162                    | (ee->ee_antennaControl[3][ix] << 12) 
1163                    | (ee->ee_antennaControl[4][ix] << 18)
1164                    | (ee->ee_antennaControl[5][ix] << 24)
1165                    ;
1166         antSwitchB =  ee->ee_antennaControl[6][ix]
1167                    | (ee->ee_antennaControl[7][ix] << 6)
1168                    | (ee->ee_antennaControl[8][ix] << 12)
1169                    | (ee->ee_antennaControl[9][ix] << 18)
1170                    | (ee->ee_antennaControl[10][ix] << 24)
1171                    ;
1172         /*
1173          * For fixed antenna, give the same setting for both switch banks
1174          */
1175         switch (settings) {
1176         case HAL_ANT_FIXED_A:
1177                 antSwitchB = antSwitchA;
1178                 break;
1179         case HAL_ANT_FIXED_B:
1180                 antSwitchA = antSwitchB;
1181                 break;
1182         case HAL_ANT_VARIABLE:
1183                 break;
1184         default:
1185                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: bad antenna setting %u\n",
1186                     __func__, settings);
1187                 return AH_FALSE;
1188         }
1189         ahp->ah_diversityControl = settings;
1190
1191         OS_REG_WRITE(ah, ANT_SWITCH_TABLE1, antSwitchA);
1192         OS_REG_WRITE(ah, ANT_SWITCH_TABLE2, antSwitchB);
1193
1194         return AH_TRUE;
1195 #undef ANT_SWITCH_TABLE1
1196 #undef ANT_SWITCH_TABLE2
1197 }
1198
1199 /*
1200  * Reads EEPROM header info and programs the device for correct operation
1201  * given the channel value
1202  */
1203 static HAL_BOOL
1204 ar5211SetBoardValues(struct ath_hal *ah, const struct ieee80211_channel *chan)
1205 {
1206         HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1207         struct ath_hal_5211 *ahp = AH5211(ah);
1208         int arrayMode, falseDectectBackoff;
1209
1210         switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
1211         case IEEE80211_CHAN_A:
1212                 arrayMode = 0;
1213                 OS_REG_RMW_FIELD(ah, AR_PHY_FRAME_CTL,
1214                         AR_PHY_FRAME_CTL_TX_CLIP, ee->ee_cornerCal.clip);
1215                 break;
1216         case IEEE80211_CHAN_B:
1217                 arrayMode = 1;
1218                 break;
1219         case IEEE80211_CHAN_PUREG:
1220                 arrayMode = 2;
1221                 break;
1222         default:
1223                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
1224                     __func__, chan->ic_flags);
1225                 return AH_FALSE;
1226         }
1227
1228         /* Set the antenna register(s) correctly for the chip revision */
1229         if (AH_PRIVATE(ah)->ah_macVersion < AR_SREV_VERSION_OAHU) {
1230                 OS_REG_WRITE(ah, AR_PHY(68),
1231                         (OS_REG_READ(ah, AR_PHY(68)) & 0xFFFFFFFC) | 0x3);
1232         } else {
1233                 OS_REG_WRITE(ah, AR_PHY(68),
1234                         (OS_REG_READ(ah, AR_PHY(68)) & 0xFFFFFC06) |
1235                         (ee->ee_antennaControl[0][arrayMode] << 4) | 0x1);
1236
1237                 ar5211SetAntennaSwitchInternal(ah,
1238                         ahp->ah_diversityControl, chan);
1239
1240                 /* Set the Noise Floor Thresh on ar5211 devices */
1241                 OS_REG_WRITE(ah, AR_PHY_BASE + (90 << 2),
1242                         (ee->ee_noiseFloorThresh[arrayMode] & 0x1FF) | (1<<9));
1243         }
1244         OS_REG_WRITE(ah, AR_PHY_BASE + (17 << 2),
1245                 (OS_REG_READ(ah, AR_PHY_BASE + (17 << 2)) & 0xFFFFC07F) |
1246                 ((ee->ee_switchSettling[arrayMode] << 7) & 0x3F80));
1247         OS_REG_WRITE(ah, AR_PHY_BASE + (18 << 2),
1248                 (OS_REG_READ(ah, AR_PHY_BASE + (18 << 2)) & 0xFFFC0FFF) |
1249                 ((ee->ee_txrxAtten[arrayMode] << 12) & 0x3F000));
1250         OS_REG_WRITE(ah, AR_PHY_BASE + (20 << 2),
1251                 (OS_REG_READ(ah, AR_PHY_BASE + (20 << 2)) & 0xFFFF0000) |
1252                 ((ee->ee_pgaDesiredSize[arrayMode] << 8) & 0xFF00) |
1253                 (ee->ee_adcDesiredSize[arrayMode] & 0x00FF));
1254         OS_REG_WRITE(ah, AR_PHY_BASE + (13 << 2),
1255                 (ee->ee_txEndToXPAOff[arrayMode] << 24) |
1256                 (ee->ee_txEndToXPAOff[arrayMode] << 16) |
1257                 (ee->ee_txFrameToXPAOn[arrayMode] << 8) |
1258                 ee->ee_txFrameToXPAOn[arrayMode]);
1259         OS_REG_WRITE(ah, AR_PHY_BASE + (10 << 2),
1260                 (OS_REG_READ(ah, AR_PHY_BASE + (10 << 2)) & 0xFFFF00FF) |
1261                 (ee->ee_txEndToXLNAOn[arrayMode] << 8));
1262         OS_REG_WRITE(ah, AR_PHY_BASE + (25 << 2),
1263                 (OS_REG_READ(ah, AR_PHY_BASE + (25 << 2)) & 0xFFF80FFF) |
1264                 ((ee->ee_thresh62[arrayMode] << 12) & 0x7F000));
1265
1266 #define NO_FALSE_DETECT_BACKOFF   2
1267 #define CB22_FALSE_DETECT_BACKOFF 6
1268         /*
1269          * False detect backoff - suspected 32 MHz spur causes
1270          * false detects in OFDM, causing Tx Hangs.  Decrease
1271          * weak signal sensitivity for this card.
1272          */
1273         falseDectectBackoff = NO_FALSE_DETECT_BACKOFF;
1274         if (AH_PRIVATE(ah)->ah_eeversion < AR_EEPROM_VER3_3) {
1275                 if (AH_PRIVATE(ah)->ah_subvendorid == 0x1022 &&
1276                     IEEE80211_IS_CHAN_OFDM(chan))
1277                         falseDectectBackoff += CB22_FALSE_DETECT_BACKOFF;
1278         } else {
1279                 uint16_t freq = ath_hal_gethwchannel(ah, chan);
1280                 uint32_t remainder = freq % 32;
1281
1282                 if (remainder && (remainder < 10 || remainder > 22))
1283                         falseDectectBackoff += ee->ee_falseDetectBackoff[arrayMode];
1284         }
1285         OS_REG_WRITE(ah, 0x9924,
1286                 (OS_REG_READ(ah, 0x9924) & 0xFFFFFF01)
1287                 | ((falseDectectBackoff << 1) & 0xF7));
1288
1289         return AH_TRUE;
1290 #undef NO_FALSE_DETECT_BACKOFF
1291 #undef CB22_FALSE_DETECT_BACKOFF
1292 }
1293
1294 /*
1295  * Set the limit on the overall output power.  Used for dynamic
1296  * transmit power control and the like.
1297  *
1298  * NOTE: The power is passed in is in units of 0.5 dBm.
1299  */
1300 HAL_BOOL
1301 ar5211SetTxPowerLimit(struct ath_hal *ah, uint32_t limit)
1302 {
1303
1304         AH_PRIVATE(ah)->ah_powerLimit = AH_MIN(limit, MAX_RATE_POWER);
1305         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE_MAX, limit);
1306         return AH_TRUE;
1307 }
1308
1309 /*
1310  * Sets the transmit power in the baseband for the given
1311  * operating channel and mode.
1312  */
1313 static HAL_BOOL
1314 ar5211SetTransmitPower(struct ath_hal *ah, const struct ieee80211_channel *chan)
1315 {
1316         uint16_t freq = ath_hal_gethwchannel(ah, chan);
1317         HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1318         TRGT_POWER_INFO *pi;
1319         RD_EDGES_POWER *rep;
1320         PCDACS_EEPROM eepromPcdacs;
1321         u_int nchan, cfgCtl;
1322         int i;
1323
1324         /* setup the pcdac struct to point to the correct info, based on mode */
1325         switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
1326         case IEEE80211_CHAN_A:
1327                 eepromPcdacs.numChannels = ee->ee_numChannels11a;
1328                 eepromPcdacs.pChannelList= ee->ee_channels11a;
1329                 eepromPcdacs.pDataPerChannel = ee->ee_dataPerChannel11a;
1330                 nchan = ee->ee_numTargetPwr_11a;
1331                 pi = ee->ee_trgtPwr_11a;
1332                 break;
1333         case IEEE80211_CHAN_PUREG:
1334                 eepromPcdacs.numChannels = ee->ee_numChannels2_4;
1335                 eepromPcdacs.pChannelList= ee->ee_channels11g;
1336                 eepromPcdacs.pDataPerChannel = ee->ee_dataPerChannel11g;
1337                 nchan = ee->ee_numTargetPwr_11g;
1338                 pi = ee->ee_trgtPwr_11g;
1339                 break;
1340         case IEEE80211_CHAN_B:
1341                 eepromPcdacs.numChannels = ee->ee_numChannels2_4;
1342                 eepromPcdacs.pChannelList= ee->ee_channels11b;
1343                 eepromPcdacs.pDataPerChannel = ee->ee_dataPerChannel11b;
1344                 nchan = ee->ee_numTargetPwr_11b;
1345                 pi = ee->ee_trgtPwr_11b;
1346                 break;
1347         default:
1348                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
1349                     __func__, chan->ic_flags);
1350                 return AH_FALSE;
1351         }
1352
1353         ar5211SetPowerTable(ah, &eepromPcdacs, freq);
1354
1355         rep = AH_NULL;
1356         /* Match CTL to EEPROM value */
1357         cfgCtl = ath_hal_getctl(ah, chan);
1358         for (i = 0; i < ee->ee_numCtls; i++)
1359                 if (ee->ee_ctl[i] != 0 && ee->ee_ctl[i] == cfgCtl) {
1360                         rep = &ee->ee_rdEdgesPower[i * NUM_EDGES];
1361                         break;
1362                 }
1363         ar5211SetRateTable(ah, rep, pi, nchan, chan);
1364
1365         return AH_TRUE;
1366 }
1367
1368 /*
1369  * Read the transmit power levels from the structures taken
1370  * from EEPROM. Interpolate read transmit power values for
1371  * this channel. Organize the transmit power values into a
1372  * table for writing into the hardware.
1373  */
1374 void
1375 ar5211SetPowerTable(struct ath_hal *ah, PCDACS_EEPROM *pSrcStruct,
1376         uint16_t channel)
1377 {
1378         static FULL_PCDAC_STRUCT pcdacStruct;
1379         static uint16_t pcdacTable[PWR_TABLE_SIZE];
1380
1381         uint16_t         i, j;
1382         uint16_t         *pPcdacValues;
1383         int16_t   *pScaledUpDbm;
1384         int16_t   minScaledPwr;
1385         int16_t   maxScaledPwr;
1386         int16_t   pwr;
1387         uint16_t         pcdacMin = 0;
1388         uint16_t         pcdacMax = 63;
1389         uint16_t         pcdacTableIndex;
1390         uint16_t         scaledPcdac;
1391         uint32_t         addr;
1392         uint32_t         temp32;
1393
1394         OS_MEMZERO(&pcdacStruct, sizeof(FULL_PCDAC_STRUCT));
1395         OS_MEMZERO(pcdacTable, sizeof(uint16_t) * PWR_TABLE_SIZE);
1396         pPcdacValues = pcdacStruct.PcdacValues;
1397         pScaledUpDbm = pcdacStruct.PwrValues;
1398
1399         /* Initialize the pcdacs to dBM structs pcdacs to be 1 to 63 */
1400         for (i = PCDAC_START, j = 0; i <= PCDAC_STOP; i+= PCDAC_STEP, j++)
1401                 pPcdacValues[j] = i;
1402
1403         pcdacStruct.numPcdacValues = j;
1404         pcdacStruct.pcdacMin = PCDAC_START;
1405         pcdacStruct.pcdacMax = PCDAC_STOP;
1406
1407         /* Fill out the power values for this channel */
1408         for (j = 0; j < pcdacStruct.numPcdacValues; j++ )
1409                 pScaledUpDbm[j] = ar5211GetScaledPower(channel, pPcdacValues[j], pSrcStruct);
1410
1411         /* Now scale the pcdac values to fit in the 64 entry power table */
1412         minScaledPwr = pScaledUpDbm[0];
1413         maxScaledPwr = pScaledUpDbm[pcdacStruct.numPcdacValues - 1];
1414
1415         /* find minimum and make monotonic */
1416         for (j = 0; j < pcdacStruct.numPcdacValues; j++) {
1417                 if (minScaledPwr >= pScaledUpDbm[j]) {
1418                         minScaledPwr = pScaledUpDbm[j];
1419                         pcdacMin = j;
1420                 }
1421                 /*
1422                  * Make the full_hsh monotonically increasing otherwise
1423                  * interpolation algorithm will get fooled gotta start
1424                  * working from the top, hence i = 63 - j.
1425                  */
1426                 i = (uint16_t)(pcdacStruct.numPcdacValues - 1 - j);
1427                 if (i == 0)
1428                         break;
1429                 if (pScaledUpDbm[i-1] > pScaledUpDbm[i]) {
1430                         /*
1431                          * It could be a glitch, so make the power for
1432                          * this pcdac the same as the power from the
1433                          * next highest pcdac.
1434                          */
1435                         pScaledUpDbm[i - 1] = pScaledUpDbm[i];
1436                 }
1437         }
1438
1439         for (j = 0; j < pcdacStruct.numPcdacValues; j++)
1440                 if (maxScaledPwr < pScaledUpDbm[j]) {
1441                         maxScaledPwr = pScaledUpDbm[j];
1442                         pcdacMax = j;
1443                 }
1444
1445         /* Find the first power level with a pcdac */
1446         pwr = (uint16_t)(PWR_STEP * ((minScaledPwr - PWR_MIN + PWR_STEP / 2) / PWR_STEP)  + PWR_MIN);
1447
1448         /* Write all the first pcdac entries based off the pcdacMin */
1449         pcdacTableIndex = 0;
1450         for (i = 0; i < (2 * (pwr - PWR_MIN) / EEP_SCALE + 1); i++)
1451                 pcdacTable[pcdacTableIndex++] = pcdacMin;
1452
1453         i = 0;
1454         while (pwr < pScaledUpDbm[pcdacStruct.numPcdacValues - 1]) {
1455                 pwr += PWR_STEP;
1456                 /* stop if dbM > max_power_possible */
1457                 while (pwr < pScaledUpDbm[pcdacStruct.numPcdacValues - 1] &&
1458                        (pwr - pScaledUpDbm[i])*(pwr - pScaledUpDbm[i+1]) > 0)
1459                         i++;
1460                 /* scale by 2 and add 1 to enable round up or down as needed */
1461                 scaledPcdac = (uint16_t)(ar5211GetInterpolatedValue(pwr,
1462                                 pScaledUpDbm[i], pScaledUpDbm[i+1],
1463                                 (uint16_t)(pPcdacValues[i] * 2),
1464                                 (uint16_t)(pPcdacValues[i+1] * 2), 0) + 1);
1465
1466                 pcdacTable[pcdacTableIndex] = scaledPcdac / 2;
1467                 if (pcdacTable[pcdacTableIndex] > pcdacMax)
1468                         pcdacTable[pcdacTableIndex] = pcdacMax;
1469                 pcdacTableIndex++;
1470         }
1471
1472         /* Write all the last pcdac entries based off the last valid pcdac */
1473         while (pcdacTableIndex < PWR_TABLE_SIZE) {
1474                 pcdacTable[pcdacTableIndex] = pcdacTable[pcdacTableIndex - 1];
1475                 pcdacTableIndex++;
1476         }
1477
1478         /* Finally, write the power values into the baseband power table */
1479         addr = AR_PHY_BASE + (608 << 2);
1480         for (i = 0; i < 32; i++) {
1481                 temp32 = 0xffff & ((pcdacTable[2 * i + 1] << 8) | 0xff);
1482                 temp32 = (temp32 << 16) | (0xffff & ((pcdacTable[2 * i] << 8) | 0xff));
1483                 OS_REG_WRITE(ah, addr, temp32);
1484                 addr += 4;
1485         }
1486
1487 }
1488
1489 /*
1490  * Set the transmit power in the baseband for the given
1491  * operating channel and mode.
1492  */
1493 static void
1494 ar5211SetRateTable(struct ath_hal *ah, RD_EDGES_POWER *pRdEdgesPower,
1495         TRGT_POWER_INFO *pPowerInfo, uint16_t numChannels,
1496         const struct ieee80211_channel *chan)
1497 {
1498         uint16_t freq = ath_hal_gethwchannel(ah, chan);
1499         HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1500         struct ath_hal_5211 *ahp = AH5211(ah);
1501         static uint16_t ratesArray[NUM_RATES];
1502         static const uint16_t tpcScaleReductionTable[5] =
1503                 { 0, 3, 6, 9, MAX_RATE_POWER };
1504
1505         uint16_t        *pRatesPower;
1506         uint16_t        lowerChannel, lowerIndex=0, lowerPower=0;
1507         uint16_t        upperChannel, upperIndex=0, upperPower=0;
1508         uint16_t        twiceMaxEdgePower=63;
1509         uint16_t        twicePower = 0;
1510         uint16_t        i, numEdges;
1511         uint16_t        tempChannelList[NUM_EDGES]; /* temp array for holding edge channels */
1512         uint16_t        twiceMaxRDPower;
1513         int16_t  scaledPower = 0;               /* for gcc -O2 */
1514         uint16_t        mask = 0x3f;
1515         HAL_BOOL          paPreDEnable = 0;
1516         int8_t    twiceAntennaGain, twiceAntennaReduction = 0;
1517
1518         pRatesPower = ratesArray;
1519         twiceMaxRDPower = chan->ic_maxregpower * 2;
1520
1521         if (IEEE80211_IS_CHAN_5GHZ(chan)) {
1522                 twiceAntennaGain = ee->ee_antennaGainMax[0];
1523         } else {
1524                 twiceAntennaGain = ee->ee_antennaGainMax[1];
1525         }
1526
1527         twiceAntennaReduction = ath_hal_getantennareduction(ah, chan, twiceAntennaGain);
1528
1529         if (pRdEdgesPower) {
1530                 /* Get the edge power */
1531                 for (i = 0; i < NUM_EDGES; i++) {
1532                         if (pRdEdgesPower[i].rdEdge == 0)
1533                                 break;
1534                         tempChannelList[i] = pRdEdgesPower[i].rdEdge;
1535                 }
1536                 numEdges = i;
1537
1538                 ar5211GetLowerUpperValues(freq, tempChannelList,
1539                         numEdges, &lowerChannel, &upperChannel);
1540                 /* Get the index for this channel */
1541                 for (i = 0; i < numEdges; i++)
1542                         if (lowerChannel == tempChannelList[i])
1543                                 break;
1544                 HALASSERT(i != numEdges);
1545
1546                 if ((lowerChannel == upperChannel &&
1547                      lowerChannel == freq) ||
1548                     pRdEdgesPower[i].flag) {
1549                         twiceMaxEdgePower = pRdEdgesPower[i].twice_rdEdgePower;
1550                         HALASSERT(twiceMaxEdgePower > 0);
1551                 }
1552         }
1553
1554         /* extrapolate the power values for the test Groups */
1555         for (i = 0; i < numChannels; i++)
1556                 tempChannelList[i] = pPowerInfo[i].testChannel;
1557
1558         ar5211GetLowerUpperValues(freq, tempChannelList,
1559                 numChannels, &lowerChannel, &upperChannel);
1560
1561         /* get the index for the channel */
1562         for (i = 0; i < numChannels; i++) {
1563                 if (lowerChannel == tempChannelList[i])
1564                         lowerIndex = i;
1565                 if (upperChannel == tempChannelList[i]) {
1566                         upperIndex = i;
1567                         break;
1568                 }
1569         }
1570
1571         for (i = 0; i < NUM_RATES; i++) {
1572                 if (IEEE80211_IS_CHAN_OFDM(chan)) {
1573                         /* power for rates 6,9,12,18,24 is all the same */
1574                         if (i < 5) {
1575                                 lowerPower = pPowerInfo[lowerIndex].twicePwr6_24;
1576                                 upperPower = pPowerInfo[upperIndex].twicePwr6_24;
1577                         } else if (i == 5) {
1578                                 lowerPower = pPowerInfo[lowerIndex].twicePwr36;
1579                                 upperPower = pPowerInfo[upperIndex].twicePwr36;
1580                         } else if (i == 6) {
1581                                 lowerPower = pPowerInfo[lowerIndex].twicePwr48;
1582                                 upperPower = pPowerInfo[upperIndex].twicePwr48;
1583                         } else if (i == 7) {
1584                                 lowerPower = pPowerInfo[lowerIndex].twicePwr54;
1585                                 upperPower = pPowerInfo[upperIndex].twicePwr54;
1586                         }
1587                 } else {
1588                         switch (i) {
1589                         case 0:
1590                         case 1:
1591                                 lowerPower = pPowerInfo[lowerIndex].twicePwr6_24;
1592                                 upperPower = pPowerInfo[upperIndex].twicePwr6_24;
1593                                 break;
1594                         case 2:
1595                         case 3:
1596                                 lowerPower = pPowerInfo[lowerIndex].twicePwr36;
1597                                 upperPower = pPowerInfo[upperIndex].twicePwr36;
1598                                 break;
1599                         case 4:
1600                         case 5:
1601                                 lowerPower = pPowerInfo[lowerIndex].twicePwr48;
1602                                 upperPower = pPowerInfo[upperIndex].twicePwr48;
1603                                 break;
1604                         case 6:
1605                         case 7:
1606                                 lowerPower = pPowerInfo[lowerIndex].twicePwr54;
1607                                 upperPower = pPowerInfo[upperIndex].twicePwr54;
1608                                 break;
1609                         }
1610                 }
1611
1612                 twicePower = ar5211GetInterpolatedValue(freq,
1613                         lowerChannel, upperChannel, lowerPower, upperPower, 0);
1614
1615                 /* Reduce power by band edge restrictions */
1616                 twicePower = AH_MIN(twicePower, twiceMaxEdgePower);
1617
1618                 /*
1619                  * If turbo is set, reduce power to keep power
1620                  * consumption under 2 Watts.  Note that we always do
1621                  * this unless specially configured.  Then we limit
1622                  * power only for non-AP operation.
1623                  */
1624                 if (IEEE80211_IS_CHAN_TURBO(chan) &&
1625                     AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER3_1
1626 #ifdef AH_ENABLE_AP_SUPPORT
1627                     && AH_PRIVATE(ah)->ah_opmode != HAL_M_HOSTAP
1628 #endif
1629                 ) {
1630                         twicePower = AH_MIN(twicePower, ee->ee_turbo2WMaxPower5);
1631                 }
1632
1633                 /* Reduce power by max regulatory domain allowed restrictions */
1634                 pRatesPower[i] = AH_MIN(twicePower, twiceMaxRDPower - twiceAntennaReduction);
1635
1636                 /* Use 6 Mb power level for transmit power scaling reduction */
1637                 /* We don't want to reduce higher rates if its not needed */
1638                 if (i == 0) {
1639                         scaledPower = pRatesPower[0] -
1640                                 (tpcScaleReductionTable[AH_PRIVATE(ah)->ah_tpScale] * 2);
1641                         if (scaledPower < 1)
1642                                 scaledPower = 1;
1643                 }
1644
1645                 pRatesPower[i] = AH_MIN(pRatesPower[i], scaledPower);
1646         }
1647
1648         /* Record txPower at Rate 6 for info gathering */
1649         ahp->ah_tx6PowerInHalfDbm = pRatesPower[0];
1650
1651 #ifdef AH_DEBUG
1652         HALDEBUG(ah, HAL_DEBUG_RESET,
1653             "%s: final output power setting %d MHz:\n",
1654             __func__, chan->ic_freq);
1655         HALDEBUG(ah, HAL_DEBUG_RESET,
1656             "6 Mb %d dBm, MaxRD: %d dBm, MaxEdge %d dBm\n",
1657             scaledPower / 2, twiceMaxRDPower / 2, twiceMaxEdgePower / 2);
1658         HALDEBUG(ah, HAL_DEBUG_RESET, "TPC Scale %d dBm - Ant Red %d dBm\n",
1659             tpcScaleReductionTable[AH_PRIVATE(ah)->ah_tpScale] * 2,
1660             twiceAntennaReduction / 2);
1661         if (IEEE80211_IS_CHAN_TURBO(chan) &&
1662             AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER3_1)
1663                 HALDEBUG(ah, HAL_DEBUG_RESET, "Max Turbo %d dBm\n",
1664                     ee->ee_turbo2WMaxPower5);
1665         HALDEBUG(ah, HAL_DEBUG_RESET,
1666             "  %2d | %2d | %2d | %2d | %2d | %2d | %2d | %2d dBm\n",
1667             pRatesPower[0] / 2, pRatesPower[1] / 2, pRatesPower[2] / 2,
1668             pRatesPower[3] / 2, pRatesPower[4] / 2, pRatesPower[5] / 2,
1669             pRatesPower[6] / 2, pRatesPower[7] / 2);
1670 #endif /* AH_DEBUG */
1671
1672         /* Write the power table into the hardware */
1673         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE1,
1674                  ((paPreDEnable & 1)<< 30) | ((pRatesPower[3] & mask) << 24) |
1675                  ((paPreDEnable & 1)<< 22) | ((pRatesPower[2] & mask) << 16) |
1676                  ((paPreDEnable & 1)<< 14) | ((pRatesPower[1] & mask) << 8) |
1677                  ((paPreDEnable & 1)<< 6 ) |  (pRatesPower[0] & mask));
1678         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE2,
1679                  ((paPreDEnable & 1)<< 30) | ((pRatesPower[7] & mask) << 24) |
1680                  ((paPreDEnable & 1)<< 22) | ((pRatesPower[6] & mask) << 16) |
1681                  ((paPreDEnable & 1)<< 14) | ((pRatesPower[5] & mask) << 8) |
1682                  ((paPreDEnable & 1)<< 6 ) |  (pRatesPower[4] & mask));
1683
1684         /* set max power to the power value at rate 6 */
1685         ar5211SetTxPowerLimit(ah, pRatesPower[0]);
1686
1687         AH_PRIVATE(ah)->ah_maxPowerLevel = pRatesPower[0];
1688 }
1689
1690 /*
1691  * Get or interpolate the pcdac value from the calibrated data
1692  */
1693 uint16_t
1694 ar5211GetScaledPower(uint16_t channel, uint16_t pcdacValue,
1695         const PCDACS_EEPROM *pSrcStruct)
1696 {
1697         uint16_t powerValue;
1698         uint16_t lFreq, rFreq;          /* left and right frequency values */
1699         uint16_t llPcdac, ulPcdac;      /* lower and upper left pcdac values */
1700         uint16_t lrPcdac, urPcdac;      /* lower and upper right pcdac values */
1701         uint16_t lPwr, uPwr;            /* lower and upper temp pwr values */
1702         uint16_t lScaledPwr, rScaledPwr; /* left and right scaled power */
1703
1704         if (ar5211FindValueInList(channel, pcdacValue, pSrcStruct, &powerValue))
1705                 /* value was copied from srcStruct */
1706                 return powerValue;
1707
1708         ar5211GetLowerUpperValues(channel, pSrcStruct->pChannelList,
1709                 pSrcStruct->numChannels, &lFreq, &rFreq);
1710         ar5211GetLowerUpperPcdacs(pcdacValue, lFreq, pSrcStruct,
1711                 &llPcdac, &ulPcdac);
1712         ar5211GetLowerUpperPcdacs(pcdacValue, rFreq, pSrcStruct,
1713                 &lrPcdac, &urPcdac);
1714
1715         /* get the power index for the pcdac value */
1716         ar5211FindValueInList(lFreq, llPcdac, pSrcStruct, &lPwr);
1717         ar5211FindValueInList(lFreq, ulPcdac, pSrcStruct, &uPwr);
1718         lScaledPwr = ar5211GetInterpolatedValue(pcdacValue,
1719                                 llPcdac, ulPcdac, lPwr, uPwr, 0);
1720
1721         ar5211FindValueInList(rFreq, lrPcdac, pSrcStruct, &lPwr);
1722         ar5211FindValueInList(rFreq, urPcdac, pSrcStruct, &uPwr);
1723         rScaledPwr = ar5211GetInterpolatedValue(pcdacValue,
1724                                 lrPcdac, urPcdac, lPwr, uPwr, 0);
1725
1726         return ar5211GetInterpolatedValue(channel, lFreq, rFreq,
1727                 lScaledPwr, rScaledPwr, 0);
1728 }
1729
1730 /*
1731  * Find the value from the calibrated source data struct
1732  */
1733 HAL_BOOL
1734 ar5211FindValueInList(uint16_t channel, uint16_t pcdacValue,
1735         const PCDACS_EEPROM *pSrcStruct, uint16_t *powerValue)
1736 {
1737         const DATA_PER_CHANNEL *pChannelData;
1738         const uint16_t *pPcdac;
1739         uint16_t i, j;
1740
1741         pChannelData = pSrcStruct->pDataPerChannel;
1742         for (i = 0; i < pSrcStruct->numChannels; i++ ) {
1743                 if (pChannelData->channelValue == channel) {
1744                         pPcdac = pChannelData->PcdacValues;
1745                         for (j = 0; j < pChannelData->numPcdacValues; j++ ) {
1746                                 if (*pPcdac == pcdacValue) {
1747                                         *powerValue = pChannelData->PwrValues[j];
1748                                         return AH_TRUE;
1749                                 }
1750                                 pPcdac++;
1751                         }
1752                 }
1753                 pChannelData++;
1754         }
1755         return AH_FALSE;
1756 }
1757
1758 /*
1759  * Returns interpolated or the scaled up interpolated value
1760  */
1761 uint16_t
1762 ar5211GetInterpolatedValue(uint16_t target,
1763         uint16_t srcLeft, uint16_t srcRight,
1764         uint16_t targetLeft, uint16_t targetRight,
1765         HAL_BOOL scaleUp)
1766 {
1767         uint16_t rv;
1768         int16_t lRatio;
1769         uint16_t scaleValue = EEP_SCALE;
1770
1771         /* to get an accurate ratio, always scale, if want to scale, then don't scale back down */
1772         if ((targetLeft * targetRight) == 0)
1773                 return 0;
1774         if (scaleUp)
1775                 scaleValue = 1;
1776
1777         if (srcRight != srcLeft) {
1778                 /*
1779                  * Note the ratio always need to be scaled,
1780                  * since it will be a fraction.
1781                  */
1782                 lRatio = (target - srcLeft) * EEP_SCALE / (srcRight - srcLeft);
1783                 if (lRatio < 0) {
1784                     /* Return as Left target if value would be negative */
1785                     rv = targetLeft * (scaleUp ? EEP_SCALE : 1);
1786                 } else if (lRatio > EEP_SCALE) {
1787                     /* Return as Right target if Ratio is greater than 100% (SCALE) */
1788                     rv = targetRight * (scaleUp ? EEP_SCALE : 1);
1789                 } else {
1790                         rv = (lRatio * targetRight + (EEP_SCALE - lRatio) *
1791                                         targetLeft) / scaleValue;
1792                 }
1793         } else {
1794                 rv = targetLeft;
1795                 if (scaleUp)
1796                         rv *= EEP_SCALE;
1797         }
1798         return rv;
1799 }
1800
1801 /*
1802  *  Look for value being within 0.1 of the search values
1803  *  however, NDIS can't do float calculations, so multiply everything
1804  *  up by EEP_SCALE so can do integer arithmatic
1805  *
1806  * INPUT  value    -value to search for
1807  * INPUT  pList    -ptr to the list to search
1808  * INPUT  listSize      -number of entries in list
1809  * OUTPUT pLowerValue -return the lower value
1810  * OUTPUT pUpperValue -return the upper value
1811  */
1812 void
1813 ar5211GetLowerUpperValues(uint16_t value,
1814         const uint16_t *pList, uint16_t listSize,
1815         uint16_t *pLowerValue, uint16_t *pUpperValue)
1816 {
1817         const uint16_t listEndValue = *(pList + listSize - 1);
1818         uint32_t target = value * EEP_SCALE;
1819         int i;
1820
1821         /*
1822          * See if value is lower than the first value in the list
1823          * if so return first value
1824          */
1825         if (target < (uint32_t)(*pList * EEP_SCALE - EEP_DELTA)) {
1826                 *pLowerValue = *pList;
1827                 *pUpperValue = *pList;
1828                 return;
1829         }
1830
1831         /*
1832          * See if value is greater than last value in list
1833          * if so return last value
1834          */
1835         if (target > (uint32_t)(listEndValue * EEP_SCALE + EEP_DELTA)) {
1836                 *pLowerValue = listEndValue;
1837                 *pUpperValue = listEndValue;
1838                 return;
1839         }
1840
1841         /* look for value being near or between 2 values in list */
1842         for (i = 0; i < listSize; i++) {
1843                 /*
1844                  * If value is close to the current value of the list
1845                  * then target is not between values, it is one of the values
1846                  */
1847                 if (abs(pList[i] * EEP_SCALE - (int32_t) target) < EEP_DELTA) {
1848                         *pLowerValue = pList[i];
1849                         *pUpperValue = pList[i];
1850                         return;
1851                 }
1852
1853                 /*
1854                  * Look for value being between current value and next value
1855                  * if so return these 2 values
1856                  */
1857                 if (target < (uint32_t)(pList[i + 1] * EEP_SCALE - EEP_DELTA)) {
1858                         *pLowerValue = pList[i];
1859                         *pUpperValue = pList[i + 1];
1860                         return;
1861                 }
1862         }
1863 }
1864
1865 /*
1866  * Get the upper and lower pcdac given the channel and the pcdac
1867  * used in the search
1868  */
1869 void
1870 ar5211GetLowerUpperPcdacs(uint16_t pcdac, uint16_t channel,
1871         const PCDACS_EEPROM *pSrcStruct,
1872         uint16_t *pLowerPcdac, uint16_t *pUpperPcdac)
1873 {
1874         const DATA_PER_CHANNEL *pChannelData;
1875         int i;
1876
1877         /* Find the channel information */
1878         pChannelData = pSrcStruct->pDataPerChannel;
1879         for (i = 0; i < pSrcStruct->numChannels; i++) {
1880                 if (pChannelData->channelValue == channel)
1881                         break;
1882                 pChannelData++;
1883         }
1884         ar5211GetLowerUpperValues(pcdac, pChannelData->PcdacValues,
1885                 pChannelData->numPcdacValues, pLowerPcdac, pUpperPcdac);
1886 }
1887
1888 #define DYN_ADJ_UP_MARGIN       15
1889 #define DYN_ADJ_LO_MARGIN       20
1890
1891 static const GAIN_OPTIMIZATION_LADDER gainLadder = {
1892         9,                                      /* numStepsInLadder */
1893         4,                                      /* defaultStepNum */
1894         { { {4, 1, 1, 1},  6, "FG8"},
1895           { {4, 0, 1, 1},  4, "FG7"},
1896           { {3, 1, 1, 1},  3, "FG6"},
1897           { {4, 0, 0, 1},  1, "FG5"},
1898           { {4, 1, 1, 0},  0, "FG4"},   /* noJack */
1899           { {4, 0, 1, 0}, -2, "FG3"},   /* halfJack */
1900           { {3, 1, 1, 0}, -3, "FG2"},   /* clip3 */
1901           { {4, 0, 0, 0}, -4, "FG1"},   /* noJack */
1902           { {2, 1, 1, 0}, -6, "FG0"}    /* clip2 */
1903         }
1904 };
1905
1906 /*
1907  * Initialize the gain structure to good values
1908  */
1909 void
1910 ar5211InitializeGainValues(struct ath_hal *ah)
1911 {
1912         struct ath_hal_5211 *ahp = AH5211(ah);
1913         GAIN_VALUES *gv = &ahp->ah_gainValues;
1914
1915         /* initialize gain optimization values */
1916         gv->currStepNum = gainLadder.defaultStepNum;
1917         gv->currStep = &gainLadder.optStep[gainLadder.defaultStepNum];
1918         gv->active = AH_TRUE;
1919         gv->loTrig = 20;
1920         gv->hiTrig = 35;
1921 }
1922
1923 static HAL_BOOL
1924 ar5211InvalidGainReadback(struct ath_hal *ah, GAIN_VALUES *gv)
1925 {
1926         const struct ieee80211_channel *chan = AH_PRIVATE(ah)->ah_curchan;
1927         uint32_t gStep, g;
1928         uint32_t L1, L2, L3, L4;
1929
1930         if (IEEE80211_IS_CHAN_CCK(chan)) {
1931                 gStep = 0x18;
1932                 L1 = 0;
1933                 L2 = gStep + 4;
1934                 L3 = 0x40;
1935                 L4 = L3 + 50;
1936
1937                 gv->loTrig = L1;
1938                 gv->hiTrig = L4+5;
1939         } else {
1940                 gStep = 0x3f;
1941                 L1 = 0;
1942                 L2 = 50;
1943                 L3 = L1;
1944                 L4 = L3 + 50;
1945
1946                 gv->loTrig = L1 + DYN_ADJ_LO_MARGIN;
1947                 gv->hiTrig = L4 - DYN_ADJ_UP_MARGIN;
1948         }
1949         g = gv->currGain;
1950
1951         return !((g >= L1 && g<= L2) || (g >= L3 && g <= L4));
1952 }
1953
1954 /*
1955  * Enable the probe gain check on the next packet
1956  */
1957 static void
1958 ar5211RequestRfgain(struct ath_hal *ah)
1959 {
1960         struct ath_hal_5211 *ahp = AH5211(ah);
1961
1962         /* Enable the gain readback probe */
1963         OS_REG_WRITE(ah, AR_PHY_PAPD_PROBE,
1964                   SM(ahp->ah_tx6PowerInHalfDbm, AR_PHY_PAPD_PROBE_POWERTX)
1965                 | AR_PHY_PAPD_PROBE_NEXT_TX);
1966
1967         ahp->ah_rfgainState = HAL_RFGAIN_READ_REQUESTED;
1968 }
1969
1970 /*
1971  * Exported call to check for a recent gain reading and return
1972  * the current state of the thermal calibration gain engine.
1973  */
1974 HAL_RFGAIN
1975 ar5211GetRfgain(struct ath_hal *ah)
1976 {
1977         struct ath_hal_5211 *ahp = AH5211(ah);
1978         GAIN_VALUES *gv = &ahp->ah_gainValues;
1979         uint32_t rddata;
1980
1981         if (!gv->active)
1982                 return HAL_RFGAIN_INACTIVE;
1983
1984         if (ahp->ah_rfgainState == HAL_RFGAIN_READ_REQUESTED) {
1985                 /* Caller had asked to setup a new reading. Check it. */
1986                 rddata = OS_REG_READ(ah, AR_PHY_PAPD_PROBE);
1987
1988                 if ((rddata & AR_PHY_PAPD_PROBE_NEXT_TX) == 0) {
1989                         /* bit got cleared, we have a new reading. */
1990                         gv->currGain = rddata >> AR_PHY_PAPD_PROBE_GAINF_S;
1991                         /* inactive by default */
1992                         ahp->ah_rfgainState = HAL_RFGAIN_INACTIVE;
1993
1994                         if (!ar5211InvalidGainReadback(ah, gv) &&
1995                             ar5211IsGainAdjustNeeded(ah, gv) &&
1996                             ar5211AdjustGain(ah, gv) > 0) {
1997                                 /*
1998                                  * Change needed. Copy ladder info
1999                                  * into eeprom info.
2000                                  */
2001                                 ar5211SetRfgain(ah, gv);
2002                                 ahp->ah_rfgainState = HAL_RFGAIN_NEED_CHANGE;
2003                         }
2004                 }
2005         }
2006         return ahp->ah_rfgainState;
2007 }
2008
2009 /*
2010  * Check to see if our readback gain level sits within the linear
2011  * region of our current variable attenuation window
2012  */
2013 static HAL_BOOL
2014 ar5211IsGainAdjustNeeded(struct ath_hal *ah, const GAIN_VALUES *gv)
2015 {
2016         return (gv->currGain <= gv->loTrig || gv->currGain >= gv->hiTrig);
2017 }
2018
2019 /*
2020  * Move the rabbit ears in the correct direction.
2021  */
2022 static int32_t 
2023 ar5211AdjustGain(struct ath_hal *ah, GAIN_VALUES *gv)
2024 {
2025         /* return > 0 for valid adjustments. */
2026         if (!gv->active)
2027                 return -1;
2028
2029         gv->currStep = &gainLadder.optStep[gv->currStepNum];
2030         if (gv->currGain >= gv->hiTrig) {
2031                 if (gv->currStepNum == 0) {
2032                         HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2033                             "%s: Max gain limit.\n", __func__);
2034                         return -1;
2035                 }
2036                 HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2037                     "%s: Adding gain: currG=%d [%s] --> ",
2038                     __func__, gv->currGain, gv->currStep->stepName);
2039                 gv->targetGain = gv->currGain;
2040                 while (gv->targetGain >= gv->hiTrig && gv->currStepNum > 0) {
2041                         gv->targetGain -= 2 * (gainLadder.optStep[--(gv->currStepNum)].stepGain -
2042                                 gv->currStep->stepGain);
2043                         gv->currStep = &gainLadder.optStep[gv->currStepNum];
2044                 }
2045                 HALDEBUG(ah, HAL_DEBUG_RFPARAM, "targG=%d [%s]\n",
2046                     gv->targetGain, gv->currStep->stepName);
2047                 return 1;
2048         }
2049         if (gv->currGain <= gv->loTrig) {
2050                 if (gv->currStepNum == gainLadder.numStepsInLadder-1) {
2051                         HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2052                             "%s: Min gain limit.\n", __func__);
2053                         return -2;
2054                 }
2055                 HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2056                     "%s: Deducting gain: currG=%d [%s] --> ",
2057                     __func__, gv->currGain, gv->currStep->stepName);
2058                 gv->targetGain = gv->currGain;
2059                 while (gv->targetGain <= gv->loTrig &&
2060                       gv->currStepNum < (gainLadder.numStepsInLadder - 1)) {
2061                         gv->targetGain -= 2 *
2062                                 (gainLadder.optStep[++(gv->currStepNum)].stepGain - gv->currStep->stepGain);
2063                         gv->currStep = &gainLadder.optStep[gv->currStepNum];
2064                 }
2065                 HALDEBUG(ah, HAL_DEBUG_RFPARAM, "targG=%d [%s]\n",
2066                     gv->targetGain, gv->currStep->stepName);
2067                 return 2;
2068         }
2069         return 0;               /* caller didn't call needAdjGain first */
2070 }
2071
2072 /*
2073  * Adjust the 5GHz EEPROM information with the desired calibration values.
2074  */
2075 static void
2076 ar5211SetRfgain(struct ath_hal *ah, const GAIN_VALUES *gv)
2077 {
2078         HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
2079
2080         if (!gv->active)
2081                 return;
2082         ee->ee_cornerCal.clip = gv->currStep->paramVal[0]; /* bb_tx_clip */
2083         ee->ee_cornerCal.pd90 = gv->currStep->paramVal[1]; /* rf_pwd_90 */
2084         ee->ee_cornerCal.pd84 = gv->currStep->paramVal[2]; /* rf_pwd_84 */
2085         ee->ee_cornerCal.gSel = gv->currStep->paramVal[3]; /* rf_rfgainsel */
2086 }
2087
2088 static void
2089 ar5211SetOperatingMode(struct ath_hal *ah, int opmode)
2090 {
2091         struct ath_hal_5211 *ahp = AH5211(ah);
2092         uint32_t val;
2093
2094         val = OS_REG_READ(ah, AR_STA_ID1) & 0xffff;
2095         switch (opmode) {
2096         case HAL_M_HOSTAP:
2097                 OS_REG_WRITE(ah, AR_STA_ID1, val
2098                         | AR_STA_ID1_STA_AP
2099                         | AR_STA_ID1_RTS_USE_DEF
2100                         | ahp->ah_staId1Defaults);
2101                 break;
2102         case HAL_M_IBSS:
2103                 OS_REG_WRITE(ah, AR_STA_ID1, val
2104                         | AR_STA_ID1_ADHOC
2105                         | AR_STA_ID1_DESC_ANTENNA
2106                         | ahp->ah_staId1Defaults);
2107                 break;
2108         case HAL_M_STA:
2109         case HAL_M_MONITOR:
2110                 OS_REG_WRITE(ah, AR_STA_ID1, val
2111                         | AR_STA_ID1_DEFAULT_ANTENNA
2112                         | ahp->ah_staId1Defaults);
2113                 break;
2114         }
2115 }
2116
2117 void
2118 ar5211SetPCUConfig(struct ath_hal *ah)
2119 {
2120         ar5211SetOperatingMode(ah, AH_PRIVATE(ah)->ah_opmode);
2121 }