xref: /openbmc/linux/drivers/net/wireless/ath/ath5k/phy.c (revision b595076a)
1 /*
2  * PHY functions
3  *
4  * Copyright (c) 2004-2007 Reyk Floeter <reyk@openbsd.org>
5  * Copyright (c) 2006-2009 Nick Kossifidis <mickflemm@gmail.com>
6  * Copyright (c) 2007-2008 Jiri Slaby <jirislaby@gmail.com>
7  * Copyright (c) 2008-2009 Felix Fietkau <nbd@openwrt.org>
8  *
9  * Permission to use, copy, modify, and distribute this software for any
10  * purpose with or without fee is hereby granted, provided that the above
11  * copyright notice and this permission notice appear in all copies.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20  *
21  */
22 
23 #include <linux/delay.h>
24 #include <linux/slab.h>
25 
26 #include "ath5k.h"
27 #include "reg.h"
28 #include "base.h"
29 #include "rfbuffer.h"
30 #include "rfgain.h"
31 
32 /*
33  * Used to modify RF Banks before writing them to AR5K_RF_BUFFER
34  */
35 static unsigned int ath5k_hw_rfb_op(struct ath5k_hw *ah,
36 					const struct ath5k_rf_reg *rf_regs,
37 					u32 val, u8 reg_id, bool set)
38 {
39 	const struct ath5k_rf_reg *rfreg = NULL;
40 	u8 offset, bank, num_bits, col, position;
41 	u16 entry;
42 	u32 mask, data, last_bit, bits_shifted, first_bit;
43 	u32 *rfb;
44 	s32 bits_left;
45 	int i;
46 
47 	data = 0;
48 	rfb = ah->ah_rf_banks;
49 
50 	for (i = 0; i < ah->ah_rf_regs_count; i++) {
51 		if (rf_regs[i].index == reg_id) {
52 			rfreg = &rf_regs[i];
53 			break;
54 		}
55 	}
56 
57 	if (rfb == NULL || rfreg == NULL) {
58 		ATH5K_PRINTF("Rf register not found!\n");
59 		/* should not happen */
60 		return 0;
61 	}
62 
63 	bank = rfreg->bank;
64 	num_bits = rfreg->field.len;
65 	first_bit = rfreg->field.pos;
66 	col = rfreg->field.col;
67 
68 	/* first_bit is an offset from bank's
69 	 * start. Since we have all banks on
70 	 * the same array, we use this offset
71 	 * to mark each bank's start */
72 	offset = ah->ah_offset[bank];
73 
74 	/* Boundary check */
75 	if (!(col <= 3 && num_bits <= 32 && first_bit + num_bits <= 319)) {
76 		ATH5K_PRINTF("invalid values at offset %u\n", offset);
77 		return 0;
78 	}
79 
80 	entry = ((first_bit - 1) / 8) + offset;
81 	position = (first_bit - 1) % 8;
82 
83 	if (set)
84 		data = ath5k_hw_bitswap(val, num_bits);
85 
86 	for (bits_shifted = 0, bits_left = num_bits; bits_left > 0;
87 	position = 0, entry++) {
88 
89 		last_bit = (position + bits_left > 8) ? 8 :
90 					position + bits_left;
91 
92 		mask = (((1 << last_bit) - 1) ^ ((1 << position) - 1)) <<
93 								(col * 8);
94 
95 		if (set) {
96 			rfb[entry] &= ~mask;
97 			rfb[entry] |= ((data << position) << (col * 8)) & mask;
98 			data >>= (8 - position);
99 		} else {
100 			data |= (((rfb[entry] & mask) >> (col * 8)) >> position)
101 				<< bits_shifted;
102 			bits_shifted += last_bit - position;
103 		}
104 
105 		bits_left -= 8 - position;
106 	}
107 
108 	data = set ? 1 : ath5k_hw_bitswap(data, num_bits);
109 
110 	return data;
111 }
112 
113 /**********************\
114 * RF Gain optimization *
115 \**********************/
116 
117 /*
118  * This code is used to optimize RF gain on different environments
119  * (temperature mostly) based on feedback from a power detector.
120  *
121  * It's only used on RF5111 and RF5112, later RF chips seem to have
122  * auto adjustment on hw -notice they have a much smaller BANK 7 and
123  * no gain optimization ladder-.
124  *
125  * For more infos check out this patent doc
126  * http://www.freepatentsonline.com/7400691.html
127  *
128  * This paper describes power drops as seen on the receiver due to
129  * probe packets
130  * http://www.cnri.dit.ie/publications/ICT08%20-%20Practical%20Issues
131  * %20of%20Power%20Control.pdf
132  *
133  * And this is the MadWiFi bug entry related to the above
134  * http://madwifi-project.org/ticket/1659
135  * with various measurements and diagrams
136  *
137  * TODO: Deal with power drops due to probes by setting an apropriate
138  * tx power on the probe packets ! Make this part of the calibration process.
139  */
140 
141 /* Initialize ah_gain durring attach */
142 int ath5k_hw_rfgain_opt_init(struct ath5k_hw *ah)
143 {
144 	/* Initialize the gain optimization values */
145 	switch (ah->ah_radio) {
146 	case AR5K_RF5111:
147 		ah->ah_gain.g_step_idx = rfgain_opt_5111.go_default;
148 		ah->ah_gain.g_low = 20;
149 		ah->ah_gain.g_high = 35;
150 		ah->ah_gain.g_state = AR5K_RFGAIN_ACTIVE;
151 		break;
152 	case AR5K_RF5112:
153 		ah->ah_gain.g_step_idx = rfgain_opt_5112.go_default;
154 		ah->ah_gain.g_low = 20;
155 		ah->ah_gain.g_high = 85;
156 		ah->ah_gain.g_state = AR5K_RFGAIN_ACTIVE;
157 		break;
158 	default:
159 		return -EINVAL;
160 	}
161 
162 	return 0;
163 }
164 
165 /* Schedule a gain probe check on the next transmited packet.
166  * That means our next packet is going to be sent with lower
167  * tx power and a Peak to Average Power Detector (PAPD) will try
168  * to measure the gain.
169  *
170  * XXX:  How about forcing a tx packet (bypassing PCU arbitrator etc)
171  * just after we enable the probe so that we don't mess with
172  * standard traffic ? Maybe it's time to use sw interrupts and
173  * a probe tasklet !!!
174  */
175 static void ath5k_hw_request_rfgain_probe(struct ath5k_hw *ah)
176 {
177 
178 	/* Skip if gain calibration is inactive or
179 	 * we already handle a probe request */
180 	if (ah->ah_gain.g_state != AR5K_RFGAIN_ACTIVE)
181 		return;
182 
183 	/* Send the packet with 2dB below max power as
184 	 * patent doc suggest */
185 	ath5k_hw_reg_write(ah, AR5K_REG_SM(ah->ah_txpower.txp_ofdm - 4,
186 			AR5K_PHY_PAPD_PROBE_TXPOWER) |
187 			AR5K_PHY_PAPD_PROBE_TX_NEXT, AR5K_PHY_PAPD_PROBE);
188 
189 	ah->ah_gain.g_state = AR5K_RFGAIN_READ_REQUESTED;
190 
191 }
192 
193 /* Calculate gain_F measurement correction
194  * based on the current step for RF5112 rev. 2 */
195 static u32 ath5k_hw_rf_gainf_corr(struct ath5k_hw *ah)
196 {
197 	u32 mix, step;
198 	u32 *rf;
199 	const struct ath5k_gain_opt *go;
200 	const struct ath5k_gain_opt_step *g_step;
201 	const struct ath5k_rf_reg *rf_regs;
202 
203 	/* Only RF5112 Rev. 2 supports it */
204 	if ((ah->ah_radio != AR5K_RF5112) ||
205 	(ah->ah_radio_5ghz_revision <= AR5K_SREV_RAD_5112A))
206 		return 0;
207 
208 	go = &rfgain_opt_5112;
209 	rf_regs = rf_regs_5112a;
210 	ah->ah_rf_regs_count = ARRAY_SIZE(rf_regs_5112a);
211 
212 	g_step = &go->go_step[ah->ah_gain.g_step_idx];
213 
214 	if (ah->ah_rf_banks == NULL)
215 		return 0;
216 
217 	rf = ah->ah_rf_banks;
218 	ah->ah_gain.g_f_corr = 0;
219 
220 	/* No VGA (Variable Gain Amplifier) override, skip */
221 	if (ath5k_hw_rfb_op(ah, rf_regs, 0, AR5K_RF_MIXVGA_OVR, false) != 1)
222 		return 0;
223 
224 	/* Mix gain stepping */
225 	step = ath5k_hw_rfb_op(ah, rf_regs, 0, AR5K_RF_MIXGAIN_STEP, false);
226 
227 	/* Mix gain override */
228 	mix = g_step->gos_param[0];
229 
230 	switch (mix) {
231 	case 3:
232 		ah->ah_gain.g_f_corr = step * 2;
233 		break;
234 	case 2:
235 		ah->ah_gain.g_f_corr = (step - 5) * 2;
236 		break;
237 	case 1:
238 		ah->ah_gain.g_f_corr = step;
239 		break;
240 	default:
241 		ah->ah_gain.g_f_corr = 0;
242 		break;
243 	}
244 
245 	return ah->ah_gain.g_f_corr;
246 }
247 
248 /* Check if current gain_F measurement is in the range of our
249  * power detector windows. If we get a measurement outside range
250  * we know it's not accurate (detectors can't measure anything outside
251  * their detection window) so we must ignore it */
252 static bool ath5k_hw_rf_check_gainf_readback(struct ath5k_hw *ah)
253 {
254 	const struct ath5k_rf_reg *rf_regs;
255 	u32 step, mix_ovr, level[4];
256 	u32 *rf;
257 
258 	if (ah->ah_rf_banks == NULL)
259 		return false;
260 
261 	rf = ah->ah_rf_banks;
262 
263 	if (ah->ah_radio == AR5K_RF5111) {
264 
265 		rf_regs = rf_regs_5111;
266 		ah->ah_rf_regs_count = ARRAY_SIZE(rf_regs_5111);
267 
268 		step = ath5k_hw_rfb_op(ah, rf_regs, 0, AR5K_RF_RFGAIN_STEP,
269 			false);
270 
271 		level[0] = 0;
272 		level[1] = (step == 63) ? 50 : step + 4;
273 		level[2] = (step != 63) ? 64 : level[0];
274 		level[3] = level[2] + 50 ;
275 
276 		ah->ah_gain.g_high = level[3] -
277 			(step == 63 ? AR5K_GAIN_DYN_ADJUST_HI_MARGIN : -5);
278 		ah->ah_gain.g_low = level[0] +
279 			(step == 63 ? AR5K_GAIN_DYN_ADJUST_LO_MARGIN : 0);
280 	} else {
281 
282 		rf_regs = rf_regs_5112;
283 		ah->ah_rf_regs_count = ARRAY_SIZE(rf_regs_5112);
284 
285 		mix_ovr = ath5k_hw_rfb_op(ah, rf_regs, 0, AR5K_RF_MIXVGA_OVR,
286 			false);
287 
288 		level[0] = level[2] = 0;
289 
290 		if (mix_ovr == 1) {
291 			level[1] = level[3] = 83;
292 		} else {
293 			level[1] = level[3] = 107;
294 			ah->ah_gain.g_high = 55;
295 		}
296 	}
297 
298 	return (ah->ah_gain.g_current >= level[0] &&
299 			ah->ah_gain.g_current <= level[1]) ||
300 		(ah->ah_gain.g_current >= level[2] &&
301 			ah->ah_gain.g_current <= level[3]);
302 }
303 
304 /* Perform gain_F adjustment by choosing the right set
305  * of parameters from RF gain optimization ladder */
306 static s8 ath5k_hw_rf_gainf_adjust(struct ath5k_hw *ah)
307 {
308 	const struct ath5k_gain_opt *go;
309 	const struct ath5k_gain_opt_step *g_step;
310 	int ret = 0;
311 
312 	switch (ah->ah_radio) {
313 	case AR5K_RF5111:
314 		go = &rfgain_opt_5111;
315 		break;
316 	case AR5K_RF5112:
317 		go = &rfgain_opt_5112;
318 		break;
319 	default:
320 		return 0;
321 	}
322 
323 	g_step = &go->go_step[ah->ah_gain.g_step_idx];
324 
325 	if (ah->ah_gain.g_current >= ah->ah_gain.g_high) {
326 
327 		/* Reached maximum */
328 		if (ah->ah_gain.g_step_idx == 0)
329 			return -1;
330 
331 		for (ah->ah_gain.g_target = ah->ah_gain.g_current;
332 				ah->ah_gain.g_target >=  ah->ah_gain.g_high &&
333 				ah->ah_gain.g_step_idx > 0;
334 				g_step = &go->go_step[ah->ah_gain.g_step_idx])
335 			ah->ah_gain.g_target -= 2 *
336 			    (go->go_step[--(ah->ah_gain.g_step_idx)].gos_gain -
337 			    g_step->gos_gain);
338 
339 		ret = 1;
340 		goto done;
341 	}
342 
343 	if (ah->ah_gain.g_current <= ah->ah_gain.g_low) {
344 
345 		/* Reached minimum */
346 		if (ah->ah_gain.g_step_idx == (go->go_steps_count - 1))
347 			return -2;
348 
349 		for (ah->ah_gain.g_target = ah->ah_gain.g_current;
350 				ah->ah_gain.g_target <= ah->ah_gain.g_low &&
351 				ah->ah_gain.g_step_idx < go->go_steps_count-1;
352 				g_step = &go->go_step[ah->ah_gain.g_step_idx])
353 			ah->ah_gain.g_target -= 2 *
354 			    (go->go_step[++ah->ah_gain.g_step_idx].gos_gain -
355 			    g_step->gos_gain);
356 
357 		ret = 2;
358 		goto done;
359 	}
360 
361 done:
362 	ATH5K_DBG(ah->ah_sc, ATH5K_DEBUG_CALIBRATE,
363 		"ret %d, gain step %u, current gain %u, target gain %u\n",
364 		ret, ah->ah_gain.g_step_idx, ah->ah_gain.g_current,
365 		ah->ah_gain.g_target);
366 
367 	return ret;
368 }
369 
370 /* Main callback for thermal RF gain calibration engine
371  * Check for a new gain reading and schedule an adjustment
372  * if needed.
373  *
374  * TODO: Use sw interrupt to schedule reset if gain_F needs
375  * adjustment */
376 enum ath5k_rfgain ath5k_hw_gainf_calibrate(struct ath5k_hw *ah)
377 {
378 	u32 data, type;
379 	struct ath5k_eeprom_info *ee = &ah->ah_capabilities.cap_eeprom;
380 
381 	if (ah->ah_rf_banks == NULL ||
382 	ah->ah_gain.g_state == AR5K_RFGAIN_INACTIVE)
383 		return AR5K_RFGAIN_INACTIVE;
384 
385 	/* No check requested, either engine is inactive
386 	 * or an adjustment is already requested */
387 	if (ah->ah_gain.g_state != AR5K_RFGAIN_READ_REQUESTED)
388 		goto done;
389 
390 	/* Read the PAPD (Peak to Average Power Detector)
391 	 * register */
392 	data = ath5k_hw_reg_read(ah, AR5K_PHY_PAPD_PROBE);
393 
394 	/* No probe is scheduled, read gain_F measurement */
395 	if (!(data & AR5K_PHY_PAPD_PROBE_TX_NEXT)) {
396 		ah->ah_gain.g_current = data >> AR5K_PHY_PAPD_PROBE_GAINF_S;
397 		type = AR5K_REG_MS(data, AR5K_PHY_PAPD_PROBE_TYPE);
398 
399 		/* If tx packet is CCK correct the gain_F measurement
400 		 * by cck ofdm gain delta */
401 		if (type == AR5K_PHY_PAPD_PROBE_TYPE_CCK) {
402 			if (ah->ah_radio_5ghz_revision >= AR5K_SREV_RAD_5112A)
403 				ah->ah_gain.g_current +=
404 					ee->ee_cck_ofdm_gain_delta;
405 			else
406 				ah->ah_gain.g_current +=
407 					AR5K_GAIN_CCK_PROBE_CORR;
408 		}
409 
410 		/* Further correct gain_F measurement for
411 		 * RF5112A radios */
412 		if (ah->ah_radio_5ghz_revision >= AR5K_SREV_RAD_5112A) {
413 			ath5k_hw_rf_gainf_corr(ah);
414 			ah->ah_gain.g_current =
415 				ah->ah_gain.g_current >= ah->ah_gain.g_f_corr ?
416 				(ah->ah_gain.g_current-ah->ah_gain.g_f_corr) :
417 				0;
418 		}
419 
420 		/* Check if measurement is ok and if we need
421 		 * to adjust gain, schedule a gain adjustment,
422 		 * else switch back to the acive state */
423 		if (ath5k_hw_rf_check_gainf_readback(ah) &&
424 		AR5K_GAIN_CHECK_ADJUST(&ah->ah_gain) &&
425 		ath5k_hw_rf_gainf_adjust(ah)) {
426 			ah->ah_gain.g_state = AR5K_RFGAIN_NEED_CHANGE;
427 		} else {
428 			ah->ah_gain.g_state = AR5K_RFGAIN_ACTIVE;
429 		}
430 	}
431 
432 done:
433 	return ah->ah_gain.g_state;
434 }
435 
436 /* Write initial RF gain table to set the RF sensitivity
437  * this one works on all RF chips and has nothing to do
438  * with gain_F calibration */
439 int ath5k_hw_rfgain_init(struct ath5k_hw *ah, unsigned int freq)
440 {
441 	const struct ath5k_ini_rfgain *ath5k_rfg;
442 	unsigned int i, size;
443 
444 	switch (ah->ah_radio) {
445 	case AR5K_RF5111:
446 		ath5k_rfg = rfgain_5111;
447 		size = ARRAY_SIZE(rfgain_5111);
448 		break;
449 	case AR5K_RF5112:
450 		ath5k_rfg = rfgain_5112;
451 		size = ARRAY_SIZE(rfgain_5112);
452 		break;
453 	case AR5K_RF2413:
454 		ath5k_rfg = rfgain_2413;
455 		size = ARRAY_SIZE(rfgain_2413);
456 		break;
457 	case AR5K_RF2316:
458 		ath5k_rfg = rfgain_2316;
459 		size = ARRAY_SIZE(rfgain_2316);
460 		break;
461 	case AR5K_RF5413:
462 		ath5k_rfg = rfgain_5413;
463 		size = ARRAY_SIZE(rfgain_5413);
464 		break;
465 	case AR5K_RF2317:
466 	case AR5K_RF2425:
467 		ath5k_rfg = rfgain_2425;
468 		size = ARRAY_SIZE(rfgain_2425);
469 		break;
470 	default:
471 		return -EINVAL;
472 	}
473 
474 	switch (freq) {
475 	case AR5K_INI_RFGAIN_2GHZ:
476 	case AR5K_INI_RFGAIN_5GHZ:
477 		break;
478 	default:
479 		return -EINVAL;
480 	}
481 
482 	for (i = 0; i < size; i++) {
483 		AR5K_REG_WAIT(i);
484 		ath5k_hw_reg_write(ah, ath5k_rfg[i].rfg_value[freq],
485 			(u32)ath5k_rfg[i].rfg_register);
486 	}
487 
488 	return 0;
489 }
490 
491 
492 
493 /********************\
494 * RF Registers setup *
495 \********************/
496 
497 
498 /*
499  * Setup RF registers by writing RF buffer on hw
500  */
501 int ath5k_hw_rfregs_init(struct ath5k_hw *ah, struct ieee80211_channel *channel,
502 		unsigned int mode)
503 {
504 	const struct ath5k_rf_reg *rf_regs;
505 	const struct ath5k_ini_rfbuffer *ini_rfb;
506 	const struct ath5k_gain_opt *go = NULL;
507 	const struct ath5k_gain_opt_step *g_step;
508 	struct ath5k_eeprom_info *ee = &ah->ah_capabilities.cap_eeprom;
509 	u8 ee_mode = 0;
510 	u32 *rfb;
511 	int i, obdb = -1, bank = -1;
512 
513 	switch (ah->ah_radio) {
514 	case AR5K_RF5111:
515 		rf_regs = rf_regs_5111;
516 		ah->ah_rf_regs_count = ARRAY_SIZE(rf_regs_5111);
517 		ini_rfb = rfb_5111;
518 		ah->ah_rf_banks_size = ARRAY_SIZE(rfb_5111);
519 		go = &rfgain_opt_5111;
520 		break;
521 	case AR5K_RF5112:
522 		if (ah->ah_radio_5ghz_revision >= AR5K_SREV_RAD_5112A) {
523 			rf_regs = rf_regs_5112a;
524 			ah->ah_rf_regs_count = ARRAY_SIZE(rf_regs_5112a);
525 			ini_rfb = rfb_5112a;
526 			ah->ah_rf_banks_size = ARRAY_SIZE(rfb_5112a);
527 		} else {
528 			rf_regs = rf_regs_5112;
529 			ah->ah_rf_regs_count = ARRAY_SIZE(rf_regs_5112);
530 			ini_rfb = rfb_5112;
531 			ah->ah_rf_banks_size = ARRAY_SIZE(rfb_5112);
532 		}
533 		go = &rfgain_opt_5112;
534 		break;
535 	case AR5K_RF2413:
536 		rf_regs = rf_regs_2413;
537 		ah->ah_rf_regs_count = ARRAY_SIZE(rf_regs_2413);
538 		ini_rfb = rfb_2413;
539 		ah->ah_rf_banks_size = ARRAY_SIZE(rfb_2413);
540 		break;
541 	case AR5K_RF2316:
542 		rf_regs = rf_regs_2316;
543 		ah->ah_rf_regs_count = ARRAY_SIZE(rf_regs_2316);
544 		ini_rfb = rfb_2316;
545 		ah->ah_rf_banks_size = ARRAY_SIZE(rfb_2316);
546 		break;
547 	case AR5K_RF5413:
548 		rf_regs = rf_regs_5413;
549 		ah->ah_rf_regs_count = ARRAY_SIZE(rf_regs_5413);
550 		ini_rfb = rfb_5413;
551 		ah->ah_rf_banks_size = ARRAY_SIZE(rfb_5413);
552 		break;
553 	case AR5K_RF2317:
554 		rf_regs = rf_regs_2425;
555 		ah->ah_rf_regs_count = ARRAY_SIZE(rf_regs_2425);
556 		ini_rfb = rfb_2317;
557 		ah->ah_rf_banks_size = ARRAY_SIZE(rfb_2317);
558 		break;
559 	case AR5K_RF2425:
560 		rf_regs = rf_regs_2425;
561 		ah->ah_rf_regs_count = ARRAY_SIZE(rf_regs_2425);
562 		if (ah->ah_mac_srev < AR5K_SREV_AR2417) {
563 			ini_rfb = rfb_2425;
564 			ah->ah_rf_banks_size = ARRAY_SIZE(rfb_2425);
565 		} else {
566 			ini_rfb = rfb_2417;
567 			ah->ah_rf_banks_size = ARRAY_SIZE(rfb_2417);
568 		}
569 		break;
570 	default:
571 		return -EINVAL;
572 	}
573 
574 	/* If it's the first time we set RF buffer, allocate
575 	 * ah->ah_rf_banks based on ah->ah_rf_banks_size
576 	 * we set above */
577 	if (ah->ah_rf_banks == NULL) {
578 		ah->ah_rf_banks = kmalloc(sizeof(u32) * ah->ah_rf_banks_size,
579 								GFP_KERNEL);
580 		if (ah->ah_rf_banks == NULL) {
581 			ATH5K_ERR(ah->ah_sc, "out of memory\n");
582 			return -ENOMEM;
583 		}
584 	}
585 
586 	/* Copy values to modify them */
587 	rfb = ah->ah_rf_banks;
588 
589 	for (i = 0; i < ah->ah_rf_banks_size; i++) {
590 		if (ini_rfb[i].rfb_bank >= AR5K_MAX_RF_BANKS) {
591 			ATH5K_ERR(ah->ah_sc, "invalid bank\n");
592 			return -EINVAL;
593 		}
594 
595 		/* Bank changed, write down the offset */
596 		if (bank != ini_rfb[i].rfb_bank) {
597 			bank = ini_rfb[i].rfb_bank;
598 			ah->ah_offset[bank] = i;
599 		}
600 
601 		rfb[i] = ini_rfb[i].rfb_mode_data[mode];
602 	}
603 
604 	/* Set Output and Driver bias current (OB/DB) */
605 	if (channel->hw_value & CHANNEL_2GHZ) {
606 
607 		if (channel->hw_value & CHANNEL_CCK)
608 			ee_mode = AR5K_EEPROM_MODE_11B;
609 		else
610 			ee_mode = AR5K_EEPROM_MODE_11G;
611 
612 		/* For RF511X/RF211X combination we
613 		 * use b_OB and b_DB parameters stored
614 		 * in eeprom on ee->ee_ob[ee_mode][0]
615 		 *
616 		 * For all other chips we use OB/DB for 2Ghz
617 		 * stored in the b/g modal section just like
618 		 * 802.11a on ee->ee_ob[ee_mode][1] */
619 		if ((ah->ah_radio == AR5K_RF5111) ||
620 		(ah->ah_radio == AR5K_RF5112))
621 			obdb = 0;
622 		else
623 			obdb = 1;
624 
625 		ath5k_hw_rfb_op(ah, rf_regs, ee->ee_ob[ee_mode][obdb],
626 						AR5K_RF_OB_2GHZ, true);
627 
628 		ath5k_hw_rfb_op(ah, rf_regs, ee->ee_db[ee_mode][obdb],
629 						AR5K_RF_DB_2GHZ, true);
630 
631 	/* RF5111 always needs OB/DB for 5GHz, even if we use 2GHz */
632 	} else if ((channel->hw_value & CHANNEL_5GHZ) ||
633 			(ah->ah_radio == AR5K_RF5111)) {
634 
635 		/* For 11a, Turbo and XR we need to choose
636 		 * OB/DB based on frequency range */
637 		ee_mode = AR5K_EEPROM_MODE_11A;
638 		obdb =	 channel->center_freq >= 5725 ? 3 :
639 			(channel->center_freq >= 5500 ? 2 :
640 			(channel->center_freq >= 5260 ? 1 :
641 			 (channel->center_freq > 4000 ? 0 : -1)));
642 
643 		if (obdb < 0)
644 			return -EINVAL;
645 
646 		ath5k_hw_rfb_op(ah, rf_regs, ee->ee_ob[ee_mode][obdb],
647 						AR5K_RF_OB_5GHZ, true);
648 
649 		ath5k_hw_rfb_op(ah, rf_regs, ee->ee_db[ee_mode][obdb],
650 						AR5K_RF_DB_5GHZ, true);
651 	}
652 
653 	g_step = &go->go_step[ah->ah_gain.g_step_idx];
654 
655 	/* Bank Modifications (chip-specific) */
656 	if (ah->ah_radio == AR5K_RF5111) {
657 
658 		/* Set gain_F settings according to current step */
659 		if (channel->hw_value & CHANNEL_OFDM) {
660 
661 			AR5K_REG_WRITE_BITS(ah, AR5K_PHY_FRAME_CTL,
662 					AR5K_PHY_FRAME_CTL_TX_CLIP,
663 					g_step->gos_param[0]);
664 
665 			ath5k_hw_rfb_op(ah, rf_regs, g_step->gos_param[1],
666 							AR5K_RF_PWD_90, true);
667 
668 			ath5k_hw_rfb_op(ah, rf_regs, g_step->gos_param[2],
669 							AR5K_RF_PWD_84, true);
670 
671 			ath5k_hw_rfb_op(ah, rf_regs, g_step->gos_param[3],
672 						AR5K_RF_RFGAIN_SEL, true);
673 
674 			/* We programmed gain_F parameters, switch back
675 			 * to active state */
676 			ah->ah_gain.g_state = AR5K_RFGAIN_ACTIVE;
677 
678 		}
679 
680 		/* Bank 6/7 setup */
681 
682 		ath5k_hw_rfb_op(ah, rf_regs, !ee->ee_xpd[ee_mode],
683 						AR5K_RF_PWD_XPD, true);
684 
685 		ath5k_hw_rfb_op(ah, rf_regs, ee->ee_x_gain[ee_mode],
686 						AR5K_RF_XPD_GAIN, true);
687 
688 		ath5k_hw_rfb_op(ah, rf_regs, ee->ee_i_gain[ee_mode],
689 						AR5K_RF_GAIN_I, true);
690 
691 		ath5k_hw_rfb_op(ah, rf_regs, ee->ee_xpd[ee_mode],
692 						AR5K_RF_PLO_SEL, true);
693 
694 		/* TODO: Half/quarter channel support */
695 	}
696 
697 	if (ah->ah_radio == AR5K_RF5112) {
698 
699 		/* Set gain_F settings according to current step */
700 		if (channel->hw_value & CHANNEL_OFDM) {
701 
702 			ath5k_hw_rfb_op(ah, rf_regs, g_step->gos_param[0],
703 						AR5K_RF_MIXGAIN_OVR, true);
704 
705 			ath5k_hw_rfb_op(ah, rf_regs, g_step->gos_param[1],
706 						AR5K_RF_PWD_138, true);
707 
708 			ath5k_hw_rfb_op(ah, rf_regs, g_step->gos_param[2],
709 						AR5K_RF_PWD_137, true);
710 
711 			ath5k_hw_rfb_op(ah, rf_regs, g_step->gos_param[3],
712 						AR5K_RF_PWD_136, true);
713 
714 			ath5k_hw_rfb_op(ah, rf_regs, g_step->gos_param[4],
715 						AR5K_RF_PWD_132, true);
716 
717 			ath5k_hw_rfb_op(ah, rf_regs, g_step->gos_param[5],
718 						AR5K_RF_PWD_131, true);
719 
720 			ath5k_hw_rfb_op(ah, rf_regs, g_step->gos_param[6],
721 						AR5K_RF_PWD_130, true);
722 
723 			/* We programmed gain_F parameters, switch back
724 			 * to active state */
725 			ah->ah_gain.g_state = AR5K_RFGAIN_ACTIVE;
726 		}
727 
728 		/* Bank 6/7 setup */
729 
730 		ath5k_hw_rfb_op(ah, rf_regs, ee->ee_xpd[ee_mode],
731 						AR5K_RF_XPD_SEL, true);
732 
733 		if (ah->ah_radio_5ghz_revision < AR5K_SREV_RAD_5112A) {
734 			/* Rev. 1 supports only one xpd */
735 			ath5k_hw_rfb_op(ah, rf_regs,
736 						ee->ee_x_gain[ee_mode],
737 						AR5K_RF_XPD_GAIN, true);
738 
739 		} else {
740 			u8 *pdg_curve_to_idx = ee->ee_pdc_to_idx[ee_mode];
741 			if (ee->ee_pd_gains[ee_mode] > 1) {
742 				ath5k_hw_rfb_op(ah, rf_regs,
743 						pdg_curve_to_idx[0],
744 						AR5K_RF_PD_GAIN_LO, true);
745 				ath5k_hw_rfb_op(ah, rf_regs,
746 						pdg_curve_to_idx[1],
747 						AR5K_RF_PD_GAIN_HI, true);
748 			} else {
749 				ath5k_hw_rfb_op(ah, rf_regs,
750 						pdg_curve_to_idx[0],
751 						AR5K_RF_PD_GAIN_LO, true);
752 				ath5k_hw_rfb_op(ah, rf_regs,
753 						pdg_curve_to_idx[0],
754 						AR5K_RF_PD_GAIN_HI, true);
755 			}
756 
757 			/* Lower synth voltage on Rev 2 */
758 			ath5k_hw_rfb_op(ah, rf_regs, 2,
759 					AR5K_RF_HIGH_VC_CP, true);
760 
761 			ath5k_hw_rfb_op(ah, rf_regs, 2,
762 					AR5K_RF_MID_VC_CP, true);
763 
764 			ath5k_hw_rfb_op(ah, rf_regs, 2,
765 					AR5K_RF_LOW_VC_CP, true);
766 
767 			ath5k_hw_rfb_op(ah, rf_regs, 2,
768 					AR5K_RF_PUSH_UP, true);
769 
770 			/* Decrease power consumption on 5213+ BaseBand */
771 			if (ah->ah_phy_revision >= AR5K_SREV_PHY_5212A) {
772 				ath5k_hw_rfb_op(ah, rf_regs, 1,
773 						AR5K_RF_PAD2GND, true);
774 
775 				ath5k_hw_rfb_op(ah, rf_regs, 1,
776 						AR5K_RF_XB2_LVL, true);
777 
778 				ath5k_hw_rfb_op(ah, rf_regs, 1,
779 						AR5K_RF_XB5_LVL, true);
780 
781 				ath5k_hw_rfb_op(ah, rf_regs, 1,
782 						AR5K_RF_PWD_167, true);
783 
784 				ath5k_hw_rfb_op(ah, rf_regs, 1,
785 						AR5K_RF_PWD_166, true);
786 			}
787 		}
788 
789 		ath5k_hw_rfb_op(ah, rf_regs, ee->ee_i_gain[ee_mode],
790 						AR5K_RF_GAIN_I, true);
791 
792 		/* TODO: Half/quarter channel support */
793 
794 	}
795 
796 	if (ah->ah_radio == AR5K_RF5413 &&
797 	channel->hw_value & CHANNEL_2GHZ) {
798 
799 		ath5k_hw_rfb_op(ah, rf_regs, 1, AR5K_RF_DERBY_CHAN_SEL_MODE,
800 									true);
801 
802 		/* Set optimum value for early revisions (on pci-e chips) */
803 		if (ah->ah_mac_srev >= AR5K_SREV_AR5424 &&
804 		ah->ah_mac_srev < AR5K_SREV_AR5413)
805 			ath5k_hw_rfb_op(ah, rf_regs, ath5k_hw_bitswap(6, 3),
806 						AR5K_RF_PWD_ICLOBUF_2G, true);
807 
808 	}
809 
810 	/* Write RF banks on hw */
811 	for (i = 0; i < ah->ah_rf_banks_size; i++) {
812 		AR5K_REG_WAIT(i);
813 		ath5k_hw_reg_write(ah, rfb[i], ini_rfb[i].rfb_ctrl_register);
814 	}
815 
816 	return 0;
817 }
818 
819 
820 /**************************\
821   PHY/RF channel functions
822 \**************************/
823 
824 /*
825  * Check if a channel is supported
826  */
827 bool ath5k_channel_ok(struct ath5k_hw *ah, u16 freq, unsigned int flags)
828 {
829 	/* Check if the channel is in our supported range */
830 	if (flags & CHANNEL_2GHZ) {
831 		if ((freq >= ah->ah_capabilities.cap_range.range_2ghz_min) &&
832 		    (freq <= ah->ah_capabilities.cap_range.range_2ghz_max))
833 			return true;
834 	} else if (flags & CHANNEL_5GHZ)
835 		if ((freq >= ah->ah_capabilities.cap_range.range_5ghz_min) &&
836 		    (freq <= ah->ah_capabilities.cap_range.range_5ghz_max))
837 			return true;
838 
839 	return false;
840 }
841 
842 /*
843  * Convertion needed for RF5110
844  */
845 static u32 ath5k_hw_rf5110_chan2athchan(struct ieee80211_channel *channel)
846 {
847 	u32 athchan;
848 
849 	/*
850 	 * Convert IEEE channel/MHz to an internal channel value used
851 	 * by the AR5210 chipset. This has not been verified with
852 	 * newer chipsets like the AR5212A who have a completely
853 	 * different RF/PHY part.
854 	 */
855 	athchan = (ath5k_hw_bitswap(
856 			(ieee80211_frequency_to_channel(
857 				channel->center_freq) - 24) / 2, 5)
858 				<< 1) | (1 << 6) | 0x1;
859 	return athchan;
860 }
861 
862 /*
863  * Set channel on RF5110
864  */
865 static int ath5k_hw_rf5110_channel(struct ath5k_hw *ah,
866 		struct ieee80211_channel *channel)
867 {
868 	u32 data;
869 
870 	/*
871 	 * Set the channel and wait
872 	 */
873 	data = ath5k_hw_rf5110_chan2athchan(channel);
874 	ath5k_hw_reg_write(ah, data, AR5K_RF_BUFFER);
875 	ath5k_hw_reg_write(ah, 0, AR5K_RF_BUFFER_CONTROL_0);
876 	mdelay(1);
877 
878 	return 0;
879 }
880 
881 /*
882  * Convertion needed for 5111
883  */
884 static int ath5k_hw_rf5111_chan2athchan(unsigned int ieee,
885 		struct ath5k_athchan_2ghz *athchan)
886 {
887 	int channel;
888 
889 	/* Cast this value to catch negative channel numbers (>= -19) */
890 	channel = (int)ieee;
891 
892 	/*
893 	 * Map 2GHz IEEE channel to 5GHz Atheros channel
894 	 */
895 	if (channel <= 13) {
896 		athchan->a2_athchan = 115 + channel;
897 		athchan->a2_flags = 0x46;
898 	} else if (channel == 14) {
899 		athchan->a2_athchan = 124;
900 		athchan->a2_flags = 0x44;
901 	} else if (channel >= 15 && channel <= 26) {
902 		athchan->a2_athchan = ((channel - 14) * 4) + 132;
903 		athchan->a2_flags = 0x46;
904 	} else
905 		return -EINVAL;
906 
907 	return 0;
908 }
909 
910 /*
911  * Set channel on 5111
912  */
913 static int ath5k_hw_rf5111_channel(struct ath5k_hw *ah,
914 		struct ieee80211_channel *channel)
915 {
916 	struct ath5k_athchan_2ghz ath5k_channel_2ghz;
917 	unsigned int ath5k_channel =
918 		ieee80211_frequency_to_channel(channel->center_freq);
919 	u32 data0, data1, clock;
920 	int ret;
921 
922 	/*
923 	 * Set the channel on the RF5111 radio
924 	 */
925 	data0 = data1 = 0;
926 
927 	if (channel->hw_value & CHANNEL_2GHZ) {
928 		/* Map 2GHz channel to 5GHz Atheros channel ID */
929 		ret = ath5k_hw_rf5111_chan2athchan(
930 			ieee80211_frequency_to_channel(channel->center_freq),
931 			&ath5k_channel_2ghz);
932 		if (ret)
933 			return ret;
934 
935 		ath5k_channel = ath5k_channel_2ghz.a2_athchan;
936 		data0 = ((ath5k_hw_bitswap(ath5k_channel_2ghz.a2_flags, 8) & 0xff)
937 		    << 5) | (1 << 4);
938 	}
939 
940 	if (ath5k_channel < 145 || !(ath5k_channel & 1)) {
941 		clock = 1;
942 		data1 = ((ath5k_hw_bitswap(ath5k_channel - 24, 8) & 0xff) << 2) |
943 			(clock << 1) | (1 << 10) | 1;
944 	} else {
945 		clock = 0;
946 		data1 = ((ath5k_hw_bitswap((ath5k_channel - 24) / 2, 8) & 0xff)
947 			<< 2) | (clock << 1) | (1 << 10) | 1;
948 	}
949 
950 	ath5k_hw_reg_write(ah, (data1 & 0xff) | ((data0 & 0xff) << 8),
951 			AR5K_RF_BUFFER);
952 	ath5k_hw_reg_write(ah, ((data1 >> 8) & 0xff) | (data0 & 0xff00),
953 			AR5K_RF_BUFFER_CONTROL_3);
954 
955 	return 0;
956 }
957 
958 /*
959  * Set channel on 5112 and newer
960  */
961 static int ath5k_hw_rf5112_channel(struct ath5k_hw *ah,
962 		struct ieee80211_channel *channel)
963 {
964 	u32 data, data0, data1, data2;
965 	u16 c;
966 
967 	data = data0 = data1 = data2 = 0;
968 	c = channel->center_freq;
969 
970 	if (c < 4800) {
971 		if (!((c - 2224) % 5)) {
972 			data0 = ((2 * (c - 704)) - 3040) / 10;
973 			data1 = 1;
974 		} else if (!((c - 2192) % 5)) {
975 			data0 = ((2 * (c - 672)) - 3040) / 10;
976 			data1 = 0;
977 		} else
978 			return -EINVAL;
979 
980 		data0 = ath5k_hw_bitswap((data0 << 2) & 0xff, 8);
981 	} else if ((c % 5) != 2 || c > 5435) {
982 		if (!(c % 20) && c >= 5120) {
983 			data0 = ath5k_hw_bitswap(((c - 4800) / 20 << 2), 8);
984 			data2 = ath5k_hw_bitswap(3, 2);
985 		} else if (!(c % 10)) {
986 			data0 = ath5k_hw_bitswap(((c - 4800) / 10 << 1), 8);
987 			data2 = ath5k_hw_bitswap(2, 2);
988 		} else if (!(c % 5)) {
989 			data0 = ath5k_hw_bitswap((c - 4800) / 5, 8);
990 			data2 = ath5k_hw_bitswap(1, 2);
991 		} else
992 			return -EINVAL;
993 	} else {
994 		data0 = ath5k_hw_bitswap((10 * (c - 2 - 4800)) / 25 + 1, 8);
995 		data2 = ath5k_hw_bitswap(0, 2);
996 	}
997 
998 	data = (data0 << 4) | (data1 << 1) | (data2 << 2) | 0x1001;
999 
1000 	ath5k_hw_reg_write(ah, data & 0xff, AR5K_RF_BUFFER);
1001 	ath5k_hw_reg_write(ah, (data >> 8) & 0x7f, AR5K_RF_BUFFER_CONTROL_5);
1002 
1003 	return 0;
1004 }
1005 
1006 /*
1007  * Set the channel on the RF2425
1008  */
1009 static int ath5k_hw_rf2425_channel(struct ath5k_hw *ah,
1010 		struct ieee80211_channel *channel)
1011 {
1012 	u32 data, data0, data2;
1013 	u16 c;
1014 
1015 	data = data0 = data2 = 0;
1016 	c = channel->center_freq;
1017 
1018 	if (c < 4800) {
1019 		data0 = ath5k_hw_bitswap((c - 2272), 8);
1020 		data2 = 0;
1021 	/* ? 5GHz ? */
1022 	} else if ((c % 5) != 2 || c > 5435) {
1023 		if (!(c % 20) && c < 5120)
1024 			data0 = ath5k_hw_bitswap(((c - 4800) / 20 << 2), 8);
1025 		else if (!(c % 10))
1026 			data0 = ath5k_hw_bitswap(((c - 4800) / 10 << 1), 8);
1027 		else if (!(c % 5))
1028 			data0 = ath5k_hw_bitswap((c - 4800) / 5, 8);
1029 		else
1030 			return -EINVAL;
1031 		data2 = ath5k_hw_bitswap(1, 2);
1032 	} else {
1033 		data0 = ath5k_hw_bitswap((10 * (c - 2 - 4800)) / 25 + 1, 8);
1034 		data2 = ath5k_hw_bitswap(0, 2);
1035 	}
1036 
1037 	data = (data0 << 4) | data2 << 2 | 0x1001;
1038 
1039 	ath5k_hw_reg_write(ah, data & 0xff, AR5K_RF_BUFFER);
1040 	ath5k_hw_reg_write(ah, (data >> 8) & 0x7f, AR5K_RF_BUFFER_CONTROL_5);
1041 
1042 	return 0;
1043 }
1044 
1045 /*
1046  * Set a channel on the radio chip
1047  */
1048 int ath5k_hw_channel(struct ath5k_hw *ah, struct ieee80211_channel *channel)
1049 {
1050 	int ret;
1051 	/*
1052 	 * Check bounds supported by the PHY (we don't care about regultory
1053 	 * restrictions at this point). Note: hw_value already has the band
1054 	 * (CHANNEL_2GHZ, or CHANNEL_5GHZ) so we inform ath5k_channel_ok()
1055 	 * of the band by that */
1056 	if (!ath5k_channel_ok(ah, channel->center_freq, channel->hw_value)) {
1057 		ATH5K_ERR(ah->ah_sc,
1058 			"channel frequency (%u MHz) out of supported "
1059 			"band range\n",
1060 			channel->center_freq);
1061 			return -EINVAL;
1062 	}
1063 
1064 	/*
1065 	 * Set the channel and wait
1066 	 */
1067 	switch (ah->ah_radio) {
1068 	case AR5K_RF5110:
1069 		ret = ath5k_hw_rf5110_channel(ah, channel);
1070 		break;
1071 	case AR5K_RF5111:
1072 		ret = ath5k_hw_rf5111_channel(ah, channel);
1073 		break;
1074 	case AR5K_RF2425:
1075 		ret = ath5k_hw_rf2425_channel(ah, channel);
1076 		break;
1077 	default:
1078 		ret = ath5k_hw_rf5112_channel(ah, channel);
1079 		break;
1080 	}
1081 
1082 	if (ret)
1083 		return ret;
1084 
1085 	/* Set JAPAN setting for channel 14 */
1086 	if (channel->center_freq == 2484) {
1087 		AR5K_REG_ENABLE_BITS(ah, AR5K_PHY_CCKTXCTL,
1088 				AR5K_PHY_CCKTXCTL_JAPAN);
1089 	} else {
1090 		AR5K_REG_ENABLE_BITS(ah, AR5K_PHY_CCKTXCTL,
1091 				AR5K_PHY_CCKTXCTL_WORLD);
1092 	}
1093 
1094 	ah->ah_current_channel = channel;
1095 	ah->ah_turbo = channel->hw_value == CHANNEL_T ? true : false;
1096 	ath5k_hw_set_clockrate(ah);
1097 
1098 	return 0;
1099 }
1100 
1101 /*****************\
1102   PHY calibration
1103 \*****************/
1104 
1105 static int sign_extend(int val, const int nbits)
1106 {
1107 	int order = BIT(nbits-1);
1108 	return (val ^ order) - order;
1109 }
1110 
1111 static s32 ath5k_hw_read_measured_noise_floor(struct ath5k_hw *ah)
1112 {
1113 	s32 val;
1114 
1115 	val = ath5k_hw_reg_read(ah, AR5K_PHY_NF);
1116 	return sign_extend(AR5K_REG_MS(val, AR5K_PHY_NF_MINCCA_PWR), 9);
1117 }
1118 
1119 void ath5k_hw_init_nfcal_hist(struct ath5k_hw *ah)
1120 {
1121 	int i;
1122 
1123 	ah->ah_nfcal_hist.index = 0;
1124 	for (i = 0; i < ATH5K_NF_CAL_HIST_MAX; i++)
1125 		ah->ah_nfcal_hist.nfval[i] = AR5K_TUNE_CCA_MAX_GOOD_VALUE;
1126 }
1127 
1128 static void ath5k_hw_update_nfcal_hist(struct ath5k_hw *ah, s16 noise_floor)
1129 {
1130 	struct ath5k_nfcal_hist *hist = &ah->ah_nfcal_hist;
1131 	hist->index = (hist->index + 1) & (ATH5K_NF_CAL_HIST_MAX-1);
1132 	hist->nfval[hist->index] = noise_floor;
1133 }
1134 
1135 static s16 ath5k_hw_get_median_noise_floor(struct ath5k_hw *ah)
1136 {
1137 	s16 sort[ATH5K_NF_CAL_HIST_MAX];
1138 	s16 tmp;
1139 	int i, j;
1140 
1141 	memcpy(sort, ah->ah_nfcal_hist.nfval, sizeof(sort));
1142 	for (i = 0; i < ATH5K_NF_CAL_HIST_MAX - 1; i++) {
1143 		for (j = 1; j < ATH5K_NF_CAL_HIST_MAX - i; j++) {
1144 			if (sort[j] > sort[j-1]) {
1145 				tmp = sort[j];
1146 				sort[j] = sort[j-1];
1147 				sort[j-1] = tmp;
1148 			}
1149 		}
1150 	}
1151 	for (i = 0; i < ATH5K_NF_CAL_HIST_MAX; i++) {
1152 		ATH5K_DBG(ah->ah_sc, ATH5K_DEBUG_CALIBRATE,
1153 			"cal %d:%d\n", i, sort[i]);
1154 	}
1155 	return sort[(ATH5K_NF_CAL_HIST_MAX-1) / 2];
1156 }
1157 
1158 /*
1159  * When we tell the hardware to perform a noise floor calibration
1160  * by setting the AR5K_PHY_AGCCTL_NF bit, it will periodically
1161  * sample-and-hold the minimum noise level seen at the antennas.
1162  * This value is then stored in a ring buffer of recently measured
1163  * noise floor values so we have a moving window of the last few
1164  * samples.
1165  *
1166  * The median of the values in the history is then loaded into the
1167  * hardware for its own use for RSSI and CCA measurements.
1168  */
1169 void ath5k_hw_update_noise_floor(struct ath5k_hw *ah)
1170 {
1171 	struct ath5k_eeprom_info *ee = &ah->ah_capabilities.cap_eeprom;
1172 	u32 val;
1173 	s16 nf, threshold;
1174 	u8 ee_mode;
1175 
1176 	/* keep last value if calibration hasn't completed */
1177 	if (ath5k_hw_reg_read(ah, AR5K_PHY_AGCCTL) & AR5K_PHY_AGCCTL_NF) {
1178 		ATH5K_DBG(ah->ah_sc, ATH5K_DEBUG_CALIBRATE,
1179 			"NF did not complete in calibration window\n");
1180 
1181 		return;
1182 	}
1183 
1184 	switch (ah->ah_current_channel->hw_value & CHANNEL_MODES) {
1185 	case CHANNEL_A:
1186 	case CHANNEL_T:
1187 	case CHANNEL_XR:
1188 		ee_mode = AR5K_EEPROM_MODE_11A;
1189 		break;
1190 	case CHANNEL_G:
1191 	case CHANNEL_TG:
1192 		ee_mode = AR5K_EEPROM_MODE_11G;
1193 		break;
1194 	default:
1195 	case CHANNEL_B:
1196 		ee_mode = AR5K_EEPROM_MODE_11B;
1197 		break;
1198 	}
1199 
1200 
1201 	/* completed NF calibration, test threshold */
1202 	nf = ath5k_hw_read_measured_noise_floor(ah);
1203 	threshold = ee->ee_noise_floor_thr[ee_mode];
1204 
1205 	if (nf > threshold) {
1206 		ATH5K_DBG(ah->ah_sc, ATH5K_DEBUG_CALIBRATE,
1207 			"noise floor failure detected; "
1208 			"read %d, threshold %d\n",
1209 			nf, threshold);
1210 
1211 		nf = AR5K_TUNE_CCA_MAX_GOOD_VALUE;
1212 	}
1213 
1214 	ath5k_hw_update_nfcal_hist(ah, nf);
1215 	nf = ath5k_hw_get_median_noise_floor(ah);
1216 
1217 	/* load noise floor (in .5 dBm) so the hardware will use it */
1218 	val = ath5k_hw_reg_read(ah, AR5K_PHY_NF) & ~AR5K_PHY_NF_M;
1219 	val |= (nf * 2) & AR5K_PHY_NF_M;
1220 	ath5k_hw_reg_write(ah, val, AR5K_PHY_NF);
1221 
1222 	AR5K_REG_MASKED_BITS(ah, AR5K_PHY_AGCCTL, AR5K_PHY_AGCCTL_NF,
1223 		~(AR5K_PHY_AGCCTL_NF_EN | AR5K_PHY_AGCCTL_NF_NOUPDATE));
1224 
1225 	ath5k_hw_register_timeout(ah, AR5K_PHY_AGCCTL, AR5K_PHY_AGCCTL_NF,
1226 		0, false);
1227 
1228 	/*
1229 	 * Load a high max CCA Power value (-50 dBm in .5 dBm units)
1230 	 * so that we're not capped by the median we just loaded.
1231 	 * This will be used as the initial value for the next noise
1232 	 * floor calibration.
1233 	 */
1234 	val = (val & ~AR5K_PHY_NF_M) | ((-50 * 2) & AR5K_PHY_NF_M);
1235 	ath5k_hw_reg_write(ah, val, AR5K_PHY_NF);
1236 	AR5K_REG_ENABLE_BITS(ah, AR5K_PHY_AGCCTL,
1237 		AR5K_PHY_AGCCTL_NF_EN |
1238 		AR5K_PHY_AGCCTL_NF_NOUPDATE |
1239 		AR5K_PHY_AGCCTL_NF);
1240 
1241 	ah->ah_noise_floor = nf;
1242 
1243 	ATH5K_DBG(ah->ah_sc, ATH5K_DEBUG_CALIBRATE,
1244 		"noise floor calibrated: %d\n", nf);
1245 }
1246 
1247 /*
1248  * Perform a PHY calibration on RF5110
1249  * -Fix BPSK/QAM Constellation (I/Q correction)
1250  */
1251 static int ath5k_hw_rf5110_calibrate(struct ath5k_hw *ah,
1252 		struct ieee80211_channel *channel)
1253 {
1254 	u32 phy_sig, phy_agc, phy_sat, beacon;
1255 	int ret;
1256 
1257 	/*
1258 	 * Disable beacons and RX/TX queues, wait
1259 	 */
1260 	AR5K_REG_ENABLE_BITS(ah, AR5K_DIAG_SW_5210,
1261 		AR5K_DIAG_SW_DIS_TX_5210 | AR5K_DIAG_SW_DIS_RX_5210);
1262 	beacon = ath5k_hw_reg_read(ah, AR5K_BEACON_5210);
1263 	ath5k_hw_reg_write(ah, beacon & ~AR5K_BEACON_ENABLE, AR5K_BEACON_5210);
1264 
1265 	mdelay(2);
1266 
1267 	/*
1268 	 * Set the channel (with AGC turned off)
1269 	 */
1270 	AR5K_REG_ENABLE_BITS(ah, AR5K_PHY_AGC, AR5K_PHY_AGC_DISABLE);
1271 	udelay(10);
1272 	ret = ath5k_hw_channel(ah, channel);
1273 
1274 	/*
1275 	 * Activate PHY and wait
1276 	 */
1277 	ath5k_hw_reg_write(ah, AR5K_PHY_ACT_ENABLE, AR5K_PHY_ACT);
1278 	mdelay(1);
1279 
1280 	AR5K_REG_DISABLE_BITS(ah, AR5K_PHY_AGC, AR5K_PHY_AGC_DISABLE);
1281 
1282 	if (ret)
1283 		return ret;
1284 
1285 	/*
1286 	 * Calibrate the radio chip
1287 	 */
1288 
1289 	/* Remember normal state */
1290 	phy_sig = ath5k_hw_reg_read(ah, AR5K_PHY_SIG);
1291 	phy_agc = ath5k_hw_reg_read(ah, AR5K_PHY_AGCCOARSE);
1292 	phy_sat = ath5k_hw_reg_read(ah, AR5K_PHY_ADCSAT);
1293 
1294 	/* Update radio registers */
1295 	ath5k_hw_reg_write(ah, (phy_sig & ~(AR5K_PHY_SIG_FIRPWR)) |
1296 		AR5K_REG_SM(-1, AR5K_PHY_SIG_FIRPWR), AR5K_PHY_SIG);
1297 
1298 	ath5k_hw_reg_write(ah, (phy_agc & ~(AR5K_PHY_AGCCOARSE_HI |
1299 			AR5K_PHY_AGCCOARSE_LO)) |
1300 		AR5K_REG_SM(-1, AR5K_PHY_AGCCOARSE_HI) |
1301 		AR5K_REG_SM(-127, AR5K_PHY_AGCCOARSE_LO), AR5K_PHY_AGCCOARSE);
1302 
1303 	ath5k_hw_reg_write(ah, (phy_sat & ~(AR5K_PHY_ADCSAT_ICNT |
1304 			AR5K_PHY_ADCSAT_THR)) |
1305 		AR5K_REG_SM(2, AR5K_PHY_ADCSAT_ICNT) |
1306 		AR5K_REG_SM(12, AR5K_PHY_ADCSAT_THR), AR5K_PHY_ADCSAT);
1307 
1308 	udelay(20);
1309 
1310 	AR5K_REG_ENABLE_BITS(ah, AR5K_PHY_AGC, AR5K_PHY_AGC_DISABLE);
1311 	udelay(10);
1312 	ath5k_hw_reg_write(ah, AR5K_PHY_RFSTG_DISABLE, AR5K_PHY_RFSTG);
1313 	AR5K_REG_DISABLE_BITS(ah, AR5K_PHY_AGC, AR5K_PHY_AGC_DISABLE);
1314 
1315 	mdelay(1);
1316 
1317 	/*
1318 	 * Enable calibration and wait until completion
1319 	 */
1320 	AR5K_REG_ENABLE_BITS(ah, AR5K_PHY_AGCCTL, AR5K_PHY_AGCCTL_CAL);
1321 
1322 	ret = ath5k_hw_register_timeout(ah, AR5K_PHY_AGCCTL,
1323 			AR5K_PHY_AGCCTL_CAL, 0, false);
1324 
1325 	/* Reset to normal state */
1326 	ath5k_hw_reg_write(ah, phy_sig, AR5K_PHY_SIG);
1327 	ath5k_hw_reg_write(ah, phy_agc, AR5K_PHY_AGCCOARSE);
1328 	ath5k_hw_reg_write(ah, phy_sat, AR5K_PHY_ADCSAT);
1329 
1330 	if (ret) {
1331 		ATH5K_ERR(ah->ah_sc, "calibration timeout (%uMHz)\n",
1332 				channel->center_freq);
1333 		return ret;
1334 	}
1335 
1336 	/*
1337 	 * Re-enable RX/TX and beacons
1338 	 */
1339 	AR5K_REG_DISABLE_BITS(ah, AR5K_DIAG_SW_5210,
1340 		AR5K_DIAG_SW_DIS_TX_5210 | AR5K_DIAG_SW_DIS_RX_5210);
1341 	ath5k_hw_reg_write(ah, beacon, AR5K_BEACON_5210);
1342 
1343 	return 0;
1344 }
1345 
1346 /*
1347  * Perform I/Q calibration on RF5111/5112 and newer chips
1348  */
1349 static int
1350 ath5k_hw_rf511x_iq_calibrate(struct ath5k_hw *ah)
1351 {
1352 	u32 i_pwr, q_pwr;
1353 	s32 iq_corr, i_coff, i_coffd, q_coff, q_coffd;
1354 	int i;
1355 
1356 	if (!ah->ah_calibration ||
1357 		ath5k_hw_reg_read(ah, AR5K_PHY_IQ) & AR5K_PHY_IQ_RUN)
1358 		return 0;
1359 
1360 	/* Calibration has finished, get the results and re-run */
1361 	/* work around empty results which can apparently happen on 5212 */
1362 	for (i = 0; i <= 10; i++) {
1363 		iq_corr = ath5k_hw_reg_read(ah, AR5K_PHY_IQRES_CAL_CORR);
1364 		i_pwr = ath5k_hw_reg_read(ah, AR5K_PHY_IQRES_CAL_PWR_I);
1365 		q_pwr = ath5k_hw_reg_read(ah, AR5K_PHY_IQRES_CAL_PWR_Q);
1366 		ATH5K_DBG_UNLIMIT(ah->ah_sc, ATH5K_DEBUG_CALIBRATE,
1367 			"iq_corr:%x i_pwr:%x q_pwr:%x", iq_corr, i_pwr, q_pwr);
1368 		if (i_pwr && q_pwr)
1369 			break;
1370 	}
1371 
1372 	i_coffd = ((i_pwr >> 1) + (q_pwr >> 1)) >> 7;
1373 
1374 	if (ah->ah_version == AR5K_AR5211)
1375 		q_coffd = q_pwr >> 6;
1376 	else
1377 		q_coffd = q_pwr >> 7;
1378 
1379 	/* protect against divide by 0 and loss of sign bits */
1380 	if (i_coffd == 0 || q_coffd < 2)
1381 		return 0;
1382 
1383 	i_coff = (-iq_corr) / i_coffd;
1384 	i_coff = clamp(i_coff, -32, 31); /* signed 6 bit */
1385 
1386 	if (ah->ah_version == AR5K_AR5211)
1387 		q_coff = (i_pwr / q_coffd) - 64;
1388 	else
1389 		q_coff = (i_pwr / q_coffd) - 128;
1390 	q_coff = clamp(q_coff, -16, 15); /* signed 5 bit */
1391 
1392 	ATH5K_DBG_UNLIMIT(ah->ah_sc, ATH5K_DEBUG_CALIBRATE,
1393 			"new I:%d Q:%d (i_coffd:%x q_coffd:%x)",
1394 			i_coff, q_coff, i_coffd, q_coffd);
1395 
1396 	/* Commit new I/Q values (set enable bit last to match HAL sources) */
1397 	AR5K_REG_WRITE_BITS(ah, AR5K_PHY_IQ, AR5K_PHY_IQ_CORR_Q_I_COFF, i_coff);
1398 	AR5K_REG_WRITE_BITS(ah, AR5K_PHY_IQ, AR5K_PHY_IQ_CORR_Q_Q_COFF, q_coff);
1399 	AR5K_REG_ENABLE_BITS(ah, AR5K_PHY_IQ, AR5K_PHY_IQ_CORR_ENABLE);
1400 
1401 	/* Re-enable calibration -if we don't we'll commit
1402 	 * the same values again and again */
1403 	AR5K_REG_WRITE_BITS(ah, AR5K_PHY_IQ,
1404 			AR5K_PHY_IQ_CAL_NUM_LOG_MAX, 15);
1405 	AR5K_REG_ENABLE_BITS(ah, AR5K_PHY_IQ, AR5K_PHY_IQ_RUN);
1406 
1407 	return 0;
1408 }
1409 
1410 /*
1411  * Perform a PHY calibration
1412  */
1413 int ath5k_hw_phy_calibrate(struct ath5k_hw *ah,
1414 		struct ieee80211_channel *channel)
1415 {
1416 	int ret;
1417 
1418 	if (ah->ah_radio == AR5K_RF5110)
1419 		ret = ath5k_hw_rf5110_calibrate(ah, channel);
1420 	else {
1421 		ret = ath5k_hw_rf511x_iq_calibrate(ah);
1422 		ath5k_hw_request_rfgain_probe(ah);
1423 	}
1424 
1425 	return ret;
1426 }
1427 
1428 /***************************\
1429 * Spur mitigation functions *
1430 \***************************/
1431 
1432 bool ath5k_hw_chan_has_spur_noise(struct ath5k_hw *ah,
1433 				struct ieee80211_channel *channel)
1434 {
1435 	u8 refclk_freq;
1436 
1437 	if ((ah->ah_radio == AR5K_RF5112) ||
1438 	(ah->ah_radio == AR5K_RF5413) ||
1439 	(ah->ah_mac_version == (AR5K_SREV_AR2417 >> 4)))
1440 		refclk_freq = 40;
1441 	else
1442 		refclk_freq = 32;
1443 
1444 	if ((channel->center_freq % refclk_freq != 0) &&
1445 	((channel->center_freq % refclk_freq < 10) ||
1446 	(channel->center_freq % refclk_freq > 22)))
1447 		return true;
1448 	else
1449 		return false;
1450 }
1451 
1452 void
1453 ath5k_hw_set_spur_mitigation_filter(struct ath5k_hw *ah,
1454 				struct ieee80211_channel *channel)
1455 {
1456 	struct ath5k_eeprom_info *ee = &ah->ah_capabilities.cap_eeprom;
1457 	u32 mag_mask[4] = {0, 0, 0, 0};
1458 	u32 pilot_mask[2] = {0, 0};
1459 	/* Note: fbin values are scaled up by 2 */
1460 	u16 spur_chan_fbin, chan_fbin, symbol_width, spur_detection_window;
1461 	s32 spur_delta_phase, spur_freq_sigma_delta;
1462 	s32 spur_offset, num_symbols_x16;
1463 	u8 num_symbol_offsets, i, freq_band;
1464 
1465 	/* Convert current frequency to fbin value (the same way channels
1466 	 * are stored on EEPROM, check out ath5k_eeprom_bin2freq) and scale
1467 	 * up by 2 so we can compare it later */
1468 	if (channel->hw_value & CHANNEL_2GHZ) {
1469 		chan_fbin = (channel->center_freq - 2300) * 10;
1470 		freq_band = AR5K_EEPROM_BAND_2GHZ;
1471 	} else {
1472 		chan_fbin = (channel->center_freq - 4900) * 10;
1473 		freq_band = AR5K_EEPROM_BAND_5GHZ;
1474 	}
1475 
1476 	/* Check if any spur_chan_fbin from EEPROM is
1477 	 * within our current channel's spur detection range */
1478 	spur_chan_fbin = AR5K_EEPROM_NO_SPUR;
1479 	spur_detection_window = AR5K_SPUR_CHAN_WIDTH;
1480 	/* XXX: Half/Quarter channels ?*/
1481 	if (channel->hw_value & CHANNEL_TURBO)
1482 		spur_detection_window *= 2;
1483 
1484 	for (i = 0; i < AR5K_EEPROM_N_SPUR_CHANS; i++) {
1485 		spur_chan_fbin = ee->ee_spur_chans[i][freq_band];
1486 
1487 		/* Note: mask cleans AR5K_EEPROM_NO_SPUR flag
1488 		 * so it's zero if we got nothing from EEPROM */
1489 		if (spur_chan_fbin == AR5K_EEPROM_NO_SPUR) {
1490 			spur_chan_fbin &= AR5K_EEPROM_SPUR_CHAN_MASK;
1491 			break;
1492 		}
1493 
1494 		if ((chan_fbin - spur_detection_window <=
1495 		(spur_chan_fbin & AR5K_EEPROM_SPUR_CHAN_MASK)) &&
1496 		(chan_fbin + spur_detection_window >=
1497 		(spur_chan_fbin & AR5K_EEPROM_SPUR_CHAN_MASK))) {
1498 			spur_chan_fbin &= AR5K_EEPROM_SPUR_CHAN_MASK;
1499 			break;
1500 		}
1501 	}
1502 
1503 	/* We need to enable spur filter for this channel */
1504 	if (spur_chan_fbin) {
1505 		spur_offset = spur_chan_fbin - chan_fbin;
1506 		/*
1507 		 * Calculate deltas:
1508 		 * spur_freq_sigma_delta -> spur_offset / sample_freq << 21
1509 		 * spur_delta_phase -> spur_offset / chip_freq << 11
1510 		 * Note: Both values have 100KHz resolution
1511 		 */
1512 		/* XXX: Half/Quarter rate channels ? */
1513 		switch (channel->hw_value) {
1514 		case CHANNEL_A:
1515 			/* Both sample_freq and chip_freq are 40MHz */
1516 			spur_delta_phase = (spur_offset << 17) / 25;
1517 			spur_freq_sigma_delta = (spur_delta_phase >> 10);
1518 			symbol_width = AR5K_SPUR_SYMBOL_WIDTH_BASE_100Hz;
1519 			break;
1520 		case CHANNEL_G:
1521 			/* sample_freq -> 40MHz chip_freq -> 44MHz
1522 			 * (for b compatibility) */
1523 			spur_freq_sigma_delta = (spur_offset << 8) / 55;
1524 			spur_delta_phase = (spur_offset << 17) / 25;
1525 			symbol_width = AR5K_SPUR_SYMBOL_WIDTH_BASE_100Hz;
1526 			break;
1527 		case CHANNEL_T:
1528 		case CHANNEL_TG:
1529 			/* Both sample_freq and chip_freq are 80MHz */
1530 			spur_delta_phase = (spur_offset << 16) / 25;
1531 			spur_freq_sigma_delta = (spur_delta_phase >> 10);
1532 			symbol_width = AR5K_SPUR_SYMBOL_WIDTH_TURBO_100Hz;
1533 			break;
1534 		default:
1535 			return;
1536 		}
1537 
1538 		/* Calculate pilot and magnitude masks */
1539 
1540 		/* Scale up spur_offset by 1000 to switch to 100HZ resolution
1541 		 * and divide by symbol_width to find how many symbols we have
1542 		 * Note: number of symbols is scaled up by 16 */
1543 		num_symbols_x16 = ((spur_offset * 1000) << 4) / symbol_width;
1544 
1545 		/* Spur is on a symbol if num_symbols_x16 % 16 is zero */
1546 		if (!(num_symbols_x16 & 0xF))
1547 			/* _X_ */
1548 			num_symbol_offsets = 3;
1549 		else
1550 			/* _xx_ */
1551 			num_symbol_offsets = 4;
1552 
1553 		for (i = 0; i < num_symbol_offsets; i++) {
1554 
1555 			/* Calculate pilot mask */
1556 			s32 curr_sym_off =
1557 				(num_symbols_x16 / 16) + i + 25;
1558 
1559 			/* Pilot magnitude mask seems to be a way to
1560 			 * declare the boundaries for our detection
1561 			 * window or something, it's 2 for the middle
1562 			 * value(s) where the symbol is expected to be
1563 			 * and 1 on the boundary values */
1564 			u8 plt_mag_map =
1565 				(i == 0 || i == (num_symbol_offsets - 1))
1566 								? 1 : 2;
1567 
1568 			if (curr_sym_off >= 0 && curr_sym_off <= 32) {
1569 				if (curr_sym_off <= 25)
1570 					pilot_mask[0] |= 1 << curr_sym_off;
1571 				else if (curr_sym_off >= 27)
1572 					pilot_mask[0] |= 1 << (curr_sym_off - 1);
1573 			} else if (curr_sym_off >= 33 && curr_sym_off <= 52)
1574 				pilot_mask[1] |= 1 << (curr_sym_off - 33);
1575 
1576 			/* Calculate magnitude mask (for viterbi decoder) */
1577 			if (curr_sym_off >= -1 && curr_sym_off <= 14)
1578 				mag_mask[0] |=
1579 					plt_mag_map << (curr_sym_off + 1) * 2;
1580 			else if (curr_sym_off >= 15 && curr_sym_off <= 30)
1581 				mag_mask[1] |=
1582 					plt_mag_map << (curr_sym_off - 15) * 2;
1583 			else if (curr_sym_off >= 31 && curr_sym_off <= 46)
1584 				mag_mask[2] |=
1585 					plt_mag_map << (curr_sym_off - 31) * 2;
1586 			else if (curr_sym_off >= 47 && curr_sym_off <= 53)
1587 				mag_mask[3] |=
1588 					plt_mag_map << (curr_sym_off - 47) * 2;
1589 
1590 		}
1591 
1592 		/* Write settings on hw to enable spur filter */
1593 		AR5K_REG_WRITE_BITS(ah, AR5K_PHY_BIN_MASK_CTL,
1594 					AR5K_PHY_BIN_MASK_CTL_RATE, 0xff);
1595 		/* XXX: Self correlator also ? */
1596 		AR5K_REG_ENABLE_BITS(ah, AR5K_PHY_IQ,
1597 					AR5K_PHY_IQ_PILOT_MASK_EN |
1598 					AR5K_PHY_IQ_CHAN_MASK_EN |
1599 					AR5K_PHY_IQ_SPUR_FILT_EN);
1600 
1601 		/* Set delta phase and freq sigma delta */
1602 		ath5k_hw_reg_write(ah,
1603 				AR5K_REG_SM(spur_delta_phase,
1604 					AR5K_PHY_TIMING_11_SPUR_DELTA_PHASE) |
1605 				AR5K_REG_SM(spur_freq_sigma_delta,
1606 				AR5K_PHY_TIMING_11_SPUR_FREQ_SD) |
1607 				AR5K_PHY_TIMING_11_USE_SPUR_IN_AGC,
1608 				AR5K_PHY_TIMING_11);
1609 
1610 		/* Write pilot masks */
1611 		ath5k_hw_reg_write(ah, pilot_mask[0], AR5K_PHY_TIMING_7);
1612 		AR5K_REG_WRITE_BITS(ah, AR5K_PHY_TIMING_8,
1613 					AR5K_PHY_TIMING_8_PILOT_MASK_2,
1614 					pilot_mask[1]);
1615 
1616 		ath5k_hw_reg_write(ah, pilot_mask[0], AR5K_PHY_TIMING_9);
1617 		AR5K_REG_WRITE_BITS(ah, AR5K_PHY_TIMING_10,
1618 					AR5K_PHY_TIMING_10_PILOT_MASK_2,
1619 					pilot_mask[1]);
1620 
1621 		/* Write magnitude masks */
1622 		ath5k_hw_reg_write(ah, mag_mask[0], AR5K_PHY_BIN_MASK_1);
1623 		ath5k_hw_reg_write(ah, mag_mask[1], AR5K_PHY_BIN_MASK_2);
1624 		ath5k_hw_reg_write(ah, mag_mask[2], AR5K_PHY_BIN_MASK_3);
1625 		AR5K_REG_WRITE_BITS(ah, AR5K_PHY_BIN_MASK_CTL,
1626 					AR5K_PHY_BIN_MASK_CTL_MASK_4,
1627 					mag_mask[3]);
1628 
1629 		ath5k_hw_reg_write(ah, mag_mask[0], AR5K_PHY_BIN_MASK2_1);
1630 		ath5k_hw_reg_write(ah, mag_mask[1], AR5K_PHY_BIN_MASK2_2);
1631 		ath5k_hw_reg_write(ah, mag_mask[2], AR5K_PHY_BIN_MASK2_3);
1632 		AR5K_REG_WRITE_BITS(ah, AR5K_PHY_BIN_MASK2_4,
1633 					AR5K_PHY_BIN_MASK2_4_MASK_4,
1634 					mag_mask[3]);
1635 
1636 	} else if (ath5k_hw_reg_read(ah, AR5K_PHY_IQ) &
1637 	AR5K_PHY_IQ_SPUR_FILT_EN) {
1638 		/* Clean up spur mitigation settings and disable fliter */
1639 		AR5K_REG_WRITE_BITS(ah, AR5K_PHY_BIN_MASK_CTL,
1640 					AR5K_PHY_BIN_MASK_CTL_RATE, 0);
1641 		AR5K_REG_DISABLE_BITS(ah, AR5K_PHY_IQ,
1642 					AR5K_PHY_IQ_PILOT_MASK_EN |
1643 					AR5K_PHY_IQ_CHAN_MASK_EN |
1644 					AR5K_PHY_IQ_SPUR_FILT_EN);
1645 		ath5k_hw_reg_write(ah, 0, AR5K_PHY_TIMING_11);
1646 
1647 		/* Clear pilot masks */
1648 		ath5k_hw_reg_write(ah, 0, AR5K_PHY_TIMING_7);
1649 		AR5K_REG_WRITE_BITS(ah, AR5K_PHY_TIMING_8,
1650 					AR5K_PHY_TIMING_8_PILOT_MASK_2,
1651 					0);
1652 
1653 		ath5k_hw_reg_write(ah, 0, AR5K_PHY_TIMING_9);
1654 		AR5K_REG_WRITE_BITS(ah, AR5K_PHY_TIMING_10,
1655 					AR5K_PHY_TIMING_10_PILOT_MASK_2,
1656 					0);
1657 
1658 		/* Clear magnitude masks */
1659 		ath5k_hw_reg_write(ah, 0, AR5K_PHY_BIN_MASK_1);
1660 		ath5k_hw_reg_write(ah, 0, AR5K_PHY_BIN_MASK_2);
1661 		ath5k_hw_reg_write(ah, 0, AR5K_PHY_BIN_MASK_3);
1662 		AR5K_REG_WRITE_BITS(ah, AR5K_PHY_BIN_MASK_CTL,
1663 					AR5K_PHY_BIN_MASK_CTL_MASK_4,
1664 					0);
1665 
1666 		ath5k_hw_reg_write(ah, 0, AR5K_PHY_BIN_MASK2_1);
1667 		ath5k_hw_reg_write(ah, 0, AR5K_PHY_BIN_MASK2_2);
1668 		ath5k_hw_reg_write(ah, 0, AR5K_PHY_BIN_MASK2_3);
1669 		AR5K_REG_WRITE_BITS(ah, AR5K_PHY_BIN_MASK2_4,
1670 					AR5K_PHY_BIN_MASK2_4_MASK_4,
1671 					0);
1672 	}
1673 }
1674 
1675 /********************\
1676   Misc PHY functions
1677 \********************/
1678 
1679 int ath5k_hw_phy_disable(struct ath5k_hw *ah)
1680 {
1681 	/*Just a try M.F.*/
1682 	ath5k_hw_reg_write(ah, AR5K_PHY_ACT_DISABLE, AR5K_PHY_ACT);
1683 
1684 	return 0;
1685 }
1686 
1687 /*
1688  * Get the PHY Chip revision
1689  */
1690 u16 ath5k_hw_radio_revision(struct ath5k_hw *ah, unsigned int chan)
1691 {
1692 	unsigned int i;
1693 	u32 srev;
1694 	u16 ret;
1695 
1696 	/*
1697 	 * Set the radio chip access register
1698 	 */
1699 	switch (chan) {
1700 	case CHANNEL_2GHZ:
1701 		ath5k_hw_reg_write(ah, AR5K_PHY_SHIFT_2GHZ, AR5K_PHY(0));
1702 		break;
1703 	case CHANNEL_5GHZ:
1704 		ath5k_hw_reg_write(ah, AR5K_PHY_SHIFT_5GHZ, AR5K_PHY(0));
1705 		break;
1706 	default:
1707 		return 0;
1708 	}
1709 
1710 	mdelay(2);
1711 
1712 	/* ...wait until PHY is ready and read the selected radio revision */
1713 	ath5k_hw_reg_write(ah, 0x00001c16, AR5K_PHY(0x34));
1714 
1715 	for (i = 0; i < 8; i++)
1716 		ath5k_hw_reg_write(ah, 0x00010000, AR5K_PHY(0x20));
1717 
1718 	if (ah->ah_version == AR5K_AR5210) {
1719 		srev = ath5k_hw_reg_read(ah, AR5K_PHY(256) >> 28) & 0xf;
1720 		ret = (u16)ath5k_hw_bitswap(srev, 4) + 1;
1721 	} else {
1722 		srev = (ath5k_hw_reg_read(ah, AR5K_PHY(0x100)) >> 24) & 0xff;
1723 		ret = (u16)ath5k_hw_bitswap(((srev & 0xf0) >> 4) |
1724 				((srev & 0x0f) << 4), 8);
1725 	}
1726 
1727 	/* Reset to the 5GHz mode */
1728 	ath5k_hw_reg_write(ah, AR5K_PHY_SHIFT_5GHZ, AR5K_PHY(0));
1729 
1730 	return ret;
1731 }
1732 
1733 /*****************\
1734 * Antenna control *
1735 \*****************/
1736 
1737 static void /*TODO:Boundary check*/
1738 ath5k_hw_set_def_antenna(struct ath5k_hw *ah, u8 ant)
1739 {
1740 	if (ah->ah_version != AR5K_AR5210)
1741 		ath5k_hw_reg_write(ah, ant & 0x7, AR5K_DEFAULT_ANTENNA);
1742 }
1743 
1744 /*
1745  * Enable/disable fast rx antenna diversity
1746  */
1747 static void
1748 ath5k_hw_set_fast_div(struct ath5k_hw *ah, u8 ee_mode, bool enable)
1749 {
1750 	switch (ee_mode) {
1751 	case AR5K_EEPROM_MODE_11G:
1752 		/* XXX: This is set to
1753 		 * disabled on initvals !!! */
1754 	case AR5K_EEPROM_MODE_11A:
1755 		if (enable)
1756 			AR5K_REG_DISABLE_BITS(ah, AR5K_PHY_AGCCTL,
1757 					AR5K_PHY_AGCCTL_OFDM_DIV_DIS);
1758 		else
1759 			AR5K_REG_ENABLE_BITS(ah, AR5K_PHY_AGCCTL,
1760 					AR5K_PHY_AGCCTL_OFDM_DIV_DIS);
1761 		break;
1762 	case AR5K_EEPROM_MODE_11B:
1763 		AR5K_REG_ENABLE_BITS(ah, AR5K_PHY_AGCCTL,
1764 					AR5K_PHY_AGCCTL_OFDM_DIV_DIS);
1765 		break;
1766 	default:
1767 		return;
1768 	}
1769 
1770 	if (enable) {
1771 		AR5K_REG_WRITE_BITS(ah, AR5K_PHY_RESTART,
1772 				AR5K_PHY_RESTART_DIV_GC, 4);
1773 
1774 		AR5K_REG_ENABLE_BITS(ah, AR5K_PHY_FAST_ANT_DIV,
1775 					AR5K_PHY_FAST_ANT_DIV_EN);
1776 	} else {
1777 		AR5K_REG_WRITE_BITS(ah, AR5K_PHY_RESTART,
1778 				AR5K_PHY_RESTART_DIV_GC, 0);
1779 
1780 		AR5K_REG_DISABLE_BITS(ah, AR5K_PHY_FAST_ANT_DIV,
1781 					AR5K_PHY_FAST_ANT_DIV_EN);
1782 	}
1783 }
1784 
1785 void
1786 ath5k_hw_set_antenna_switch(struct ath5k_hw *ah, u8 ee_mode)
1787 {
1788 	u8 ant0, ant1;
1789 
1790 	/*
1791 	 * In case a fixed antenna was set as default
1792 	 * use the same switch table twice.
1793 	 */
1794 	if (ah->ah_ant_mode == AR5K_ANTMODE_FIXED_A)
1795 		ant0 = ant1 = AR5K_ANT_SWTABLE_A;
1796 	else if (ah->ah_ant_mode == AR5K_ANTMODE_FIXED_B)
1797 		ant0 = ant1 = AR5K_ANT_SWTABLE_B;
1798 	else {
1799 		ant0 = AR5K_ANT_SWTABLE_A;
1800 		ant1 = AR5K_ANT_SWTABLE_B;
1801 	}
1802 
1803 	/* Set antenna idle switch table */
1804 	AR5K_REG_WRITE_BITS(ah, AR5K_PHY_ANT_CTL,
1805 			AR5K_PHY_ANT_CTL_SWTABLE_IDLE,
1806 			(ah->ah_ant_ctl[ee_mode][AR5K_ANT_CTL] |
1807 			AR5K_PHY_ANT_CTL_TXRX_EN));
1808 
1809 	/* Set antenna switch tables */
1810 	ath5k_hw_reg_write(ah, ah->ah_ant_ctl[ee_mode][ant0],
1811 		AR5K_PHY_ANT_SWITCH_TABLE_0);
1812 	ath5k_hw_reg_write(ah, ah->ah_ant_ctl[ee_mode][ant1],
1813 		AR5K_PHY_ANT_SWITCH_TABLE_1);
1814 }
1815 
1816 /*
1817  * Set antenna operating mode
1818  */
1819 void
1820 ath5k_hw_set_antenna_mode(struct ath5k_hw *ah, u8 ant_mode)
1821 {
1822 	struct ieee80211_channel *channel = ah->ah_current_channel;
1823 	bool use_def_for_tx, update_def_on_tx, use_def_for_rts, fast_div;
1824 	bool use_def_for_sg;
1825 	u8 def_ant, tx_ant, ee_mode;
1826 	u32 sta_id1 = 0;
1827 
1828 	/* if channel is not initialized yet we can't set the antennas
1829 	 * so just store the mode. it will be set on the next reset */
1830 	if (channel == NULL) {
1831 		ah->ah_ant_mode = ant_mode;
1832 		return;
1833 	}
1834 
1835 	def_ant = ah->ah_def_ant;
1836 
1837 	switch (channel->hw_value & CHANNEL_MODES) {
1838 	case CHANNEL_A:
1839 	case CHANNEL_T:
1840 	case CHANNEL_XR:
1841 		ee_mode = AR5K_EEPROM_MODE_11A;
1842 		break;
1843 	case CHANNEL_G:
1844 	case CHANNEL_TG:
1845 		ee_mode = AR5K_EEPROM_MODE_11G;
1846 		break;
1847 	case CHANNEL_B:
1848 		ee_mode = AR5K_EEPROM_MODE_11B;
1849 		break;
1850 	default:
1851 		ATH5K_ERR(ah->ah_sc,
1852 			"invalid channel: %d\n", channel->center_freq);
1853 		return;
1854 	}
1855 
1856 	switch (ant_mode) {
1857 	case AR5K_ANTMODE_DEFAULT:
1858 		tx_ant = 0;
1859 		use_def_for_tx = false;
1860 		update_def_on_tx = false;
1861 		use_def_for_rts = false;
1862 		use_def_for_sg = false;
1863 		fast_div = true;
1864 		break;
1865 	case AR5K_ANTMODE_FIXED_A:
1866 		def_ant = 1;
1867 		tx_ant = 1;
1868 		use_def_for_tx = true;
1869 		update_def_on_tx = false;
1870 		use_def_for_rts = true;
1871 		use_def_for_sg = true;
1872 		fast_div = false;
1873 		break;
1874 	case AR5K_ANTMODE_FIXED_B:
1875 		def_ant = 2;
1876 		tx_ant = 2;
1877 		use_def_for_tx = true;
1878 		update_def_on_tx = false;
1879 		use_def_for_rts = true;
1880 		use_def_for_sg = true;
1881 		fast_div = false;
1882 		break;
1883 	case AR5K_ANTMODE_SINGLE_AP:
1884 		def_ant = 1;	/* updated on tx */
1885 		tx_ant = 0;
1886 		use_def_for_tx = true;
1887 		update_def_on_tx = true;
1888 		use_def_for_rts = true;
1889 		use_def_for_sg = true;
1890 		fast_div = true;
1891 		break;
1892 	case AR5K_ANTMODE_SECTOR_AP:
1893 		tx_ant = 1;	/* variable */
1894 		use_def_for_tx = false;
1895 		update_def_on_tx = false;
1896 		use_def_for_rts = true;
1897 		use_def_for_sg = false;
1898 		fast_div = false;
1899 		break;
1900 	case AR5K_ANTMODE_SECTOR_STA:
1901 		tx_ant = 1;	/* variable */
1902 		use_def_for_tx = true;
1903 		update_def_on_tx = false;
1904 		use_def_for_rts = true;
1905 		use_def_for_sg = false;
1906 		fast_div = true;
1907 		break;
1908 	case AR5K_ANTMODE_DEBUG:
1909 		def_ant = 1;
1910 		tx_ant = 2;
1911 		use_def_for_tx = false;
1912 		update_def_on_tx = false;
1913 		use_def_for_rts = false;
1914 		use_def_for_sg = false;
1915 		fast_div = false;
1916 		break;
1917 	default:
1918 		return;
1919 	}
1920 
1921 	ah->ah_tx_ant = tx_ant;
1922 	ah->ah_ant_mode = ant_mode;
1923 	ah->ah_def_ant = def_ant;
1924 
1925 	sta_id1 |= use_def_for_tx ? AR5K_STA_ID1_DEFAULT_ANTENNA : 0;
1926 	sta_id1 |= update_def_on_tx ? AR5K_STA_ID1_DESC_ANTENNA : 0;
1927 	sta_id1 |= use_def_for_rts ? AR5K_STA_ID1_RTS_DEF_ANTENNA : 0;
1928 	sta_id1 |= use_def_for_sg ? AR5K_STA_ID1_SELFGEN_DEF_ANT : 0;
1929 
1930 	AR5K_REG_DISABLE_BITS(ah, AR5K_STA_ID1, AR5K_STA_ID1_ANTENNA_SETTINGS);
1931 
1932 	if (sta_id1)
1933 		AR5K_REG_ENABLE_BITS(ah, AR5K_STA_ID1, sta_id1);
1934 
1935 	ath5k_hw_set_antenna_switch(ah, ee_mode);
1936 	/* Note: set diversity before default antenna
1937 	 * because it won't work correctly */
1938 	ath5k_hw_set_fast_div(ah, ee_mode, fast_div);
1939 	ath5k_hw_set_def_antenna(ah, def_ant);
1940 }
1941 
1942 
1943 /****************\
1944 * TX power setup *
1945 \****************/
1946 
1947 /*
1948  * Helper functions
1949  */
1950 
1951 /*
1952  * Do linear interpolation between two given (x, y) points
1953  */
1954 static s16
1955 ath5k_get_interpolated_value(s16 target, s16 x_left, s16 x_right,
1956 					s16 y_left, s16 y_right)
1957 {
1958 	s16 ratio, result;
1959 
1960 	/* Avoid divide by zero and skip interpolation
1961 	 * if we have the same point */
1962 	if ((x_left == x_right) || (y_left == y_right))
1963 		return y_left;
1964 
1965 	/*
1966 	 * Since we use ints and not fps, we need to scale up in
1967 	 * order to get a sane ratio value (or else we 'll eg. get
1968 	 * always 1 instead of 1.25, 1.75 etc). We scale up by 100
1969 	 * to have some accuracy both for 0.5 and 0.25 steps.
1970 	 */
1971 	ratio = ((100 * y_right - 100 * y_left)/(x_right - x_left));
1972 
1973 	/* Now scale down to be in range */
1974 	result = y_left + (ratio * (target - x_left) / 100);
1975 
1976 	return result;
1977 }
1978 
1979 /*
1980  * Find vertical boundary (min pwr) for the linear PCDAC curve.
1981  *
1982  * Since we have the top of the curve and we draw the line below
1983  * until we reach 1 (1 pcdac step) we need to know which point
1984  * (x value) that is so that we don't go below y axis and have negative
1985  * pcdac values when creating the curve, or fill the table with zeroes.
1986  */
1987 static s16
1988 ath5k_get_linear_pcdac_min(const u8 *stepL, const u8 *stepR,
1989 				const s16 *pwrL, const s16 *pwrR)
1990 {
1991 	s8 tmp;
1992 	s16 min_pwrL, min_pwrR;
1993 	s16 pwr_i;
1994 
1995 	/* Some vendors write the same pcdac value twice !!! */
1996 	if (stepL[0] == stepL[1] || stepR[0] == stepR[1])
1997 		return max(pwrL[0], pwrR[0]);
1998 
1999 	if (pwrL[0] == pwrL[1])
2000 		min_pwrL = pwrL[0];
2001 	else {
2002 		pwr_i = pwrL[0];
2003 		do {
2004 			pwr_i--;
2005 			tmp = (s8) ath5k_get_interpolated_value(pwr_i,
2006 							pwrL[0], pwrL[1],
2007 							stepL[0], stepL[1]);
2008 		} while (tmp > 1);
2009 
2010 		min_pwrL = pwr_i;
2011 	}
2012 
2013 	if (pwrR[0] == pwrR[1])
2014 		min_pwrR = pwrR[0];
2015 	else {
2016 		pwr_i = pwrR[0];
2017 		do {
2018 			pwr_i--;
2019 			tmp = (s8) ath5k_get_interpolated_value(pwr_i,
2020 							pwrR[0], pwrR[1],
2021 							stepR[0], stepR[1]);
2022 		} while (tmp > 1);
2023 
2024 		min_pwrR = pwr_i;
2025 	}
2026 
2027 	/* Keep the right boundary so that it works for both curves */
2028 	return max(min_pwrL, min_pwrR);
2029 }
2030 
2031 /*
2032  * Interpolate (pwr,vpd) points to create a Power to PDADC or a
2033  * Power to PCDAC curve.
2034  *
2035  * Each curve has power on x axis (in 0.5dB units) and PCDAC/PDADC
2036  * steps (offsets) on y axis. Power can go up to 31.5dB and max
2037  * PCDAC/PDADC step for each curve is 64 but we can write more than
2038  * one curves on hw so we can go up to 128 (which is the max step we
2039  * can write on the final table).
2040  *
2041  * We write y values (PCDAC/PDADC steps) on hw.
2042  */
2043 static void
2044 ath5k_create_power_curve(s16 pmin, s16 pmax,
2045 			const s16 *pwr, const u8 *vpd,
2046 			u8 num_points,
2047 			u8 *vpd_table, u8 type)
2048 {
2049 	u8 idx[2] = { 0, 1 };
2050 	s16 pwr_i = 2*pmin;
2051 	int i;
2052 
2053 	if (num_points < 2)
2054 		return;
2055 
2056 	/* We want the whole line, so adjust boundaries
2057 	 * to cover the entire power range. Note that
2058 	 * power values are already 0.25dB so no need
2059 	 * to multiply pwr_i by 2 */
2060 	if (type == AR5K_PWRTABLE_LINEAR_PCDAC) {
2061 		pwr_i = pmin;
2062 		pmin = 0;
2063 		pmax = 63;
2064 	}
2065 
2066 	/* Find surrounding turning points (TPs)
2067 	 * and interpolate between them */
2068 	for (i = 0; (i <= (u16) (pmax - pmin)) &&
2069 	(i < AR5K_EEPROM_POWER_TABLE_SIZE); i++) {
2070 
2071 		/* We passed the right TP, move to the next set of TPs
2072 		 * if we pass the last TP, extrapolate above using the last
2073 		 * two TPs for ratio */
2074 		if ((pwr_i > pwr[idx[1]]) && (idx[1] < num_points - 1)) {
2075 			idx[0]++;
2076 			idx[1]++;
2077 		}
2078 
2079 		vpd_table[i] = (u8) ath5k_get_interpolated_value(pwr_i,
2080 						pwr[idx[0]], pwr[idx[1]],
2081 						vpd[idx[0]], vpd[idx[1]]);
2082 
2083 		/* Increase by 0.5dB
2084 		 * (0.25 dB units) */
2085 		pwr_i += 2;
2086 	}
2087 }
2088 
2089 /*
2090  * Get the surrounding per-channel power calibration piers
2091  * for a given frequency so that we can interpolate between
2092  * them and come up with an apropriate dataset for our current
2093  * channel.
2094  */
2095 static void
2096 ath5k_get_chan_pcal_surrounding_piers(struct ath5k_hw *ah,
2097 			struct ieee80211_channel *channel,
2098 			struct ath5k_chan_pcal_info **pcinfo_l,
2099 			struct ath5k_chan_pcal_info **pcinfo_r)
2100 {
2101 	struct ath5k_eeprom_info *ee = &ah->ah_capabilities.cap_eeprom;
2102 	struct ath5k_chan_pcal_info *pcinfo;
2103 	u8 idx_l, idx_r;
2104 	u8 mode, max, i;
2105 	u32 target = channel->center_freq;
2106 
2107 	idx_l = 0;
2108 	idx_r = 0;
2109 
2110 	if (!(channel->hw_value & CHANNEL_OFDM)) {
2111 		pcinfo = ee->ee_pwr_cal_b;
2112 		mode = AR5K_EEPROM_MODE_11B;
2113 	} else if (channel->hw_value & CHANNEL_2GHZ) {
2114 		pcinfo = ee->ee_pwr_cal_g;
2115 		mode = AR5K_EEPROM_MODE_11G;
2116 	} else {
2117 		pcinfo = ee->ee_pwr_cal_a;
2118 		mode = AR5K_EEPROM_MODE_11A;
2119 	}
2120 	max = ee->ee_n_piers[mode] - 1;
2121 
2122 	/* Frequency is below our calibrated
2123 	 * range. Use the lowest power curve
2124 	 * we have */
2125 	if (target < pcinfo[0].freq) {
2126 		idx_l = idx_r = 0;
2127 		goto done;
2128 	}
2129 
2130 	/* Frequency is above our calibrated
2131 	 * range. Use the highest power curve
2132 	 * we have */
2133 	if (target > pcinfo[max].freq) {
2134 		idx_l = idx_r = max;
2135 		goto done;
2136 	}
2137 
2138 	/* Frequency is inside our calibrated
2139 	 * channel range. Pick the surrounding
2140 	 * calibration piers so that we can
2141 	 * interpolate */
2142 	for (i = 0; i <= max; i++) {
2143 
2144 		/* Frequency matches one of our calibration
2145 		 * piers, no need to interpolate, just use
2146 		 * that calibration pier */
2147 		if (pcinfo[i].freq == target) {
2148 			idx_l = idx_r = i;
2149 			goto done;
2150 		}
2151 
2152 		/* We found a calibration pier that's above
2153 		 * frequency, use this pier and the previous
2154 		 * one to interpolate */
2155 		if (target < pcinfo[i].freq) {
2156 			idx_r = i;
2157 			idx_l = idx_r - 1;
2158 			goto done;
2159 		}
2160 	}
2161 
2162 done:
2163 	*pcinfo_l = &pcinfo[idx_l];
2164 	*pcinfo_r = &pcinfo[idx_r];
2165 }
2166 
2167 /*
2168  * Get the surrounding per-rate power calibration data
2169  * for a given frequency and interpolate between power
2170  * values to set max target power supported by hw for
2171  * each rate.
2172  */
2173 static void
2174 ath5k_get_rate_pcal_data(struct ath5k_hw *ah,
2175 			struct ieee80211_channel *channel,
2176 			struct ath5k_rate_pcal_info *rates)
2177 {
2178 	struct ath5k_eeprom_info *ee = &ah->ah_capabilities.cap_eeprom;
2179 	struct ath5k_rate_pcal_info *rpinfo;
2180 	u8 idx_l, idx_r;
2181 	u8 mode, max, i;
2182 	u32 target = channel->center_freq;
2183 
2184 	idx_l = 0;
2185 	idx_r = 0;
2186 
2187 	if (!(channel->hw_value & CHANNEL_OFDM)) {
2188 		rpinfo = ee->ee_rate_tpwr_b;
2189 		mode = AR5K_EEPROM_MODE_11B;
2190 	} else if (channel->hw_value & CHANNEL_2GHZ) {
2191 		rpinfo = ee->ee_rate_tpwr_g;
2192 		mode = AR5K_EEPROM_MODE_11G;
2193 	} else {
2194 		rpinfo = ee->ee_rate_tpwr_a;
2195 		mode = AR5K_EEPROM_MODE_11A;
2196 	}
2197 	max = ee->ee_rate_target_pwr_num[mode] - 1;
2198 
2199 	/* Get the surrounding calibration
2200 	 * piers - same as above */
2201 	if (target < rpinfo[0].freq) {
2202 		idx_l = idx_r = 0;
2203 		goto done;
2204 	}
2205 
2206 	if (target > rpinfo[max].freq) {
2207 		idx_l = idx_r = max;
2208 		goto done;
2209 	}
2210 
2211 	for (i = 0; i <= max; i++) {
2212 
2213 		if (rpinfo[i].freq == target) {
2214 			idx_l = idx_r = i;
2215 			goto done;
2216 		}
2217 
2218 		if (target < rpinfo[i].freq) {
2219 			idx_r = i;
2220 			idx_l = idx_r - 1;
2221 			goto done;
2222 		}
2223 	}
2224 
2225 done:
2226 	/* Now interpolate power value, based on the frequency */
2227 	rates->freq = target;
2228 
2229 	rates->target_power_6to24 =
2230 		ath5k_get_interpolated_value(target, rpinfo[idx_l].freq,
2231 					rpinfo[idx_r].freq,
2232 					rpinfo[idx_l].target_power_6to24,
2233 					rpinfo[idx_r].target_power_6to24);
2234 
2235 	rates->target_power_36 =
2236 		ath5k_get_interpolated_value(target, rpinfo[idx_l].freq,
2237 					rpinfo[idx_r].freq,
2238 					rpinfo[idx_l].target_power_36,
2239 					rpinfo[idx_r].target_power_36);
2240 
2241 	rates->target_power_48 =
2242 		ath5k_get_interpolated_value(target, rpinfo[idx_l].freq,
2243 					rpinfo[idx_r].freq,
2244 					rpinfo[idx_l].target_power_48,
2245 					rpinfo[idx_r].target_power_48);
2246 
2247 	rates->target_power_54 =
2248 		ath5k_get_interpolated_value(target, rpinfo[idx_l].freq,
2249 					rpinfo[idx_r].freq,
2250 					rpinfo[idx_l].target_power_54,
2251 					rpinfo[idx_r].target_power_54);
2252 }
2253 
2254 /*
2255  * Get the max edge power for this channel if
2256  * we have such data from EEPROM's Conformance Test
2257  * Limits (CTL), and limit max power if needed.
2258  */
2259 static void
2260 ath5k_get_max_ctl_power(struct ath5k_hw *ah,
2261 			struct ieee80211_channel *channel)
2262 {
2263 	struct ath_regulatory *regulatory = ath5k_hw_regulatory(ah);
2264 	struct ath5k_eeprom_info *ee = &ah->ah_capabilities.cap_eeprom;
2265 	struct ath5k_edge_power *rep = ee->ee_ctl_pwr;
2266 	u8 *ctl_val = ee->ee_ctl;
2267 	s16 max_chan_pwr = ah->ah_txpower.txp_max_pwr / 4;
2268 	s16 edge_pwr = 0;
2269 	u8 rep_idx;
2270 	u8 i, ctl_mode;
2271 	u8 ctl_idx = 0xFF;
2272 	u32 target = channel->center_freq;
2273 
2274 	ctl_mode = ath_regd_get_band_ctl(regulatory, channel->band);
2275 
2276 	switch (channel->hw_value & CHANNEL_MODES) {
2277 	case CHANNEL_A:
2278 		ctl_mode |= AR5K_CTL_11A;
2279 		break;
2280 	case CHANNEL_G:
2281 		ctl_mode |= AR5K_CTL_11G;
2282 		break;
2283 	case CHANNEL_B:
2284 		ctl_mode |= AR5K_CTL_11B;
2285 		break;
2286 	case CHANNEL_T:
2287 		ctl_mode |= AR5K_CTL_TURBO;
2288 		break;
2289 	case CHANNEL_TG:
2290 		ctl_mode |= AR5K_CTL_TURBOG;
2291 		break;
2292 	case CHANNEL_XR:
2293 		/* Fall through */
2294 	default:
2295 		return;
2296 	}
2297 
2298 	for (i = 0; i < ee->ee_ctls; i++) {
2299 		if (ctl_val[i] == ctl_mode) {
2300 			ctl_idx = i;
2301 			break;
2302 		}
2303 	}
2304 
2305 	/* If we have a CTL dataset available grab it and find the
2306 	 * edge power for our frequency */
2307 	if (ctl_idx == 0xFF)
2308 		return;
2309 
2310 	/* Edge powers are sorted by frequency from lower
2311 	 * to higher. Each CTL corresponds to 8 edge power
2312 	 * measurements. */
2313 	rep_idx = ctl_idx * AR5K_EEPROM_N_EDGES;
2314 
2315 	/* Don't do boundaries check because we
2316 	 * might have more that one bands defined
2317 	 * for this mode */
2318 
2319 	/* Get the edge power that's closer to our
2320 	 * frequency */
2321 	for (i = 0; i < AR5K_EEPROM_N_EDGES; i++) {
2322 		rep_idx += i;
2323 		if (target <= rep[rep_idx].freq)
2324 			edge_pwr = (s16) rep[rep_idx].edge;
2325 	}
2326 
2327 	if (edge_pwr)
2328 		ah->ah_txpower.txp_max_pwr = 4*min(edge_pwr, max_chan_pwr);
2329 }
2330 
2331 
2332 /*
2333  * Power to PCDAC table functions
2334  */
2335 
2336 /*
2337  * Fill Power to PCDAC table on RF5111
2338  *
2339  * No further processing is needed for RF5111, the only thing we have to
2340  * do is fill the values below and above calibration range since eeprom data
2341  * may not cover the entire PCDAC table.
2342  */
2343 static void
2344 ath5k_fill_pwr_to_pcdac_table(struct ath5k_hw *ah, s16* table_min,
2345 							s16 *table_max)
2346 {
2347 	u8 	*pcdac_out = ah->ah_txpower.txp_pd_table;
2348 	u8	*pcdac_tmp = ah->ah_txpower.tmpL[0];
2349 	u8	pcdac_0, pcdac_n, pcdac_i, pwr_idx, i;
2350 	s16	min_pwr, max_pwr;
2351 
2352 	/* Get table boundaries */
2353 	min_pwr = table_min[0];
2354 	pcdac_0 = pcdac_tmp[0];
2355 
2356 	max_pwr = table_max[0];
2357 	pcdac_n = pcdac_tmp[table_max[0] - table_min[0]];
2358 
2359 	/* Extrapolate below minimum using pcdac_0 */
2360 	pcdac_i = 0;
2361 	for (i = 0; i < min_pwr; i++)
2362 		pcdac_out[pcdac_i++] = pcdac_0;
2363 
2364 	/* Copy values from pcdac_tmp */
2365 	pwr_idx = min_pwr;
2366 	for (i = 0 ; pwr_idx <= max_pwr &&
2367 	pcdac_i < AR5K_EEPROM_POWER_TABLE_SIZE; i++) {
2368 		pcdac_out[pcdac_i++] = pcdac_tmp[i];
2369 		pwr_idx++;
2370 	}
2371 
2372 	/* Extrapolate above maximum */
2373 	while (pcdac_i < AR5K_EEPROM_POWER_TABLE_SIZE)
2374 		pcdac_out[pcdac_i++] = pcdac_n;
2375 
2376 }
2377 
2378 /*
2379  * Combine available XPD Curves and fill Linear Power to PCDAC table
2380  * on RF5112
2381  *
2382  * RFX112 can have up to 2 curves (one for low txpower range and one for
2383  * higher txpower range). We need to put them both on pcdac_out and place
2384  * them in the correct location. In case we only have one curve available
2385  * just fit it on pcdac_out (it's supposed to cover the entire range of
2386  * available pwr levels since it's always the higher power curve). Extrapolate
2387  * below and above final table if needed.
2388  */
2389 static void
2390 ath5k_combine_linear_pcdac_curves(struct ath5k_hw *ah, s16* table_min,
2391 						s16 *table_max, u8 pdcurves)
2392 {
2393 	u8 	*pcdac_out = ah->ah_txpower.txp_pd_table;
2394 	u8	*pcdac_low_pwr;
2395 	u8	*pcdac_high_pwr;
2396 	u8	*pcdac_tmp;
2397 	u8	pwr;
2398 	s16	max_pwr_idx;
2399 	s16	min_pwr_idx;
2400 	s16	mid_pwr_idx = 0;
2401 	/* Edge flag turs on the 7nth bit on the PCDAC
2402 	 * to delcare the higher power curve (force values
2403 	 * to be greater than 64). If we only have one curve
2404 	 * we don't need to set this, if we have 2 curves and
2405 	 * fill the table backwards this can also be used to
2406 	 * switch from higher power curve to lower power curve */
2407 	u8	edge_flag;
2408 	int	i;
2409 
2410 	/* When we have only one curve available
2411 	 * that's the higher power curve. If we have
2412 	 * two curves the first is the high power curve
2413 	 * and the next is the low power curve. */
2414 	if (pdcurves > 1) {
2415 		pcdac_low_pwr = ah->ah_txpower.tmpL[1];
2416 		pcdac_high_pwr = ah->ah_txpower.tmpL[0];
2417 		mid_pwr_idx = table_max[1] - table_min[1] - 1;
2418 		max_pwr_idx = (table_max[0] - table_min[0]) / 2;
2419 
2420 		/* If table size goes beyond 31.5dB, keep the
2421 		 * upper 31.5dB range when setting tx power.
2422 		 * Note: 126 = 31.5 dB in quarter dB steps */
2423 		if (table_max[0] - table_min[1] > 126)
2424 			min_pwr_idx = table_max[0] - 126;
2425 		else
2426 			min_pwr_idx = table_min[1];
2427 
2428 		/* Since we fill table backwards
2429 		 * start from high power curve */
2430 		pcdac_tmp = pcdac_high_pwr;
2431 
2432 		edge_flag = 0x40;
2433 	} else {
2434 		pcdac_low_pwr = ah->ah_txpower.tmpL[1]; /* Zeroed */
2435 		pcdac_high_pwr = ah->ah_txpower.tmpL[0];
2436 		min_pwr_idx = table_min[0];
2437 		max_pwr_idx = (table_max[0] - table_min[0]) / 2;
2438 		pcdac_tmp = pcdac_high_pwr;
2439 		edge_flag = 0;
2440 	}
2441 
2442 	/* This is used when setting tx power*/
2443 	ah->ah_txpower.txp_min_idx = min_pwr_idx/2;
2444 
2445 	/* Fill Power to PCDAC table backwards */
2446 	pwr = max_pwr_idx;
2447 	for (i = 63; i >= 0; i--) {
2448 		/* Entering lower power range, reset
2449 		 * edge flag and set pcdac_tmp to lower
2450 		 * power curve.*/
2451 		if (edge_flag == 0x40 &&
2452 		(2*pwr <= (table_max[1] - table_min[0]) || pwr == 0)) {
2453 			edge_flag = 0x00;
2454 			pcdac_tmp = pcdac_low_pwr;
2455 			pwr = mid_pwr_idx/2;
2456 		}
2457 
2458 		/* Don't go below 1, extrapolate below if we have
2459 		 * already swithced to the lower power curve -or
2460 		 * we only have one curve and edge_flag is zero
2461 		 * anyway */
2462 		if (pcdac_tmp[pwr] < 1 && (edge_flag == 0x00)) {
2463 			while (i >= 0) {
2464 				pcdac_out[i] = pcdac_out[i + 1];
2465 				i--;
2466 			}
2467 			break;
2468 		}
2469 
2470 		pcdac_out[i] = pcdac_tmp[pwr] | edge_flag;
2471 
2472 		/* Extrapolate above if pcdac is greater than
2473 		 * 126 -this can happen because we OR pcdac_out
2474 		 * value with edge_flag on high power curve */
2475 		if (pcdac_out[i] > 126)
2476 			pcdac_out[i] = 126;
2477 
2478 		/* Decrease by a 0.5dB step */
2479 		pwr--;
2480 	}
2481 }
2482 
2483 /* Write PCDAC values on hw */
2484 static void
2485 ath5k_setup_pcdac_table(struct ath5k_hw *ah)
2486 {
2487 	u8 	*pcdac_out = ah->ah_txpower.txp_pd_table;
2488 	int	i;
2489 
2490 	/*
2491 	 * Write TX power values
2492 	 */
2493 	for (i = 0; i < (AR5K_EEPROM_POWER_TABLE_SIZE / 2); i++) {
2494 		ath5k_hw_reg_write(ah,
2495 			(((pcdac_out[2*i + 0] << 8 | 0xff) & 0xffff) << 0) |
2496 			(((pcdac_out[2*i + 1] << 8 | 0xff) & 0xffff) << 16),
2497 			AR5K_PHY_PCDAC_TXPOWER(i));
2498 	}
2499 }
2500 
2501 
2502 /*
2503  * Power to PDADC table functions
2504  */
2505 
2506 /*
2507  * Set the gain boundaries and create final Power to PDADC table
2508  *
2509  * We can have up to 4 pd curves, we need to do a simmilar process
2510  * as we do for RF5112. This time we don't have an edge_flag but we
2511  * set the gain boundaries on a separate register.
2512  */
2513 static void
2514 ath5k_combine_pwr_to_pdadc_curves(struct ath5k_hw *ah,
2515 			s16 *pwr_min, s16 *pwr_max, u8 pdcurves)
2516 {
2517 	u8 gain_boundaries[AR5K_EEPROM_N_PD_GAINS];
2518 	u8 *pdadc_out = ah->ah_txpower.txp_pd_table;
2519 	u8 *pdadc_tmp;
2520 	s16 pdadc_0;
2521 	u8 pdadc_i, pdadc_n, pwr_step, pdg, max_idx, table_size;
2522 	u8 pd_gain_overlap;
2523 
2524 	/* Note: Register value is initialized on initvals
2525 	 * there is no feedback from hw.
2526 	 * XXX: What about pd_gain_overlap from EEPROM ? */
2527 	pd_gain_overlap = (u8) ath5k_hw_reg_read(ah, AR5K_PHY_TPC_RG5) &
2528 		AR5K_PHY_TPC_RG5_PD_GAIN_OVERLAP;
2529 
2530 	/* Create final PDADC table */
2531 	for (pdg = 0, pdadc_i = 0; pdg < pdcurves; pdg++) {
2532 		pdadc_tmp = ah->ah_txpower.tmpL[pdg];
2533 
2534 		if (pdg == pdcurves - 1)
2535 			/* 2 dB boundary stretch for last
2536 			 * (higher power) curve */
2537 			gain_boundaries[pdg] = pwr_max[pdg] + 4;
2538 		else
2539 			/* Set gain boundary in the middle
2540 			 * between this curve and the next one */
2541 			gain_boundaries[pdg] =
2542 				(pwr_max[pdg] + pwr_min[pdg + 1]) / 2;
2543 
2544 		/* Sanity check in case our 2 db stretch got out of
2545 		 * range. */
2546 		if (gain_boundaries[pdg] > AR5K_TUNE_MAX_TXPOWER)
2547 			gain_boundaries[pdg] = AR5K_TUNE_MAX_TXPOWER;
2548 
2549 		/* For the first curve (lower power)
2550 		 * start from 0 dB */
2551 		if (pdg == 0)
2552 			pdadc_0 = 0;
2553 		else
2554 			/* For the other curves use the gain overlap */
2555 			pdadc_0 = (gain_boundaries[pdg - 1] - pwr_min[pdg]) -
2556 							pd_gain_overlap;
2557 
2558 		/* Force each power step to be at least 0.5 dB */
2559 		if ((pdadc_tmp[1] - pdadc_tmp[0]) > 1)
2560 			pwr_step = pdadc_tmp[1] - pdadc_tmp[0];
2561 		else
2562 			pwr_step = 1;
2563 
2564 		/* If pdadc_0 is negative, we need to extrapolate
2565 		 * below this pdgain by a number of pwr_steps */
2566 		while ((pdadc_0 < 0) && (pdadc_i < 128)) {
2567 			s16 tmp = pdadc_tmp[0] + pdadc_0 * pwr_step;
2568 			pdadc_out[pdadc_i++] = (tmp < 0) ? 0 : (u8) tmp;
2569 			pdadc_0++;
2570 		}
2571 
2572 		/* Set last pwr level, using gain boundaries */
2573 		pdadc_n = gain_boundaries[pdg] + pd_gain_overlap - pwr_min[pdg];
2574 		/* Limit it to be inside pwr range */
2575 		table_size = pwr_max[pdg] - pwr_min[pdg];
2576 		max_idx = (pdadc_n < table_size) ? pdadc_n : table_size;
2577 
2578 		/* Fill pdadc_out table */
2579 		while (pdadc_0 < max_idx && pdadc_i < 128)
2580 			pdadc_out[pdadc_i++] = pdadc_tmp[pdadc_0++];
2581 
2582 		/* Need to extrapolate above this pdgain? */
2583 		if (pdadc_n <= max_idx)
2584 			continue;
2585 
2586 		/* Force each power step to be at least 0.5 dB */
2587 		if ((pdadc_tmp[table_size - 1] - pdadc_tmp[table_size - 2]) > 1)
2588 			pwr_step = pdadc_tmp[table_size - 1] -
2589 						pdadc_tmp[table_size - 2];
2590 		else
2591 			pwr_step = 1;
2592 
2593 		/* Extrapolate above */
2594 		while ((pdadc_0 < (s16) pdadc_n) &&
2595 		(pdadc_i < AR5K_EEPROM_POWER_TABLE_SIZE * 2)) {
2596 			s16 tmp = pdadc_tmp[table_size - 1] +
2597 					(pdadc_0 - max_idx) * pwr_step;
2598 			pdadc_out[pdadc_i++] = (tmp > 127) ? 127 : (u8) tmp;
2599 			pdadc_0++;
2600 		}
2601 	}
2602 
2603 	while (pdg < AR5K_EEPROM_N_PD_GAINS) {
2604 		gain_boundaries[pdg] = gain_boundaries[pdg - 1];
2605 		pdg++;
2606 	}
2607 
2608 	while (pdadc_i < AR5K_EEPROM_POWER_TABLE_SIZE * 2) {
2609 		pdadc_out[pdadc_i] = pdadc_out[pdadc_i - 1];
2610 		pdadc_i++;
2611 	}
2612 
2613 	/* Set gain boundaries */
2614 	ath5k_hw_reg_write(ah,
2615 		AR5K_REG_SM(pd_gain_overlap,
2616 			AR5K_PHY_TPC_RG5_PD_GAIN_OVERLAP) |
2617 		AR5K_REG_SM(gain_boundaries[0],
2618 			AR5K_PHY_TPC_RG5_PD_GAIN_BOUNDARY_1) |
2619 		AR5K_REG_SM(gain_boundaries[1],
2620 			AR5K_PHY_TPC_RG5_PD_GAIN_BOUNDARY_2) |
2621 		AR5K_REG_SM(gain_boundaries[2],
2622 			AR5K_PHY_TPC_RG5_PD_GAIN_BOUNDARY_3) |
2623 		AR5K_REG_SM(gain_boundaries[3],
2624 			AR5K_PHY_TPC_RG5_PD_GAIN_BOUNDARY_4),
2625 		AR5K_PHY_TPC_RG5);
2626 
2627 	/* Used for setting rate power table */
2628 	ah->ah_txpower.txp_min_idx = pwr_min[0];
2629 
2630 }
2631 
2632 /* Write PDADC values on hw */
2633 static void
2634 ath5k_setup_pwr_to_pdadc_table(struct ath5k_hw *ah,
2635 			u8 pdcurves, u8 *pdg_to_idx)
2636 {
2637 	u8 *pdadc_out = ah->ah_txpower.txp_pd_table;
2638 	u32 reg;
2639 	u8 i;
2640 
2641 	/* Select the right pdgain curves */
2642 
2643 	/* Clear current settings */
2644 	reg = ath5k_hw_reg_read(ah, AR5K_PHY_TPC_RG1);
2645 	reg &= ~(AR5K_PHY_TPC_RG1_PDGAIN_1 |
2646 		AR5K_PHY_TPC_RG1_PDGAIN_2 |
2647 		AR5K_PHY_TPC_RG1_PDGAIN_3 |
2648 		AR5K_PHY_TPC_RG1_NUM_PD_GAIN);
2649 
2650 	/*
2651 	 * Use pd_gains curve from eeprom
2652 	 *
2653 	 * This overrides the default setting from initvals
2654 	 * in case some vendors (e.g. Zcomax) don't use the default
2655 	 * curves. If we don't honor their settings we 'll get a
2656 	 * 5dB (1 * gain overlap ?) drop.
2657 	 */
2658 	reg |= AR5K_REG_SM(pdcurves, AR5K_PHY_TPC_RG1_NUM_PD_GAIN);
2659 
2660 	switch (pdcurves) {
2661 	case 3:
2662 		reg |= AR5K_REG_SM(pdg_to_idx[2], AR5K_PHY_TPC_RG1_PDGAIN_3);
2663 		/* Fall through */
2664 	case 2:
2665 		reg |= AR5K_REG_SM(pdg_to_idx[1], AR5K_PHY_TPC_RG1_PDGAIN_2);
2666 		/* Fall through */
2667 	case 1:
2668 		reg |= AR5K_REG_SM(pdg_to_idx[0], AR5K_PHY_TPC_RG1_PDGAIN_1);
2669 		break;
2670 	}
2671 	ath5k_hw_reg_write(ah, reg, AR5K_PHY_TPC_RG1);
2672 
2673 	/*
2674 	 * Write TX power values
2675 	 */
2676 	for (i = 0; i < (AR5K_EEPROM_POWER_TABLE_SIZE / 2); i++) {
2677 		ath5k_hw_reg_write(ah,
2678 			((pdadc_out[4*i + 0] & 0xff) << 0) |
2679 			((pdadc_out[4*i + 1] & 0xff) << 8) |
2680 			((pdadc_out[4*i + 2] & 0xff) << 16) |
2681 			((pdadc_out[4*i + 3] & 0xff) << 24),
2682 			AR5K_PHY_PDADC_TXPOWER(i));
2683 	}
2684 }
2685 
2686 
2687 /*
2688  * Common code for PCDAC/PDADC tables
2689  */
2690 
2691 /*
2692  * This is the main function that uses all of the above
2693  * to set PCDAC/PDADC table on hw for the current channel.
2694  * This table is used for tx power calibration on the basband,
2695  * without it we get weird tx power levels and in some cases
2696  * distorted spectral mask
2697  */
2698 static int
2699 ath5k_setup_channel_powertable(struct ath5k_hw *ah,
2700 			struct ieee80211_channel *channel,
2701 			u8 ee_mode, u8 type)
2702 {
2703 	struct ath5k_pdgain_info *pdg_L, *pdg_R;
2704 	struct ath5k_chan_pcal_info *pcinfo_L;
2705 	struct ath5k_chan_pcal_info *pcinfo_R;
2706 	struct ath5k_eeprom_info *ee = &ah->ah_capabilities.cap_eeprom;
2707 	u8 *pdg_curve_to_idx = ee->ee_pdc_to_idx[ee_mode];
2708 	s16 table_min[AR5K_EEPROM_N_PD_GAINS];
2709 	s16 table_max[AR5K_EEPROM_N_PD_GAINS];
2710 	u8 *tmpL;
2711 	u8 *tmpR;
2712 	u32 target = channel->center_freq;
2713 	int pdg, i;
2714 
2715 	/* Get surounding freq piers for this channel */
2716 	ath5k_get_chan_pcal_surrounding_piers(ah, channel,
2717 						&pcinfo_L,
2718 						&pcinfo_R);
2719 
2720 	/* Loop over pd gain curves on
2721 	 * surounding freq piers by index */
2722 	for (pdg = 0; pdg < ee->ee_pd_gains[ee_mode]; pdg++) {
2723 
2724 		/* Fill curves in reverse order
2725 		 * from lower power (max gain)
2726 		 * to higher power. Use curve -> idx
2727 		 * backmapping we did on eeprom init */
2728 		u8 idx = pdg_curve_to_idx[pdg];
2729 
2730 		/* Grab the needed curves by index */
2731 		pdg_L = &pcinfo_L->pd_curves[idx];
2732 		pdg_R = &pcinfo_R->pd_curves[idx];
2733 
2734 		/* Initialize the temp tables */
2735 		tmpL = ah->ah_txpower.tmpL[pdg];
2736 		tmpR = ah->ah_txpower.tmpR[pdg];
2737 
2738 		/* Set curve's x boundaries and create
2739 		 * curves so that they cover the same
2740 		 * range (if we don't do that one table
2741 		 * will have values on some range and the
2742 		 * other one won't have any so interpolation
2743 		 * will fail) */
2744 		table_min[pdg] = min(pdg_L->pd_pwr[0],
2745 					pdg_R->pd_pwr[0]) / 2;
2746 
2747 		table_max[pdg] = max(pdg_L->pd_pwr[pdg_L->pd_points - 1],
2748 				pdg_R->pd_pwr[pdg_R->pd_points - 1]) / 2;
2749 
2750 		/* Now create the curves on surrounding channels
2751 		 * and interpolate if needed to get the final
2752 		 * curve for this gain on this channel */
2753 		switch (type) {
2754 		case AR5K_PWRTABLE_LINEAR_PCDAC:
2755 			/* Override min/max so that we don't loose
2756 			 * accuracy (don't divide by 2) */
2757 			table_min[pdg] = min(pdg_L->pd_pwr[0],
2758 						pdg_R->pd_pwr[0]);
2759 
2760 			table_max[pdg] =
2761 				max(pdg_L->pd_pwr[pdg_L->pd_points - 1],
2762 					pdg_R->pd_pwr[pdg_R->pd_points - 1]);
2763 
2764 			/* Override minimum so that we don't get
2765 			 * out of bounds while extrapolating
2766 			 * below. Don't do this when we have 2
2767 			 * curves and we are on the high power curve
2768 			 * because table_min is ok in this case */
2769 			if (!(ee->ee_pd_gains[ee_mode] > 1 && pdg == 0)) {
2770 
2771 				table_min[pdg] =
2772 					ath5k_get_linear_pcdac_min(pdg_L->pd_step,
2773 								pdg_R->pd_step,
2774 								pdg_L->pd_pwr,
2775 								pdg_R->pd_pwr);
2776 
2777 				/* Don't go too low because we will
2778 				 * miss the upper part of the curve.
2779 				 * Note: 126 = 31.5dB (max power supported)
2780 				 * in 0.25dB units */
2781 				if (table_max[pdg] - table_min[pdg] > 126)
2782 					table_min[pdg] = table_max[pdg] - 126;
2783 			}
2784 
2785 			/* Fall through */
2786 		case AR5K_PWRTABLE_PWR_TO_PCDAC:
2787 		case AR5K_PWRTABLE_PWR_TO_PDADC:
2788 
2789 			ath5k_create_power_curve(table_min[pdg],
2790 						table_max[pdg],
2791 						pdg_L->pd_pwr,
2792 						pdg_L->pd_step,
2793 						pdg_L->pd_points, tmpL, type);
2794 
2795 			/* We are in a calibration
2796 			 * pier, no need to interpolate
2797 			 * between freq piers */
2798 			if (pcinfo_L == pcinfo_R)
2799 				continue;
2800 
2801 			ath5k_create_power_curve(table_min[pdg],
2802 						table_max[pdg],
2803 						pdg_R->pd_pwr,
2804 						pdg_R->pd_step,
2805 						pdg_R->pd_points, tmpR, type);
2806 			break;
2807 		default:
2808 			return -EINVAL;
2809 		}
2810 
2811 		/* Interpolate between curves
2812 		 * of surounding freq piers to
2813 		 * get the final curve for this
2814 		 * pd gain. Re-use tmpL for interpolation
2815 		 * output */
2816 		for (i = 0; (i < (u16) (table_max[pdg] - table_min[pdg])) &&
2817 		(i < AR5K_EEPROM_POWER_TABLE_SIZE); i++) {
2818 			tmpL[i] = (u8) ath5k_get_interpolated_value(target,
2819 							(s16) pcinfo_L->freq,
2820 							(s16) pcinfo_R->freq,
2821 							(s16) tmpL[i],
2822 							(s16) tmpR[i]);
2823 		}
2824 	}
2825 
2826 	/* Now we have a set of curves for this
2827 	 * channel on tmpL (x range is table_max - table_min
2828 	 * and y values are tmpL[pdg][]) sorted in the same
2829 	 * order as EEPROM (because we've used the backmapping).
2830 	 * So for RF5112 it's from higher power to lower power
2831 	 * and for RF2413 it's from lower power to higher power.
2832 	 * For RF5111 we only have one curve. */
2833 
2834 	/* Fill min and max power levels for this
2835 	 * channel by interpolating the values on
2836 	 * surounding channels to complete the dataset */
2837 	ah->ah_txpower.txp_min_pwr = ath5k_get_interpolated_value(target,
2838 					(s16) pcinfo_L->freq,
2839 					(s16) pcinfo_R->freq,
2840 					pcinfo_L->min_pwr, pcinfo_R->min_pwr);
2841 
2842 	ah->ah_txpower.txp_max_pwr = ath5k_get_interpolated_value(target,
2843 					(s16) pcinfo_L->freq,
2844 					(s16) pcinfo_R->freq,
2845 					pcinfo_L->max_pwr, pcinfo_R->max_pwr);
2846 
2847 	/* We are ready to go, fill PCDAC/PDADC
2848 	 * table and write settings on hardware */
2849 	switch (type) {
2850 	case AR5K_PWRTABLE_LINEAR_PCDAC:
2851 		/* For RF5112 we can have one or two curves
2852 		 * and each curve covers a certain power lvl
2853 		 * range so we need to do some more processing */
2854 		ath5k_combine_linear_pcdac_curves(ah, table_min, table_max,
2855 						ee->ee_pd_gains[ee_mode]);
2856 
2857 		/* Set txp.offset so that we can
2858 		 * match max power value with max
2859 		 * table index */
2860 		ah->ah_txpower.txp_offset = 64 - (table_max[0] / 2);
2861 
2862 		/* Write settings on hw */
2863 		ath5k_setup_pcdac_table(ah);
2864 		break;
2865 	case AR5K_PWRTABLE_PWR_TO_PCDAC:
2866 		/* We are done for RF5111 since it has only
2867 		 * one curve, just fit the curve on the table */
2868 		ath5k_fill_pwr_to_pcdac_table(ah, table_min, table_max);
2869 
2870 		/* No rate powertable adjustment for RF5111 */
2871 		ah->ah_txpower.txp_min_idx = 0;
2872 		ah->ah_txpower.txp_offset = 0;
2873 
2874 		/* Write settings on hw */
2875 		ath5k_setup_pcdac_table(ah);
2876 		break;
2877 	case AR5K_PWRTABLE_PWR_TO_PDADC:
2878 		/* Set PDADC boundaries and fill
2879 		 * final PDADC table */
2880 		ath5k_combine_pwr_to_pdadc_curves(ah, table_min, table_max,
2881 						ee->ee_pd_gains[ee_mode]);
2882 
2883 		/* Write settings on hw */
2884 		ath5k_setup_pwr_to_pdadc_table(ah, pdg, pdg_curve_to_idx);
2885 
2886 		/* Set txp.offset, note that table_min
2887 		 * can be negative */
2888 		ah->ah_txpower.txp_offset = table_min[0];
2889 		break;
2890 	default:
2891 		return -EINVAL;
2892 	}
2893 
2894 	return 0;
2895 }
2896 
2897 
2898 /*
2899  * Per-rate tx power setting
2900  *
2901  * This is the code that sets the desired tx power (below
2902  * maximum) on hw for each rate (we also have TPC that sets
2903  * power per packet). We do that by providing an index on the
2904  * PCDAC/PDADC table we set up.
2905  */
2906 
2907 /*
2908  * Set rate power table
2909  *
2910  * For now we only limit txpower based on maximum tx power
2911  * supported by hw (what's inside rate_info). We need to limit
2912  * this even more, based on regulatory domain etc.
2913  *
2914  * Rate power table contains indices to PCDAC/PDADC table (0.5dB steps)
2915  * and is indexed as follows:
2916  * rates[0] - rates[7] -> OFDM rates
2917  * rates[8] - rates[14] -> CCK rates
2918  * rates[15] -> XR rates (they all have the same power)
2919  */
2920 static void
2921 ath5k_setup_rate_powertable(struct ath5k_hw *ah, u16 max_pwr,
2922 			struct ath5k_rate_pcal_info *rate_info,
2923 			u8 ee_mode)
2924 {
2925 	unsigned int i;
2926 	u16 *rates;
2927 
2928 	/* max_pwr is power level we got from driver/user in 0.5dB
2929 	 * units, switch to 0.25dB units so we can compare */
2930 	max_pwr *= 2;
2931 	max_pwr = min(max_pwr, (u16) ah->ah_txpower.txp_max_pwr) / 2;
2932 
2933 	/* apply rate limits */
2934 	rates = ah->ah_txpower.txp_rates_power_table;
2935 
2936 	/* OFDM rates 6 to 24Mb/s */
2937 	for (i = 0; i < 5; i++)
2938 		rates[i] = min(max_pwr, rate_info->target_power_6to24);
2939 
2940 	/* Rest OFDM rates */
2941 	rates[5] = min(rates[0], rate_info->target_power_36);
2942 	rates[6] = min(rates[0], rate_info->target_power_48);
2943 	rates[7] = min(rates[0], rate_info->target_power_54);
2944 
2945 	/* CCK rates */
2946 	/* 1L */
2947 	rates[8] = min(rates[0], rate_info->target_power_6to24);
2948 	/* 2L */
2949 	rates[9] = min(rates[0], rate_info->target_power_36);
2950 	/* 2S */
2951 	rates[10] = min(rates[0], rate_info->target_power_36);
2952 	/* 5L */
2953 	rates[11] = min(rates[0], rate_info->target_power_48);
2954 	/* 5S */
2955 	rates[12] = min(rates[0], rate_info->target_power_48);
2956 	/* 11L */
2957 	rates[13] = min(rates[0], rate_info->target_power_54);
2958 	/* 11S */
2959 	rates[14] = min(rates[0], rate_info->target_power_54);
2960 
2961 	/* XR rates */
2962 	rates[15] = min(rates[0], rate_info->target_power_6to24);
2963 
2964 	/* CCK rates have different peak to average ratio
2965 	 * so we have to tweak their power so that gainf
2966 	 * correction works ok. For this we use OFDM to
2967 	 * CCK delta from eeprom */
2968 	if ((ee_mode == AR5K_EEPROM_MODE_11G) &&
2969 	(ah->ah_phy_revision < AR5K_SREV_PHY_5212A))
2970 		for (i = 8; i <= 15; i++)
2971 			rates[i] -= ah->ah_txpower.txp_cck_ofdm_gainf_delta;
2972 
2973 	/* Now that we have all rates setup use table offset to
2974 	 * match the power range set by user with the power indices
2975 	 * on PCDAC/PDADC table */
2976 	for (i = 0; i < 16; i++) {
2977 		rates[i] += ah->ah_txpower.txp_offset;
2978 		/* Don't get out of bounds */
2979 		if (rates[i] > 63)
2980 			rates[i] = 63;
2981 	}
2982 
2983 	/* Min/max in 0.25dB units */
2984 	ah->ah_txpower.txp_min_pwr = 2 * rates[7];
2985 	ah->ah_txpower.txp_max_pwr = 2 * rates[0];
2986 	ah->ah_txpower.txp_ofdm = rates[7];
2987 }
2988 
2989 
2990 /*
2991  * Set transmission power
2992  */
2993 int
2994 ath5k_hw_txpower(struct ath5k_hw *ah, struct ieee80211_channel *channel,
2995 		u8 ee_mode, u8 txpower)
2996 {
2997 	struct ath5k_rate_pcal_info rate_info;
2998 	u8 type;
2999 	int ret;
3000 
3001 	if (txpower > AR5K_TUNE_MAX_TXPOWER) {
3002 		ATH5K_ERR(ah->ah_sc, "invalid tx power: %u\n", txpower);
3003 		return -EINVAL;
3004 	}
3005 
3006 	/* Reset TX power values */
3007 	memset(&ah->ah_txpower, 0, sizeof(ah->ah_txpower));
3008 	ah->ah_txpower.txp_tpc = AR5K_TUNE_TPC_TXPOWER;
3009 	ah->ah_txpower.txp_min_pwr = 0;
3010 	ah->ah_txpower.txp_max_pwr = AR5K_TUNE_MAX_TXPOWER;
3011 
3012 	/* Initialize TX power table */
3013 	switch (ah->ah_radio) {
3014 	case AR5K_RF5111:
3015 		type = AR5K_PWRTABLE_PWR_TO_PCDAC;
3016 		break;
3017 	case AR5K_RF5112:
3018 		type = AR5K_PWRTABLE_LINEAR_PCDAC;
3019 		break;
3020 	case AR5K_RF2413:
3021 	case AR5K_RF5413:
3022 	case AR5K_RF2316:
3023 	case AR5K_RF2317:
3024 	case AR5K_RF2425:
3025 		type = AR5K_PWRTABLE_PWR_TO_PDADC;
3026 		break;
3027 	default:
3028 		return -EINVAL;
3029 	}
3030 
3031 	/* FIXME: Only on channel/mode change */
3032 	ret = ath5k_setup_channel_powertable(ah, channel, ee_mode, type);
3033 	if (ret)
3034 		return ret;
3035 
3036 	/* Limit max power if we have a CTL available */
3037 	ath5k_get_max_ctl_power(ah, channel);
3038 
3039 	/* FIXME: Antenna reduction stuff */
3040 
3041 	/* FIXME: Limit power on turbo modes */
3042 
3043 	/* FIXME: TPC scale reduction */
3044 
3045 	/* Get surounding channels for per-rate power table
3046 	 * calibration */
3047 	ath5k_get_rate_pcal_data(ah, channel, &rate_info);
3048 
3049 	/* Setup rate power table */
3050 	ath5k_setup_rate_powertable(ah, txpower, &rate_info, ee_mode);
3051 
3052 	/* Write rate power table on hw */
3053 	ath5k_hw_reg_write(ah, AR5K_TXPOWER_OFDM(3, 24) |
3054 		AR5K_TXPOWER_OFDM(2, 16) | AR5K_TXPOWER_OFDM(1, 8) |
3055 		AR5K_TXPOWER_OFDM(0, 0), AR5K_PHY_TXPOWER_RATE1);
3056 
3057 	ath5k_hw_reg_write(ah, AR5K_TXPOWER_OFDM(7, 24) |
3058 		AR5K_TXPOWER_OFDM(6, 16) | AR5K_TXPOWER_OFDM(5, 8) |
3059 		AR5K_TXPOWER_OFDM(4, 0), AR5K_PHY_TXPOWER_RATE2);
3060 
3061 	ath5k_hw_reg_write(ah, AR5K_TXPOWER_CCK(10, 24) |
3062 		AR5K_TXPOWER_CCK(9, 16) | AR5K_TXPOWER_CCK(15, 8) |
3063 		AR5K_TXPOWER_CCK(8, 0), AR5K_PHY_TXPOWER_RATE3);
3064 
3065 	ath5k_hw_reg_write(ah, AR5K_TXPOWER_CCK(14, 24) |
3066 		AR5K_TXPOWER_CCK(13, 16) | AR5K_TXPOWER_CCK(12, 8) |
3067 		AR5K_TXPOWER_CCK(11, 0), AR5K_PHY_TXPOWER_RATE4);
3068 
3069 	/* FIXME: TPC support */
3070 	if (ah->ah_txpower.txp_tpc) {
3071 		ath5k_hw_reg_write(ah, AR5K_PHY_TXPOWER_RATE_MAX_TPC_ENABLE |
3072 			AR5K_TUNE_MAX_TXPOWER, AR5K_PHY_TXPOWER_RATE_MAX);
3073 
3074 		ath5k_hw_reg_write(ah,
3075 			AR5K_REG_MS(AR5K_TUNE_MAX_TXPOWER, AR5K_TPC_ACK) |
3076 			AR5K_REG_MS(AR5K_TUNE_MAX_TXPOWER, AR5K_TPC_CTS) |
3077 			AR5K_REG_MS(AR5K_TUNE_MAX_TXPOWER, AR5K_TPC_CHIRP),
3078 			AR5K_TPC);
3079 	} else {
3080 		ath5k_hw_reg_write(ah, AR5K_PHY_TXPOWER_RATE_MAX |
3081 			AR5K_TUNE_MAX_TXPOWER, AR5K_PHY_TXPOWER_RATE_MAX);
3082 	}
3083 
3084 	return 0;
3085 }
3086 
3087 int ath5k_hw_set_txpower_limit(struct ath5k_hw *ah, u8 txpower)
3088 {
3089 	/*Just a try M.F.*/
3090 	struct ieee80211_channel *channel = ah->ah_current_channel;
3091 	u8 ee_mode;
3092 
3093 	switch (channel->hw_value & CHANNEL_MODES) {
3094 	case CHANNEL_A:
3095 	case CHANNEL_T:
3096 	case CHANNEL_XR:
3097 		ee_mode = AR5K_EEPROM_MODE_11A;
3098 		break;
3099 	case CHANNEL_G:
3100 	case CHANNEL_TG:
3101 		ee_mode = AR5K_EEPROM_MODE_11G;
3102 		break;
3103 	case CHANNEL_B:
3104 		ee_mode = AR5K_EEPROM_MODE_11B;
3105 		break;
3106 	default:
3107 		ATH5K_ERR(ah->ah_sc,
3108 			"invalid channel: %d\n", channel->center_freq);
3109 		return -EINVAL;
3110 	}
3111 
3112 	ATH5K_DBG(ah->ah_sc, ATH5K_DEBUG_TXPOWER,
3113 		"changing txpower to %d\n", txpower);
3114 
3115 	return ath5k_hw_txpower(ah, channel, ee_mode, txpower);
3116 }
3117