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