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