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