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