1/*
2 * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
3 * Copyright (c) 2002-2008 Atheros Communications, Inc.
4 *
5 * Permission to use, copy, modify, and/or distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 *
17 * $FreeBSD$
18 */
19#include "opt_ah.h"
20
21#include "ah.h"
22#include "ah_internal.h"
23
24#include "ah_eeprom_v3.h"
25
26#include "ar5212/ar5212.h"
27#include "ar5212/ar5212reg.h"
28#include "ar5212/ar5212phy.h"
29
30#define AH_5212_5112
31#include "ar5212/ar5212.ini"
32
33#define	N(a)	(sizeof(a)/sizeof(a[0]))
34
35struct ar5112State {
36	RF_HAL_FUNCS	base;		/* public state, must be first */
37	uint16_t	pcdacTable[PWR_TABLE_SIZE];
38
39	uint32_t	Bank1Data[N(ar5212Bank1_5112)];
40	uint32_t	Bank2Data[N(ar5212Bank2_5112)];
41	uint32_t	Bank3Data[N(ar5212Bank3_5112)];
42	uint32_t	Bank6Data[N(ar5212Bank6_5112)];
43	uint32_t	Bank7Data[N(ar5212Bank7_5112)];
44};
45#define	AR5112(ah)	((struct ar5112State *) AH5212(ah)->ah_rfHal)
46
47static	void ar5212GetLowerUpperIndex(uint16_t v,
48		uint16_t *lp, uint16_t listSize,
49		uint32_t *vlo, uint32_t *vhi);
50static HAL_BOOL getFullPwrTable(uint16_t numPcdacs, uint16_t *pcdacs,
51		int16_t *power, int16_t maxPower, int16_t *retVals);
52static int16_t getPminAndPcdacTableFromPowerTable(int16_t *pwrTableT4,
53		uint16_t retVals[]);
54static int16_t getPminAndPcdacTableFromTwoPowerTables(int16_t *pwrTableLXpdT4,
55		int16_t *pwrTableHXpdT4, uint16_t retVals[], int16_t *pMid);
56static int16_t interpolate_signed(uint16_t target,
57		uint16_t srcLeft, uint16_t srcRight,
58		int16_t targetLeft, int16_t targetRight);
59
60extern	void ar5212ModifyRfBuffer(uint32_t *rfBuf, uint32_t reg32,
61		uint32_t numBits, uint32_t firstBit, uint32_t column);
62
63static void
64ar5112WriteRegs(struct ath_hal *ah, u_int modesIndex, u_int freqIndex,
65	int writes)
66{
67	HAL_INI_WRITE_ARRAY(ah, ar5212Modes_5112, modesIndex, writes);
68	HAL_INI_WRITE_ARRAY(ah, ar5212Common_5112, 1, writes);
69	HAL_INI_WRITE_ARRAY(ah, ar5212BB_RfGain_5112, freqIndex, writes);
70}
71
72/*
73 * Take the MHz channel value and set the Channel value
74 *
75 * ASSUMES: Writes enabled to analog bus
76 */
77static HAL_BOOL
78ar5112SetChannel(struct ath_hal *ah, const struct ieee80211_channel *chan)
79{
80	uint16_t freq = ath_hal_gethwchannel(ah, chan);
81	uint32_t channelSel  = 0;
82	uint32_t bModeSynth  = 0;
83	uint32_t aModeRefSel = 0;
84	uint32_t reg32       = 0;
85
86	OS_MARK(ah, AH_MARK_SETCHANNEL, freq);
87
88	if (freq < 4800) {
89		uint32_t txctl;
90
91		if (((freq - 2192) % 5) == 0) {
92			channelSel = ((freq - 672) * 2 - 3040)/10;
93			bModeSynth = 0;
94		} else if (((freq - 2224) % 5) == 0) {
95			channelSel = ((freq - 704) * 2 - 3040) / 10;
96			bModeSynth = 1;
97		} else {
98			HALDEBUG(ah, HAL_DEBUG_ANY,
99			    "%s: invalid channel %u MHz\n",
100			    __func__, freq);
101			return AH_FALSE;
102		}
103
104		channelSel = (channelSel << 2) & 0xff;
105		channelSel = ath_hal_reverseBits(channelSel, 8);
106
107		txctl = OS_REG_READ(ah, AR_PHY_CCK_TX_CTRL);
108		if (freq == 2484) {
109			/* Enable channel spreading for channel 14 */
110			OS_REG_WRITE(ah, AR_PHY_CCK_TX_CTRL,
111				txctl | AR_PHY_CCK_TX_CTRL_JAPAN);
112		} else {
113			OS_REG_WRITE(ah, AR_PHY_CCK_TX_CTRL,
114				txctl &~ AR_PHY_CCK_TX_CTRL_JAPAN);
115		}
116	} else if (((freq % 5) == 2) && (freq <= 5435)) {
117		freq = freq - 2; /* Align to even 5MHz raster */
118		channelSel = ath_hal_reverseBits(
119			(uint32_t)(((freq - 4800)*10)/25 + 1), 8);
120            	aModeRefSel = ath_hal_reverseBits(0, 2);
121	} else if ((freq % 20) == 0 && freq >= 5120) {
122		channelSel = ath_hal_reverseBits(
123			((freq - 4800) / 20 << 2), 8);
124		aModeRefSel = ath_hal_reverseBits(3, 2);
125	} else if ((freq % 10) == 0) {
126		channelSel = ath_hal_reverseBits(
127			((freq - 4800) / 10 << 1), 8);
128		aModeRefSel = ath_hal_reverseBits(2, 2);
129	} else if ((freq % 5) == 0) {
130		channelSel = ath_hal_reverseBits(
131			(freq - 4800) / 5, 8);
132		aModeRefSel = ath_hal_reverseBits(1, 2);
133	} else {
134		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel %u MHz\n",
135		    __func__, freq);
136		return AH_FALSE;
137	}
138
139	reg32 = (channelSel << 4) | (aModeRefSel << 2) | (bModeSynth << 1) |
140			(1 << 12) | 0x1;
141	OS_REG_WRITE(ah, AR_PHY(0x27), reg32 & 0xff);
142
143	reg32 >>= 8;
144	OS_REG_WRITE(ah, AR_PHY(0x36), reg32 & 0x7f);
145
146	AH_PRIVATE(ah)->ah_curchan = chan;
147	return AH_TRUE;
148}
149
150/*
151 * Return a reference to the requested RF Bank.
152 */
153static uint32_t *
154ar5112GetRfBank(struct ath_hal *ah, int bank)
155{
156	struct ar5112State *priv = AR5112(ah);
157
158	HALASSERT(priv != AH_NULL);
159	switch (bank) {
160	case 1: return priv->Bank1Data;
161	case 2: return priv->Bank2Data;
162	case 3: return priv->Bank3Data;
163	case 6: return priv->Bank6Data;
164	case 7: return priv->Bank7Data;
165	}
166	HALDEBUG(ah, HAL_DEBUG_ANY, "%s: unknown RF Bank %d requested\n",
167	    __func__, bank);
168	return AH_NULL;
169}
170
171/*
172 * Reads EEPROM header info from device structure and programs
173 * all rf registers
174 *
175 * REQUIRES: Access to the analog rf device
176 */
177static HAL_BOOL
178ar5112SetRfRegs(struct ath_hal *ah,
179	const struct ieee80211_channel *chan,
180	uint16_t modesIndex, uint16_t *rfXpdGain)
181{
182#define	RF_BANK_SETUP(_priv, _ix, _col) do {				    \
183	int i;								    \
184	for (i = 0; i < N(ar5212Bank##_ix##_5112); i++)			    \
185		(_priv)->Bank##_ix##Data[i] = ar5212Bank##_ix##_5112[i][_col];\
186} while (0)
187	uint16_t freq = ath_hal_gethwchannel(ah, chan);
188	struct ath_hal_5212 *ahp = AH5212(ah);
189	const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
190	uint16_t rfXpdSel, gainI;
191	uint16_t ob5GHz = 0, db5GHz = 0;
192	uint16_t ob2GHz = 0, db2GHz = 0;
193	struct ar5112State *priv = AR5112(ah);
194	GAIN_VALUES *gv = &ahp->ah_gainValues;
195	int regWrites = 0;
196
197	HALASSERT(priv);
198
199	HALDEBUG(ah, HAL_DEBUG_RFPARAM, "%s: chan %u/0x%x modesIndex %u\n",
200	    __func__, chan->ic_freq, chan->ic_flags, modesIndex);
201
202	/* Setup rf parameters */
203	switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
204	case IEEE80211_CHAN_A:
205		if (freq > 4000 && freq < 5260) {
206			ob5GHz = ee->ee_ob1;
207			db5GHz = ee->ee_db1;
208		} else if (freq >= 5260 && freq < 5500) {
209			ob5GHz = ee->ee_ob2;
210			db5GHz = ee->ee_db2;
211		} else if (freq >= 5500 && freq < 5725) {
212			ob5GHz = ee->ee_ob3;
213			db5GHz = ee->ee_db3;
214		} else if (freq >= 5725) {
215			ob5GHz = ee->ee_ob4;
216			db5GHz = ee->ee_db4;
217		} else {
218			/* XXX else */
219		}
220		rfXpdSel = ee->ee_xpd[headerInfo11A];
221		gainI = ee->ee_gainI[headerInfo11A];
222		break;
223	case IEEE80211_CHAN_B:
224		ob2GHz = ee->ee_ob2GHz[0];
225		db2GHz = ee->ee_db2GHz[0];
226		rfXpdSel = ee->ee_xpd[headerInfo11B];
227		gainI = ee->ee_gainI[headerInfo11B];
228		break;
229	case IEEE80211_CHAN_G:
230	case IEEE80211_CHAN_PUREG:	/* NB: really 108G */
231		ob2GHz = ee->ee_ob2GHz[1];
232		db2GHz = ee->ee_ob2GHz[1];
233		rfXpdSel = ee->ee_xpd[headerInfo11G];
234		gainI = ee->ee_gainI[headerInfo11G];
235		break;
236	default:
237		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
238		    __func__, chan->ic_flags);
239		return AH_FALSE;
240	}
241
242	/* Setup Bank 1 Write */
243	RF_BANK_SETUP(priv, 1, 1);
244
245	/* Setup Bank 2 Write */
246	RF_BANK_SETUP(priv, 2, modesIndex);
247
248	/* Setup Bank 3 Write */
249	RF_BANK_SETUP(priv, 3, modesIndex);
250
251	/* Setup Bank 6 Write */
252	RF_BANK_SETUP(priv, 6, modesIndex);
253
254	ar5212ModifyRfBuffer(priv->Bank6Data, rfXpdSel,     1, 302, 0);
255
256	ar5212ModifyRfBuffer(priv->Bank6Data, rfXpdGain[0], 2, 270, 0);
257	ar5212ModifyRfBuffer(priv->Bank6Data, rfXpdGain[1], 2, 257, 0);
258
259	if (IEEE80211_IS_CHAN_OFDM(chan)) {
260		ar5212ModifyRfBuffer(priv->Bank6Data,
261			gv->currStep->paramVal[GP_PWD_138], 1, 168, 3);
262		ar5212ModifyRfBuffer(priv->Bank6Data,
263			gv->currStep->paramVal[GP_PWD_137], 1, 169, 3);
264		ar5212ModifyRfBuffer(priv->Bank6Data,
265			gv->currStep->paramVal[GP_PWD_136], 1, 170, 3);
266		ar5212ModifyRfBuffer(priv->Bank6Data,
267			gv->currStep->paramVal[GP_PWD_132], 1, 174, 3);
268		ar5212ModifyRfBuffer(priv->Bank6Data,
269			gv->currStep->paramVal[GP_PWD_131], 1, 175, 3);
270		ar5212ModifyRfBuffer(priv->Bank6Data,
271			gv->currStep->paramVal[GP_PWD_130], 1, 176, 3);
272	}
273
274	/* Only the 5 or 2 GHz OB/DB need to be set for a mode */
275	if (IEEE80211_IS_CHAN_2GHZ(chan)) {
276		ar5212ModifyRfBuffer(priv->Bank6Data, ob2GHz, 3, 287, 0);
277		ar5212ModifyRfBuffer(priv->Bank6Data, db2GHz, 3, 290, 0);
278	} else {
279		ar5212ModifyRfBuffer(priv->Bank6Data, ob5GHz, 3, 279, 0);
280		ar5212ModifyRfBuffer(priv->Bank6Data, db5GHz, 3, 282, 0);
281	}
282
283	/* Lower synth voltage for X112 Rev 2.0 only */
284	if (IS_RADX112_REV2(ah)) {
285		/* Non-Reversed analyg registers - so values are pre-reversed */
286		ar5212ModifyRfBuffer(priv->Bank6Data, 2, 2, 90, 2);
287		ar5212ModifyRfBuffer(priv->Bank6Data, 2, 2, 92, 2);
288		ar5212ModifyRfBuffer(priv->Bank6Data, 2, 2, 94, 2);
289		ar5212ModifyRfBuffer(priv->Bank6Data, 2, 1, 254, 2);
290	}
291
292    /* Decrease Power Consumption for 5312/5213 and up */
293    if (AH_PRIVATE(ah)->ah_phyRev >= AR_PHY_CHIP_ID_REV_2) {
294        ar5212ModifyRfBuffer(priv->Bank6Data, 1, 1, 281, 1);
295        ar5212ModifyRfBuffer(priv->Bank6Data, 1, 2, 1, 3);
296        ar5212ModifyRfBuffer(priv->Bank6Data, 1, 2, 3, 3);
297        ar5212ModifyRfBuffer(priv->Bank6Data, 1, 1, 139, 3);
298        ar5212ModifyRfBuffer(priv->Bank6Data, 1, 1, 140, 3);
299    }
300
301	/* Setup Bank 7 Setup */
302	RF_BANK_SETUP(priv, 7, modesIndex);
303	if (IEEE80211_IS_CHAN_OFDM(chan))
304		ar5212ModifyRfBuffer(priv->Bank7Data,
305			gv->currStep->paramVal[GP_MIXGAIN_OVR], 2, 37, 0);
306
307	ar5212ModifyRfBuffer(priv->Bank7Data, gainI, 6, 14, 0);
308
309	/* Adjust params for Derby TX power control */
310	if (IEEE80211_IS_CHAN_HALF(chan) || IEEE80211_IS_CHAN_QUARTER(chan)) {
311        	uint32_t	rfDelay, rfPeriod;
312
313        	rfDelay = 0xf;
314        	rfPeriod = (IEEE80211_IS_CHAN_HALF(chan)) ?  0x8 : 0xf;
315        	ar5212ModifyRfBuffer(priv->Bank7Data, rfDelay, 4, 58, 0);
316        	ar5212ModifyRfBuffer(priv->Bank7Data, rfPeriod, 4, 70, 0);
317	}
318
319#ifdef notyet
320	/* Analog registers are setup - EAR can modify */
321	if (ar5212IsEarEngaged(pDev, chan))
322		uint32_t modifier;
323		ar5212EarModify(pDev, EAR_LC_RF_WRITE, chan, &modifier);
324#endif
325	/* Write Analog registers */
326	HAL_INI_WRITE_BANK(ah, ar5212Bank1_5112, priv->Bank1Data, regWrites);
327	HAL_INI_WRITE_BANK(ah, ar5212Bank2_5112, priv->Bank2Data, regWrites);
328	HAL_INI_WRITE_BANK(ah, ar5212Bank3_5112, priv->Bank3Data, regWrites);
329	HAL_INI_WRITE_BANK(ah, ar5212Bank6_5112, priv->Bank6Data, regWrites);
330	HAL_INI_WRITE_BANK(ah, ar5212Bank7_5112, priv->Bank7Data, regWrites);
331
332	/* Now that we have reprogrammed rfgain value, clear the flag. */
333	ahp->ah_rfgainState = HAL_RFGAIN_INACTIVE;
334	return AH_TRUE;
335#undef	RF_BANK_SETUP
336}
337
338/*
339 * Read the transmit power levels from the structures taken from EEPROM
340 * Interpolate read transmit power values for this channel
341 * Organize the transmit power values into a table for writing into the hardware
342 */
343static HAL_BOOL
344ar5112SetPowerTable(struct ath_hal *ah,
345	int16_t *pPowerMin, int16_t *pPowerMax,
346	const struct ieee80211_channel *chan,
347	uint16_t *rfXpdGain)
348{
349	uint16_t freq = ath_hal_gethwchannel(ah, chan);
350	struct ath_hal_5212 *ahp = AH5212(ah);
351	const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
352	uint32_t numXpdGain = IS_RADX112_REV2(ah) ? 2 : 1;
353	uint32_t    xpdGainMask = 0;
354	int16_t     powerMid, *pPowerMid = &powerMid;
355
356	const EXPN_DATA_PER_CHANNEL_5112 *pRawCh;
357	const EEPROM_POWER_EXPN_5112     *pPowerExpn = AH_NULL;
358
359	uint32_t    ii, jj, kk;
360	int16_t     minPwr_t4, maxPwr_t4, Pmin, Pmid;
361
362	uint32_t    chan_idx_L = 0, chan_idx_R = 0;
363	uint16_t    chan_L, chan_R;
364
365	int16_t     pwr_table0[64];
366	int16_t     pwr_table1[64];
367	uint16_t    pcdacs[10];
368	int16_t     powers[10];
369	uint16_t    numPcd;
370	int16_t     powTableLXPD[2][64];
371	int16_t     powTableHXPD[2][64];
372	int16_t     tmpPowerTable[64];
373	uint16_t    xgainList[2];
374	uint16_t    xpdMask;
375
376	switch (chan->ic_flags & IEEE80211_CHAN_ALLTURBOFULL) {
377	case IEEE80211_CHAN_A:
378	case IEEE80211_CHAN_ST:
379		pPowerExpn = &ee->ee_modePowerArray5112[headerInfo11A];
380		xpdGainMask = ee->ee_xgain[headerInfo11A];
381		break;
382	case IEEE80211_CHAN_B:
383		pPowerExpn = &ee->ee_modePowerArray5112[headerInfo11B];
384		xpdGainMask = ee->ee_xgain[headerInfo11B];
385		break;
386	case IEEE80211_CHAN_G:
387	case IEEE80211_CHAN_108G:
388		pPowerExpn = &ee->ee_modePowerArray5112[headerInfo11G];
389		xpdGainMask = ee->ee_xgain[headerInfo11G];
390		break;
391	default:
392		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: unknown channel flags 0x%x\n",
393		    __func__, chan->ic_flags);
394		return AH_FALSE;
395	}
396
397	if ((xpdGainMask & pPowerExpn->xpdMask) < 1) {
398		HALDEBUG(ah, HAL_DEBUG_ANY,
399		    "%s: desired xpdGainMask 0x%x not supported by "
400		    "calibrated xpdMask 0x%x\n", __func__,
401		    xpdGainMask, pPowerExpn->xpdMask);
402		return AH_FALSE;
403	}
404
405	maxPwr_t4 = (int16_t)(2*(*pPowerMax));	/* pwr_t2 -> pwr_t4 */
406	minPwr_t4 = (int16_t)(2*(*pPowerMin));	/* pwr_t2 -> pwr_t4 */
407
408	xgainList[0] = 0xDEAD;
409	xgainList[1] = 0xDEAD;
410
411	kk = 0;
412	xpdMask = pPowerExpn->xpdMask;
413	for (jj = 0; jj < NUM_XPD_PER_CHANNEL; jj++) {
414		if (((xpdMask >> jj) & 1) > 0) {
415			if (kk > 1) {
416				HALDEBUG(ah, HAL_DEBUG_ANY,
417				    "A maximum of 2 xpdGains supported"
418				    "in pExpnPower data\n");
419				return AH_FALSE;
420			}
421			xgainList[kk++] = (uint16_t)jj;
422		}
423	}
424
425	ar5212GetLowerUpperIndex(freq, &pPowerExpn->pChannels[0],
426		pPowerExpn->numChannels, &chan_idx_L, &chan_idx_R);
427
428	kk = 0;
429	for (ii = chan_idx_L; ii <= chan_idx_R; ii++) {
430		pRawCh = &(pPowerExpn->pDataPerChannel[ii]);
431		if (xgainList[1] == 0xDEAD) {
432			jj = xgainList[0];
433			numPcd = pRawCh->pDataPerXPD[jj].numPcdacs;
434			OS_MEMCPY(&pcdacs[0], &pRawCh->pDataPerXPD[jj].pcdac[0],
435				numPcd * sizeof(uint16_t));
436			OS_MEMCPY(&powers[0], &pRawCh->pDataPerXPD[jj].pwr_t4[0],
437				numPcd * sizeof(int16_t));
438			if (!getFullPwrTable(numPcd, &pcdacs[0], &powers[0],
439				pRawCh->maxPower_t4, &tmpPowerTable[0])) {
440				return AH_FALSE;
441			}
442			OS_MEMCPY(&powTableLXPD[kk][0], &tmpPowerTable[0],
443				64*sizeof(int16_t));
444		} else {
445			jj = xgainList[0];
446			numPcd = pRawCh->pDataPerXPD[jj].numPcdacs;
447			OS_MEMCPY(&pcdacs[0], &pRawCh->pDataPerXPD[jj].pcdac[0],
448				numPcd*sizeof(uint16_t));
449			OS_MEMCPY(&powers[0],
450				&pRawCh->pDataPerXPD[jj].pwr_t4[0],
451				numPcd*sizeof(int16_t));
452			if (!getFullPwrTable(numPcd, &pcdacs[0], &powers[0],
453				pRawCh->maxPower_t4, &tmpPowerTable[0])) {
454				return AH_FALSE;
455			}
456			OS_MEMCPY(&powTableLXPD[kk][0], &tmpPowerTable[0],
457				64 * sizeof(int16_t));
458
459			jj = xgainList[1];
460			numPcd = pRawCh->pDataPerXPD[jj].numPcdacs;
461			OS_MEMCPY(&pcdacs[0], &pRawCh->pDataPerXPD[jj].pcdac[0],
462				numPcd * sizeof(uint16_t));
463			OS_MEMCPY(&powers[0],
464				&pRawCh->pDataPerXPD[jj].pwr_t4[0],
465				numPcd * sizeof(int16_t));
466			if (!getFullPwrTable(numPcd, &pcdacs[0], &powers[0],
467				pRawCh->maxPower_t4, &tmpPowerTable[0])) {
468				return AH_FALSE;
469			}
470			OS_MEMCPY(&powTableHXPD[kk][0], &tmpPowerTable[0],
471				64 * sizeof(int16_t));
472		}
473		kk++;
474	}
475
476	chan_L = pPowerExpn->pChannels[chan_idx_L];
477	chan_R = pPowerExpn->pChannels[chan_idx_R];
478	kk = chan_idx_R - chan_idx_L;
479
480	if (xgainList[1] == 0xDEAD) {
481		for (jj = 0; jj < 64; jj++) {
482			pwr_table0[jj] = interpolate_signed(
483				freq, chan_L, chan_R,
484				powTableLXPD[0][jj], powTableLXPD[kk][jj]);
485		}
486		Pmin = getPminAndPcdacTableFromPowerTable(&pwr_table0[0],
487				ahp->ah_pcdacTable);
488		*pPowerMin = (int16_t) (Pmin / 2);
489		*pPowerMid = (int16_t) (pwr_table0[63] / 2);
490		*pPowerMax = (int16_t) (pwr_table0[63] / 2);
491		rfXpdGain[0] = xgainList[0];
492		rfXpdGain[1] = rfXpdGain[0];
493	} else {
494		for (jj = 0; jj < 64; jj++) {
495			pwr_table0[jj] = interpolate_signed(
496				freq, chan_L, chan_R,
497				powTableLXPD[0][jj], powTableLXPD[kk][jj]);
498			pwr_table1[jj] = interpolate_signed(
499				freq, chan_L, chan_R,
500				powTableHXPD[0][jj], powTableHXPD[kk][jj]);
501		}
502		if (numXpdGain == 2) {
503			Pmin = getPminAndPcdacTableFromTwoPowerTables(
504				&pwr_table0[0], &pwr_table1[0],
505				ahp->ah_pcdacTable, &Pmid);
506			*pPowerMin = (int16_t) (Pmin / 2);
507			*pPowerMid = (int16_t) (Pmid / 2);
508			*pPowerMax = (int16_t) (pwr_table0[63] / 2);
509			rfXpdGain[0] = xgainList[0];
510			rfXpdGain[1] = xgainList[1];
511		} else if (minPwr_t4 <= pwr_table1[63] &&
512			   maxPwr_t4 <= pwr_table1[63]) {
513			Pmin = getPminAndPcdacTableFromPowerTable(
514				&pwr_table1[0], ahp->ah_pcdacTable);
515			rfXpdGain[0] = xgainList[1];
516			rfXpdGain[1] = rfXpdGain[0];
517			*pPowerMin = (int16_t) (Pmin / 2);
518			*pPowerMid = (int16_t) (pwr_table1[63] / 2);
519			*pPowerMax = (int16_t) (pwr_table1[63] / 2);
520		} else {
521			Pmin = getPminAndPcdacTableFromPowerTable(
522				&pwr_table0[0], ahp->ah_pcdacTable);
523			rfXpdGain[0] = xgainList[0];
524			rfXpdGain[1] = rfXpdGain[0];
525			*pPowerMin = (int16_t) (Pmin/2);
526			*pPowerMid = (int16_t) (pwr_table0[63] / 2);
527			*pPowerMax = (int16_t) (pwr_table0[63] / 2);
528		}
529	}
530
531	/*
532	 * Move 5112 rates to match power tables where the max
533	 * power table entry corresponds with maxPower.
534	 */
535	HALASSERT(*pPowerMax <= PCDAC_STOP);
536	ahp->ah_txPowerIndexOffset = PCDAC_STOP - *pPowerMax;
537
538	return AH_TRUE;
539}
540
541/*
542 * Returns interpolated or the scaled up interpolated value
543 */
544static int16_t
545interpolate_signed(uint16_t target, uint16_t srcLeft, uint16_t srcRight,
546	int16_t targetLeft, int16_t targetRight)
547{
548	int16_t rv;
549
550	if (srcRight != srcLeft) {
551		rv = ((target - srcLeft)*targetRight +
552		      (srcRight - target)*targetLeft) / (srcRight - srcLeft);
553	} else {
554		rv = targetLeft;
555	}
556	return rv;
557}
558
559/*
560 * Return indices surrounding the value in sorted integer lists.
561 *
562 * NB: the input list is assumed to be sorted in ascending order
563 */
564static void
565ar5212GetLowerUpperIndex(uint16_t v, uint16_t *lp, uint16_t listSize,
566                          uint32_t *vlo, uint32_t *vhi)
567{
568	uint32_t target = v;
569	uint16_t *ep = lp+listSize;
570	uint16_t *tp;
571
572	/*
573	 * Check first and last elements for out-of-bounds conditions.
574	 */
575	if (target < lp[0]) {
576		*vlo = *vhi = 0;
577		return;
578	}
579	if (target >= ep[-1]) {
580		*vlo = *vhi = listSize - 1;
581		return;
582	}
583
584	/* look for value being near or between 2 values in list */
585	for (tp = lp; tp < ep; tp++) {
586		/*
587		 * If value is close to the current value of the list
588		 * then target is not between values, it is one of the values
589		 */
590		if (*tp == target) {
591			*vlo = *vhi = tp - lp;
592			return;
593		}
594		/*
595		 * Look for value being between current value and next value
596		 * if so return these 2 values
597		 */
598		if (target < tp[1]) {
599			*vlo = tp - lp;
600			*vhi = *vlo + 1;
601			return;
602		}
603	}
604}
605
606static HAL_BOOL
607getFullPwrTable(uint16_t numPcdacs, uint16_t *pcdacs, int16_t *power, int16_t maxPower, int16_t *retVals)
608{
609	uint16_t    ii;
610	uint16_t    idxL = 0;
611	uint16_t    idxR = 1;
612
613	if (numPcdacs < 2) {
614		HALDEBUG(AH_NULL, HAL_DEBUG_ANY,
615		     "%s: at least 2 pcdac values needed [%d]\n",
616		     __func__, numPcdacs);
617		return AH_FALSE;
618	}
619	for (ii = 0; ii < 64; ii++) {
620		if (ii>pcdacs[idxR] && idxR < numPcdacs-1) {
621			idxL++;
622			idxR++;
623		}
624		retVals[ii] = interpolate_signed(ii,
625			pcdacs[idxL], pcdacs[idxR], power[idxL], power[idxR]);
626		if (retVals[ii] >= maxPower) {
627			while (ii < 64)
628				retVals[ii++] = maxPower;
629		}
630	}
631	return AH_TRUE;
632}
633
634/*
635 * Takes a single calibration curve and creates a power table.
636 * Adjusts the new power table so the max power is relative
637 * to the maximum index in the power table.
638 *
639 * WARNING: rates must be adjusted for this relative power table
640 */
641static int16_t
642getPminAndPcdacTableFromPowerTable(int16_t *pwrTableT4, uint16_t retVals[])
643{
644    int16_t ii, jj, jjMax;
645    int16_t pMin, currPower, pMax;
646
647    /* If the spread is > 31.5dB, keep the upper 31.5dB range */
648    if ((pwrTableT4[63] - pwrTableT4[0]) > 126) {
649        pMin = pwrTableT4[63] - 126;
650    } else {
651        pMin = pwrTableT4[0];
652    }
653
654    pMax = pwrTableT4[63];
655    jjMax = 63;
656
657    /* Search for highest pcdac 0.25dB below maxPower */
658    while ((pwrTableT4[jjMax] > (pMax - 1) ) && (jjMax >= 0)) {
659        jjMax--;
660    }
661
662    jj = jjMax;
663    currPower = pMax;
664    for (ii = 63; ii >= 0; ii--) {
665        while ((jj < 64) && (jj > 0) && (pwrTableT4[jj] >= currPower)) {
666            jj--;
667        }
668        if (jj == 0) {
669            while (ii >= 0) {
670                retVals[ii] = retVals[ii + 1];
671                ii--;
672            }
673            break;
674        }
675        retVals[ii] = jj;
676        currPower -= 2;  // corresponds to a 0.5dB step
677    }
678    return pMin;
679}
680
681/*
682 * Combines the XPD curves from two calibration sets into a single
683 * power table and adjusts the power table so the max power is relative
684 * to the maximum index in the power table
685 *
686 * WARNING: rates must be adjusted for this relative power table
687 */
688static int16_t
689getPminAndPcdacTableFromTwoPowerTables(int16_t *pwrTableLXpdT4,
690	int16_t *pwrTableHXpdT4, uint16_t retVals[], int16_t *pMid)
691{
692    int16_t     ii, jj, jjMax;
693    int16_t     pMin, pMax, currPower;
694    int16_t     *pwrTableT4;
695    uint16_t    msbFlag = 0x40;  // turns on the 7th bit of the pcdac
696
697    /* If the spread is > 31.5dB, keep the upper 31.5dB range */
698    if ((pwrTableLXpdT4[63] - pwrTableHXpdT4[0]) > 126) {
699        pMin = pwrTableLXpdT4[63] - 126;
700    } else {
701        pMin = pwrTableHXpdT4[0];
702    }
703
704    pMax = pwrTableLXpdT4[63];
705    jjMax = 63;
706    /* Search for highest pcdac 0.25dB below maxPower */
707    while ((pwrTableLXpdT4[jjMax] > (pMax - 1) ) && (jjMax >= 0)){
708        jjMax--;
709    }
710
711    *pMid = pwrTableHXpdT4[63];
712    jj = jjMax;
713    ii = 63;
714    currPower = pMax;
715    pwrTableT4 = &(pwrTableLXpdT4[0]);
716    while (ii >= 0) {
717        if ((currPower <= *pMid) || ( (jj == 0) && (msbFlag == 0x40))){
718            msbFlag = 0x00;
719            pwrTableT4 = &(pwrTableHXpdT4[0]);
720            jj = 63;
721        }
722        while ((jj > 0) && (pwrTableT4[jj] >= currPower)) {
723            jj--;
724        }
725        if ((jj == 0) && (msbFlag == 0x00)) {
726            while (ii >= 0) {
727                retVals[ii] = retVals[ii+1];
728                ii--;
729            }
730            break;
731        }
732        retVals[ii] = jj | msbFlag;
733        currPower -= 2;  // corresponds to a 0.5dB step
734        ii--;
735    }
736    return pMin;
737}
738
739static int16_t
740ar5112GetMinPower(struct ath_hal *ah, const EXPN_DATA_PER_CHANNEL_5112 *data)
741{
742	int i, minIndex;
743	int16_t minGain,minPwr,minPcdac,retVal;
744
745	/* Assume NUM_POINTS_XPD0 > 0 */
746	minGain = data->pDataPerXPD[0].xpd_gain;
747	for (minIndex=0,i=1; i<NUM_XPD_PER_CHANNEL; i++) {
748		if (data->pDataPerXPD[i].xpd_gain < minGain) {
749			minIndex = i;
750			minGain = data->pDataPerXPD[i].xpd_gain;
751		}
752	}
753	minPwr = data->pDataPerXPD[minIndex].pwr_t4[0];
754	minPcdac = data->pDataPerXPD[minIndex].pcdac[0];
755	for (i=1; i<NUM_POINTS_XPD0; i++) {
756		if (data->pDataPerXPD[minIndex].pwr_t4[i] < minPwr) {
757			minPwr = data->pDataPerXPD[minIndex].pwr_t4[i];
758			minPcdac = data->pDataPerXPD[minIndex].pcdac[i];
759		}
760	}
761	retVal = minPwr - (minPcdac*2);
762	return(retVal);
763}
764
765static HAL_BOOL
766ar5112GetChannelMaxMinPower(struct ath_hal *ah,
767	const struct ieee80211_channel *chan,
768	int16_t *maxPow, int16_t *minPow)
769{
770	uint16_t freq = chan->ic_freq;		/* NB: never mapped */
771	const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
772	int numChannels=0,i,last;
773	int totalD, totalF,totalMin;
774	const EXPN_DATA_PER_CHANNEL_5112 *data=AH_NULL;
775	const EEPROM_POWER_EXPN_5112 *powerArray=AH_NULL;
776
777	*maxPow = 0;
778	if (IEEE80211_IS_CHAN_A(chan)) {
779		powerArray = ee->ee_modePowerArray5112;
780		data = powerArray[headerInfo11A].pDataPerChannel;
781		numChannels = powerArray[headerInfo11A].numChannels;
782	} else if (IEEE80211_IS_CHAN_G(chan) || IEEE80211_IS_CHAN_108G(chan)) {
783		/* XXX - is this correct? Should we also use the same power for turbo G? */
784		powerArray = ee->ee_modePowerArray5112;
785		data = powerArray[headerInfo11G].pDataPerChannel;
786		numChannels = powerArray[headerInfo11G].numChannels;
787	} else if (IEEE80211_IS_CHAN_B(chan)) {
788		powerArray = ee->ee_modePowerArray5112;
789		data = powerArray[headerInfo11B].pDataPerChannel;
790		numChannels = powerArray[headerInfo11B].numChannels;
791	} else {
792		return (AH_TRUE);
793	}
794	/* Make sure the channel is in the range of the TP values
795	 *  (freq piers)
796	 */
797	if (numChannels < 1)
798		return(AH_FALSE);
799
800	if ((freq < data[0].channelValue) ||
801	    (freq > data[numChannels-1].channelValue)) {
802		if (freq < data[0].channelValue) {
803			*maxPow = data[0].maxPower_t4;
804			*minPow = ar5112GetMinPower(ah, &data[0]);
805			return(AH_TRUE);
806		} else {
807			*maxPow = data[numChannels - 1].maxPower_t4;
808			*minPow = ar5112GetMinPower(ah, &data[numChannels - 1]);
809			return(AH_TRUE);
810		}
811	}
812
813	/* Linearly interpolate the power value now */
814	for (last=0,i=0;
815	     (i<numChannels) && (freq > data[i].channelValue);
816	     last=i++);
817	totalD = data[i].channelValue - data[last].channelValue;
818	if (totalD > 0) {
819		totalF = data[i].maxPower_t4 - data[last].maxPower_t4;
820		*maxPow = (int8_t) ((totalF*(freq-data[last].channelValue) + data[last].maxPower_t4*totalD)/totalD);
821
822		totalMin = ar5112GetMinPower(ah,&data[i]) - ar5112GetMinPower(ah, &data[last]);
823		*minPow = (int8_t) ((totalMin*(freq-data[last].channelValue) + ar5112GetMinPower(ah, &data[last])*totalD)/totalD);
824		return (AH_TRUE);
825	} else {
826		if (freq == data[i].channelValue) {
827			*maxPow = data[i].maxPower_t4;
828			*minPow = ar5112GetMinPower(ah, &data[i]);
829			return(AH_TRUE);
830		} else
831			return(AH_FALSE);
832	}
833}
834
835/*
836 * Free memory for analog bank scratch buffers
837 */
838static void
839ar5112RfDetach(struct ath_hal *ah)
840{
841	struct ath_hal_5212 *ahp = AH5212(ah);
842
843	HALASSERT(ahp->ah_rfHal != AH_NULL);
844	ath_hal_free(ahp->ah_rfHal);
845	ahp->ah_rfHal = AH_NULL;
846}
847
848/*
849 * Allocate memory for analog bank scratch buffers
850 * Scratch Buffer will be reinitialized every reset so no need to zero now
851 */
852static HAL_BOOL
853ar5112RfAttach(struct ath_hal *ah, HAL_STATUS *status)
854{
855	struct ath_hal_5212 *ahp = AH5212(ah);
856	struct ar5112State *priv;
857
858	HALASSERT(ah->ah_magic == AR5212_MAGIC);
859
860	HALASSERT(ahp->ah_rfHal == AH_NULL);
861	priv = ath_hal_malloc(sizeof(struct ar5112State));
862	if (priv == AH_NULL) {
863		HALDEBUG(ah, HAL_DEBUG_ANY,
864		    "%s: cannot allocate private state\n", __func__);
865		*status = HAL_ENOMEM;		/* XXX */
866		return AH_FALSE;
867	}
868	priv->base.rfDetach		= ar5112RfDetach;
869	priv->base.writeRegs		= ar5112WriteRegs;
870	priv->base.getRfBank		= ar5112GetRfBank;
871	priv->base.setChannel		= ar5112SetChannel;
872	priv->base.setRfRegs		= ar5112SetRfRegs;
873	priv->base.setPowerTable	= ar5112SetPowerTable;
874	priv->base.getChannelMaxMinPower = ar5112GetChannelMaxMinPower;
875	priv->base.getNfAdjust		= ar5212GetNfAdjust;
876
877	ahp->ah_pcdacTable = priv->pcdacTable;
878	ahp->ah_pcdacTableSize = sizeof(priv->pcdacTable);
879	ahp->ah_rfHal = &priv->base;
880
881	return AH_TRUE;
882}
883
884static HAL_BOOL
885ar5112Probe(struct ath_hal *ah)
886{
887	return IS_RAD5112(ah);
888}
889AH_RF(RF5112, ar5112Probe, ar5112RfAttach);
890