Merge branch 'master' of git://git.theshell.com/dragonfly
[dragonfly.git] / sys / dev / netif / ath / hal / ath_hal / ar5212 / ar5212_reset.c
1 /*
2  * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
3  * Copyright (c) 2002-2008 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/ar5212/ar5212_reset.c 188979 2009-02-24 01:07:06Z sam $
18  * $DragonFly$
19  */
20 #include "opt_ah.h"
21
22 #include "ah.h"
23 #include "ah_internal.h"
24 #include "ah_devid.h"
25
26 #include "ar5212/ar5212.h"
27 #include "ar5212/ar5212reg.h"
28 #include "ar5212/ar5212phy.h"
29
30 #include "ah_eeprom_v3.h"
31
32 /* Additional Time delay to wait after activiting the Base band */
33 #define BASE_ACTIVATE_DELAY     100     /* 100 usec */
34 #define PLL_SETTLE_DELAY        300     /* 300 usec */
35
36 static HAL_BOOL ar5212SetResetReg(struct ath_hal *, uint32_t resetMask);
37 /* NB: public for 5312 use */
38 HAL_BOOL        ar5212IsSpurChannel(struct ath_hal *,
39                     const struct ieee80211_channel *);
40 HAL_BOOL        ar5212ChannelChange(struct ath_hal *,
41                     const struct ieee80211_channel *);
42 int16_t         ar5212GetNf(struct ath_hal *, struct ieee80211_channel *);
43 HAL_BOOL        ar5212SetBoardValues(struct ath_hal *,
44                     const struct ieee80211_channel *);
45 void            ar5212SetDeltaSlope(struct ath_hal *,
46                     const struct ieee80211_channel *);
47 HAL_BOOL        ar5212SetTransmitPower(struct ath_hal *ah,
48                    const struct ieee80211_channel *chan, uint16_t *rfXpdGain);
49 static HAL_BOOL ar5212SetRateTable(struct ath_hal *, 
50                    const struct ieee80211_channel *, int16_t tpcScaleReduction,
51                    int16_t powerLimit,
52                    HAL_BOOL commit, int16_t *minPower, int16_t *maxPower);
53 static void ar5212CorrectGainDelta(struct ath_hal *, int twiceOfdmCckDelta);
54 static void ar5212GetTargetPowers(struct ath_hal *,
55                    const struct ieee80211_channel *,
56                    const TRGT_POWER_INFO *pPowerInfo, uint16_t numChannels,
57                    TRGT_POWER_INFO *pNewPower);
58 static uint16_t ar5212GetMaxEdgePower(uint16_t channel,
59                    const RD_EDGES_POWER  *pRdEdgesPower);
60 void            ar5212SetRateDurationTable(struct ath_hal *,
61                     const struct ieee80211_channel *);
62 void            ar5212SetIFSTiming(struct ath_hal *,
63                     const struct ieee80211_channel *);
64
65 /* NB: public for RF backend use */
66 void            ar5212GetLowerUpperValues(uint16_t value,
67                    uint16_t *pList, uint16_t listSize,
68                    uint16_t *pLowerValue, uint16_t *pUpperValue);
69 void            ar5212ModifyRfBuffer(uint32_t *rfBuf, uint32_t reg32,
70                    uint32_t numBits, uint32_t firstBit, uint32_t column);
71
72 static int
73 write_common(struct ath_hal *ah, const HAL_INI_ARRAY *ia,
74         HAL_BOOL bChannelChange, int writes)
75 {
76 #define IS_NO_RESET_TIMER_ADDR(x)                      \
77     ( (((x) >= AR_BEACON) && ((x) <= AR_CFP_DUR)) || \
78       (((x) >= AR_SLEEP1) && ((x) <= AR_SLEEP3)))
79 #define V(r, c) (ia)->data[((r)*(ia)->cols) + (c)]
80         int r;
81
82         /* Write Common Array Parameters */
83         for (r = 0; r < ia->rows; r++) {
84                 uint32_t reg = V(r, 0);
85                 /* XXX timer/beacon setup registers? */
86                 /* On channel change, don't reset the PCU registers */
87                 if (!(bChannelChange && IS_NO_RESET_TIMER_ADDR(reg))) {
88                         OS_REG_WRITE(ah, reg, V(r, 1));
89                         DMA_YIELD(writes);
90                 }
91         }
92         return writes;
93 #undef IS_NO_RESET_TIMER_ADDR
94 #undef V
95 }
96
97 #define IS_DISABLE_FAST_ADC_CHAN(x) (((x) == 2462) || ((x) == 2467))
98
99 /*
100  * Places the device in and out of reset and then places sane
101  * values in the registers based on EEPROM config, initialization
102  * vectors (as determined by the mode), and station configuration
103  *
104  * bChannelChange is used to preserve DMA/PCU registers across
105  * a HW Reset during channel change.
106  */
107 HAL_BOOL
108 ar5212Reset(struct ath_hal *ah, HAL_OPMODE opmode,
109         struct ieee80211_channel *chan,
110         HAL_BOOL bChannelChange, HAL_STATUS *status)
111 {
112 #define FAIL(_code)     do { ecode = _code; goto bad; } while (0)
113         struct ath_hal_5212 *ahp = AH5212(ah);
114         HAL_CHANNEL_INTERNAL *ichan = AH_NULL;
115         const HAL_EEPROM *ee;
116         uint32_t softLedCfg, softLedState;
117         uint32_t saveFrameSeqCount, saveDefAntenna, saveLedState;
118         uint32_t macStaId1, synthDelay, txFrm2TxDStart;
119         uint16_t rfXpdGain[MAX_NUM_PDGAINS_PER_CHANNEL];
120         int16_t cckOfdmPwrDelta = 0;
121         u_int modesIndex, freqIndex;
122         HAL_STATUS ecode;
123         int i, regWrites;
124         uint32_t testReg, powerVal;
125         int8_t twiceAntennaGain, twiceAntennaReduction;
126         uint32_t ackTpcPow, ctsTpcPow, chirpTpcPow;
127         HAL_BOOL isBmode = AH_FALSE;
128
129         HALASSERT(ah->ah_magic == AR5212_MAGIC);
130         ee = AH_PRIVATE(ah)->ah_eeprom;
131
132         OS_MARK(ah, AH_MARK_RESET, bChannelChange);
133
134         /* Bring out of sleep mode */
135         if (!ar5212SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE)) {
136                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: chip did not wakeup\n",
137                     __func__);
138                 FAIL(HAL_EIO);
139         }
140
141         /*
142          * Map public channel to private.
143          */
144         ichan = ath_hal_checkchannel(ah, chan);
145         if (ichan == AH_NULL)
146                 FAIL(HAL_EINVAL);
147         switch (opmode) {
148         case HAL_M_STA:
149         case HAL_M_IBSS:
150         case HAL_M_HOSTAP:
151         case HAL_M_MONITOR:
152                 break;
153         default:
154                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid operating mode %u\n",
155                     __func__, opmode);
156                 FAIL(HAL_EINVAL);
157                 break;
158         }
159         HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER3);
160
161         SAVE_CCK(ah, chan, isBmode);
162
163         /* Preserve certain DMA hardware registers on a channel change */
164         if (bChannelChange) {
165                 /*
166                  * On Venice, the TSF is almost preserved across a reset;
167                  * it requires doubling writes to the RESET_TSF
168                  * bit in the AR_BEACON register; it also has the quirk
169                  * of the TSF going back in time on the station (station
170                  * latches onto the last beacon's tsf during a reset 50%
171                  * of the times); the latter is not a problem for adhoc
172                  * stations since as long as the TSF is behind, it will
173                  * get resynchronized on receiving the next beacon; the
174                  * TSF going backwards in time could be a problem for the
175                  * sleep operation (supported on infrastructure stations
176                  * only) - the best and most general fix for this situation
177                  * is to resynchronize the various sleep/beacon timers on
178                  * the receipt of the next beacon i.e. when the TSF itself
179                  * gets resynchronized to the AP's TSF - power save is
180                  * needed to be temporarily disabled until that time
181                  *
182                  * Need to save the sequence number to restore it after
183                  * the reset!
184                  */
185                 saveFrameSeqCount = OS_REG_READ(ah, AR_D_SEQNUM);
186         } else
187                 saveFrameSeqCount = 0;          /* NB: silence compiler */
188 #if 0
189         /*
190          * XXX disable for now; this appears to sometimes cause OFDM
191          * XXX timing error floods when ani is enabled and bg scanning
192          * XXX kicks in
193          */
194         /* If the channel change is across the same mode - perform a fast channel change */
195         if (IS_2413(ah) || IS_5413(ah)) {
196                 /*
197                  * Fast channel change can only be used when:
198                  *  -channel change requested - so it's not the initial reset.
199                  *  -it's not a change to the current channel -
200                  *      often called when switching modes on a channel
201                  *  -the modes of the previous and requested channel are the
202                  *      same
203                  * XXX opmode shouldn't change either?
204                  */
205                 if (bChannelChange &&
206                     (AH_PRIVATE(ah)->ah_curchan != AH_NULL) &&
207                     (chan->ic_freq != AH_PRIVATE(ah)->ah_curchan->ic_freq) &&
208                     ((chan->ic_flags & IEEE80211_CHAN_ALLTURBO) ==
209                      (AH_PRIVATE(ah)->ah_curchan->ic_flags & IEEE80211_CHAN_ALLTURBO))) {
210                         if (ar5212ChannelChange(ah, chan)) {
211                                 /* If ChannelChange completed - skip the rest of reset */
212                                 /* XXX ani? */
213                                 goto done;
214                         }
215                 }
216         }
217 #endif
218         /*
219          * Preserve the antenna on a channel change
220          */
221         saveDefAntenna = OS_REG_READ(ah, AR_DEF_ANTENNA);
222         if (saveDefAntenna == 0)                /* XXX magic constants */
223                 saveDefAntenna = 1;
224
225         /* Save hardware flag before chip reset clears the register */
226         macStaId1 = OS_REG_READ(ah, AR_STA_ID1) & 
227                 (AR_STA_ID1_BASE_RATE_11B | AR_STA_ID1_USE_DEFANT);
228
229         /* Save led state from pci config register */
230         saveLedState = OS_REG_READ(ah, AR_PCICFG) &
231                 (AR_PCICFG_LEDCTL | AR_PCICFG_LEDMODE | AR_PCICFG_LEDBLINK |
232                  AR_PCICFG_LEDSLOW);
233         softLedCfg = OS_REG_READ(ah, AR_GPIOCR);
234         softLedState = OS_REG_READ(ah, AR_GPIODO);
235
236         ar5212RestoreClock(ah, opmode);         /* move to refclk operation */
237
238         /*
239          * Adjust gain parameters before reset if
240          * there's an outstanding gain updated.
241          */
242         (void) ar5212GetRfgain(ah);
243
244         if (!ar5212ChipReset(ah, chan)) {
245                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: chip reset failed\n", __func__);
246                 FAIL(HAL_EIO);
247         }
248
249         /* Setup the indices for the next set of register array writes */
250         if (IEEE80211_IS_CHAN_2GHZ(chan)) {
251                 freqIndex  = 2;
252                 if (IEEE80211_IS_CHAN_108G(chan))
253                         modesIndex = 5;
254                 else if (IEEE80211_IS_CHAN_G(chan))
255                         modesIndex = 4;
256                 else if (IEEE80211_IS_CHAN_B(chan))
257                         modesIndex = 3;
258                 else {
259                         HALDEBUG(ah, HAL_DEBUG_ANY,
260                             "%s: invalid channel %u/0x%x\n",
261                             __func__, chan->ic_freq, chan->ic_flags);
262                         FAIL(HAL_EINVAL);
263                 }
264         } else {
265                 freqIndex  = 1;
266                 if (IEEE80211_IS_CHAN_TURBO(chan))
267                         modesIndex = 2;
268                 else if (IEEE80211_IS_CHAN_A(chan))
269                         modesIndex = 1;
270                 else {
271                         HALDEBUG(ah, HAL_DEBUG_ANY,
272                             "%s: invalid channel %u/0x%x\n",
273                             __func__, chan->ic_freq, chan->ic_flags);
274                         FAIL(HAL_EINVAL);
275                 }
276         }
277
278         OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
279
280         /* Set correct Baseband to analog shift setting to access analog chips. */
281         OS_REG_WRITE(ah, AR_PHY(0), 0x00000007);
282
283         regWrites = ath_hal_ini_write(ah, &ahp->ah_ini_modes, modesIndex, 0);
284         regWrites = write_common(ah, &ahp->ah_ini_common, bChannelChange,
285                 regWrites);
286 #ifdef AH_RXCFG_SDMAMW_4BYTES
287         /*
288          * Nala doesn't work with 128 byte bursts on pb42(hydra) (ar71xx),
289          * use 4 instead.  Enabling it on all platforms would hurt performance,
290          * so we only enable it on the ones that are affected by it.
291          */
292         OS_REG_WRITE(ah, AR_RXCFG, 0);
293 #endif
294         ahp->ah_rfHal->writeRegs(ah, modesIndex, freqIndex, regWrites);
295
296         OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
297
298         if (IEEE80211_IS_CHAN_HALF(chan) || IEEE80211_IS_CHAN_QUARTER(chan)) {
299                 ar5212SetIFSTiming(ah, chan);
300                 if (IS_5413(ah)) {
301                         /*
302                          * Force window_length for 1/2 and 1/4 rate channels,
303                          * the ini file sets this to zero otherwise.
304                          */
305                         OS_REG_RMW_FIELD(ah, AR_PHY_FRAME_CTL,
306                                 AR_PHY_FRAME_CTL_WINLEN, 3);
307                 }
308         }
309
310         /* Overwrite INI values for revised chipsets */
311         if (AH_PRIVATE(ah)->ah_phyRev >= AR_PHY_CHIP_ID_REV_2) {
312                 /* ADC_CTL */
313                 OS_REG_WRITE(ah, AR_PHY_ADC_CTL,
314                         SM(2, AR_PHY_ADC_CTL_OFF_INBUFGAIN) |
315                         SM(2, AR_PHY_ADC_CTL_ON_INBUFGAIN) |
316                         AR_PHY_ADC_CTL_OFF_PWDDAC |
317                         AR_PHY_ADC_CTL_OFF_PWDADC);
318
319                 /* TX_PWR_ADJ */
320                 if (ichan->channel == 2484) {
321                         cckOfdmPwrDelta = SCALE_OC_DELTA(
322                             ee->ee_cckOfdmPwrDelta -
323                             ee->ee_scaledCh14FilterCckDelta);
324                 } else {
325                         cckOfdmPwrDelta = SCALE_OC_DELTA(
326                             ee->ee_cckOfdmPwrDelta);
327                 }
328
329                 if (IEEE80211_IS_CHAN_G(chan)) {
330                     OS_REG_WRITE(ah, AR_PHY_TXPWRADJ,
331                         SM((ee->ee_cckOfdmPwrDelta*-1),
332                             AR_PHY_TXPWRADJ_CCK_GAIN_DELTA) |
333                         SM((cckOfdmPwrDelta*-1),
334                             AR_PHY_TXPWRADJ_CCK_PCDAC_INDEX));
335                 } else {
336                         OS_REG_WRITE(ah, AR_PHY_TXPWRADJ, 0);
337                 }
338
339                 /* Add barker RSSI thresh enable as disabled */
340                 OS_REG_CLR_BIT(ah, AR_PHY_DAG_CTRLCCK,
341                         AR_PHY_DAG_CTRLCCK_EN_RSSI_THR);
342                 OS_REG_RMW_FIELD(ah, AR_PHY_DAG_CTRLCCK,
343                         AR_PHY_DAG_CTRLCCK_RSSI_THR, 2);
344
345                 /* Set the mute mask to the correct default */
346                 OS_REG_WRITE(ah, AR_SEQ_MASK, 0x0000000F);
347         }
348
349         if (AH_PRIVATE(ah)->ah_phyRev >= AR_PHY_CHIP_ID_REV_3) {
350                 /* Clear reg to alllow RX_CLEAR line debug */
351                 OS_REG_WRITE(ah, AR_PHY_BLUETOOTH,  0);
352         }
353         if (AH_PRIVATE(ah)->ah_phyRev >= AR_PHY_CHIP_ID_REV_4) {
354 #ifdef notyet
355                 /* Enable burst prefetch for the data queues */
356                 OS_REG_RMW_FIELD(ah, AR_D_FPCTL, ... );
357                 /* Enable double-buffering */
358                 OS_REG_CLR_BIT(ah, AR_TXCFG, AR_TXCFG_DBL_BUF_DIS);
359 #endif
360         }
361
362         /* Set ADC/DAC select values */
363         OS_REG_WRITE(ah, AR_PHY_SLEEP_SCAL, 0x0e);
364
365         if (IS_5413(ah) || IS_2417(ah)) {
366                 uint32_t newReg = 1;
367                 if (IS_DISABLE_FAST_ADC_CHAN(ichan->channel))
368                         newReg = 0;
369                 /* As it's a clock changing register, only write when the value needs to be changed */
370                 if (OS_REG_READ(ah, AR_PHY_FAST_ADC) != newReg)
371                         OS_REG_WRITE(ah, AR_PHY_FAST_ADC, newReg);
372         }
373
374         /* Setup the transmit power values. */
375         if (!ar5212SetTransmitPower(ah, chan, rfXpdGain)) {
376                 HALDEBUG(ah, HAL_DEBUG_ANY,
377                     "%s: error init'ing transmit power\n", __func__);
378                 FAIL(HAL_EIO);
379         }
380
381         /* Write the analog registers */
382         if (!ahp->ah_rfHal->setRfRegs(ah, chan, modesIndex, rfXpdGain)) {
383                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: ar5212SetRfRegs failed\n",
384                     __func__);
385                 FAIL(HAL_EIO);
386         }
387
388         /* Write delta slope for OFDM enabled modes (A, G, Turbo) */
389         if (IEEE80211_IS_CHAN_OFDM(chan)) {
390                 if (IS_5413(ah) ||
391                     AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER5_3)
392                         ar5212SetSpurMitigation(ah, chan);
393                 ar5212SetDeltaSlope(ah, chan);
394         }
395
396         /* Setup board specific options for EEPROM version 3 */
397         if (!ar5212SetBoardValues(ah, chan)) {
398                 HALDEBUG(ah, HAL_DEBUG_ANY,
399                     "%s: error setting board options\n", __func__);
400                 FAIL(HAL_EIO);
401         }
402
403         /* Restore certain DMA hardware registers on a channel change */
404         if (bChannelChange)
405                 OS_REG_WRITE(ah, AR_D_SEQNUM, saveFrameSeqCount);
406
407         OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
408
409         OS_REG_WRITE(ah, AR_STA_ID0, LE_READ_4(ahp->ah_macaddr));
410         OS_REG_WRITE(ah, AR_STA_ID1, LE_READ_2(ahp->ah_macaddr + 4)
411                 | macStaId1
412                 | AR_STA_ID1_RTS_USE_DEF
413                 | ahp->ah_staId1Defaults
414         );
415         ar5212SetOperatingMode(ah, opmode);
416
417         /* Set Venice BSSID mask according to current state */
418         OS_REG_WRITE(ah, AR_BSSMSKL, LE_READ_4(ahp->ah_bssidmask));
419         OS_REG_WRITE(ah, AR_BSSMSKU, LE_READ_2(ahp->ah_bssidmask + 4));
420
421         /* Restore previous led state */
422         OS_REG_WRITE(ah, AR_PCICFG, OS_REG_READ(ah, AR_PCICFG) | saveLedState);
423
424         /* Restore soft Led state to GPIO */
425         OS_REG_WRITE(ah, AR_GPIOCR, softLedCfg);
426         OS_REG_WRITE(ah, AR_GPIODO, softLedState);
427
428         /* Restore previous antenna */
429         OS_REG_WRITE(ah, AR_DEF_ANTENNA, saveDefAntenna);
430
431         /* then our BSSID */
432         OS_REG_WRITE(ah, AR_BSS_ID0, LE_READ_4(ahp->ah_bssid));
433         OS_REG_WRITE(ah, AR_BSS_ID1, LE_READ_2(ahp->ah_bssid + 4));
434
435         /* Restore bmiss rssi & count thresholds */
436         OS_REG_WRITE(ah, AR_RSSI_THR, ahp->ah_rssiThr);
437
438         OS_REG_WRITE(ah, AR_ISR, ~0);           /* cleared on write */
439
440         if (!ar5212SetChannel(ah, chan))
441                 FAIL(HAL_EIO);
442
443         OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
444
445         ar5212SetCoverageClass(ah, AH_PRIVATE(ah)->ah_coverageClass, 1);
446
447         ar5212SetRateDurationTable(ah, chan);
448
449         /* Set Tx frame start to tx data start delay */
450         if (IS_RAD5112_ANY(ah) &&
451             (IEEE80211_IS_CHAN_HALF(chan) || IEEE80211_IS_CHAN_QUARTER(chan))) {
452                 txFrm2TxDStart = 
453                         IEEE80211_IS_CHAN_HALF(chan) ?
454                                         TX_FRAME_D_START_HALF_RATE:
455                                         TX_FRAME_D_START_QUARTER_RATE;
456                 OS_REG_RMW_FIELD(ah, AR_PHY_TX_CTL, 
457                         AR_PHY_TX_FRAME_TO_TX_DATA_START, txFrm2TxDStart);
458         }
459
460         /*
461          * Setup fast diversity.
462          * Fast diversity can be enabled or disabled via regadd.txt.
463          * Default is enabled.
464          * For reference,
465          *    Disable: reg        val
466          *             0x00009860 0x00009d18 (if 11a / 11g, else no change)
467          *             0x00009970 0x192bb514
468          *             0x0000a208 0xd03e4648
469          *
470          *    Enable:  0x00009860 0x00009d10 (if 11a / 11g, else no change)
471          *             0x00009970 0x192fb514
472          *             0x0000a208 0xd03e6788
473          */
474
475         /* XXX Setup pre PHY ENABLE EAR additions */
476         /*
477          * Wait for the frequency synth to settle (synth goes on
478          * via AR_PHY_ACTIVE_EN).  Read the phy active delay register.
479          * Value is in 100ns increments.
480          */
481         synthDelay = OS_REG_READ(ah, AR_PHY_RX_DELAY) & AR_PHY_RX_DELAY_DELAY;
482         if (IEEE80211_IS_CHAN_B(chan)) {
483                 synthDelay = (4 * synthDelay) / 22;
484         } else {
485                 synthDelay /= 10;
486         }
487
488         /* Activate the PHY (includes baseband activate and synthesizer on) */
489         OS_REG_WRITE(ah, AR_PHY_ACTIVE, AR_PHY_ACTIVE_EN);
490
491         /* 
492          * There is an issue if the AP starts the calibration before
493          * the base band timeout completes.  This could result in the
494          * rx_clear false triggering.  As a workaround we add delay an
495          * extra BASE_ACTIVATE_DELAY usecs to ensure this condition
496          * does not happen.
497          */
498         if (IEEE80211_IS_CHAN_HALF(chan)) {
499                 OS_DELAY((synthDelay << 1) + BASE_ACTIVATE_DELAY);
500         } else if (IEEE80211_IS_CHAN_QUARTER(chan)) {
501                 OS_DELAY((synthDelay << 2) + BASE_ACTIVATE_DELAY);
502         } else {
503                 OS_DELAY(synthDelay + BASE_ACTIVATE_DELAY);
504         }
505
506         /*
507          * The udelay method is not reliable with notebooks.
508          * Need to check to see if the baseband is ready
509          */
510         testReg = OS_REG_READ(ah, AR_PHY_TESTCTRL);
511         /* Selects the Tx hold */
512         OS_REG_WRITE(ah, AR_PHY_TESTCTRL, AR_PHY_TESTCTRL_TXHOLD);
513         i = 0;
514         while ((i++ < 20) &&
515                (OS_REG_READ(ah, 0x9c24) & 0x10)) /* test if baseband not ready */               OS_DELAY(200);
516         OS_REG_WRITE(ah, AR_PHY_TESTCTRL, testReg);
517
518         /* Calibrate the AGC and start a NF calculation */
519         OS_REG_WRITE(ah, AR_PHY_AGC_CONTROL,
520                   OS_REG_READ(ah, AR_PHY_AGC_CONTROL)
521                 | AR_PHY_AGC_CONTROL_CAL
522                 | AR_PHY_AGC_CONTROL_NF);
523
524         if (!IEEE80211_IS_CHAN_B(chan) && ahp->ah_bIQCalibration != IQ_CAL_DONE) {
525                 /* Start IQ calibration w/ 2^(INIT_IQCAL_LOG_COUNT_MAX+1) samples */
526                 OS_REG_RMW_FIELD(ah, AR_PHY_TIMING_CTRL4, 
527                         AR_PHY_TIMING_CTRL4_IQCAL_LOG_COUNT_MAX,
528                         INIT_IQCAL_LOG_COUNT_MAX);
529                 OS_REG_SET_BIT(ah, AR_PHY_TIMING_CTRL4,
530                         AR_PHY_TIMING_CTRL4_DO_IQCAL);
531                 ahp->ah_bIQCalibration = IQ_CAL_RUNNING;
532         } else
533                 ahp->ah_bIQCalibration = IQ_CAL_INACTIVE;
534
535         /* Setup compression registers */
536         ar5212SetCompRegs(ah);
537
538         /* Set 1:1 QCU to DCU mapping for all queues */
539         for (i = 0; i < AR_NUM_DCU; i++)
540                 OS_REG_WRITE(ah, AR_DQCUMASK(i), 1 << i);
541
542         ahp->ah_intrTxqs = 0;
543         for (i = 0; i < AH_PRIVATE(ah)->ah_caps.halTotalQueues; i++)
544                 ar5212ResetTxQueue(ah, i);
545
546         /*
547          * Setup interrupt handling.  Note that ar5212ResetTxQueue
548          * manipulates the secondary IMR's as queues are enabled
549          * and disabled.  This is done with RMW ops to insure the
550          * settings we make here are preserved.
551          */
552         ahp->ah_maskReg = AR_IMR_TXOK | AR_IMR_TXERR | AR_IMR_TXURN
553                         | AR_IMR_RXOK | AR_IMR_RXERR | AR_IMR_RXORN
554                         | AR_IMR_HIUERR
555                         ;
556         if (opmode == HAL_M_HOSTAP)
557                 ahp->ah_maskReg |= AR_IMR_MIB;
558         OS_REG_WRITE(ah, AR_IMR, ahp->ah_maskReg);
559         /* Enable bus errors that are OR'd to set the HIUERR bit */
560         OS_REG_WRITE(ah, AR_IMR_S2,
561                 OS_REG_READ(ah, AR_IMR_S2)
562                 | AR_IMR_S2_MCABT | AR_IMR_S2_SSERR | AR_IMR_S2_DPERR);
563
564         if (AH_PRIVATE(ah)->ah_rfkillEnabled)
565                 ar5212EnableRfKill(ah);
566
567         if (!ath_hal_wait(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_CAL, 0)) {
568                 HALDEBUG(ah, HAL_DEBUG_ANY,
569                     "%s: offset calibration failed to complete in 1ms;"
570                     " noisy environment?\n", __func__);
571         }
572
573         /*
574          * Set clocks back to 32kHz if they had been using refClk, then
575          * use an external 32kHz crystal when sleeping, if one exists.
576          */
577         ar5212SetupClock(ah, opmode);
578
579         /*
580          * Writing to AR_BEACON will start timers. Hence it should
581          * be the last register to be written. Do not reset tsf, do
582          * not enable beacons at this point, but preserve other values
583          * like beaconInterval.
584          */
585         OS_REG_WRITE(ah, AR_BEACON,
586                 (OS_REG_READ(ah, AR_BEACON) &~ (AR_BEACON_EN | AR_BEACON_RESET_TSF)));
587
588         /* XXX Setup post reset EAR additions */
589
590         /* QoS support */
591         if (AH_PRIVATE(ah)->ah_macVersion > AR_SREV_VERSION_VENICE ||
592             (AH_PRIVATE(ah)->ah_macVersion == AR_SREV_VERSION_VENICE &&
593              AH_PRIVATE(ah)->ah_macRev >= AR_SREV_GRIFFIN_LITE)) {
594                 OS_REG_WRITE(ah, AR_QOS_CONTROL, 0x100aa);      /* XXX magic */
595                 OS_REG_WRITE(ah, AR_QOS_SELECT, 0x3210);        /* XXX magic */
596         }
597
598         /* Turn on NOACK Support for QoS packets */
599         OS_REG_WRITE(ah, AR_NOACK,
600                 SM(2, AR_NOACK_2BIT_VALUE) |
601                 SM(5, AR_NOACK_BIT_OFFSET) |
602                 SM(0, AR_NOACK_BYTE_OFFSET));
603
604         /* Get Antenna Gain reduction */
605         if (IEEE80211_IS_CHAN_5GHZ(chan)) {
606                 ath_hal_eepromGet(ah, AR_EEP_ANTGAINMAX_5, &twiceAntennaGain);
607         } else {
608                 ath_hal_eepromGet(ah, AR_EEP_ANTGAINMAX_2, &twiceAntennaGain);
609         }
610         twiceAntennaReduction =
611                 ath_hal_getantennareduction(ah, chan, twiceAntennaGain);
612
613         /* TPC for self-generated frames */
614
615         ackTpcPow = MS(ahp->ah_macTPC, AR_TPC_ACK);
616         if ((ackTpcPow-ahp->ah_txPowerIndexOffset) > chan->ic_maxpower)
617                 ackTpcPow = chan->ic_maxpower+ahp->ah_txPowerIndexOffset;
618
619         if (ackTpcPow > (2*chan->ic_maxregpower - twiceAntennaReduction))
620                 ackTpcPow = (2*chan->ic_maxregpower - twiceAntennaReduction)
621                         + ahp->ah_txPowerIndexOffset;
622
623         ctsTpcPow = MS(ahp->ah_macTPC, AR_TPC_CTS);
624         if ((ctsTpcPow-ahp->ah_txPowerIndexOffset) > chan->ic_maxpower)
625                 ctsTpcPow = chan->ic_maxpower+ahp->ah_txPowerIndexOffset;
626
627         if (ctsTpcPow > (2*chan->ic_maxregpower - twiceAntennaReduction))
628                 ctsTpcPow = (2*chan->ic_maxregpower - twiceAntennaReduction)
629                         + ahp->ah_txPowerIndexOffset;
630
631         chirpTpcPow = MS(ahp->ah_macTPC, AR_TPC_CHIRP);
632         if ((chirpTpcPow-ahp->ah_txPowerIndexOffset) > chan->ic_maxpower)
633                 chirpTpcPow = chan->ic_maxpower+ahp->ah_txPowerIndexOffset;
634
635         if (chirpTpcPow > (2*chan->ic_maxregpower - twiceAntennaReduction))
636                 chirpTpcPow = (2*chan->ic_maxregpower - twiceAntennaReduction)
637                         + ahp->ah_txPowerIndexOffset;
638
639         if (ackTpcPow > 63)
640                 ackTpcPow = 63;
641         if (ctsTpcPow > 63)
642                 ctsTpcPow = 63;
643         if (chirpTpcPow > 63)
644                 chirpTpcPow = 63;
645
646         powerVal = SM(ackTpcPow, AR_TPC_ACK) |
647                 SM(ctsTpcPow, AR_TPC_CTS) |
648                 SM(chirpTpcPow, AR_TPC_CHIRP);
649
650         OS_REG_WRITE(ah, AR_TPC, powerVal);
651
652         /* Restore user-specified settings */
653         if (ahp->ah_miscMode != 0)
654                 OS_REG_WRITE(ah, AR_MISC_MODE, ahp->ah_miscMode);
655         if (ahp->ah_sifstime != (u_int) -1)
656                 ar5212SetSifsTime(ah, ahp->ah_sifstime);
657         if (ahp->ah_slottime != (u_int) -1)
658                 ar5212SetSlotTime(ah, ahp->ah_slottime);
659         if (ahp->ah_acktimeout != (u_int) -1)
660                 ar5212SetAckTimeout(ah, ahp->ah_acktimeout);
661         if (ahp->ah_ctstimeout != (u_int) -1)
662                 ar5212SetCTSTimeout(ah, ahp->ah_ctstimeout);
663         if (AH_PRIVATE(ah)->ah_diagreg != 0)
664                 OS_REG_WRITE(ah, AR_DIAG_SW, AH_PRIVATE(ah)->ah_diagreg);
665
666         AH_PRIVATE(ah)->ah_opmode = opmode;     /* record operating mode */
667 #if 0
668 done:
669 #endif
670         if (bChannelChange && !IEEE80211_IS_CHAN_DFS(chan)) 
671                 chan->ic_state &= ~IEEE80211_CHANSTATE_CWINT;
672
673         HALDEBUG(ah, HAL_DEBUG_RESET, "%s: done\n", __func__);
674
675         RESTORE_CCK(ah, chan, isBmode);
676         
677         OS_MARK(ah, AH_MARK_RESET_DONE, 0);
678
679         return AH_TRUE;
680 bad:
681         RESTORE_CCK(ah, chan, isBmode);
682
683         OS_MARK(ah, AH_MARK_RESET_DONE, ecode);
684         if (status != AH_NULL)
685                 *status = ecode;
686         return AH_FALSE;
687 #undef FAIL
688 }
689
690 /*
691  * Call the rf backend to change the channel.
692  */
693 HAL_BOOL
694 ar5212SetChannel(struct ath_hal *ah, const struct ieee80211_channel *chan)
695 {
696         struct ath_hal_5212 *ahp = AH5212(ah);
697
698         /* Change the synth */
699         if (!ahp->ah_rfHal->setChannel(ah, chan))
700                 return AH_FALSE;
701         return AH_TRUE;
702 }
703
704 /*
705  * This channel change evaluates whether the selected hardware can
706  * perform a synthesizer-only channel change (no reset).  If the
707  * TX is not stopped, or the RFBus cannot be granted in the given
708  * time, the function returns false as a reset is necessary
709  */
710 HAL_BOOL
711 ar5212ChannelChange(struct ath_hal *ah, const struct ieee80211_channel *chan)
712 {
713         uint32_t       ulCount;
714         uint32_t   data, synthDelay, qnum;
715         uint16_t   rfXpdGain[MAX_NUM_PDGAINS_PER_CHANNEL];
716         HAL_BOOL    txStopped = AH_TRUE;
717         HAL_CHANNEL_INTERNAL *ichan;
718
719         /*
720          * Map public channel to private.
721          */
722         ichan = ath_hal_checkchannel(ah, chan);
723
724         /* TX must be stopped or RF Bus grant will not work */
725         for (qnum = 0; qnum < AH_PRIVATE(ah)->ah_caps.halTotalQueues; qnum++) {
726                 if (ar5212NumTxPending(ah, qnum)) {
727                         txStopped = AH_FALSE;
728                         break;
729                 }
730         }
731         if (!txStopped)
732                 return AH_FALSE;
733
734         /* Kill last Baseband Rx Frame */
735         OS_REG_WRITE(ah, AR_PHY_RFBUS_REQ, AR_PHY_RFBUS_REQ_REQUEST); /* Request analog bus grant */
736         for (ulCount = 0; ulCount < 100; ulCount++) {
737                 if (OS_REG_READ(ah, AR_PHY_RFBUS_GNT))
738                         break;
739                 OS_DELAY(5);
740         }
741         if (ulCount >= 100)
742                 return AH_FALSE;
743
744         /* Change the synth */
745         if (!ar5212SetChannel(ah, chan))
746                 return AH_FALSE;
747
748         /*
749          * Wait for the frequency synth to settle (synth goes on via PHY_ACTIVE_EN).
750          * Read the phy active delay register. Value is in 100ns increments.
751          */
752         data = OS_REG_READ(ah, AR_PHY_RX_DELAY) & AR_PHY_RX_DELAY_DELAY;
753         if (IEEE80211_IS_CHAN_B(chan)) {
754                 synthDelay = (4 * data) / 22;
755         } else {
756                 synthDelay = data / 10;
757         }
758         OS_DELAY(synthDelay + BASE_ACTIVATE_DELAY);
759
760         /* Setup the transmit power values. */
761         if (!ar5212SetTransmitPower(ah, chan, rfXpdGain)) {
762                 HALDEBUG(ah, HAL_DEBUG_ANY,
763                     "%s: error init'ing transmit power\n", __func__);
764                 return AH_FALSE;
765         }
766
767         /* Write delta slope for OFDM enabled modes (A, G, Turbo) */
768         if (IEEE80211_IS_CHAN_OFDM(chan)) {
769                 if (IS_5413(ah) ||
770                     AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER5_3)
771                         ar5212SetSpurMitigation(ah, chan);
772                 ar5212SetDeltaSlope(ah, chan);
773         }
774
775         /* Release the RFBus Grant */
776         OS_REG_WRITE(ah, AR_PHY_RFBUS_REQ, 0);
777
778         /* Start Noise Floor Cal */
779         OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NF);
780         return AH_TRUE;
781 }
782
783 void
784 ar5212SetOperatingMode(struct ath_hal *ah, int opmode)
785 {
786         uint32_t val;
787
788         val = OS_REG_READ(ah, AR_STA_ID1);
789         val &= ~(AR_STA_ID1_STA_AP | AR_STA_ID1_ADHOC);
790         switch (opmode) {
791         case HAL_M_HOSTAP:
792                 OS_REG_WRITE(ah, AR_STA_ID1, val | AR_STA_ID1_STA_AP
793                                         | AR_STA_ID1_KSRCH_MODE);
794                 OS_REG_CLR_BIT(ah, AR_CFG, AR_CFG_AP_ADHOC_INDICATION);
795                 break;
796         case HAL_M_IBSS:
797                 OS_REG_WRITE(ah, AR_STA_ID1, val | AR_STA_ID1_ADHOC
798                                         | AR_STA_ID1_KSRCH_MODE);
799                 OS_REG_SET_BIT(ah, AR_CFG, AR_CFG_AP_ADHOC_INDICATION);
800                 break;
801         case HAL_M_STA:
802         case HAL_M_MONITOR:
803                 OS_REG_WRITE(ah, AR_STA_ID1, val | AR_STA_ID1_KSRCH_MODE);
804                 break;
805         }
806 }
807
808 /*
809  * Places the PHY and Radio chips into reset.  A full reset
810  * must be called to leave this state.  The PCI/MAC/PCU are
811  * not placed into reset as we must receive interrupt to
812  * re-enable the hardware.
813  */
814 HAL_BOOL
815 ar5212PhyDisable(struct ath_hal *ah)
816 {
817         return ar5212SetResetReg(ah, AR_RC_BB);
818 }
819
820 /*
821  * Places all of hardware into reset
822  */
823 HAL_BOOL
824 ar5212Disable(struct ath_hal *ah)
825 {
826         if (!ar5212SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
827                 return AH_FALSE;
828         /*
829          * Reset the HW - PCI must be reset after the rest of the
830          * device has been reset.
831          */
832         return ar5212SetResetReg(ah, AR_RC_MAC | AR_RC_BB | AR_RC_PCI);
833 }
834
835 /*
836  * Places the hardware into reset and then pulls it out of reset
837  *
838  * TODO: Only write the PLL if we're changing to or from CCK mode
839  * 
840  * WARNING: The order of the PLL and mode registers must be correct.
841  */
842 HAL_BOOL
843 ar5212ChipReset(struct ath_hal *ah, const struct ieee80211_channel *chan)
844 {
845
846         OS_MARK(ah, AH_MARK_CHIPRESET, chan ? chan->ic_freq : 0);
847
848         /*
849          * Reset the HW - PCI must be reset after the rest of the
850          * device has been reset
851          */
852         if (!ar5212SetResetReg(ah, AR_RC_MAC | AR_RC_BB | AR_RC_PCI))
853                 return AH_FALSE;
854
855         /* Bring out of sleep mode (AGAIN) */
856         if (!ar5212SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
857                 return AH_FALSE;
858
859         /* Clear warm reset register */
860         if (!ar5212SetResetReg(ah, 0))
861                 return AH_FALSE;
862
863         /*
864          * Perform warm reset before the mode/PLL/turbo registers
865          * are changed in order to deactivate the radio.  Mode changes
866          * with an active radio can result in corrupted shifts to the
867          * radio device.
868          */
869
870         /*
871          * Set CCK and Turbo modes correctly.
872          */
873         if (chan != AH_NULL) {          /* NB: can be null during attach */
874                 uint32_t rfMode, phyPLL = 0, curPhyPLL, turbo;
875
876                 if (IS_5413(ah)) {      /* NB: =>'s 5424 also */
877                         rfMode = AR_PHY_MODE_AR5112;
878                         if (IEEE80211_IS_CHAN_HALF(chan))
879                                 rfMode |= AR_PHY_MODE_HALF;
880                         else if (IEEE80211_IS_CHAN_QUARTER(chan))
881                                 rfMode |= AR_PHY_MODE_QUARTER;
882
883                         if (IEEE80211_IS_CHAN_CCK(chan))
884                                 phyPLL = AR_PHY_PLL_CTL_44_5112;
885                         else
886                                 phyPLL = AR_PHY_PLL_CTL_40_5413;
887                 } else if (IS_RAD5111(ah)) {
888                         rfMode = AR_PHY_MODE_AR5111;
889                         if (IEEE80211_IS_CHAN_CCK(chan))
890                                 phyPLL = AR_PHY_PLL_CTL_44;
891                         else
892                                 phyPLL = AR_PHY_PLL_CTL_40;
893                         if (IEEE80211_IS_CHAN_HALF(chan))
894                                 phyPLL = AR_PHY_PLL_CTL_HALF;
895                         else if (IEEE80211_IS_CHAN_QUARTER(chan))
896                                 phyPLL = AR_PHY_PLL_CTL_QUARTER;
897                 } else {                /* 5112, 2413, 2316, 2317 */
898                         rfMode = AR_PHY_MODE_AR5112;
899                         if (IEEE80211_IS_CHAN_CCK(chan))
900                                 phyPLL = AR_PHY_PLL_CTL_44_5112;
901                         else
902                                 phyPLL = AR_PHY_PLL_CTL_40_5112;
903                         if (IEEE80211_IS_CHAN_HALF(chan))
904                                 phyPLL |= AR_PHY_PLL_CTL_HALF;
905                         else if (IEEE80211_IS_CHAN_QUARTER(chan))
906                                 phyPLL |= AR_PHY_PLL_CTL_QUARTER;
907                 }
908                 if (IEEE80211_IS_CHAN_G(chan))
909                         rfMode |= AR_PHY_MODE_DYNAMIC;
910                 else if (IEEE80211_IS_CHAN_OFDM(chan))
911                         rfMode |= AR_PHY_MODE_OFDM;
912                 else
913                         rfMode |= AR_PHY_MODE_CCK;
914                 if (IEEE80211_IS_CHAN_5GHZ(chan))
915                         rfMode |= AR_PHY_MODE_RF5GHZ;
916                 else
917                         rfMode |= AR_PHY_MODE_RF2GHZ;
918                 turbo = IEEE80211_IS_CHAN_TURBO(chan) ?
919                         (AR_PHY_FC_TURBO_MODE | AR_PHY_FC_TURBO_SHORT) : 0;
920                 curPhyPLL = OS_REG_READ(ah, AR_PHY_PLL_CTL);
921                 /*
922                  * PLL, Mode, and Turbo values must be written in the correct
923                  * order to ensure:
924                  * - The PLL cannot be set to 44 unless the CCK or DYNAMIC
925                  *   mode bit is set
926                  * - Turbo cannot be set at the same time as CCK or DYNAMIC
927                  */
928                 if (IEEE80211_IS_CHAN_CCK(chan)) {
929                         OS_REG_WRITE(ah, AR_PHY_TURBO, turbo);
930                         OS_REG_WRITE(ah, AR_PHY_MODE, rfMode);
931                         if (curPhyPLL != phyPLL) {
932                                 OS_REG_WRITE(ah,  AR_PHY_PLL_CTL,  phyPLL);
933                                 /* Wait for the PLL to settle */
934                                 OS_DELAY(PLL_SETTLE_DELAY);
935                         }
936                 } else {
937                         if (curPhyPLL != phyPLL) {
938                                 OS_REG_WRITE(ah,  AR_PHY_PLL_CTL,  phyPLL);
939                                 /* Wait for the PLL to settle */
940                                 OS_DELAY(PLL_SETTLE_DELAY);
941                         }
942                         OS_REG_WRITE(ah, AR_PHY_TURBO, turbo);
943                         OS_REG_WRITE(ah, AR_PHY_MODE, rfMode);
944                 }
945         }
946         return AH_TRUE;
947 }
948
949 /*
950  * Recalibrate the lower PHY chips to account for temperature/environment
951  * changes.
952  */
953 HAL_BOOL
954 ar5212PerCalibrationN(struct ath_hal *ah,
955         struct ieee80211_channel *chan,
956         u_int chainMask, HAL_BOOL longCal, HAL_BOOL *isCalDone)
957 {
958 #define IQ_CAL_TRIES    10
959         struct ath_hal_5212 *ahp = AH5212(ah);
960         HAL_CHANNEL_INTERNAL *ichan;
961         int32_t qCoff, qCoffDenom;
962         int32_t iqCorrMeas, iCoff, iCoffDenom;
963         uint32_t powerMeasQ, powerMeasI;
964         HAL_BOOL isBmode = AH_FALSE;
965
966         OS_MARK(ah, AH_MARK_PERCAL, chan->ic_freq);
967         *isCalDone = AH_FALSE;
968         ichan = ath_hal_checkchannel(ah, chan);
969         if (ichan == AH_NULL) {
970                 HALDEBUG(ah, HAL_DEBUG_ANY,
971                     "%s: invalid channel %u/0x%x; no mapping\n",
972                     __func__, chan->ic_freq, chan->ic_flags);
973                 return AH_FALSE;
974         }
975         SAVE_CCK(ah, chan, isBmode);
976
977         if (ahp->ah_bIQCalibration == IQ_CAL_DONE ||
978             ahp->ah_bIQCalibration == IQ_CAL_INACTIVE)
979                 *isCalDone = AH_TRUE;
980
981         /* IQ calibration in progress. Check to see if it has finished. */
982         if (ahp->ah_bIQCalibration == IQ_CAL_RUNNING &&
983             !(OS_REG_READ(ah, AR_PHY_TIMING_CTRL4) & AR_PHY_TIMING_CTRL4_DO_IQCAL)) {
984                 int i;
985
986                 /* IQ Calibration has finished. */
987                 ahp->ah_bIQCalibration = IQ_CAL_INACTIVE;
988                 *isCalDone = AH_TRUE;
989
990                 /* workaround for misgated IQ Cal results */
991                 i = 0;
992                 do {
993                         /* Read calibration results. */
994                         powerMeasI = OS_REG_READ(ah, AR_PHY_IQCAL_RES_PWR_MEAS_I);
995                         powerMeasQ = OS_REG_READ(ah, AR_PHY_IQCAL_RES_PWR_MEAS_Q);
996                         iqCorrMeas = OS_REG_READ(ah, AR_PHY_IQCAL_RES_IQ_CORR_MEAS);
997                         if (powerMeasI && powerMeasQ)
998                                 break;
999                         /* Do we really need this??? */
1000                         OS_REG_SET_BIT(ah, AR_PHY_TIMING_CTRL4,
1001                             AR_PHY_TIMING_CTRL4_DO_IQCAL);
1002                 } while (++i < IQ_CAL_TRIES);
1003
1004                 HALDEBUG(ah, HAL_DEBUG_PERCAL,
1005                     "%s: IQ cal finished: %d tries\n", __func__, i);
1006                 HALDEBUG(ah, HAL_DEBUG_PERCAL,
1007                     "%s: powerMeasI %u powerMeasQ %u iqCorrMeas %d\n",
1008                     __func__, powerMeasI, powerMeasQ, iqCorrMeas);
1009
1010                 /*
1011                  * Prescale these values to remove 64-bit operation
1012                  * requirement at the loss of a little precision.
1013                  */
1014                 iCoffDenom = (powerMeasI / 2 + powerMeasQ / 2) / 128;
1015                 qCoffDenom = powerMeasQ / 128;
1016
1017                 /* Protect against divide-by-0 and loss of sign bits. */
1018                 if (iCoffDenom != 0 && qCoffDenom >= 2) {
1019                         iCoff = (int8_t)(-iqCorrMeas) / iCoffDenom;
1020                         /* IQCORR_Q_I_COFF is a signed 6 bit number */
1021                         if (iCoff < -32) {
1022                                 iCoff = -32;
1023                         } else if (iCoff > 31) {
1024                                 iCoff = 31;
1025                         }
1026
1027                         /* IQCORR_Q_Q_COFF is a signed 5 bit number */
1028                         qCoff = (powerMeasI / qCoffDenom) - 128;
1029                         if (qCoff < -16) {
1030                                 qCoff = -16;
1031                         } else if (qCoff > 15) {
1032                                 qCoff = 15;
1033                         }
1034
1035                         HALDEBUG(ah, HAL_DEBUG_PERCAL,
1036                             "%s: iCoff %d qCoff %d\n", __func__, iCoff, qCoff);
1037
1038                         /* Write values and enable correction */
1039                         OS_REG_RMW_FIELD(ah, AR_PHY_TIMING_CTRL4,
1040                                 AR_PHY_TIMING_CTRL4_IQCORR_Q_I_COFF, iCoff);
1041                         OS_REG_RMW_FIELD(ah, AR_PHY_TIMING_CTRL4,
1042                                 AR_PHY_TIMING_CTRL4_IQCORR_Q_Q_COFF, qCoff);
1043                         OS_REG_SET_BIT(ah, AR_PHY_TIMING_CTRL4, 
1044                                 AR_PHY_TIMING_CTRL4_IQCORR_ENABLE);
1045
1046                         ahp->ah_bIQCalibration = IQ_CAL_DONE;
1047                         ichan->privFlags |= CHANNEL_IQVALID;
1048                         ichan->iCoff = iCoff;
1049                         ichan->qCoff = qCoff;
1050                 }
1051         } else if (!IEEE80211_IS_CHAN_B(chan) &&
1052             ahp->ah_bIQCalibration == IQ_CAL_DONE &&
1053             (ichan->privFlags & CHANNEL_IQVALID) == 0) {
1054                 /*
1055                  * Start IQ calibration if configured channel has changed.
1056                  * Use a magic number of 15 based on default value.
1057                  */
1058                 OS_REG_RMW_FIELD(ah, AR_PHY_TIMING_CTRL4,
1059                         AR_PHY_TIMING_CTRL4_IQCAL_LOG_COUNT_MAX,
1060                         INIT_IQCAL_LOG_COUNT_MAX);
1061                 OS_REG_SET_BIT(ah, AR_PHY_TIMING_CTRL4,
1062                         AR_PHY_TIMING_CTRL4_DO_IQCAL);
1063                 ahp->ah_bIQCalibration = IQ_CAL_RUNNING;
1064         }
1065         /* XXX EAR */
1066
1067         if (longCal) {
1068                 /* Check noise floor results */
1069                 ar5212GetNf(ah, chan);
1070                 if (!IEEE80211_IS_CHAN_CWINT(chan)) {
1071                         /* Perform cal for 5Ghz channels and any OFDM on 5112 */
1072                         if (IEEE80211_IS_CHAN_5GHZ(chan) ||
1073                             (IS_RAD5112(ah) && IEEE80211_IS_CHAN_OFDM(chan)))
1074                                 ar5212RequestRfgain(ah);
1075                 }
1076         }
1077         RESTORE_CCK(ah, chan, isBmode);
1078
1079         return AH_TRUE;
1080 #undef IQ_CAL_TRIES
1081 }
1082
1083 HAL_BOOL
1084 ar5212PerCalibration(struct ath_hal *ah,  struct ieee80211_channel *chan,
1085         HAL_BOOL *isIQdone)
1086 {
1087         return ar5212PerCalibrationN(ah, chan, 0x1, AH_TRUE, isIQdone);
1088 }
1089
1090 HAL_BOOL
1091 ar5212ResetCalValid(struct ath_hal *ah, const struct ieee80211_channel *chan)
1092 {
1093         HAL_CHANNEL_INTERNAL *ichan;
1094
1095         ichan = ath_hal_checkchannel(ah, chan);
1096         if (ichan == AH_NULL) {
1097                 HALDEBUG(ah, HAL_DEBUG_ANY,
1098                     "%s: invalid channel %u/0x%x; no mapping\n",
1099                     __func__, chan->ic_freq, chan->ic_flags);
1100                 return AH_FALSE;
1101         }
1102         ichan->privFlags &= ~CHANNEL_IQVALID;
1103         return AH_TRUE;
1104 }
1105
1106 /*
1107  * Write the given reset bit mask into the reset register
1108  */
1109 static HAL_BOOL
1110 ar5212SetResetReg(struct ath_hal *ah, uint32_t resetMask)
1111 {
1112         uint32_t mask = resetMask ? resetMask : ~0;
1113         HAL_BOOL rt;
1114
1115         /* XXX ar5212MacStop & co. */
1116
1117         if (AH_PRIVATE(ah)->ah_ispcie) {
1118                 resetMask &= ~AR_RC_PCI;
1119         }
1120
1121         (void) OS_REG_READ(ah, AR_RXDP);/* flush any pending MMR writes */
1122         OS_REG_WRITE(ah, AR_RC, resetMask);
1123         OS_DELAY(15);                   /* need to wait at least 128 clocks
1124                                            when reseting PCI before read */
1125         mask &= (AR_RC_MAC | AR_RC_BB);
1126         resetMask &= (AR_RC_MAC | AR_RC_BB);
1127         rt = ath_hal_wait(ah, AR_RC, mask, resetMask);
1128         if ((resetMask & AR_RC_MAC) == 0) {
1129                 if (isBigEndian()) {
1130                         /*
1131                          * Set CFG, little-endian for register
1132                          * and descriptor accesses.
1133                          */
1134                         mask = INIT_CONFIG_STATUS | AR_CFG_SWRD | AR_CFG_SWRG;
1135 #ifndef AH_NEED_DESC_SWAP
1136                         mask |= AR_CFG_SWTD;
1137 #endif
1138                         OS_REG_WRITE(ah, AR_CFG, LE_READ_4(&mask));
1139                 } else
1140                         OS_REG_WRITE(ah, AR_CFG, INIT_CONFIG_STATUS);
1141                 if (ar5212SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
1142                         (void) OS_REG_READ(ah, AR_ISR_RAC);
1143         }
1144
1145         /* track PHY power state so we don't try to r/w BB registers */
1146         AH5212(ah)->ah_phyPowerOn = ((resetMask & AR_RC_BB) == 0);
1147         return rt;
1148 }
1149
1150 int16_t
1151 ar5212GetNoiseFloor(struct ath_hal *ah)
1152 {
1153         int16_t nf = (OS_REG_READ(ah, AR_PHY(25)) >> 19) & 0x1ff;
1154         if (nf & 0x100)
1155                 nf = 0 - ((nf ^ 0x1ff) + 1);
1156         return nf;
1157 }
1158
1159 static HAL_BOOL
1160 getNoiseFloorThresh(struct ath_hal *ah, const struct ieee80211_channel *chan,
1161         int16_t *nft)
1162 {
1163         const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1164
1165         HALASSERT(ah->ah_magic == AR5212_MAGIC);
1166
1167         switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
1168         case IEEE80211_CHAN_A:
1169                 *nft = ee->ee_noiseFloorThresh[headerInfo11A];
1170                 break;
1171         case IEEE80211_CHAN_B:
1172                 *nft = ee->ee_noiseFloorThresh[headerInfo11B];
1173                 break;
1174         case IEEE80211_CHAN_G:
1175         case IEEE80211_CHAN_PUREG:      /* NB: really 108G */
1176                 *nft = ee->ee_noiseFloorThresh[headerInfo11G];
1177                 break;
1178         default:
1179                 HALDEBUG(ah, HAL_DEBUG_ANY,
1180                     "%s: invalid channel flags %u/0x%x\n",
1181                     __func__, chan->ic_freq, chan->ic_flags);
1182                 return AH_FALSE;
1183         }
1184         return AH_TRUE;
1185 }
1186
1187 /*
1188  * Setup the noise floor cal history buffer.
1189  */
1190 void 
1191 ar5212InitNfCalHistBuffer(struct ath_hal *ah)
1192 {
1193         struct ath_hal_5212 *ahp = AH5212(ah);
1194         int i;
1195
1196         ahp->ah_nfCalHist.first_run = 1;        
1197         ahp->ah_nfCalHist.currIndex = 0;
1198         ahp->ah_nfCalHist.privNF = AR5212_CCA_MAX_GOOD_VALUE;
1199         ahp->ah_nfCalHist.invalidNFcount = AR512_NF_CAL_HIST_MAX;
1200         for (i = 0; i < AR512_NF_CAL_HIST_MAX; i ++)
1201                 ahp->ah_nfCalHist.nfCalBuffer[i] = AR5212_CCA_MAX_GOOD_VALUE;
1202 }
1203
1204 /*
1205  * Add a noise floor value to the ring buffer.
1206  */
1207 static __inline void
1208 updateNFHistBuff(struct ar5212NfCalHist *h, int16_t nf)
1209 {
1210         h->nfCalBuffer[h->currIndex] = nf;
1211         if (++h->currIndex >= AR512_NF_CAL_HIST_MAX)
1212                 h->currIndex = 0;
1213 }       
1214
1215 /*
1216  * Return the median noise floor value in the ring buffer.
1217  */
1218 int16_t 
1219 ar5212GetNfHistMid(const int16_t calData[AR512_NF_CAL_HIST_MAX])
1220 {
1221         int16_t sort[AR512_NF_CAL_HIST_MAX];
1222         int i, j;
1223
1224         OS_MEMCPY(sort, calData, AR512_NF_CAL_HIST_MAX*sizeof(int16_t));
1225         for (i = 0; i < AR512_NF_CAL_HIST_MAX-1; i ++) {
1226                 for (j = 1; j < AR512_NF_CAL_HIST_MAX-i; j ++) {
1227                         if (sort[j] > sort[j-1]) {
1228                                 int16_t nf = sort[j];
1229                                 sort[j] = sort[j-1];
1230                                 sort[j-1] = nf;
1231                         }
1232                 }
1233         }
1234         return sort[(AR512_NF_CAL_HIST_MAX-1)>>1];
1235 }
1236
1237 /*
1238  * Read the NF and check it against the noise floor threshhold
1239  */
1240 int16_t
1241 ar5212GetNf(struct ath_hal *ah, struct ieee80211_channel *chan)
1242 {
1243         struct ath_hal_5212 *ahp = AH5212(ah);
1244         struct ar5212NfCalHist *h = &ahp->ah_nfCalHist;
1245         HAL_CHANNEL_INTERNAL *ichan = ath_hal_checkchannel(ah, chan);
1246         int16_t nf, nfThresh;
1247         int32_t val;
1248
1249         if (OS_REG_READ(ah, AR_PHY_AGC_CONTROL) & AR_PHY_AGC_CONTROL_NF) {
1250                 HALDEBUG(ah, HAL_DEBUG_ANY,
1251                     "%s: NF did not complete in calibration window\n", __func__);
1252                 ichan->rawNoiseFloor = h->privNF;       /* most recent value */
1253                 return ichan->rawNoiseFloor;
1254         }
1255
1256         /*
1257          * Finished NF cal, check against threshold.
1258          */
1259         nf = ar5212GetNoiseFloor(ah);
1260         if (getNoiseFloorThresh(ah, chan, &nfThresh)) {
1261                 if (nf > nfThresh) {
1262                         HALDEBUG(ah, HAL_DEBUG_ANY,
1263                             "%s: noise floor failed detected; detected %u, "
1264                             "threshold %u\n", __func__, nf, nfThresh);
1265                         /*
1266                          * NB: Don't discriminate 2.4 vs 5Ghz, if this
1267                          *     happens it indicates a problem regardless
1268                          *     of the band.
1269                          */
1270                         chan->ic_state |= IEEE80211_CHANSTATE_CWINT;
1271                         nf = 0;
1272                 }
1273         } else
1274                 nf = 0;
1275
1276         /*
1277          * Pass through histogram and write median value as
1278          * calculated from the accrued window.  We require a
1279          * full window of in-range values to be seen before we
1280          * start using the history.
1281          */
1282         updateNFHistBuff(h, nf);
1283         if (h->first_run) {
1284                 if (nf < AR5212_CCA_MIN_BAD_VALUE ||
1285                     nf > AR5212_CCA_MAX_HIGH_VALUE) {
1286                         nf = AR5212_CCA_MAX_GOOD_VALUE;
1287                         h->invalidNFcount = AR512_NF_CAL_HIST_MAX;
1288                 } else if (--(h->invalidNFcount) == 0) {
1289                         h->first_run = 0;
1290                         h->privNF = nf = ar5212GetNfHistMid(h->nfCalBuffer);
1291                 } else {
1292                         nf = AR5212_CCA_MAX_GOOD_VALUE;
1293                 }
1294         } else {
1295                 h->privNF = nf = ar5212GetNfHistMid(h->nfCalBuffer);
1296         }
1297
1298         val = OS_REG_READ(ah, AR_PHY(25));
1299         val &= 0xFFFFFE00;
1300         val |= (((uint32_t)nf << 1) & 0x1FF);
1301         OS_REG_WRITE(ah, AR_PHY(25), val);
1302         OS_REG_CLR_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_ENABLE_NF);
1303         OS_REG_CLR_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NO_UPDATE_NF);
1304         OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NF);
1305
1306         if (!ath_hal_wait(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NF, 0)) {
1307 #ifdef AH_DEBUG
1308                 ath_hal_printf(ah, "%s: AGC not ready AGC_CONTROL 0x%x\n",
1309                     __func__, OS_REG_READ(ah, AR_PHY_AGC_CONTROL));
1310 #endif
1311         }
1312
1313         /*
1314          * Now load a high maxCCAPower value again so that we're
1315          * not capped by the median we just loaded
1316          */
1317         val &= 0xFFFFFE00;
1318         val |= (((uint32_t)(-50) << 1) & 0x1FF);
1319         OS_REG_WRITE(ah, AR_PHY(25), val);
1320         OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_ENABLE_NF);
1321         OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NO_UPDATE_NF);
1322         OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NF);
1323
1324         return (ichan->rawNoiseFloor = nf);
1325 }
1326
1327 /*
1328  * Set up compression configuration registers
1329  */
1330 void
1331 ar5212SetCompRegs(struct ath_hal *ah)
1332 {
1333         struct ath_hal_5212 *ahp = AH5212(ah);
1334         int i;
1335
1336         /* Check if h/w supports compression */
1337         if (!AH_PRIVATE(ah)->ah_caps.halCompressSupport)
1338                 return;
1339
1340         OS_REG_WRITE(ah, AR_DCCFG, 1);
1341
1342         OS_REG_WRITE(ah, AR_CCFG,
1343                 (AR_COMPRESSION_WINDOW_SIZE >> 8) & AR_CCFG_WIN_M);
1344
1345         OS_REG_WRITE(ah, AR_CCFG,
1346                 OS_REG_READ(ah, AR_CCFG) | AR_CCFG_MIB_INT_EN);
1347         OS_REG_WRITE(ah, AR_CCUCFG,
1348                 AR_CCUCFG_RESET_VAL | AR_CCUCFG_CATCHUP_EN);
1349
1350         OS_REG_WRITE(ah, AR_CPCOVF, 0);
1351
1352         /* reset decompression mask */
1353         for (i = 0; i < HAL_DECOMP_MASK_SIZE; i++) {
1354                 OS_REG_WRITE(ah, AR_DCM_A, i);
1355                 OS_REG_WRITE(ah, AR_DCM_D, ahp->ah_decompMask[i]);
1356         }
1357 }
1358
1359 HAL_BOOL
1360 ar5212SetAntennaSwitchInternal(struct ath_hal *ah, HAL_ANT_SETTING settings,
1361         const struct ieee80211_channel *chan)
1362 {
1363 #define ANT_SWITCH_TABLE1       AR_PHY(88)
1364 #define ANT_SWITCH_TABLE2       AR_PHY(89)
1365         struct ath_hal_5212 *ahp = AH5212(ah);
1366         const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1367         uint32_t antSwitchA, antSwitchB;
1368         int ix;
1369
1370         HALASSERT(ah->ah_magic == AR5212_MAGIC);
1371         HALASSERT(ahp->ah_phyPowerOn);
1372
1373         switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
1374         case IEEE80211_CHAN_A:
1375                 ix = 0;
1376                 break;
1377         case IEEE80211_CHAN_G:
1378         case IEEE80211_CHAN_PUREG:              /* NB: 108G */
1379                 ix = 2;
1380                 break;
1381         case IEEE80211_CHAN_B:
1382                 if (IS_2425(ah) || IS_2417(ah)) {
1383                         /* NB: Nala/Swan: 11b is handled using 11g */
1384                         ix = 2;
1385                 } else
1386                         ix = 1;
1387                 break;
1388         default:
1389                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
1390                     __func__, chan->ic_flags);
1391                 return AH_FALSE;
1392         }
1393
1394         antSwitchA =  ee->ee_antennaControl[1][ix]
1395                    | (ee->ee_antennaControl[2][ix] << 6)
1396                    | (ee->ee_antennaControl[3][ix] << 12) 
1397                    | (ee->ee_antennaControl[4][ix] << 18)
1398                    | (ee->ee_antennaControl[5][ix] << 24)
1399                    ;
1400         antSwitchB =  ee->ee_antennaControl[6][ix]
1401                    | (ee->ee_antennaControl[7][ix] << 6)
1402                    | (ee->ee_antennaControl[8][ix] << 12)
1403                    | (ee->ee_antennaControl[9][ix] << 18)
1404                    | (ee->ee_antennaControl[10][ix] << 24)
1405                    ;
1406         /*
1407          * For fixed antenna, give the same setting for both switch banks
1408          */
1409         switch (settings) {
1410         case HAL_ANT_FIXED_A:
1411                 antSwitchB = antSwitchA;
1412                 break;
1413         case HAL_ANT_FIXED_B:
1414                 antSwitchA = antSwitchB;
1415                 break;
1416         case HAL_ANT_VARIABLE:
1417                 break;
1418         default:
1419                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: bad antenna setting %u\n",
1420                     __func__, settings);
1421                 return AH_FALSE;
1422         }
1423         if (antSwitchB == antSwitchA) {
1424                 HALDEBUG(ah, HAL_DEBUG_RFPARAM,
1425                     "%s: Setting fast diversity off.\n", __func__);
1426                 OS_REG_CLR_BIT(ah,AR_PHY_CCK_DETECT, 
1427                                AR_PHY_CCK_DETECT_BB_ENABLE_ANT_FAST_DIV);
1428                 ahp->ah_diversity = AH_FALSE;
1429         } else {
1430                 HALDEBUG(ah, HAL_DEBUG_RFPARAM,
1431                     "%s: Setting fast diversity on.\n", __func__);
1432                 OS_REG_SET_BIT(ah,AR_PHY_CCK_DETECT, 
1433                                AR_PHY_CCK_DETECT_BB_ENABLE_ANT_FAST_DIV);
1434                 ahp->ah_diversity = AH_TRUE;
1435         }
1436         ahp->ah_antControl = settings;
1437
1438         OS_REG_WRITE(ah, ANT_SWITCH_TABLE1, antSwitchA);
1439         OS_REG_WRITE(ah, ANT_SWITCH_TABLE2, antSwitchB);
1440
1441         return AH_TRUE;
1442 #undef ANT_SWITCH_TABLE2
1443 #undef ANT_SWITCH_TABLE1
1444 }
1445
1446 HAL_BOOL
1447 ar5212IsSpurChannel(struct ath_hal *ah, const struct ieee80211_channel *chan)
1448 {
1449         uint16_t freq = ath_hal_gethwchannel(ah, chan);
1450         uint32_t clockFreq =
1451             ((IS_5413(ah) || IS_RAD5112_ANY(ah) || IS_2417(ah)) ? 40 : 32);
1452         return ( ((freq % clockFreq) != 0)
1453               && (((freq % clockFreq) < 10)
1454              || (((freq) % clockFreq) > 22)) );
1455 }
1456
1457 /*
1458  * Read EEPROM header info and program the device for correct operation
1459  * given the channel value.
1460  */
1461 HAL_BOOL
1462 ar5212SetBoardValues(struct ath_hal *ah, const struct ieee80211_channel *chan)
1463 {
1464 #define NO_FALSE_DETECT_BACKOFF   2
1465 #define CB22_FALSE_DETECT_BACKOFF 6
1466 #define AR_PHY_BIS(_ah, _reg, _mask, _val) \
1467         OS_REG_WRITE(_ah, AR_PHY(_reg), \
1468                 (OS_REG_READ(_ah, AR_PHY(_reg)) & _mask) | (_val));
1469         struct ath_hal_5212 *ahp = AH5212(ah);
1470         const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1471         int arrayMode, falseDectectBackoff;
1472         int is2GHz = IEEE80211_IS_CHAN_2GHZ(chan);
1473         HAL_CHANNEL_INTERNAL *ichan = ath_hal_checkchannel(ah, chan);
1474         int8_t adcDesiredSize, pgaDesiredSize;
1475         uint16_t switchSettling, txrxAtten, rxtxMargin;
1476         int iCoff, qCoff;
1477
1478         HALASSERT(ah->ah_magic == AR5212_MAGIC);
1479
1480         switch (chan->ic_flags & IEEE80211_CHAN_ALLTURBOFULL) {
1481         case IEEE80211_CHAN_A:
1482         case IEEE80211_CHAN_ST:
1483                 arrayMode = headerInfo11A;
1484                 if (!IS_RAD5112_ANY(ah) && !IS_2413(ah) && !IS_5413(ah))
1485                         OS_REG_RMW_FIELD(ah, AR_PHY_FRAME_CTL,
1486                                 AR_PHY_FRAME_CTL_TX_CLIP,
1487                                 ahp->ah_gainValues.currStep->paramVal[GP_TXCLIP]);
1488                 break;
1489         case IEEE80211_CHAN_B:
1490                 arrayMode = headerInfo11B;
1491                 break;
1492         case IEEE80211_CHAN_G:
1493         case IEEE80211_CHAN_108G:
1494                 arrayMode = headerInfo11G;
1495                 break;
1496         default:
1497                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
1498                     __func__, chan->ic_flags);
1499                 return AH_FALSE;
1500         }
1501
1502         /* Set the antenna register(s) correctly for the chip revision */
1503         AR_PHY_BIS(ah, 68, 0xFFFFFC06,
1504                 (ee->ee_antennaControl[0][arrayMode] << 4) | 0x1);
1505
1506         ar5212SetAntennaSwitchInternal(ah, ahp->ah_antControl, chan);
1507
1508         /* Set the Noise Floor Thresh on ar5211 devices */
1509         OS_REG_WRITE(ah, AR_PHY(90),
1510                 (ee->ee_noiseFloorThresh[arrayMode] & 0x1FF)
1511                 | (1 << 9));
1512
1513         if (ee->ee_version >= AR_EEPROM_VER5_0 && IEEE80211_IS_CHAN_TURBO(chan)) {
1514                 switchSettling = ee->ee_switchSettlingTurbo[is2GHz];
1515                 adcDesiredSize = ee->ee_adcDesiredSizeTurbo[is2GHz];
1516                 pgaDesiredSize = ee->ee_pgaDesiredSizeTurbo[is2GHz];
1517                 txrxAtten = ee->ee_txrxAttenTurbo[is2GHz];
1518                 rxtxMargin = ee->ee_rxtxMarginTurbo[is2GHz];
1519         } else {
1520                 switchSettling = ee->ee_switchSettling[arrayMode];
1521                 adcDesiredSize = ee->ee_adcDesiredSize[arrayMode];
1522                 pgaDesiredSize = ee->ee_pgaDesiredSize[is2GHz];
1523                 txrxAtten = ee->ee_txrxAtten[is2GHz];
1524                 rxtxMargin = ee->ee_rxtxMargin[is2GHz];
1525         }
1526
1527         OS_REG_RMW_FIELD(ah, AR_PHY_SETTLING, 
1528                          AR_PHY_SETTLING_SWITCH, switchSettling);
1529         OS_REG_RMW_FIELD(ah, AR_PHY_DESIRED_SZ,
1530                          AR_PHY_DESIRED_SZ_ADC, adcDesiredSize);
1531         OS_REG_RMW_FIELD(ah, AR_PHY_DESIRED_SZ,
1532                          AR_PHY_DESIRED_SZ_PGA, pgaDesiredSize);
1533         OS_REG_RMW_FIELD(ah, AR_PHY_RXGAIN,
1534                          AR_PHY_RXGAIN_TXRX_ATTEN, txrxAtten);
1535         OS_REG_WRITE(ah, AR_PHY(13),
1536                 (ee->ee_txEndToXPAOff[arrayMode] << 24)
1537                 | (ee->ee_txEndToXPAOff[arrayMode] << 16)
1538                 | (ee->ee_txFrameToXPAOn[arrayMode] << 8)
1539                 | ee->ee_txFrameToXPAOn[arrayMode]);
1540         AR_PHY_BIS(ah, 10, 0xFFFF00FF,
1541                 ee->ee_txEndToXLNAOn[arrayMode] << 8);
1542         AR_PHY_BIS(ah, 25, 0xFFF80FFF,
1543                 (ee->ee_thresh62[arrayMode] << 12) & 0x7F000);
1544
1545         /*
1546          * False detect backoff - suspected 32 MHz spur causes false
1547          * detects in OFDM, causing Tx Hangs.  Decrease weak signal
1548          * sensitivity for this card.
1549          */
1550         falseDectectBackoff = NO_FALSE_DETECT_BACKOFF;
1551         if (ee->ee_version < AR_EEPROM_VER3_3) {
1552                 /* XXX magic number */
1553                 if (AH_PRIVATE(ah)->ah_subvendorid == 0x1022 &&
1554                     IEEE80211_IS_CHAN_OFDM(chan))
1555                         falseDectectBackoff += CB22_FALSE_DETECT_BACKOFF;
1556         } else {
1557                 if (ar5212IsSpurChannel(ah, chan))
1558                         falseDectectBackoff += ee->ee_falseDetectBackoff[arrayMode];
1559         }
1560         AR_PHY_BIS(ah, 73, 0xFFFFFF01, (falseDectectBackoff << 1) & 0xFE);
1561
1562         if (ichan->privFlags & CHANNEL_IQVALID) {
1563                 iCoff = ichan->iCoff;
1564                 qCoff = ichan->qCoff;
1565         } else {
1566                 iCoff = ee->ee_iqCalI[is2GHz];
1567                 qCoff = ee->ee_iqCalQ[is2GHz];
1568         }
1569
1570         /* write previous IQ results */
1571         OS_REG_RMW_FIELD(ah, AR_PHY_TIMING_CTRL4,
1572                 AR_PHY_TIMING_CTRL4_IQCORR_Q_I_COFF, iCoff);
1573         OS_REG_RMW_FIELD(ah, AR_PHY_TIMING_CTRL4,
1574                 AR_PHY_TIMING_CTRL4_IQCORR_Q_Q_COFF, qCoff);
1575         OS_REG_SET_BIT(ah, AR_PHY_TIMING_CTRL4,
1576                 AR_PHY_TIMING_CTRL4_IQCORR_ENABLE);
1577
1578         if (ee->ee_version >= AR_EEPROM_VER4_1) {
1579                 if (!IEEE80211_IS_CHAN_108G(chan) || ee->ee_version >= AR_EEPROM_VER5_0)
1580                         OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ,
1581                                 AR_PHY_GAIN_2GHZ_RXTX_MARGIN, rxtxMargin);
1582         }
1583         if (ee->ee_version >= AR_EEPROM_VER5_1) {
1584                 /* for now always disabled */
1585                 OS_REG_WRITE(ah,  AR_PHY_HEAVY_CLIP_ENABLE,  0);
1586         }
1587
1588         return AH_TRUE;
1589 #undef AR_PHY_BIS
1590 #undef NO_FALSE_DETECT_BACKOFF
1591 #undef CB22_FALSE_DETECT_BACKOFF
1592 }
1593
1594 /*
1595  * Apply Spur Immunity to Boards that require it.
1596  * Applies only to OFDM RX operation.
1597  */
1598
1599 void
1600 ar5212SetSpurMitigation(struct ath_hal *ah,
1601         const struct ieee80211_channel *chan)
1602 {
1603         uint32_t pilotMask[2] = {0, 0}, binMagMask[4] = {0, 0, 0 , 0};
1604         uint16_t i, finalSpur, curChanAsSpur, binWidth = 0, spurDetectWidth, spurChan;
1605         int32_t spurDeltaPhase = 0, spurFreqSd = 0, spurOffset, binOffsetNumT16, curBinOffset;
1606         int16_t numBinOffsets;
1607         static const uint16_t magMapFor4[4] = {1, 2, 2, 1};
1608         static const uint16_t magMapFor3[3] = {1, 2, 1};
1609         const uint16_t *pMagMap;
1610         HAL_BOOL is2GHz = IEEE80211_IS_CHAN_2GHZ(chan);
1611         HAL_CHANNEL_INTERNAL *ichan = ath_hal_checkchannel(ah, chan);
1612         uint32_t val;
1613
1614 #define CHAN_TO_SPUR(_f, _freq)   ( ((_freq) - ((_f) ? 2300 : 4900)) * 10 )
1615         if (IS_2417(ah)) {
1616                 HALDEBUG(ah, HAL_DEBUG_RFPARAM, "%s: no spur mitigation\n",
1617                     __func__);
1618                 return;
1619         }
1620
1621         curChanAsSpur = CHAN_TO_SPUR(is2GHz, ichan->channel);
1622
1623         if (ichan->mainSpur) {
1624                 /* Pull out the saved spur value */
1625                 finalSpur = ichan->mainSpur;
1626         } else {
1627                 /*
1628                  * Check if spur immunity should be performed for this channel
1629                  * Should only be performed once per channel and then saved
1630                  */
1631                 finalSpur = AR_NO_SPUR;
1632                 spurDetectWidth = HAL_SPUR_CHAN_WIDTH;
1633                 if (IEEE80211_IS_CHAN_TURBO(chan))
1634                         spurDetectWidth *= 2;
1635
1636                 /* Decide if any spur affects the current channel */
1637                 for (i = 0; i < AR_EEPROM_MODAL_SPURS; i++) {
1638                         spurChan = ath_hal_getSpurChan(ah, i, is2GHz);
1639                         if (spurChan == AR_NO_SPUR) {
1640                                 break;
1641                         }
1642                         if ((curChanAsSpur - spurDetectWidth <= (spurChan & HAL_SPUR_VAL_MASK)) &&
1643                             (curChanAsSpur + spurDetectWidth >= (spurChan & HAL_SPUR_VAL_MASK))) {
1644                                 finalSpur = spurChan & HAL_SPUR_VAL_MASK;
1645                                 break;
1646                         }
1647                 }
1648                 /* Save detected spur (or no spur) for this channel */
1649                 ichan->mainSpur = finalSpur;
1650         }
1651
1652         /* Write spur immunity data */
1653         if (finalSpur == AR_NO_SPUR) {
1654                 /* Disable Spur Immunity Regs if they appear set */
1655                 if (OS_REG_READ(ah, AR_PHY_TIMING_CTRL4) & AR_PHY_TIMING_CTRL4_ENABLE_SPUR_FILTER) {
1656                         /* Clear Spur Delta Phase, Spur Freq, and enable bits */
1657                         OS_REG_RMW_FIELD(ah, AR_PHY_MASK_CTL, AR_PHY_MASK_CTL_RATE, 0);
1658                         val = OS_REG_READ(ah, AR_PHY_TIMING_CTRL4);
1659                         val &= ~(AR_PHY_TIMING_CTRL4_ENABLE_SPUR_FILTER |
1660                                  AR_PHY_TIMING_CTRL4_ENABLE_CHAN_MASK |
1661                                  AR_PHY_TIMING_CTRL4_ENABLE_PILOT_MASK);
1662                         OS_REG_WRITE(ah, AR_PHY_MASK_CTL, val);
1663                         OS_REG_WRITE(ah, AR_PHY_TIMING11, 0);
1664
1665                         /* Clear pilot masks */
1666                         OS_REG_WRITE(ah, AR_PHY_TIMING7, 0);
1667                         OS_REG_RMW_FIELD(ah, AR_PHY_TIMING8, AR_PHY_TIMING8_PILOT_MASK_2, 0);
1668                         OS_REG_WRITE(ah, AR_PHY_TIMING9, 0);
1669                         OS_REG_RMW_FIELD(ah, AR_PHY_TIMING10, AR_PHY_TIMING10_PILOT_MASK_2, 0);
1670
1671                         /* Clear magnitude masks */
1672                         OS_REG_WRITE(ah, AR_PHY_BIN_MASK_1, 0);
1673                         OS_REG_WRITE(ah, AR_PHY_BIN_MASK_2, 0);
1674                         OS_REG_WRITE(ah, AR_PHY_BIN_MASK_3, 0);
1675                         OS_REG_RMW_FIELD(ah, AR_PHY_MASK_CTL, AR_PHY_MASK_CTL_MASK_4, 0);
1676                         OS_REG_WRITE(ah, AR_PHY_BIN_MASK2_1, 0);
1677                         OS_REG_WRITE(ah, AR_PHY_BIN_MASK2_2, 0);
1678                         OS_REG_WRITE(ah, AR_PHY_BIN_MASK2_3, 0);
1679                         OS_REG_RMW_FIELD(ah, AR_PHY_BIN_MASK2_4, AR_PHY_BIN_MASK2_4_MASK_4, 0);
1680                 }
1681         } else {
1682                 spurOffset = finalSpur - curChanAsSpur;
1683                 /*
1684                  * Spur calculations:
1685                  * spurDeltaPhase is (spurOffsetIn100KHz / chipFrequencyIn100KHz) << 21
1686                  * spurFreqSd is (spurOffsetIn100KHz / sampleFrequencyIn100KHz) << 11
1687                  */
1688                 if (IEEE80211_IS_CHAN_TURBO(chan)) {
1689                         /* Chip Frequency & sampleFrequency are 80 MHz */
1690                         spurDeltaPhase = (spurOffset << 16) / 25;
1691                         spurFreqSd = spurDeltaPhase >> 10;
1692                         binWidth = HAL_BIN_WIDTH_TURBO_100HZ;
1693                 } else if (IEEE80211_IS_CHAN_G(chan)) {
1694                         /* Chip Frequency is 44MHz, sampleFrequency is 40 MHz */
1695                         spurFreqSd = (spurOffset << 8) / 55;
1696                         spurDeltaPhase = (spurOffset << 17) / 25;
1697                         binWidth = HAL_BIN_WIDTH_BASE_100HZ;
1698                 } else {
1699                         HALASSERT(!IEEE80211_IS_CHAN_B(chan));
1700                         /* Chip Frequency & sampleFrequency are 40 MHz */
1701                         spurDeltaPhase = (spurOffset << 17) / 25;
1702                         spurFreqSd = spurDeltaPhase >> 10;
1703                         binWidth = HAL_BIN_WIDTH_BASE_100HZ;
1704                 }
1705
1706                 /* Compute Pilot Mask */
1707                 binOffsetNumT16 = ((spurOffset * 1000) << 4) / binWidth;
1708                 /* The spur is on a bin if it's remainder at times 16 is 0 */
1709                 if (binOffsetNumT16 & 0xF) {
1710                         numBinOffsets = 4;
1711                         pMagMap = magMapFor4;
1712                 } else {
1713                         numBinOffsets = 3;
1714                         pMagMap = magMapFor3;
1715                 }
1716                 for (i = 0; i < numBinOffsets; i++) {
1717                         if ((binOffsetNumT16 >> 4) > HAL_MAX_BINS_ALLOWED) {
1718                                 HALDEBUG(ah, HAL_DEBUG_ANY,
1719                                     "Too man bins in spur mitigation\n");
1720                                 return;
1721                         }
1722
1723                         /* Get Pilot Mask values */
1724                         curBinOffset = (binOffsetNumT16 >> 4) + i + 25;
1725                         if ((curBinOffset >= 0) && (curBinOffset <= 32)) {
1726                                 if (curBinOffset <= 25)
1727                                         pilotMask[0] |= 1 << curBinOffset;
1728                                 else if (curBinOffset >= 27)
1729                                         pilotMask[0] |= 1 << (curBinOffset - 1);
1730                         } else if ((curBinOffset >= 33) && (curBinOffset <= 52))
1731                                 pilotMask[1] |= 1 << (curBinOffset - 33);
1732
1733                         /* Get viterbi values */
1734                         if ((curBinOffset >= -1) && (curBinOffset <= 14))
1735                                 binMagMask[0] |= pMagMap[i] << (curBinOffset + 1) * 2;
1736                         else if ((curBinOffset >= 15) && (curBinOffset <= 30))
1737                                 binMagMask[1] |= pMagMap[i] << (curBinOffset - 15) * 2;
1738                         else if ((curBinOffset >= 31) && (curBinOffset <= 46))
1739                                 binMagMask[2] |= pMagMap[i] << (curBinOffset -31) * 2;
1740                         else if((curBinOffset >= 47) && (curBinOffset <= 53))
1741                                 binMagMask[3] |= pMagMap[i] << (curBinOffset -47) * 2;
1742                 }
1743
1744                 /* Write Spur Delta Phase, Spur Freq, and enable bits */
1745                 OS_REG_RMW_FIELD(ah, AR_PHY_MASK_CTL, AR_PHY_MASK_CTL_RATE, 0xFF);
1746                 val = OS_REG_READ(ah, AR_PHY_TIMING_CTRL4);
1747                 val |= (AR_PHY_TIMING_CTRL4_ENABLE_SPUR_FILTER |
1748                         AR_PHY_TIMING_CTRL4_ENABLE_CHAN_MASK | 
1749                         AR_PHY_TIMING_CTRL4_ENABLE_PILOT_MASK);
1750                 OS_REG_WRITE(ah, AR_PHY_TIMING_CTRL4, val);
1751                 OS_REG_WRITE(ah, AR_PHY_TIMING11, AR_PHY_TIMING11_USE_SPUR_IN_AGC |             
1752                              SM(spurFreqSd, AR_PHY_TIMING11_SPUR_FREQ_SD) |
1753                              SM(spurDeltaPhase, AR_PHY_TIMING11_SPUR_DELTA_PHASE));
1754
1755                 /* Write pilot masks */
1756                 OS_REG_WRITE(ah, AR_PHY_TIMING7, pilotMask[0]);
1757                 OS_REG_RMW_FIELD(ah, AR_PHY_TIMING8, AR_PHY_TIMING8_PILOT_MASK_2, pilotMask[1]);
1758                 OS_REG_WRITE(ah, AR_PHY_TIMING9, pilotMask[0]);
1759                 OS_REG_RMW_FIELD(ah, AR_PHY_TIMING10, AR_PHY_TIMING10_PILOT_MASK_2, pilotMask[1]);
1760
1761                 /* Write magnitude masks */
1762                 OS_REG_WRITE(ah, AR_PHY_BIN_MASK_1, binMagMask[0]);
1763                 OS_REG_WRITE(ah, AR_PHY_BIN_MASK_2, binMagMask[1]);
1764                 OS_REG_WRITE(ah, AR_PHY_BIN_MASK_3, binMagMask[2]);
1765                 OS_REG_RMW_FIELD(ah, AR_PHY_MASK_CTL, AR_PHY_MASK_CTL_MASK_4, binMagMask[3]);
1766                 OS_REG_WRITE(ah, AR_PHY_BIN_MASK2_1, binMagMask[0]);
1767                 OS_REG_WRITE(ah, AR_PHY_BIN_MASK2_2, binMagMask[1]);
1768                 OS_REG_WRITE(ah, AR_PHY_BIN_MASK2_3, binMagMask[2]);
1769                 OS_REG_RMW_FIELD(ah, AR_PHY_BIN_MASK2_4, AR_PHY_BIN_MASK2_4_MASK_4, binMagMask[3]);
1770         }
1771 #undef CHAN_TO_SPUR
1772 }
1773
1774
1775 /*
1776  * Delta slope coefficient computation.
1777  * Required for OFDM operation.
1778  */
1779 void
1780 ar5212SetDeltaSlope(struct ath_hal *ah, const struct ieee80211_channel *chan)
1781 {
1782 #define COEF_SCALE_S 24
1783 #define INIT_CLOCKMHZSCALED     0x64000000
1784         uint16_t freq = ath_hal_gethwchannel(ah, chan);
1785         unsigned long coef_scaled, coef_exp, coef_man, ds_coef_exp, ds_coef_man;
1786         unsigned long clockMhzScaled = INIT_CLOCKMHZSCALED;
1787
1788         if (IEEE80211_IS_CHAN_TURBO(chan))
1789                 clockMhzScaled *= 2;
1790         /* half and quarter rate can divide the scaled clock by 2 or 4 respectively */
1791         /* scale for selected channel bandwidth */ 
1792         if (IEEE80211_IS_CHAN_HALF(chan)) {
1793                 clockMhzScaled = clockMhzScaled >> 1;
1794         } else if (IEEE80211_IS_CHAN_QUARTER(chan)) {
1795                 clockMhzScaled = clockMhzScaled >> 2;
1796         } 
1797
1798         /*
1799          * ALGO -> coef = 1e8/fcarrier*fclock/40;
1800          * scaled coef to provide precision for this floating calculation 
1801          */
1802         coef_scaled = clockMhzScaled / freq;
1803
1804         /*
1805          * ALGO -> coef_exp = 14-floor(log2(coef)); 
1806          * floor(log2(x)) is the highest set bit position
1807          */
1808         for (coef_exp = 31; coef_exp > 0; coef_exp--)
1809                 if ((coef_scaled >> coef_exp) & 0x1)
1810                         break;
1811         /* A coef_exp of 0 is a legal bit position but an unexpected coef_exp */
1812         HALASSERT(coef_exp);
1813         coef_exp = 14 - (coef_exp - COEF_SCALE_S);
1814
1815         /*
1816          * ALGO -> coef_man = floor(coef* 2^coef_exp+0.5);
1817          * The coefficient is already shifted up for scaling
1818          */
1819         coef_man = coef_scaled + (1 << (COEF_SCALE_S - coef_exp - 1));
1820         ds_coef_man = coef_man >> (COEF_SCALE_S - coef_exp);
1821         ds_coef_exp = coef_exp - 16;
1822
1823         OS_REG_RMW_FIELD(ah, AR_PHY_TIMING3,
1824                 AR_PHY_TIMING3_DSC_MAN, ds_coef_man);
1825         OS_REG_RMW_FIELD(ah, AR_PHY_TIMING3,
1826                 AR_PHY_TIMING3_DSC_EXP, ds_coef_exp);
1827 #undef INIT_CLOCKMHZSCALED
1828 #undef COEF_SCALE_S
1829 }
1830
1831 /*
1832  * Set a limit on the overall output power.  Used for dynamic
1833  * transmit power control and the like.
1834  *
1835  * NB: limit is in units of 0.5 dbM.
1836  */
1837 HAL_BOOL
1838 ar5212SetTxPowerLimit(struct ath_hal *ah, uint32_t limit)
1839 {
1840         /* XXX blech, construct local writable copy */
1841         struct ieee80211_channel dummy = *AH_PRIVATE(ah)->ah_curchan;
1842         uint16_t dummyXpdGains[2];
1843         HAL_BOOL isBmode;
1844
1845         SAVE_CCK(ah, &dummy, isBmode);
1846         AH_PRIVATE(ah)->ah_powerLimit = AH_MIN(limit, MAX_RATE_POWER);
1847         return ar5212SetTransmitPower(ah, &dummy, dummyXpdGains);
1848 }
1849
1850 /*
1851  * Set the transmit power in the baseband for the given
1852  * operating channel and mode.
1853  */
1854 HAL_BOOL
1855 ar5212SetTransmitPower(struct ath_hal *ah,
1856         const struct ieee80211_channel *chan, uint16_t *rfXpdGain)
1857 {
1858 #define POW_OFDM(_r, _s)        (((0 & 1)<< ((_s)+6)) | (((_r) & 0x3f) << (_s)))
1859 #define POW_CCK(_r, _s)         (((_r) & 0x3f) << (_s))
1860         static const uint16_t tpcScaleReductionTable[5] =
1861                 { 0, 3, 6, 9, MAX_RATE_POWER };
1862         struct ath_hal_5212 *ahp = AH5212(ah);
1863         uint16_t freq = ath_hal_gethwchannel(ah, chan);
1864         const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1865         int16_t minPower, maxPower, tpcInDb, powerLimit;
1866         int i;
1867
1868         HALASSERT(ah->ah_magic == AR5212_MAGIC);
1869
1870         OS_MEMZERO(ahp->ah_pcdacTable, ahp->ah_pcdacTableSize);
1871         OS_MEMZERO(ahp->ah_ratesArray, sizeof(ahp->ah_ratesArray));
1872
1873         powerLimit = AH_MIN(MAX_RATE_POWER, AH_PRIVATE(ah)->ah_powerLimit);
1874         if (powerLimit >= MAX_RATE_POWER || powerLimit == 0)
1875                 tpcInDb = tpcScaleReductionTable[AH_PRIVATE(ah)->ah_tpScale];
1876         else
1877                 tpcInDb = 0;
1878         if (!ar5212SetRateTable(ah, chan, tpcInDb, powerLimit,
1879                                 AH_TRUE, &minPower, &maxPower)) {
1880                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: unable to set rate table\n",
1881                     __func__);
1882                 return AH_FALSE;
1883         }
1884         if (!ahp->ah_rfHal->setPowerTable(ah,
1885                 &minPower, &maxPower, chan, rfXpdGain)) {
1886                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: unable to set power table\n",
1887                     __func__);
1888                 return AH_FALSE;
1889         }
1890
1891         /* 
1892          * Adjust XR power/rate up by 2 dB to account for greater peak
1893          * to avg ratio - except in newer avg power designs
1894          */
1895         if (!IS_2413(ah) && !IS_5413(ah))
1896                 ahp->ah_ratesArray[15] += 4;
1897         /* 
1898          * txPowerIndexOffset is set by the SetPowerTable() call -
1899          *  adjust the rate table 
1900          */
1901         for (i = 0; i < NELEM(ahp->ah_ratesArray); i++) {
1902                 ahp->ah_ratesArray[i] += ahp->ah_txPowerIndexOffset;
1903                 if (ahp->ah_ratesArray[i] > 63) 
1904                         ahp->ah_ratesArray[i] = 63;
1905         }
1906
1907         if (ee->ee_eepMap < 2) {
1908                 /* 
1909                  * Correct gain deltas for 5212 G operation -
1910                  * Removed with revised chipset
1911                  */
1912                 if (AH_PRIVATE(ah)->ah_phyRev < AR_PHY_CHIP_ID_REV_2 &&
1913                     IEEE80211_IS_CHAN_G(chan)) {
1914                         uint16_t cckOfdmPwrDelta;
1915
1916                         if (freq == 2484) 
1917                                 cckOfdmPwrDelta = SCALE_OC_DELTA(
1918                                         ee->ee_cckOfdmPwrDelta - 
1919                                         ee->ee_scaledCh14FilterCckDelta);
1920                         else 
1921                                 cckOfdmPwrDelta = SCALE_OC_DELTA(
1922                                         ee->ee_cckOfdmPwrDelta);
1923                         ar5212CorrectGainDelta(ah, cckOfdmPwrDelta);
1924                 }
1925                 /* 
1926                  * Finally, write the power values into the
1927                  * baseband power table
1928                  */
1929                 for (i = 0; i < (PWR_TABLE_SIZE/2); i++) {
1930                         OS_REG_WRITE(ah, AR_PHY_PCDAC_TX_POWER(i),
1931                                  ((((ahp->ah_pcdacTable[2*i + 1] << 8) | 0xff) & 0xffff) << 16)
1932                                 | (((ahp->ah_pcdacTable[2*i]     << 8) | 0xff) & 0xffff)
1933                         );
1934                 }
1935         }
1936
1937         /* Write the OFDM power per rate set */
1938         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE1, 
1939                 POW_OFDM(ahp->ah_ratesArray[3], 24)
1940               | POW_OFDM(ahp->ah_ratesArray[2], 16)
1941               | POW_OFDM(ahp->ah_ratesArray[1],  8)
1942               | POW_OFDM(ahp->ah_ratesArray[0],  0)
1943         );
1944         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE2, 
1945                 POW_OFDM(ahp->ah_ratesArray[7], 24)
1946               | POW_OFDM(ahp->ah_ratesArray[6], 16)
1947               | POW_OFDM(ahp->ah_ratesArray[5],  8)
1948               | POW_OFDM(ahp->ah_ratesArray[4],  0)
1949         );
1950
1951         /* Write the CCK power per rate set */
1952         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE3,
1953                 POW_CCK(ahp->ah_ratesArray[10], 24)
1954               | POW_CCK(ahp->ah_ratesArray[9],  16)
1955               | POW_CCK(ahp->ah_ratesArray[15],  8)     /* XR target power */
1956               | POW_CCK(ahp->ah_ratesArray[8],   0)
1957         );
1958         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE4,
1959                 POW_CCK(ahp->ah_ratesArray[14], 24)
1960               | POW_CCK(ahp->ah_ratesArray[13], 16)
1961               | POW_CCK(ahp->ah_ratesArray[12],  8)
1962               | POW_CCK(ahp->ah_ratesArray[11],  0)
1963         );
1964
1965         /*
1966          * Set max power to 30 dBm and, optionally,
1967          * enable TPC in tx descriptors.
1968          */
1969         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE_MAX, MAX_RATE_POWER |
1970                 (ahp->ah_tpcEnabled ? AR_PHY_POWER_TX_RATE_MAX_TPC_ENABLE : 0));
1971
1972         return AH_TRUE;
1973 #undef POW_CCK
1974 #undef POW_OFDM
1975 }
1976
1977 /*
1978  * Sets the transmit power in the baseband for the given
1979  * operating channel and mode.
1980  */
1981 static HAL_BOOL
1982 ar5212SetRateTable(struct ath_hal *ah, const struct ieee80211_channel *chan,
1983         int16_t tpcScaleReduction, int16_t powerLimit, HAL_BOOL commit,
1984         int16_t *pMinPower, int16_t *pMaxPower)
1985 {
1986         struct ath_hal_5212 *ahp = AH5212(ah);
1987         uint16_t freq = ath_hal_gethwchannel(ah, chan);
1988         const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1989         uint16_t *rpow = ahp->ah_ratesArray;
1990         uint16_t twiceMaxEdgePower = MAX_RATE_POWER;
1991         uint16_t twiceMaxEdgePowerCck = MAX_RATE_POWER;
1992         uint16_t twiceMaxRDPower = MAX_RATE_POWER;
1993         int i;
1994         uint8_t cfgCtl;
1995         int8_t twiceAntennaGain, twiceAntennaReduction;
1996         const RD_EDGES_POWER *rep;
1997         TRGT_POWER_INFO targetPowerOfdm, targetPowerCck;
1998         int16_t scaledPower, maxAvailPower = 0;
1999         int16_t r13, r9, r7, r0;
2000
2001         HALASSERT(ah->ah_magic == AR5212_MAGIC);
2002
2003         twiceMaxRDPower = chan->ic_maxregpower * 2;
2004         *pMaxPower = -MAX_RATE_POWER;
2005         *pMinPower = MAX_RATE_POWER;
2006
2007         /* Get conformance test limit maximum for this channel */
2008         cfgCtl = ath_hal_getctl(ah, chan);
2009         for (i = 0; i < ee->ee_numCtls; i++) {
2010                 uint16_t twiceMinEdgePower;
2011
2012                 if (ee->ee_ctl[i] == 0)
2013                         continue;
2014                 if (ee->ee_ctl[i] == cfgCtl ||
2015                     cfgCtl == ((ee->ee_ctl[i] & CTL_MODE_M) | SD_NO_CTL)) {
2016                         rep = &ee->ee_rdEdgesPower[i * NUM_EDGES];
2017                         twiceMinEdgePower = ar5212GetMaxEdgePower(freq, rep);
2018                         if ((cfgCtl & ~CTL_MODE_M) == SD_NO_CTL) {
2019                                 /* Find the minimum of all CTL edge powers that apply to this channel */
2020                                 twiceMaxEdgePower = AH_MIN(twiceMaxEdgePower, twiceMinEdgePower);
2021                         } else {
2022                                 twiceMaxEdgePower = twiceMinEdgePower;
2023                                 break;
2024                         }
2025                 }
2026         }
2027
2028         if (IEEE80211_IS_CHAN_G(chan)) {
2029                 /* Check for a CCK CTL for 11G CCK powers */
2030                 cfgCtl = (cfgCtl & ~CTL_MODE_M) | CTL_11B;
2031                 for (i = 0; i < ee->ee_numCtls; i++) {
2032                         uint16_t twiceMinEdgePowerCck;
2033
2034                         if (ee->ee_ctl[i] == 0)
2035                                 continue;
2036                         if (ee->ee_ctl[i] == cfgCtl ||
2037                             cfgCtl == ((ee->ee_ctl[i] & CTL_MODE_M) | SD_NO_CTL)) {
2038                                 rep = &ee->ee_rdEdgesPower[i * NUM_EDGES];
2039                                 twiceMinEdgePowerCck = ar5212GetMaxEdgePower(freq, rep);
2040                                 if ((cfgCtl & ~CTL_MODE_M) == SD_NO_CTL) {
2041                                         /* Find the minimum of all CTL edge powers that apply to this channel */
2042                                         twiceMaxEdgePowerCck = AH_MIN(twiceMaxEdgePowerCck, twiceMinEdgePowerCck);
2043                                 } else {
2044                                         twiceMaxEdgePowerCck = twiceMinEdgePowerCck;
2045                                         break;
2046                                 }
2047                         }
2048                 }
2049         } else {
2050                 /* Set the 11B cck edge power to the one found before */
2051                 twiceMaxEdgePowerCck = twiceMaxEdgePower;
2052         }
2053
2054         /* Get Antenna Gain reduction */
2055         if (IEEE80211_IS_CHAN_5GHZ(chan)) {
2056                 ath_hal_eepromGet(ah, AR_EEP_ANTGAINMAX_5, &twiceAntennaGain);
2057         } else {
2058                 ath_hal_eepromGet(ah, AR_EEP_ANTGAINMAX_2, &twiceAntennaGain);
2059         }
2060         twiceAntennaReduction =
2061                 ath_hal_getantennareduction(ah, chan, twiceAntennaGain);
2062
2063         if (IEEE80211_IS_CHAN_OFDM(chan)) {
2064                 /* Get final OFDM target powers */
2065                 if (IEEE80211_IS_CHAN_2GHZ(chan)) { 
2066                         ar5212GetTargetPowers(ah, chan, ee->ee_trgtPwr_11g,
2067                                 ee->ee_numTargetPwr_11g, &targetPowerOfdm);
2068                 } else {
2069                         ar5212GetTargetPowers(ah, chan, ee->ee_trgtPwr_11a,
2070                                 ee->ee_numTargetPwr_11a, &targetPowerOfdm);
2071                 }
2072
2073                 /* Get Maximum OFDM power */
2074                 /* Minimum of target and edge powers */
2075                 scaledPower = AH_MIN(twiceMaxEdgePower,
2076                                 twiceMaxRDPower - twiceAntennaReduction);
2077
2078                 /*
2079                  * If turbo is set, reduce power to keep power
2080                  * consumption under 2 Watts.  Note that we always do
2081                  * this unless specially configured.  Then we limit
2082                  * power only for non-AP operation.
2083                  */
2084                 if (IEEE80211_IS_CHAN_TURBO(chan)
2085 #ifdef AH_ENABLE_AP_SUPPORT
2086                     && AH_PRIVATE(ah)->ah_opmode != HAL_M_HOSTAP
2087 #endif
2088                 ) {
2089                         /*
2090                          * If turbo is set, reduce power to keep power
2091                          * consumption under 2 Watts
2092                          */
2093                         if (ee->ee_version >= AR_EEPROM_VER3_1)
2094                                 scaledPower = AH_MIN(scaledPower,
2095                                         ee->ee_turbo2WMaxPower5);
2096                         /*
2097                          * EEPROM version 4.0 added an additional
2098                          * constraint on 2.4GHz channels.
2099                          */
2100                         if (ee->ee_version >= AR_EEPROM_VER4_0 &&
2101                             IEEE80211_IS_CHAN_2GHZ(chan))
2102                                 scaledPower = AH_MIN(scaledPower,
2103                                         ee->ee_turbo2WMaxPower2);
2104                 }
2105
2106                 maxAvailPower = AH_MIN(scaledPower,
2107                                         targetPowerOfdm.twicePwr6_24);
2108
2109                 /* Reduce power by max regulatory domain allowed restrictions */
2110                 scaledPower = maxAvailPower - (tpcScaleReduction * 2);
2111                 scaledPower = (scaledPower < 0) ? 0 : scaledPower;
2112                 scaledPower = AH_MIN(scaledPower, powerLimit);
2113
2114                 if (commit) {
2115                         /* Set OFDM rates 9, 12, 18, 24 */
2116                         r0 = rpow[0] = rpow[1] = rpow[2] = rpow[3] = rpow[4] = scaledPower;
2117
2118                         /* Set OFDM rates 36, 48, 54, XR */
2119                         rpow[5] = AH_MIN(rpow[0], targetPowerOfdm.twicePwr36);
2120                         rpow[6] = AH_MIN(rpow[0], targetPowerOfdm.twicePwr48);
2121                         r7 = rpow[7] = AH_MIN(rpow[0], targetPowerOfdm.twicePwr54);
2122
2123                         if (ee->ee_version >= AR_EEPROM_VER4_0) {
2124                                 /* Setup XR target power from EEPROM */
2125                                 rpow[15] = AH_MIN(scaledPower, IEEE80211_IS_CHAN_2GHZ(chan) ?
2126                                                   ee->ee_xrTargetPower2 : ee->ee_xrTargetPower5);
2127                         } else {
2128                                 /* XR uses 6mb power */
2129                                 rpow[15] = rpow[0];
2130                         }
2131                         ahp->ah_ofdmTxPower = *pMaxPower;
2132
2133                 } else {
2134                         r0 = scaledPower;
2135                         r7 = AH_MIN(r0, targetPowerOfdm.twicePwr54);
2136                 }
2137                 *pMinPower = r7;
2138                 *pMaxPower = r0;
2139
2140                 HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2141                     "%s: MaxRD: %d TurboMax: %d MaxCTL: %d "
2142                     "TPC_Reduction %d chan=%d (0x%x) maxAvailPower=%d pwr6_24=%d, maxPower=%d\n",
2143                     __func__, twiceMaxRDPower, ee->ee_turbo2WMaxPower5,
2144                     twiceMaxEdgePower, tpcScaleReduction * 2,
2145                     chan->ic_freq, chan->ic_flags,
2146                     maxAvailPower, targetPowerOfdm.twicePwr6_24, *pMaxPower);
2147         }
2148
2149         if (IEEE80211_IS_CHAN_CCK(chan)) {
2150                 /* Get final CCK target powers */
2151                 ar5212GetTargetPowers(ah, chan, ee->ee_trgtPwr_11b,
2152                         ee->ee_numTargetPwr_11b, &targetPowerCck);
2153
2154                 /* Reduce power by max regulatory domain allowed restrictions */
2155                 scaledPower = AH_MIN(twiceMaxEdgePowerCck,
2156                         twiceMaxRDPower - twiceAntennaReduction);
2157                 if (maxAvailPower < AH_MIN(scaledPower, targetPowerCck.twicePwr6_24))
2158                         maxAvailPower = AH_MIN(scaledPower, targetPowerCck.twicePwr6_24);
2159
2160                 /* Reduce power by user selection */
2161                 scaledPower = AH_MIN(scaledPower, targetPowerCck.twicePwr6_24) - (tpcScaleReduction * 2);
2162                 scaledPower = (scaledPower < 0) ? 0 : scaledPower;
2163                 scaledPower = AH_MIN(scaledPower, powerLimit);
2164
2165                 if (commit) {
2166                         /* Set CCK rates 2L, 2S, 5.5L, 5.5S, 11L, 11S */
2167                         rpow[8]  = AH_MIN(scaledPower, targetPowerCck.twicePwr6_24);
2168                         r9 = rpow[9]  = AH_MIN(scaledPower, targetPowerCck.twicePwr36);
2169                         rpow[10] = rpow[9];
2170                         rpow[11] = AH_MIN(scaledPower, targetPowerCck.twicePwr48);
2171                         rpow[12] = rpow[11];
2172                         r13 = rpow[13] = AH_MIN(scaledPower, targetPowerCck.twicePwr54);
2173                         rpow[14] = rpow[13];
2174                 } else {
2175                         r9 = AH_MIN(scaledPower, targetPowerCck.twicePwr36);
2176                         r13 = AH_MIN(scaledPower, targetPowerCck.twicePwr54);
2177                 }
2178
2179                 /* Set min/max power based off OFDM values or initialization */
2180                 if (r13 < *pMinPower)
2181                         *pMinPower = r13;
2182                 if (r9 > *pMaxPower)
2183                         *pMaxPower = r9;
2184
2185                 HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2186                     "%s: cck: MaxRD: %d MaxCTL: %d "
2187                     "TPC_Reduction %d chan=%d (0x%x) maxAvailPower=%d pwr6_24=%d, maxPower=%d\n",
2188                     __func__, twiceMaxRDPower, twiceMaxEdgePowerCck,
2189                     tpcScaleReduction * 2, chan->ic_freq, chan->ic_flags,
2190                     maxAvailPower, targetPowerCck.twicePwr6_24, *pMaxPower);
2191         }
2192         if (commit) {
2193                 ahp->ah_tx6PowerInHalfDbm = *pMaxPower;
2194                 AH_PRIVATE(ah)->ah_maxPowerLevel = ahp->ah_tx6PowerInHalfDbm;
2195         }
2196         return AH_TRUE;
2197 }
2198
2199 HAL_BOOL
2200 ar5212GetChipPowerLimits(struct ath_hal *ah, struct ieee80211_channel *chan)
2201 {
2202         struct ath_hal_5212 *ahp = AH5212(ah);
2203 #if 0
2204         static const uint16_t tpcScaleReductionTable[5] =
2205                 { 0, 3, 6, 9, MAX_RATE_POWER };
2206         int16_t tpcInDb, powerLimit;
2207 #endif
2208         int16_t minPower, maxPower;
2209
2210         /*
2211          * Get Pier table max and min powers.
2212          */
2213         if (ahp->ah_rfHal->getChannelMaxMinPower(ah, chan, &maxPower, &minPower)) {
2214                 /* NB: rf code returns 1/4 dBm units, convert */
2215                 chan->ic_maxpower = maxPower / 2;
2216                 chan->ic_minpower = minPower / 2;
2217         } else {
2218                 HALDEBUG(ah, HAL_DEBUG_ANY,
2219                     "%s: no min/max power for %u/0x%x\n",
2220                     __func__, chan->ic_freq, chan->ic_flags);
2221                 chan->ic_maxpower = MAX_RATE_POWER;
2222                 chan->ic_minpower = 0;
2223         }
2224 #if 0
2225         /*
2226          * Now adjust to reflect any global scale and/or CTL's.
2227          * (XXX is that correct?)
2228          */
2229         powerLimit = AH_MIN(MAX_RATE_POWER, AH_PRIVATE(ah)->ah_powerLimit);
2230         if (powerLimit >= MAX_RATE_POWER || powerLimit == 0)
2231                 tpcInDb = tpcScaleReductionTable[AH_PRIVATE(ah)->ah_tpScale];
2232         else
2233                 tpcInDb = 0;
2234         if (!ar5212SetRateTable(ah, chan, tpcInDb, powerLimit,
2235                                 AH_FALSE, &minPower, &maxPower)) {
2236                 HALDEBUG(ah, HAL_DEBUG_ANY,
2237                     "%s: unable to find max/min power\n",__func__);
2238                 return AH_FALSE;
2239         }
2240         if (maxPower < chan->ic_maxpower)
2241                 chan->ic_maxpower = maxPower;
2242         if (minPower < chan->ic_minpower)
2243                 chan->ic_minpower = minPower;
2244         HALDEBUG(ah, HAL_DEBUG_RESET,
2245             "Chan %d: MaxPow = %d MinPow = %d\n",
2246             chan->ic_freq, chan->ic_maxpower, chans->ic_minpower);
2247 #endif
2248         return AH_TRUE;
2249 }
2250
2251 /*
2252  * Correct for the gain-delta between ofdm and cck mode target
2253  * powers. Write the results to the rate table and the power table.
2254  *
2255  *   Conventions :
2256  *   1. rpow[ii] is the integer value of 2*(desired power
2257  *    for the rate ii in dBm) to provide 0.5dB resolution. rate
2258  *    mapping is as following :
2259  *     [0..7]  --> ofdm 6, 9, .. 48, 54
2260  *     [8..14] --> cck 1L, 2L, 2S, .. 11L, 11S
2261  *     [15]    --> XR (all rates get the same power)
2262  *   2. powv[ii]  is the pcdac corresponding to ii/2 dBm.
2263  */
2264 static void
2265 ar5212CorrectGainDelta(struct ath_hal *ah, int twiceOfdmCckDelta)
2266 {
2267         struct ath_hal_5212 *ahp = AH5212(ah);
2268         const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
2269         int16_t ratesIndex[NELEM(ahp->ah_ratesArray)];
2270         uint16_t ii, jj, iter;
2271         int32_t cckIndex;
2272         int16_t gainDeltaAdjust;
2273
2274         HALASSERT(ah->ah_magic == AR5212_MAGIC);
2275
2276         gainDeltaAdjust = ee->ee_cckOfdmGainDelta;
2277
2278         /* make a local copy of desired powers as initial indices */
2279         OS_MEMCPY(ratesIndex, ahp->ah_ratesArray, sizeof(ratesIndex));
2280
2281         /* fix only the CCK indices */
2282         for (ii = 8; ii < 15; ii++) {
2283                 /* apply a gain_delta correction of -15 for CCK */
2284                 ratesIndex[ii] -= gainDeltaAdjust;
2285
2286                 /* Now check for contention with all ofdm target powers */
2287                 jj = 0;
2288                 iter = 0;
2289                 /* indicates not all ofdm rates checked forcontention yet */
2290                 while (jj < 16) {
2291                         if (ratesIndex[ii] < 0)
2292                                 ratesIndex[ii] = 0;
2293                         if (jj == 8) {          /* skip CCK rates */
2294                                 jj = 15;
2295                                 continue;
2296                         }
2297                         if (ratesIndex[ii] == ahp->ah_ratesArray[jj]) {
2298                                 if (ahp->ah_ratesArray[jj] == 0)
2299                                         ratesIndex[ii]++;
2300                                 else if (iter > 50) {
2301                                         /*
2302                                          * To avoid pathological case of of
2303                                          * dm target powers 0 and 0.5dBm
2304                                          */
2305                                         ratesIndex[ii]++;
2306                                 } else
2307                                         ratesIndex[ii]--;
2308                                 /* check with all rates again */
2309                                 jj = 0;
2310                                 iter++;
2311                         } else
2312                                 jj++;
2313                 }
2314                 if (ratesIndex[ii] >= PWR_TABLE_SIZE)
2315                         ratesIndex[ii] = PWR_TABLE_SIZE -1;
2316                 cckIndex = ahp->ah_ratesArray[ii] - twiceOfdmCckDelta;
2317                 if (cckIndex < 0)
2318                         cckIndex = 0;
2319
2320                 /* 
2321                  * Validate that the indexes for the powv are not
2322                  * out of bounds.
2323                  */
2324                 HALASSERT(cckIndex < PWR_TABLE_SIZE);
2325                 HALASSERT(ratesIndex[ii] < PWR_TABLE_SIZE);
2326                 ahp->ah_pcdacTable[ratesIndex[ii]] =
2327                         ahp->ah_pcdacTable[cckIndex];
2328         }
2329         /* Override rate per power table with new values */
2330         for (ii = 8; ii < 15; ii++)
2331                 ahp->ah_ratesArray[ii] = ratesIndex[ii];
2332 }
2333
2334 /*
2335  * Find the maximum conformance test limit for the given channel and CTL info
2336  */
2337 static uint16_t
2338 ar5212GetMaxEdgePower(uint16_t channel, const RD_EDGES_POWER *pRdEdgesPower)
2339 {
2340         /* temp array for holding edge channels */
2341         uint16_t tempChannelList[NUM_EDGES];
2342         uint16_t clo, chi, twiceMaxEdgePower;
2343         int i, numEdges;
2344
2345         /* Get the edge power */
2346         for (i = 0; i < NUM_EDGES; i++) {
2347                 if (pRdEdgesPower[i].rdEdge == 0)
2348                         break;
2349                 tempChannelList[i] = pRdEdgesPower[i].rdEdge;
2350         }
2351         numEdges = i;
2352
2353         ar5212GetLowerUpperValues(channel, tempChannelList,
2354                 numEdges, &clo, &chi);
2355         /* Get the index for the lower channel */
2356         for (i = 0; i < numEdges && clo != tempChannelList[i]; i++)
2357                 ;
2358         /* Is lower channel ever outside the rdEdge? */
2359         HALASSERT(i != numEdges);
2360
2361         if ((clo == chi && clo == channel) || (pRdEdgesPower[i].flag)) {
2362                 /* 
2363                  * If there's an exact channel match or an inband flag set
2364                  * on the lower channel use the given rdEdgePower 
2365                  */
2366                 twiceMaxEdgePower = pRdEdgesPower[i].twice_rdEdgePower;
2367                 HALASSERT(twiceMaxEdgePower > 0);
2368         } else
2369                 twiceMaxEdgePower = MAX_RATE_POWER;
2370         return twiceMaxEdgePower;
2371 }
2372
2373 /*
2374  * Returns interpolated or the scaled up interpolated value
2375  */
2376 static uint16_t
2377 interpolate(uint16_t target, uint16_t srcLeft, uint16_t srcRight,
2378         uint16_t targetLeft, uint16_t targetRight)
2379 {
2380         uint16_t rv;
2381         int16_t lRatio;
2382
2383         /* to get an accurate ratio, always scale, if want to scale, then don't scale back down */
2384         if ((targetLeft * targetRight) == 0)
2385                 return 0;
2386
2387         if (srcRight != srcLeft) {
2388                 /*
2389                  * Note the ratio always need to be scaled,
2390                  * since it will be a fraction.
2391                  */
2392                 lRatio = (target - srcLeft) * EEP_SCALE / (srcRight - srcLeft);
2393                 if (lRatio < 0) {
2394                     /* Return as Left target if value would be negative */
2395                     rv = targetLeft;
2396                 } else if (lRatio > EEP_SCALE) {
2397                     /* Return as Right target if Ratio is greater than 100% (SCALE) */
2398                     rv = targetRight;
2399                 } else {
2400                         rv = (lRatio * targetRight + (EEP_SCALE - lRatio) *
2401                                         targetLeft) / EEP_SCALE;
2402                 }
2403         } else {
2404                 rv = targetLeft;
2405         }
2406         return rv;
2407 }
2408
2409 /*
2410  * Return the four rates of target power for the given target power table 
2411  * channel, and number of channels
2412  */
2413 static void
2414 ar5212GetTargetPowers(struct ath_hal *ah, const struct ieee80211_channel *chan,
2415         const TRGT_POWER_INFO *powInfo,
2416         uint16_t numChannels, TRGT_POWER_INFO *pNewPower)
2417 {
2418         uint16_t freq = ath_hal_gethwchannel(ah, chan);
2419         /* temp array for holding target power channels */
2420         uint16_t tempChannelList[NUM_TEST_FREQUENCIES];
2421         uint16_t clo, chi, ixlo, ixhi;
2422         int i;
2423
2424         /* Copy the target powers into the temp channel list */
2425         for (i = 0; i < numChannels; i++)
2426                 tempChannelList[i] = powInfo[i].testChannel;
2427
2428         ar5212GetLowerUpperValues(freq, tempChannelList,
2429                 numChannels, &clo, &chi);
2430
2431         /* Get the indices for the channel */
2432         ixlo = ixhi = 0;
2433         for (i = 0; i < numChannels; i++) {
2434                 if (clo == tempChannelList[i]) {
2435                         ixlo = i;
2436                 }
2437                 if (chi == tempChannelList[i]) {
2438                         ixhi = i;
2439                         break;
2440                 }
2441         }
2442
2443         /*
2444          * Get the lower and upper channels, target powers,
2445          * and interpolate between them.
2446          */
2447         pNewPower->twicePwr6_24 = interpolate(freq, clo, chi,
2448                 powInfo[ixlo].twicePwr6_24, powInfo[ixhi].twicePwr6_24);
2449         pNewPower->twicePwr36 = interpolate(freq, clo, chi,
2450                 powInfo[ixlo].twicePwr36, powInfo[ixhi].twicePwr36);
2451         pNewPower->twicePwr48 = interpolate(freq, clo, chi,
2452                 powInfo[ixlo].twicePwr48, powInfo[ixhi].twicePwr48);
2453         pNewPower->twicePwr54 = interpolate(freq, clo, chi,
2454                 powInfo[ixlo].twicePwr54, powInfo[ixhi].twicePwr54);
2455 }
2456
2457 /*
2458  * Search a list for a specified value v that is within
2459  * EEP_DELTA of the search values.  Return the closest
2460  * values in the list above and below the desired value.
2461  * EEP_DELTA is a factional value; everything is scaled
2462  * so only integer arithmetic is used.
2463  *
2464  * NB: the input list is assumed to be sorted in ascending order
2465  */
2466 void
2467 ar5212GetLowerUpperValues(uint16_t v, uint16_t *lp, uint16_t listSize,
2468                           uint16_t *vlo, uint16_t *vhi)
2469 {
2470         uint32_t target = v * EEP_SCALE;
2471         uint16_t *ep = lp+listSize;
2472
2473         /*
2474          * Check first and last elements for out-of-bounds conditions.
2475          */
2476         if (target < (uint32_t)(lp[0] * EEP_SCALE - EEP_DELTA)) {
2477                 *vlo = *vhi = lp[0];
2478                 return;
2479         }
2480         if (target > (uint32_t)(ep[-1] * EEP_SCALE + EEP_DELTA)) {
2481                 *vlo = *vhi = ep[-1];
2482                 return;
2483         }
2484
2485         /* look for value being near or between 2 values in list */
2486         for (; lp < ep; lp++) {
2487                 /*
2488                  * If value is close to the current value of the list
2489                  * then target is not between values, it is one of the values
2490                  */
2491                 if (abs(lp[0] * EEP_SCALE - target) < EEP_DELTA) {
2492                         *vlo = *vhi = lp[0];
2493                         return;
2494                 }
2495                 /*
2496                  * Look for value being between current value and next value
2497                  * if so return these 2 values
2498                  */
2499                 if (target < (uint32_t)(lp[1] * EEP_SCALE - EEP_DELTA)) {
2500                         *vlo = lp[0];
2501                         *vhi = lp[1];
2502                         return;
2503                 }
2504         }
2505         HALASSERT(AH_FALSE);            /* should not reach here */
2506 }
2507
2508 /*
2509  * Perform analog "swizzling" of parameters into their location
2510  *
2511  * NB: used by RF backends
2512  */
2513 void
2514 ar5212ModifyRfBuffer(uint32_t *rfBuf, uint32_t reg32, uint32_t numBits,
2515                      uint32_t firstBit, uint32_t column)
2516 {
2517 #define MAX_ANALOG_START        319             /* XXX */
2518         uint32_t tmp32, mask, arrayEntry, lastBit;
2519         int32_t bitPosition, bitsLeft;
2520
2521         HALASSERT(column <= 3);
2522         HALASSERT(numBits <= 32);
2523         HALASSERT(firstBit + numBits <= MAX_ANALOG_START);
2524
2525         tmp32 = ath_hal_reverseBits(reg32, numBits);
2526         arrayEntry = (firstBit - 1) / 8;
2527         bitPosition = (firstBit - 1) % 8;
2528         bitsLeft = numBits;
2529         while (bitsLeft > 0) {
2530                 lastBit = (bitPosition + bitsLeft > 8) ?
2531                         8 : bitPosition + bitsLeft;
2532                 mask = (((1 << lastBit) - 1) ^ ((1 << bitPosition) - 1)) <<
2533                         (column * 8);
2534                 rfBuf[arrayEntry] &= ~mask;
2535                 rfBuf[arrayEntry] |= ((tmp32 << bitPosition) <<
2536                         (column * 8)) & mask;
2537                 bitsLeft -= 8 - bitPosition;
2538                 tmp32 = tmp32 >> (8 - bitPosition);
2539                 bitPosition = 0;
2540                 arrayEntry++;
2541         }
2542 #undef MAX_ANALOG_START
2543 }
2544
2545 /*
2546  * Sets the rate to duration values in MAC - used for multi-
2547  * rate retry.
2548  * The rate duration table needs to cover all valid rate codes;
2549  * the 11g table covers all ofdm rates, while the 11b table
2550  * covers all cck rates => all valid rates get covered between
2551  * these two mode's ratetables!
2552  * But if we're turbo, the ofdm phy is replaced by the turbo phy
2553  * and cck is not valid with turbo => all rates get covered
2554  * by the turbo ratetable only
2555  */
2556 void
2557 ar5212SetRateDurationTable(struct ath_hal *ah,
2558         const struct ieee80211_channel *chan)
2559 {
2560         const HAL_RATE_TABLE *rt;
2561         int i;
2562
2563         /* NB: band doesn't matter for 1/2 and 1/4 rate */
2564         if (IEEE80211_IS_CHAN_HALF(chan)) {
2565                 rt = ar5212GetRateTable(ah, HAL_MODE_11A_HALF_RATE);
2566         } else if (IEEE80211_IS_CHAN_QUARTER(chan)) {
2567                 rt = ar5212GetRateTable(ah, HAL_MODE_11A_QUARTER_RATE);
2568         } else {
2569                 rt = ar5212GetRateTable(ah,
2570                         IEEE80211_IS_CHAN_TURBO(chan) ? HAL_MODE_TURBO : HAL_MODE_11G);
2571         }
2572
2573         for (i = 0; i < rt->rateCount; ++i)
2574                 OS_REG_WRITE(ah,
2575                         AR_RATE_DURATION(rt->info[i].rateCode),
2576                         ath_hal_computetxtime(ah, rt,
2577                                 WLAN_CTRL_FRAME_SIZE,
2578                                 rt->info[i].controlRate, AH_FALSE));
2579         if (!IEEE80211_IS_CHAN_TURBO(chan)) {
2580                 /* 11g Table is used to cover the CCK rates. */
2581                 rt = ar5212GetRateTable(ah, HAL_MODE_11G);
2582                 for (i = 0; i < rt->rateCount; ++i) {
2583                         uint32_t reg = AR_RATE_DURATION(rt->info[i].rateCode);
2584
2585                         if (rt->info[i].phy != IEEE80211_T_CCK)
2586                                 continue;
2587
2588                         OS_REG_WRITE(ah, reg,
2589                                 ath_hal_computetxtime(ah, rt,
2590                                         WLAN_CTRL_FRAME_SIZE,
2591                                         rt->info[i].controlRate, AH_FALSE));
2592                         /* cck rates have short preamble option also */
2593                         if (rt->info[i].shortPreamble) {
2594                                 reg += rt->info[i].shortPreamble << 2;
2595                                 OS_REG_WRITE(ah, reg,
2596                                         ath_hal_computetxtime(ah, rt,
2597                                                 WLAN_CTRL_FRAME_SIZE,
2598                                                 rt->info[i].controlRate,
2599                                                 AH_TRUE));
2600                         }
2601                 }
2602         }
2603 }
2604
2605 /* Adjust various register settings based on half/quarter rate clock setting.
2606  * This includes: +USEC, TX/RX latency, 
2607  *                + IFS params: slot, eifs, misc etc.
2608  */
2609 void 
2610 ar5212SetIFSTiming(struct ath_hal *ah, const struct ieee80211_channel *chan)
2611 {
2612         uint32_t txLat, rxLat, usec, slot, refClock, eifs, init_usec;
2613
2614         HALASSERT(IEEE80211_IS_CHAN_HALF(chan) ||
2615                   IEEE80211_IS_CHAN_QUARTER(chan));
2616
2617         refClock = OS_REG_READ(ah, AR_USEC) & AR_USEC_USEC32;
2618         if (IEEE80211_IS_CHAN_HALF(chan)) {
2619                 slot = IFS_SLOT_HALF_RATE;
2620                 rxLat = RX_NON_FULL_RATE_LATENCY << AR5212_USEC_RX_LAT_S;
2621                 txLat = TX_HALF_RATE_LATENCY << AR5212_USEC_TX_LAT_S;
2622                 usec = HALF_RATE_USEC;
2623                 eifs = IFS_EIFS_HALF_RATE;
2624                 init_usec = INIT_USEC >> 1;
2625         } else { /* quarter rate */
2626                 slot = IFS_SLOT_QUARTER_RATE;
2627                 rxLat = RX_NON_FULL_RATE_LATENCY << AR5212_USEC_RX_LAT_S;
2628                 txLat = TX_QUARTER_RATE_LATENCY << AR5212_USEC_TX_LAT_S;
2629                 usec = QUARTER_RATE_USEC;
2630                 eifs = IFS_EIFS_QUARTER_RATE;
2631                 init_usec = INIT_USEC >> 2;
2632         }
2633
2634         OS_REG_WRITE(ah, AR_USEC, (usec | refClock | txLat | rxLat));
2635         OS_REG_WRITE(ah, AR_D_GBL_IFS_SLOT, slot);
2636         OS_REG_WRITE(ah, AR_D_GBL_IFS_EIFS, eifs);
2637         OS_REG_RMW_FIELD(ah, AR_D_GBL_IFS_MISC,
2638                                 AR_D_GBL_IFS_MISC_USEC_DURATION, init_usec);
2639 }