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