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