xref: /freebsd/sys/dev/ath/ath_hal/ar5416/ar5416_reset.c (revision 3ef51c5fb9163f2aafb1c14729e06a8bf0c4d113)
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 register
1391 			 * and descriptor accesses.
1392 			 */
1393 			mask = INIT_CONFIG_STATUS | AR_CFG_SWRD | AR_CFG_SWRG;
1394 #ifndef AH_NEED_DESC_SWAP
1395 			mask |= AR_CFG_SWTD;
1396 #endif
1397 			HALDEBUG(ah, HAL_DEBUG_RESET,
1398 			    "%s Applying descriptor swap\n", __func__);
1399 			OS_REG_WRITE(ah, AR_CFG, LE_READ_4(&mask));
1400 		} else
1401 			OS_REG_WRITE(ah, AR_CFG, INIT_CONFIG_STATUS);
1402 	}
1403     }
1404 
1405     return AH_TRUE;
1406 }
1407 
1408 void
1409 ar5416InitChainMasks(struct ath_hal *ah)
1410 {
1411 	int rx_chainmask = AH5416(ah)->ah_rx_chainmask;
1412 
1413 	/* Flip this for this chainmask regardless of chip */
1414 	if (rx_chainmask == 0x5)
1415 		OS_REG_SET_BIT(ah, AR_PHY_ANALOG_SWAP, AR_PHY_SWAP_ALT_CHAIN);
1416 
1417 	/*
1418 	 * Workaround for OWL 1.0 calibration failure; enable multi-chain;
1419 	 * then set true mask after calibration.
1420 	 */
1421 	if (IS_5416V1(ah) && (rx_chainmask == 0x5 || rx_chainmask == 0x3)) {
1422 		OS_REG_WRITE(ah, AR_PHY_RX_CHAINMASK, 0x7);
1423 		OS_REG_WRITE(ah, AR_PHY_CAL_CHAINMASK, 0x7);
1424 	} else {
1425 		OS_REG_WRITE(ah, AR_PHY_RX_CHAINMASK, AH5416(ah)->ah_rx_chainmask);
1426 		OS_REG_WRITE(ah, AR_PHY_CAL_CHAINMASK, AH5416(ah)->ah_rx_chainmask);
1427 	}
1428 	OS_REG_WRITE(ah, AR_SELFGEN_MASK, AH5416(ah)->ah_tx_chainmask);
1429 
1430 	if (AH5416(ah)->ah_tx_chainmask == 0x5)
1431 		OS_REG_SET_BIT(ah, AR_PHY_ANALOG_SWAP, AR_PHY_SWAP_ALT_CHAIN);
1432 
1433 	if (AR_SREV_HOWL(ah)) {
1434 		OS_REG_WRITE(ah, AR_PHY_ANALOG_SWAP,
1435 		OS_REG_READ(ah, AR_PHY_ANALOG_SWAP) | 0x00000001);
1436 	}
1437 }
1438 
1439 /*
1440  * Work-around for Owl 1.0 calibration failure.
1441  *
1442  * ar5416InitChainMasks sets the RX chainmask to 0x7 if it's Owl 1.0
1443  * due to init calibration failures. ar5416RestoreChainMask restores
1444  * these registers to the correct setting.
1445  */
1446 void
1447 ar5416RestoreChainMask(struct ath_hal *ah)
1448 {
1449 	int rx_chainmask = AH5416(ah)->ah_rx_chainmask;
1450 
1451 	if (IS_5416V1(ah) && (rx_chainmask == 0x5 || rx_chainmask == 0x3)) {
1452 		OS_REG_WRITE(ah, AR_PHY_RX_CHAINMASK, rx_chainmask);
1453 		OS_REG_WRITE(ah, AR_PHY_CAL_CHAINMASK, rx_chainmask);
1454 	}
1455 }
1456 
1457 /*
1458  * Update the chainmask based on the current channel configuration.
1459  *
1460  * XXX ath9k checks bluetooth co-existence here
1461  * XXX ath9k checks whether the current state is "off-channel".
1462  * XXX ath9k sticks the hardware into 1x1 mode for legacy;
1463  *     we're going to leave multi-RX on for multi-path cancellation.
1464  */
1465 static void
1466 ar5416UpdateChainMasks(struct ath_hal *ah, HAL_BOOL is_ht)
1467 {
1468 	struct ath_hal_private *ahpriv = AH_PRIVATE(ah);
1469 	HAL_CAPABILITIES *pCap = &ahpriv->ah_caps;
1470 
1471 	if (is_ht) {
1472 		AH5416(ah)->ah_tx_chainmask = pCap->halTxChainMask;
1473 	} else {
1474 		AH5416(ah)->ah_tx_chainmask = 1;
1475 	}
1476 	AH5416(ah)->ah_rx_chainmask = pCap->halRxChainMask;
1477 	HALDEBUG(ah, HAL_DEBUG_RESET, "TX chainmask: 0x%x; RX chainmask: 0x%x\n",
1478 	    AH5416(ah)->ah_tx_chainmask,
1479 	    AH5416(ah)->ah_rx_chainmask);
1480 }
1481 
1482 void
1483 ar5416InitPLL(struct ath_hal *ah, const struct ieee80211_channel *chan)
1484 {
1485 	uint32_t pll = AR_RTC_PLL_REFDIV_5 | AR_RTC_PLL_DIV2;
1486 	if (chan != AH_NULL) {
1487 		if (IEEE80211_IS_CHAN_HALF(chan))
1488 			pll |= SM(0x1, AR_RTC_PLL_CLKSEL);
1489 		else if (IEEE80211_IS_CHAN_QUARTER(chan))
1490 			pll |= SM(0x2, AR_RTC_PLL_CLKSEL);
1491 
1492 		if (IEEE80211_IS_CHAN_5GHZ(chan))
1493 			pll |= SM(0xa, AR_RTC_PLL_DIV);
1494 		else
1495 			pll |= SM(0xb, AR_RTC_PLL_DIV);
1496 	} else
1497 		pll |= SM(0xb, AR_RTC_PLL_DIV);
1498 
1499 	OS_REG_WRITE(ah, AR_RTC_PLL_CONTROL, pll);
1500 
1501 	/* TODO:
1502 	* For multi-band owl, switch between bands by reiniting the PLL.
1503 	*/
1504 
1505 	OS_DELAY(RTC_PLL_SETTLE_DELAY);
1506 
1507 	OS_REG_WRITE(ah, AR_RTC_SLEEP_CLK, AR_RTC_SLEEP_DERIVED_CLK);
1508 }
1509 
1510 static void
1511 ar5416SetDefGainValues(struct ath_hal *ah,
1512     const MODAL_EEP_HEADER *pModal,
1513     const struct ar5416eeprom *eep,
1514     uint8_t txRxAttenLocal, int regChainOffset, int i)
1515 {
1516 
1517 	if (IS_EEP_MINOR_V3(ah)) {
1518 		txRxAttenLocal = pModal->txRxAttenCh[i];
1519 
1520 		if (AR_SREV_MERLIN_10_OR_LATER(ah)) {
1521 			OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ + regChainOffset,
1522 			      AR_PHY_GAIN_2GHZ_XATTEN1_MARGIN,
1523 			      pModal->bswMargin[i]);
1524 			OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ + regChainOffset,
1525 			      AR_PHY_GAIN_2GHZ_XATTEN1_DB,
1526 			      pModal->bswAtten[i]);
1527 			OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ + regChainOffset,
1528 			      AR_PHY_GAIN_2GHZ_XATTEN2_MARGIN,
1529 			      pModal->xatten2Margin[i]);
1530 			OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ + regChainOffset,
1531 			      AR_PHY_GAIN_2GHZ_XATTEN2_DB,
1532 			      pModal->xatten2Db[i]);
1533 		} else {
1534 			OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ + regChainOffset,
1535 			      AR_PHY_GAIN_2GHZ_BSW_MARGIN,
1536 			      pModal->bswMargin[i]);
1537 			OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ + regChainOffset,
1538 			      AR_PHY_GAIN_2GHZ_BSW_ATTEN,
1539 			      pModal->bswAtten[i]);
1540 		}
1541 	}
1542 
1543 	if (AR_SREV_MERLIN_10_OR_LATER(ah)) {
1544 		OS_REG_RMW_FIELD(ah,
1545 		      AR_PHY_RXGAIN + regChainOffset,
1546 		      AR9280_PHY_RXGAIN_TXRX_ATTEN, txRxAttenLocal);
1547 		OS_REG_RMW_FIELD(ah,
1548 		      AR_PHY_RXGAIN + regChainOffset,
1549 		      AR9280_PHY_RXGAIN_TXRX_MARGIN, pModal->rxTxMarginCh[i]);
1550 	} else {
1551 		OS_REG_RMW_FIELD(ah,
1552 			  AR_PHY_RXGAIN + regChainOffset,
1553 			  AR_PHY_RXGAIN_TXRX_ATTEN, txRxAttenLocal);
1554 		OS_REG_RMW_FIELD(ah,
1555 			  AR_PHY_GAIN_2GHZ + regChainOffset,
1556 			  AR_PHY_GAIN_2GHZ_RXTX_MARGIN, pModal->rxTxMarginCh[i]);
1557 	}
1558 }
1559 
1560 /*
1561  * Get the register chain offset for the given chain.
1562  *
1563  * Take into account the register chain swapping with AR5416 v2.0.
1564  *
1565  * XXX make sure that the reg chain swapping is only done for
1566  * XXX AR5416 v2.0 or greater, and not later chips?
1567  */
1568 int
1569 ar5416GetRegChainOffset(struct ath_hal *ah, int i)
1570 {
1571 	int regChainOffset;
1572 
1573 	if (AR_SREV_5416_V20_OR_LATER(ah) &&
1574 	    (AH5416(ah)->ah_rx_chainmask == 0x5 ||
1575 	    AH5416(ah)->ah_tx_chainmask == 0x5) && (i != 0)) {
1576 		/* Regs are swapped from chain 2 to 1 for 5416 2_0 with
1577 		 * only chains 0 and 2 populated
1578 		 */
1579 		regChainOffset = (i == 1) ? 0x2000 : 0x1000;
1580 	} else {
1581 		regChainOffset = i * 0x1000;
1582 	}
1583 
1584 	return regChainOffset;
1585 }
1586 
1587 /*
1588  * Read EEPROM header info and program the device for correct operation
1589  * given the channel value.
1590  */
1591 HAL_BOOL
1592 ar5416SetBoardValues(struct ath_hal *ah, const struct ieee80211_channel *chan)
1593 {
1594     const HAL_EEPROM_v14 *ee = AH_PRIVATE(ah)->ah_eeprom;
1595     const struct ar5416eeprom *eep = &ee->ee_base;
1596     const MODAL_EEP_HEADER *pModal;
1597     int			i, regChainOffset;
1598     uint8_t		txRxAttenLocal;    /* workaround for eeprom versions <= 14.2 */
1599 
1600     HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER14_1);
1601     pModal = &eep->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)];
1602 
1603     /* NB: workaround for eeprom versions <= 14.2 */
1604     txRxAttenLocal = IEEE80211_IS_CHAN_2GHZ(chan) ? 23 : 44;
1605 
1606     OS_REG_WRITE(ah, AR_PHY_SWITCH_COM, pModal->antCtrlCommon);
1607     for (i = 0; i < AR5416_MAX_CHAINS; i++) {
1608 	   if (AR_SREV_MERLIN(ah)) {
1609 		if (i >= 2) break;
1610 	   }
1611 	regChainOffset = ar5416GetRegChainOffset(ah, i);
1612 
1613         OS_REG_WRITE(ah, AR_PHY_SWITCH_CHAIN_0 + regChainOffset, pModal->antCtrlChain[i]);
1614 
1615         OS_REG_WRITE(ah, AR_PHY_TIMING_CTRL4 + regChainOffset,
1616         	(OS_REG_READ(ah, AR_PHY_TIMING_CTRL4 + regChainOffset) &
1617         	~(AR_PHY_TIMING_CTRL4_IQCORR_Q_Q_COFF | AR_PHY_TIMING_CTRL4_IQCORR_Q_I_COFF)) |
1618         	SM(pModal->iqCalICh[i], AR_PHY_TIMING_CTRL4_IQCORR_Q_I_COFF) |
1619         	SM(pModal->iqCalQCh[i], AR_PHY_TIMING_CTRL4_IQCORR_Q_Q_COFF));
1620 
1621         /*
1622          * Large signal upgrade,
1623 	 * If 14.3 or later EEPROM, use
1624 	 * txRxAttenLocal = pModal->txRxAttenCh[i]
1625 	 * else txRxAttenLocal is fixed value above.
1626          */
1627 
1628         if ((i == 0) || AR_SREV_5416_V20_OR_LATER(ah))
1629 	    ar5416SetDefGainValues(ah, pModal, eep, txRxAttenLocal, regChainOffset, i);
1630 
1631     }
1632 
1633 	if (AR_SREV_MERLIN_10_OR_LATER(ah)) {
1634                 if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1635                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF2G1_CH0, AR_AN_RF2G1_CH0_OB, pModal->ob);
1636                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF2G1_CH0, AR_AN_RF2G1_CH0_DB, pModal->db);
1637                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF2G1_CH1, AR_AN_RF2G1_CH1_OB, pModal->ob_ch1);
1638                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF2G1_CH1, AR_AN_RF2G1_CH1_DB, pModal->db_ch1);
1639                 } else {
1640                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF5G1_CH0, AR_AN_RF5G1_CH0_OB5, pModal->ob);
1641                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF5G1_CH0, AR_AN_RF5G1_CH0_DB5, pModal->db);
1642                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF5G1_CH1, AR_AN_RF5G1_CH1_OB5, pModal->ob_ch1);
1643                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF5G1_CH1, AR_AN_RF5G1_CH1_DB5, pModal->db_ch1);
1644                 }
1645                 OS_A_REG_RMW_FIELD(ah, AR_AN_TOP2, AR_AN_TOP2_XPABIAS_LVL, pModal->xpaBiasLvl);
1646                 OS_A_REG_RMW_FIELD(ah, AR_AN_TOP2, AR_AN_TOP2_LOCALBIAS,
1647 		    !!(pModal->flagBits & AR5416_EEP_FLAG_LOCALBIAS));
1648                 OS_A_REG_RMW_FIELD(ah, AR_PHY_XPA_CFG, AR_PHY_FORCE_XPA_CFG,
1649 		    !!(pModal->flagBits & AR5416_EEP_FLAG_FORCEXPAON));
1650         }
1651 
1652     OS_REG_RMW_FIELD(ah, AR_PHY_SETTLING, AR_PHY_SETTLING_SWITCH, pModal->switchSettling);
1653     OS_REG_RMW_FIELD(ah, AR_PHY_DESIRED_SZ, AR_PHY_DESIRED_SZ_ADC, pModal->adcDesiredSize);
1654 
1655     if (! AR_SREV_MERLIN_10_OR_LATER(ah))
1656     	OS_REG_RMW_FIELD(ah, AR_PHY_DESIRED_SZ, AR_PHY_DESIRED_SZ_PGA, pModal->pgaDesiredSize);
1657 
1658     OS_REG_WRITE(ah, AR_PHY_RF_CTL4,
1659         SM(pModal->txEndToXpaOff, AR_PHY_RF_CTL4_TX_END_XPAA_OFF)
1660         | SM(pModal->txEndToXpaOff, AR_PHY_RF_CTL4_TX_END_XPAB_OFF)
1661         | SM(pModal->txFrameToXpaOn, AR_PHY_RF_CTL4_FRAME_XPAA_ON)
1662         | SM(pModal->txFrameToXpaOn, AR_PHY_RF_CTL4_FRAME_XPAB_ON));
1663 
1664     OS_REG_RMW_FIELD(ah, AR_PHY_RF_CTL3, AR_PHY_TX_END_TO_A2_RX_ON,
1665 	pModal->txEndToRxOn);
1666 
1667     if (AR_SREV_MERLIN_10_OR_LATER(ah)) {
1668 	OS_REG_RMW_FIELD(ah, AR_PHY_CCA, AR9280_PHY_CCA_THRESH62,
1669 	    pModal->thresh62);
1670 	OS_REG_RMW_FIELD(ah, AR_PHY_EXT_CCA0, AR_PHY_EXT_CCA0_THRESH62,
1671 	    pModal->thresh62);
1672     } else {
1673 	OS_REG_RMW_FIELD(ah, AR_PHY_CCA, AR_PHY_CCA_THRESH62,
1674 	    pModal->thresh62);
1675 	OS_REG_RMW_FIELD(ah, AR_PHY_EXT_CCA, AR_PHY_EXT_CCA_THRESH62,
1676 	    pModal->thresh62);
1677     }
1678 
1679     /* Minor Version Specific application */
1680     if (IS_EEP_MINOR_V2(ah)) {
1681         OS_REG_RMW_FIELD(ah, AR_PHY_RF_CTL2, AR_PHY_TX_FRAME_TO_DATA_START,
1682 	    pModal->txFrameToDataStart);
1683         OS_REG_RMW_FIELD(ah, AR_PHY_RF_CTL2, AR_PHY_TX_FRAME_TO_PA_ON,
1684 	    pModal->txFrameToPaOn);
1685     }
1686 
1687     if (IS_EEP_MINOR_V3(ah) && IEEE80211_IS_CHAN_HT40(chan))
1688 		/* Overwrite switch settling with HT40 value */
1689 		OS_REG_RMW_FIELD(ah, AR_PHY_SETTLING, AR_PHY_SETTLING_SWITCH,
1690 		    pModal->swSettleHt40);
1691 
1692     if (AR_SREV_MERLIN_20_OR_LATER(ah) && EEP_MINOR(ah) >= AR5416_EEP_MINOR_VER_19)
1693          OS_REG_RMW_FIELD(ah, AR_PHY_CCK_TX_CTRL, AR_PHY_CCK_TX_CTRL_TX_DAC_SCALE_CCK, pModal->miscBits);
1694 
1695         if (AR_SREV_MERLIN_20(ah) && EEP_MINOR(ah) >= AR5416_EEP_MINOR_VER_20) {
1696                 if (IEEE80211_IS_CHAN_2GHZ(chan))
1697                         OS_A_REG_RMW_FIELD(ah, AR_AN_TOP1, AR_AN_TOP1_DACIPMODE,
1698 			    eep->baseEepHeader.dacLpMode);
1699                 else if (eep->baseEepHeader.dacHiPwrMode_5G)
1700                         OS_A_REG_RMW_FIELD(ah, AR_AN_TOP1, AR_AN_TOP1_DACIPMODE, 0);
1701                 else
1702                         OS_A_REG_RMW_FIELD(ah, AR_AN_TOP1, AR_AN_TOP1_DACIPMODE,
1703 			    eep->baseEepHeader.dacLpMode);
1704 
1705 		OS_DELAY(100);
1706 
1707                 OS_REG_RMW_FIELD(ah, AR_PHY_FRAME_CTL, AR_PHY_FRAME_CTL_TX_CLIP,
1708 		    pModal->miscBits >> 2);
1709                 OS_REG_RMW_FIELD(ah, AR_PHY_TX_PWRCTRL9, AR_PHY_TX_DESIRED_SCALE_CCK,
1710 		    eep->baseEepHeader.desiredScaleCCK);
1711         }
1712 
1713     return (AH_TRUE);
1714 }
1715 
1716 /*
1717  * Helper functions common for AP/CB/XB
1718  */
1719 
1720 /*
1721  * Set the target power array "ratesArray" from the
1722  * given set of target powers.
1723  *
1724  * This is used by the various chipset/EEPROM TX power
1725  * setup routines.
1726  */
1727 void
1728 ar5416SetRatesArrayFromTargetPower(struct ath_hal *ah,
1729     const struct ieee80211_channel *chan,
1730     int16_t *ratesArray,
1731     const CAL_TARGET_POWER_LEG *targetPowerCck,
1732     const CAL_TARGET_POWER_LEG *targetPowerCckExt,
1733     const CAL_TARGET_POWER_LEG *targetPowerOfdm,
1734     const CAL_TARGET_POWER_LEG *targetPowerOfdmExt,
1735     const CAL_TARGET_POWER_HT *targetPowerHt20,
1736     const CAL_TARGET_POWER_HT *targetPowerHt40)
1737 {
1738 #define	N(a)	(sizeof(a)/sizeof(a[0]))
1739 	int i;
1740 
1741 	/* Blank the rates array, to be consistent */
1742 	for (i = 0; i < Ar5416RateSize; i++)
1743 		ratesArray[i] = 0;
1744 
1745 	/* Set rates Array from collected data */
1746 	ratesArray[rate6mb] = ratesArray[rate9mb] = ratesArray[rate12mb] =
1747 	ratesArray[rate18mb] = ratesArray[rate24mb] =
1748 	    targetPowerOfdm->tPow2x[0];
1749 	ratesArray[rate36mb] = targetPowerOfdm->tPow2x[1];
1750 	ratesArray[rate48mb] = targetPowerOfdm->tPow2x[2];
1751 	ratesArray[rate54mb] = targetPowerOfdm->tPow2x[3];
1752 	ratesArray[rateXr] = targetPowerOfdm->tPow2x[0];
1753 
1754 	for (i = 0; i < N(targetPowerHt20->tPow2x); i++) {
1755 		ratesArray[rateHt20_0 + i] = targetPowerHt20->tPow2x[i];
1756 	}
1757 
1758 	if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1759 		ratesArray[rate1l]  = targetPowerCck->tPow2x[0];
1760 		ratesArray[rate2s] = ratesArray[rate2l]  = targetPowerCck->tPow2x[1];
1761 		ratesArray[rate5_5s] = ratesArray[rate5_5l] = targetPowerCck->tPow2x[2];
1762 		ratesArray[rate11s] = ratesArray[rate11l] = targetPowerCck->tPow2x[3];
1763 	}
1764 	if (IEEE80211_IS_CHAN_HT40(chan)) {
1765 		for (i = 0; i < N(targetPowerHt40->tPow2x); i++) {
1766 			ratesArray[rateHt40_0 + i] = targetPowerHt40->tPow2x[i];
1767 		}
1768 		ratesArray[rateDupOfdm] = targetPowerHt40->tPow2x[0];
1769 		ratesArray[rateDupCck]  = targetPowerHt40->tPow2x[0];
1770 		ratesArray[rateExtOfdm] = targetPowerOfdmExt->tPow2x[0];
1771 		if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1772 			ratesArray[rateExtCck]  = targetPowerCckExt->tPow2x[0];
1773 		}
1774 	}
1775 #undef	N
1776 }
1777 
1778 /*
1779  * ar5416SetPowerPerRateTable
1780  *
1781  * Sets the transmit power in the baseband for the given
1782  * operating channel and mode.
1783  */
1784 static HAL_BOOL
1785 ar5416SetPowerPerRateTable(struct ath_hal *ah, struct ar5416eeprom *pEepData,
1786                            const struct ieee80211_channel *chan,
1787                            int16_t *ratesArray, uint16_t cfgCtl,
1788                            uint16_t AntennaReduction,
1789                            uint16_t twiceMaxRegulatoryPower,
1790                            uint16_t powerLimit)
1791 {
1792 #define	N(a)	(sizeof(a)/sizeof(a[0]))
1793 /* Local defines to distinguish between extension and control CTL's */
1794 #define EXT_ADDITIVE (0x8000)
1795 #define CTL_11A_EXT (CTL_11A | EXT_ADDITIVE)
1796 #define CTL_11G_EXT (CTL_11G | EXT_ADDITIVE)
1797 #define CTL_11B_EXT (CTL_11B | EXT_ADDITIVE)
1798 
1799 	uint16_t twiceMaxEdgePower = AR5416_MAX_RATE_POWER;
1800 	int i;
1801 	int16_t  twiceLargestAntenna;
1802 	CAL_CTL_DATA *rep;
1803 	CAL_TARGET_POWER_LEG targetPowerOfdm, targetPowerCck = {0, {0, 0, 0, 0}};
1804 	CAL_TARGET_POWER_LEG targetPowerOfdmExt = {0, {0, 0, 0, 0}}, targetPowerCckExt = {0, {0, 0, 0, 0}};
1805 	CAL_TARGET_POWER_HT  targetPowerHt20, targetPowerHt40 = {0, {0, 0, 0, 0}};
1806 	int16_t scaledPower, minCtlPower;
1807 
1808 #define SUB_NUM_CTL_MODES_AT_5G_40 2   /* excluding HT40, EXT-OFDM */
1809 #define SUB_NUM_CTL_MODES_AT_2G_40 3   /* excluding HT40, EXT-OFDM, EXT-CCK */
1810 	static const uint16_t ctlModesFor11a[] = {
1811 	   CTL_11A, CTL_5GHT20, CTL_11A_EXT, CTL_5GHT40
1812 	};
1813 	static const uint16_t ctlModesFor11g[] = {
1814 	   CTL_11B, CTL_11G, CTL_2GHT20, CTL_11B_EXT, CTL_11G_EXT, CTL_2GHT40
1815 	};
1816 	const uint16_t *pCtlMode;
1817 	uint16_t numCtlModes, ctlMode, freq;
1818 	CHAN_CENTERS centers;
1819 
1820 	ar5416GetChannelCenters(ah,  chan, &centers);
1821 
1822 	/* Compute TxPower reduction due to Antenna Gain */
1823 
1824 	twiceLargestAntenna = AH_MAX(AH_MAX(
1825 	    pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[0],
1826 	    pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[1]),
1827 	    pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[2]);
1828 #if 0
1829 	/* Turn it back on if we need to calculate per chain antenna gain reduction */
1830 	/* Use only if the expected gain > 6dbi */
1831 	/* Chain 0 is always used */
1832 	twiceLargestAntenna = pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[0];
1833 
1834 	/* Look at antenna gains of Chains 1 and 2 if the TX mask is set */
1835 	if (ahp->ah_tx_chainmask & 0x2)
1836 		twiceLargestAntenna = AH_MAX(twiceLargestAntenna,
1837 			pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[1]);
1838 
1839 	if (ahp->ah_tx_chainmask & 0x4)
1840 		twiceLargestAntenna = AH_MAX(twiceLargestAntenna,
1841 			pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[2]);
1842 #endif
1843 	twiceLargestAntenna = (int16_t)AH_MIN((AntennaReduction) - twiceLargestAntenna, 0);
1844 
1845 	/* XXX setup for 5212 use (really used?) */
1846 	ath_hal_eepromSet(ah,
1847 	    IEEE80211_IS_CHAN_2GHZ(chan) ? AR_EEP_ANTGAINMAX_2 : AR_EEP_ANTGAINMAX_5,
1848 	    twiceLargestAntenna);
1849 
1850 	/*
1851 	 * scaledPower is the minimum of the user input power level and
1852 	 * the regulatory allowed power level
1853 	 */
1854 	scaledPower = AH_MIN(powerLimit, twiceMaxRegulatoryPower + twiceLargestAntenna);
1855 
1856 	/* Reduce scaled Power by number of chains active to get to per chain tx power level */
1857 	/* TODO: better value than these? */
1858 	switch (owl_get_ntxchains(AH5416(ah)->ah_tx_chainmask)) {
1859 	case 1:
1860 		break;
1861 	case 2:
1862 		scaledPower -= pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].pwrDecreaseFor2Chain;
1863 		break;
1864 	case 3:
1865 		scaledPower -= pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].pwrDecreaseFor3Chain;
1866 		break;
1867 	default:
1868 		return AH_FALSE; /* Unsupported number of chains */
1869 	}
1870 
1871 	scaledPower = AH_MAX(0, scaledPower);
1872 
1873 	/* Get target powers from EEPROM - our baseline for TX Power */
1874 	if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1875 		/* Setup for CTL modes */
1876 		numCtlModes = N(ctlModesFor11g) - SUB_NUM_CTL_MODES_AT_2G_40; /* CTL_11B, CTL_11G, CTL_2GHT20 */
1877 		pCtlMode = ctlModesFor11g;
1878 
1879 		ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPowerCck,
1880 				AR5416_NUM_2G_CCK_TARGET_POWERS, &targetPowerCck, 4, AH_FALSE);
1881 		ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPower2G,
1882 				AR5416_NUM_2G_20_TARGET_POWERS, &targetPowerOfdm, 4, AH_FALSE);
1883 		ar5416GetTargetPowers(ah,  chan, pEepData->calTargetPower2GHT20,
1884 				AR5416_NUM_2G_20_TARGET_POWERS, &targetPowerHt20, 8, AH_FALSE);
1885 
1886 		if (IEEE80211_IS_CHAN_HT40(chan)) {
1887 			numCtlModes = N(ctlModesFor11g);    /* All 2G CTL's */
1888 
1889 			ar5416GetTargetPowers(ah,  chan, pEepData->calTargetPower2GHT40,
1890 				AR5416_NUM_2G_40_TARGET_POWERS, &targetPowerHt40, 8, AH_TRUE);
1891 			/* Get target powers for extension channels */
1892 			ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPowerCck,
1893 				AR5416_NUM_2G_CCK_TARGET_POWERS, &targetPowerCckExt, 4, AH_TRUE);
1894 			ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPower2G,
1895 				AR5416_NUM_2G_20_TARGET_POWERS, &targetPowerOfdmExt, 4, AH_TRUE);
1896 		}
1897 	} else {
1898 		/* Setup for CTL modes */
1899 		numCtlModes = N(ctlModesFor11a) - SUB_NUM_CTL_MODES_AT_5G_40; /* CTL_11A, CTL_5GHT20 */
1900 		pCtlMode = ctlModesFor11a;
1901 
1902 		ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPower5G,
1903 				AR5416_NUM_5G_20_TARGET_POWERS, &targetPowerOfdm, 4, AH_FALSE);
1904 		ar5416GetTargetPowers(ah,  chan, pEepData->calTargetPower5GHT20,
1905 				AR5416_NUM_5G_20_TARGET_POWERS, &targetPowerHt20, 8, AH_FALSE);
1906 
1907 		if (IEEE80211_IS_CHAN_HT40(chan)) {
1908 			numCtlModes = N(ctlModesFor11a); /* All 5G CTL's */
1909 
1910 			ar5416GetTargetPowers(ah,  chan, pEepData->calTargetPower5GHT40,
1911 				AR5416_NUM_5G_40_TARGET_POWERS, &targetPowerHt40, 8, AH_TRUE);
1912 			ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPower5G,
1913 				AR5416_NUM_5G_20_TARGET_POWERS, &targetPowerOfdmExt, 4, AH_TRUE);
1914 		}
1915 	}
1916 
1917 	/*
1918 	 * For MIMO, need to apply regulatory caps individually across dynamically
1919 	 * running modes: CCK, OFDM, HT20, HT40
1920 	 *
1921 	 * The outer loop walks through each possible applicable runtime mode.
1922 	 * The inner loop walks through each ctlIndex entry in EEPROM.
1923 	 * The ctl value is encoded as [7:4] == test group, [3:0] == test mode.
1924 	 *
1925 	 */
1926 	for (ctlMode = 0; ctlMode < numCtlModes; ctlMode++) {
1927 		HAL_BOOL isHt40CtlMode = (pCtlMode[ctlMode] == CTL_5GHT40) ||
1928 		    (pCtlMode[ctlMode] == CTL_2GHT40);
1929 		if (isHt40CtlMode) {
1930 			freq = centers.ctl_center;
1931 		} else if (pCtlMode[ctlMode] & EXT_ADDITIVE) {
1932 			freq = centers.ext_center;
1933 		} else {
1934 			freq = centers.ctl_center;
1935 		}
1936 
1937 		/* walk through each CTL index stored in EEPROM */
1938 		for (i = 0; (i < AR5416_NUM_CTLS) && pEepData->ctlIndex[i]; i++) {
1939 			uint16_t twiceMinEdgePower;
1940 
1941 			/* compare test group from regulatory channel list with test mode from pCtlMode list */
1942 			if ((((cfgCtl & ~CTL_MODE_M) | (pCtlMode[ctlMode] & CTL_MODE_M)) == pEepData->ctlIndex[i]) ||
1943 				(((cfgCtl & ~CTL_MODE_M) | (pCtlMode[ctlMode] & CTL_MODE_M)) ==
1944 				 ((pEepData->ctlIndex[i] & CTL_MODE_M) | SD_NO_CTL))) {
1945 				rep = &(pEepData->ctlData[i]);
1946 				twiceMinEdgePower = ar5416GetMaxEdgePower(freq,
1947 							rep->ctlEdges[owl_get_ntxchains(AH5416(ah)->ah_tx_chainmask) - 1],
1948 							IEEE80211_IS_CHAN_2GHZ(chan));
1949 				if ((cfgCtl & ~CTL_MODE_M) == SD_NO_CTL) {
1950 					/* Find the minimum of all CTL edge powers that apply to this channel */
1951 					twiceMaxEdgePower = AH_MIN(twiceMaxEdgePower, twiceMinEdgePower);
1952 				} else {
1953 					/* specific */
1954 					twiceMaxEdgePower = twiceMinEdgePower;
1955 					break;
1956 				}
1957 			}
1958 		}
1959 		minCtlPower = (uint8_t)AH_MIN(twiceMaxEdgePower, scaledPower);
1960 		/* Apply ctl mode to correct target power set */
1961 		switch(pCtlMode[ctlMode]) {
1962 		case CTL_11B:
1963 			for (i = 0; i < N(targetPowerCck.tPow2x); i++) {
1964 				targetPowerCck.tPow2x[i] = (uint8_t)AH_MIN(targetPowerCck.tPow2x[i], minCtlPower);
1965 			}
1966 			break;
1967 		case CTL_11A:
1968 		case CTL_11G:
1969 			for (i = 0; i < N(targetPowerOfdm.tPow2x); i++) {
1970 				targetPowerOfdm.tPow2x[i] = (uint8_t)AH_MIN(targetPowerOfdm.tPow2x[i], minCtlPower);
1971 			}
1972 			break;
1973 		case CTL_5GHT20:
1974 		case CTL_2GHT20:
1975 			for (i = 0; i < N(targetPowerHt20.tPow2x); i++) {
1976 				targetPowerHt20.tPow2x[i] = (uint8_t)AH_MIN(targetPowerHt20.tPow2x[i], minCtlPower);
1977 			}
1978 			break;
1979 		case CTL_11B_EXT:
1980 			targetPowerCckExt.tPow2x[0] = (uint8_t)AH_MIN(targetPowerCckExt.tPow2x[0], minCtlPower);
1981 			break;
1982 		case CTL_11A_EXT:
1983 		case CTL_11G_EXT:
1984 			targetPowerOfdmExt.tPow2x[0] = (uint8_t)AH_MIN(targetPowerOfdmExt.tPow2x[0], minCtlPower);
1985 			break;
1986 		case CTL_5GHT40:
1987 		case CTL_2GHT40:
1988 			for (i = 0; i < N(targetPowerHt40.tPow2x); i++) {
1989 				targetPowerHt40.tPow2x[i] = (uint8_t)AH_MIN(targetPowerHt40.tPow2x[i], minCtlPower);
1990 			}
1991 			break;
1992 		default:
1993 			return AH_FALSE;
1994 			break;
1995 		}
1996 	} /* end ctl mode checking */
1997 
1998 	/* Set rates Array from collected data */
1999 	ar5416SetRatesArrayFromTargetPower(ah, chan, ratesArray,
2000 	    &targetPowerCck,
2001 	    &targetPowerCckExt,
2002 	    &targetPowerOfdm,
2003 	    &targetPowerOfdmExt,
2004 	    &targetPowerHt20,
2005 	    &targetPowerHt40);
2006 	return AH_TRUE;
2007 #undef EXT_ADDITIVE
2008 #undef CTL_11A_EXT
2009 #undef CTL_11G_EXT
2010 #undef CTL_11B_EXT
2011 #undef SUB_NUM_CTL_MODES_AT_5G_40
2012 #undef SUB_NUM_CTL_MODES_AT_2G_40
2013 #undef N
2014 }
2015 
2016 /**************************************************************************
2017  * fbin2freq
2018  *
2019  * Get channel value from binary representation held in eeprom
2020  * RETURNS: the frequency in MHz
2021  */
2022 static uint16_t
2023 fbin2freq(uint8_t fbin, HAL_BOOL is2GHz)
2024 {
2025     /*
2026      * Reserved value 0xFF provides an empty definition both as
2027      * an fbin and as a frequency - do not convert
2028      */
2029     if (fbin == AR5416_BCHAN_UNUSED) {
2030         return fbin;
2031     }
2032 
2033     return (uint16_t)((is2GHz) ? (2300 + fbin) : (4800 + 5 * fbin));
2034 }
2035 
2036 /*
2037  * ar5416GetMaxEdgePower
2038  *
2039  * Find the maximum conformance test limit for the given channel and CTL info
2040  */
2041 uint16_t
2042 ar5416GetMaxEdgePower(uint16_t freq, CAL_CTL_EDGES *pRdEdgesPower, HAL_BOOL is2GHz)
2043 {
2044     uint16_t twiceMaxEdgePower = AR5416_MAX_RATE_POWER;
2045     int      i;
2046 
2047     /* Get the edge power */
2048     for (i = 0; (i < AR5416_NUM_BAND_EDGES) && (pRdEdgesPower[i].bChannel != AR5416_BCHAN_UNUSED) ; i++) {
2049         /*
2050          * If there's an exact channel match or an inband flag set
2051          * on the lower channel use the given rdEdgePower
2052          */
2053         if (freq == fbin2freq(pRdEdgesPower[i].bChannel, is2GHz)) {
2054             twiceMaxEdgePower = MS(pRdEdgesPower[i].tPowerFlag, CAL_CTL_EDGES_POWER);
2055             break;
2056         } else if ((i > 0) && (freq < fbin2freq(pRdEdgesPower[i].bChannel, is2GHz))) {
2057             if (fbin2freq(pRdEdgesPower[i - 1].bChannel, is2GHz) < freq && (pRdEdgesPower[i - 1].tPowerFlag & CAL_CTL_EDGES_FLAG) != 0) {
2058                 twiceMaxEdgePower = MS(pRdEdgesPower[i - 1].tPowerFlag, CAL_CTL_EDGES_POWER);
2059             }
2060             /* Leave loop - no more affecting edges possible in this monotonic increasing list */
2061             break;
2062         }
2063     }
2064     HALASSERT(twiceMaxEdgePower > 0);
2065     return twiceMaxEdgePower;
2066 }
2067 
2068 /**************************************************************
2069  * ar5416GetTargetPowers
2070  *
2071  * Return the rates of target power for the given target power table
2072  * channel, and number of channels
2073  */
2074 void
2075 ar5416GetTargetPowers(struct ath_hal *ah,  const struct ieee80211_channel *chan,
2076                       CAL_TARGET_POWER_HT *powInfo, uint16_t numChannels,
2077                       CAL_TARGET_POWER_HT *pNewPower, uint16_t numRates,
2078                       HAL_BOOL isHt40Target)
2079 {
2080     uint16_t clo, chi;
2081     int i;
2082     int matchIndex = -1, lowIndex = -1;
2083     uint16_t freq;
2084     CHAN_CENTERS centers;
2085 
2086     ar5416GetChannelCenters(ah,  chan, &centers);
2087     freq = isHt40Target ? centers.synth_center : centers.ctl_center;
2088 
2089     /* Copy the target powers into the temp channel list */
2090     if (freq <= fbin2freq(powInfo[0].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) {
2091         matchIndex = 0;
2092     } else {
2093         for (i = 0; (i < numChannels) && (powInfo[i].bChannel != AR5416_BCHAN_UNUSED); i++) {
2094             if (freq == fbin2freq(powInfo[i].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) {
2095                 matchIndex = i;
2096                 break;
2097             } else if ((freq < fbin2freq(powInfo[i].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) &&
2098                        (freq > fbin2freq(powInfo[i - 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))))
2099             {
2100                 lowIndex = i - 1;
2101                 break;
2102             }
2103         }
2104         if ((matchIndex == -1) && (lowIndex == -1)) {
2105             HALASSERT(freq > fbin2freq(powInfo[i - 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan)));
2106             matchIndex = i - 1;
2107         }
2108     }
2109 
2110     if (matchIndex != -1) {
2111         OS_MEMCPY(pNewPower, &powInfo[matchIndex], sizeof(*pNewPower));
2112     } else {
2113         HALASSERT(lowIndex != -1);
2114         /*
2115          * Get the lower and upper channels, target powers,
2116          * and interpolate between them.
2117          */
2118         clo = fbin2freq(powInfo[lowIndex].bChannel, IEEE80211_IS_CHAN_2GHZ(chan));
2119         chi = fbin2freq(powInfo[lowIndex + 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan));
2120 
2121         for (i = 0; i < numRates; i++) {
2122             pNewPower->tPow2x[i] = (uint8_t)ath_ee_interpolate(freq, clo, chi,
2123                                    powInfo[lowIndex].tPow2x[i], powInfo[lowIndex + 1].tPow2x[i]);
2124         }
2125     }
2126 }
2127 /**************************************************************
2128  * ar5416GetTargetPowersLeg
2129  *
2130  * Return the four rates of target power for the given target power table
2131  * channel, and number of channels
2132  */
2133 void
2134 ar5416GetTargetPowersLeg(struct ath_hal *ah,
2135                          const struct ieee80211_channel *chan,
2136                          CAL_TARGET_POWER_LEG *powInfo, uint16_t numChannels,
2137                          CAL_TARGET_POWER_LEG *pNewPower, uint16_t numRates,
2138 			 HAL_BOOL isExtTarget)
2139 {
2140     uint16_t clo, chi;
2141     int i;
2142     int matchIndex = -1, lowIndex = -1;
2143     uint16_t freq;
2144     CHAN_CENTERS centers;
2145 
2146     ar5416GetChannelCenters(ah,  chan, &centers);
2147     freq = (isExtTarget) ? centers.ext_center :centers.ctl_center;
2148 
2149     /* Copy the target powers into the temp channel list */
2150     if (freq <= fbin2freq(powInfo[0].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) {
2151         matchIndex = 0;
2152     } else {
2153         for (i = 0; (i < numChannels) && (powInfo[i].bChannel != AR5416_BCHAN_UNUSED); i++) {
2154             if (freq == fbin2freq(powInfo[i].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) {
2155                 matchIndex = i;
2156                 break;
2157             } else if ((freq < fbin2freq(powInfo[i].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) &&
2158                        (freq > fbin2freq(powInfo[i - 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))))
2159             {
2160                 lowIndex = i - 1;
2161                 break;
2162             }
2163         }
2164         if ((matchIndex == -1) && (lowIndex == -1)) {
2165             HALASSERT(freq > fbin2freq(powInfo[i - 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan)));
2166             matchIndex = i - 1;
2167         }
2168     }
2169 
2170     if (matchIndex != -1) {
2171         OS_MEMCPY(pNewPower, &powInfo[matchIndex], sizeof(*pNewPower));
2172     } else {
2173         HALASSERT(lowIndex != -1);
2174         /*
2175          * Get the lower and upper channels, target powers,
2176          * and interpolate between them.
2177          */
2178         clo = fbin2freq(powInfo[lowIndex].bChannel, IEEE80211_IS_CHAN_2GHZ(chan));
2179         chi = fbin2freq(powInfo[lowIndex + 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan));
2180 
2181         for (i = 0; i < numRates; i++) {
2182             pNewPower->tPow2x[i] = (uint8_t)ath_ee_interpolate(freq, clo, chi,
2183                                    powInfo[lowIndex].tPow2x[i], powInfo[lowIndex + 1].tPow2x[i]);
2184         }
2185     }
2186 }
2187 
2188 /*
2189  * Set the gain boundaries for the given radio chain.
2190  *
2191  * The gain boundaries tell the hardware at what point in the
2192  * PDADC array to "switch over" from one PD gain setting
2193  * to another. There's also a gain overlap between two
2194  * PDADC array gain curves where there's valid PD values
2195  * for 2 gain settings.
2196  *
2197  * The hardware uses the gain overlap and gain boundaries
2198  * to determine which gain curve to use for the given
2199  * target TX power.
2200  */
2201 void
2202 ar5416SetGainBoundariesClosedLoop(struct ath_hal *ah, int i,
2203     uint16_t pdGainOverlap_t2, uint16_t gainBoundaries[])
2204 {
2205 	int regChainOffset;
2206 
2207 	regChainOffset = ar5416GetRegChainOffset(ah, i);
2208 
2209 	HALDEBUG(ah, HAL_DEBUG_EEPROM, "%s: chain %d: gainOverlap_t2: %d,"
2210 	    " gainBoundaries: %d, %d, %d, %d\n", __func__, i, pdGainOverlap_t2,
2211 	    gainBoundaries[0], gainBoundaries[1], gainBoundaries[2],
2212 	    gainBoundaries[3]);
2213 	OS_REG_WRITE(ah, AR_PHY_TPCRG5 + regChainOffset,
2214 	    SM(pdGainOverlap_t2, AR_PHY_TPCRG5_PD_GAIN_OVERLAP) |
2215 	    SM(gainBoundaries[0], AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_1)  |
2216 	    SM(gainBoundaries[1], AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_2)  |
2217 	    SM(gainBoundaries[2], AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_3)  |
2218 	    SM(gainBoundaries[3], AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_4));
2219 }
2220 
2221 /*
2222  * Get the gain values and the number of gain levels given
2223  * in xpdMask.
2224  *
2225  * The EEPROM xpdMask determines which power detector gain
2226  * levels were used during calibration. Each of these mask
2227  * bits maps to a fixed gain level in hardware.
2228  */
2229 uint16_t
2230 ar5416GetXpdGainValues(struct ath_hal *ah, uint16_t xpdMask,
2231     uint16_t xpdGainValues[])
2232 {
2233     int i;
2234     uint16_t numXpdGain = 0;
2235 
2236     for (i = 1; i <= AR5416_PD_GAINS_IN_MASK; i++) {
2237         if ((xpdMask >> (AR5416_PD_GAINS_IN_MASK - i)) & 1) {
2238             if (numXpdGain >= AR5416_NUM_PD_GAINS) {
2239                 HALASSERT(0);
2240                 break;
2241             }
2242             xpdGainValues[numXpdGain] = (uint16_t)(AR5416_PD_GAINS_IN_MASK - i);
2243             numXpdGain++;
2244         }
2245     }
2246     return numXpdGain;
2247 }
2248 
2249 /*
2250  * Write the detector gain and biases.
2251  *
2252  * There are four power detector gain levels. The xpdMask in the EEPROM
2253  * determines which power detector gain levels have TX power calibration
2254  * data associated with them. This function writes the number of
2255  * PD gain levels and their values into the hardware.
2256  *
2257  * This is valid for all TX chains - the calibration data itself however
2258  * will likely differ per-chain.
2259  */
2260 void
2261 ar5416WriteDetectorGainBiases(struct ath_hal *ah, uint16_t numXpdGain,
2262     uint16_t xpdGainValues[])
2263 {
2264     HALDEBUG(ah, HAL_DEBUG_EEPROM, "%s: numXpdGain: %d,"
2265       " xpdGainValues: %d, %d, %d\n", __func__, numXpdGain,
2266       xpdGainValues[0], xpdGainValues[1], xpdGainValues[2]);
2267 
2268     OS_REG_WRITE(ah, AR_PHY_TPCRG1, (OS_REG_READ(ah, AR_PHY_TPCRG1) &
2269     	~(AR_PHY_TPCRG1_NUM_PD_GAIN | AR_PHY_TPCRG1_PD_GAIN_1 |
2270 	AR_PHY_TPCRG1_PD_GAIN_2 | AR_PHY_TPCRG1_PD_GAIN_3)) |
2271 	SM(numXpdGain - 1, AR_PHY_TPCRG1_NUM_PD_GAIN) |
2272 	SM(xpdGainValues[0], AR_PHY_TPCRG1_PD_GAIN_1 ) |
2273 	SM(xpdGainValues[1], AR_PHY_TPCRG1_PD_GAIN_2) |
2274 	SM(xpdGainValues[2],  AR_PHY_TPCRG1_PD_GAIN_3));
2275 }
2276 
2277 /*
2278  * Write the PDADC array to the given radio chain i.
2279  *
2280  * The 32 PDADC registers are written without any care about
2281  * their contents - so if various chips treat values as "special",
2282  * this routine will not care.
2283  */
2284 void
2285 ar5416WritePdadcValues(struct ath_hal *ah, int i, uint8_t pdadcValues[])
2286 {
2287 	int regOffset, regChainOffset;
2288 	int j;
2289 	int reg32;
2290 
2291 	regChainOffset = ar5416GetRegChainOffset(ah, i);
2292 	regOffset = AR_PHY_BASE + (672 << 2) + regChainOffset;
2293 
2294 	for (j = 0; j < 32; j++) {
2295 		reg32 = ((pdadcValues[4*j + 0] & 0xFF) << 0)  |
2296 		    ((pdadcValues[4*j + 1] & 0xFF) << 8)  |
2297 		    ((pdadcValues[4*j + 2] & 0xFF) << 16) |
2298 		    ((pdadcValues[4*j + 3] & 0xFF) << 24) ;
2299 		OS_REG_WRITE(ah, regOffset, reg32);
2300 		HALDEBUG(ah, HAL_DEBUG_EEPROM, "PDADC: Chain %d |"
2301 		    " PDADC %3d Value %3d | PDADC %3d Value %3d | PDADC %3d"
2302 		    " Value %3d | PDADC %3d Value %3d |\n",
2303 		    i,
2304 		    4*j, pdadcValues[4*j],
2305 		    4*j+1, pdadcValues[4*j + 1],
2306 		    4*j+2, pdadcValues[4*j + 2],
2307 		    4*j+3, pdadcValues[4*j + 3]);
2308 		regOffset += 4;
2309 	}
2310 }
2311 
2312 /**************************************************************
2313  * ar5416SetPowerCalTable
2314  *
2315  * Pull the PDADC piers from cal data and interpolate them across the given
2316  * points as well as from the nearest pier(s) to get a power detector
2317  * linear voltage to power level table.
2318  */
2319 HAL_BOOL
2320 ar5416SetPowerCalTable(struct ath_hal *ah, struct ar5416eeprom *pEepData,
2321 	const struct ieee80211_channel *chan, int16_t *pTxPowerIndexOffset)
2322 {
2323     CAL_DATA_PER_FREQ *pRawDataset;
2324     uint8_t  *pCalBChans = AH_NULL;
2325     uint16_t pdGainOverlap_t2;
2326     static uint8_t  pdadcValues[AR5416_NUM_PDADC_VALUES];
2327     uint16_t gainBoundaries[AR5416_PD_GAINS_IN_MASK];
2328     uint16_t numPiers, i;
2329     int16_t  tMinCalPower;
2330     uint16_t numXpdGain, xpdMask;
2331     uint16_t xpdGainValues[AR5416_NUM_PD_GAINS];
2332     uint32_t regChainOffset;
2333 
2334     OS_MEMZERO(xpdGainValues, sizeof(xpdGainValues));
2335 
2336     xpdMask = pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].xpdGain;
2337 
2338     if (IS_EEP_MINOR_V2(ah)) {
2339         pdGainOverlap_t2 = pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].pdGainOverlap;
2340     } else {
2341     	pdGainOverlap_t2 = (uint16_t)(MS(OS_REG_READ(ah, AR_PHY_TPCRG5), AR_PHY_TPCRG5_PD_GAIN_OVERLAP));
2342     }
2343 
2344     if (IEEE80211_IS_CHAN_2GHZ(chan)) {
2345         pCalBChans = pEepData->calFreqPier2G;
2346         numPiers = AR5416_NUM_2G_CAL_PIERS;
2347     } else {
2348         pCalBChans = pEepData->calFreqPier5G;
2349         numPiers = AR5416_NUM_5G_CAL_PIERS;
2350     }
2351 
2352     /* Calculate the value of xpdgains from the xpdGain Mask */
2353     numXpdGain = ar5416GetXpdGainValues(ah, xpdMask, xpdGainValues);
2354 
2355     /* Write the detector gain biases and their number */
2356     ar5416WriteDetectorGainBiases(ah, numXpdGain, xpdGainValues);
2357 
2358     for (i = 0; i < AR5416_MAX_CHAINS; i++) {
2359 	regChainOffset = ar5416GetRegChainOffset(ah, i);
2360 
2361         if (pEepData->baseEepHeader.txMask & (1 << i)) {
2362             if (IEEE80211_IS_CHAN_2GHZ(chan)) {
2363                 pRawDataset = pEepData->calPierData2G[i];
2364             } else {
2365                 pRawDataset = pEepData->calPierData5G[i];
2366             }
2367 
2368             /* Fetch the gain boundaries and the PDADC values */
2369 	    ar5416GetGainBoundariesAndPdadcs(ah,  chan, pRawDataset,
2370                                              pCalBChans, numPiers,
2371                                              pdGainOverlap_t2,
2372                                              &tMinCalPower, gainBoundaries,
2373                                              pdadcValues, numXpdGain);
2374 
2375             if ((i == 0) || AR_SREV_5416_V20_OR_LATER(ah)) {
2376 		ar5416SetGainBoundariesClosedLoop(ah, i, pdGainOverlap_t2,
2377 		  gainBoundaries);
2378             }
2379 
2380             /* Write the power values into the baseband power table */
2381 	    ar5416WritePdadcValues(ah, i, pdadcValues);
2382         }
2383     }
2384     *pTxPowerIndexOffset = 0;
2385 
2386     return AH_TRUE;
2387 }
2388 
2389 /**************************************************************
2390  * ar5416GetGainBoundariesAndPdadcs
2391  *
2392  * Uses the data points read from EEPROM to reconstruct the pdadc power table
2393  * Called by ar5416SetPowerCalTable only.
2394  */
2395 void
2396 ar5416GetGainBoundariesAndPdadcs(struct ath_hal *ah,
2397                                  const struct ieee80211_channel *chan,
2398 				 CAL_DATA_PER_FREQ *pRawDataSet,
2399                                  uint8_t * bChans,  uint16_t availPiers,
2400                                  uint16_t tPdGainOverlap, int16_t *pMinCalPower, uint16_t * pPdGainBoundaries,
2401                                  uint8_t * pPDADCValues, uint16_t numXpdGains)
2402 {
2403 
2404     int       i, j, k;
2405     int16_t   ss;         /* potentially -ve index for taking care of pdGainOverlap */
2406     uint16_t  idxL, idxR, numPiers; /* Pier indexes */
2407 
2408     /* filled out Vpd table for all pdGains (chanL) */
2409     static uint8_t   vpdTableL[AR5416_NUM_PD_GAINS][AR5416_MAX_PWR_RANGE_IN_HALF_DB];
2410 
2411     /* filled out Vpd table for all pdGains (chanR) */
2412     static uint8_t   vpdTableR[AR5416_NUM_PD_GAINS][AR5416_MAX_PWR_RANGE_IN_HALF_DB];
2413 
2414     /* filled out Vpd table for all pdGains (interpolated) */
2415     static uint8_t   vpdTableI[AR5416_NUM_PD_GAINS][AR5416_MAX_PWR_RANGE_IN_HALF_DB];
2416 
2417     uint8_t   *pVpdL, *pVpdR, *pPwrL, *pPwrR;
2418     uint8_t   minPwrT4[AR5416_NUM_PD_GAINS];
2419     uint8_t   maxPwrT4[AR5416_NUM_PD_GAINS];
2420     int16_t   vpdStep;
2421     int16_t   tmpVal;
2422     uint16_t  sizeCurrVpdTable, maxIndex, tgtIndex;
2423     HAL_BOOL    match;
2424     int16_t  minDelta = 0;
2425     CHAN_CENTERS centers;
2426 
2427     ar5416GetChannelCenters(ah, chan, &centers);
2428 
2429     /* Trim numPiers for the number of populated channel Piers */
2430     for (numPiers = 0; numPiers < availPiers; numPiers++) {
2431         if (bChans[numPiers] == AR5416_BCHAN_UNUSED) {
2432             break;
2433         }
2434     }
2435 
2436     /* Find pier indexes around the current channel */
2437     match = ath_ee_getLowerUpperIndex((uint8_t)FREQ2FBIN(centers.synth_center,
2438 	IEEE80211_IS_CHAN_2GHZ(chan)), bChans, numPiers, &idxL, &idxR);
2439 
2440     if (match) {
2441         /* Directly fill both vpd tables from the matching index */
2442         for (i = 0; i < numXpdGains; i++) {
2443             minPwrT4[i] = pRawDataSet[idxL].pwrPdg[i][0];
2444             maxPwrT4[i] = pRawDataSet[idxL].pwrPdg[i][4];
2445             ath_ee_FillVpdTable(minPwrT4[i], maxPwrT4[i], pRawDataSet[idxL].pwrPdg[i],
2446                                pRawDataSet[idxL].vpdPdg[i], AR5416_PD_GAIN_ICEPTS, vpdTableI[i]);
2447         }
2448     } else {
2449         for (i = 0; i < numXpdGains; i++) {
2450             pVpdL = pRawDataSet[idxL].vpdPdg[i];
2451             pPwrL = pRawDataSet[idxL].pwrPdg[i];
2452             pVpdR = pRawDataSet[idxR].vpdPdg[i];
2453             pPwrR = pRawDataSet[idxR].pwrPdg[i];
2454 
2455             /* Start Vpd interpolation from the max of the minimum powers */
2456             minPwrT4[i] = AH_MAX(pPwrL[0], pPwrR[0]);
2457 
2458             /* End Vpd interpolation from the min of the max powers */
2459             maxPwrT4[i] = AH_MIN(pPwrL[AR5416_PD_GAIN_ICEPTS - 1], pPwrR[AR5416_PD_GAIN_ICEPTS - 1]);
2460             HALASSERT(maxPwrT4[i] > minPwrT4[i]);
2461 
2462             /* Fill pier Vpds */
2463             ath_ee_FillVpdTable(minPwrT4[i], maxPwrT4[i], pPwrL, pVpdL, AR5416_PD_GAIN_ICEPTS, vpdTableL[i]);
2464             ath_ee_FillVpdTable(minPwrT4[i], maxPwrT4[i], pPwrR, pVpdR, AR5416_PD_GAIN_ICEPTS, vpdTableR[i]);
2465 
2466             /* Interpolate the final vpd */
2467             for (j = 0; j <= (maxPwrT4[i] - minPwrT4[i]) / 2; j++) {
2468                 vpdTableI[i][j] = (uint8_t)(ath_ee_interpolate((uint16_t)FREQ2FBIN(centers.synth_center,
2469 		    IEEE80211_IS_CHAN_2GHZ(chan)),
2470                     bChans[idxL], bChans[idxR], vpdTableL[i][j], vpdTableR[i][j]));
2471             }
2472         }
2473     }
2474     *pMinCalPower = (int16_t)(minPwrT4[0] / 2);
2475 
2476     k = 0; /* index for the final table */
2477     for (i = 0; i < numXpdGains; i++) {
2478         if (i == (numXpdGains - 1)) {
2479             pPdGainBoundaries[i] = (uint16_t)(maxPwrT4[i] / 2);
2480         } else {
2481             pPdGainBoundaries[i] = (uint16_t)((maxPwrT4[i] + minPwrT4[i+1]) / 4);
2482         }
2483 
2484         pPdGainBoundaries[i] = (uint16_t)AH_MIN(AR5416_MAX_RATE_POWER, pPdGainBoundaries[i]);
2485 
2486 	/* NB: only applies to owl 1.0 */
2487         if ((i == 0) && !AR_SREV_5416_V20_OR_LATER(ah) ) {
2488 	    /*
2489              * fix the gain delta, but get a delta that can be applied to min to
2490              * keep the upper power values accurate, don't think max needs to
2491              * be adjusted because should not be at that area of the table?
2492 	     */
2493             minDelta = pPdGainBoundaries[0] - 23;
2494             pPdGainBoundaries[0] = 23;
2495         }
2496         else {
2497             minDelta = 0;
2498         }
2499 
2500         /* Find starting index for this pdGain */
2501         if (i == 0) {
2502             if (AR_SREV_MERLIN_10_OR_LATER(ah))
2503                 ss = (int16_t)(0 - (minPwrT4[i] / 2));
2504             else
2505                 ss = 0; /* for the first pdGain, start from index 0 */
2506         } else {
2507 	    /* need overlap entries extrapolated below. */
2508             ss = (int16_t)((pPdGainBoundaries[i-1] - (minPwrT4[i] / 2)) - tPdGainOverlap + 1 + minDelta);
2509         }
2510         vpdStep = (int16_t)(vpdTableI[i][1] - vpdTableI[i][0]);
2511         vpdStep = (int16_t)((vpdStep < 1) ? 1 : vpdStep);
2512         /*
2513          *-ve ss indicates need to extrapolate data below for this pdGain
2514          */
2515         while ((ss < 0) && (k < (AR5416_NUM_PDADC_VALUES - 1))) {
2516             tmpVal = (int16_t)(vpdTableI[i][0] + ss * vpdStep);
2517             pPDADCValues[k++] = (uint8_t)((tmpVal < 0) ? 0 : tmpVal);
2518             ss++;
2519         }
2520 
2521         sizeCurrVpdTable = (uint8_t)((maxPwrT4[i] - minPwrT4[i]) / 2 +1);
2522         tgtIndex = (uint8_t)(pPdGainBoundaries[i] + tPdGainOverlap - (minPwrT4[i] / 2));
2523         maxIndex = (tgtIndex < sizeCurrVpdTable) ? tgtIndex : sizeCurrVpdTable;
2524 
2525         while ((ss < maxIndex) && (k < (AR5416_NUM_PDADC_VALUES - 1))) {
2526             pPDADCValues[k++] = vpdTableI[i][ss++];
2527         }
2528 
2529         vpdStep = (int16_t)(vpdTableI[i][sizeCurrVpdTable - 1] - vpdTableI[i][sizeCurrVpdTable - 2]);
2530         vpdStep = (int16_t)((vpdStep < 1) ? 1 : vpdStep);
2531         /*
2532          * for last gain, pdGainBoundary == Pmax_t2, so will
2533          * have to extrapolate
2534          */
2535         if (tgtIndex >= maxIndex) {  /* need to extrapolate above */
2536             while ((ss <= tgtIndex) && (k < (AR5416_NUM_PDADC_VALUES - 1))) {
2537                 tmpVal = (int16_t)((vpdTableI[i][sizeCurrVpdTable - 1] +
2538                           (ss - maxIndex +1) * vpdStep));
2539                 pPDADCValues[k++] = (uint8_t)((tmpVal > 255) ? 255 : tmpVal);
2540                 ss++;
2541             }
2542         }               /* extrapolated above */
2543     }                   /* for all pdGainUsed */
2544 
2545     /* Fill out pdGainBoundaries - only up to 2 allowed here, but hardware allows up to 4 */
2546     while (i < AR5416_PD_GAINS_IN_MASK) {
2547         pPdGainBoundaries[i] = pPdGainBoundaries[i-1];
2548         i++;
2549     }
2550 
2551     while (k < AR5416_NUM_PDADC_VALUES) {
2552         pPDADCValues[k] = pPDADCValues[k-1];
2553         k++;
2554     }
2555     return;
2556 }
2557 
2558 /*
2559  * The linux ath9k driver and (from what I've been told) the reference
2560  * Atheros driver enables the 11n PHY by default whether or not it's
2561  * configured.
2562  */
2563 static void
2564 ar5416Set11nRegs(struct ath_hal *ah, const struct ieee80211_channel *chan)
2565 {
2566 	uint32_t phymode;
2567 	uint32_t enableDacFifo = 0;
2568 	HAL_HT_MACMODE macmode;		/* MAC - 20/40 mode */
2569 
2570 	if (AR_SREV_KITE_10_OR_LATER(ah))
2571 		enableDacFifo = (OS_REG_READ(ah, AR_PHY_TURBO) & AR_PHY_FC_ENABLE_DAC_FIFO);
2572 
2573 	/* Enable 11n HT, 20 MHz */
2574 	phymode = AR_PHY_FC_HT_EN | AR_PHY_FC_SHORT_GI_40
2575 		| AR_PHY_FC_SINGLE_HT_LTF1 | AR_PHY_FC_WALSH | enableDacFifo;
2576 
2577 	/* Configure baseband for dynamic 20/40 operation */
2578 	if (IEEE80211_IS_CHAN_HT40(chan)) {
2579 		phymode |= AR_PHY_FC_DYN2040_EN;
2580 
2581 		/* Configure control (primary) channel at +-10MHz */
2582 		if (IEEE80211_IS_CHAN_HT40U(chan))
2583 			phymode |= AR_PHY_FC_DYN2040_PRI_CH;
2584 #if 0
2585 		/* Configure 20/25 spacing */
2586 		if (ht->ht_extprotspacing == HAL_HT_EXTPROTSPACING_25)
2587 			phymode |= AR_PHY_FC_DYN2040_EXT_CH;
2588 #endif
2589 		macmode = HAL_HT_MACMODE_2040;
2590 	} else
2591 		macmode = HAL_HT_MACMODE_20;
2592 	OS_REG_WRITE(ah, AR_PHY_TURBO, phymode);
2593 
2594 	/* Configure MAC for 20/40 operation */
2595 	ar5416Set11nMac2040(ah, macmode);
2596 
2597 	/* global transmit timeout (25 TUs default)*/
2598 	/* XXX - put this elsewhere??? */
2599 	OS_REG_WRITE(ah, AR_GTXTO, 25 << AR_GTXTO_TIMEOUT_LIMIT_S) ;
2600 
2601 	/* carrier sense timeout */
2602 	OS_REG_SET_BIT(ah, AR_GTTM, AR_GTTM_CST_USEC);
2603 	OS_REG_WRITE(ah, AR_CST, 0xF << AR_CST_TIMEOUT_LIMIT_S);
2604 }
2605 
2606 void
2607 ar5416GetChannelCenters(struct ath_hal *ah,
2608 	const struct ieee80211_channel *chan, CHAN_CENTERS *centers)
2609 {
2610 	uint16_t freq = ath_hal_gethwchannel(ah, chan);
2611 
2612 	centers->ctl_center = freq;
2613 	centers->synth_center = freq;
2614 	/*
2615 	 * In 20/40 phy mode, the center frequency is
2616 	 * "between" the control and extension channels.
2617 	 */
2618 	if (IEEE80211_IS_CHAN_HT40U(chan)) {
2619 		centers->synth_center += HT40_CHANNEL_CENTER_SHIFT;
2620 		centers->ext_center =
2621 		    centers->synth_center + HT40_CHANNEL_CENTER_SHIFT;
2622 	} else if (IEEE80211_IS_CHAN_HT40D(chan)) {
2623 		centers->synth_center -= HT40_CHANNEL_CENTER_SHIFT;
2624 		centers->ext_center =
2625 		    centers->synth_center - HT40_CHANNEL_CENTER_SHIFT;
2626 	} else {
2627 		centers->ext_center = freq;
2628 	}
2629 }
2630 
2631 /*
2632  * Override the INI vals being programmed.
2633  */
2634 static void
2635 ar5416OverrideIni(struct ath_hal *ah, const struct ieee80211_channel *chan)
2636 {
2637 	uint32_t val;
2638 
2639 	/*
2640 	 * Set the RX_ABORT and RX_DIS and clear if off only after
2641 	 * RXE is set for MAC. This prevents frames with corrupted
2642 	 * descriptor status.
2643 	 */
2644 	OS_REG_SET_BIT(ah, AR_DIAG_SW, (AR_DIAG_RX_DIS | AR_DIAG_RX_ABORT));
2645 
2646 	if (AR_SREV_MERLIN_10_OR_LATER(ah)) {
2647 		val = OS_REG_READ(ah, AR_PCU_MISC_MODE2);
2648 		val &= (~AR_PCU_MISC_MODE2_ADHOC_MCAST_KEYID_ENABLE);
2649 		if (!AR_SREV_9271(ah))
2650 			val &= ~AR_PCU_MISC_MODE2_HWWAR1;
2651 
2652 		if (AR_SREV_KIWI_10_OR_LATER(ah))
2653 			val = val & (~AR_PCU_MISC_MODE2_HWWAR2);
2654 
2655 		OS_REG_WRITE(ah, AR_PCU_MISC_MODE2, val);
2656 	}
2657 
2658 	/*
2659 	 * Disable RIFS search on some chips to avoid baseband
2660 	 * hang issues.
2661 	 */
2662 	if (AR_SREV_HOWL(ah) || AR_SREV_SOWL(ah))
2663 		(void) ar5416SetRifsDelay(ah, chan, AH_FALSE);
2664 
2665         if (!AR_SREV_5416_V20_OR_LATER(ah) || AR_SREV_MERLIN(ah))
2666 		return;
2667 
2668 	/*
2669 	 * Disable BB clock gating
2670 	 * Necessary to avoid issues on AR5416 2.0
2671 	 */
2672 	OS_REG_WRITE(ah, 0x9800 + (651 << 2), 0x11);
2673 }
2674 
2675 struct ini {
2676 	uint32_t        *data;          /* NB: !const */
2677 	int             rows, cols;
2678 };
2679 
2680 /*
2681  * Override XPA bias level based on operating frequency.
2682  * This is a v14 EEPROM specific thing for the AR9160.
2683  */
2684 void
2685 ar5416EepromSetAddac(struct ath_hal *ah, const struct ieee80211_channel *chan)
2686 {
2687 #define	XPA_LVL_FREQ(cnt)	(pModal->xpaBiasLvlFreq[cnt])
2688 	MODAL_EEP_HEADER	*pModal;
2689 	HAL_EEPROM_v14 *ee = AH_PRIVATE(ah)->ah_eeprom;
2690 	struct ar5416eeprom	*eep = &ee->ee_base;
2691 	uint8_t biaslevel;
2692 
2693 	if (! AR_SREV_SOWL(ah))
2694 		return;
2695 
2696         if (EEP_MINOR(ah) < AR5416_EEP_MINOR_VER_7)
2697                 return;
2698 
2699 	pModal = &(eep->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)]);
2700 
2701 	if (pModal->xpaBiasLvl != 0xff)
2702 		biaslevel = pModal->xpaBiasLvl;
2703 	else {
2704 		uint16_t resetFreqBin, freqBin, freqCount = 0;
2705 		CHAN_CENTERS centers;
2706 
2707 		ar5416GetChannelCenters(ah, chan, &centers);
2708 
2709 		resetFreqBin = FREQ2FBIN(centers.synth_center, IEEE80211_IS_CHAN_2GHZ(chan));
2710 		freqBin = XPA_LVL_FREQ(0) & 0xff;
2711 		biaslevel = (uint8_t) (XPA_LVL_FREQ(0) >> 14);
2712 
2713 		freqCount++;
2714 
2715 		while (freqCount < 3) {
2716 			if (XPA_LVL_FREQ(freqCount) == 0x0)
2717 			break;
2718 
2719 			freqBin = XPA_LVL_FREQ(freqCount) & 0xff;
2720 			if (resetFreqBin >= freqBin)
2721 				biaslevel = (uint8_t)(XPA_LVL_FREQ(freqCount) >> 14);
2722 			else
2723 				break;
2724 			freqCount++;
2725 		}
2726 	}
2727 
2728 	HALDEBUG(ah, HAL_DEBUG_EEPROM, "%s: overriding XPA bias level = %d\n",
2729 	    __func__, biaslevel);
2730 
2731 	/*
2732 	 * This is a dirty workaround for the const initval data,
2733 	 * which will upset multiple AR9160's on the same board.
2734 	 *
2735 	 * The HAL should likely just have a private copy of the addac
2736 	 * data per instance.
2737 	 */
2738 	if (IEEE80211_IS_CHAN_2GHZ(chan))
2739                 HAL_INI_VAL((struct ini *) &AH5416(ah)->ah_ini_addac, 7, 1) =
2740 		    (HAL_INI_VAL(&AH5416(ah)->ah_ini_addac, 7, 1) & (~0x18)) | biaslevel << 3;
2741         else
2742                 HAL_INI_VAL((struct ini *) &AH5416(ah)->ah_ini_addac, 6, 1) =
2743 		    (HAL_INI_VAL(&AH5416(ah)->ah_ini_addac, 6, 1) & (~0xc0)) | biaslevel << 6;
2744 #undef XPA_LVL_FREQ
2745 }
2746 
2747 static void
2748 ar5416MarkPhyInactive(struct ath_hal *ah)
2749 {
2750 	OS_REG_WRITE(ah, AR_PHY_ACTIVE, AR_PHY_ACTIVE_DIS);
2751 }
2752