netmap: d_poll -> d_kqfilter
[dragonfly.git] / sys / dev / netif / ath / hal / ath_hal / ar5416 / ar5416_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/ar5416/ar5416_reset.c 203930 2010-02-15 17:49:49Z rpaulo $
18  */
19 #include "opt_ah.h"
20
21 #include "ah.h"
22 #include "ah_internal.h"
23 #include "ah_devid.h"
24
25 #include "ah_eeprom_v14.h"
26
27 #include "ar5416/ar5416.h"
28 #include "ar5416/ar5416reg.h"
29 #include "ar5416/ar5416phy.h"
30
31 /* Eeprom versioning macros. Returns true if the version is equal or newer than the ver specified */ 
32 #define EEP_MINOR(_ah) \
33         (AH_PRIVATE(_ah)->ah_eeversion & AR5416_EEP_VER_MINOR_MASK)
34 #define IS_EEP_MINOR_V2(_ah)    (EEP_MINOR(_ah) >= AR5416_EEP_MINOR_VER_2)
35 #define IS_EEP_MINOR_V3(_ah)    (EEP_MINOR(_ah) >= AR5416_EEP_MINOR_VER_3)
36
37 /* Additional Time delay to wait after activiting the Base band */
38 #define BASE_ACTIVATE_DELAY     100     /* 100 usec */
39 #define PLL_SETTLE_DELAY        300     /* 300 usec */
40 #define RTC_PLL_SETTLE_DELAY    1000    /* 1 ms     */
41
42 static void ar5416InitDMA(struct ath_hal *ah);
43 static void ar5416InitBB(struct ath_hal *ah, const struct ieee80211_channel *);
44 static void ar5416InitIMR(struct ath_hal *ah, HAL_OPMODE opmode);
45 static void ar5416InitQoS(struct ath_hal *ah);
46 static void ar5416InitUserSettings(struct ath_hal *ah);
47
48 #if 0
49 static HAL_BOOL ar5416ChannelChange(struct ath_hal *, const struct ieee80211_channel *);
50 #endif
51 static void ar5416SetDeltaSlope(struct ath_hal *, const struct ieee80211_channel *);
52
53 static HAL_BOOL ar5416SetResetPowerOn(struct ath_hal *ah);
54 static HAL_BOOL ar5416SetReset(struct ath_hal *ah, int type);
55 static void ar5416InitPLL(struct ath_hal *ah, const struct ieee80211_channel *chan);
56 static HAL_BOOL ar5416SetPowerPerRateTable(struct ath_hal *ah,
57         struct ar5416eeprom *pEepData, 
58         const struct ieee80211_channel *chan, int16_t *ratesArray,
59         uint16_t cfgCtl, uint16_t AntennaReduction,
60         uint16_t twiceMaxRegulatoryPower, 
61         uint16_t powerLimit);
62 static HAL_BOOL ar5416SetPowerCalTable(struct ath_hal *ah,
63         struct ar5416eeprom *pEepData,
64         const struct ieee80211_channel *chan,
65         int16_t *pTxPowerIndexOffset);
66 static uint16_t ar5416GetMaxEdgePower(uint16_t freq,
67         CAL_CTL_EDGES *pRdEdgesPower, HAL_BOOL is2GHz);
68
69 static int16_t interpolate(uint16_t target, uint16_t srcLeft,
70         uint16_t srcRight, int16_t targetLeft, int16_t targetRight);
71 static void ar5416Set11nRegs(struct ath_hal *ah, const struct ieee80211_channel *chan);
72 static void ar5416GetGainBoundariesAndPdadcs(struct ath_hal *ah, 
73         const struct ieee80211_channel *chan, CAL_DATA_PER_FREQ *pRawDataSet,
74         uint8_t * bChans, uint16_t availPiers,
75         uint16_t tPdGainOverlap, int16_t *pMinCalPower,
76         uint16_t * pPdGainBoundaries, uint8_t * pPDADCValues,
77         uint16_t numXpdGains);
78 static HAL_BOOL getLowerUpperIndex(uint8_t target, uint8_t *pList,
79         uint16_t listSize,  uint16_t *indexL, uint16_t *indexR);
80 static HAL_BOOL ar5416FillVpdTable(uint8_t pwrMin, uint8_t pwrMax,
81         uint8_t *pPwrList, uint8_t *pVpdList,
82         uint16_t numIntercepts, uint8_t *pRetVpdList);
83
84 /*
85  * Places the device in and out of reset and then places sane
86  * values in the registers based on EEPROM config, initialization
87  * vectors (as determined by the mode), and station configuration
88  *
89  * bChannelChange is used to preserve DMA/PCU registers across
90  * a HW Reset during channel change.
91  */
92 HAL_BOOL
93 ar5416Reset(struct ath_hal *ah, HAL_OPMODE opmode,
94         struct ieee80211_channel *chan,
95         HAL_BOOL bChannelChange, HAL_STATUS *status)
96 {
97 #define FAIL(_code)     do { ecode = _code; goto bad; } while (0)
98         struct ath_hal_5212 *ahp = AH5212(ah);
99         HAL_CHANNEL_INTERNAL *ichan;
100         uint32_t saveDefAntenna, saveLedState;
101         uint32_t macStaId1;
102         uint16_t rfXpdGain[2];
103         HAL_STATUS ecode;
104         uint32_t powerVal, rssiThrReg;
105         uint32_t ackTpcPow, ctsTpcPow, chirpTpcPow;
106         int i;
107
108         OS_MARK(ah, AH_MARK_RESET, bChannelChange);
109
110         /* Bring out of sleep mode */
111         if (!ar5416SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE)) {
112                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: chip did not wakeup\n",
113                     __func__);
114                 FAIL(HAL_EIO);
115         }
116
117         /*
118          * Map public channel to private.
119          */
120         ichan = ath_hal_checkchannel(ah, chan);
121         if (ichan == AH_NULL)
122                 FAIL(HAL_EINVAL);
123         switch (opmode) {
124         case HAL_M_STA:
125         case HAL_M_IBSS:
126         case HAL_M_HOSTAP:
127         case HAL_M_MONITOR:
128                 break;
129         default:
130                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid operating mode %u\n",
131                     __func__, opmode);
132                 FAIL(HAL_EINVAL);
133                 break;
134         }
135         HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER14_1);
136
137         /* XXX Turn on fast channel change for 5416 */
138         /*
139          * Preserve the bmiss rssi threshold and count threshold
140          * across resets
141          */
142         rssiThrReg = OS_REG_READ(ah, AR_RSSI_THR);
143         /* If reg is zero, first time thru set to default val */
144         if (rssiThrReg == 0)
145                 rssiThrReg = INIT_RSSI_THR;
146
147         /*
148          * Preserve the antenna on a channel change
149          */
150         saveDefAntenna = OS_REG_READ(ah, AR_DEF_ANTENNA);
151         if (saveDefAntenna == 0)                /* XXX magic constants */
152                 saveDefAntenna = 1;
153
154         /* Save hardware flag before chip reset clears the register */
155         macStaId1 = OS_REG_READ(ah, AR_STA_ID1) & 
156                 (AR_STA_ID1_BASE_RATE_11B | AR_STA_ID1_USE_DEFANT);
157
158         /* Save led state from pci config register */
159         saveLedState = OS_REG_READ(ah, AR_MAC_LED) &
160                 (AR_MAC_LED_ASSOC | AR_MAC_LED_MODE |
161                  AR_MAC_LED_BLINK_THRESH_SEL | AR_MAC_LED_BLINK_SLOW);
162
163         if (!ar5416ChipReset(ah, chan)) {
164                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: chip reset failed\n", __func__);
165                 FAIL(HAL_EIO);
166         }
167
168         /* Restore bmiss rssi & count thresholds */
169         OS_REG_WRITE(ah, AR_RSSI_THR, rssiThrReg);
170
171         OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
172         if (AR_SREV_MERLIN_10_OR_LATER(ah))
173                 OS_REG_SET_BIT(ah, AR_GPIO_INPUT_EN_VAL, AR_GPIO_JTAG_DISABLE);
174
175         if (AR_SREV_KITE(ah)) {
176                 uint32_t val;
177                 val = OS_REG_READ(ah, AR_PHY_HEAVY_CLIP_FACTOR_RIFS);
178                 val &= ~AR_PHY_RIFS_INIT_DELAY;
179                 OS_REG_WRITE(ah, AR_PHY_HEAVY_CLIP_FACTOR_RIFS, val);
180         }
181
182         AH5416(ah)->ah_writeIni(ah, chan);
183
184         /* Setup 11n MAC/Phy mode registers */
185         ar5416Set11nRegs(ah, chan);     
186
187         OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
188
189         HALDEBUG(ah, HAL_DEBUG_RESET, ">>>2 %s: AR_PHY_DAG_CTRLCCK=0x%x\n",
190                 __func__, OS_REG_READ(ah,AR_PHY_DAG_CTRLCCK));
191         HALDEBUG(ah, HAL_DEBUG_RESET, ">>>2 %s: AR_PHY_ADC_CTL=0x%x\n",
192                 __func__, OS_REG_READ(ah,AR_PHY_ADC_CTL));      
193
194         /* Set the mute mask to the correct default */
195         if (AH_PRIVATE(ah)->ah_phyRev >= AR_PHY_CHIP_ID_REV_2)
196                 OS_REG_WRITE(ah, AR_SEQ_MASK, 0x0000000F);
197
198         if (AH_PRIVATE(ah)->ah_phyRev >= AR_PHY_CHIP_ID_REV_3) {
199                 /* Clear reg to alllow RX_CLEAR line debug */
200                 OS_REG_WRITE(ah, AR_PHY_BLUETOOTH,  0);
201         }
202         if (AH_PRIVATE(ah)->ah_phyRev >= AR_PHY_CHIP_ID_REV_4) {
203 #ifdef notyet
204                 /* Enable burst prefetch for the data queues */
205                 OS_REG_RMW_FIELD(ah, AR_D_FPCTL, ... );
206                 /* Enable double-buffering */
207                 OS_REG_CLR_BIT(ah, AR_TXCFG, AR_TXCFG_DBL_BUF_DIS);
208 #endif
209         }
210
211         /* Set ADC/DAC select values */
212         OS_REG_WRITE(ah, AR_PHY_SLEEP_SCAL, 0x0e);
213
214         if (AH5416(ah)->ah_rx_chainmask == 0x5 ||
215             AH5416(ah)->ah_tx_chainmask == 0x5)
216                 OS_REG_WRITE(ah, AR_PHY_ANALOG_SWAP, AR_PHY_SWAP_ALT_CHAIN);
217         /* Setup Chain Masks */
218         OS_REG_WRITE(ah, AR_PHY_RX_CHAINMASK, AH5416(ah)->ah_rx_chainmask);
219         OS_REG_WRITE(ah, AR_PHY_CAL_CHAINMASK, AH5416(ah)->ah_rx_chainmask);
220         OS_REG_WRITE(ah, AR_SELFGEN_MASK, AH5416(ah)->ah_tx_chainmask);
221
222         /* Setup the transmit power values. */
223         if (!ah->ah_setTxPower(ah, chan, rfXpdGain)) {
224                 HALDEBUG(ah, HAL_DEBUG_ANY,
225                     "%s: error init'ing transmit power\n", __func__);
226                 FAIL(HAL_EIO);
227         }
228
229         /* Write the analog registers */
230         if (!ahp->ah_rfHal->setRfRegs(ah, chan,
231             IEEE80211_IS_CHAN_2GHZ(chan) ? 2: 1, rfXpdGain)) {
232                 HALDEBUG(ah, HAL_DEBUG_ANY,
233                     "%s: ar5212SetRfRegs failed\n", __func__);
234                 FAIL(HAL_EIO);
235         }
236
237         /* Write delta slope for OFDM enabled modes (A, G, Turbo) */
238         if (IEEE80211_IS_CHAN_OFDM(chan)|| IEEE80211_IS_CHAN_HT(chan))
239                 ar5416SetDeltaSlope(ah, chan);
240
241         AH5416(ah)->ah_spurMitigate(ah, chan);
242
243         /* Setup board specific options for EEPROM version 3 */
244         if (!ah->ah_setBoardValues(ah, chan)) {
245                 HALDEBUG(ah, HAL_DEBUG_ANY,
246                     "%s: error setting board options\n", __func__);
247                 FAIL(HAL_EIO);
248         }
249
250         OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
251
252         OS_REG_WRITE(ah, AR_STA_ID0, LE_READ_4(ahp->ah_macaddr));
253         OS_REG_WRITE(ah, AR_STA_ID1, LE_READ_2(ahp->ah_macaddr + 4)
254                 | macStaId1
255                 | AR_STA_ID1_RTS_USE_DEF
256                 | ahp->ah_staId1Defaults
257         );
258         ar5212SetOperatingMode(ah, opmode);
259
260         /* Set Venice BSSID mask according to current state */
261         OS_REG_WRITE(ah, AR_BSSMSKL, LE_READ_4(ahp->ah_bssidmask));
262         OS_REG_WRITE(ah, AR_BSSMSKU, LE_READ_2(ahp->ah_bssidmask + 4));
263
264         /* Restore previous led state */
265         OS_REG_WRITE(ah, AR_MAC_LED, OS_REG_READ(ah, AR_MAC_LED) | saveLedState);
266
267         /* Restore previous antenna */
268         OS_REG_WRITE(ah, AR_DEF_ANTENNA, saveDefAntenna);
269
270         /* then our BSSID */
271         OS_REG_WRITE(ah, AR_BSS_ID0, LE_READ_4(ahp->ah_bssid));
272         OS_REG_WRITE(ah, AR_BSS_ID1, LE_READ_2(ahp->ah_bssid + 4));
273
274         /* Restore bmiss rssi & count thresholds */
275         OS_REG_WRITE(ah, AR_RSSI_THR, ahp->ah_rssiThr);
276
277         OS_REG_WRITE(ah, AR_ISR, ~0);           /* cleared on write */
278
279         if (!ar5212SetChannel(ah, chan))
280                 FAIL(HAL_EIO);
281
282         OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
283
284         /* Set 1:1 QCU to DCU mapping for all queues */
285         for (i = 0; i < AR_NUM_DCU; i++)
286                 OS_REG_WRITE(ah, AR_DQCUMASK(i), 1 << i);
287
288         ahp->ah_intrTxqs = 0;
289         for (i = 0; i < AH_PRIVATE(ah)->ah_caps.halTotalQueues; i++)
290                 ar5212ResetTxQueue(ah, i);
291
292         ar5416InitIMR(ah, opmode);
293         ar5212SetCoverageClass(ah, AH_PRIVATE(ah)->ah_coverageClass, 1);
294         ar5416InitQoS(ah);
295         ar5416InitUserSettings(ah);
296
297         /*
298          * disable seq number generation in hw
299          */
300          OS_REG_WRITE(ah, AR_STA_ID1,
301              OS_REG_READ(ah, AR_STA_ID1) | AR_STA_ID1_PRESERVE_SEQNUM);
302          
303         ar5416InitDMA(ah);
304
305         /*
306          * program OBS bus to see MAC interrupts
307          */
308         OS_REG_WRITE(ah, AR_OBS, 8);
309
310 #ifdef AR5416_INT_MITIGATION
311         OS_REG_WRITE(ah, AR_MIRT, 0);
312         OS_REG_RMW_FIELD(ah, AR_RIMT, AR_RIMT_LAST, 500);
313         OS_REG_RMW_FIELD(ah, AR_RIMT, AR_RIMT_FIRST, 2000);
314 #endif      
315         
316         ar5416InitBB(ah, chan);
317
318         /* Setup compression registers */
319         ar5212SetCompRegs(ah);          /* XXX not needed? */
320
321         /*
322          * 5416 baseband will check the per rate power table
323          * and select the lower of the two
324          */
325         ackTpcPow = 63;
326         ctsTpcPow = 63;
327         chirpTpcPow = 63;
328         powerVal = SM(ackTpcPow, AR_TPC_ACK) |
329                 SM(ctsTpcPow, AR_TPC_CTS) |
330                 SM(chirpTpcPow, AR_TPC_CHIRP);
331         OS_REG_WRITE(ah, AR_TPC, powerVal);
332
333         if (!ar5416InitCal(ah, chan))
334                 FAIL(HAL_ESELFTEST);
335
336         AH_PRIVATE(ah)->ah_opmode = opmode;     /* record operating mode */
337
338         if (bChannelChange && !IEEE80211_IS_CHAN_DFS(chan)) 
339                 chan->ic_state &= ~IEEE80211_CHANSTATE_CWINT;
340
341         HALDEBUG(ah, HAL_DEBUG_RESET, "%s: done\n", __func__);
342
343         OS_MARK(ah, AH_MARK_RESET_DONE, 0);
344
345         return AH_TRUE;
346 bad:
347         OS_MARK(ah, AH_MARK_RESET_DONE, ecode);
348         if (status != AH_NULL)
349                 *status = ecode;
350         return AH_FALSE;
351 #undef FAIL
352 }
353
354 #if 0
355 /*
356  * This channel change evaluates whether the selected hardware can
357  * perform a synthesizer-only channel change (no reset).  If the
358  * TX is not stopped, or the RFBus cannot be granted in the given
359  * time, the function returns false as a reset is necessary
360  */
361 HAL_BOOL
362 ar5416ChannelChange(struct ath_hal *ah, const structu ieee80211_channel *chan)
363 {
364         uint32_t       ulCount;
365         uint32_t   data, synthDelay, qnum;
366         uint16_t   rfXpdGain[4];
367         struct ath_hal_5212 *ahp = AH5212(ah);
368         HAL_CHANNEL_INTERNAL *ichan;
369
370         /*
371          * Map public channel to private.
372          */
373         ichan = ath_hal_checkchannel(ah, chan);
374
375         /* TX must be stopped or RF Bus grant will not work */
376         for (qnum = 0; qnum < AH_PRIVATE(ah)->ah_caps.halTotalQueues; qnum++) {
377                 if (ar5212NumTxPending(ah, qnum)) {
378                         HALDEBUG(ah, HAL_DEBUG_ANY,
379                             "%s: frames pending on queue %d\n", __func__, qnum);
380                         return AH_FALSE;
381                 }
382         }
383
384         /*
385          * Kill last Baseband Rx Frame - Request analog bus grant
386          */
387         OS_REG_WRITE(ah, AR_PHY_RFBUS_REQ, AR_PHY_RFBUS_REQ_REQUEST);
388         if (!ath_hal_wait(ah, AR_PHY_RFBUS_GNT, AR_PHY_RFBUS_GRANT_EN, AR_PHY_RFBUS_GRANT_EN)) {
389                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: could not kill baseband rx\n",
390                     __func__);
391                 return AH_FALSE;
392         }
393
394         ar5416Set11nRegs(ah, chan);     /* NB: setup 5416-specific regs */
395
396         /* Change the synth */
397         if (!ar5212SetChannel(ah, chan))
398                 return AH_FALSE;
399
400         /* Setup the transmit power values. */
401         if (!ar5416SetTransmitPower(ah, chan, rfXpdGain)) {
402                 HALDEBUG(ah, HAL_DEBUG_ANY,
403                     "%s: error init'ing transmit power\n", __func__);
404                 return AH_FALSE;
405         }
406
407         /*
408          * Wait for the frequency synth to settle (synth goes on
409          * via PHY_ACTIVE_EN).  Read the phy active delay register.
410          * Value is in 100ns increments.
411          */
412         data = OS_REG_READ(ah, AR_PHY_RX_DELAY) & AR_PHY_RX_DELAY_DELAY;
413         if (IS_CHAN_CCK(ichan)) {
414                 synthDelay = (4 * data) / 22;
415         } else {
416                 synthDelay = data / 10;
417         }
418
419         OS_DELAY(synthDelay + BASE_ACTIVATE_DELAY);
420
421         /* Release the RFBus Grant */
422         OS_REG_WRITE(ah, AR_PHY_RFBUS_REQ, 0);
423
424         /* Write delta slope for OFDM enabled modes (A, G, Turbo) */
425         if (IEEE80211_IS_CHAN_OFDM(ichan)|| IEEE80211_IS_CHAN_HT(chan)) {
426                 HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER5_3);
427                 ar5212SetSpurMitigation(ah, chan);
428                 ar5416SetDeltaSlope(ah, chan);
429         }
430
431         /* XXX spur mitigation for Melin */
432
433         if (!IEEE80211_IS_CHAN_DFS(chan)) 
434                 chan->ic_state &= ~IEEE80211_CHANSTATE_CWINT;
435
436         ichan->channel_time = 0;
437         ichan->tsf_last = ar5212GetTsf64(ah);
438         ar5212TxEnable(ah, AH_TRUE);
439         return AH_TRUE;
440 }
441 #endif
442
443 static void
444 ar5416InitDMA(struct ath_hal *ah)
445 {
446         struct ath_hal_5212 *ahp = AH5212(ah);
447
448         /*
449          * set AHB_MODE not to do cacheline prefetches
450          */
451         OS_REG_SET_BIT(ah, AR_AHB_MODE, AR_AHB_PREFETCH_RD_EN);
452
453         /*
454          * let mac dma reads be in 128 byte chunks
455          */
456         OS_REG_WRITE(ah, AR_TXCFG, 
457                 (OS_REG_READ(ah, AR_TXCFG) & ~AR_TXCFG_DMASZ_MASK) | AR_TXCFG_DMASZ_128B);
458
459         /*
460          * let mac dma writes be in 128 byte chunks
461          */
462         OS_REG_WRITE(ah, AR_RXCFG, 
463                 (OS_REG_READ(ah, AR_RXCFG) & ~AR_RXCFG_DMASZ_MASK) | AR_RXCFG_DMASZ_128B);
464
465         /* restore TX trigger level */
466         OS_REG_WRITE(ah, AR_TXCFG,
467                 (OS_REG_READ(ah, AR_TXCFG) &~ AR_FTRIG) |
468                     SM(ahp->ah_txTrigLev, AR_FTRIG));
469
470         /*
471          * Setup receive FIFO threshold to hold off TX activities
472          */
473         OS_REG_WRITE(ah, AR_RXFIFO_CFG, 0x200);
474         
475         /*
476          * reduce the number of usable entries in PCU TXBUF to avoid
477          * wrap around.
478          */
479         OS_REG_WRITE(ah, AR_PCU_TXBUF_CTRL, AR_PCU_TXBUF_CTRL_USABLE_SIZE);
480 }
481
482 static void
483 ar5416InitBB(struct ath_hal *ah, const struct ieee80211_channel *chan)
484 {
485         uint32_t synthDelay;
486
487         /*
488          * Wait for the frequency synth to settle (synth goes on
489          * via AR_PHY_ACTIVE_EN).  Read the phy active delay register.
490          * Value is in 100ns increments.
491           */
492         synthDelay = OS_REG_READ(ah, AR_PHY_RX_DELAY) & AR_PHY_RX_DELAY_DELAY;
493         if (IEEE80211_IS_CHAN_CCK(chan)) {
494                 synthDelay = (4 * synthDelay) / 22;
495         } else {
496                 synthDelay /= 10;
497         }
498
499         /* Turn on PLL on 5416 */
500         HALDEBUG(ah, HAL_DEBUG_RESET, "%s %s channel\n",
501             __func__, IEEE80211_IS_CHAN_5GHZ(chan) ? "5GHz" : "2GHz");
502         ar5416InitPLL(ah, chan);
503
504         /* Activate the PHY (includes baseband activate and synthesizer on) */
505         OS_REG_WRITE(ah, AR_PHY_ACTIVE, AR_PHY_ACTIVE_EN);
506         
507         /* 
508          * If the AP starts the calibration before the base band timeout
509          * completes  we could get rx_clear false triggering.  Add an
510          * extra BASE_ACTIVATE_DELAY usecs to ensure this condition
511          * does not happen.
512          */
513         if (IEEE80211_IS_CHAN_HALF(chan)) {
514                 OS_DELAY((synthDelay << 1) + BASE_ACTIVATE_DELAY);
515         } else if (IEEE80211_IS_CHAN_QUARTER(chan)) {
516                 OS_DELAY((synthDelay << 2) + BASE_ACTIVATE_DELAY);
517         } else {
518                 OS_DELAY(synthDelay + BASE_ACTIVATE_DELAY);
519         }
520 }
521
522 static void
523 ar5416InitIMR(struct ath_hal *ah, HAL_OPMODE opmode)
524 {
525         struct ath_hal_5212 *ahp = AH5212(ah);
526
527         /*
528          * Setup interrupt handling.  Note that ar5212ResetTxQueue
529          * manipulates the secondary IMR's as queues are enabled
530          * and disabled.  This is done with RMW ops to insure the
531          * settings we make here are preserved.
532          */
533         ahp->ah_maskReg = AR_IMR_TXERR | AR_IMR_TXURN
534                         | AR_IMR_RXERR | AR_IMR_RXORN
535                         | AR_IMR_BCNMISC;
536
537 #ifdef AR5416_INT_MITIGATION
538         ahp->ah_maskReg |= AR_IMR_TXINTM | AR_IMR_RXINTM
539                         |  AR_IMR_TXMINTR | AR_IMR_RXMINTR;
540 #else
541         ahp->ah_maskReg |= AR_IMR_TXOK | AR_IMR_RXOK;
542 #endif  
543         if (opmode == HAL_M_HOSTAP)
544                 ahp->ah_maskReg |= AR_IMR_MIB;
545         OS_REG_WRITE(ah, AR_IMR, ahp->ah_maskReg);
546         /* Enable bus errors that are OR'd to set the HIUERR bit */
547 #if 0
548         OS_REG_WRITE(ah, AR_IMR_S2, 
549                 OS_REG_READ(ah, AR_IMR_S2) | AR_IMR_S2_GTT | AR_IMR_S2_CST);
550 #endif
551 }
552
553 static void
554 ar5416InitQoS(struct ath_hal *ah)
555 {
556         /* QoS support */
557         OS_REG_WRITE(ah, AR_QOS_CONTROL, 0x100aa);      /* XXX magic */
558         OS_REG_WRITE(ah, AR_QOS_SELECT, 0x3210);        /* XXX magic */
559
560         /* Turn on NOACK Support for QoS packets */
561         OS_REG_WRITE(ah, AR_NOACK,
562                 SM(2, AR_NOACK_2BIT_VALUE) |
563                 SM(5, AR_NOACK_BIT_OFFSET) |
564                 SM(0, AR_NOACK_BYTE_OFFSET));
565                 
566         /*
567          * initialize TXOP for all TIDs
568          */
569         OS_REG_WRITE(ah, AR_TXOP_X, AR_TXOP_X_VAL);
570         OS_REG_WRITE(ah, AR_TXOP_0_3, 0xFFFFFFFF);
571         OS_REG_WRITE(ah, AR_TXOP_4_7, 0xFFFFFFFF);
572         OS_REG_WRITE(ah, AR_TXOP_8_11, 0xFFFFFFFF);
573         OS_REG_WRITE(ah, AR_TXOP_12_15, 0xFFFFFFFF);
574 }
575
576 static void
577 ar5416InitUserSettings(struct ath_hal *ah)
578 {
579         struct ath_hal_5212 *ahp = AH5212(ah);
580
581         /* Restore user-specified settings */
582         if (ahp->ah_miscMode != 0)
583                 OS_REG_WRITE(ah, AR_MISC_MODE, ahp->ah_miscMode);
584         if (ahp->ah_sifstime != (u_int) -1)
585                 ar5212SetSifsTime(ah, ahp->ah_sifstime);
586         if (ahp->ah_slottime != (u_int) -1)
587                 ar5212SetSlotTime(ah, ahp->ah_slottime);
588         if (ahp->ah_acktimeout != (u_int) -1)
589                 ar5212SetAckTimeout(ah, ahp->ah_acktimeout);
590         if (ahp->ah_ctstimeout != (u_int) -1)
591                 ar5212SetCTSTimeout(ah, ahp->ah_ctstimeout);
592         if (AH_PRIVATE(ah)->ah_diagreg != 0)
593                 OS_REG_WRITE(ah, AR_DIAG_SW, AH_PRIVATE(ah)->ah_diagreg);
594 #if 0 /* XXX Todo */
595         if (ahp->ah_globaltxtimeout != (u_int) -1)
596                 ar5416SetGlobalTxTimeout(ah, ahp->ah_globaltxtimeout);
597 #endif
598 }
599
600 /*
601  * Places the hardware into reset and then pulls it out of reset
602  */
603 HAL_BOOL
604 ar5416ChipReset(struct ath_hal *ah, const struct ieee80211_channel *chan)
605 {
606         OS_MARK(ah, AH_MARK_CHIPRESET, chan ? chan->ic_freq : 0);
607         /*
608          * Warm reset is optimistic.
609          */
610         if (AR_SREV_MERLIN_20_OR_LATER(ah) &&
611             ath_hal_eepromGetFlag(ah, AR_EEP_OL_PWRCTRL)) {
612                 if (!ar5416SetResetReg(ah, HAL_RESET_POWER_ON))
613                         return AH_FALSE;
614         } else {
615                 if (!ar5416SetResetReg(ah, HAL_RESET_WARM))
616                         return AH_FALSE;
617         }
618
619         /* Bring out of sleep mode (AGAIN) */
620         if (!ar5416SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
621                return AH_FALSE;
622
623         ar5416InitPLL(ah, chan);
624
625         /*
626          * Perform warm reset before the mode/PLL/turbo registers
627          * are changed in order to deactivate the radio.  Mode changes
628          * with an active radio can result in corrupted shifts to the
629          * radio device.
630          */
631         if (chan != AH_NULL) { 
632                 uint32_t rfMode;
633
634                 /* treat channel B as channel G , no  B mode suport in owl */
635                 rfMode = IEEE80211_IS_CHAN_CCK(chan) ?
636                     AR_PHY_MODE_DYNAMIC : AR_PHY_MODE_OFDM;
637                 if (AR_SREV_MERLIN_20(ah) && IS_5GHZ_FAST_CLOCK_EN(ah, chan)) {
638                         /* phy mode bits for 5GHz channels require Fast Clock */
639                         rfMode |= AR_PHY_MODE_DYNAMIC
640                                |  AR_PHY_MODE_DYN_CCK_DISABLE;
641                 } else if (!AR_SREV_MERLIN_10_OR_LATER(ah)) {
642                         rfMode |= IEEE80211_IS_CHAN_5GHZ(chan) ?
643                                 AR_PHY_MODE_RF5GHZ : AR_PHY_MODE_RF2GHZ;
644                 }
645                 OS_REG_WRITE(ah, AR_PHY_MODE, rfMode);
646         }
647         return AH_TRUE; 
648 }
649
650 /*
651  * Delta slope coefficient computation.
652  * Required for OFDM operation.
653  */
654 static void
655 ar5416GetDeltaSlopeValues(struct ath_hal *ah, uint32_t coef_scaled,
656                           uint32_t *coef_mantissa, uint32_t *coef_exponent)
657 {
658 #define COEF_SCALE_S 24
659     uint32_t coef_exp, coef_man;
660     /*
661      * ALGO -> coef_exp = 14-floor(log2(coef));
662      * floor(log2(x)) is the highest set bit position
663      */
664     for (coef_exp = 31; coef_exp > 0; coef_exp--)
665             if ((coef_scaled >> coef_exp) & 0x1)
666                     break;
667     /* A coef_exp of 0 is a legal bit position but an unexpected coef_exp */
668     HALASSERT(coef_exp);
669     coef_exp = 14 - (coef_exp - COEF_SCALE_S);
670
671     /*
672      * ALGO -> coef_man = floor(coef* 2^coef_exp+0.5);
673      * The coefficient is already shifted up for scaling
674      */
675     coef_man = coef_scaled + (1 << (COEF_SCALE_S - coef_exp - 1));
676
677     *coef_mantissa = coef_man >> (COEF_SCALE_S - coef_exp);
678     *coef_exponent = coef_exp - 16;
679
680 #undef COEF_SCALE_S    
681 }
682
683 void
684 ar5416SetDeltaSlope(struct ath_hal *ah, const struct ieee80211_channel *chan)
685 {
686 #define INIT_CLOCKMHZSCALED     0x64000000
687         uint32_t coef_scaled, ds_coef_exp, ds_coef_man;
688         uint32_t clockMhzScaled;
689
690         CHAN_CENTERS centers;
691
692         /* half and quarter rate can divide the scaled clock by 2 or 4 respectively */
693         /* scale for selected channel bandwidth */ 
694         clockMhzScaled = INIT_CLOCKMHZSCALED;
695         if (IEEE80211_IS_CHAN_TURBO(chan))
696                 clockMhzScaled <<= 1;
697         else if (IEEE80211_IS_CHAN_HALF(chan))
698                 clockMhzScaled >>= 1;
699         else if (IEEE80211_IS_CHAN_QUARTER(chan))
700                 clockMhzScaled >>= 2;
701
702         /*
703          * ALGO -> coef = 1e8/fcarrier*fclock/40;
704          * scaled coef to provide precision for this floating calculation 
705          */
706         ar5416GetChannelCenters(ah, chan, &centers);
707         coef_scaled = clockMhzScaled / centers.synth_center;            
708
709         ar5416GetDeltaSlopeValues(ah, coef_scaled, &ds_coef_man, &ds_coef_exp);
710
711         OS_REG_RMW_FIELD(ah, AR_PHY_TIMING3,
712                 AR_PHY_TIMING3_DSC_MAN, ds_coef_man);
713         OS_REG_RMW_FIELD(ah, AR_PHY_TIMING3,
714                 AR_PHY_TIMING3_DSC_EXP, ds_coef_exp);
715
716         /*
717          * For Short GI,
718          * scaled coeff is 9/10 that of normal coeff
719          */ 
720         coef_scaled = (9 * coef_scaled)/10;
721
722         ar5416GetDeltaSlopeValues(ah, coef_scaled, &ds_coef_man, &ds_coef_exp);
723
724         /* for short gi */
725         OS_REG_RMW_FIELD(ah, AR_PHY_HALFGI,
726                 AR_PHY_HALFGI_DSC_MAN, ds_coef_man);
727         OS_REG_RMW_FIELD(ah, AR_PHY_HALFGI,
728                 AR_PHY_HALFGI_DSC_EXP, ds_coef_exp);    
729 #undef INIT_CLOCKMHZSCALED
730 }
731
732 /*
733  * Set a limit on the overall output power.  Used for dynamic
734  * transmit power control and the like.
735  *
736  * NB: limit is in units of 0.5 dbM.
737  */
738 HAL_BOOL
739 ar5416SetTxPowerLimit(struct ath_hal *ah, uint32_t limit)
740 {
741         uint16_t dummyXpdGains[2];
742
743         AH_PRIVATE(ah)->ah_powerLimit = AH_MIN(limit, MAX_RATE_POWER);
744         return ar5416SetTransmitPower(ah, AH_PRIVATE(ah)->ah_curchan,
745                         dummyXpdGains);
746 }
747
748 HAL_BOOL
749 ar5416GetChipPowerLimits(struct ath_hal *ah,
750         struct ieee80211_channel *chan)
751 {
752         struct ath_hal_5212 *ahp = AH5212(ah);
753         int16_t minPower, maxPower;
754
755         /*
756          * Get Pier table max and min powers.
757          */
758         if (ahp->ah_rfHal->getChannelMaxMinPower(ah, chan, &maxPower, &minPower)) {
759                 /* NB: rf code returns 1/4 dBm units, convert */
760                 chan->ic_maxpower = maxPower / 2;
761                 chan->ic_minpower = minPower / 2;
762         } else {
763                 HALDEBUG(ah, HAL_DEBUG_ANY,
764                     "%s: no min/max power for %u/0x%x\n",
765                     __func__, chan->ic_freq, chan->ic_flags);
766                 chan->ic_maxpower = AR5416_MAX_RATE_POWER;
767                 chan->ic_minpower = 0;
768         }
769         HALDEBUG(ah, HAL_DEBUG_RESET,
770             "Chan %d: MaxPow = %d MinPow = %d\n",
771             chan->ic_freq, chan->ic_maxpower, chan->ic_minpower);
772         return AH_TRUE;
773 }
774
775 /* XXX gag, this is sick */
776 typedef enum Ar5416_Rates {
777         rate6mb,  rate9mb,  rate12mb, rate18mb,
778         rate24mb, rate36mb, rate48mb, rate54mb,
779         rate1l,   rate2l,   rate2s,   rate5_5l,
780         rate5_5s, rate11l,  rate11s,  rateXr,
781         rateHt20_0, rateHt20_1, rateHt20_2, rateHt20_3,
782         rateHt20_4, rateHt20_5, rateHt20_6, rateHt20_7,
783         rateHt40_0, rateHt40_1, rateHt40_2, rateHt40_3,
784         rateHt40_4, rateHt40_5, rateHt40_6, rateHt40_7,
785         rateDupCck, rateDupOfdm, rateExtCck, rateExtOfdm,
786         Ar5416RateSize
787 } AR5416_RATES;
788
789 /**************************************************************
790  * ar5416SetTransmitPower
791  *
792  * Set the transmit power in the baseband for the given
793  * operating channel and mode.
794  */
795 HAL_BOOL
796 ar5416SetTransmitPower(struct ath_hal *ah,
797         const struct ieee80211_channel *chan, uint16_t *rfXpdGain)
798 {
799 #define POW_SM(_r, _s)     (((_r) & 0x3f) << (_s))
800
801     MODAL_EEP_HEADER    *pModal;
802     struct ath_hal_5212 *ahp = AH5212(ah);
803     int16_t             ratesArray[Ar5416RateSize];
804     int16_t             txPowerIndexOffset = 0;
805     uint8_t             ht40PowerIncForPdadc = 2;       
806     int                 i;
807     
808     uint16_t            cfgCtl;
809     uint16_t            powerLimit;
810     uint16_t            twiceAntennaReduction;
811     uint16_t            twiceMaxRegulatoryPower;
812     int16_t             maxPower;
813     HAL_EEPROM_v14 *ee = AH_PRIVATE(ah)->ah_eeprom;
814     struct ar5416eeprom *pEepData = &ee->ee_base;
815
816     HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER14_1);
817
818     /* Setup info for the actual eeprom */
819     OS_MEMZERO(ratesArray, sizeof(ratesArray));
820     cfgCtl = ath_hal_getctl(ah, chan);
821     powerLimit = chan->ic_maxregpower * 2;
822     twiceAntennaReduction = chan->ic_maxantgain;
823     twiceMaxRegulatoryPower = AH_MIN(MAX_RATE_POWER, AH_PRIVATE(ah)->ah_powerLimit); 
824     pModal = &pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)];
825     HALDEBUG(ah, HAL_DEBUG_RESET, "%s Channel=%u CfgCtl=%u\n",
826         __func__,chan->ic_freq, cfgCtl );      
827   
828     if (IS_EEP_MINOR_V2(ah)) {
829         ht40PowerIncForPdadc = pModal->ht40PowerIncForPdadc;
830     }
831  
832     if (!ar5416SetPowerPerRateTable(ah, pEepData,  chan,
833                                     &ratesArray[0],cfgCtl,
834                                     twiceAntennaReduction,
835                                     twiceMaxRegulatoryPower, powerLimit)) {
836         HALDEBUG(ah, HAL_DEBUG_ANY,
837             "%s: unable to set tx power per rate table\n", __func__);
838         return AH_FALSE;
839     }
840
841     if (!ar5416SetPowerCalTable(ah,  pEepData, chan, &txPowerIndexOffset)) {
842         HALDEBUG(ah, HAL_DEBUG_ANY, "%s: unable to set power table\n",
843             __func__);
844         return AH_FALSE;
845     }
846   
847     maxPower = AH_MAX(ratesArray[rate6mb], ratesArray[rateHt20_0]);
848
849     if (IEEE80211_IS_CHAN_2GHZ(chan)) {
850         maxPower = AH_MAX(maxPower, ratesArray[rate1l]);
851     }
852
853     if (IEEE80211_IS_CHAN_HT40(chan)) {
854         maxPower = AH_MAX(maxPower, ratesArray[rateHt40_0]);
855     }
856
857     ahp->ah_tx6PowerInHalfDbm = maxPower;   
858     AH_PRIVATE(ah)->ah_maxPowerLevel = maxPower;
859     ahp->ah_txPowerIndexOffset = txPowerIndexOffset;
860
861     /*
862      * txPowerIndexOffset is set by the SetPowerTable() call -
863      *  adjust the rate table (0 offset if rates EEPROM not loaded)
864      */
865     for (i = 0; i < NELEM(ratesArray); i++) {
866         ratesArray[i] = (int16_t)(txPowerIndexOffset + ratesArray[i]);
867         if (ratesArray[i] > AR5416_MAX_RATE_POWER)
868             ratesArray[i] = AR5416_MAX_RATE_POWER;
869     }
870
871 #ifdef AH_EEPROM_DUMP
872     ar5416PrintPowerPerRate(ah, ratesArray);
873 #endif
874
875     /* Write the OFDM power per rate set */
876     OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE1,
877         POW_SM(ratesArray[rate18mb], 24)
878           | POW_SM(ratesArray[rate12mb], 16)
879           | POW_SM(ratesArray[rate9mb], 8)
880           | POW_SM(ratesArray[rate6mb], 0)
881     );
882     OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE2,
883         POW_SM(ratesArray[rate54mb], 24)
884           | POW_SM(ratesArray[rate48mb], 16)
885           | POW_SM(ratesArray[rate36mb], 8)
886           | POW_SM(ratesArray[rate24mb], 0)
887     );
888
889     if (IEEE80211_IS_CHAN_2GHZ(chan)) {
890         /* Write the CCK power per rate set */
891         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE3,
892             POW_SM(ratesArray[rate2s], 24)
893               | POW_SM(ratesArray[rate2l],  16)
894               | POW_SM(ratesArray[rateXr],  8) /* XR target power */
895               | POW_SM(ratesArray[rate1l],   0)
896         );
897         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE4,
898             POW_SM(ratesArray[rate11s], 24)
899               | POW_SM(ratesArray[rate11l], 16)
900               | POW_SM(ratesArray[rate5_5s], 8)
901               | POW_SM(ratesArray[rate5_5l], 0)
902         );
903     HALDEBUG(ah, HAL_DEBUG_RESET,
904         "%s AR_PHY_POWER_TX_RATE3=0x%x AR_PHY_POWER_TX_RATE4=0x%x\n",
905             __func__, OS_REG_READ(ah,AR_PHY_POWER_TX_RATE3),
906             OS_REG_READ(ah,AR_PHY_POWER_TX_RATE4)); 
907     }
908
909     /* Write the HT20 power per rate set */
910     OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE5,
911         POW_SM(ratesArray[rateHt20_3], 24)
912           | POW_SM(ratesArray[rateHt20_2], 16)
913           | POW_SM(ratesArray[rateHt20_1], 8)
914           | POW_SM(ratesArray[rateHt20_0], 0)
915     );
916     OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE6,
917         POW_SM(ratesArray[rateHt20_7], 24)
918           | POW_SM(ratesArray[rateHt20_6], 16)
919           | POW_SM(ratesArray[rateHt20_5], 8)
920           | POW_SM(ratesArray[rateHt20_4], 0)
921     );
922
923     if (IEEE80211_IS_CHAN_HT40(chan)) {
924         /* Write the HT40 power per rate set */
925         /* Correct PAR difference between HT40 and HT20/LEGACY */
926         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE7,
927             POW_SM(ratesArray[rateHt40_3] + ht40PowerIncForPdadc, 24)
928               | POW_SM(ratesArray[rateHt40_2] + ht40PowerIncForPdadc, 16)
929               | POW_SM(ratesArray[rateHt40_1] + ht40PowerIncForPdadc, 8)
930               | POW_SM(ratesArray[rateHt40_0] + ht40PowerIncForPdadc, 0)
931         );
932         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE8,
933             POW_SM(ratesArray[rateHt40_7] + ht40PowerIncForPdadc, 24)
934               | POW_SM(ratesArray[rateHt40_6] + ht40PowerIncForPdadc, 16)
935               | POW_SM(ratesArray[rateHt40_5] + ht40PowerIncForPdadc, 8)
936               | POW_SM(ratesArray[rateHt40_4] + ht40PowerIncForPdadc, 0)
937         );
938         /* Write the Dup/Ext 40 power per rate set */
939         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE9,
940             POW_SM(ratesArray[rateExtOfdm], 24)
941               | POW_SM(ratesArray[rateExtCck], 16)
942               | POW_SM(ratesArray[rateDupOfdm], 8)
943               | POW_SM(ratesArray[rateDupCck], 0)
944         );
945     }
946
947     /* Write the Power subtraction for dynamic chain changing, for per-packet powertx */
948     OS_REG_WRITE(ah, AR_PHY_POWER_TX_SUB,
949         POW_SM(pModal->pwrDecreaseFor3Chain, 6)
950           | POW_SM(pModal->pwrDecreaseFor2Chain, 0)
951     );
952     return AH_TRUE;
953 #undef POW_SM
954 }
955
956 /*
957  * Exported call to check for a recent gain reading and return
958  * the current state of the thermal calibration gain engine.
959  */
960 HAL_RFGAIN
961 ar5416GetRfgain(struct ath_hal *ah)
962 {
963         return HAL_RFGAIN_INACTIVE;
964 }
965
966 /*
967  * Places all of hardware into reset
968  */
969 HAL_BOOL
970 ar5416Disable(struct ath_hal *ah)
971 {
972         if (!ar5212SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
973                 return AH_FALSE;
974         return ar5416SetResetReg(ah, HAL_RESET_COLD);
975 }
976
977 /*
978  * Places the PHY and Radio chips into reset.  A full reset
979  * must be called to leave this state.  The PCI/MAC/PCU are
980  * not placed into reset as we must receive interrupt to
981  * re-enable the hardware.
982  */
983 HAL_BOOL
984 ar5416PhyDisable(struct ath_hal *ah)
985 {
986         return ar5416SetResetReg(ah, HAL_RESET_WARM);
987 }
988
989 /*
990  * Write the given reset bit mask into the reset register
991  */
992 HAL_BOOL
993 ar5416SetResetReg(struct ath_hal *ah, uint32_t type)
994 {
995         switch (type) {
996         case HAL_RESET_POWER_ON:
997                 return ar5416SetResetPowerOn(ah);
998         case HAL_RESET_WARM:
999         case HAL_RESET_COLD:
1000                 return ar5416SetReset(ah, type);
1001         default:
1002                 HALASSERT(AH_FALSE);
1003                 return AH_FALSE;
1004         }
1005 }
1006
1007 static HAL_BOOL
1008 ar5416SetResetPowerOn(struct ath_hal *ah)
1009 {
1010     /* Power On Reset (Hard Reset) */
1011
1012     /*
1013      * Set force wake
1014      *  
1015      * If the MAC was running, previously calling
1016      * reset will wake up the MAC but it may go back to sleep
1017      * before we can start polling. 
1018      * Set force wake  stops that 
1019      * This must be called before initiating a hard reset.
1020      */
1021     OS_REG_WRITE(ah, AR_RTC_FORCE_WAKE,
1022             AR_RTC_FORCE_WAKE_EN | AR_RTC_FORCE_WAKE_ON_INT);    
1023
1024     /*
1025      * RTC reset and clear
1026      */
1027     OS_REG_WRITE(ah, AR_RC, AR_RC_AHB);
1028     OS_REG_WRITE(ah, AR_RTC_RESET, 0);
1029     OS_DELAY(20);
1030     OS_REG_WRITE(ah, AR_RC, 0);
1031
1032     OS_REG_WRITE(ah, AR_RTC_RESET, 1);
1033
1034     /*
1035      * Poll till RTC is ON
1036      */
1037     if (!ath_hal_wait(ah, AR_RTC_STATUS, AR_RTC_PM_STATUS_M, AR_RTC_STATUS_ON)) {
1038         HALDEBUG(ah, HAL_DEBUG_ANY, "%s: RTC not waking up\n", __func__);
1039         return AH_FALSE;
1040     }
1041
1042     return ar5416SetReset(ah, HAL_RESET_COLD);
1043 }
1044
1045 static HAL_BOOL
1046 ar5416SetReset(struct ath_hal *ah, int type)
1047 {
1048     uint32_t tmpReg, mask;
1049
1050     /*
1051      * Force wake
1052      */
1053     OS_REG_WRITE(ah, AR_RTC_FORCE_WAKE,
1054         AR_RTC_FORCE_WAKE_EN | AR_RTC_FORCE_WAKE_ON_INT);
1055
1056     /*
1057      * Reset AHB
1058      */
1059     tmpReg = OS_REG_READ(ah, AR_INTR_SYNC_CAUSE);
1060     if (tmpReg & (AR_INTR_SYNC_LOCAL_TIMEOUT|AR_INTR_SYNC_RADM_CPL_TIMEOUT)) {
1061         OS_REG_WRITE(ah, AR_INTR_SYNC_ENABLE, 0);
1062         OS_REG_WRITE(ah, AR_RC, AR_RC_AHB|AR_RC_HOSTIF);
1063     } else {
1064         OS_REG_WRITE(ah, AR_RC, AR_RC_AHB);
1065     }
1066
1067     /*
1068      * Set Mac(BB,Phy) Warm Reset
1069      */
1070     switch (type) {
1071     case HAL_RESET_WARM:
1072             OS_REG_WRITE(ah, AR_RTC_RC, AR_RTC_RC_MAC_WARM);
1073             break;
1074     case HAL_RESET_COLD:
1075             OS_REG_WRITE(ah, AR_RTC_RC, AR_RTC_RC_MAC_WARM|AR_RTC_RC_MAC_COLD);
1076             break;
1077     default:
1078             HALASSERT(AH_FALSE);
1079             break;
1080     }
1081
1082     /*
1083      * Clear resets and force wakeup
1084      */
1085     OS_REG_WRITE(ah, AR_RTC_RC, 0);
1086     if (!ath_hal_wait(ah, AR_RTC_RC, AR_RTC_RC_M, 0)) {
1087         HALDEBUG(ah, HAL_DEBUG_ANY, "%s: RTC stuck in MAC reset\n", __func__);
1088         return AH_FALSE;
1089     }
1090
1091     /* Clear AHB reset */
1092     OS_REG_WRITE(ah, AR_RC, 0);
1093
1094         if (type == HAL_RESET_COLD) {
1095                 if (isBigEndian()) {
1096                         /*
1097                          * Set CFG, little-endian for register
1098                          * and descriptor accesses.
1099                          */
1100                         mask = INIT_CONFIG_STATUS | AR_CFG_SWRD | AR_CFG_SWRG;
1101 #ifndef AH_NEED_DESC_SWAP
1102                         mask |= AR_CFG_SWTD;
1103 #endif
1104                         HALDEBUG(ah, HAL_DEBUG_RESET,
1105                             "%s Applying descriptor swap\n", __func__);
1106                         OS_REG_WRITE(ah, AR_CFG, LE_READ_4(&mask));
1107                 } else
1108                         OS_REG_WRITE(ah, AR_CFG, INIT_CONFIG_STATUS);
1109         }
1110
1111     ar5416InitPLL(ah, AH_NULL);
1112
1113     return AH_TRUE;
1114 }
1115
1116 #ifndef IS_5GHZ_FAST_CLOCK_EN
1117 #define IS_5GHZ_FAST_CLOCK_EN(ah, chan) AH_FALSE
1118 #endif
1119
1120 static void
1121 ar5416InitPLL(struct ath_hal *ah, const struct ieee80211_channel *chan)
1122 {
1123         uint32_t pll;
1124
1125         if (AR_SREV_MERLIN_20(ah) &&
1126             chan != AH_NULL && IEEE80211_IS_CHAN_5GHZ(chan)) {
1127                 /*
1128                  * PLL WAR for Merlin 2.0/2.1
1129                  * When doing fast clock, set PLL to 0x142c
1130                  * Else, set PLL to 0x2850 to prevent reset-to-reset variation 
1131                  */
1132                 pll = IS_5GHZ_FAST_CLOCK_EN(ah, chan) ? 0x142c : 0x2850;
1133         } else if (AR_SREV_MERLIN_10_OR_LATER(ah)) {
1134                 pll = SM(0x5, AR_RTC_SOWL_PLL_REFDIV);
1135                 if (chan != AH_NULL) {
1136                         if (IEEE80211_IS_CHAN_HALF(chan))
1137                                 pll |= SM(0x1, AR_RTC_SOWL_PLL_CLKSEL);
1138                         else if (IEEE80211_IS_CHAN_QUARTER(chan))
1139                                 pll |= SM(0x2, AR_RTC_SOWL_PLL_CLKSEL);
1140                         else if (IEEE80211_IS_CHAN_5GHZ(chan))
1141                                 pll |= SM(0x28, AR_RTC_SOWL_PLL_DIV);
1142                         else
1143                                 pll |= SM(0x2c, AR_RTC_SOWL_PLL_DIV);
1144                 } else
1145                         pll |= SM(0x2c, AR_RTC_SOWL_PLL_DIV);
1146         } else if (AR_SREV_SOWL_10_OR_LATER(ah)) {
1147                 pll = SM(0x5, AR_RTC_SOWL_PLL_REFDIV);
1148                 if (chan != AH_NULL) {
1149                         if (IEEE80211_IS_CHAN_HALF(chan))
1150                                 pll |= SM(0x1, AR_RTC_SOWL_PLL_CLKSEL);
1151                         else if (IEEE80211_IS_CHAN_QUARTER(chan))
1152                                 pll |= SM(0x2, AR_RTC_SOWL_PLL_CLKSEL);
1153                         else if (IEEE80211_IS_CHAN_5GHZ(chan))
1154                                 pll |= SM(0x50, AR_RTC_SOWL_PLL_DIV);
1155                         else
1156                                 pll |= SM(0x58, AR_RTC_SOWL_PLL_DIV);
1157                 } else
1158                         pll |= SM(0x58, AR_RTC_SOWL_PLL_DIV);
1159         } else {
1160                 pll = AR_RTC_PLL_REFDIV_5 | AR_RTC_PLL_DIV2;
1161                 if (chan != AH_NULL) {
1162                         if (IEEE80211_IS_CHAN_HALF(chan))
1163                                 pll |= SM(0x1, AR_RTC_PLL_CLKSEL);
1164                         else if (IEEE80211_IS_CHAN_QUARTER(chan))
1165                                 pll |= SM(0x2, AR_RTC_PLL_CLKSEL);
1166                         else if (IEEE80211_IS_CHAN_5GHZ(chan))
1167                                 pll |= SM(0xa, AR_RTC_PLL_DIV);
1168                         else
1169                                 pll |= SM(0xb, AR_RTC_PLL_DIV);
1170                 } else
1171                         pll |= SM(0xb, AR_RTC_PLL_DIV);
1172         }
1173         OS_REG_WRITE(ah, AR_RTC_PLL_CONTROL, pll);
1174
1175         /* TODO:
1176         * For multi-band owl, switch between bands by reiniting the PLL.
1177         */
1178
1179         OS_DELAY(RTC_PLL_SETTLE_DELAY);
1180
1181         OS_REG_WRITE(ah, AR_RTC_SLEEP_CLK, AR_RTC_SLEEP_DERIVED_CLK);
1182 }
1183
1184 /*
1185  * Read EEPROM header info and program the device for correct operation
1186  * given the channel value.
1187  */
1188 HAL_BOOL
1189 ar5416SetBoardValues(struct ath_hal *ah, const struct ieee80211_channel *chan)
1190 {
1191     const HAL_EEPROM_v14 *ee = AH_PRIVATE(ah)->ah_eeprom;
1192     const struct ar5416eeprom *eep = &ee->ee_base;
1193     const MODAL_EEP_HEADER *pModal;
1194     int                 i, regChainOffset;
1195     uint8_t             txRxAttenLocal;    /* workaround for eeprom versions <= 14.2 */
1196
1197     HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER14_1);
1198     pModal = &eep->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)];
1199
1200     /* NB: workaround for eeprom versions <= 14.2 */
1201     txRxAttenLocal = IEEE80211_IS_CHAN_2GHZ(chan) ? 23 : 44;
1202
1203     OS_REG_WRITE(ah, AR_PHY_SWITCH_COM, pModal->antCtrlCommon);
1204     for (i = 0; i < AR5416_MAX_CHAINS; i++) { 
1205            if (AR_SREV_MERLIN(ah)) {
1206                 if (i >= 2) break;
1207            }
1208            if (AR_SREV_OWL_20_OR_LATER(ah) &&
1209             (AH5416(ah)->ah_rx_chainmask == 0x5 ||
1210              AH5416(ah)->ah_tx_chainmask == 0x5) && i != 0) {
1211             /* Regs are swapped from chain 2 to 1 for 5416 2_0 with 
1212              * only chains 0 and 2 populated 
1213              */
1214             regChainOffset = (i == 1) ? 0x2000 : 0x1000;
1215         } else {
1216             regChainOffset = i * 0x1000;
1217         }
1218
1219         OS_REG_WRITE(ah, AR_PHY_SWITCH_CHAIN_0 + regChainOffset, pModal->antCtrlChain[i]);
1220         OS_REG_WRITE(ah, AR_PHY_TIMING_CTRL4 + regChainOffset, 
1221                 (OS_REG_READ(ah, AR_PHY_TIMING_CTRL4 + regChainOffset) &
1222                 ~(AR_PHY_TIMING_CTRL4_IQCORR_Q_Q_COFF | AR_PHY_TIMING_CTRL4_IQCORR_Q_I_COFF)) |
1223                 SM(pModal->iqCalICh[i], AR_PHY_TIMING_CTRL4_IQCORR_Q_I_COFF) |
1224                 SM(pModal->iqCalQCh[i], AR_PHY_TIMING_CTRL4_IQCORR_Q_Q_COFF));
1225
1226         /*
1227          * Large signal upgrade.
1228          * XXX update
1229          */
1230
1231         if ((i == 0) || AR_SREV_OWL_20_OR_LATER(ah)) {
1232             OS_REG_WRITE(ah, AR_PHY_RXGAIN + regChainOffset, 
1233                 (OS_REG_READ(ah, AR_PHY_RXGAIN + regChainOffset) & ~AR_PHY_RXGAIN_TXRX_ATTEN) |
1234                         SM(IS_EEP_MINOR_V3(ah)  ? pModal->txRxAttenCh[i] : txRxAttenLocal,
1235                                 AR_PHY_RXGAIN_TXRX_ATTEN));
1236
1237             OS_REG_WRITE(ah, AR_PHY_GAIN_2GHZ + regChainOffset, 
1238                 (OS_REG_READ(ah, AR_PHY_GAIN_2GHZ + regChainOffset) & ~AR_PHY_GAIN_2GHZ_RXTX_MARGIN) |
1239                         SM(pModal->rxTxMarginCh[i], AR_PHY_GAIN_2GHZ_RXTX_MARGIN));
1240         }
1241     }
1242
1243     OS_REG_RMW_FIELD(ah, AR_PHY_SETTLING, AR_PHY_SETTLING_SWITCH, pModal->switchSettling);
1244     OS_REG_RMW_FIELD(ah, AR_PHY_DESIRED_SZ, AR_PHY_DESIRED_SZ_ADC, pModal->adcDesiredSize);
1245     OS_REG_RMW_FIELD(ah, AR_PHY_DESIRED_SZ, AR_PHY_DESIRED_SZ_PGA, pModal->pgaDesiredSize);
1246     OS_REG_WRITE(ah, AR_PHY_RF_CTL4,
1247         SM(pModal->txEndToXpaOff, AR_PHY_RF_CTL4_TX_END_XPAA_OFF)
1248         | SM(pModal->txEndToXpaOff, AR_PHY_RF_CTL4_TX_END_XPAB_OFF)
1249         | SM(pModal->txFrameToXpaOn, AR_PHY_RF_CTL4_FRAME_XPAA_ON)
1250         | SM(pModal->txFrameToXpaOn, AR_PHY_RF_CTL4_FRAME_XPAB_ON));
1251
1252     OS_REG_RMW_FIELD(ah, AR_PHY_RF_CTL3, AR_PHY_TX_END_TO_A2_RX_ON, pModal->txEndToRxOn);
1253
1254     if (AR_SREV_MERLIN_10_OR_LATER(ah)) {
1255         OS_REG_RMW_FIELD(ah, AR_PHY_CCA, AR9280_PHY_CCA_THRESH62,
1256             pModal->thresh62);
1257         OS_REG_RMW_FIELD(ah, AR_PHY_EXT_CCA0, AR_PHY_EXT_CCA0_THRESH62,
1258             pModal->thresh62);
1259     } else {
1260         OS_REG_RMW_FIELD(ah, AR_PHY_CCA, AR_PHY_CCA_THRESH62,
1261             pModal->thresh62);
1262         OS_REG_RMW_FIELD(ah, AR_PHY_EXT_CCA0, AR_PHY_EXT_CCA_THRESH62,
1263             pModal->thresh62);
1264     }
1265     
1266     /* Minor Version Specific application */
1267     if (IS_EEP_MINOR_V2(ah)) {
1268         OS_REG_RMW_FIELD(ah, AR_PHY_RF_CTL2,  AR_PHY_TX_FRAME_TO_DATA_START, pModal->txFrameToDataStart);
1269         OS_REG_RMW_FIELD(ah, AR_PHY_RF_CTL2,  AR_PHY_TX_FRAME_TO_PA_ON, pModal->txFrameToPaOn);    
1270     }   
1271     
1272     if (IS_EEP_MINOR_V3(ah)) {
1273         if (IEEE80211_IS_CHAN_HT40(chan)) {
1274                 /* Overwrite switch settling with HT40 value */
1275                 OS_REG_RMW_FIELD(ah, AR_PHY_SETTLING, AR_PHY_SETTLING_SWITCH, pModal->swSettleHt40);
1276         }
1277         
1278         if ((AR_SREV_OWL_20_OR_LATER(ah)) &&
1279             (  AH5416(ah)->ah_rx_chainmask == 0x5 || AH5416(ah)->ah_tx_chainmask == 0x5)){
1280             /* Reg Offsets are swapped for logical mapping */
1281                 OS_REG_WRITE(ah, AR_PHY_GAIN_2GHZ + 0x1000, (OS_REG_READ(ah, AR_PHY_GAIN_2GHZ + 0x1000) & ~AR_PHY_GAIN_2GHZ_BSW_MARGIN) |
1282                         SM(pModal->bswMargin[2], AR_PHY_GAIN_2GHZ_BSW_MARGIN));
1283                 OS_REG_WRITE(ah, AR_PHY_GAIN_2GHZ + 0x1000, (OS_REG_READ(ah, AR_PHY_GAIN_2GHZ + 0x1000) & ~AR_PHY_GAIN_2GHZ_BSW_ATTEN) |
1284                         SM(pModal->bswAtten[2], AR_PHY_GAIN_2GHZ_BSW_ATTEN));
1285                 OS_REG_WRITE(ah, AR_PHY_GAIN_2GHZ + 0x2000, (OS_REG_READ(ah, AR_PHY_GAIN_2GHZ + 0x2000) & ~AR_PHY_GAIN_2GHZ_BSW_MARGIN) |
1286                         SM(pModal->bswMargin[1], AR_PHY_GAIN_2GHZ_BSW_MARGIN));
1287                 OS_REG_WRITE(ah, AR_PHY_GAIN_2GHZ + 0x2000, (OS_REG_READ(ah, AR_PHY_GAIN_2GHZ + 0x2000) & ~AR_PHY_GAIN_2GHZ_BSW_ATTEN) |
1288                         SM(pModal->bswAtten[1], AR_PHY_GAIN_2GHZ_BSW_ATTEN));
1289         } else {
1290                 OS_REG_WRITE(ah, AR_PHY_GAIN_2GHZ + 0x1000, (OS_REG_READ(ah, AR_PHY_GAIN_2GHZ + 0x1000) & ~AR_PHY_GAIN_2GHZ_BSW_MARGIN) |
1291                         SM(pModal->bswMargin[1], AR_PHY_GAIN_2GHZ_BSW_MARGIN));
1292                 OS_REG_WRITE(ah, AR_PHY_GAIN_2GHZ + 0x1000, (OS_REG_READ(ah, AR_PHY_GAIN_2GHZ + 0x1000) & ~AR_PHY_GAIN_2GHZ_BSW_ATTEN) |
1293                         SM(pModal->bswAtten[1], AR_PHY_GAIN_2GHZ_BSW_ATTEN));
1294                 OS_REG_WRITE(ah, AR_PHY_GAIN_2GHZ + 0x2000, (OS_REG_READ(ah, AR_PHY_GAIN_2GHZ + 0x2000) & ~AR_PHY_GAIN_2GHZ_BSW_MARGIN) |
1295                         SM(pModal->bswMargin[2],AR_PHY_GAIN_2GHZ_BSW_MARGIN));
1296                 OS_REG_WRITE(ah, AR_PHY_GAIN_2GHZ + 0x2000, (OS_REG_READ(ah, AR_PHY_GAIN_2GHZ + 0x2000) & ~AR_PHY_GAIN_2GHZ_BSW_ATTEN) |
1297                         SM(pModal->bswAtten[2], AR_PHY_GAIN_2GHZ_BSW_ATTEN));
1298         }
1299         OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ, AR_PHY_GAIN_2GHZ_BSW_MARGIN, pModal->bswMargin[0]);
1300         OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ, AR_PHY_GAIN_2GHZ_BSW_ATTEN, pModal->bswAtten[0]);
1301     }
1302     return AH_TRUE;
1303 }
1304
1305 /*
1306  * Helper functions common for AP/CB/XB
1307  */
1308
1309 /*
1310  * ar5416SetPowerPerRateTable
1311  *
1312  * Sets the transmit power in the baseband for the given
1313  * operating channel and mode.
1314  */
1315 static HAL_BOOL
1316 ar5416SetPowerPerRateTable(struct ath_hal *ah, struct ar5416eeprom *pEepData,
1317                            const struct ieee80211_channel *chan,
1318                            int16_t *ratesArray, uint16_t cfgCtl,
1319                            uint16_t AntennaReduction, 
1320                            uint16_t twiceMaxRegulatoryPower,
1321                            uint16_t powerLimit)
1322 {
1323 /* Local defines to distinguish between extension and control CTL's */
1324 #define EXT_ADDITIVE (0x8000)
1325 #define CTL_11A_EXT (CTL_11A | EXT_ADDITIVE)
1326 #define CTL_11G_EXT (CTL_11G | EXT_ADDITIVE)
1327 #define CTL_11B_EXT (CTL_11B | EXT_ADDITIVE)
1328
1329         uint16_t twiceMaxEdgePower = AR5416_MAX_RATE_POWER;
1330         int i;
1331         int16_t  twiceLargestAntenna;
1332         CAL_CTL_DATA *rep;
1333         CAL_TARGET_POWER_LEG targetPowerOfdm, targetPowerCck = {0, {0, 0, 0, 0}};
1334         CAL_TARGET_POWER_LEG targetPowerOfdmExt = {0, {0, 0, 0, 0}}, targetPowerCckExt = {0, {0, 0, 0, 0}};
1335         CAL_TARGET_POWER_HT  targetPowerHt20, targetPowerHt40 = {0, {0, 0, 0, 0}};
1336         int16_t scaledPower, minCtlPower;
1337
1338 #define SUB_NUM_CTL_MODES_AT_5G_40 2   /* excluding HT40, EXT-OFDM */
1339 #define SUB_NUM_CTL_MODES_AT_2G_40 3   /* excluding HT40, EXT-OFDM, EXT-CCK */
1340         static const uint16_t ctlModesFor11a[] = {
1341            CTL_11A, CTL_5GHT20, CTL_11A_EXT, CTL_5GHT40
1342         };
1343         static const uint16_t ctlModesFor11g[] = {
1344            CTL_11B, CTL_11G, CTL_2GHT20, CTL_11B_EXT, CTL_11G_EXT, CTL_2GHT40
1345         };
1346         const uint16_t *pCtlMode;
1347         uint16_t numCtlModes, ctlMode, freq;
1348         CHAN_CENTERS centers;
1349
1350         ar5416GetChannelCenters(ah,  chan, &centers);
1351
1352         /* Compute TxPower reduction due to Antenna Gain */
1353
1354         twiceLargestAntenna = AH_MAX(AH_MAX(
1355             pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[0],
1356             pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[1]),
1357             pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[2]);
1358 #if 0
1359         /* Turn it back on if we need to calculate per chain antenna gain reduction */
1360         /* Use only if the expected gain > 6dbi */
1361         /* Chain 0 is always used */
1362         twiceLargestAntenna = pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[0];
1363
1364         /* Look at antenna gains of Chains 1 and 2 if the TX mask is set */
1365         if (ahp->ah_tx_chainmask & 0x2)
1366                 twiceLargestAntenna = AH_MAX(twiceLargestAntenna,
1367                         pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[1]);
1368
1369         if (ahp->ah_tx_chainmask & 0x4)
1370                 twiceLargestAntenna = AH_MAX(twiceLargestAntenna,
1371                         pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[2]);
1372 #endif
1373         twiceLargestAntenna = (int16_t)AH_MIN((AntennaReduction) - twiceLargestAntenna, 0);
1374
1375         /* XXX setup for 5212 use (really used?) */
1376         ath_hal_eepromSet(ah,
1377             IEEE80211_IS_CHAN_2GHZ(chan) ? AR_EEP_ANTGAINMAX_2 : AR_EEP_ANTGAINMAX_5,
1378             twiceLargestAntenna);
1379
1380         /* 
1381          * scaledPower is the minimum of the user input power level and
1382          * the regulatory allowed power level
1383          */
1384         scaledPower = AH_MIN(powerLimit, twiceMaxRegulatoryPower + twiceLargestAntenna);
1385
1386         /* Reduce scaled Power by number of chains active to get to per chain tx power level */
1387         /* TODO: better value than these? */
1388         switch (owl_get_ntxchains(AH5416(ah)->ah_tx_chainmask)) {
1389         case 1:
1390                 break;
1391         case 2:
1392                 scaledPower -= pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].pwrDecreaseFor2Chain;
1393                 break;
1394         case 3:
1395                 scaledPower -= pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].pwrDecreaseFor3Chain;
1396                 break;
1397         default:
1398                 return AH_FALSE; /* Unsupported number of chains */
1399         }
1400
1401         scaledPower = AH_MAX(0, scaledPower);
1402
1403         /* Get target powers from EEPROM - our baseline for TX Power */
1404         if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1405                 /* Setup for CTL modes */
1406                 numCtlModes = NELEM(ctlModesFor11g) - SUB_NUM_CTL_MODES_AT_2G_40; /* CTL_11B, CTL_11G, CTL_2GHT20 */
1407                 pCtlMode = ctlModesFor11g;
1408
1409                 ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPowerCck,
1410                                 AR5416_NUM_2G_CCK_TARGET_POWERS, &targetPowerCck, 4, AH_FALSE);
1411                 ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPower2G,
1412                                 AR5416_NUM_2G_20_TARGET_POWERS, &targetPowerOfdm, 4, AH_FALSE);
1413                 ar5416GetTargetPowers(ah,  chan, pEepData->calTargetPower2GHT20,
1414                                 AR5416_NUM_2G_20_TARGET_POWERS, &targetPowerHt20, 8, AH_FALSE);
1415
1416                 if (IEEE80211_IS_CHAN_HT40(chan)) {
1417                         numCtlModes = NELEM(ctlModesFor11g);    /* All 2G CTL's */
1418
1419                         ar5416GetTargetPowers(ah,  chan, pEepData->calTargetPower2GHT40,
1420                                 AR5416_NUM_2G_40_TARGET_POWERS, &targetPowerHt40, 8, AH_TRUE);
1421                         /* Get target powers for extension channels */
1422                         ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPowerCck,
1423                                 AR5416_NUM_2G_CCK_TARGET_POWERS, &targetPowerCckExt, 4, AH_TRUE);
1424                         ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPower2G,
1425                                 AR5416_NUM_2G_20_TARGET_POWERS, &targetPowerOfdmExt, 4, AH_TRUE);
1426                 }
1427         } else {
1428                 /* Setup for CTL modes */
1429                 numCtlModes = NELEM(ctlModesFor11a) - SUB_NUM_CTL_MODES_AT_5G_40; /* CTL_11A, CTL_5GHT20 */
1430                 pCtlMode = ctlModesFor11a;
1431
1432                 ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPower5G,
1433                                 AR5416_NUM_5G_20_TARGET_POWERS, &targetPowerOfdm, 4, AH_FALSE);
1434                 ar5416GetTargetPowers(ah,  chan, pEepData->calTargetPower5GHT20,
1435                                 AR5416_NUM_5G_20_TARGET_POWERS, &targetPowerHt20, 8, AH_FALSE);
1436
1437                 if (IEEE80211_IS_CHAN_HT40(chan)) {
1438                         numCtlModes = NELEM(ctlModesFor11a); /* All 5G CTL's */
1439
1440                         ar5416GetTargetPowers(ah,  chan, pEepData->calTargetPower5GHT40,
1441                                 AR5416_NUM_5G_40_TARGET_POWERS, &targetPowerHt40, 8, AH_TRUE);
1442                         ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPower5G,
1443                                 AR5416_NUM_5G_20_TARGET_POWERS, &targetPowerOfdmExt, 4, AH_TRUE);
1444                 }
1445         }
1446
1447         /*
1448          * For MIMO, need to apply regulatory caps individually across dynamically
1449          * running modes: CCK, OFDM, HT20, HT40
1450          *
1451          * The outer loop walks through each possible applicable runtime mode.
1452          * The inner loop walks through each ctlIndex entry in EEPROM.
1453          * The ctl value is encoded as [7:4] == test group, [3:0] == test mode.
1454          *
1455          */
1456         for (ctlMode = 0; ctlMode < numCtlModes; ctlMode++) {
1457                 HAL_BOOL isHt40CtlMode = (pCtlMode[ctlMode] == CTL_5GHT40) ||
1458                     (pCtlMode[ctlMode] == CTL_2GHT40);
1459                 if (isHt40CtlMode) {
1460                         freq = centers.ctl_center;
1461                 } else if (pCtlMode[ctlMode] & EXT_ADDITIVE) {
1462                         freq = centers.ext_center;
1463                 } else {
1464                         freq = centers.ctl_center;
1465                 }
1466
1467                 /* walk through each CTL index stored in EEPROM */
1468                 for (i = 0; (i < AR5416_NUM_CTLS) && pEepData->ctlIndex[i]; i++) {
1469                         uint16_t twiceMinEdgePower;
1470
1471                         /* compare test group from regulatory channel list with test mode from pCtlMode list */
1472                         if ((((cfgCtl & ~CTL_MODE_M) | (pCtlMode[ctlMode] & CTL_MODE_M)) == pEepData->ctlIndex[i]) ||
1473                                 (((cfgCtl & ~CTL_MODE_M) | (pCtlMode[ctlMode] & CTL_MODE_M)) == 
1474                                  ((pEepData->ctlIndex[i] & CTL_MODE_M) | SD_NO_CTL))) {
1475                                 rep = &(pEepData->ctlData[i]);
1476                                 twiceMinEdgePower = ar5416GetMaxEdgePower(freq,
1477                                                         rep->ctlEdges[owl_get_ntxchains(AH5416(ah)->ah_tx_chainmask) - 1],
1478                                                         IEEE80211_IS_CHAN_2GHZ(chan));
1479                                 if ((cfgCtl & ~CTL_MODE_M) == SD_NO_CTL) {
1480                                         /* Find the minimum of all CTL edge powers that apply to this channel */
1481                                         twiceMaxEdgePower = AH_MIN(twiceMaxEdgePower, twiceMinEdgePower);
1482                                 } else {
1483                                         /* specific */
1484                                         twiceMaxEdgePower = twiceMinEdgePower;
1485                                         break;
1486                                 }
1487                         }
1488                 }
1489                 minCtlPower = (uint8_t)AH_MIN(twiceMaxEdgePower, scaledPower);
1490                 /* Apply ctl mode to correct target power set */
1491                 switch(pCtlMode[ctlMode]) {
1492                 case CTL_11B:
1493                         for (i = 0; i < NELEM(targetPowerCck.tPow2x); i++) {
1494                                 targetPowerCck.tPow2x[i] = (uint8_t)AH_MIN(targetPowerCck.tPow2x[i], minCtlPower);
1495                         }
1496                         break;
1497                 case CTL_11A:
1498                 case CTL_11G:
1499                         for (i = 0; i < NELEM(targetPowerOfdm.tPow2x); i++) {
1500                                 targetPowerOfdm.tPow2x[i] = (uint8_t)AH_MIN(targetPowerOfdm.tPow2x[i], minCtlPower);
1501                         }
1502                         break;
1503                 case CTL_5GHT20:
1504                 case CTL_2GHT20:
1505                         for (i = 0; i < NELEM(targetPowerHt20.tPow2x); i++) {
1506                                 targetPowerHt20.tPow2x[i] = (uint8_t)AH_MIN(targetPowerHt20.tPow2x[i], minCtlPower);
1507                         }
1508                         break;
1509                 case CTL_11B_EXT:
1510                         targetPowerCckExt.tPow2x[0] = (uint8_t)AH_MIN(targetPowerCckExt.tPow2x[0], minCtlPower);
1511                         break;
1512                 case CTL_11A_EXT:
1513                 case CTL_11G_EXT:
1514                         targetPowerOfdmExt.tPow2x[0] = (uint8_t)AH_MIN(targetPowerOfdmExt.tPow2x[0], minCtlPower);
1515                         break;
1516                 case CTL_5GHT40:
1517                 case CTL_2GHT40:
1518                         for (i = 0; i < NELEM(targetPowerHt40.tPow2x); i++) {
1519                                 targetPowerHt40.tPow2x[i] = (uint8_t)AH_MIN(targetPowerHt40.tPow2x[i], minCtlPower);
1520                         }
1521                         break;
1522                 default:
1523                         return AH_FALSE;
1524                         break;
1525                 }
1526         } /* end ctl mode checking */
1527
1528         /* Set rates Array from collected data */
1529         ratesArray[rate6mb] = ratesArray[rate9mb] = ratesArray[rate12mb] = ratesArray[rate18mb] = ratesArray[rate24mb] = targetPowerOfdm.tPow2x[0];
1530         ratesArray[rate36mb] = targetPowerOfdm.tPow2x[1];
1531         ratesArray[rate48mb] = targetPowerOfdm.tPow2x[2];
1532         ratesArray[rate54mb] = targetPowerOfdm.tPow2x[3];
1533         ratesArray[rateXr] = targetPowerOfdm.tPow2x[0];
1534
1535         for (i = 0; i < NELEM(targetPowerHt20.tPow2x); i++) {
1536                 ratesArray[rateHt20_0 + i] = targetPowerHt20.tPow2x[i];
1537         }
1538
1539         if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1540                 ratesArray[rate1l]  = targetPowerCck.tPow2x[0];
1541                 ratesArray[rate2s] = ratesArray[rate2l]  = targetPowerCck.tPow2x[1];
1542                 ratesArray[rate5_5s] = ratesArray[rate5_5l] = targetPowerCck.tPow2x[2];
1543                 ratesArray[rate11s] = ratesArray[rate11l] = targetPowerCck.tPow2x[3];
1544         }
1545         if (IEEE80211_IS_CHAN_HT40(chan)) {
1546                 for (i = 0; i < NELEM(targetPowerHt40.tPow2x); i++) {
1547                         ratesArray[rateHt40_0 + i] = targetPowerHt40.tPow2x[i];
1548                 }
1549                 ratesArray[rateDupOfdm] = targetPowerHt40.tPow2x[0];
1550                 ratesArray[rateDupCck]  = targetPowerHt40.tPow2x[0];
1551                 ratesArray[rateExtOfdm] = targetPowerOfdmExt.tPow2x[0];
1552                 if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1553                         ratesArray[rateExtCck]  = targetPowerCckExt.tPow2x[0];
1554                 }
1555         }
1556         return AH_TRUE;
1557 #undef EXT_ADDITIVE
1558 #undef CTL_11A_EXT
1559 #undef CTL_11G_EXT
1560 #undef CTL_11B_EXT
1561 #undef SUB_NUM_CTL_MODES_AT_5G_40
1562 #undef SUB_NUM_CTL_MODES_AT_2G_40
1563 }
1564
1565 /**************************************************************************
1566  * fbin2freq
1567  *
1568  * Get channel value from binary representation held in eeprom
1569  * RETURNS: the frequency in MHz
1570  */
1571 static uint16_t
1572 fbin2freq(uint8_t fbin, HAL_BOOL is2GHz)
1573 {
1574     /*
1575      * Reserved value 0xFF provides an empty definition both as
1576      * an fbin and as a frequency - do not convert
1577      */
1578     if (fbin == AR5416_BCHAN_UNUSED) {
1579         return fbin;
1580     }
1581
1582     return (uint16_t)((is2GHz) ? (2300 + fbin) : (4800 + 5 * fbin));
1583 }
1584
1585 /*
1586  * ar5416GetMaxEdgePower
1587  *
1588  * Find the maximum conformance test limit for the given channel and CTL info
1589  */
1590 static uint16_t
1591 ar5416GetMaxEdgePower(uint16_t freq, CAL_CTL_EDGES *pRdEdgesPower, HAL_BOOL is2GHz)
1592 {
1593     uint16_t twiceMaxEdgePower = AR5416_MAX_RATE_POWER;
1594     int      i;
1595
1596     /* Get the edge power */
1597     for (i = 0; (i < AR5416_NUM_BAND_EDGES) && (pRdEdgesPower[i].bChannel != AR5416_BCHAN_UNUSED) ; i++) {
1598         /*
1599          * If there's an exact channel match or an inband flag set
1600          * on the lower channel use the given rdEdgePower
1601          */
1602         if (freq == fbin2freq(pRdEdgesPower[i].bChannel, is2GHz)) {
1603             twiceMaxEdgePower = MS(pRdEdgesPower[i].tPowerFlag, CAL_CTL_EDGES_POWER);
1604             break;
1605         } else if ((i > 0) && (freq < fbin2freq(pRdEdgesPower[i].bChannel, is2GHz))) {
1606             if (fbin2freq(pRdEdgesPower[i - 1].bChannel, is2GHz) < freq && (pRdEdgesPower[i - 1].tPowerFlag & CAL_CTL_EDGES_FLAG) != 0) {
1607                 twiceMaxEdgePower = MS(pRdEdgesPower[i - 1].tPowerFlag, CAL_CTL_EDGES_POWER);
1608             }
1609             /* Leave loop - no more affecting edges possible in this monotonic increasing list */
1610             break;
1611         }
1612     }
1613     HALASSERT(twiceMaxEdgePower > 0);
1614     return twiceMaxEdgePower;
1615 }
1616
1617 /**************************************************************
1618  * ar5416GetTargetPowers
1619  *
1620  * Return the rates of target power for the given target power table
1621  * channel, and number of channels
1622  */
1623 void
1624 ar5416GetTargetPowers(struct ath_hal *ah,  const struct ieee80211_channel *chan,
1625                       CAL_TARGET_POWER_HT *powInfo, uint16_t numChannels,
1626                       CAL_TARGET_POWER_HT *pNewPower, uint16_t numRates,
1627                       HAL_BOOL isHt40Target)
1628 {
1629     uint16_t clo, chi;
1630     int i;
1631     int matchIndex = -1, lowIndex = -1;
1632     uint16_t freq;
1633     CHAN_CENTERS centers;
1634
1635     ar5416GetChannelCenters(ah,  chan, &centers);
1636     freq = isHt40Target ? centers.synth_center : centers.ctl_center;
1637
1638     /* Copy the target powers into the temp channel list */
1639     if (freq <= fbin2freq(powInfo[0].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) {
1640         matchIndex = 0;
1641     } else {
1642         for (i = 0; (i < numChannels) && (powInfo[i].bChannel != AR5416_BCHAN_UNUSED); i++) {
1643             if (freq == fbin2freq(powInfo[i].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) {
1644                 matchIndex = i;
1645                 break;
1646             } else if ((freq < fbin2freq(powInfo[i].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) &&
1647                        (freq > fbin2freq(powInfo[i - 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))))
1648             {
1649                 lowIndex = i - 1;
1650                 break;
1651             }
1652         }
1653         if ((matchIndex == -1) && (lowIndex == -1)) {
1654             HALASSERT(freq > fbin2freq(powInfo[i - 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan)));
1655             matchIndex = i - 1;
1656         }
1657     }
1658
1659     if (matchIndex != -1) {
1660         OS_MEMCPY(pNewPower, &powInfo[matchIndex], sizeof(*pNewPower));
1661     } else {
1662         HALASSERT(lowIndex != -1);
1663         /*
1664          * Get the lower and upper channels, target powers,
1665          * and interpolate between them.
1666          */
1667         clo = fbin2freq(powInfo[lowIndex].bChannel, IEEE80211_IS_CHAN_2GHZ(chan));
1668         chi = fbin2freq(powInfo[lowIndex + 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan));
1669
1670         for (i = 0; i < numRates; i++) {
1671             pNewPower->tPow2x[i] = (uint8_t)interpolate(freq, clo, chi,
1672                                    powInfo[lowIndex].tPow2x[i], powInfo[lowIndex + 1].tPow2x[i]);
1673         }
1674     }
1675 }
1676 /**************************************************************
1677  * ar5416GetTargetPowersLeg
1678  *
1679  * Return the four rates of target power for the given target power table
1680  * channel, and number of channels
1681  */
1682 void
1683 ar5416GetTargetPowersLeg(struct ath_hal *ah, 
1684                          const struct ieee80211_channel *chan,
1685                          CAL_TARGET_POWER_LEG *powInfo, uint16_t numChannels,
1686                          CAL_TARGET_POWER_LEG *pNewPower, uint16_t numRates,
1687                          HAL_BOOL isExtTarget)
1688 {
1689     uint16_t clo, chi;
1690     int i;
1691     int matchIndex = -1, lowIndex = -1;
1692     uint16_t freq;
1693     CHAN_CENTERS centers;
1694
1695     ar5416GetChannelCenters(ah,  chan, &centers);
1696     freq = (isExtTarget) ? centers.ext_center :centers.ctl_center;
1697
1698     /* Copy the target powers into the temp channel list */
1699     if (freq <= fbin2freq(powInfo[0].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) {
1700         matchIndex = 0;
1701     } else {
1702         for (i = 0; (i < numChannels) && (powInfo[i].bChannel != AR5416_BCHAN_UNUSED); i++) {
1703             if (freq == fbin2freq(powInfo[i].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) {
1704                 matchIndex = i;
1705                 break;
1706             } else if ((freq < fbin2freq(powInfo[i].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) &&
1707                        (freq > fbin2freq(powInfo[i - 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))))
1708             {
1709                 lowIndex = i - 1;
1710                 break;
1711             }
1712         }
1713         if ((matchIndex == -1) && (lowIndex == -1)) {
1714             HALASSERT(freq > fbin2freq(powInfo[i - 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan)));
1715             matchIndex = i - 1;
1716         }
1717     }
1718
1719     if (matchIndex != -1) {
1720         OS_MEMCPY(pNewPower, &powInfo[matchIndex], sizeof(*pNewPower));
1721     } else {
1722         HALASSERT(lowIndex != -1);
1723         /*
1724          * Get the lower and upper channels, target powers,
1725          * and interpolate between them.
1726          */
1727         clo = fbin2freq(powInfo[lowIndex].bChannel, IEEE80211_IS_CHAN_2GHZ(chan));
1728         chi = fbin2freq(powInfo[lowIndex + 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan));
1729
1730         for (i = 0; i < numRates; i++) {
1731             pNewPower->tPow2x[i] = (uint8_t)interpolate(freq, clo, chi,
1732                                    powInfo[lowIndex].tPow2x[i], powInfo[lowIndex + 1].tPow2x[i]);
1733         }
1734     }
1735 }
1736
1737 /**************************************************************
1738  * ar5416SetPowerCalTable
1739  *
1740  * Pull the PDADC piers from cal data and interpolate them across the given
1741  * points as well as from the nearest pier(s) to get a power detector
1742  * linear voltage to power level table.
1743  */
1744 static HAL_BOOL
1745 ar5416SetPowerCalTable(struct ath_hal *ah, struct ar5416eeprom *pEepData,
1746         const struct ieee80211_channel *chan, int16_t *pTxPowerIndexOffset)
1747 {
1748     CAL_DATA_PER_FREQ *pRawDataset;
1749     uint8_t  *pCalBChans = AH_NULL;
1750     uint16_t pdGainOverlap_t2;
1751     static uint8_t  pdadcValues[AR5416_NUM_PDADC_VALUES];
1752     uint16_t gainBoundaries[AR5416_PD_GAINS_IN_MASK];
1753     uint16_t numPiers, i, j;
1754     int16_t  tMinCalPower;
1755     uint16_t numXpdGain, xpdMask;
1756     uint16_t xpdGainValues[AR5416_NUM_PD_GAINS];
1757     uint32_t reg32, regOffset, regChainOffset;
1758
1759     OS_MEMZERO(xpdGainValues, sizeof(xpdGainValues));
1760     
1761     xpdMask = pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].xpdGain;
1762
1763     if (IS_EEP_MINOR_V2(ah)) {
1764         pdGainOverlap_t2 = pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].pdGainOverlap;
1765     } else { 
1766         pdGainOverlap_t2 = (uint16_t)(MS(OS_REG_READ(ah, AR_PHY_TPCRG5), AR_PHY_TPCRG5_PD_GAIN_OVERLAP));
1767     }
1768
1769     if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1770         pCalBChans = pEepData->calFreqPier2G;
1771         numPiers = AR5416_NUM_2G_CAL_PIERS;
1772     } else {
1773         pCalBChans = pEepData->calFreqPier5G;
1774         numPiers = AR5416_NUM_5G_CAL_PIERS;
1775     }
1776
1777     numXpdGain = 0;
1778     /* Calculate the value of xpdgains from the xpdGain Mask */
1779     for (i = 1; i <= AR5416_PD_GAINS_IN_MASK; i++) {
1780         if ((xpdMask >> (AR5416_PD_GAINS_IN_MASK - i)) & 1) {
1781             if (numXpdGain >= AR5416_NUM_PD_GAINS) {
1782                 HALASSERT(0);
1783                 break;
1784             }
1785             xpdGainValues[numXpdGain] = (uint16_t)(AR5416_PD_GAINS_IN_MASK - i);
1786             numXpdGain++;
1787         }
1788     }
1789     
1790     /* Write the detector gain biases and their number */
1791     OS_REG_WRITE(ah, AR_PHY_TPCRG1, (OS_REG_READ(ah, AR_PHY_TPCRG1) & 
1792         ~(AR_PHY_TPCRG1_NUM_PD_GAIN | AR_PHY_TPCRG1_PD_GAIN_1 | AR_PHY_TPCRG1_PD_GAIN_2 | AR_PHY_TPCRG1_PD_GAIN_3)) | 
1793         SM(numXpdGain - 1, AR_PHY_TPCRG1_NUM_PD_GAIN) | SM(xpdGainValues[0], AR_PHY_TPCRG1_PD_GAIN_1 ) |
1794         SM(xpdGainValues[1], AR_PHY_TPCRG1_PD_GAIN_2) | SM(xpdGainValues[2],  AR_PHY_TPCRG1_PD_GAIN_3));
1795
1796     for (i = 0; i < AR5416_MAX_CHAINS; i++) {
1797
1798             if (AR_SREV_OWL_20_OR_LATER(ah) && 
1799             ( AH5416(ah)->ah_rx_chainmask == 0x5 || AH5416(ah)->ah_tx_chainmask == 0x5) && (i != 0)) {
1800             /* Regs are swapped from chain 2 to 1 for 5416 2_0 with 
1801              * only chains 0 and 2 populated 
1802              */
1803             regChainOffset = (i == 1) ? 0x2000 : 0x1000;
1804         } else {
1805             regChainOffset = i * 0x1000;
1806         }
1807
1808         if (pEepData->baseEepHeader.txMask & (1 << i)) {
1809             if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1810                 pRawDataset = pEepData->calPierData2G[i];
1811             } else {
1812                 pRawDataset = pEepData->calPierData5G[i];
1813             }
1814
1815             ar5416GetGainBoundariesAndPdadcs(ah,  chan, pRawDataset,
1816                                              pCalBChans, numPiers,
1817                                              pdGainOverlap_t2,
1818                                              &tMinCalPower, gainBoundaries,
1819                                              pdadcValues, numXpdGain);
1820
1821             if ((i == 0) || AR_SREV_OWL_20_OR_LATER(ah)) {
1822                 /*
1823                  * Note the pdadc table may not start at 0 dBm power, could be
1824                  * negative or greater than 0.  Need to offset the power
1825                  * values by the amount of minPower for griffin
1826                  */
1827
1828                 OS_REG_WRITE(ah, AR_PHY_TPCRG5 + regChainOffset,
1829                      SM(pdGainOverlap_t2, AR_PHY_TPCRG5_PD_GAIN_OVERLAP) |
1830                      SM(gainBoundaries[0], AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_1)  |
1831                      SM(gainBoundaries[1], AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_2)  |
1832                      SM(gainBoundaries[2], AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_3)  |
1833                      SM(gainBoundaries[3], AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_4));
1834             }
1835
1836             /* Write the power values into the baseband power table */
1837             regOffset = AR_PHY_BASE + (672 << 2) + regChainOffset;
1838
1839             for (j = 0; j < 32; j++) {
1840                 reg32 = ((pdadcValues[4*j + 0] & 0xFF) << 0)  |
1841                     ((pdadcValues[4*j + 1] & 0xFF) << 8)  |
1842                     ((pdadcValues[4*j + 2] & 0xFF) << 16) |
1843                     ((pdadcValues[4*j + 3] & 0xFF) << 24) ;
1844                 OS_REG_WRITE(ah, regOffset, reg32);
1845
1846 #ifdef PDADC_DUMP
1847                 ath_hal_printf(ah, "PDADC: Chain %d | PDADC %3d Value %3d | PDADC %3d Value %3d | PDADC %3d Value %3d | PDADC %3d Value %3d |\n",
1848                                i,
1849                                4*j, pdadcValues[4*j],
1850                                4*j+1, pdadcValues[4*j + 1],
1851                                4*j+2, pdadcValues[4*j + 2],
1852                                4*j+3, pdadcValues[4*j + 3]);
1853 #endif
1854                 regOffset += 4;
1855             }
1856         }
1857     }
1858     *pTxPowerIndexOffset = 0;
1859
1860     return AH_TRUE;
1861 }
1862
1863 /**************************************************************
1864  * ar5416GetGainBoundariesAndPdadcs
1865  *
1866  * Uses the data points read from EEPROM to reconstruct the pdadc power table
1867  * Called by ar5416SetPowerCalTable only.
1868  */
1869 static void
1870 ar5416GetGainBoundariesAndPdadcs(struct ath_hal *ah, 
1871                                  const struct ieee80211_channel *chan,
1872                                  CAL_DATA_PER_FREQ *pRawDataSet,
1873                                  uint8_t * bChans,  uint16_t availPiers,
1874                                  uint16_t tPdGainOverlap, int16_t *pMinCalPower, uint16_t * pPdGainBoundaries,
1875                                  uint8_t * pPDADCValues, uint16_t numXpdGains)
1876 {
1877
1878     int       i, j, k;
1879     int16_t   ss;         /* potentially -ve index for taking care of pdGainOverlap */
1880     uint16_t  idxL, idxR, numPiers; /* Pier indexes */
1881
1882     /* filled out Vpd table for all pdGains (chanL) */
1883     static uint8_t   vpdTableL[AR5416_NUM_PD_GAINS][AR5416_MAX_PWR_RANGE_IN_HALF_DB];
1884
1885     /* filled out Vpd table for all pdGains (chanR) */
1886     static uint8_t   vpdTableR[AR5416_NUM_PD_GAINS][AR5416_MAX_PWR_RANGE_IN_HALF_DB];
1887
1888     /* filled out Vpd table for all pdGains (interpolated) */
1889     static uint8_t   vpdTableI[AR5416_NUM_PD_GAINS][AR5416_MAX_PWR_RANGE_IN_HALF_DB];
1890
1891     uint8_t   *pVpdL, *pVpdR, *pPwrL, *pPwrR;
1892     uint8_t   minPwrT4[AR5416_NUM_PD_GAINS];
1893     uint8_t   maxPwrT4[AR5416_NUM_PD_GAINS];
1894     int16_t   vpdStep;
1895     int16_t   tmpVal;
1896     uint16_t  sizeCurrVpdTable, maxIndex, tgtIndex;
1897     HAL_BOOL    match;
1898     int16_t  minDelta = 0;
1899     CHAN_CENTERS centers;
1900
1901     ar5416GetChannelCenters(ah, chan, &centers);
1902
1903     /* Trim numPiers for the number of populated channel Piers */
1904     for (numPiers = 0; numPiers < availPiers; numPiers++) {
1905         if (bChans[numPiers] == AR5416_BCHAN_UNUSED) {
1906             break;
1907         }
1908     }
1909
1910     /* Find pier indexes around the current channel */
1911     match = getLowerUpperIndex((uint8_t)FREQ2FBIN(centers.synth_center, IEEE80211_IS_CHAN_2GHZ(chan)),
1912                         bChans, numPiers, &idxL, &idxR);
1913
1914     if (match) {
1915         /* Directly fill both vpd tables from the matching index */
1916         for (i = 0; i < numXpdGains; i++) {
1917             minPwrT4[i] = pRawDataSet[idxL].pwrPdg[i][0];
1918             maxPwrT4[i] = pRawDataSet[idxL].pwrPdg[i][4];
1919             ar5416FillVpdTable(minPwrT4[i], maxPwrT4[i], pRawDataSet[idxL].pwrPdg[i],
1920                                pRawDataSet[idxL].vpdPdg[i], AR5416_PD_GAIN_ICEPTS, vpdTableI[i]);
1921         }
1922     } else {
1923         for (i = 0; i < numXpdGains; i++) {
1924             pVpdL = pRawDataSet[idxL].vpdPdg[i];
1925             pPwrL = pRawDataSet[idxL].pwrPdg[i];
1926             pVpdR = pRawDataSet[idxR].vpdPdg[i];
1927             pPwrR = pRawDataSet[idxR].pwrPdg[i];
1928
1929             /* Start Vpd interpolation from the max of the minimum powers */
1930             minPwrT4[i] = AH_MAX(pPwrL[0], pPwrR[0]);
1931
1932             /* End Vpd interpolation from the min of the max powers */
1933             maxPwrT4[i] = AH_MIN(pPwrL[AR5416_PD_GAIN_ICEPTS - 1], pPwrR[AR5416_PD_GAIN_ICEPTS - 1]);
1934             HALASSERT(maxPwrT4[i] > minPwrT4[i]);
1935
1936             /* Fill pier Vpds */
1937             ar5416FillVpdTable(minPwrT4[i], maxPwrT4[i], pPwrL, pVpdL, AR5416_PD_GAIN_ICEPTS, vpdTableL[i]);
1938             ar5416FillVpdTable(minPwrT4[i], maxPwrT4[i], pPwrR, pVpdR, AR5416_PD_GAIN_ICEPTS, vpdTableR[i]);
1939
1940             /* Interpolate the final vpd */
1941             for (j = 0; j <= (maxPwrT4[i] - minPwrT4[i]) / 2; j++) {
1942                 vpdTableI[i][j] = (uint8_t)(interpolate((uint16_t)FREQ2FBIN(centers.synth_center, IEEE80211_IS_CHAN_2GHZ(chan)),
1943                     bChans[idxL], bChans[idxR], vpdTableL[i][j], vpdTableR[i][j]));
1944             }
1945         }
1946     }
1947     *pMinCalPower = (int16_t)(minPwrT4[0] / 2);
1948
1949     k = 0; /* index for the final table */
1950     for (i = 0; i < numXpdGains; i++) {
1951         if (i == (numXpdGains - 1)) {
1952             pPdGainBoundaries[i] = (uint16_t)(maxPwrT4[i] / 2);
1953         } else {
1954             pPdGainBoundaries[i] = (uint16_t)((maxPwrT4[i] + minPwrT4[i+1]) / 4);
1955         }
1956
1957         pPdGainBoundaries[i] = (uint16_t)AH_MIN(AR5416_MAX_RATE_POWER, pPdGainBoundaries[i]);
1958
1959         /* NB: only applies to owl 1.0 */
1960         if ((i == 0) && !AR_SREV_OWL_20_OR_LATER(ah) ) {
1961             /*
1962              * fix the gain delta, but get a delta that can be applied to min to
1963              * keep the upper power values accurate, don't think max needs to
1964              * be adjusted because should not be at that area of the table?
1965              */
1966             minDelta = pPdGainBoundaries[0] - 23;
1967             pPdGainBoundaries[0] = 23;
1968         }
1969         else {
1970             minDelta = 0;
1971         }
1972
1973         /* Find starting index for this pdGain */
1974         if (i == 0) {
1975             ss = 0; /* for the first pdGain, start from index 0 */
1976         } else {
1977             /* need overlap entries extrapolated below. */
1978             ss = (int16_t)((pPdGainBoundaries[i-1] - (minPwrT4[i] / 2)) - tPdGainOverlap + 1 + minDelta);
1979         }
1980         vpdStep = (int16_t)(vpdTableI[i][1] - vpdTableI[i][0]);
1981         vpdStep = (int16_t)((vpdStep < 1) ? 1 : vpdStep);
1982         /*
1983          *-ve ss indicates need to extrapolate data below for this pdGain
1984          */
1985         while ((ss < 0) && (k < (AR5416_NUM_PDADC_VALUES - 1))) {
1986             tmpVal = (int16_t)(vpdTableI[i][0] + ss * vpdStep);
1987             pPDADCValues[k++] = (uint8_t)((tmpVal < 0) ? 0 : tmpVal);
1988             ss++;
1989         }
1990
1991         sizeCurrVpdTable = (uint8_t)((maxPwrT4[i] - minPwrT4[i]) / 2 +1);
1992         tgtIndex = (uint8_t)(pPdGainBoundaries[i] + tPdGainOverlap - (minPwrT4[i] / 2));
1993         maxIndex = (tgtIndex < sizeCurrVpdTable) ? tgtIndex : sizeCurrVpdTable;
1994
1995         while ((ss < maxIndex) && (k < (AR5416_NUM_PDADC_VALUES - 1))) {
1996             pPDADCValues[k++] = vpdTableI[i][ss++];
1997         }
1998
1999         vpdStep = (int16_t)(vpdTableI[i][sizeCurrVpdTable - 1] - vpdTableI[i][sizeCurrVpdTable - 2]);
2000         vpdStep = (int16_t)((vpdStep < 1) ? 1 : vpdStep);
2001         /*
2002          * for last gain, pdGainBoundary == Pmax_t2, so will
2003          * have to extrapolate
2004          */
2005         if (tgtIndex >= maxIndex) {  /* need to extrapolate above */
2006             while ((ss <= tgtIndex) && (k < (AR5416_NUM_PDADC_VALUES - 1))) {
2007                 tmpVal = (int16_t)((vpdTableI[i][sizeCurrVpdTable - 1] +
2008                           (ss - maxIndex +1) * vpdStep));
2009                 pPDADCValues[k++] = (uint8_t)((tmpVal > 255) ? 255 : tmpVal);
2010                 ss++;
2011             }
2012         }               /* extrapolated above */
2013     }                   /* for all pdGainUsed */
2014
2015     /* Fill out pdGainBoundaries - only up to 2 allowed here, but hardware allows up to 4 */
2016     while (i < AR5416_PD_GAINS_IN_MASK) {
2017         pPdGainBoundaries[i] = pPdGainBoundaries[i-1];
2018         i++;
2019     }
2020
2021     while (k < AR5416_NUM_PDADC_VALUES) {
2022         pPDADCValues[k] = pPDADCValues[k-1];
2023         k++;
2024     }
2025     return;
2026 }
2027
2028 /**************************************************************
2029  * getLowerUppderIndex
2030  *
2031  * Return indices surrounding the value in sorted integer lists.
2032  * Requirement: the input list must be monotonically increasing
2033  *     and populated up to the list size
2034  * Returns: match is set if an index in the array matches exactly
2035  *     or a the target is before or after the range of the array.
2036  */
2037 HAL_BOOL
2038 getLowerUpperIndex(uint8_t target, uint8_t *pList, uint16_t listSize,
2039                    uint16_t *indexL, uint16_t *indexR)
2040 {
2041     uint16_t i;
2042
2043     /*
2044      * Check first and last elements for beyond ordered array cases.
2045      */
2046     if (target <= pList[0]) {
2047         *indexL = *indexR = 0;
2048         return AH_TRUE;
2049     }
2050     if (target >= pList[listSize-1]) {
2051         *indexL = *indexR = (uint16_t)(listSize - 1);
2052         return AH_TRUE;
2053     }
2054
2055     /* look for value being near or between 2 values in list */
2056     for (i = 0; i < listSize - 1; i++) {
2057         /*
2058          * If value is close to the current value of the list
2059          * then target is not between values, it is one of the values
2060          */
2061         if (pList[i] == target) {
2062             *indexL = *indexR = i;
2063             return AH_TRUE;
2064         }
2065         /*
2066          * Look for value being between current value and next value
2067          * if so return these 2 values
2068          */
2069         if (target < pList[i + 1]) {
2070             *indexL = i;
2071             *indexR = (uint16_t)(i + 1);
2072             return AH_FALSE;
2073         }
2074     }
2075     HALASSERT(0);
2076     *indexL = *indexR = 0;
2077     return AH_FALSE;
2078 }
2079
2080 /**************************************************************
2081  * ar5416FillVpdTable
2082  *
2083  * Fill the Vpdlist for indices Pmax-Pmin
2084  * Note: pwrMin, pwrMax and Vpdlist are all in dBm * 4
2085  */
2086 static HAL_BOOL
2087 ar5416FillVpdTable(uint8_t pwrMin, uint8_t pwrMax, uint8_t *pPwrList,
2088                    uint8_t *pVpdList, uint16_t numIntercepts, uint8_t *pRetVpdList)
2089 {
2090     uint16_t  i, k;
2091     uint8_t   currPwr = pwrMin;
2092     uint16_t  idxL, idxR;
2093
2094     HALASSERT(pwrMax > pwrMin);
2095     for (i = 0; i <= (pwrMax - pwrMin) / 2; i++) {
2096         getLowerUpperIndex(currPwr, pPwrList, numIntercepts,
2097                            &(idxL), &(idxR));
2098         if (idxR < 1)
2099             idxR = 1;           /* extrapolate below */
2100         if (idxL == numIntercepts - 1)
2101             idxL = (uint16_t)(numIntercepts - 2);   /* extrapolate above */
2102         if (pPwrList[idxL] == pPwrList[idxR])
2103             k = pVpdList[idxL];
2104         else
2105             k = (uint16_t)( ((currPwr - pPwrList[idxL]) * pVpdList[idxR] + (pPwrList[idxR] - currPwr) * pVpdList[idxL]) /
2106                   (pPwrList[idxR] - pPwrList[idxL]) );
2107         HALASSERT(k < 256);
2108         pRetVpdList[i] = (uint8_t)k;
2109         currPwr += 2;               /* half dB steps */
2110     }
2111
2112     return AH_TRUE;
2113 }
2114
2115 /**************************************************************************
2116  * interpolate
2117  *
2118  * Returns signed interpolated or the scaled up interpolated value
2119  */
2120 static int16_t
2121 interpolate(uint16_t target, uint16_t srcLeft, uint16_t srcRight,
2122             int16_t targetLeft, int16_t targetRight)
2123 {
2124     int16_t rv;
2125
2126     if (srcRight == srcLeft) {
2127         rv = targetLeft;
2128     } else {
2129         rv = (int16_t)( ((target - srcLeft) * targetRight +
2130               (srcRight - target) * targetLeft) / (srcRight - srcLeft) );
2131     }
2132     return rv;
2133 }
2134
2135 static void
2136 ar5416Set11nRegs(struct ath_hal *ah, const struct ieee80211_channel *chan)
2137 {
2138         uint32_t phymode;
2139         HAL_HT_MACMODE macmode;         /* MAC - 20/40 mode */
2140
2141         if (!IEEE80211_IS_CHAN_HT(chan))
2142                 return;
2143
2144         /* Enable 11n HT, 20 MHz */
2145         phymode = AR_PHY_FC_HT_EN | AR_PHY_FC_SHORT_GI_40
2146                 | AR_PHY_FC_SINGLE_HT_LTF1 | AR_PHY_FC_WALSH;
2147
2148         /* Configure baseband for dynamic 20/40 operation */
2149         if (IEEE80211_IS_CHAN_HT40(chan)) {
2150                 phymode |= AR_PHY_FC_DYN2040_EN | AR_PHY_FC_SHORT_GI_40;
2151
2152                 /* Configure control (primary) channel at +-10MHz */
2153                 if (IEEE80211_IS_CHAN_HT40U(chan))
2154                         phymode |= AR_PHY_FC_DYN2040_PRI_CH;
2155 #if 0
2156                 /* Configure 20/25 spacing */
2157                 if (ht->ht_extprotspacing == HAL_HT_EXTPROTSPACING_25)
2158                         phymode |= AR_PHY_FC_DYN2040_EXT_CH;
2159 #endif
2160                 macmode = HAL_HT_MACMODE_2040;
2161         } else
2162                 macmode = HAL_HT_MACMODE_20;
2163         OS_REG_WRITE(ah, AR_PHY_TURBO, phymode);
2164
2165         /* Configure MAC for 20/40 operation */
2166         ar5416Set11nMac2040(ah, macmode);
2167
2168         /* global transmit timeout (25 TUs default)*/
2169         /* XXX - put this elsewhere??? */
2170         OS_REG_WRITE(ah, AR_GTXTO, 25 << AR_GTXTO_TIMEOUT_LIMIT_S) ;
2171
2172         /* carrier sense timeout */
2173         OS_REG_SET_BIT(ah, AR_GTTM, AR_GTTM_CST_USEC);
2174         OS_REG_WRITE(ah, AR_CST, 1 << AR_CST_TIMEOUT_LIMIT_S);
2175 }
2176
2177 void
2178 ar5416GetChannelCenters(struct ath_hal *ah,
2179         const struct ieee80211_channel *chan, CHAN_CENTERS *centers)
2180 {
2181         uint16_t freq = ath_hal_gethwchannel(ah, chan);
2182
2183         centers->ctl_center = freq;
2184         centers->synth_center = freq;
2185         /*
2186          * In 20/40 phy mode, the center frequency is
2187          * "between" the control and extension channels.
2188          */
2189         if (IEEE80211_IS_CHAN_HT40U(chan)) {
2190                 centers->synth_center += HT40_CHANNEL_CENTER_SHIFT;
2191                 centers->ext_center =
2192                     centers->synth_center + HT40_CHANNEL_CENTER_SHIFT;
2193         } else if (IEEE80211_IS_CHAN_HT40D(chan)) {
2194                 centers->synth_center -= HT40_CHANNEL_CENTER_SHIFT;
2195                 centers->ext_center =
2196                     centers->synth_center - HT40_CHANNEL_CENTER_SHIFT;
2197         } else {
2198                 centers->ext_center = freq;
2199         }
2200 }