xref: /freebsd/sys/dev/ath/ath_hal/ar5416/ar5416_reset.c (revision 6486b015fc84e96725fef22b0e3363351399ae83)
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 static void ar5416UpdateChainMasks(struct ath_hal *ah, HAL_BOOL is_ht);
48 static void ar5416OverrideIni(struct ath_hal *ah, const struct ieee80211_channel *);
49 
50 #if 0
51 static HAL_BOOL	ar5416ChannelChange(struct ath_hal *, const struct ieee80211_channel *);
52 #endif
53 static void ar5416SetDeltaSlope(struct ath_hal *, const struct ieee80211_channel *);
54 
55 static HAL_BOOL ar5416SetResetPowerOn(struct ath_hal *ah);
56 static HAL_BOOL ar5416SetReset(struct ath_hal *ah, int type);
57 static HAL_BOOL ar5416SetPowerPerRateTable(struct ath_hal *ah,
58 	struct ar5416eeprom *pEepData,
59 	const struct ieee80211_channel *chan, int16_t *ratesArray,
60 	uint16_t cfgCtl, uint16_t AntennaReduction,
61 	uint16_t twiceMaxRegulatoryPower,
62 	uint16_t powerLimit);
63 static void ar5416Set11nRegs(struct ath_hal *ah, const struct ieee80211_channel *chan);
64 static void ar5416MarkPhyInactive(struct ath_hal *ah);
65 
66 /*
67  * Places the device in and out of reset and then places sane
68  * values in the registers based on EEPROM config, initialization
69  * vectors (as determined by the mode), and station configuration
70  *
71  * bChannelChange is used to preserve DMA/PCU registers across
72  * a HW Reset during channel change.
73  */
74 HAL_BOOL
75 ar5416Reset(struct ath_hal *ah, HAL_OPMODE opmode,
76 	struct ieee80211_channel *chan,
77 	HAL_BOOL bChannelChange, HAL_STATUS *status)
78 {
79 #define	N(a)	(sizeof (a) / sizeof (a[0]))
80 #define	FAIL(_code)	do { ecode = _code; goto bad; } while (0)
81 	struct ath_hal_5212 *ahp = AH5212(ah);
82 	HAL_CHANNEL_INTERNAL *ichan;
83 	uint32_t saveDefAntenna, saveLedState;
84 	uint32_t macStaId1;
85 	uint16_t rfXpdGain[2];
86 	HAL_STATUS ecode;
87 	uint32_t powerVal, rssiThrReg;
88 	uint32_t ackTpcPow, ctsTpcPow, chirpTpcPow;
89 	int i;
90 	uint64_t tsf = 0;
91 
92 	OS_MARK(ah, AH_MARK_RESET, bChannelChange);
93 
94 	/* Bring out of sleep mode */
95 	if (!ar5416SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE)) {
96 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: chip did not wakeup\n",
97 		    __func__);
98 		FAIL(HAL_EIO);
99 	}
100 
101 	/*
102 	 * Map public channel to private.
103 	 */
104 	ichan = ath_hal_checkchannel(ah, chan);
105 	if (ichan == AH_NULL)
106 		FAIL(HAL_EINVAL);
107 	switch (opmode) {
108 	case HAL_M_STA:
109 	case HAL_M_IBSS:
110 	case HAL_M_HOSTAP:
111 	case HAL_M_MONITOR:
112 		break;
113 	default:
114 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid operating mode %u\n",
115 		    __func__, opmode);
116 		FAIL(HAL_EINVAL);
117 		break;
118 	}
119 	HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER14_1);
120 
121 	/* XXX Turn on fast channel change for 5416 */
122 	/*
123 	 * Preserve the bmiss rssi threshold and count threshold
124 	 * across resets
125 	 */
126 	rssiThrReg = OS_REG_READ(ah, AR_RSSI_THR);
127 	/* If reg is zero, first time thru set to default val */
128 	if (rssiThrReg == 0)
129 		rssiThrReg = INIT_RSSI_THR;
130 
131 	/*
132 	 * Preserve the antenna on a channel change
133 	 */
134 	saveDefAntenna = OS_REG_READ(ah, AR_DEF_ANTENNA);
135 	if (saveDefAntenna == 0)		/* XXX magic constants */
136 		saveDefAntenna = 1;
137 
138 	/* Save hardware flag before chip reset clears the register */
139 	macStaId1 = OS_REG_READ(ah, AR_STA_ID1) &
140 		(AR_STA_ID1_BASE_RATE_11B | AR_STA_ID1_USE_DEFANT);
141 
142 	/* Save led state from pci config register */
143 	saveLedState = OS_REG_READ(ah, AR_MAC_LED) &
144 		(AR_MAC_LED_ASSOC | AR_MAC_LED_MODE |
145 		 AR_MAC_LED_BLINK_THRESH_SEL | AR_MAC_LED_BLINK_SLOW);
146 
147 	/* For chips on which the RTC reset is done, save TSF before it gets cleared */
148 	if (AR_SREV_HOWL(ah) ||
149 	    (AR_SREV_MERLIN(ah) &&
150 	     ath_hal_eepromGetFlag(ah, AR_EEP_OL_PWRCTRL)) ||
151 	    (ah->ah_config.ah_force_full_reset))
152 		tsf = ar5416GetTsf64(ah);
153 
154 	/* Mark PHY as inactive; marked active in ar5416InitBB() */
155 	ar5416MarkPhyInactive(ah);
156 
157 	if (!ar5416ChipReset(ah, chan)) {
158 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: chip reset failed\n", __func__);
159 		FAIL(HAL_EIO);
160 	}
161 
162 	/* Restore TSF */
163 	if (tsf)
164 		ar5416SetTsf64(ah, tsf);
165 
166 	OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
167 	if (AR_SREV_MERLIN_10_OR_LATER(ah))
168 		OS_REG_SET_BIT(ah, AR_GPIO_INPUT_EN_VAL, AR_GPIO_JTAG_DISABLE);
169 
170 	AH5416(ah)->ah_writeIni(ah, chan);
171 
172 	if(AR_SREV_KIWI_13_OR_LATER(ah) ) {
173 		/* Enable ASYNC FIFO */
174 		OS_REG_SET_BIT(ah, AR_MAC_PCU_ASYNC_FIFO_REG3,
175 		    AR_MAC_PCU_ASYNC_FIFO_REG3_DATAPATH_SEL);
176 		OS_REG_SET_BIT(ah, AR_PHY_MODE, AR_PHY_MODE_ASYNCFIFO);
177 		OS_REG_CLR_BIT(ah, AR_MAC_PCU_ASYNC_FIFO_REG3,
178 		    AR_MAC_PCU_ASYNC_FIFO_REG3_SOFT_RESET);
179 		OS_REG_SET_BIT(ah, AR_MAC_PCU_ASYNC_FIFO_REG3,
180 		    AR_MAC_PCU_ASYNC_FIFO_REG3_SOFT_RESET);
181 	}
182 
183 	/* Override ini values (that can be overriden in this fashion) */
184 	ar5416OverrideIni(ah, chan);
185 
186 	/* Setup 11n MAC/Phy mode registers */
187 	ar5416Set11nRegs(ah, chan);
188 
189 	OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
190 
191 	/*
192 	 * Some AR91xx SoC devices frequently fail to accept TSF writes
193 	 * right after the chip reset. When that happens, write a new
194 	 * value after the initvals have been applied, with an offset
195 	 * based on measured time difference
196 	 */
197 	if (AR_SREV_HOWL(ah) && (ar5416GetTsf64(ah) < tsf)) {
198 		tsf += 1500;
199 		ar5416SetTsf64(ah, tsf);
200 	}
201 
202 	HALDEBUG(ah, HAL_DEBUG_RESET, ">>>2 %s: AR_PHY_DAG_CTRLCCK=0x%x\n",
203 		__func__, OS_REG_READ(ah,AR_PHY_DAG_CTRLCCK));
204 	HALDEBUG(ah, HAL_DEBUG_RESET, ">>>2 %s: AR_PHY_ADC_CTL=0x%x\n",
205 		__func__, OS_REG_READ(ah,AR_PHY_ADC_CTL));
206 
207 	/*
208 	 * Setup ah_tx_chainmask / ah_rx_chainmask before we fiddle
209 	 * with enabling the TX/RX radio chains.
210 	 */
211 	ar5416UpdateChainMasks(ah, IEEE80211_IS_CHAN_HT(chan));
212 	/*
213 	 * This routine swaps the analog chains - it should be done
214 	 * before any radio register twiddling is done.
215 	 */
216 	ar5416InitChainMasks(ah);
217 
218 	/* Setup the open-loop power calibration if required */
219 	if (ath_hal_eepromGetFlag(ah, AR_EEP_OL_PWRCTRL)) {
220 		AH5416(ah)->ah_olcInit(ah);
221 		AH5416(ah)->ah_olcTempCompensation(ah);
222 	}
223 
224 	/* Setup the transmit power values. */
225 	if (!ah->ah_setTxPower(ah, chan, rfXpdGain)) {
226 		HALDEBUG(ah, HAL_DEBUG_ANY,
227 		    "%s: error init'ing transmit power\n", __func__);
228 		FAIL(HAL_EIO);
229 	}
230 
231 	/* Write the analog registers */
232 	if (!ahp->ah_rfHal->setRfRegs(ah, chan,
233 	    IEEE80211_IS_CHAN_2GHZ(chan) ? 2: 1, rfXpdGain)) {
234 		HALDEBUG(ah, HAL_DEBUG_ANY,
235 		    "%s: ar5212SetRfRegs failed\n", __func__);
236 		FAIL(HAL_EIO);
237 	}
238 
239 	/* Write delta slope for OFDM enabled modes (A, G, Turbo) */
240 	if (IEEE80211_IS_CHAN_OFDM(chan)|| IEEE80211_IS_CHAN_HT(chan))
241 		ar5416SetDeltaSlope(ah, chan);
242 
243 	AH5416(ah)->ah_spurMitigate(ah, chan);
244 
245 	/* Setup board specific options for EEPROM version 3 */
246 	if (!ah->ah_setBoardValues(ah, chan)) {
247 		HALDEBUG(ah, HAL_DEBUG_ANY,
248 		    "%s: error setting board options\n", __func__);
249 		FAIL(HAL_EIO);
250 	}
251 
252 	OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
253 
254 	OS_REG_WRITE(ah, AR_STA_ID0, LE_READ_4(ahp->ah_macaddr));
255 	OS_REG_WRITE(ah, AR_STA_ID1, LE_READ_2(ahp->ah_macaddr + 4)
256 		| macStaId1
257 		| AR_STA_ID1_RTS_USE_DEF
258 		| ahp->ah_staId1Defaults
259 	);
260 	ar5212SetOperatingMode(ah, opmode);
261 
262 	/* Set Venice BSSID mask according to current state */
263 	OS_REG_WRITE(ah, AR_BSSMSKL, LE_READ_4(ahp->ah_bssidmask));
264 	OS_REG_WRITE(ah, AR_BSSMSKU, LE_READ_2(ahp->ah_bssidmask + 4));
265 
266 	/* Restore previous led state */
267 	if (AR_SREV_HOWL(ah))
268 		OS_REG_WRITE(ah, AR_MAC_LED,
269 		    AR_MAC_LED_ASSOC_ACTIVE | AR_CFG_SCLK_32KHZ);
270 	else
271 		OS_REG_WRITE(ah, AR_MAC_LED, OS_REG_READ(ah, AR_MAC_LED) |
272 		    saveLedState);
273 
274         /* Start TSF2 for generic timer 8-15 */
275 #ifdef	NOTYET
276 	if (AR_SREV_KIWI(ah))
277 		ar5416StartTsf2(ah);
278 #endif
279 
280 	/* Restore previous antenna */
281 	OS_REG_WRITE(ah, AR_DEF_ANTENNA, saveDefAntenna);
282 
283 	/* then our BSSID and associate id */
284 	OS_REG_WRITE(ah, AR_BSS_ID0, LE_READ_4(ahp->ah_bssid));
285 	OS_REG_WRITE(ah, AR_BSS_ID1, LE_READ_2(ahp->ah_bssid + 4) |
286 	    (ahp->ah_assocId & 0x3fff) << AR_BSS_ID1_AID_S);
287 
288 	/* Restore bmiss rssi & count thresholds */
289 	OS_REG_WRITE(ah, AR_RSSI_THR, ahp->ah_rssiThr);
290 
291 	OS_REG_WRITE(ah, AR_ISR, ~0);		/* cleared on write */
292 
293 	/* Restore bmiss rssi & count thresholds */
294 	OS_REG_WRITE(ah, AR_RSSI_THR, rssiThrReg);
295 
296 	if (!ar5212SetChannel(ah, chan))
297 		FAIL(HAL_EIO);
298 
299 	OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
300 
301 	/* Set 1:1 QCU to DCU mapping for all queues */
302 	for (i = 0; i < AR_NUM_DCU; i++)
303 		OS_REG_WRITE(ah, AR_DQCUMASK(i), 1 << i);
304 
305 	ahp->ah_intrTxqs = 0;
306 	for (i = 0; i < AH_PRIVATE(ah)->ah_caps.halTotalQueues; i++)
307 		ah->ah_resetTxQueue(ah, i);
308 
309 	ar5416InitIMR(ah, opmode);
310 	ar5212SetCoverageClass(ah, AH_PRIVATE(ah)->ah_coverageClass, 1);
311 	ar5416InitQoS(ah);
312 	/* This may override the AR_DIAG_SW register */
313 	ar5416InitUserSettings(ah);
314 
315 	if (AR_SREV_KIWI_13_OR_LATER(ah)) {
316 		/*
317 		 * Enable ASYNC FIFO
318 		 *
319 		 * If Async FIFO is enabled, the following counters change
320 		 * as MAC now runs at 117 Mhz instead of 88/44MHz when
321 		 * async FIFO is disabled.
322 		 *
323 		 * Overwrite the delay/timeouts initialized in ProcessIni()
324 		 * above.
325 		 */
326 		OS_REG_WRITE(ah, AR_D_GBL_IFS_SIFS,
327 		    AR_D_GBL_IFS_SIFS_ASYNC_FIFO_DUR);
328 		OS_REG_WRITE(ah, AR_D_GBL_IFS_SLOT,
329 		    AR_D_GBL_IFS_SLOT_ASYNC_FIFO_DUR);
330 		OS_REG_WRITE(ah, AR_D_GBL_IFS_EIFS,
331 		    AR_D_GBL_IFS_EIFS_ASYNC_FIFO_DUR);
332 
333 		OS_REG_WRITE(ah, AR_TIME_OUT,
334 		    AR_TIME_OUT_ACK_CTS_ASYNC_FIFO_DUR);
335 		OS_REG_WRITE(ah, AR_USEC, AR_USEC_ASYNC_FIFO_DUR);
336 
337 		OS_REG_SET_BIT(ah, AR_MAC_PCU_LOGIC_ANALYZER,
338 		    AR_MAC_PCU_LOGIC_ANALYZER_DISBUG20768);
339 		OS_REG_RMW_FIELD(ah, AR_AHB_MODE, AR_AHB_CUSTOM_BURST_EN,
340 		    AR_AHB_CUSTOM_BURST_ASYNC_FIFO_VAL);
341 	}
342 
343 	if (AR_SREV_KIWI_13_OR_LATER(ah)) {
344 		/* Enable AGGWEP to accelerate encryption engine */
345 		OS_REG_SET_BIT(ah, AR_PCU_MISC_MODE2,
346 		    AR_PCU_MISC_MODE2_ENABLE_AGGWEP);
347 	}
348 
349 
350 	/*
351 	 * disable seq number generation in hw
352 	 */
353 	 OS_REG_WRITE(ah, AR_STA_ID1,
354 	     OS_REG_READ(ah, AR_STA_ID1) | AR_STA_ID1_PRESERVE_SEQNUM);
355 
356 	ar5416InitDMA(ah);
357 
358 	/*
359 	 * program OBS bus to see MAC interrupts
360 	 */
361 	OS_REG_WRITE(ah, AR_OBS, 8);
362 
363 	/*
364 	 * Disable the "general" TX/RX mitigation timers.
365 	 */
366 	OS_REG_WRITE(ah, AR_MIRT, 0);
367 
368 #ifdef	AH_AR5416_INTERRUPT_MITIGATION
369 	/*
370 	 * This initialises the RX interrupt mitigation timers.
371 	 *
372 	 * The mitigation timers begin at idle and are triggered
373 	 * upon the RXOK of a single frame (or sub-frame, for A-MPDU.)
374 	 * Then, the RX mitigation interrupt will fire:
375 	 *
376 	 * + 250uS after the last RX'ed frame, or
377 	 * + 700uS after the first RX'ed frame
378 	 *
379 	 * Thus, the LAST field dictates the extra latency
380 	 * induced by the RX mitigation method and the FIRST
381 	 * field dictates how long to delay before firing an
382 	 * RX mitigation interrupt.
383 	 *
384 	 * Please note this only seems to be for RXOK frames;
385 	 * not CRC or PHY error frames.
386 	 *
387 	 */
388 	OS_REG_RMW_FIELD(ah, AR_RIMT, AR_RIMT_LAST, 250);
389 	OS_REG_RMW_FIELD(ah, AR_RIMT, AR_RIMT_FIRST, 700);
390 #endif
391 	ar5416InitBB(ah, chan);
392 
393 	/* Setup compression registers */
394 	ar5212SetCompRegs(ah);		/* XXX not needed? */
395 
396 	/*
397 	 * 5416 baseband will check the per rate power table
398 	 * and select the lower of the two
399 	 */
400 	ackTpcPow = 63;
401 	ctsTpcPow = 63;
402 	chirpTpcPow = 63;
403 	powerVal = SM(ackTpcPow, AR_TPC_ACK) |
404 		SM(ctsTpcPow, AR_TPC_CTS) |
405 		SM(chirpTpcPow, AR_TPC_CHIRP);
406 	OS_REG_WRITE(ah, AR_TPC, powerVal);
407 
408 	if (!ar5416InitCal(ah, chan))
409 		FAIL(HAL_ESELFTEST);
410 
411 	ar5416RestoreChainMask(ah);
412 
413 	AH_PRIVATE(ah)->ah_opmode = opmode;	/* record operating mode */
414 
415 	if (bChannelChange && !IEEE80211_IS_CHAN_DFS(chan))
416 		chan->ic_state &= ~IEEE80211_CHANSTATE_CWINT;
417 
418 	if (AR_SREV_HOWL(ah)) {
419 		/*
420 		 * Enable the MBSSID block-ack fix for HOWL.
421 		 * This feature is only supported on Howl 1.4, but it is safe to
422 		 * set bit 22 of STA_ID1 on other Howl revisions (1.1, 1.2, 1.3),
423 		 * since bit 22 is unused in those Howl revisions.
424 		 */
425 		unsigned int reg;
426 		reg = (OS_REG_READ(ah, AR_STA_ID1) | (1<<22));
427 		OS_REG_WRITE(ah,AR_STA_ID1, reg);
428 		ath_hal_printf(ah, "MBSSID Set bit 22 of AR_STA_ID 0x%x\n", reg);
429 	}
430 
431 	HALDEBUG(ah, HAL_DEBUG_RESET, "%s: done\n", __func__);
432 
433 	OS_MARK(ah, AH_MARK_RESET_DONE, 0);
434 
435 	return AH_TRUE;
436 bad:
437 	OS_MARK(ah, AH_MARK_RESET_DONE, ecode);
438 	if (status != AH_NULL)
439 		*status = ecode;
440 	return AH_FALSE;
441 #undef FAIL
442 #undef N
443 }
444 
445 #if 0
446 /*
447  * This channel change evaluates whether the selected hardware can
448  * perform a synthesizer-only channel change (no reset).  If the
449  * TX is not stopped, or the RFBus cannot be granted in the given
450  * time, the function returns false as a reset is necessary
451  */
452 HAL_BOOL
453 ar5416ChannelChange(struct ath_hal *ah, const structu ieee80211_channel *chan)
454 {
455 	uint32_t       ulCount;
456 	uint32_t   data, synthDelay, qnum;
457 	uint16_t   rfXpdGain[4];
458 	struct ath_hal_5212 *ahp = AH5212(ah);
459 	HAL_CHANNEL_INTERNAL *ichan;
460 
461 	/*
462 	 * Map public channel to private.
463 	 */
464 	ichan = ath_hal_checkchannel(ah, chan);
465 
466 	/* TX must be stopped or RF Bus grant will not work */
467 	for (qnum = 0; qnum < AH_PRIVATE(ah)->ah_caps.halTotalQueues; qnum++) {
468 		if (ar5212NumTxPending(ah, qnum)) {
469 			HALDEBUG(ah, HAL_DEBUG_ANY,
470 			    "%s: frames pending on queue %d\n", __func__, qnum);
471 			return AH_FALSE;
472 		}
473 	}
474 
475 	/*
476 	 * Kill last Baseband Rx Frame - Request analog bus grant
477 	 */
478 	OS_REG_WRITE(ah, AR_PHY_RFBUS_REQ, AR_PHY_RFBUS_REQ_REQUEST);
479 	if (!ath_hal_wait(ah, AR_PHY_RFBUS_GNT, AR_PHY_RFBUS_GRANT_EN, AR_PHY_RFBUS_GRANT_EN)) {
480 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: could not kill baseband rx\n",
481 		    __func__);
482 		return AH_FALSE;
483 	}
484 
485 	ar5416Set11nRegs(ah, chan);	/* NB: setup 5416-specific regs */
486 
487 	/* Change the synth */
488 	if (!ar5212SetChannel(ah, chan))
489 		return AH_FALSE;
490 
491 	/* Setup the transmit power values. */
492 	if (!ah->ah_setTxPower(ah, chan, rfXpdGain)) {
493 		HALDEBUG(ah, HAL_DEBUG_ANY,
494 		    "%s: error init'ing transmit power\n", __func__);
495 		return AH_FALSE;
496 	}
497 
498 	/*
499 	 * Wait for the frequency synth to settle (synth goes on
500 	 * via PHY_ACTIVE_EN).  Read the phy active delay register.
501 	 * Value is in 100ns increments.
502 	 */
503 	data = OS_REG_READ(ah, AR_PHY_RX_DELAY) & AR_PHY_RX_DELAY_DELAY;
504 	if (IS_CHAN_CCK(ichan)) {
505 		synthDelay = (4 * data) / 22;
506 	} else {
507 		synthDelay = data / 10;
508 	}
509 
510 	OS_DELAY(synthDelay + BASE_ACTIVATE_DELAY);
511 
512 	/* Release the RFBus Grant */
513 	OS_REG_WRITE(ah, AR_PHY_RFBUS_REQ, 0);
514 
515 	/* Write delta slope for OFDM enabled modes (A, G, Turbo) */
516 	if (IEEE80211_IS_CHAN_OFDM(ichan)|| IEEE80211_IS_CHAN_HT(chan)) {
517 		HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER5_3);
518 		ar5212SetSpurMitigation(ah, chan);
519 		ar5416SetDeltaSlope(ah, chan);
520 	}
521 
522 	/* XXX spur mitigation for Melin */
523 
524 	if (!IEEE80211_IS_CHAN_DFS(chan))
525 		chan->ic_state &= ~IEEE80211_CHANSTATE_CWINT;
526 
527 	ichan->channel_time = 0;
528 	ichan->tsf_last = ar5416GetTsf64(ah);
529 	ar5212TxEnable(ah, AH_TRUE);
530 	return AH_TRUE;
531 }
532 #endif
533 
534 static void
535 ar5416InitDMA(struct ath_hal *ah)
536 {
537 	struct ath_hal_5212 *ahp = AH5212(ah);
538 
539 	/*
540 	 * set AHB_MODE not to do cacheline prefetches
541 	 */
542 	OS_REG_SET_BIT(ah, AR_AHB_MODE, AR_AHB_PREFETCH_RD_EN);
543 
544 	/*
545 	 * let mac dma reads be in 128 byte chunks
546 	 */
547 	OS_REG_WRITE(ah, AR_TXCFG,
548 		(OS_REG_READ(ah, AR_TXCFG) & ~AR_TXCFG_DMASZ_MASK) | AR_TXCFG_DMASZ_128B);
549 
550 	/*
551 	 * let mac dma writes be in 128 byte chunks
552 	 */
553 	OS_REG_WRITE(ah, AR_RXCFG,
554 		(OS_REG_READ(ah, AR_RXCFG) & ~AR_RXCFG_DMASZ_MASK) | AR_RXCFG_DMASZ_128B);
555 
556 	/* restore TX trigger level */
557 	OS_REG_WRITE(ah, AR_TXCFG,
558 		(OS_REG_READ(ah, AR_TXCFG) &~ AR_FTRIG) |
559 		    SM(ahp->ah_txTrigLev, AR_FTRIG));
560 
561 	/*
562 	 * Setup receive FIFO threshold to hold off TX activities
563 	 */
564 	OS_REG_WRITE(ah, AR_RXFIFO_CFG, 0x200);
565 
566 	/*
567 	 * reduce the number of usable entries in PCU TXBUF to avoid
568 	 * wrap around.
569 	 */
570 	if (AR_SREV_KITE(ah))
571 		/*
572 		 * For AR9285 the number of Fifos are reduced to half.
573 		 * So set the usable tx buf size also to half to
574 		 * avoid data/delimiter underruns
575 		 */
576 		OS_REG_WRITE(ah, AR_PCU_TXBUF_CTRL, AR_9285_PCU_TXBUF_CTRL_USABLE_SIZE);
577 	else
578 		OS_REG_WRITE(ah, AR_PCU_TXBUF_CTRL, AR_PCU_TXBUF_CTRL_USABLE_SIZE);
579 }
580 
581 static void
582 ar5416InitBB(struct ath_hal *ah, const struct ieee80211_channel *chan)
583 {
584 	uint32_t synthDelay;
585 
586 	/*
587 	 * Wait for the frequency synth to settle (synth goes on
588 	 * via AR_PHY_ACTIVE_EN).  Read the phy active delay register.
589 	 * Value is in 100ns increments.
590 	  */
591 	synthDelay = OS_REG_READ(ah, AR_PHY_RX_DELAY) & AR_PHY_RX_DELAY_DELAY;
592 	if (IEEE80211_IS_CHAN_CCK(chan)) {
593 		synthDelay = (4 * synthDelay) / 22;
594 	} else {
595 		synthDelay /= 10;
596 	}
597 
598 	/* Turn on PLL on 5416 */
599 	HALDEBUG(ah, HAL_DEBUG_RESET, "%s %s channel\n",
600 	    __func__, IEEE80211_IS_CHAN_5GHZ(chan) ? "5GHz" : "2GHz");
601 
602 	/* Activate the PHY (includes baseband activate and synthesizer on) */
603 	OS_REG_WRITE(ah, AR_PHY_ACTIVE, AR_PHY_ACTIVE_EN);
604 
605 	/*
606 	 * If the AP starts the calibration before the base band timeout
607 	 * completes  we could get rx_clear false triggering.  Add an
608 	 * extra BASE_ACTIVATE_DELAY usecs to ensure this condition
609 	 * does not happen.
610 	 */
611 	if (IEEE80211_IS_CHAN_HALF(chan)) {
612 		OS_DELAY((synthDelay << 1) + BASE_ACTIVATE_DELAY);
613 	} else if (IEEE80211_IS_CHAN_QUARTER(chan)) {
614 		OS_DELAY((synthDelay << 2) + BASE_ACTIVATE_DELAY);
615 	} else {
616 		OS_DELAY(synthDelay + BASE_ACTIVATE_DELAY);
617 	}
618 }
619 
620 static void
621 ar5416InitIMR(struct ath_hal *ah, HAL_OPMODE opmode)
622 {
623 	struct ath_hal_5212 *ahp = AH5212(ah);
624 
625 	/*
626 	 * Setup interrupt handling.  Note that ar5212ResetTxQueue
627 	 * manipulates the secondary IMR's as queues are enabled
628 	 * and disabled.  This is done with RMW ops to insure the
629 	 * settings we make here are preserved.
630 	 */
631         ahp->ah_maskReg = AR_IMR_TXERR | AR_IMR_TXURN
632 			| AR_IMR_RXERR | AR_IMR_RXORN
633                         | AR_IMR_BCNMISC;
634 
635 #ifdef	AH_AR5416_INTERRUPT_MITIGATION
636 	ahp->ah_maskReg |= AR_IMR_RXINTM | AR_IMR_RXMINTR;
637 #else
638 	ahp->ah_maskReg |= AR_IMR_RXOK;
639 #endif
640 	ahp->ah_maskReg |= AR_IMR_TXOK;
641 
642 	if (opmode == HAL_M_HOSTAP)
643 		ahp->ah_maskReg |= AR_IMR_MIB;
644 	OS_REG_WRITE(ah, AR_IMR, ahp->ah_maskReg);
645 
646 #ifdef  ADRIAN_NOTYET
647 	/* This is straight from ath9k */
648 	if (! AR_SREV_HOWL(ah)) {
649 		OS_REG_WRITE(ah, AR_INTR_SYNC_CAUSE, 0xFFFFFFFF);
650 		OS_REG_WRITE(ah, AR_INTR_SYNC_ENABLE, AR_INTR_SYNC_DEFAULT);
651 		OS_REG_WRITE(ah, AR_INTR_SYNC_MASK, 0);
652 	}
653 #endif
654 
655 	/* Enable bus errors that are OR'd to set the HIUERR bit */
656 #if 0
657 	OS_REG_WRITE(ah, AR_IMR_S2,
658 	    	OS_REG_READ(ah, AR_IMR_S2) | AR_IMR_S2_GTT | AR_IMR_S2_CST);
659 #endif
660 }
661 
662 static void
663 ar5416InitQoS(struct ath_hal *ah)
664 {
665 	/* QoS support */
666 	OS_REG_WRITE(ah, AR_QOS_CONTROL, 0x100aa);	/* XXX magic */
667 	OS_REG_WRITE(ah, AR_QOS_SELECT, 0x3210);	/* XXX magic */
668 
669 	/* Turn on NOACK Support for QoS packets */
670 	OS_REG_WRITE(ah, AR_NOACK,
671 		SM(2, AR_NOACK_2BIT_VALUE) |
672 		SM(5, AR_NOACK_BIT_OFFSET) |
673 		SM(0, AR_NOACK_BYTE_OFFSET));
674 
675     	/*
676     	 * initialize TXOP for all TIDs
677     	 */
678 	OS_REG_WRITE(ah, AR_TXOP_X, AR_TXOP_X_VAL);
679 	OS_REG_WRITE(ah, AR_TXOP_0_3, 0xFFFFFFFF);
680 	OS_REG_WRITE(ah, AR_TXOP_4_7, 0xFFFFFFFF);
681 	OS_REG_WRITE(ah, AR_TXOP_8_11, 0xFFFFFFFF);
682 	OS_REG_WRITE(ah, AR_TXOP_12_15, 0xFFFFFFFF);
683 }
684 
685 static void
686 ar5416InitUserSettings(struct ath_hal *ah)
687 {
688 	struct ath_hal_5212 *ahp = AH5212(ah);
689 
690 	/* Restore user-specified settings */
691 	if (ahp->ah_miscMode != 0)
692 		OS_REG_WRITE(ah, AR_MISC_MODE, OS_REG_READ(ah, AR_MISC_MODE)
693 		    | ahp->ah_miscMode);
694 	if (ahp->ah_sifstime != (u_int) -1)
695 		ar5212SetSifsTime(ah, ahp->ah_sifstime);
696 	if (ahp->ah_slottime != (u_int) -1)
697 		ar5212SetSlotTime(ah, ahp->ah_slottime);
698 	if (ahp->ah_acktimeout != (u_int) -1)
699 		ar5212SetAckTimeout(ah, ahp->ah_acktimeout);
700 	if (ahp->ah_ctstimeout != (u_int) -1)
701 		ar5212SetCTSTimeout(ah, ahp->ah_ctstimeout);
702 	if (AH_PRIVATE(ah)->ah_diagreg != 0)
703 		OS_REG_WRITE(ah, AR_DIAG_SW, AH_PRIVATE(ah)->ah_diagreg);
704 	if (AH5416(ah)->ah_globaltxtimeout != (u_int) -1)
705         	ar5416SetGlobalTxTimeout(ah, AH5416(ah)->ah_globaltxtimeout);
706 }
707 
708 static void
709 ar5416SetRfMode(struct ath_hal *ah, const struct ieee80211_channel *chan)
710 {
711 	uint32_t rfMode;
712 
713 	if (chan == AH_NULL)
714 		return;
715 
716 	/* treat channel B as channel G , no  B mode suport in owl */
717 	rfMode = IEEE80211_IS_CHAN_CCK(chan) ?
718 	    AR_PHY_MODE_DYNAMIC : AR_PHY_MODE_OFDM;
719 
720 	if (AR_SREV_MERLIN_20(ah) && IS_5GHZ_FAST_CLOCK_EN(ah, chan)) {
721 		/* phy mode bits for 5GHz channels require Fast Clock */
722 		rfMode |= AR_PHY_MODE_DYNAMIC
723 		       |  AR_PHY_MODE_DYN_CCK_DISABLE;
724 	} else if (!AR_SREV_MERLIN_10_OR_LATER(ah)) {
725 		rfMode |= IEEE80211_IS_CHAN_5GHZ(chan) ?
726 			AR_PHY_MODE_RF5GHZ : AR_PHY_MODE_RF2GHZ;
727 	}
728 
729 	/*
730 	 * Set half/quarter mode flags if required.
731 	 *
732 	 * This doesn't change the IFS timings at all; that needs to
733 	 * be done as part of the MAC setup.  Similarly, the PLL
734 	 * configuration also needs some changes for the half/quarter
735 	 * rate clock.
736 	 */
737 	if (IEEE80211_IS_CHAN_HALF(chan))
738 		rfMode |= AR_PHY_MODE_HALF;
739 	else if (IEEE80211_IS_CHAN_QUARTER(chan))
740 		rfMode |= AR_PHY_MODE_QUARTER;
741 
742 	OS_REG_WRITE(ah, AR_PHY_MODE, rfMode);
743 }
744 
745 /*
746  * Places the hardware into reset and then pulls it out of reset
747  */
748 HAL_BOOL
749 ar5416ChipReset(struct ath_hal *ah, const struct ieee80211_channel *chan)
750 {
751 	OS_MARK(ah, AH_MARK_CHIPRESET, chan ? chan->ic_freq : 0);
752 	/*
753 	 * Warm reset is optimistic for open-loop TX power control.
754 	 */
755 	if (AR_SREV_MERLIN(ah) &&
756 	    ath_hal_eepromGetFlag(ah, AR_EEP_OL_PWRCTRL)) {
757 		if (!ar5416SetResetReg(ah, HAL_RESET_POWER_ON))
758 			return AH_FALSE;
759 	} else if (ah->ah_config.ah_force_full_reset) {
760 		if (!ar5416SetResetReg(ah, HAL_RESET_POWER_ON))
761 			return AH_FALSE;
762 	} else {
763 		if (!ar5416SetResetReg(ah, HAL_RESET_WARM))
764 			return AH_FALSE;
765 	}
766 
767 	/* Bring out of sleep mode (AGAIN) */
768 	if (!ar5416SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
769 	       return AH_FALSE;
770 
771 #ifdef notyet
772 	ahp->ah_chipFullSleep = AH_FALSE;
773 #endif
774 
775 	AH5416(ah)->ah_initPLL(ah, chan);
776 
777 	/*
778 	 * Perform warm reset before the mode/PLL/turbo registers
779 	 * are changed in order to deactivate the radio.  Mode changes
780 	 * with an active radio can result in corrupted shifts to the
781 	 * radio device.
782 	 */
783 	ar5416SetRfMode(ah, chan);
784 
785 	return AH_TRUE;
786 }
787 
788 /*
789  * Delta slope coefficient computation.
790  * Required for OFDM operation.
791  */
792 static void
793 ar5416GetDeltaSlopeValues(struct ath_hal *ah, uint32_t coef_scaled,
794                           uint32_t *coef_mantissa, uint32_t *coef_exponent)
795 {
796 #define COEF_SCALE_S 24
797     uint32_t coef_exp, coef_man;
798     /*
799      * ALGO -> coef_exp = 14-floor(log2(coef));
800      * floor(log2(x)) is the highest set bit position
801      */
802     for (coef_exp = 31; coef_exp > 0; coef_exp--)
803             if ((coef_scaled >> coef_exp) & 0x1)
804                     break;
805     /* A coef_exp of 0 is a legal bit position but an unexpected coef_exp */
806     HALASSERT(coef_exp);
807     coef_exp = 14 - (coef_exp - COEF_SCALE_S);
808 
809     /*
810      * ALGO -> coef_man = floor(coef* 2^coef_exp+0.5);
811      * The coefficient is already shifted up for scaling
812      */
813     coef_man = coef_scaled + (1 << (COEF_SCALE_S - coef_exp - 1));
814 
815     *coef_mantissa = coef_man >> (COEF_SCALE_S - coef_exp);
816     *coef_exponent = coef_exp - 16;
817 
818 #undef COEF_SCALE_S
819 }
820 
821 void
822 ar5416SetDeltaSlope(struct ath_hal *ah, const struct ieee80211_channel *chan)
823 {
824 #define INIT_CLOCKMHZSCALED	0x64000000
825 	uint32_t coef_scaled, ds_coef_exp, ds_coef_man;
826 	uint32_t clockMhzScaled;
827 
828 	CHAN_CENTERS centers;
829 
830 	/* half and quarter rate can divide the scaled clock by 2 or 4 respectively */
831 	/* scale for selected channel bandwidth */
832 	clockMhzScaled = INIT_CLOCKMHZSCALED;
833 	if (IEEE80211_IS_CHAN_TURBO(chan))
834 		clockMhzScaled <<= 1;
835 	else if (IEEE80211_IS_CHAN_HALF(chan))
836 		clockMhzScaled >>= 1;
837 	else if (IEEE80211_IS_CHAN_QUARTER(chan))
838 		clockMhzScaled >>= 2;
839 
840 	/*
841 	 * ALGO -> coef = 1e8/fcarrier*fclock/40;
842 	 * scaled coef to provide precision for this floating calculation
843 	 */
844 	ar5416GetChannelCenters(ah, chan, &centers);
845 	coef_scaled = clockMhzScaled / centers.synth_center;
846 
847  	ar5416GetDeltaSlopeValues(ah, coef_scaled, &ds_coef_man, &ds_coef_exp);
848 
849 	OS_REG_RMW_FIELD(ah, AR_PHY_TIMING3,
850 		AR_PHY_TIMING3_DSC_MAN, ds_coef_man);
851 	OS_REG_RMW_FIELD(ah, AR_PHY_TIMING3,
852 		AR_PHY_TIMING3_DSC_EXP, ds_coef_exp);
853 
854         /*
855          * For Short GI,
856          * scaled coeff is 9/10 that of normal coeff
857          */
858         coef_scaled = (9 * coef_scaled)/10;
859 
860         ar5416GetDeltaSlopeValues(ah, coef_scaled, &ds_coef_man, &ds_coef_exp);
861 
862         /* for short gi */
863         OS_REG_RMW_FIELD(ah, AR_PHY_HALFGI,
864                 AR_PHY_HALFGI_DSC_MAN, ds_coef_man);
865         OS_REG_RMW_FIELD(ah, AR_PHY_HALFGI,
866                 AR_PHY_HALFGI_DSC_EXP, ds_coef_exp);
867 #undef INIT_CLOCKMHZSCALED
868 }
869 
870 /*
871  * Set a limit on the overall output power.  Used for dynamic
872  * transmit power control and the like.
873  *
874  * NB: limit is in units of 0.5 dbM.
875  */
876 HAL_BOOL
877 ar5416SetTxPowerLimit(struct ath_hal *ah, uint32_t limit)
878 {
879 	uint16_t dummyXpdGains[2];
880 
881 	AH_PRIVATE(ah)->ah_powerLimit = AH_MIN(limit, MAX_RATE_POWER);
882 	return ah->ah_setTxPower(ah, AH_PRIVATE(ah)->ah_curchan,
883 			dummyXpdGains);
884 }
885 
886 HAL_BOOL
887 ar5416GetChipPowerLimits(struct ath_hal *ah,
888 	struct ieee80211_channel *chan)
889 {
890 	struct ath_hal_5212 *ahp = AH5212(ah);
891 	int16_t minPower, maxPower;
892 
893 	/*
894 	 * Get Pier table max and min powers.
895 	 */
896 	if (ahp->ah_rfHal->getChannelMaxMinPower(ah, chan, &maxPower, &minPower)) {
897 		/* NB: rf code returns 1/4 dBm units, convert */
898 		chan->ic_maxpower = maxPower / 2;
899 		chan->ic_minpower = minPower / 2;
900 	} else {
901 		HALDEBUG(ah, HAL_DEBUG_ANY,
902 		    "%s: no min/max power for %u/0x%x\n",
903 		    __func__, chan->ic_freq, chan->ic_flags);
904 		chan->ic_maxpower = AR5416_MAX_RATE_POWER;
905 		chan->ic_minpower = 0;
906 	}
907 	HALDEBUG(ah, HAL_DEBUG_RESET,
908 	    "Chan %d: MaxPow = %d MinPow = %d\n",
909 	    chan->ic_freq, chan->ic_maxpower, chan->ic_minpower);
910 	return AH_TRUE;
911 }
912 
913 /**************************************************************
914  * ar5416WriteTxPowerRateRegisters
915  *
916  * Write the TX power rate registers from the raw values given
917  * in ratesArray[].
918  *
919  * The CCK and HT40 rate registers are only written if needed.
920  * HT20 and 11g/11a OFDM rate registers are always written.
921  *
922  * The values written are raw values which should be written
923  * to the registers - so it's up to the caller to pre-adjust
924  * them (eg CCK power offset value, or Merlin TX power offset,
925  * etc.)
926  */
927 void
928 ar5416WriteTxPowerRateRegisters(struct ath_hal *ah,
929     const struct ieee80211_channel *chan, const int16_t ratesArray[])
930 {
931 #define POW_SM(_r, _s)     (((_r) & 0x3f) << (_s))
932 
933     /* Write the OFDM power per rate set */
934     OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE1,
935         POW_SM(ratesArray[rate18mb], 24)
936           | POW_SM(ratesArray[rate12mb], 16)
937           | POW_SM(ratesArray[rate9mb], 8)
938           | POW_SM(ratesArray[rate6mb], 0)
939     );
940     OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE2,
941         POW_SM(ratesArray[rate54mb], 24)
942           | POW_SM(ratesArray[rate48mb], 16)
943           | POW_SM(ratesArray[rate36mb], 8)
944           | POW_SM(ratesArray[rate24mb], 0)
945     );
946 
947     if (IEEE80211_IS_CHAN_2GHZ(chan)) {
948         /* Write the CCK power per rate set */
949         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE3,
950             POW_SM(ratesArray[rate2s], 24)
951               | POW_SM(ratesArray[rate2l],  16)
952               | POW_SM(ratesArray[rateXr],  8) /* XR target power */
953               | POW_SM(ratesArray[rate1l],   0)
954         );
955         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE4,
956             POW_SM(ratesArray[rate11s], 24)
957               | POW_SM(ratesArray[rate11l], 16)
958               | POW_SM(ratesArray[rate5_5s], 8)
959               | POW_SM(ratesArray[rate5_5l], 0)
960         );
961     HALDEBUG(ah, HAL_DEBUG_RESET,
962 	"%s AR_PHY_POWER_TX_RATE3=0x%x AR_PHY_POWER_TX_RATE4=0x%x\n",
963 	    __func__, OS_REG_READ(ah,AR_PHY_POWER_TX_RATE3),
964 	    OS_REG_READ(ah,AR_PHY_POWER_TX_RATE4));
965     }
966 
967     /* Write the HT20 power per rate set */
968     OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE5,
969         POW_SM(ratesArray[rateHt20_3], 24)
970           | POW_SM(ratesArray[rateHt20_2], 16)
971           | POW_SM(ratesArray[rateHt20_1], 8)
972           | POW_SM(ratesArray[rateHt20_0], 0)
973     );
974     OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE6,
975         POW_SM(ratesArray[rateHt20_7], 24)
976           | POW_SM(ratesArray[rateHt20_6], 16)
977           | POW_SM(ratesArray[rateHt20_5], 8)
978           | POW_SM(ratesArray[rateHt20_4], 0)
979     );
980 
981     if (IEEE80211_IS_CHAN_HT40(chan)) {
982         /* Write the HT40 power per rate set */
983         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE7,
984             POW_SM(ratesArray[rateHt40_3], 24)
985               | POW_SM(ratesArray[rateHt40_2], 16)
986               | POW_SM(ratesArray[rateHt40_1], 8)
987               | POW_SM(ratesArray[rateHt40_0], 0)
988         );
989         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE8,
990             POW_SM(ratesArray[rateHt40_7], 24)
991               | POW_SM(ratesArray[rateHt40_6], 16)
992               | POW_SM(ratesArray[rateHt40_5], 8)
993               | POW_SM(ratesArray[rateHt40_4], 0)
994         );
995         /* Write the Dup/Ext 40 power per rate set */
996         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE9,
997             POW_SM(ratesArray[rateExtOfdm], 24)
998               | POW_SM(ratesArray[rateExtCck], 16)
999               | POW_SM(ratesArray[rateDupOfdm], 8)
1000               | POW_SM(ratesArray[rateDupCck], 0)
1001         );
1002     }
1003 }
1004 
1005 
1006 /**************************************************************
1007  * ar5416SetTransmitPower
1008  *
1009  * Set the transmit power in the baseband for the given
1010  * operating channel and mode.
1011  */
1012 HAL_BOOL
1013 ar5416SetTransmitPower(struct ath_hal *ah,
1014 	const struct ieee80211_channel *chan, uint16_t *rfXpdGain)
1015 {
1016 #define N(a)            (sizeof (a) / sizeof (a[0]))
1017 
1018     MODAL_EEP_HEADER	*pModal;
1019     struct ath_hal_5212 *ahp = AH5212(ah);
1020     int16_t		ratesArray[Ar5416RateSize];
1021     int16_t		txPowerIndexOffset = 0;
1022     uint8_t		ht40PowerIncForPdadc = 2;
1023     int			i;
1024 
1025     uint16_t		cfgCtl;
1026     uint16_t		powerLimit;
1027     uint16_t		twiceAntennaReduction;
1028     uint16_t		twiceMaxRegulatoryPower;
1029     int16_t		maxPower;
1030     HAL_EEPROM_v14 *ee = AH_PRIVATE(ah)->ah_eeprom;
1031     struct ar5416eeprom	*pEepData = &ee->ee_base;
1032 
1033     HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER14_1);
1034 
1035     /* Setup info for the actual eeprom */
1036     OS_MEMZERO(ratesArray, sizeof(ratesArray));
1037     cfgCtl = ath_hal_getctl(ah, chan);
1038     powerLimit = chan->ic_maxregpower * 2;
1039     twiceAntennaReduction = chan->ic_maxantgain;
1040     twiceMaxRegulatoryPower = AH_MIN(MAX_RATE_POWER, AH_PRIVATE(ah)->ah_powerLimit);
1041     pModal = &pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)];
1042     HALDEBUG(ah, HAL_DEBUG_RESET, "%s Channel=%u CfgCtl=%u\n",
1043 	__func__,chan->ic_freq, cfgCtl );
1044 
1045     if (IS_EEP_MINOR_V2(ah)) {
1046         ht40PowerIncForPdadc = pModal->ht40PowerIncForPdadc;
1047     }
1048 
1049     if (!ar5416SetPowerPerRateTable(ah, pEepData,  chan,
1050                                     &ratesArray[0],cfgCtl,
1051                                     twiceAntennaReduction,
1052 				    twiceMaxRegulatoryPower, powerLimit)) {
1053         HALDEBUG(ah, HAL_DEBUG_ANY,
1054 	    "%s: unable to set tx power per rate table\n", __func__);
1055         return AH_FALSE;
1056     }
1057 
1058     if (!AH5416(ah)->ah_setPowerCalTable(ah,  pEepData, chan, &txPowerIndexOffset)) {
1059         HALDEBUG(ah, HAL_DEBUG_ANY, "%s: unable to set power table\n",
1060 	    __func__);
1061         return AH_FALSE;
1062     }
1063 
1064     maxPower = AH_MAX(ratesArray[rate6mb], ratesArray[rateHt20_0]);
1065 
1066     if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1067         maxPower = AH_MAX(maxPower, ratesArray[rate1l]);
1068     }
1069 
1070     if (IEEE80211_IS_CHAN_HT40(chan)) {
1071         maxPower = AH_MAX(maxPower, ratesArray[rateHt40_0]);
1072     }
1073 
1074     ahp->ah_tx6PowerInHalfDbm = maxPower;
1075     AH_PRIVATE(ah)->ah_maxPowerLevel = maxPower;
1076     ahp->ah_txPowerIndexOffset = txPowerIndexOffset;
1077 
1078     /*
1079      * txPowerIndexOffset is set by the SetPowerTable() call -
1080      *  adjust the rate table (0 offset if rates EEPROM not loaded)
1081      */
1082     for (i = 0; i < N(ratesArray); i++) {
1083         ratesArray[i] = (int16_t)(txPowerIndexOffset + ratesArray[i]);
1084         if (ratesArray[i] > AR5416_MAX_RATE_POWER)
1085             ratesArray[i] = AR5416_MAX_RATE_POWER;
1086     }
1087 
1088 #ifdef AH_EEPROM_DUMP
1089     /*
1090      * Dump the rate array whilst it represents the intended dBm*2
1091      * values versus what's being adjusted before being programmed
1092      * in. Keep this in mind if you code up this function and enable
1093      * this debugging; the values won't necessarily be what's being
1094      * programmed into the hardware.
1095      */
1096     ar5416PrintPowerPerRate(ah, ratesArray);
1097 #endif
1098 
1099     /*
1100      * Merlin and later have a power offset, so subtract
1101      * pwr_table_offset * 2 from each value. The default
1102      * power offset is -5 dBm - ie, a register value of 0
1103      * equates to a TX power of -5 dBm.
1104      */
1105     if (AR_SREV_MERLIN_20_OR_LATER(ah)) {
1106         int8_t pwr_table_offset;
1107 
1108 	(void) ath_hal_eepromGet(ah, AR_EEP_PWR_TABLE_OFFSET,
1109 	    &pwr_table_offset);
1110 	/* Underflow power gets clamped at raw value 0 */
1111 	/* Overflow power gets camped at AR5416_MAX_RATE_POWER */
1112 	for (i = 0; i < N(ratesArray); i++) {
1113 		/*
1114 		 * + pwr_table_offset is in dBm
1115 		 * + ratesArray is in 1/2 dBm
1116 		 */
1117 		ratesArray[i] -= (pwr_table_offset * 2);
1118 		if (ratesArray[i] < 0)
1119 			ratesArray[i] = 0;
1120 		else if (ratesArray[i] > AR5416_MAX_RATE_POWER)
1121 		    ratesArray[i] = AR5416_MAX_RATE_POWER;
1122 	}
1123     }
1124 
1125     /*
1126      * Adjust rates for OLC where needed
1127      *
1128      * The following CCK rates need adjusting when doing 2.4ghz
1129      * CCK transmission.
1130      *
1131      * + rate2s, rate2l, rate1l, rate11s, rate11l, rate5_5s, rate5_5l
1132      * + rateExtCck, rateDupCck
1133      *
1134      * They're adjusted here regardless. The hardware then gets
1135      * programmed as needed. 5GHz operation doesn't program in CCK
1136      * rates for legacy mode but they seem to be initialised for
1137      * HT40 regardless of channel type.
1138      */
1139     if (AR_SREV_MERLIN_20_OR_LATER(ah) &&
1140 	    ath_hal_eepromGetFlag(ah, AR_EEP_OL_PWRCTRL)) {
1141         int adj[] = {
1142 	              rate2s, rate2l, rate1l, rate11s, rate11l,
1143 	              rate5_5s, rate5_5l, rateExtCck, rateDupCck
1144 		    };
1145         int cck_ofdm_delta = 2;
1146 	int i;
1147 	for (i = 0; i < N(adj); i++) {
1148             ratesArray[adj[i]] -= cck_ofdm_delta;
1149 	    if (ratesArray[adj[i]] < 0)
1150 	        ratesArray[adj[i]] = 0;
1151         }
1152     }
1153 
1154     /*
1155      * Adjust the HT40 power to meet the correct target TX power
1156      * for 40MHz mode, based on TX power curves that are established
1157      * for 20MHz mode.
1158      *
1159      * XXX handle overflow/too high power level?
1160      */
1161     if (IEEE80211_IS_CHAN_HT40(chan)) {
1162 	ratesArray[rateHt40_0] += ht40PowerIncForPdadc;
1163 	ratesArray[rateHt40_1] += ht40PowerIncForPdadc;
1164 	ratesArray[rateHt40_2] += ht40PowerIncForPdadc;
1165 	ratesArray[rateHt40_3] += ht40PowerIncForPdadc;
1166 	ratesArray[rateHt40_4] += ht40PowerIncForPdadc;
1167 	ratesArray[rateHt40_5] += ht40PowerIncForPdadc;
1168 	ratesArray[rateHt40_6] += ht40PowerIncForPdadc;
1169 	ratesArray[rateHt40_7] += ht40PowerIncForPdadc;
1170     }
1171 
1172     /* Write the TX power rate registers */
1173     ar5416WriteTxPowerRateRegisters(ah, chan, ratesArray);
1174 
1175     /* Write the Power subtraction for dynamic chain changing, for per-packet powertx */
1176     OS_REG_WRITE(ah, AR_PHY_POWER_TX_SUB,
1177         POW_SM(pModal->pwrDecreaseFor3Chain, 6)
1178           | POW_SM(pModal->pwrDecreaseFor2Chain, 0)
1179     );
1180     return AH_TRUE;
1181 #undef POW_SM
1182 #undef N
1183 }
1184 
1185 /*
1186  * Exported call to check for a recent gain reading and return
1187  * the current state of the thermal calibration gain engine.
1188  */
1189 HAL_RFGAIN
1190 ar5416GetRfgain(struct ath_hal *ah)
1191 {
1192 
1193 	return (HAL_RFGAIN_INACTIVE);
1194 }
1195 
1196 /*
1197  * Places all of hardware into reset
1198  */
1199 HAL_BOOL
1200 ar5416Disable(struct ath_hal *ah)
1201 {
1202 
1203 	if (!ar5416SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
1204 		return AH_FALSE;
1205 	if (! ar5416SetResetReg(ah, HAL_RESET_COLD))
1206 		return AH_FALSE;
1207 
1208 	AH5416(ah)->ah_initPLL(ah, AH_NULL);
1209 	return (AH_TRUE);
1210 }
1211 
1212 /*
1213  * Places the PHY and Radio chips into reset.  A full reset
1214  * must be called to leave this state.  The PCI/MAC/PCU are
1215  * not placed into reset as we must receive interrupt to
1216  * re-enable the hardware.
1217  */
1218 HAL_BOOL
1219 ar5416PhyDisable(struct ath_hal *ah)
1220 {
1221 
1222 	if (! ar5416SetResetReg(ah, HAL_RESET_WARM))
1223 		return AH_FALSE;
1224 
1225 	AH5416(ah)->ah_initPLL(ah, AH_NULL);
1226 	return (AH_TRUE);
1227 }
1228 
1229 /*
1230  * Write the given reset bit mask into the reset register
1231  */
1232 HAL_BOOL
1233 ar5416SetResetReg(struct ath_hal *ah, uint32_t type)
1234 {
1235 	/*
1236 	 * Set force wake
1237 	 */
1238 	OS_REG_WRITE(ah, AR_RTC_FORCE_WAKE,
1239 	    AR_RTC_FORCE_WAKE_EN | AR_RTC_FORCE_WAKE_ON_INT);
1240 
1241 	switch (type) {
1242 	case HAL_RESET_POWER_ON:
1243 		return ar5416SetResetPowerOn(ah);
1244 	case HAL_RESET_WARM:
1245 	case HAL_RESET_COLD:
1246 		return ar5416SetReset(ah, type);
1247 	default:
1248 		HALASSERT(AH_FALSE);
1249 		return AH_FALSE;
1250 	}
1251 }
1252 
1253 static HAL_BOOL
1254 ar5416SetResetPowerOn(struct ath_hal *ah)
1255 {
1256     /* Power On Reset (Hard Reset) */
1257 
1258     /*
1259      * Set force wake
1260      *
1261      * If the MAC was running, previously calling
1262      * reset will wake up the MAC but it may go back to sleep
1263      * before we can start polling.
1264      * Set force wake  stops that
1265      * This must be called before initiating a hard reset.
1266      */
1267     OS_REG_WRITE(ah, AR_RTC_FORCE_WAKE,
1268             AR_RTC_FORCE_WAKE_EN | AR_RTC_FORCE_WAKE_ON_INT);
1269 
1270     /*
1271      * PowerOn reset can be used in open loop power control or failure recovery.
1272      * If we do RTC reset while DMA is still running, hardware may corrupt memory.
1273      * Therefore, we need to reset AHB first to stop DMA.
1274      */
1275     if (! AR_SREV_HOWL(ah))
1276     	OS_REG_WRITE(ah, AR_RC, AR_RC_AHB);
1277     /*
1278      * RTC reset and clear
1279      */
1280     OS_REG_WRITE(ah, AR_RTC_RESET, 0);
1281     OS_DELAY(20);
1282 
1283     if (! AR_SREV_HOWL(ah))
1284     	OS_REG_WRITE(ah, AR_RC, 0);
1285 
1286     OS_REG_WRITE(ah, AR_RTC_RESET, 1);
1287 
1288     /*
1289      * Poll till RTC is ON
1290      */
1291     if (!ath_hal_wait(ah, AR_RTC_STATUS, AR_RTC_PM_STATUS_M, AR_RTC_STATUS_ON)) {
1292         HALDEBUG(ah, HAL_DEBUG_ANY, "%s: RTC not waking up\n", __func__);
1293         return AH_FALSE;
1294     }
1295 
1296     return ar5416SetReset(ah, HAL_RESET_COLD);
1297 }
1298 
1299 static HAL_BOOL
1300 ar5416SetReset(struct ath_hal *ah, int type)
1301 {
1302     uint32_t tmpReg, mask;
1303     uint32_t rst_flags;
1304 
1305 #ifdef	AH_SUPPORT_AR9130	/* Because of the AR9130 specific registers */
1306     if (AR_SREV_HOWL(ah)) {
1307         HALDEBUG(ah, HAL_DEBUG_ANY, "[ath] HOWL: Fiddling with derived clk!\n");
1308         uint32_t val = OS_REG_READ(ah, AR_RTC_DERIVED_CLK);
1309         val &= ~AR_RTC_DERIVED_CLK_PERIOD;
1310         val |= SM(1, AR_RTC_DERIVED_CLK_PERIOD);
1311         OS_REG_WRITE(ah, AR_RTC_DERIVED_CLK, val);
1312         (void) OS_REG_READ(ah, AR_RTC_DERIVED_CLK);
1313     }
1314 #endif	/* AH_SUPPORT_AR9130 */
1315 
1316     /*
1317      * Force wake
1318      */
1319     OS_REG_WRITE(ah, AR_RTC_FORCE_WAKE,
1320 	AR_RTC_FORCE_WAKE_EN | AR_RTC_FORCE_WAKE_ON_INT);
1321 
1322 #ifdef	AH_SUPPORT_AR9130
1323     if (AR_SREV_HOWL(ah)) {
1324         rst_flags = AR_RTC_RC_MAC_WARM | AR_RTC_RC_MAC_COLD |
1325           AR_RTC_RC_COLD_RESET | AR_RTC_RC_WARM_RESET;
1326     } else {
1327 #endif	/* AH_SUPPORT_AR9130 */
1328         /*
1329          * Reset AHB
1330          *
1331          * (In case the last interrupt source was a bus timeout.)
1332          * XXX TODO: this is not the way to do it! It should be recorded
1333          * XXX by the interrupt handler and passed _into_ the
1334          * XXX reset path routine so this occurs.
1335          */
1336         tmpReg = OS_REG_READ(ah, AR_INTR_SYNC_CAUSE);
1337         if (tmpReg & (AR_INTR_SYNC_LOCAL_TIMEOUT|AR_INTR_SYNC_RADM_CPL_TIMEOUT)) {
1338             OS_REG_WRITE(ah, AR_INTR_SYNC_ENABLE, 0);
1339             OS_REG_WRITE(ah, AR_RC, AR_RC_AHB|AR_RC_HOSTIF);
1340         } else {
1341 	    OS_REG_WRITE(ah, AR_RC, AR_RC_AHB);
1342         }
1343         rst_flags = AR_RTC_RC_MAC_WARM;
1344         if (type == HAL_RESET_COLD)
1345             rst_flags |= AR_RTC_RC_MAC_COLD;
1346 #ifdef	AH_SUPPORT_AR9130
1347     }
1348 #endif	/* AH_SUPPORT_AR9130 */
1349 
1350     OS_REG_WRITE(ah, AR_RTC_RC, rst_flags);
1351 
1352     if (AR_SREV_HOWL(ah))
1353         OS_DELAY(10000);
1354     else
1355         OS_DELAY(100);
1356 
1357     /*
1358      * Clear resets and force wakeup
1359      */
1360     OS_REG_WRITE(ah, AR_RTC_RC, 0);
1361     if (!ath_hal_wait(ah, AR_RTC_RC, AR_RTC_RC_M, 0)) {
1362         HALDEBUG(ah, HAL_DEBUG_ANY, "%s: RTC stuck in MAC reset\n", __func__);
1363         return AH_FALSE;
1364     }
1365 
1366     /* Clear AHB reset */
1367     if (! AR_SREV_HOWL(ah))
1368         OS_REG_WRITE(ah, AR_RC, 0);
1369 
1370     if (AR_SREV_HOWL(ah))
1371         OS_DELAY(50);
1372 
1373     if (AR_SREV_HOWL(ah)) {
1374                 uint32_t mask;
1375                 mask = OS_REG_READ(ah, AR_CFG);
1376                 if (mask & (AR_CFG_SWRB | AR_CFG_SWTB | AR_CFG_SWRG)) {
1377                         HALDEBUG(ah, HAL_DEBUG_RESET,
1378                                 "CFG Byte Swap Set 0x%x\n", mask);
1379                 } else {
1380                         mask =
1381                                 INIT_CONFIG_STATUS | AR_CFG_SWRB | AR_CFG_SWTB;
1382                         OS_REG_WRITE(ah, AR_CFG, mask);
1383                         HALDEBUG(ah, HAL_DEBUG_RESET,
1384                                 "Setting CFG 0x%x\n", OS_REG_READ(ah, AR_CFG));
1385                 }
1386     } else {
1387 	if (type == HAL_RESET_COLD) {
1388 		if (isBigEndian()) {
1389 			/*
1390 			 * Set CFG, little-endian for descriptor accesses.
1391 			 */
1392 			mask = INIT_CONFIG_STATUS | AR_CFG_SWRD;
1393 #ifndef AH_NEED_DESC_SWAP
1394 			mask |= AR_CFG_SWTD;
1395 #endif
1396 			HALDEBUG(ah, HAL_DEBUG_RESET,
1397 			    "%s Applying descriptor swap\n", __func__);
1398 			OS_REG_WRITE(ah, AR_CFG, mask);
1399 		} else
1400 			OS_REG_WRITE(ah, AR_CFG, INIT_CONFIG_STATUS);
1401 	}
1402     }
1403 
1404     return AH_TRUE;
1405 }
1406 
1407 void
1408 ar5416InitChainMasks(struct ath_hal *ah)
1409 {
1410 	int rx_chainmask = AH5416(ah)->ah_rx_chainmask;
1411 
1412 	/* Flip this for this chainmask regardless of chip */
1413 	if (rx_chainmask == 0x5)
1414 		OS_REG_SET_BIT(ah, AR_PHY_ANALOG_SWAP, AR_PHY_SWAP_ALT_CHAIN);
1415 
1416 	/*
1417 	 * Workaround for OWL 1.0 calibration failure; enable multi-chain;
1418 	 * then set true mask after calibration.
1419 	 */
1420 	if (IS_5416V1(ah) && (rx_chainmask == 0x5 || rx_chainmask == 0x3)) {
1421 		OS_REG_WRITE(ah, AR_PHY_RX_CHAINMASK, 0x7);
1422 		OS_REG_WRITE(ah, AR_PHY_CAL_CHAINMASK, 0x7);
1423 	} else {
1424 		OS_REG_WRITE(ah, AR_PHY_RX_CHAINMASK, AH5416(ah)->ah_rx_chainmask);
1425 		OS_REG_WRITE(ah, AR_PHY_CAL_CHAINMASK, AH5416(ah)->ah_rx_chainmask);
1426 	}
1427 	OS_REG_WRITE(ah, AR_SELFGEN_MASK, AH5416(ah)->ah_tx_chainmask);
1428 
1429 	if (AH5416(ah)->ah_tx_chainmask == 0x5)
1430 		OS_REG_SET_BIT(ah, AR_PHY_ANALOG_SWAP, AR_PHY_SWAP_ALT_CHAIN);
1431 
1432 	if (AR_SREV_HOWL(ah)) {
1433 		OS_REG_WRITE(ah, AR_PHY_ANALOG_SWAP,
1434 		OS_REG_READ(ah, AR_PHY_ANALOG_SWAP) | 0x00000001);
1435 	}
1436 }
1437 
1438 /*
1439  * Work-around for Owl 1.0 calibration failure.
1440  *
1441  * ar5416InitChainMasks sets the RX chainmask to 0x7 if it's Owl 1.0
1442  * due to init calibration failures. ar5416RestoreChainMask restores
1443  * these registers to the correct setting.
1444  */
1445 void
1446 ar5416RestoreChainMask(struct ath_hal *ah)
1447 {
1448 	int rx_chainmask = AH5416(ah)->ah_rx_chainmask;
1449 
1450 	if (IS_5416V1(ah) && (rx_chainmask == 0x5 || rx_chainmask == 0x3)) {
1451 		OS_REG_WRITE(ah, AR_PHY_RX_CHAINMASK, rx_chainmask);
1452 		OS_REG_WRITE(ah, AR_PHY_CAL_CHAINMASK, rx_chainmask);
1453 	}
1454 }
1455 
1456 /*
1457  * Update the chainmask based on the current channel configuration.
1458  *
1459  * XXX ath9k checks bluetooth co-existence here
1460  * XXX ath9k checks whether the current state is "off-channel".
1461  * XXX ath9k sticks the hardware into 1x1 mode for legacy;
1462  *     we're going to leave multi-RX on for multi-path cancellation.
1463  */
1464 static void
1465 ar5416UpdateChainMasks(struct ath_hal *ah, HAL_BOOL is_ht)
1466 {
1467 	struct ath_hal_private *ahpriv = AH_PRIVATE(ah);
1468 	HAL_CAPABILITIES *pCap = &ahpriv->ah_caps;
1469 
1470 	if (is_ht) {
1471 		AH5416(ah)->ah_tx_chainmask = pCap->halTxChainMask;
1472 	} else {
1473 		AH5416(ah)->ah_tx_chainmask = 1;
1474 	}
1475 	AH5416(ah)->ah_rx_chainmask = pCap->halRxChainMask;
1476 	HALDEBUG(ah, HAL_DEBUG_RESET, "TX chainmask: 0x%x; RX chainmask: 0x%x\n",
1477 	    AH5416(ah)->ah_tx_chainmask,
1478 	    AH5416(ah)->ah_rx_chainmask);
1479 }
1480 
1481 void
1482 ar5416InitPLL(struct ath_hal *ah, const struct ieee80211_channel *chan)
1483 {
1484 	uint32_t pll = AR_RTC_PLL_REFDIV_5 | AR_RTC_PLL_DIV2;
1485 	if (chan != AH_NULL) {
1486 		if (IEEE80211_IS_CHAN_HALF(chan))
1487 			pll |= SM(0x1, AR_RTC_PLL_CLKSEL);
1488 		else if (IEEE80211_IS_CHAN_QUARTER(chan))
1489 			pll |= SM(0x2, AR_RTC_PLL_CLKSEL);
1490 
1491 		if (IEEE80211_IS_CHAN_5GHZ(chan))
1492 			pll |= SM(0xa, AR_RTC_PLL_DIV);
1493 		else
1494 			pll |= SM(0xb, AR_RTC_PLL_DIV);
1495 	} else
1496 		pll |= SM(0xb, AR_RTC_PLL_DIV);
1497 
1498 	OS_REG_WRITE(ah, AR_RTC_PLL_CONTROL, pll);
1499 
1500 	/* TODO:
1501 	* For multi-band owl, switch between bands by reiniting the PLL.
1502 	*/
1503 
1504 	OS_DELAY(RTC_PLL_SETTLE_DELAY);
1505 
1506 	OS_REG_WRITE(ah, AR_RTC_SLEEP_CLK, AR_RTC_SLEEP_DERIVED_CLK);
1507 }
1508 
1509 static void
1510 ar5416SetDefGainValues(struct ath_hal *ah,
1511     const MODAL_EEP_HEADER *pModal,
1512     const struct ar5416eeprom *eep,
1513     uint8_t txRxAttenLocal, int regChainOffset, int i)
1514 {
1515 
1516 	if (IS_EEP_MINOR_V3(ah)) {
1517 		txRxAttenLocal = pModal->txRxAttenCh[i];
1518 
1519 		if (AR_SREV_MERLIN_10_OR_LATER(ah)) {
1520 			OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ + regChainOffset,
1521 			      AR_PHY_GAIN_2GHZ_XATTEN1_MARGIN,
1522 			      pModal->bswMargin[i]);
1523 			OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ + regChainOffset,
1524 			      AR_PHY_GAIN_2GHZ_XATTEN1_DB,
1525 			      pModal->bswAtten[i]);
1526 			OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ + regChainOffset,
1527 			      AR_PHY_GAIN_2GHZ_XATTEN2_MARGIN,
1528 			      pModal->xatten2Margin[i]);
1529 			OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ + regChainOffset,
1530 			      AR_PHY_GAIN_2GHZ_XATTEN2_DB,
1531 			      pModal->xatten2Db[i]);
1532 		} else {
1533 			OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ + regChainOffset,
1534 			      AR_PHY_GAIN_2GHZ_BSW_MARGIN,
1535 			      pModal->bswMargin[i]);
1536 			OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ + regChainOffset,
1537 			      AR_PHY_GAIN_2GHZ_BSW_ATTEN,
1538 			      pModal->bswAtten[i]);
1539 		}
1540 	}
1541 
1542 	if (AR_SREV_MERLIN_10_OR_LATER(ah)) {
1543 		OS_REG_RMW_FIELD(ah,
1544 		      AR_PHY_RXGAIN + regChainOffset,
1545 		      AR9280_PHY_RXGAIN_TXRX_ATTEN, txRxAttenLocal);
1546 		OS_REG_RMW_FIELD(ah,
1547 		      AR_PHY_RXGAIN + regChainOffset,
1548 		      AR9280_PHY_RXGAIN_TXRX_MARGIN, pModal->rxTxMarginCh[i]);
1549 	} else {
1550 		OS_REG_RMW_FIELD(ah,
1551 			  AR_PHY_RXGAIN + regChainOffset,
1552 			  AR_PHY_RXGAIN_TXRX_ATTEN, txRxAttenLocal);
1553 		OS_REG_RMW_FIELD(ah,
1554 			  AR_PHY_GAIN_2GHZ + regChainOffset,
1555 			  AR_PHY_GAIN_2GHZ_RXTX_MARGIN, pModal->rxTxMarginCh[i]);
1556 	}
1557 }
1558 
1559 /*
1560  * Get the register chain offset for the given chain.
1561  *
1562  * Take into account the register chain swapping with AR5416 v2.0.
1563  *
1564  * XXX make sure that the reg chain swapping is only done for
1565  * XXX AR5416 v2.0 or greater, and not later chips?
1566  */
1567 int
1568 ar5416GetRegChainOffset(struct ath_hal *ah, int i)
1569 {
1570 	int regChainOffset;
1571 
1572 	if (AR_SREV_5416_V20_OR_LATER(ah) &&
1573 	    (AH5416(ah)->ah_rx_chainmask == 0x5 ||
1574 	    AH5416(ah)->ah_tx_chainmask == 0x5) && (i != 0)) {
1575 		/* Regs are swapped from chain 2 to 1 for 5416 2_0 with
1576 		 * only chains 0 and 2 populated
1577 		 */
1578 		regChainOffset = (i == 1) ? 0x2000 : 0x1000;
1579 	} else {
1580 		regChainOffset = i * 0x1000;
1581 	}
1582 
1583 	return regChainOffset;
1584 }
1585 
1586 /*
1587  * Read EEPROM header info and program the device for correct operation
1588  * given the channel value.
1589  */
1590 HAL_BOOL
1591 ar5416SetBoardValues(struct ath_hal *ah, const struct ieee80211_channel *chan)
1592 {
1593     const HAL_EEPROM_v14 *ee = AH_PRIVATE(ah)->ah_eeprom;
1594     const struct ar5416eeprom *eep = &ee->ee_base;
1595     const MODAL_EEP_HEADER *pModal;
1596     int			i, regChainOffset;
1597     uint8_t		txRxAttenLocal;    /* workaround for eeprom versions <= 14.2 */
1598 
1599     HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER14_1);
1600     pModal = &eep->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)];
1601 
1602     /* NB: workaround for eeprom versions <= 14.2 */
1603     txRxAttenLocal = IEEE80211_IS_CHAN_2GHZ(chan) ? 23 : 44;
1604 
1605     OS_REG_WRITE(ah, AR_PHY_SWITCH_COM, pModal->antCtrlCommon);
1606     for (i = 0; i < AR5416_MAX_CHAINS; i++) {
1607 	   if (AR_SREV_MERLIN(ah)) {
1608 		if (i >= 2) break;
1609 	   }
1610 	regChainOffset = ar5416GetRegChainOffset(ah, i);
1611 
1612         OS_REG_WRITE(ah, AR_PHY_SWITCH_CHAIN_0 + regChainOffset, pModal->antCtrlChain[i]);
1613 
1614         OS_REG_WRITE(ah, AR_PHY_TIMING_CTRL4 + regChainOffset,
1615         	(OS_REG_READ(ah, AR_PHY_TIMING_CTRL4 + regChainOffset) &
1616         	~(AR_PHY_TIMING_CTRL4_IQCORR_Q_Q_COFF | AR_PHY_TIMING_CTRL4_IQCORR_Q_I_COFF)) |
1617         	SM(pModal->iqCalICh[i], AR_PHY_TIMING_CTRL4_IQCORR_Q_I_COFF) |
1618         	SM(pModal->iqCalQCh[i], AR_PHY_TIMING_CTRL4_IQCORR_Q_Q_COFF));
1619 
1620         /*
1621          * Large signal upgrade,
1622 	 * If 14.3 or later EEPROM, use
1623 	 * txRxAttenLocal = pModal->txRxAttenCh[i]
1624 	 * else txRxAttenLocal is fixed value above.
1625          */
1626 
1627         if ((i == 0) || AR_SREV_5416_V20_OR_LATER(ah))
1628 	    ar5416SetDefGainValues(ah, pModal, eep, txRxAttenLocal, regChainOffset, i);
1629 
1630     }
1631 
1632 	if (AR_SREV_MERLIN_10_OR_LATER(ah)) {
1633                 if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1634                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF2G1_CH0, AR_AN_RF2G1_CH0_OB, pModal->ob);
1635                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF2G1_CH0, AR_AN_RF2G1_CH0_DB, pModal->db);
1636                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF2G1_CH1, AR_AN_RF2G1_CH1_OB, pModal->ob_ch1);
1637                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF2G1_CH1, AR_AN_RF2G1_CH1_DB, pModal->db_ch1);
1638                 } else {
1639                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF5G1_CH0, AR_AN_RF5G1_CH0_OB5, pModal->ob);
1640                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF5G1_CH0, AR_AN_RF5G1_CH0_DB5, pModal->db);
1641                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF5G1_CH1, AR_AN_RF5G1_CH1_OB5, pModal->ob_ch1);
1642                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF5G1_CH1, AR_AN_RF5G1_CH1_DB5, pModal->db_ch1);
1643                 }
1644                 OS_A_REG_RMW_FIELD(ah, AR_AN_TOP2, AR_AN_TOP2_XPABIAS_LVL, pModal->xpaBiasLvl);
1645                 OS_A_REG_RMW_FIELD(ah, AR_AN_TOP2, AR_AN_TOP2_LOCALBIAS,
1646 		    !!(pModal->flagBits & AR5416_EEP_FLAG_LOCALBIAS));
1647                 OS_A_REG_RMW_FIELD(ah, AR_PHY_XPA_CFG, AR_PHY_FORCE_XPA_CFG,
1648 		    !!(pModal->flagBits & AR5416_EEP_FLAG_FORCEXPAON));
1649         }
1650 
1651     OS_REG_RMW_FIELD(ah, AR_PHY_SETTLING, AR_PHY_SETTLING_SWITCH, pModal->switchSettling);
1652     OS_REG_RMW_FIELD(ah, AR_PHY_DESIRED_SZ, AR_PHY_DESIRED_SZ_ADC, pModal->adcDesiredSize);
1653 
1654     if (! AR_SREV_MERLIN_10_OR_LATER(ah))
1655     	OS_REG_RMW_FIELD(ah, AR_PHY_DESIRED_SZ, AR_PHY_DESIRED_SZ_PGA, pModal->pgaDesiredSize);
1656 
1657     OS_REG_WRITE(ah, AR_PHY_RF_CTL4,
1658         SM(pModal->txEndToXpaOff, AR_PHY_RF_CTL4_TX_END_XPAA_OFF)
1659         | SM(pModal->txEndToXpaOff, AR_PHY_RF_CTL4_TX_END_XPAB_OFF)
1660         | SM(pModal->txFrameToXpaOn, AR_PHY_RF_CTL4_FRAME_XPAA_ON)
1661         | SM(pModal->txFrameToXpaOn, AR_PHY_RF_CTL4_FRAME_XPAB_ON));
1662 
1663     OS_REG_RMW_FIELD(ah, AR_PHY_RF_CTL3, AR_PHY_TX_END_TO_A2_RX_ON,
1664 	pModal->txEndToRxOn);
1665 
1666     if (AR_SREV_MERLIN_10_OR_LATER(ah)) {
1667 	OS_REG_RMW_FIELD(ah, AR_PHY_CCA, AR9280_PHY_CCA_THRESH62,
1668 	    pModal->thresh62);
1669 	OS_REG_RMW_FIELD(ah, AR_PHY_EXT_CCA0, AR_PHY_EXT_CCA0_THRESH62,
1670 	    pModal->thresh62);
1671     } else {
1672 	OS_REG_RMW_FIELD(ah, AR_PHY_CCA, AR_PHY_CCA_THRESH62,
1673 	    pModal->thresh62);
1674 	OS_REG_RMW_FIELD(ah, AR_PHY_EXT_CCA, AR_PHY_EXT_CCA_THRESH62,
1675 	    pModal->thresh62);
1676     }
1677 
1678     /* Minor Version Specific application */
1679     if (IS_EEP_MINOR_V2(ah)) {
1680         OS_REG_RMW_FIELD(ah, AR_PHY_RF_CTL2, AR_PHY_TX_FRAME_TO_DATA_START,
1681 	    pModal->txFrameToDataStart);
1682         OS_REG_RMW_FIELD(ah, AR_PHY_RF_CTL2, AR_PHY_TX_FRAME_TO_PA_ON,
1683 	    pModal->txFrameToPaOn);
1684     }
1685 
1686     if (IS_EEP_MINOR_V3(ah) && IEEE80211_IS_CHAN_HT40(chan))
1687 		/* Overwrite switch settling with HT40 value */
1688 		OS_REG_RMW_FIELD(ah, AR_PHY_SETTLING, AR_PHY_SETTLING_SWITCH,
1689 		    pModal->swSettleHt40);
1690 
1691     if (AR_SREV_MERLIN_20_OR_LATER(ah) && EEP_MINOR(ah) >= AR5416_EEP_MINOR_VER_19)
1692          OS_REG_RMW_FIELD(ah, AR_PHY_CCK_TX_CTRL, AR_PHY_CCK_TX_CTRL_TX_DAC_SCALE_CCK, pModal->miscBits);
1693 
1694         if (AR_SREV_MERLIN_20(ah) && EEP_MINOR(ah) >= AR5416_EEP_MINOR_VER_20) {
1695                 if (IEEE80211_IS_CHAN_2GHZ(chan))
1696                         OS_A_REG_RMW_FIELD(ah, AR_AN_TOP1, AR_AN_TOP1_DACIPMODE,
1697 			    eep->baseEepHeader.dacLpMode);
1698                 else if (eep->baseEepHeader.dacHiPwrMode_5G)
1699                         OS_A_REG_RMW_FIELD(ah, AR_AN_TOP1, AR_AN_TOP1_DACIPMODE, 0);
1700                 else
1701                         OS_A_REG_RMW_FIELD(ah, AR_AN_TOP1, AR_AN_TOP1_DACIPMODE,
1702 			    eep->baseEepHeader.dacLpMode);
1703 
1704 		OS_DELAY(100);
1705 
1706                 OS_REG_RMW_FIELD(ah, AR_PHY_FRAME_CTL, AR_PHY_FRAME_CTL_TX_CLIP,
1707 		    pModal->miscBits >> 2);
1708                 OS_REG_RMW_FIELD(ah, AR_PHY_TX_PWRCTRL9, AR_PHY_TX_DESIRED_SCALE_CCK,
1709 		    eep->baseEepHeader.desiredScaleCCK);
1710         }
1711 
1712     return (AH_TRUE);
1713 }
1714 
1715 /*
1716  * Helper functions common for AP/CB/XB
1717  */
1718 
1719 /*
1720  * Set the target power array "ratesArray" from the
1721  * given set of target powers.
1722  *
1723  * This is used by the various chipset/EEPROM TX power
1724  * setup routines.
1725  */
1726 void
1727 ar5416SetRatesArrayFromTargetPower(struct ath_hal *ah,
1728     const struct ieee80211_channel *chan,
1729     int16_t *ratesArray,
1730     const CAL_TARGET_POWER_LEG *targetPowerCck,
1731     const CAL_TARGET_POWER_LEG *targetPowerCckExt,
1732     const CAL_TARGET_POWER_LEG *targetPowerOfdm,
1733     const CAL_TARGET_POWER_LEG *targetPowerOfdmExt,
1734     const CAL_TARGET_POWER_HT *targetPowerHt20,
1735     const CAL_TARGET_POWER_HT *targetPowerHt40)
1736 {
1737 #define	N(a)	(sizeof(a)/sizeof(a[0]))
1738 	int i;
1739 
1740 	/* Blank the rates array, to be consistent */
1741 	for (i = 0; i < Ar5416RateSize; i++)
1742 		ratesArray[i] = 0;
1743 
1744 	/* Set rates Array from collected data */
1745 	ratesArray[rate6mb] = ratesArray[rate9mb] = ratesArray[rate12mb] =
1746 	ratesArray[rate18mb] = ratesArray[rate24mb] =
1747 	    targetPowerOfdm->tPow2x[0];
1748 	ratesArray[rate36mb] = targetPowerOfdm->tPow2x[1];
1749 	ratesArray[rate48mb] = targetPowerOfdm->tPow2x[2];
1750 	ratesArray[rate54mb] = targetPowerOfdm->tPow2x[3];
1751 	ratesArray[rateXr] = targetPowerOfdm->tPow2x[0];
1752 
1753 	for (i = 0; i < N(targetPowerHt20->tPow2x); i++) {
1754 		ratesArray[rateHt20_0 + i] = targetPowerHt20->tPow2x[i];
1755 	}
1756 
1757 	if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1758 		ratesArray[rate1l]  = targetPowerCck->tPow2x[0];
1759 		ratesArray[rate2s] = ratesArray[rate2l]  = targetPowerCck->tPow2x[1];
1760 		ratesArray[rate5_5s] = ratesArray[rate5_5l] = targetPowerCck->tPow2x[2];
1761 		ratesArray[rate11s] = ratesArray[rate11l] = targetPowerCck->tPow2x[3];
1762 	}
1763 	if (IEEE80211_IS_CHAN_HT40(chan)) {
1764 		for (i = 0; i < N(targetPowerHt40->tPow2x); i++) {
1765 			ratesArray[rateHt40_0 + i] = targetPowerHt40->tPow2x[i];
1766 		}
1767 		ratesArray[rateDupOfdm] = targetPowerHt40->tPow2x[0];
1768 		ratesArray[rateDupCck]  = targetPowerHt40->tPow2x[0];
1769 		ratesArray[rateExtOfdm] = targetPowerOfdmExt->tPow2x[0];
1770 		if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1771 			ratesArray[rateExtCck]  = targetPowerCckExt->tPow2x[0];
1772 		}
1773 	}
1774 #undef	N
1775 }
1776 
1777 /*
1778  * ar5416SetPowerPerRateTable
1779  *
1780  * Sets the transmit power in the baseband for the given
1781  * operating channel and mode.
1782  */
1783 static HAL_BOOL
1784 ar5416SetPowerPerRateTable(struct ath_hal *ah, struct ar5416eeprom *pEepData,
1785                            const struct ieee80211_channel *chan,
1786                            int16_t *ratesArray, uint16_t cfgCtl,
1787                            uint16_t AntennaReduction,
1788                            uint16_t twiceMaxRegulatoryPower,
1789                            uint16_t powerLimit)
1790 {
1791 #define	N(a)	(sizeof(a)/sizeof(a[0]))
1792 /* Local defines to distinguish between extension and control CTL's */
1793 #define EXT_ADDITIVE (0x8000)
1794 #define CTL_11A_EXT (CTL_11A | EXT_ADDITIVE)
1795 #define CTL_11G_EXT (CTL_11G | EXT_ADDITIVE)
1796 #define CTL_11B_EXT (CTL_11B | EXT_ADDITIVE)
1797 
1798 	uint16_t twiceMaxEdgePower = AR5416_MAX_RATE_POWER;
1799 	int i;
1800 	int16_t  twiceLargestAntenna;
1801 	CAL_CTL_DATA *rep;
1802 	CAL_TARGET_POWER_LEG targetPowerOfdm, targetPowerCck = {0, {0, 0, 0, 0}};
1803 	CAL_TARGET_POWER_LEG targetPowerOfdmExt = {0, {0, 0, 0, 0}}, targetPowerCckExt = {0, {0, 0, 0, 0}};
1804 	CAL_TARGET_POWER_HT  targetPowerHt20, targetPowerHt40 = {0, {0, 0, 0, 0}};
1805 	int16_t scaledPower, minCtlPower;
1806 
1807 #define SUB_NUM_CTL_MODES_AT_5G_40 2   /* excluding HT40, EXT-OFDM */
1808 #define SUB_NUM_CTL_MODES_AT_2G_40 3   /* excluding HT40, EXT-OFDM, EXT-CCK */
1809 	static const uint16_t ctlModesFor11a[] = {
1810 	   CTL_11A, CTL_5GHT20, CTL_11A_EXT, CTL_5GHT40
1811 	};
1812 	static const uint16_t ctlModesFor11g[] = {
1813 	   CTL_11B, CTL_11G, CTL_2GHT20, CTL_11B_EXT, CTL_11G_EXT, CTL_2GHT40
1814 	};
1815 	const uint16_t *pCtlMode;
1816 	uint16_t numCtlModes, ctlMode, freq;
1817 	CHAN_CENTERS centers;
1818 
1819 	ar5416GetChannelCenters(ah,  chan, &centers);
1820 
1821 	/* Compute TxPower reduction due to Antenna Gain */
1822 
1823 	twiceLargestAntenna = AH_MAX(AH_MAX(
1824 	    pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[0],
1825 	    pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[1]),
1826 	    pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[2]);
1827 #if 0
1828 	/* Turn it back on if we need to calculate per chain antenna gain reduction */
1829 	/* Use only if the expected gain > 6dbi */
1830 	/* Chain 0 is always used */
1831 	twiceLargestAntenna = pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[0];
1832 
1833 	/* Look at antenna gains of Chains 1 and 2 if the TX mask is set */
1834 	if (ahp->ah_tx_chainmask & 0x2)
1835 		twiceLargestAntenna = AH_MAX(twiceLargestAntenna,
1836 			pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[1]);
1837 
1838 	if (ahp->ah_tx_chainmask & 0x4)
1839 		twiceLargestAntenna = AH_MAX(twiceLargestAntenna,
1840 			pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[2]);
1841 #endif
1842 	twiceLargestAntenna = (int16_t)AH_MIN((AntennaReduction) - twiceLargestAntenna, 0);
1843 
1844 	/* XXX setup for 5212 use (really used?) */
1845 	ath_hal_eepromSet(ah,
1846 	    IEEE80211_IS_CHAN_2GHZ(chan) ? AR_EEP_ANTGAINMAX_2 : AR_EEP_ANTGAINMAX_5,
1847 	    twiceLargestAntenna);
1848 
1849 	/*
1850 	 * scaledPower is the minimum of the user input power level and
1851 	 * the regulatory allowed power level
1852 	 */
1853 	scaledPower = AH_MIN(powerLimit, twiceMaxRegulatoryPower + twiceLargestAntenna);
1854 
1855 	/* Reduce scaled Power by number of chains active to get to per chain tx power level */
1856 	/* TODO: better value than these? */
1857 	switch (owl_get_ntxchains(AH5416(ah)->ah_tx_chainmask)) {
1858 	case 1:
1859 		break;
1860 	case 2:
1861 		scaledPower -= pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].pwrDecreaseFor2Chain;
1862 		break;
1863 	case 3:
1864 		scaledPower -= pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].pwrDecreaseFor3Chain;
1865 		break;
1866 	default:
1867 		return AH_FALSE; /* Unsupported number of chains */
1868 	}
1869 
1870 	scaledPower = AH_MAX(0, scaledPower);
1871 
1872 	/* Get target powers from EEPROM - our baseline for TX Power */
1873 	if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1874 		/* Setup for CTL modes */
1875 		numCtlModes = N(ctlModesFor11g) - SUB_NUM_CTL_MODES_AT_2G_40; /* CTL_11B, CTL_11G, CTL_2GHT20 */
1876 		pCtlMode = ctlModesFor11g;
1877 
1878 		ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPowerCck,
1879 				AR5416_NUM_2G_CCK_TARGET_POWERS, &targetPowerCck, 4, AH_FALSE);
1880 		ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPower2G,
1881 				AR5416_NUM_2G_20_TARGET_POWERS, &targetPowerOfdm, 4, AH_FALSE);
1882 		ar5416GetTargetPowers(ah,  chan, pEepData->calTargetPower2GHT20,
1883 				AR5416_NUM_2G_20_TARGET_POWERS, &targetPowerHt20, 8, AH_FALSE);
1884 
1885 		if (IEEE80211_IS_CHAN_HT40(chan)) {
1886 			numCtlModes = N(ctlModesFor11g);    /* All 2G CTL's */
1887 
1888 			ar5416GetTargetPowers(ah,  chan, pEepData->calTargetPower2GHT40,
1889 				AR5416_NUM_2G_40_TARGET_POWERS, &targetPowerHt40, 8, AH_TRUE);
1890 			/* Get target powers for extension channels */
1891 			ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPowerCck,
1892 				AR5416_NUM_2G_CCK_TARGET_POWERS, &targetPowerCckExt, 4, AH_TRUE);
1893 			ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPower2G,
1894 				AR5416_NUM_2G_20_TARGET_POWERS, &targetPowerOfdmExt, 4, AH_TRUE);
1895 		}
1896 	} else {
1897 		/* Setup for CTL modes */
1898 		numCtlModes = N(ctlModesFor11a) - SUB_NUM_CTL_MODES_AT_5G_40; /* CTL_11A, CTL_5GHT20 */
1899 		pCtlMode = ctlModesFor11a;
1900 
1901 		ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPower5G,
1902 				AR5416_NUM_5G_20_TARGET_POWERS, &targetPowerOfdm, 4, AH_FALSE);
1903 		ar5416GetTargetPowers(ah,  chan, pEepData->calTargetPower5GHT20,
1904 				AR5416_NUM_5G_20_TARGET_POWERS, &targetPowerHt20, 8, AH_FALSE);
1905 
1906 		if (IEEE80211_IS_CHAN_HT40(chan)) {
1907 			numCtlModes = N(ctlModesFor11a); /* All 5G CTL's */
1908 
1909 			ar5416GetTargetPowers(ah,  chan, pEepData->calTargetPower5GHT40,
1910 				AR5416_NUM_5G_40_TARGET_POWERS, &targetPowerHt40, 8, AH_TRUE);
1911 			ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPower5G,
1912 				AR5416_NUM_5G_20_TARGET_POWERS, &targetPowerOfdmExt, 4, AH_TRUE);
1913 		}
1914 	}
1915 
1916 	/*
1917 	 * For MIMO, need to apply regulatory caps individually across dynamically
1918 	 * running modes: CCK, OFDM, HT20, HT40
1919 	 *
1920 	 * The outer loop walks through each possible applicable runtime mode.
1921 	 * The inner loop walks through each ctlIndex entry in EEPROM.
1922 	 * The ctl value is encoded as [7:4] == test group, [3:0] == test mode.
1923 	 *
1924 	 */
1925 	for (ctlMode = 0; ctlMode < numCtlModes; ctlMode++) {
1926 		HAL_BOOL isHt40CtlMode = (pCtlMode[ctlMode] == CTL_5GHT40) ||
1927 		    (pCtlMode[ctlMode] == CTL_2GHT40);
1928 		if (isHt40CtlMode) {
1929 			freq = centers.ctl_center;
1930 		} else if (pCtlMode[ctlMode] & EXT_ADDITIVE) {
1931 			freq = centers.ext_center;
1932 		} else {
1933 			freq = centers.ctl_center;
1934 		}
1935 
1936 		/* walk through each CTL index stored in EEPROM */
1937 		for (i = 0; (i < AR5416_NUM_CTLS) && pEepData->ctlIndex[i]; i++) {
1938 			uint16_t twiceMinEdgePower;
1939 
1940 			/* compare test group from regulatory channel list with test mode from pCtlMode list */
1941 			if ((((cfgCtl & ~CTL_MODE_M) | (pCtlMode[ctlMode] & CTL_MODE_M)) == pEepData->ctlIndex[i]) ||
1942 				(((cfgCtl & ~CTL_MODE_M) | (pCtlMode[ctlMode] & CTL_MODE_M)) ==
1943 				 ((pEepData->ctlIndex[i] & CTL_MODE_M) | SD_NO_CTL))) {
1944 				rep = &(pEepData->ctlData[i]);
1945 				twiceMinEdgePower = ar5416GetMaxEdgePower(freq,
1946 							rep->ctlEdges[owl_get_ntxchains(AH5416(ah)->ah_tx_chainmask) - 1],
1947 							IEEE80211_IS_CHAN_2GHZ(chan));
1948 				if ((cfgCtl & ~CTL_MODE_M) == SD_NO_CTL) {
1949 					/* Find the minimum of all CTL edge powers that apply to this channel */
1950 					twiceMaxEdgePower = AH_MIN(twiceMaxEdgePower, twiceMinEdgePower);
1951 				} else {
1952 					/* specific */
1953 					twiceMaxEdgePower = twiceMinEdgePower;
1954 					break;
1955 				}
1956 			}
1957 		}
1958 		minCtlPower = (uint8_t)AH_MIN(twiceMaxEdgePower, scaledPower);
1959 		/* Apply ctl mode to correct target power set */
1960 		switch(pCtlMode[ctlMode]) {
1961 		case CTL_11B:
1962 			for (i = 0; i < N(targetPowerCck.tPow2x); i++) {
1963 				targetPowerCck.tPow2x[i] = (uint8_t)AH_MIN(targetPowerCck.tPow2x[i], minCtlPower);
1964 			}
1965 			break;
1966 		case CTL_11A:
1967 		case CTL_11G:
1968 			for (i = 0; i < N(targetPowerOfdm.tPow2x); i++) {
1969 				targetPowerOfdm.tPow2x[i] = (uint8_t)AH_MIN(targetPowerOfdm.tPow2x[i], minCtlPower);
1970 			}
1971 			break;
1972 		case CTL_5GHT20:
1973 		case CTL_2GHT20:
1974 			for (i = 0; i < N(targetPowerHt20.tPow2x); i++) {
1975 				targetPowerHt20.tPow2x[i] = (uint8_t)AH_MIN(targetPowerHt20.tPow2x[i], minCtlPower);
1976 			}
1977 			break;
1978 		case CTL_11B_EXT:
1979 			targetPowerCckExt.tPow2x[0] = (uint8_t)AH_MIN(targetPowerCckExt.tPow2x[0], minCtlPower);
1980 			break;
1981 		case CTL_11A_EXT:
1982 		case CTL_11G_EXT:
1983 			targetPowerOfdmExt.tPow2x[0] = (uint8_t)AH_MIN(targetPowerOfdmExt.tPow2x[0], minCtlPower);
1984 			break;
1985 		case CTL_5GHT40:
1986 		case CTL_2GHT40:
1987 			for (i = 0; i < N(targetPowerHt40.tPow2x); i++) {
1988 				targetPowerHt40.tPow2x[i] = (uint8_t)AH_MIN(targetPowerHt40.tPow2x[i], minCtlPower);
1989 			}
1990 			break;
1991 		default:
1992 			return AH_FALSE;
1993 			break;
1994 		}
1995 	} /* end ctl mode checking */
1996 
1997 	/* Set rates Array from collected data */
1998 	ar5416SetRatesArrayFromTargetPower(ah, chan, ratesArray,
1999 	    &targetPowerCck,
2000 	    &targetPowerCckExt,
2001 	    &targetPowerOfdm,
2002 	    &targetPowerOfdmExt,
2003 	    &targetPowerHt20,
2004 	    &targetPowerHt40);
2005 	return AH_TRUE;
2006 #undef EXT_ADDITIVE
2007 #undef CTL_11A_EXT
2008 #undef CTL_11G_EXT
2009 #undef CTL_11B_EXT
2010 #undef SUB_NUM_CTL_MODES_AT_5G_40
2011 #undef SUB_NUM_CTL_MODES_AT_2G_40
2012 #undef N
2013 }
2014 
2015 /**************************************************************************
2016  * fbin2freq
2017  *
2018  * Get channel value from binary representation held in eeprom
2019  * RETURNS: the frequency in MHz
2020  */
2021 static uint16_t
2022 fbin2freq(uint8_t fbin, HAL_BOOL is2GHz)
2023 {
2024     /*
2025      * Reserved value 0xFF provides an empty definition both as
2026      * an fbin and as a frequency - do not convert
2027      */
2028     if (fbin == AR5416_BCHAN_UNUSED) {
2029         return fbin;
2030     }
2031 
2032     return (uint16_t)((is2GHz) ? (2300 + fbin) : (4800 + 5 * fbin));
2033 }
2034 
2035 /*
2036  * ar5416GetMaxEdgePower
2037  *
2038  * Find the maximum conformance test limit for the given channel and CTL info
2039  */
2040 uint16_t
2041 ar5416GetMaxEdgePower(uint16_t freq, CAL_CTL_EDGES *pRdEdgesPower, HAL_BOOL is2GHz)
2042 {
2043     uint16_t twiceMaxEdgePower = AR5416_MAX_RATE_POWER;
2044     int      i;
2045 
2046     /* Get the edge power */
2047     for (i = 0; (i < AR5416_NUM_BAND_EDGES) && (pRdEdgesPower[i].bChannel != AR5416_BCHAN_UNUSED) ; i++) {
2048         /*
2049          * If there's an exact channel match or an inband flag set
2050          * on the lower channel use the given rdEdgePower
2051          */
2052         if (freq == fbin2freq(pRdEdgesPower[i].bChannel, is2GHz)) {
2053             twiceMaxEdgePower = MS(pRdEdgesPower[i].tPowerFlag, CAL_CTL_EDGES_POWER);
2054             break;
2055         } else if ((i > 0) && (freq < fbin2freq(pRdEdgesPower[i].bChannel, is2GHz))) {
2056             if (fbin2freq(pRdEdgesPower[i - 1].bChannel, is2GHz) < freq && (pRdEdgesPower[i - 1].tPowerFlag & CAL_CTL_EDGES_FLAG) != 0) {
2057                 twiceMaxEdgePower = MS(pRdEdgesPower[i - 1].tPowerFlag, CAL_CTL_EDGES_POWER);
2058             }
2059             /* Leave loop - no more affecting edges possible in this monotonic increasing list */
2060             break;
2061         }
2062     }
2063     HALASSERT(twiceMaxEdgePower > 0);
2064     return twiceMaxEdgePower;
2065 }
2066 
2067 /**************************************************************
2068  * ar5416GetTargetPowers
2069  *
2070  * Return the rates of target power for the given target power table
2071  * channel, and number of channels
2072  */
2073 void
2074 ar5416GetTargetPowers(struct ath_hal *ah,  const struct ieee80211_channel *chan,
2075                       CAL_TARGET_POWER_HT *powInfo, uint16_t numChannels,
2076                       CAL_TARGET_POWER_HT *pNewPower, uint16_t numRates,
2077                       HAL_BOOL isHt40Target)
2078 {
2079     uint16_t clo, chi;
2080     int i;
2081     int matchIndex = -1, lowIndex = -1;
2082     uint16_t freq;
2083     CHAN_CENTERS centers;
2084 
2085     ar5416GetChannelCenters(ah,  chan, &centers);
2086     freq = isHt40Target ? centers.synth_center : centers.ctl_center;
2087 
2088     /* Copy the target powers into the temp channel list */
2089     if (freq <= fbin2freq(powInfo[0].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) {
2090         matchIndex = 0;
2091     } else {
2092         for (i = 0; (i < numChannels) && (powInfo[i].bChannel != AR5416_BCHAN_UNUSED); i++) {
2093             if (freq == fbin2freq(powInfo[i].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) {
2094                 matchIndex = i;
2095                 break;
2096             } else if ((freq < fbin2freq(powInfo[i].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) &&
2097                        (freq > fbin2freq(powInfo[i - 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))))
2098             {
2099                 lowIndex = i - 1;
2100                 break;
2101             }
2102         }
2103         if ((matchIndex == -1) && (lowIndex == -1)) {
2104             HALASSERT(freq > fbin2freq(powInfo[i - 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan)));
2105             matchIndex = i - 1;
2106         }
2107     }
2108 
2109     if (matchIndex != -1) {
2110         OS_MEMCPY(pNewPower, &powInfo[matchIndex], sizeof(*pNewPower));
2111     } else {
2112         HALASSERT(lowIndex != -1);
2113         /*
2114          * Get the lower and upper channels, target powers,
2115          * and interpolate between them.
2116          */
2117         clo = fbin2freq(powInfo[lowIndex].bChannel, IEEE80211_IS_CHAN_2GHZ(chan));
2118         chi = fbin2freq(powInfo[lowIndex + 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan));
2119 
2120         for (i = 0; i < numRates; i++) {
2121             pNewPower->tPow2x[i] = (uint8_t)ath_ee_interpolate(freq, clo, chi,
2122                                    powInfo[lowIndex].tPow2x[i], powInfo[lowIndex + 1].tPow2x[i]);
2123         }
2124     }
2125 }
2126 /**************************************************************
2127  * ar5416GetTargetPowersLeg
2128  *
2129  * Return the four rates of target power for the given target power table
2130  * channel, and number of channels
2131  */
2132 void
2133 ar5416GetTargetPowersLeg(struct ath_hal *ah,
2134                          const struct ieee80211_channel *chan,
2135                          CAL_TARGET_POWER_LEG *powInfo, uint16_t numChannels,
2136                          CAL_TARGET_POWER_LEG *pNewPower, uint16_t numRates,
2137 			 HAL_BOOL isExtTarget)
2138 {
2139     uint16_t clo, chi;
2140     int i;
2141     int matchIndex = -1, lowIndex = -1;
2142     uint16_t freq;
2143     CHAN_CENTERS centers;
2144 
2145     ar5416GetChannelCenters(ah,  chan, &centers);
2146     freq = (isExtTarget) ? centers.ext_center :centers.ctl_center;
2147 
2148     /* Copy the target powers into the temp channel list */
2149     if (freq <= fbin2freq(powInfo[0].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) {
2150         matchIndex = 0;
2151     } else {
2152         for (i = 0; (i < numChannels) && (powInfo[i].bChannel != AR5416_BCHAN_UNUSED); i++) {
2153             if (freq == fbin2freq(powInfo[i].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) {
2154                 matchIndex = i;
2155                 break;
2156             } else if ((freq < fbin2freq(powInfo[i].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) &&
2157                        (freq > fbin2freq(powInfo[i - 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))))
2158             {
2159                 lowIndex = i - 1;
2160                 break;
2161             }
2162         }
2163         if ((matchIndex == -1) && (lowIndex == -1)) {
2164             HALASSERT(freq > fbin2freq(powInfo[i - 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan)));
2165             matchIndex = i - 1;
2166         }
2167     }
2168 
2169     if (matchIndex != -1) {
2170         OS_MEMCPY(pNewPower, &powInfo[matchIndex], sizeof(*pNewPower));
2171     } else {
2172         HALASSERT(lowIndex != -1);
2173         /*
2174          * Get the lower and upper channels, target powers,
2175          * and interpolate between them.
2176          */
2177         clo = fbin2freq(powInfo[lowIndex].bChannel, IEEE80211_IS_CHAN_2GHZ(chan));
2178         chi = fbin2freq(powInfo[lowIndex + 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan));
2179 
2180         for (i = 0; i < numRates; i++) {
2181             pNewPower->tPow2x[i] = (uint8_t)ath_ee_interpolate(freq, clo, chi,
2182                                    powInfo[lowIndex].tPow2x[i], powInfo[lowIndex + 1].tPow2x[i]);
2183         }
2184     }
2185 }
2186 
2187 /*
2188  * Set the gain boundaries for the given radio chain.
2189  *
2190  * The gain boundaries tell the hardware at what point in the
2191  * PDADC array to "switch over" from one PD gain setting
2192  * to another. There's also a gain overlap between two
2193  * PDADC array gain curves where there's valid PD values
2194  * for 2 gain settings.
2195  *
2196  * The hardware uses the gain overlap and gain boundaries
2197  * to determine which gain curve to use for the given
2198  * target TX power.
2199  */
2200 void
2201 ar5416SetGainBoundariesClosedLoop(struct ath_hal *ah, int i,
2202     uint16_t pdGainOverlap_t2, uint16_t gainBoundaries[])
2203 {
2204 	int regChainOffset;
2205 
2206 	regChainOffset = ar5416GetRegChainOffset(ah, i);
2207 
2208 	HALDEBUG(ah, HAL_DEBUG_EEPROM, "%s: chain %d: gainOverlap_t2: %d,"
2209 	    " gainBoundaries: %d, %d, %d, %d\n", __func__, i, pdGainOverlap_t2,
2210 	    gainBoundaries[0], gainBoundaries[1], gainBoundaries[2],
2211 	    gainBoundaries[3]);
2212 	OS_REG_WRITE(ah, AR_PHY_TPCRG5 + regChainOffset,
2213 	    SM(pdGainOverlap_t2, AR_PHY_TPCRG5_PD_GAIN_OVERLAP) |
2214 	    SM(gainBoundaries[0], AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_1)  |
2215 	    SM(gainBoundaries[1], AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_2)  |
2216 	    SM(gainBoundaries[2], AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_3)  |
2217 	    SM(gainBoundaries[3], AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_4));
2218 }
2219 
2220 /*
2221  * Get the gain values and the number of gain levels given
2222  * in xpdMask.
2223  *
2224  * The EEPROM xpdMask determines which power detector gain
2225  * levels were used during calibration. Each of these mask
2226  * bits maps to a fixed gain level in hardware.
2227  */
2228 uint16_t
2229 ar5416GetXpdGainValues(struct ath_hal *ah, uint16_t xpdMask,
2230     uint16_t xpdGainValues[])
2231 {
2232     int i;
2233     uint16_t numXpdGain = 0;
2234 
2235     for (i = 1; i <= AR5416_PD_GAINS_IN_MASK; i++) {
2236         if ((xpdMask >> (AR5416_PD_GAINS_IN_MASK - i)) & 1) {
2237             if (numXpdGain >= AR5416_NUM_PD_GAINS) {
2238                 HALASSERT(0);
2239                 break;
2240             }
2241             xpdGainValues[numXpdGain] = (uint16_t)(AR5416_PD_GAINS_IN_MASK - i);
2242             numXpdGain++;
2243         }
2244     }
2245     return numXpdGain;
2246 }
2247 
2248 /*
2249  * Write the detector gain and biases.
2250  *
2251  * There are four power detector gain levels. The xpdMask in the EEPROM
2252  * determines which power detector gain levels have TX power calibration
2253  * data associated with them. This function writes the number of
2254  * PD gain levels and their values into the hardware.
2255  *
2256  * This is valid for all TX chains - the calibration data itself however
2257  * will likely differ per-chain.
2258  */
2259 void
2260 ar5416WriteDetectorGainBiases(struct ath_hal *ah, uint16_t numXpdGain,
2261     uint16_t xpdGainValues[])
2262 {
2263     HALDEBUG(ah, HAL_DEBUG_EEPROM, "%s: numXpdGain: %d,"
2264       " xpdGainValues: %d, %d, %d\n", __func__, numXpdGain,
2265       xpdGainValues[0], xpdGainValues[1], xpdGainValues[2]);
2266 
2267     OS_REG_WRITE(ah, AR_PHY_TPCRG1, (OS_REG_READ(ah, AR_PHY_TPCRG1) &
2268     	~(AR_PHY_TPCRG1_NUM_PD_GAIN | AR_PHY_TPCRG1_PD_GAIN_1 |
2269 	AR_PHY_TPCRG1_PD_GAIN_2 | AR_PHY_TPCRG1_PD_GAIN_3)) |
2270 	SM(numXpdGain - 1, AR_PHY_TPCRG1_NUM_PD_GAIN) |
2271 	SM(xpdGainValues[0], AR_PHY_TPCRG1_PD_GAIN_1 ) |
2272 	SM(xpdGainValues[1], AR_PHY_TPCRG1_PD_GAIN_2) |
2273 	SM(xpdGainValues[2],  AR_PHY_TPCRG1_PD_GAIN_3));
2274 }
2275 
2276 /*
2277  * Write the PDADC array to the given radio chain i.
2278  *
2279  * The 32 PDADC registers are written without any care about
2280  * their contents - so if various chips treat values as "special",
2281  * this routine will not care.
2282  */
2283 void
2284 ar5416WritePdadcValues(struct ath_hal *ah, int i, uint8_t pdadcValues[])
2285 {
2286 	int regOffset, regChainOffset;
2287 	int j;
2288 	int reg32;
2289 
2290 	regChainOffset = ar5416GetRegChainOffset(ah, i);
2291 	regOffset = AR_PHY_BASE + (672 << 2) + regChainOffset;
2292 
2293 	for (j = 0; j < 32; j++) {
2294 		reg32 = ((pdadcValues[4*j + 0] & 0xFF) << 0)  |
2295 		    ((pdadcValues[4*j + 1] & 0xFF) << 8)  |
2296 		    ((pdadcValues[4*j + 2] & 0xFF) << 16) |
2297 		    ((pdadcValues[4*j + 3] & 0xFF) << 24) ;
2298 		OS_REG_WRITE(ah, regOffset, reg32);
2299 		HALDEBUG(ah, HAL_DEBUG_EEPROM, "PDADC: Chain %d |"
2300 		    " PDADC %3d Value %3d | PDADC %3d Value %3d | PDADC %3d"
2301 		    " Value %3d | PDADC %3d Value %3d |\n",
2302 		    i,
2303 		    4*j, pdadcValues[4*j],
2304 		    4*j+1, pdadcValues[4*j + 1],
2305 		    4*j+2, pdadcValues[4*j + 2],
2306 		    4*j+3, pdadcValues[4*j + 3]);
2307 		regOffset += 4;
2308 	}
2309 }
2310 
2311 /**************************************************************
2312  * ar5416SetPowerCalTable
2313  *
2314  * Pull the PDADC piers from cal data and interpolate them across the given
2315  * points as well as from the nearest pier(s) to get a power detector
2316  * linear voltage to power level table.
2317  */
2318 HAL_BOOL
2319 ar5416SetPowerCalTable(struct ath_hal *ah, struct ar5416eeprom *pEepData,
2320 	const struct ieee80211_channel *chan, int16_t *pTxPowerIndexOffset)
2321 {
2322     CAL_DATA_PER_FREQ *pRawDataset;
2323     uint8_t  *pCalBChans = AH_NULL;
2324     uint16_t pdGainOverlap_t2;
2325     static uint8_t  pdadcValues[AR5416_NUM_PDADC_VALUES];
2326     uint16_t gainBoundaries[AR5416_PD_GAINS_IN_MASK];
2327     uint16_t numPiers, i;
2328     int16_t  tMinCalPower;
2329     uint16_t numXpdGain, xpdMask;
2330     uint16_t xpdGainValues[AR5416_NUM_PD_GAINS];
2331     uint32_t regChainOffset;
2332 
2333     OS_MEMZERO(xpdGainValues, sizeof(xpdGainValues));
2334 
2335     xpdMask = pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].xpdGain;
2336 
2337     if (IS_EEP_MINOR_V2(ah)) {
2338         pdGainOverlap_t2 = pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].pdGainOverlap;
2339     } else {
2340     	pdGainOverlap_t2 = (uint16_t)(MS(OS_REG_READ(ah, AR_PHY_TPCRG5), AR_PHY_TPCRG5_PD_GAIN_OVERLAP));
2341     }
2342 
2343     if (IEEE80211_IS_CHAN_2GHZ(chan)) {
2344         pCalBChans = pEepData->calFreqPier2G;
2345         numPiers = AR5416_NUM_2G_CAL_PIERS;
2346     } else {
2347         pCalBChans = pEepData->calFreqPier5G;
2348         numPiers = AR5416_NUM_5G_CAL_PIERS;
2349     }
2350 
2351     /* Calculate the value of xpdgains from the xpdGain Mask */
2352     numXpdGain = ar5416GetXpdGainValues(ah, xpdMask, xpdGainValues);
2353 
2354     /* Write the detector gain biases and their number */
2355     ar5416WriteDetectorGainBiases(ah, numXpdGain, xpdGainValues);
2356 
2357     for (i = 0; i < AR5416_MAX_CHAINS; i++) {
2358 	regChainOffset = ar5416GetRegChainOffset(ah, i);
2359 
2360         if (pEepData->baseEepHeader.txMask & (1 << i)) {
2361             if (IEEE80211_IS_CHAN_2GHZ(chan)) {
2362                 pRawDataset = pEepData->calPierData2G[i];
2363             } else {
2364                 pRawDataset = pEepData->calPierData5G[i];
2365             }
2366 
2367             /* Fetch the gain boundaries and the PDADC values */
2368 	    ar5416GetGainBoundariesAndPdadcs(ah,  chan, pRawDataset,
2369                                              pCalBChans, numPiers,
2370                                              pdGainOverlap_t2,
2371                                              &tMinCalPower, gainBoundaries,
2372                                              pdadcValues, numXpdGain);
2373 
2374             if ((i == 0) || AR_SREV_5416_V20_OR_LATER(ah)) {
2375 		ar5416SetGainBoundariesClosedLoop(ah, i, pdGainOverlap_t2,
2376 		  gainBoundaries);
2377             }
2378 
2379             /* Write the power values into the baseband power table */
2380 	    ar5416WritePdadcValues(ah, i, pdadcValues);
2381         }
2382     }
2383     *pTxPowerIndexOffset = 0;
2384 
2385     return AH_TRUE;
2386 }
2387 
2388 /**************************************************************
2389  * ar5416GetGainBoundariesAndPdadcs
2390  *
2391  * Uses the data points read from EEPROM to reconstruct the pdadc power table
2392  * Called by ar5416SetPowerCalTable only.
2393  */
2394 void
2395 ar5416GetGainBoundariesAndPdadcs(struct ath_hal *ah,
2396                                  const struct ieee80211_channel *chan,
2397 				 CAL_DATA_PER_FREQ *pRawDataSet,
2398                                  uint8_t * bChans,  uint16_t availPiers,
2399                                  uint16_t tPdGainOverlap, int16_t *pMinCalPower, uint16_t * pPdGainBoundaries,
2400                                  uint8_t * pPDADCValues, uint16_t numXpdGains)
2401 {
2402 
2403     int       i, j, k;
2404     int16_t   ss;         /* potentially -ve index for taking care of pdGainOverlap */
2405     uint16_t  idxL, idxR, numPiers; /* Pier indexes */
2406 
2407     /* filled out Vpd table for all pdGains (chanL) */
2408     static uint8_t   vpdTableL[AR5416_NUM_PD_GAINS][AR5416_MAX_PWR_RANGE_IN_HALF_DB];
2409 
2410     /* filled out Vpd table for all pdGains (chanR) */
2411     static uint8_t   vpdTableR[AR5416_NUM_PD_GAINS][AR5416_MAX_PWR_RANGE_IN_HALF_DB];
2412 
2413     /* filled out Vpd table for all pdGains (interpolated) */
2414     static uint8_t   vpdTableI[AR5416_NUM_PD_GAINS][AR5416_MAX_PWR_RANGE_IN_HALF_DB];
2415 
2416     uint8_t   *pVpdL, *pVpdR, *pPwrL, *pPwrR;
2417     uint8_t   minPwrT4[AR5416_NUM_PD_GAINS];
2418     uint8_t   maxPwrT4[AR5416_NUM_PD_GAINS];
2419     int16_t   vpdStep;
2420     int16_t   tmpVal;
2421     uint16_t  sizeCurrVpdTable, maxIndex, tgtIndex;
2422     HAL_BOOL    match;
2423     int16_t  minDelta = 0;
2424     CHAN_CENTERS centers;
2425 
2426     ar5416GetChannelCenters(ah, chan, &centers);
2427 
2428     /* Trim numPiers for the number of populated channel Piers */
2429     for (numPiers = 0; numPiers < availPiers; numPiers++) {
2430         if (bChans[numPiers] == AR5416_BCHAN_UNUSED) {
2431             break;
2432         }
2433     }
2434 
2435     /* Find pier indexes around the current channel */
2436     match = ath_ee_getLowerUpperIndex((uint8_t)FREQ2FBIN(centers.synth_center,
2437 	IEEE80211_IS_CHAN_2GHZ(chan)), bChans, numPiers, &idxL, &idxR);
2438 
2439     if (match) {
2440         /* Directly fill both vpd tables from the matching index */
2441         for (i = 0; i < numXpdGains; i++) {
2442             minPwrT4[i] = pRawDataSet[idxL].pwrPdg[i][0];
2443             maxPwrT4[i] = pRawDataSet[idxL].pwrPdg[i][4];
2444             ath_ee_FillVpdTable(minPwrT4[i], maxPwrT4[i], pRawDataSet[idxL].pwrPdg[i],
2445                                pRawDataSet[idxL].vpdPdg[i], AR5416_PD_GAIN_ICEPTS, vpdTableI[i]);
2446         }
2447     } else {
2448         for (i = 0; i < numXpdGains; i++) {
2449             pVpdL = pRawDataSet[idxL].vpdPdg[i];
2450             pPwrL = pRawDataSet[idxL].pwrPdg[i];
2451             pVpdR = pRawDataSet[idxR].vpdPdg[i];
2452             pPwrR = pRawDataSet[idxR].pwrPdg[i];
2453 
2454             /* Start Vpd interpolation from the max of the minimum powers */
2455             minPwrT4[i] = AH_MAX(pPwrL[0], pPwrR[0]);
2456 
2457             /* End Vpd interpolation from the min of the max powers */
2458             maxPwrT4[i] = AH_MIN(pPwrL[AR5416_PD_GAIN_ICEPTS - 1], pPwrR[AR5416_PD_GAIN_ICEPTS - 1]);
2459             HALASSERT(maxPwrT4[i] > minPwrT4[i]);
2460 
2461             /* Fill pier Vpds */
2462             ath_ee_FillVpdTable(minPwrT4[i], maxPwrT4[i], pPwrL, pVpdL, AR5416_PD_GAIN_ICEPTS, vpdTableL[i]);
2463             ath_ee_FillVpdTable(minPwrT4[i], maxPwrT4[i], pPwrR, pVpdR, AR5416_PD_GAIN_ICEPTS, vpdTableR[i]);
2464 
2465             /* Interpolate the final vpd */
2466             for (j = 0; j <= (maxPwrT4[i] - minPwrT4[i]) / 2; j++) {
2467                 vpdTableI[i][j] = (uint8_t)(ath_ee_interpolate((uint16_t)FREQ2FBIN(centers.synth_center,
2468 		    IEEE80211_IS_CHAN_2GHZ(chan)),
2469                     bChans[idxL], bChans[idxR], vpdTableL[i][j], vpdTableR[i][j]));
2470             }
2471         }
2472     }
2473     *pMinCalPower = (int16_t)(minPwrT4[0] / 2);
2474 
2475     k = 0; /* index for the final table */
2476     for (i = 0; i < numXpdGains; i++) {
2477         if (i == (numXpdGains - 1)) {
2478             pPdGainBoundaries[i] = (uint16_t)(maxPwrT4[i] / 2);
2479         } else {
2480             pPdGainBoundaries[i] = (uint16_t)((maxPwrT4[i] + minPwrT4[i+1]) / 4);
2481         }
2482 
2483         pPdGainBoundaries[i] = (uint16_t)AH_MIN(AR5416_MAX_RATE_POWER, pPdGainBoundaries[i]);
2484 
2485 	/* NB: only applies to owl 1.0 */
2486         if ((i == 0) && !AR_SREV_5416_V20_OR_LATER(ah) ) {
2487 	    /*
2488              * fix the gain delta, but get a delta that can be applied to min to
2489              * keep the upper power values accurate, don't think max needs to
2490              * be adjusted because should not be at that area of the table?
2491 	     */
2492             minDelta = pPdGainBoundaries[0] - 23;
2493             pPdGainBoundaries[0] = 23;
2494         }
2495         else {
2496             minDelta = 0;
2497         }
2498 
2499         /* Find starting index for this pdGain */
2500         if (i == 0) {
2501             if (AR_SREV_MERLIN_10_OR_LATER(ah))
2502                 ss = (int16_t)(0 - (minPwrT4[i] / 2));
2503             else
2504                 ss = 0; /* for the first pdGain, start from index 0 */
2505         } else {
2506 	    /* need overlap entries extrapolated below. */
2507             ss = (int16_t)((pPdGainBoundaries[i-1] - (minPwrT4[i] / 2)) - tPdGainOverlap + 1 + minDelta);
2508         }
2509         vpdStep = (int16_t)(vpdTableI[i][1] - vpdTableI[i][0]);
2510         vpdStep = (int16_t)((vpdStep < 1) ? 1 : vpdStep);
2511         /*
2512          *-ve ss indicates need to extrapolate data below for this pdGain
2513          */
2514         while ((ss < 0) && (k < (AR5416_NUM_PDADC_VALUES - 1))) {
2515             tmpVal = (int16_t)(vpdTableI[i][0] + ss * vpdStep);
2516             pPDADCValues[k++] = (uint8_t)((tmpVal < 0) ? 0 : tmpVal);
2517             ss++;
2518         }
2519 
2520         sizeCurrVpdTable = (uint8_t)((maxPwrT4[i] - minPwrT4[i]) / 2 +1);
2521         tgtIndex = (uint8_t)(pPdGainBoundaries[i] + tPdGainOverlap - (minPwrT4[i] / 2));
2522         maxIndex = (tgtIndex < sizeCurrVpdTable) ? tgtIndex : sizeCurrVpdTable;
2523 
2524         while ((ss < maxIndex) && (k < (AR5416_NUM_PDADC_VALUES - 1))) {
2525             pPDADCValues[k++] = vpdTableI[i][ss++];
2526         }
2527 
2528         vpdStep = (int16_t)(vpdTableI[i][sizeCurrVpdTable - 1] - vpdTableI[i][sizeCurrVpdTable - 2]);
2529         vpdStep = (int16_t)((vpdStep < 1) ? 1 : vpdStep);
2530         /*
2531          * for last gain, pdGainBoundary == Pmax_t2, so will
2532          * have to extrapolate
2533          */
2534         if (tgtIndex >= maxIndex) {  /* need to extrapolate above */
2535             while ((ss <= tgtIndex) && (k < (AR5416_NUM_PDADC_VALUES - 1))) {
2536                 tmpVal = (int16_t)((vpdTableI[i][sizeCurrVpdTable - 1] +
2537                           (ss - maxIndex +1) * vpdStep));
2538                 pPDADCValues[k++] = (uint8_t)((tmpVal > 255) ? 255 : tmpVal);
2539                 ss++;
2540             }
2541         }               /* extrapolated above */
2542     }                   /* for all pdGainUsed */
2543 
2544     /* Fill out pdGainBoundaries - only up to 2 allowed here, but hardware allows up to 4 */
2545     while (i < AR5416_PD_GAINS_IN_MASK) {
2546         pPdGainBoundaries[i] = pPdGainBoundaries[i-1];
2547         i++;
2548     }
2549 
2550     while (k < AR5416_NUM_PDADC_VALUES) {
2551         pPDADCValues[k] = pPDADCValues[k-1];
2552         k++;
2553     }
2554     return;
2555 }
2556 
2557 /*
2558  * The linux ath9k driver and (from what I've been told) the reference
2559  * Atheros driver enables the 11n PHY by default whether or not it's
2560  * configured.
2561  */
2562 static void
2563 ar5416Set11nRegs(struct ath_hal *ah, const struct ieee80211_channel *chan)
2564 {
2565 	uint32_t phymode;
2566 	uint32_t enableDacFifo = 0;
2567 	HAL_HT_MACMODE macmode;		/* MAC - 20/40 mode */
2568 
2569 	if (AR_SREV_KITE_10_OR_LATER(ah))
2570 		enableDacFifo = (OS_REG_READ(ah, AR_PHY_TURBO) & AR_PHY_FC_ENABLE_DAC_FIFO);
2571 
2572 	/* Enable 11n HT, 20 MHz */
2573 	phymode = AR_PHY_FC_HT_EN | AR_PHY_FC_SHORT_GI_40
2574 		| AR_PHY_FC_SINGLE_HT_LTF1 | AR_PHY_FC_WALSH | enableDacFifo;
2575 
2576 	/* Configure baseband for dynamic 20/40 operation */
2577 	if (IEEE80211_IS_CHAN_HT40(chan)) {
2578 		phymode |= AR_PHY_FC_DYN2040_EN;
2579 
2580 		/* Configure control (primary) channel at +-10MHz */
2581 		if (IEEE80211_IS_CHAN_HT40U(chan))
2582 			phymode |= AR_PHY_FC_DYN2040_PRI_CH;
2583 #if 0
2584 		/* Configure 20/25 spacing */
2585 		if (ht->ht_extprotspacing == HAL_HT_EXTPROTSPACING_25)
2586 			phymode |= AR_PHY_FC_DYN2040_EXT_CH;
2587 #endif
2588 		macmode = HAL_HT_MACMODE_2040;
2589 	} else
2590 		macmode = HAL_HT_MACMODE_20;
2591 	OS_REG_WRITE(ah, AR_PHY_TURBO, phymode);
2592 
2593 	/* Configure MAC for 20/40 operation */
2594 	ar5416Set11nMac2040(ah, macmode);
2595 
2596 	/* global transmit timeout (25 TUs default)*/
2597 	/* XXX - put this elsewhere??? */
2598 	OS_REG_WRITE(ah, AR_GTXTO, 25 << AR_GTXTO_TIMEOUT_LIMIT_S) ;
2599 
2600 	/* carrier sense timeout */
2601 	OS_REG_SET_BIT(ah, AR_GTTM, AR_GTTM_CST_USEC);
2602 	OS_REG_WRITE(ah, AR_CST, 0xF << AR_CST_TIMEOUT_LIMIT_S);
2603 }
2604 
2605 void
2606 ar5416GetChannelCenters(struct ath_hal *ah,
2607 	const struct ieee80211_channel *chan, CHAN_CENTERS *centers)
2608 {
2609 	uint16_t freq = ath_hal_gethwchannel(ah, chan);
2610 
2611 	centers->ctl_center = freq;
2612 	centers->synth_center = freq;
2613 	/*
2614 	 * In 20/40 phy mode, the center frequency is
2615 	 * "between" the control and extension channels.
2616 	 */
2617 	if (IEEE80211_IS_CHAN_HT40U(chan)) {
2618 		centers->synth_center += HT40_CHANNEL_CENTER_SHIFT;
2619 		centers->ext_center =
2620 		    centers->synth_center + HT40_CHANNEL_CENTER_SHIFT;
2621 	} else if (IEEE80211_IS_CHAN_HT40D(chan)) {
2622 		centers->synth_center -= HT40_CHANNEL_CENTER_SHIFT;
2623 		centers->ext_center =
2624 		    centers->synth_center - HT40_CHANNEL_CENTER_SHIFT;
2625 	} else {
2626 		centers->ext_center = freq;
2627 	}
2628 }
2629 
2630 /*
2631  * Override the INI vals being programmed.
2632  */
2633 static void
2634 ar5416OverrideIni(struct ath_hal *ah, const struct ieee80211_channel *chan)
2635 {
2636 	uint32_t val;
2637 
2638 	/*
2639 	 * Set the RX_ABORT and RX_DIS and clear if off only after
2640 	 * RXE is set for MAC. This prevents frames with corrupted
2641 	 * descriptor status.
2642 	 */
2643 	OS_REG_SET_BIT(ah, AR_DIAG_SW, (AR_DIAG_RX_DIS | AR_DIAG_RX_ABORT));
2644 
2645 	if (AR_SREV_MERLIN_10_OR_LATER(ah)) {
2646 		val = OS_REG_READ(ah, AR_PCU_MISC_MODE2);
2647 		val &= (~AR_PCU_MISC_MODE2_ADHOC_MCAST_KEYID_ENABLE);
2648 		if (!AR_SREV_9271(ah))
2649 			val &= ~AR_PCU_MISC_MODE2_HWWAR1;
2650 
2651 		if (AR_SREV_KIWI_10_OR_LATER(ah))
2652 			val = val & (~AR_PCU_MISC_MODE2_HWWAR2);
2653 
2654 		OS_REG_WRITE(ah, AR_PCU_MISC_MODE2, val);
2655 	}
2656 
2657 	/*
2658 	 * Disable RIFS search on some chips to avoid baseband
2659 	 * hang issues.
2660 	 */
2661 	if (AR_SREV_HOWL(ah) || AR_SREV_SOWL(ah))
2662 		(void) ar5416SetRifsDelay(ah, chan, AH_FALSE);
2663 
2664         if (!AR_SREV_5416_V20_OR_LATER(ah) || AR_SREV_MERLIN(ah))
2665 		return;
2666 
2667 	/*
2668 	 * Disable BB clock gating
2669 	 * Necessary to avoid issues on AR5416 2.0
2670 	 */
2671 	OS_REG_WRITE(ah, 0x9800 + (651 << 2), 0x11);
2672 }
2673 
2674 struct ini {
2675 	uint32_t        *data;          /* NB: !const */
2676 	int             rows, cols;
2677 };
2678 
2679 /*
2680  * Override XPA bias level based on operating frequency.
2681  * This is a v14 EEPROM specific thing for the AR9160.
2682  */
2683 void
2684 ar5416EepromSetAddac(struct ath_hal *ah, const struct ieee80211_channel *chan)
2685 {
2686 #define	XPA_LVL_FREQ(cnt)	(pModal->xpaBiasLvlFreq[cnt])
2687 	MODAL_EEP_HEADER	*pModal;
2688 	HAL_EEPROM_v14 *ee = AH_PRIVATE(ah)->ah_eeprom;
2689 	struct ar5416eeprom	*eep = &ee->ee_base;
2690 	uint8_t biaslevel;
2691 
2692 	if (! AR_SREV_SOWL(ah))
2693 		return;
2694 
2695         if (EEP_MINOR(ah) < AR5416_EEP_MINOR_VER_7)
2696                 return;
2697 
2698 	pModal = &(eep->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)]);
2699 
2700 	if (pModal->xpaBiasLvl != 0xff)
2701 		biaslevel = pModal->xpaBiasLvl;
2702 	else {
2703 		uint16_t resetFreqBin, freqBin, freqCount = 0;
2704 		CHAN_CENTERS centers;
2705 
2706 		ar5416GetChannelCenters(ah, chan, &centers);
2707 
2708 		resetFreqBin = FREQ2FBIN(centers.synth_center, IEEE80211_IS_CHAN_2GHZ(chan));
2709 		freqBin = XPA_LVL_FREQ(0) & 0xff;
2710 		biaslevel = (uint8_t) (XPA_LVL_FREQ(0) >> 14);
2711 
2712 		freqCount++;
2713 
2714 		while (freqCount < 3) {
2715 			if (XPA_LVL_FREQ(freqCount) == 0x0)
2716 			break;
2717 
2718 			freqBin = XPA_LVL_FREQ(freqCount) & 0xff;
2719 			if (resetFreqBin >= freqBin)
2720 				biaslevel = (uint8_t)(XPA_LVL_FREQ(freqCount) >> 14);
2721 			else
2722 				break;
2723 			freqCount++;
2724 		}
2725 	}
2726 
2727 	HALDEBUG(ah, HAL_DEBUG_EEPROM, "%s: overriding XPA bias level = %d\n",
2728 	    __func__, biaslevel);
2729 
2730 	/*
2731 	 * This is a dirty workaround for the const initval data,
2732 	 * which will upset multiple AR9160's on the same board.
2733 	 *
2734 	 * The HAL should likely just have a private copy of the addac
2735 	 * data per instance.
2736 	 */
2737 	if (IEEE80211_IS_CHAN_2GHZ(chan))
2738                 HAL_INI_VAL((struct ini *) &AH5416(ah)->ah_ini_addac, 7, 1) =
2739 		    (HAL_INI_VAL(&AH5416(ah)->ah_ini_addac, 7, 1) & (~0x18)) | biaslevel << 3;
2740         else
2741                 HAL_INI_VAL((struct ini *) &AH5416(ah)->ah_ini_addac, 6, 1) =
2742 		    (HAL_INI_VAL(&AH5416(ah)->ah_ini_addac, 6, 1) & (~0xc0)) | biaslevel << 6;
2743 #undef XPA_LVL_FREQ
2744 }
2745 
2746 static void
2747 ar5416MarkPhyInactive(struct ath_hal *ah)
2748 {
2749 	OS_REG_WRITE(ah, AR_PHY_ACTIVE, AR_PHY_ACTIVE_DIS);
2750 }
2751