[media] cx24120: Convert read_ber to retrieve from cache
[firefly-linux-kernel-4.4.55.git] / drivers / media / dvb-frontends / cx24120.c
1 /*
2     Conexant cx24120/cx24118 - DVBS/S2 Satellite demod/tuner driver
3
4     Copyright (C) 2008 Patrick Boettcher <pb@linuxtv.org>
5     Copyright (C) 2009 Sergey Tyurin <forum.free-x.de>
6     Updated 2012 by Jannis Achstetter <jannis_achstetter@web.de>
7     Copyright (C) 2015 Jemma Denson <jdenson@gmail.com>
8         April 2015
9             Refactored & simplified driver
10             Updated to work with delivery system supplied by DVBv5
11             Add frequency, fec & pilot to get_frontend
12
13         Cards supported: Technisat Skystar S2
14
15     This program is free software; you can redistribute it and/or modify
16     it under the terms of the GNU General Public License as published by
17     the Free Software Foundation; either version 2 of the License, or
18     (at your option) any later version.
19
20     This program is distributed in the hope that it will be useful,
21     but WITHOUT ANY WARRANTY; without even the implied warranty of
22     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23     GNU General Public License for more details.
24 */
25
26 #include <linux/slab.h>
27 #include <linux/kernel.h>
28 #include <linux/module.h>
29 #include <linux/moduleparam.h>
30 #include <linux/init.h>
31 #include <linux/firmware.h>
32 #include "dvb_frontend.h"
33 #include "cx24120.h"
34
35 #define CX24120_SEARCH_RANGE_KHZ 5000
36 #define CX24120_FIRMWARE "dvb-fe-cx24120-1.20.58.2.fw"
37
38 /* cx24120 i2c registers  */
39 #define CX24120_REG_CMD_START   0x00            /* write cmd_id */
40 #define CX24120_REG_CMD_ARGS    0x01            /* write command arguments */
41 #define CX24120_REG_CMD_END     0x1f            /* write 0x01 for end */
42
43 #define CX24120_REG_MAILBOX     0x33
44 #define CX24120_REG_FREQ3       0x34            /* frequency */
45 #define CX24120_REG_FREQ2       0x35
46 #define CX24120_REG_FREQ1       0x36
47
48 #define CX24120_REG_FECMODE     0x39            /* FEC status */
49 #define CX24120_REG_STATUS      0x3a            /* Tuner status */
50 #define CX24120_REG_SIGSTR_H    0x3a            /* Signal strength high */
51 #define CX24120_REG_SIGSTR_L    0x3b            /* Signal strength low byte */
52 #define CX24120_REG_QUALITY_H   0x40            /* SNR high byte */
53 #define CX24120_REG_QUALITY_L   0x41            /* SNR low byte */
54
55 #define CX24120_REG_BER_HH      0x47            /* BER high byte of high word */
56 #define CX24120_REG_BER_HL      0x48            /* BER low byte of high word */
57 #define CX24120_REG_BER_LH      0x49            /* BER high byte of low word */
58 #define CX24120_REG_BER_LL      0x4a            /* BER low byte of low word */
59
60 #define CX24120_REG_UCB_H       0x50            /* UCB high byte */
61 #define CX24120_REG_UCB_L       0x51            /* UCB low byte  */
62
63 #define CX24120_REG_CLKDIV      0xe6
64 #define CX24120_REG_RATEDIV     0xf0
65
66 #define CX24120_REG_REVISION    0xff            /* Chip revision (ro) */
67
68 /* Command messages */
69 enum command_message_id {
70         CMD_VCO_SET             = 0x10,         /* cmd.len = 12; */
71         CMD_TUNEREQUEST         = 0x11,         /* cmd.len = 15; */
72
73         CMD_MPEG_ONOFF          = 0x13,         /* cmd.len = 4; */
74         CMD_MPEG_INIT           = 0x14,         /* cmd.len = 7; */
75         CMD_BANDWIDTH           = 0x15,         /* cmd.len = 12; */
76         CMD_CLOCK_READ          = 0x16,         /* read clock */
77         CMD_CLOCK_SET           = 0x17,         /* cmd.len = 10; */
78
79         CMD_DISEQC_MSG1         = 0x20,         /* cmd.len = 11; */
80         CMD_DISEQC_MSG2         = 0x21,         /* cmd.len = d->msg_len + 6; */
81         CMD_SETVOLTAGE          = 0x22,         /* cmd.len = 2; */
82         CMD_SETTONE             = 0x23,         /* cmd.len = 4; */
83         CMD_DISEQC_BURST        = 0x24,         /* cmd.len not used !!! */
84
85         CMD_READ_SNR            = 0x1a,         /* Read signal strength */
86         CMD_START_TUNER         = 0x1b,         /* ??? */
87
88         CMD_FWVERSION           = 0x35,
89
90         CMD_BER_CTRL            = 0x3c,         /* cmd.len = 0x03; */
91 };
92
93 #define CX24120_MAX_CMD_LEN     30
94
95 /* pilot mask */
96 #define CX24120_PILOT_OFF       0x00
97 #define CX24120_PILOT_ON        0x40
98 #define CX24120_PILOT_AUTO      0x80
99
100 /* signal status */
101 #define CX24120_HAS_SIGNAL      0x01
102 #define CX24120_HAS_CARRIER     0x02
103 #define CX24120_HAS_VITERBI     0x04
104 #define CX24120_HAS_LOCK        0x08
105 #define CX24120_HAS_UNK1        0x10
106 #define CX24120_HAS_UNK2        0x20
107 #define CX24120_STATUS_MASK     0x0f
108 #define CX24120_SIGNAL_MASK     0xc0
109
110 /* ber window */
111 #define CX24120_BER_WINDOW      16
112 #define CX24120_BER_WSIZE       ((1 << CX24120_BER_WINDOW) * 208 * 8)
113
114 #define info(args...) pr_info("cx24120: " args)
115 #define err(args...)  pr_err("cx24120: ### ERROR: " args)
116
117 /* The Demod/Tuner can't easily provide these, we cache them */
118 struct cx24120_tuning {
119         u32 frequency;
120         u32 symbol_rate;
121         fe_spectral_inversion_t inversion;
122         fe_code_rate_t fec;
123
124         fe_delivery_system_t delsys;
125         fe_modulation_t modulation;
126         fe_pilot_t pilot;
127
128         /* Demod values */
129         u8 fec_val;
130         u8 fec_mask;
131         u8 clkdiv;
132         u8 ratediv;
133         u8 inversion_val;
134         u8 pilot_val;
135 };
136
137 /* Private state */
138 struct cx24120_state {
139         struct i2c_adapter *i2c;
140         const struct cx24120_config *config;
141         struct dvb_frontend frontend;
142
143         u8 cold_init;
144         u8 mpeg_enabled;
145         u8 need_clock_set;
146
147         /* current and next tuning parameters */
148         struct cx24120_tuning dcur;
149         struct cx24120_tuning dnxt;
150
151         fe_status_t fe_status;
152
153         /* ber stats calulations */
154         u32 berw_usecs;
155         u32 ber_prev;
156         unsigned long ber_jiffies_stats;
157 };
158
159 /* Command message to firmware */
160 struct cx24120_cmd {
161         u8 id;
162         u8 len;
163         u8 arg[CX24120_MAX_CMD_LEN];
164 };
165
166 /* Read single register */
167 static int cx24120_readreg(struct cx24120_state *state, u8 reg)
168 {
169         int ret;
170         u8 buf = 0;
171         struct i2c_msg msg[] = {
172                 {
173                         .addr = state->config->i2c_addr,
174                         .flags = 0,
175                         .len = 1,
176                         .buf = &reg
177                 }, {
178                         .addr = state->config->i2c_addr,
179                         .flags = I2C_M_RD,
180                         .len = 1,
181                         .buf = &buf
182                 }
183         };
184
185         ret = i2c_transfer(state->i2c, msg, 2);
186         if (ret != 2) {
187                 err("Read error: reg=0x%02x, ret=%i)\n", reg, ret);
188                 return ret;
189         }
190
191         dev_dbg(&state->i2c->dev, "reg=0x%02x; data=0x%02x\n", reg, buf);
192
193         return buf;
194 }
195
196 /* Write single register */
197 static int cx24120_writereg(struct cx24120_state *state, u8 reg, u8 data)
198 {
199         u8 buf[] = { reg, data };
200         struct i2c_msg msg = {
201                 .addr = state->config->i2c_addr,
202                 .flags = 0,
203                 .buf = buf,
204                 .len = 2
205         };
206         int ret;
207
208         ret = i2c_transfer(state->i2c, &msg, 1);
209         if (ret != 1) {
210                 err("Write error: i2c_write error(err == %i, 0x%02x: 0x%02x)\n",
211                     ret, reg, data);
212                 return ret;
213         }
214
215         dev_dbg(&state->i2c->dev, "reg=0x%02x; data=0x%02x\n", reg, data);
216
217         return 0;
218 }
219
220 /* Write multiple registers in chunks of i2c_wr_max-sized buffers */
221 static int cx24120_writeregs(struct cx24120_state *state,
222                              u8 reg, const u8 *values, u16 len, u8 incr)
223 {
224         int ret;
225         u16 max = state->config->i2c_wr_max > 0 ?
226                                 state->config->i2c_wr_max :
227                                 len;
228
229         struct i2c_msg msg = {
230                 .addr = state->config->i2c_addr,
231                 .flags = 0,
232         };
233
234         msg.buf = kmalloc(max + 1, GFP_KERNEL);
235         if (!msg.buf)
236                 return -ENOMEM;
237
238         while (len) {
239                 msg.buf[0] = reg;
240                 msg.len = len > max ? max : len;
241                 memcpy(&msg.buf[1], values, msg.len);
242
243                 len    -= msg.len;      /* data length revers counter */
244                 values += msg.len;      /* incr data pointer */
245
246                 if (incr)
247                         reg += msg.len;
248                 msg.len++;              /* don't forget the addr byte */
249
250                 ret = i2c_transfer(state->i2c, &msg, 1);
251                 if (ret != 1) {
252                         err("i2c_write error(err == %i, 0x%02x)\n", ret, reg);
253                         goto out;
254                 }
255
256                 dev_dbg(&state->i2c->dev, "reg=0x%02x; data=%*ph\n",
257                         reg, msg.len - 1, msg.buf + 1);
258         }
259
260         ret = 0;
261
262 out:
263         kfree(msg.buf);
264         return ret;
265 }
266
267 static struct dvb_frontend_ops cx24120_ops;
268
269 struct dvb_frontend *cx24120_attach(const struct cx24120_config *config,
270                                     struct i2c_adapter *i2c)
271 {
272         struct cx24120_state *state;
273         int demod_rev;
274
275         info("Conexant cx24120/cx24118 - DVBS/S2 Satellite demod/tuner\n");
276         state = kzalloc(sizeof(*state), GFP_KERNEL);
277         if (!state) {
278                 err("Unable to allocate memory for cx24120_state\n");
279                 goto error;
280         }
281
282         /* setup the state */
283         state->config = config;
284         state->i2c = i2c;
285
286         /* check if the demod is present and has proper type */
287         demod_rev = cx24120_readreg(state, CX24120_REG_REVISION);
288         switch (demod_rev) {
289         case 0x07:
290                 info("Demod cx24120 rev. 0x07 detected.\n");
291                 break;
292         case 0x05:
293                 info("Demod cx24120 rev. 0x05 detected.\n");
294                 break;
295         default:
296                 err("Unsupported demod revision: 0x%x detected.\n", demod_rev);
297                 goto error;
298         }
299
300         /* create dvb_frontend */
301         state->cold_init = 0;
302         memcpy(&state->frontend.ops, &cx24120_ops,
303                sizeof(struct dvb_frontend_ops));
304         state->frontend.demodulator_priv = state;
305
306         info("Conexant cx24120/cx24118 attached.\n");
307         return &state->frontend;
308
309 error:
310         kfree(state);
311         return NULL;
312 }
313 EXPORT_SYMBOL(cx24120_attach);
314
315 static int cx24120_test_rom(struct cx24120_state *state)
316 {
317         int err, ret;
318
319         err = cx24120_readreg(state, 0xfd);
320         if (err & 4) {
321                 ret = cx24120_readreg(state, 0xdf) & 0xfe;
322                 err = cx24120_writereg(state, 0xdf, ret);
323         }
324         return err;
325 }
326
327 static int cx24120_read_snr(struct dvb_frontend *fe, u16 *snr)
328 {
329         struct dtv_frontend_properties *c = &fe->dtv_property_cache;
330
331         if (c->cnr.stat[0].scale != FE_SCALE_DECIBEL)
332                 *snr = 0;
333         else
334                 *snr = div_s64(c->cnr.stat[0].svalue, 100);
335
336         return 0;
337 }
338
339 static int cx24120_read_ber(struct dvb_frontend *fe, u32 *ber)
340 {
341         struct cx24120_state *state = fe->demodulator_priv;
342         struct dtv_frontend_properties *c = &fe->dtv_property_cache;
343
344         if (c->post_bit_error.stat[0].scale != FE_SCALE_COUNTER) {
345                 *ber = 0;
346                 return 0;
347         }
348
349         *ber = c->post_bit_error.stat[0].uvalue - state->ber_prev;
350         state->ber_prev = c->post_bit_error.stat[0].uvalue;
351
352         return 0;
353 }
354
355 static int cx24120_msg_mpeg_output_global_config(struct cx24120_state *state,
356                                                  u8 flag);
357
358 /* Check if we're running a command that needs to disable mpeg out */
359 static void cx24120_check_cmd(struct cx24120_state *state, u8 id)
360 {
361         switch (id) {
362         case CMD_TUNEREQUEST:
363         case CMD_CLOCK_READ:
364         case CMD_DISEQC_MSG1:
365         case CMD_DISEQC_MSG2:
366         case CMD_SETVOLTAGE:
367         case CMD_SETTONE:
368         case CMD_DISEQC_BURST:
369                 cx24120_msg_mpeg_output_global_config(state, 0);
370                 /* Old driver would do a msleep(100) here */
371         default:
372                 return;
373         }
374 }
375
376 /* Send a message to the firmware */
377 static int cx24120_message_send(struct cx24120_state *state,
378                                 struct cx24120_cmd *cmd)
379 {
380         int ficus;
381
382         if (state->mpeg_enabled) {
383                 /* Disable mpeg out on certain commands */
384                 cx24120_check_cmd(state, cmd->id);
385         }
386
387         cx24120_writereg(state, CX24120_REG_CMD_START, cmd->id);
388         cx24120_writeregs(state, CX24120_REG_CMD_ARGS, &cmd->arg[0],
389                           cmd->len, 1);
390         cx24120_writereg(state, CX24120_REG_CMD_END, 0x01);
391
392         ficus = 1000;
393         while (cx24120_readreg(state, CX24120_REG_CMD_END)) {
394                 msleep(20);
395                 ficus -= 20;
396                 if (ficus == 0) {
397                         err("Error sending message to firmware\n");
398                         return -EREMOTEIO;
399                 }
400         }
401         dev_dbg(&state->i2c->dev, "sent message 0x%02x\n", cmd->id);
402
403         return 0;
404 }
405
406 /* Send a message and fill arg[] with the results */
407 static int cx24120_message_sendrcv(struct cx24120_state *state,
408                                    struct cx24120_cmd *cmd, u8 numreg)
409 {
410         int ret, i;
411
412         if (numreg > CX24120_MAX_CMD_LEN) {
413                 err("Too many registers to read. cmd->reg = %d", numreg);
414                 return -EREMOTEIO;
415         }
416
417         ret = cx24120_message_send(state, cmd);
418         if (ret != 0)
419                 return ret;
420
421         if (!numreg)
422                 return 0;
423
424         /* Read numreg registers starting from register cmd->len */
425         for (i = 0; i < numreg; i++)
426                 cmd->arg[i] = cx24120_readreg(state, (cmd->len + i + 1));
427
428         return 0;
429 }
430
431 static int cx24120_read_signal_strength(struct dvb_frontend *fe,
432                                         u16 *signal_strength)
433 {
434         struct dtv_frontend_properties *c = &fe->dtv_property_cache;
435
436         if (c->strength.stat[0].scale != FE_SCALE_RELATIVE)
437                 *signal_strength = 0;
438         else
439                 *signal_strength = c->strength.stat[0].uvalue;
440
441         return 0;
442 }
443
444 static int cx24120_msg_mpeg_output_global_config(struct cx24120_state *state,
445                                                  u8 enable)
446 {
447         struct cx24120_cmd cmd;
448         int ret;
449
450         cmd.id = CMD_MPEG_ONOFF;
451         cmd.len = 4;
452         cmd.arg[0] = 0x01;
453         cmd.arg[1] = 0x00;
454         cmd.arg[2] = enable ? 0 : (u8)(-1);
455         cmd.arg[3] = 0x01;
456
457         ret = cx24120_message_send(state, &cmd);
458         if (ret != 0) {
459                 dev_dbg(&state->i2c->dev, "failed to %s MPEG output\n",
460                         enable ? "enable" : "disable");
461                 return ret;
462         }
463
464         state->mpeg_enabled = enable;
465         dev_dbg(&state->i2c->dev, "MPEG output %s\n",
466                 enable ? "enabled" : "disabled");
467
468         return 0;
469 }
470
471 static int cx24120_msg_mpeg_output_config(struct cx24120_state *state, u8 seq)
472 {
473         struct cx24120_cmd cmd;
474         struct cx24120_initial_mpeg_config i =
475                         state->config->initial_mpeg_config;
476
477         cmd.id = CMD_MPEG_INIT;
478         cmd.len = 7;
479         cmd.arg[0] = seq; /* sequental number - can be 0,1,2 */
480         cmd.arg[1] = ((i.x1 & 0x01) << 1) | ((i.x1 >> 1) & 0x01);
481         cmd.arg[2] = 0x05;
482         cmd.arg[3] = 0x02;
483         cmd.arg[4] = ((i.x2 >> 1) & 0x01);
484         cmd.arg[5] = (i.x2 & 0xf0) | (i.x3 & 0x0f);
485         cmd.arg[6] = 0x10;
486
487         return cx24120_message_send(state, &cmd);
488 }
489
490 static int cx24120_diseqc_send_burst(struct dvb_frontend *fe,
491                                      fe_sec_mini_cmd_t burst)
492 {
493         struct cx24120_state *state = fe->demodulator_priv;
494         struct cx24120_cmd cmd;
495
496         dev_dbg(&state->i2c->dev, "\n");
497
498         /*
499          * Yes, cmd.len is set to zero. The old driver
500          * didn't specify any len, but also had a
501          * memset 0 before every use of the cmd struct
502          * which would have set it to zero.
503          * This quite probably needs looking into.
504          */
505         cmd.id = CMD_DISEQC_BURST;
506         cmd.len = 0;
507         cmd.arg[0] = 0x00;
508         cmd.arg[1] = (burst == SEC_MINI_B) ? 0x01 : 0x00;
509
510         return cx24120_message_send(state, &cmd);
511 }
512
513 static int cx24120_set_tone(struct dvb_frontend *fe, fe_sec_tone_mode_t tone)
514 {
515         struct cx24120_state *state = fe->demodulator_priv;
516         struct cx24120_cmd cmd;
517
518         dev_dbg(&state->i2c->dev, "(%d)\n", tone);
519
520         if ((tone != SEC_TONE_ON) && (tone != SEC_TONE_OFF)) {
521                 err("Invalid tone=%d\n", tone);
522                 return -EINVAL;
523         }
524
525         cmd.id = CMD_SETTONE;
526         cmd.len = 4;
527         cmd.arg[0] = 0x00;
528         cmd.arg[1] = 0x00;
529         cmd.arg[2] = 0x00;
530         cmd.arg[3] = (tone == SEC_TONE_ON) ? 0x01 : 0x00;
531
532         return cx24120_message_send(state, &cmd);
533 }
534
535 static int cx24120_set_voltage(struct dvb_frontend *fe,
536                                fe_sec_voltage_t voltage)
537 {
538         struct cx24120_state *state = fe->demodulator_priv;
539         struct cx24120_cmd cmd;
540
541         dev_dbg(&state->i2c->dev, "(%d)\n", voltage);
542
543         cmd.id = CMD_SETVOLTAGE;
544         cmd.len = 2;
545         cmd.arg[0] = 0x00;
546         cmd.arg[1] = (voltage == SEC_VOLTAGE_18) ? 0x01 : 0x00;
547
548         return cx24120_message_send(state, &cmd);
549 }
550
551 static int cx24120_send_diseqc_msg(struct dvb_frontend *fe,
552                                    struct dvb_diseqc_master_cmd *d)
553 {
554         struct cx24120_state *state = fe->demodulator_priv;
555         struct cx24120_cmd cmd;
556         int back_count;
557
558         dev_dbg(&state->i2c->dev, "\n");
559
560         cmd.id = CMD_DISEQC_MSG1;
561         cmd.len = 11;
562         cmd.arg[0] = 0x00;
563         cmd.arg[1] = 0x00;
564         cmd.arg[2] = 0x03;
565         cmd.arg[3] = 0x16;
566         cmd.arg[4] = 0x28;
567         cmd.arg[5] = 0x01;
568         cmd.arg[6] = 0x01;
569         cmd.arg[7] = 0x14;
570         cmd.arg[8] = 0x19;
571         cmd.arg[9] = 0x14;
572         cmd.arg[10] = 0x1e;
573
574         if (cx24120_message_send(state, &cmd)) {
575                 err("send 1st message(0x%x) failed\n", cmd.id);
576                 return -EREMOTEIO;
577         }
578
579         cmd.id = CMD_DISEQC_MSG2;
580         cmd.len = d->msg_len + 6;
581         cmd.arg[0] = 0x00;
582         cmd.arg[1] = 0x01;
583         cmd.arg[2] = 0x02;
584         cmd.arg[3] = 0x00;
585         cmd.arg[4] = 0x00;
586         cmd.arg[5] = d->msg_len;
587
588         memcpy(&cmd.arg[6], &d->msg, d->msg_len);
589
590         if (cx24120_message_send(state, &cmd)) {
591                 err("send 2nd message(0x%x) failed\n", cmd.id);
592                 return -EREMOTEIO;
593         }
594
595         back_count = 500;
596         do {
597                 if (!(cx24120_readreg(state, 0x93) & 0x01)) {
598                         dev_dbg(&state->i2c->dev, "diseqc sequence sent\n");
599                         return 0;
600                 }
601                 msleep(20);
602                 back_count -= 20;
603         } while (back_count);
604
605         err("Too long waiting for diseqc.\n");
606         return -ETIMEDOUT;
607 }
608
609 static void cx24120_get_stats(struct cx24120_state *state)
610 {
611         struct dvb_frontend *fe = &state->frontend;
612         struct dtv_frontend_properties *c = &fe->dtv_property_cache;
613         struct cx24120_cmd cmd;
614         int ret, cnr, msecs;
615         u16 sig;
616         u32 ber;
617
618         dev_dbg(&state->i2c->dev, "\n");
619
620         /* signal strength */
621         if (state->fe_status & FE_HAS_SIGNAL) {
622                 cmd.id = CMD_READ_SNR;
623                 cmd.len = 1;
624                 cmd.arg[0] = 0x00;
625
626                 ret = cx24120_message_send(state, &cmd);
627                 if (ret != 0) {
628                         err("error reading signal strength\n");
629                         return;
630                 }
631
632                 /* raw */
633                 sig = cx24120_readreg(state, CX24120_REG_SIGSTR_H) >> 6;
634                 sig = sig << 8;
635                 sig |= cx24120_readreg(state, CX24120_REG_SIGSTR_L);
636                 dev_dbg(&state->i2c->dev,
637                         "signal strength from firmware = 0x%x\n", sig);
638
639                 /* cooked */
640                 sig = -100 * sig + 94324;
641
642                 c->strength.stat[0].scale = FE_SCALE_RELATIVE;
643                 c->strength.stat[0].uvalue = sig;
644         } else {
645                 c->strength.stat[0].scale = FE_SCALE_NOT_AVAILABLE;
646         }
647
648         /* CNR */
649         if (state->fe_status & FE_HAS_VITERBI) {
650                 cnr = cx24120_readreg(state, CX24120_REG_QUALITY_H) << 8;
651                 cnr |= cx24120_readreg(state, CX24120_REG_QUALITY_L);
652                 dev_dbg(&state->i2c->dev, "read SNR index = %d\n", cnr);
653
654                 /* guessed - seems about right */
655                 cnr = cnr * 100;
656
657                 c->cnr.stat[0].scale = FE_SCALE_DECIBEL;
658                 c->cnr.stat[0].svalue = cnr;
659         } else {
660                 c->cnr.stat[0].scale = FE_SCALE_NOT_AVAILABLE;
661         }
662
663         /* BER */
664         if (time_after(jiffies, state->ber_jiffies_stats)) {
665                 msecs = (state->berw_usecs + 500) / 1000;
666                 state->ber_jiffies_stats = jiffies + msecs_to_jiffies(msecs);
667
668                 ber = cx24120_readreg(state, CX24120_REG_BER_HH) << 24;
669                 ber |= cx24120_readreg(state, CX24120_REG_BER_HL) << 16;
670                 ber |= cx24120_readreg(state, CX24120_REG_BER_LH) << 8;
671                 ber |= cx24120_readreg(state, CX24120_REG_BER_LL);
672                 dev_dbg(&state->i2c->dev, "read BER index = %d\n", ber);
673
674                 c->post_bit_error.stat[0].scale = FE_SCALE_COUNTER;
675                 c->post_bit_error.stat[0].uvalue += ber;
676
677                 c->post_bit_count.stat[0].scale = FE_SCALE_COUNTER;
678                 c->post_bit_count.stat[0].uvalue += CX24120_BER_WSIZE;
679         }
680
681         /* FIXME: add UCB */
682 }
683
684 static void cx24120_set_clock_ratios(struct dvb_frontend *fe);
685
686 /* Read current tuning status */
687 static int cx24120_read_status(struct dvb_frontend *fe, fe_status_t *status)
688 {
689         struct cx24120_state *state = fe->demodulator_priv;
690         int lock;
691
692         lock = cx24120_readreg(state, CX24120_REG_STATUS);
693
694         dev_dbg(&state->i2c->dev, "status = 0x%02x\n", lock);
695
696         *status = 0;
697
698         if (lock & CX24120_HAS_SIGNAL)
699                 *status = FE_HAS_SIGNAL;
700         if (lock & CX24120_HAS_CARRIER)
701                 *status |= FE_HAS_CARRIER;
702         if (lock & CX24120_HAS_VITERBI)
703                 *status |= FE_HAS_VITERBI | FE_HAS_SYNC;
704         if (lock & CX24120_HAS_LOCK)
705                 *status |= FE_HAS_LOCK;
706
707         /*
708          * TODO: is FE_HAS_SYNC in the right place?
709          * Other cx241xx drivers have this slightly
710          * different
711          */
712
713         state->fe_status = *status;
714         cx24120_get_stats(state);
715
716         /* Set the clock once tuned in */
717         if (state->need_clock_set && *status & FE_HAS_LOCK) {
718                 /* Set clock ratios */
719                 cx24120_set_clock_ratios(fe);
720
721                 /* Old driver would do a msleep(200) here */
722
723                 /* Renable mpeg output */
724                 if (!state->mpeg_enabled)
725                         cx24120_msg_mpeg_output_global_config(state, 1);
726
727                 state->need_clock_set = 0;
728         }
729
730         return 0;
731 }
732
733 /*
734  * FEC & modulation lookup table
735  * Used for decoding the REG_FECMODE register
736  * once tuned in.
737  */
738 struct cx24120_modfec {
739         fe_delivery_system_t delsys;
740         fe_modulation_t mod;
741         fe_code_rate_t fec;
742         u8 val;
743 };
744
745 static const struct cx24120_modfec modfec_lookup_table[] = {
746         /*delsys     mod    fec       val */
747         { SYS_DVBS,  QPSK,  FEC_1_2,  0x01 },
748         { SYS_DVBS,  QPSK,  FEC_2_3,  0x02 },
749         { SYS_DVBS,  QPSK,  FEC_3_4,  0x03 },
750         { SYS_DVBS,  QPSK,  FEC_4_5,  0x04 },
751         { SYS_DVBS,  QPSK,  FEC_5_6,  0x05 },
752         { SYS_DVBS,  QPSK,  FEC_6_7,  0x06 },
753         { SYS_DVBS,  QPSK,  FEC_7_8,  0x07 },
754
755         { SYS_DVBS2, QPSK,  FEC_1_2,  0x04 },
756         { SYS_DVBS2, QPSK,  FEC_3_5,  0x05 },
757         { SYS_DVBS2, QPSK,  FEC_2_3,  0x06 },
758         { SYS_DVBS2, QPSK,  FEC_3_4,  0x07 },
759         { SYS_DVBS2, QPSK,  FEC_4_5,  0x08 },
760         { SYS_DVBS2, QPSK,  FEC_5_6,  0x09 },
761         { SYS_DVBS2, QPSK,  FEC_8_9,  0x0a },
762         { SYS_DVBS2, QPSK,  FEC_9_10, 0x0b },
763
764         { SYS_DVBS2, PSK_8, FEC_3_5,  0x0c },
765         { SYS_DVBS2, PSK_8, FEC_2_3,  0x0d },
766         { SYS_DVBS2, PSK_8, FEC_3_4,  0x0e },
767         { SYS_DVBS2, PSK_8, FEC_5_6,  0x0f },
768         { SYS_DVBS2, PSK_8, FEC_8_9,  0x10 },
769         { SYS_DVBS2, PSK_8, FEC_9_10, 0x11 },
770 };
771
772 /* Retrieve current fec, modulation & pilot values */
773 static int cx24120_get_fec(struct dvb_frontend *fe)
774 {
775         struct dtv_frontend_properties *c = &fe->dtv_property_cache;
776         struct cx24120_state *state = fe->demodulator_priv;
777         int idx;
778         int ret;
779         int fec;
780
781         ret = cx24120_readreg(state, CX24120_REG_FECMODE);
782         fec = ret & 0x3f; /* Lower 6 bits */
783
784         dev_dbg(&state->i2c->dev, "raw fec = %d\n", fec);
785
786         for (idx = 0; idx < ARRAY_SIZE(modfec_lookup_table); idx++) {
787                 if (modfec_lookup_table[idx].delsys != state->dcur.delsys)
788                         continue;
789                 if (modfec_lookup_table[idx].val != fec)
790                         continue;
791
792                 break; /* found */
793         }
794
795         if (idx >= ARRAY_SIZE(modfec_lookup_table)) {
796                 dev_dbg(&state->i2c->dev, "couldn't find fec!\n");
797                 return -EINVAL;
798         }
799
800         /* save values back to cache */
801         c->modulation = modfec_lookup_table[idx].mod;
802         c->fec_inner = modfec_lookup_table[idx].fec;
803         c->pilot = (ret & 0x80) ? PILOT_ON : PILOT_OFF;
804
805         dev_dbg(&state->i2c->dev, "mod(%d), fec(%d), pilot(%d)\n",
806                 c->modulation, c->fec_inner, c->pilot);
807
808         return 0;
809 }
810
811 /* Calculate ber window time */
812 void cx24120_calculate_ber_window(struct cx24120_state *state, u32 rate)
813 {
814         struct dvb_frontend *fe = &state->frontend;
815         struct dtv_frontend_properties *c = &fe->dtv_property_cache;
816         u64 bitrate, tmp;
817
818         /*
819          * Calculate bitrate from rate in the clock ratios table.
820          * This isn't *exactly* right but close enough.
821          */
822         bitrate = (u64)c->symbol_rate * rate;
823         do_div(bitrate, 256);
824
825         /* usecs per ber window */
826         tmp = 1000000ULL * CX24120_BER_WSIZE;
827         do_div(tmp, bitrate);
828         state->berw_usecs = tmp;
829
830         dev_dbg(&state->i2c->dev, "bitrate: %llu, berw_usecs: %u\n",
831                 bitrate, state->berw_usecs);
832 }
833
834 /*
835  * Clock ratios lookup table
836  *
837  * Values obtained from much larger table in old driver
838  * which had numerous entries which would never match.
839  *
840  * There's probably some way of calculating these but I
841  * can't determine the pattern
842  */
843 struct cx24120_clock_ratios_table {
844         fe_delivery_system_t delsys;
845         fe_pilot_t pilot;
846         fe_modulation_t mod;
847         fe_code_rate_t fec;
848         u32 m_rat;
849         u32 n_rat;
850         u32 rate;
851 };
852
853 static const struct cx24120_clock_ratios_table clock_ratios_table[] = {
854         /*delsys     pilot      mod    fec       m_rat    n_rat   rate */
855         { SYS_DVBS2, PILOT_OFF, QPSK,  FEC_1_2,  273088,  254505, 274 },
856         { SYS_DVBS2, PILOT_OFF, QPSK,  FEC_3_5,  17272,   13395,  330 },
857         { SYS_DVBS2, PILOT_OFF, QPSK,  FEC_2_3,  24344,   16967,  367 },
858         { SYS_DVBS2, PILOT_OFF, QPSK,  FEC_3_4,  410788,  254505, 413 },
859         { SYS_DVBS2, PILOT_OFF, QPSK,  FEC_4_5,  438328,  254505, 440 },
860         { SYS_DVBS2, PILOT_OFF, QPSK,  FEC_5_6,  30464,   16967,  459 },
861         { SYS_DVBS2, PILOT_OFF, QPSK,  FEC_8_9,  487832,  254505, 490 },
862         { SYS_DVBS2, PILOT_OFF, QPSK,  FEC_9_10, 493952,  254505, 496 },
863         { SYS_DVBS2, PILOT_OFF, PSK_8, FEC_3_5,  328168,  169905, 494 },
864         { SYS_DVBS2, PILOT_OFF, PSK_8, FEC_2_3,  24344,   11327,  550 },
865         { SYS_DVBS2, PILOT_OFF, PSK_8, FEC_3_4,  410788,  169905, 618 },
866         { SYS_DVBS2, PILOT_OFF, PSK_8, FEC_5_6,  30464,   11327,  688 },
867         { SYS_DVBS2, PILOT_OFF, PSK_8, FEC_8_9,  487832,  169905, 735 },
868         { SYS_DVBS2, PILOT_OFF, PSK_8, FEC_9_10, 493952,  169905, 744 },
869         { SYS_DVBS2, PILOT_ON,  QPSK,  FEC_1_2,  273088,  260709, 268 },
870         { SYS_DVBS2, PILOT_ON,  QPSK,  FEC_3_5,  328168,  260709, 322 },
871         { SYS_DVBS2, PILOT_ON,  QPSK,  FEC_2_3,  121720,  86903,  358 },
872         { SYS_DVBS2, PILOT_ON,  QPSK,  FEC_3_4,  410788,  260709, 403 },
873         { SYS_DVBS2, PILOT_ON,  QPSK,  FEC_4_5,  438328,  260709, 430 },
874         { SYS_DVBS2, PILOT_ON,  QPSK,  FEC_5_6,  152320,  86903,  448 },
875         { SYS_DVBS2, PILOT_ON,  QPSK,  FEC_8_9,  487832,  260709, 479 },
876         { SYS_DVBS2, PILOT_ON,  QPSK,  FEC_9_10, 493952,  260709, 485 },
877         { SYS_DVBS2, PILOT_ON,  PSK_8, FEC_3_5,  328168,  173853, 483 },
878         { SYS_DVBS2, PILOT_ON,  PSK_8, FEC_2_3,  121720,  57951,  537 },
879         { SYS_DVBS2, PILOT_ON,  PSK_8, FEC_3_4,  410788,  173853, 604 },
880         { SYS_DVBS2, PILOT_ON,  PSK_8, FEC_5_6,  152320,  57951,  672 },
881         { SYS_DVBS2, PILOT_ON,  PSK_8, FEC_8_9,  487832,  173853, 718 },
882         { SYS_DVBS2, PILOT_ON,  PSK_8, FEC_9_10, 493952,  173853, 727 },
883         { SYS_DVBS,  PILOT_OFF, QPSK,  FEC_1_2,  152592,  152592, 256 },
884         { SYS_DVBS,  PILOT_OFF, QPSK,  FEC_2_3,  305184,  228888, 341 },
885         { SYS_DVBS,  PILOT_OFF, QPSK,  FEC_3_4,  457776,  305184, 384 },
886         { SYS_DVBS,  PILOT_OFF, QPSK,  FEC_5_6,  762960,  457776, 427 },
887         { SYS_DVBS,  PILOT_OFF, QPSK,  FEC_7_8,  1068144, 610368, 448 },
888 };
889
890 /* Set clock ratio from lookup table */
891 static void cx24120_set_clock_ratios(struct dvb_frontend *fe)
892 {
893         struct dtv_frontend_properties *c = &fe->dtv_property_cache;
894         struct cx24120_state *state = fe->demodulator_priv;
895         struct cx24120_cmd cmd;
896         int ret, idx;
897
898         /* Find fec, modulation, pilot */
899         ret = cx24120_get_fec(fe);
900         if (ret != 0)
901                 return;
902
903         /* Find the clock ratios in the lookup table */
904         for (idx = 0; idx < ARRAY_SIZE(clock_ratios_table); idx++) {
905                 if (clock_ratios_table[idx].delsys != state->dcur.delsys)
906                         continue;
907                 if (clock_ratios_table[idx].mod != c->modulation)
908                         continue;
909                 if (clock_ratios_table[idx].fec != c->fec_inner)
910                         continue;
911                 if (clock_ratios_table[idx].pilot != c->pilot)
912                         continue;
913
914                 break;          /* found */
915         }
916
917         if (idx >= ARRAY_SIZE(clock_ratios_table)) {
918                 info("Clock ratio not found - data reception in danger\n");
919                 return;
920         }
921
922         /* Read current values? */
923         cmd.id = CMD_CLOCK_READ;
924         cmd.len = 1;
925         cmd.arg[0] = 0x00;
926         ret = cx24120_message_sendrcv(state, &cmd, 6);
927         if (ret != 0)
928                 return;
929         /* in cmd[0]-[5] - result */
930
931         dev_dbg(&state->i2c->dev, "m=%d, n=%d; idx: %d m=%d, n=%d, rate=%d\n",
932                 cmd.arg[2] | (cmd.arg[1] << 8) | (cmd.arg[0] << 16),
933                 cmd.arg[5] | (cmd.arg[4] << 8) | (cmd.arg[3] << 16),
934                 idx,
935                 clock_ratios_table[idx].m_rat,
936                 clock_ratios_table[idx].n_rat,
937                 clock_ratios_table[idx].rate);
938
939         /* Set the clock */
940         cmd.id = CMD_CLOCK_SET;
941         cmd.len = 10;
942         cmd.arg[0] = 0;
943         cmd.arg[1] = 0x10;
944         cmd.arg[2] = (clock_ratios_table[idx].m_rat >> 16) & 0xff;
945         cmd.arg[3] = (clock_ratios_table[idx].m_rat >>  8) & 0xff;
946         cmd.arg[4] = (clock_ratios_table[idx].m_rat >>  0) & 0xff;
947         cmd.arg[5] = (clock_ratios_table[idx].n_rat >> 16) & 0xff;
948         cmd.arg[6] = (clock_ratios_table[idx].n_rat >>  8) & 0xff;
949         cmd.arg[7] = (clock_ratios_table[idx].n_rat >>  0) & 0xff;
950         cmd.arg[8] = (clock_ratios_table[idx].rate >> 8) & 0xff;
951         cmd.arg[9] = (clock_ratios_table[idx].rate >> 0) & 0xff;
952
953         cx24120_message_send(state, &cmd);
954
955         /* Calculate ber window rates for stat work */
956         cx24120_calculate_ber_window(state, clock_ratios_table[idx].rate);
957 }
958
959 /* Set inversion value */
960 static int cx24120_set_inversion(struct cx24120_state *state,
961                                  fe_spectral_inversion_t inversion)
962 {
963         dev_dbg(&state->i2c->dev, "(%d)\n", inversion);
964
965         switch (inversion) {
966         case INVERSION_OFF:
967                 state->dnxt.inversion_val = 0x00;
968                 break;
969         case INVERSION_ON:
970                 state->dnxt.inversion_val = 0x04;
971                 break;
972         case INVERSION_AUTO:
973                 state->dnxt.inversion_val = 0x0c;
974                 break;
975         default:
976                 return -EINVAL;
977         }
978
979         state->dnxt.inversion = inversion;
980
981         return 0;
982 }
983
984 /* FEC lookup table for tuning */
985 struct cx24120_modfec_table {
986         fe_delivery_system_t delsys;
987         fe_modulation_t mod;
988         fe_code_rate_t fec;
989         u8 val;
990 };
991
992 static const struct cx24120_modfec_table modfec_table[] = {
993         /*delsys     mod    fec       val */
994         { SYS_DVBS,  QPSK,  FEC_1_2,  0x2e },
995         { SYS_DVBS,  QPSK,  FEC_2_3,  0x2f },
996         { SYS_DVBS,  QPSK,  FEC_3_4,  0x30 },
997         { SYS_DVBS,  QPSK,  FEC_5_6,  0x31 },
998         { SYS_DVBS,  QPSK,  FEC_6_7,  0x32 },
999         { SYS_DVBS,  QPSK,  FEC_7_8,  0x33 },
1000
1001         { SYS_DVBS2, QPSK,  FEC_1_2,  0x04 },
1002         { SYS_DVBS2, QPSK,  FEC_3_5,  0x05 },
1003         { SYS_DVBS2, QPSK,  FEC_2_3,  0x06 },
1004         { SYS_DVBS2, QPSK,  FEC_3_4,  0x07 },
1005         { SYS_DVBS2, QPSK,  FEC_4_5,  0x08 },
1006         { SYS_DVBS2, QPSK,  FEC_5_6,  0x09 },
1007         { SYS_DVBS2, QPSK,  FEC_8_9,  0x0a },
1008         { SYS_DVBS2, QPSK,  FEC_9_10, 0x0b },
1009
1010         { SYS_DVBS2, PSK_8, FEC_3_5,  0x0c },
1011         { SYS_DVBS2, PSK_8, FEC_2_3,  0x0d },
1012         { SYS_DVBS2, PSK_8, FEC_3_4,  0x0e },
1013         { SYS_DVBS2, PSK_8, FEC_5_6,  0x0f },
1014         { SYS_DVBS2, PSK_8, FEC_8_9,  0x10 },
1015         { SYS_DVBS2, PSK_8, FEC_9_10, 0x11 },
1016 };
1017
1018 /* Set fec_val & fec_mask values from delsys, modulation & fec */
1019 static int cx24120_set_fec(struct cx24120_state *state, fe_modulation_t mod,
1020                            fe_code_rate_t fec)
1021 {
1022         int idx;
1023
1024         dev_dbg(&state->i2c->dev, "(0x%02x,0x%02x)\n", mod, fec);
1025
1026         state->dnxt.fec = fec;
1027
1028         /* Lookup fec_val from modfec table */
1029         for (idx = 0; idx < ARRAY_SIZE(modfec_table); idx++) {
1030                 if (modfec_table[idx].delsys != state->dnxt.delsys)
1031                         continue;
1032                 if (modfec_table[idx].mod != mod)
1033                         continue;
1034                 if (modfec_table[idx].fec != fec)
1035                         continue;
1036
1037                 /* found */
1038                 state->dnxt.fec_mask = 0x00;
1039                 state->dnxt.fec_val = modfec_table[idx].val;
1040                 return 0;
1041         }
1042
1043         if (state->dnxt.delsys == SYS_DVBS2) {
1044                 /* DVBS2 auto is 0x00/0x00 */
1045                 state->dnxt.fec_mask = 0x00;
1046                 state->dnxt.fec_val  = 0x00;
1047         } else {
1048                 /* Set DVB-S to auto */
1049                 state->dnxt.fec_val  = 0x2e;
1050                 state->dnxt.fec_mask = 0xac;
1051         }
1052
1053         return 0;
1054 }
1055
1056 /* Set pilot */
1057 static int cx24120_set_pilot(struct cx24120_state *state, fe_pilot_t pilot)
1058 {
1059         dev_dbg(&state->i2c->dev, "(%d)\n", pilot);
1060
1061         /* Pilot only valid in DVBS2 */
1062         if (state->dnxt.delsys != SYS_DVBS2) {
1063                 state->dnxt.pilot_val = CX24120_PILOT_OFF;
1064                 return 0;
1065         }
1066
1067         switch (pilot) {
1068         case PILOT_OFF:
1069                 state->dnxt.pilot_val = CX24120_PILOT_OFF;
1070                 break;
1071         case PILOT_ON:
1072                 state->dnxt.pilot_val = CX24120_PILOT_ON;
1073                 break;
1074         case PILOT_AUTO:
1075         default:
1076                 state->dnxt.pilot_val = CX24120_PILOT_AUTO;
1077         }
1078
1079         return 0;
1080 }
1081
1082 /* Set symbol rate */
1083 static int cx24120_set_symbolrate(struct cx24120_state *state, u32 rate)
1084 {
1085         dev_dbg(&state->i2c->dev, "(%d)\n", rate);
1086
1087         state->dnxt.symbol_rate = rate;
1088
1089         /* Check symbol rate */
1090         if (rate  > 31000000) {
1091                 state->dnxt.clkdiv  = (-(rate < 31000001) & 3) + 2;
1092                 state->dnxt.ratediv = (-(rate < 31000001) & 6) + 4;
1093         } else {
1094                 state->dnxt.clkdiv  = 3;
1095                 state->dnxt.ratediv = 6;
1096         }
1097
1098         return 0;
1099 }
1100
1101 /* Overwrite the current tuning params, we are about to tune */
1102 static void cx24120_clone_params(struct dvb_frontend *fe)
1103 {
1104         struct cx24120_state *state = fe->demodulator_priv;
1105
1106         state->dcur = state->dnxt;
1107 }
1108
1109 static int cx24120_set_frontend(struct dvb_frontend *fe)
1110 {
1111         struct dtv_frontend_properties *c = &fe->dtv_property_cache;
1112         struct cx24120_state *state = fe->demodulator_priv;
1113         struct cx24120_cmd cmd;
1114         int ret;
1115
1116         switch (c->delivery_system) {
1117         case SYS_DVBS2:
1118                 dev_dbg(&state->i2c->dev, "DVB-S2\n");
1119                 break;
1120         case SYS_DVBS:
1121                 dev_dbg(&state->i2c->dev, "DVB-S\n");
1122                 break;
1123         default:
1124                 dev_dbg(&state->i2c->dev,
1125                         "delivery system(%d) not supported\n",
1126                         c->delivery_system);
1127                 ret = -EINVAL;
1128                 break;
1129         }
1130
1131         state->dnxt.delsys = c->delivery_system;
1132         state->dnxt.modulation = c->modulation;
1133         state->dnxt.frequency = c->frequency;
1134         state->dnxt.pilot = c->pilot;
1135
1136         ret = cx24120_set_inversion(state, c->inversion);
1137         if (ret !=  0)
1138                 return ret;
1139
1140         ret = cx24120_set_fec(state, c->modulation, c->fec_inner);
1141         if (ret !=  0)
1142                 return ret;
1143
1144         ret = cx24120_set_pilot(state, c->pilot);
1145         if (ret != 0)
1146                 return ret;
1147
1148         ret = cx24120_set_symbolrate(state, c->symbol_rate);
1149         if (ret !=  0)
1150                 return ret;
1151
1152         /* discard the 'current' tuning parameters and prepare to tune */
1153         cx24120_clone_params(fe);
1154
1155         dev_dbg(&state->i2c->dev,
1156                 "delsys      = %d\n", state->dcur.delsys);
1157         dev_dbg(&state->i2c->dev,
1158                 "modulation  = %d\n", state->dcur.modulation);
1159         dev_dbg(&state->i2c->dev,
1160                 "frequency   = %d\n", state->dcur.frequency);
1161         dev_dbg(&state->i2c->dev,
1162                 "pilot       = %d (val = 0x%02x)\n",
1163                 state->dcur.pilot, state->dcur.pilot_val);
1164         dev_dbg(&state->i2c->dev,
1165                 "symbol_rate = %d (clkdiv/ratediv = 0x%02x/0x%02x)\n",
1166                  state->dcur.symbol_rate,
1167                  state->dcur.clkdiv, state->dcur.ratediv);
1168         dev_dbg(&state->i2c->dev,
1169                 "FEC         = %d (mask/val = 0x%02x/0x%02x)\n",
1170                 state->dcur.fec, state->dcur.fec_mask, state->dcur.fec_val);
1171         dev_dbg(&state->i2c->dev,
1172                 "Inversion   = %d (val = 0x%02x)\n",
1173                 state->dcur.inversion, state->dcur.inversion_val);
1174
1175         /* Flag that clock needs to be set after tune */
1176         state->need_clock_set = 1;
1177
1178         /* Tune in */
1179         cmd.id = CMD_TUNEREQUEST;
1180         cmd.len = 15;
1181         cmd.arg[0] = 0;
1182         cmd.arg[1]  = (state->dcur.frequency & 0xff0000) >> 16;
1183         cmd.arg[2]  = (state->dcur.frequency & 0x00ff00) >> 8;
1184         cmd.arg[3]  = (state->dcur.frequency & 0x0000ff);
1185         cmd.arg[4]  = ((state->dcur.symbol_rate / 1000) & 0xff00) >> 8;
1186         cmd.arg[5]  = ((state->dcur.symbol_rate / 1000) & 0x00ff);
1187         cmd.arg[6]  = state->dcur.inversion;
1188         cmd.arg[7]  = state->dcur.fec_val | state->dcur.pilot_val;
1189         cmd.arg[8]  = CX24120_SEARCH_RANGE_KHZ >> 8;
1190         cmd.arg[9]  = CX24120_SEARCH_RANGE_KHZ & 0xff;
1191         cmd.arg[10] = 0;                /* maybe rolloff? */
1192         cmd.arg[11] = state->dcur.fec_mask;
1193         cmd.arg[12] = state->dcur.ratediv;
1194         cmd.arg[13] = state->dcur.clkdiv;
1195         cmd.arg[14] = 0;
1196
1197         /* Send tune command */
1198         ret = cx24120_message_send(state, &cmd);
1199         if (ret != 0)
1200                 return ret;
1201
1202         /* Write symbol rate values */
1203         ret = cx24120_writereg(state, CX24120_REG_CLKDIV, state->dcur.clkdiv);
1204         ret = cx24120_readreg(state, CX24120_REG_RATEDIV);
1205         ret &= 0xfffffff0;
1206         ret |= state->dcur.ratediv;
1207         ret = cx24120_writereg(state, CX24120_REG_RATEDIV, ret);
1208
1209         return 0;
1210 }
1211
1212 /* Set vco from config */
1213 static int cx24120_set_vco(struct cx24120_state *state)
1214 {
1215         struct cx24120_cmd cmd;
1216         u32 nxtal_khz, vco;
1217         u64 inv_vco;
1218         u32 xtal_khz = state->config->xtal_khz;
1219
1220         nxtal_khz = xtal_khz * 4;
1221         vco = nxtal_khz * 10;
1222         inv_vco = DIV_ROUND_CLOSEST_ULL(0x400000000ULL, vco);
1223
1224         dev_dbg(&state->i2c->dev, "xtal=%d, vco=%d, inv_vco=%lld\n",
1225                 xtal_khz, vco, inv_vco);
1226
1227         cmd.id = CMD_VCO_SET;
1228         cmd.len = 12;
1229         cmd.arg[0] = (vco >> 16) & 0xff;
1230         cmd.arg[1] = (vco >> 8) & 0xff;
1231         cmd.arg[2] = vco & 0xff;
1232         cmd.arg[3] = (inv_vco >> 8) & 0xff;
1233         cmd.arg[4] = (inv_vco) & 0xff;
1234         cmd.arg[5] = 0x03;
1235         cmd.arg[6] = (nxtal_khz >> 8) & 0xff;
1236         cmd.arg[7] = nxtal_khz & 0xff;
1237         cmd.arg[8] = 0x06;
1238         cmd.arg[9] = 0x03;
1239         cmd.arg[10] = (xtal_khz >> 16) & 0xff;
1240         cmd.arg[11] = xtal_khz & 0xff;
1241
1242         return cx24120_message_send(state, &cmd);
1243 }
1244
1245 static int cx24120_init(struct dvb_frontend *fe)
1246 {
1247         const struct firmware *fw;
1248         struct dtv_frontend_properties *c = &fe->dtv_property_cache;
1249         struct cx24120_state *state = fe->demodulator_priv;
1250         struct cx24120_cmd cmd;
1251         u8 reg;
1252         int ret, i;
1253         unsigned char vers[4];
1254
1255         if (state->cold_init)
1256                 return 0;
1257
1258         /* ???? */
1259         cx24120_writereg(state, 0xea, 0x00);
1260         cx24120_test_rom(state);
1261         reg = cx24120_readreg(state, 0xfb) & 0xfe;
1262         cx24120_writereg(state, 0xfb, reg);
1263         reg = cx24120_readreg(state, 0xfc) & 0xfe;
1264         cx24120_writereg(state, 0xfc, reg);
1265         cx24120_writereg(state, 0xc3, 0x04);
1266         cx24120_writereg(state, 0xc4, 0x04);
1267         cx24120_writereg(state, 0xce, 0x00);
1268         cx24120_writereg(state, 0xcf, 0x00);
1269         reg = cx24120_readreg(state, 0xea) & 0xfe;
1270         cx24120_writereg(state, 0xea, reg);
1271         cx24120_writereg(state, 0xeb, 0x0c);
1272         cx24120_writereg(state, 0xec, 0x06);
1273         cx24120_writereg(state, 0xed, 0x05);
1274         cx24120_writereg(state, 0xee, 0x03);
1275         cx24120_writereg(state, 0xef, 0x05);
1276         cx24120_writereg(state, 0xf3, 0x03);
1277         cx24120_writereg(state, 0xf4, 0x44);
1278
1279         for (i = 0; i < 3; i++) {
1280                 cx24120_writereg(state, 0xf0 + i, 0x04);
1281                 cx24120_writereg(state, 0xe6 + i, 0x02);
1282         }
1283
1284         cx24120_writereg(state, 0xea, (reg | 0x01));
1285         for (i = 0; i < 6; i += 2) {
1286                 cx24120_writereg(state, 0xc5 + i, 0x00);
1287                 cx24120_writereg(state, 0xc6 + i, 0x00);
1288         }
1289
1290         cx24120_writereg(state, 0xe4, 0x03);
1291         cx24120_writereg(state, 0xeb, 0x0a);
1292
1293         dev_dbg(&state->i2c->dev, "requesting firmware (%s) to download...\n",
1294                 CX24120_FIRMWARE);
1295
1296         ret = state->config->request_firmware(fe, &fw, CX24120_FIRMWARE);
1297         if (ret) {
1298                 err("Could not load firmware (%s): %d\n", CX24120_FIRMWARE,
1299                     ret);
1300                 return ret;
1301         }
1302
1303         dev_dbg(&state->i2c->dev,
1304                 "Firmware found, size %d bytes (%02x %02x .. %02x %02x)\n",
1305                 (int)fw->size,                  /* firmware_size in bytes */
1306                 fw->data[0],                    /* fw 1st byte */
1307                 fw->data[1],                    /* fw 2d byte */
1308                 fw->data[fw->size - 2],         /* fw before last byte */
1309                 fw->data[fw->size - 1]);        /* fw last byte */
1310
1311         cx24120_test_rom(state);
1312         reg = cx24120_readreg(state, 0xfb) & 0xfe;
1313         cx24120_writereg(state, 0xfb, reg);
1314         cx24120_writereg(state, 0xe0, 0x76);
1315         cx24120_writereg(state, 0xf7, 0x81);
1316         cx24120_writereg(state, 0xf8, 0x00);
1317         cx24120_writereg(state, 0xf9, 0x00);
1318         cx24120_writeregs(state, 0xfa, fw->data, (fw->size - 1), 0x00);
1319         cx24120_writereg(state, 0xf7, 0xc0);
1320         cx24120_writereg(state, 0xe0, 0x00);
1321         reg = (fw->size - 2) & 0x00ff;
1322         cx24120_writereg(state, 0xf8, reg);
1323         reg = ((fw->size - 2) >> 8) & 0x00ff;
1324         cx24120_writereg(state, 0xf9, reg);
1325         cx24120_writereg(state, 0xf7, 0x00);
1326         cx24120_writereg(state, 0xdc, 0x00);
1327         cx24120_writereg(state, 0xdc, 0x07);
1328         msleep(500);
1329
1330         /* Check final byte matches final byte of firmware */
1331         reg = cx24120_readreg(state, 0xe1);
1332         if (reg == fw->data[fw->size - 1]) {
1333                 dev_dbg(&state->i2c->dev, "Firmware uploaded successfully\n");
1334                 ret = 0;
1335         } else {
1336                 err("Firmware upload failed. Last byte returned=0x%x\n", ret);
1337                 ret = -EREMOTEIO;
1338         }
1339         cx24120_writereg(state, 0xdc, 0x00);
1340         release_firmware(fw);
1341         if (ret != 0)
1342                 return ret;
1343
1344         /* Start tuner */
1345         cmd.id = CMD_START_TUNER;
1346         cmd.len = 3;
1347         cmd.arg[0] = 0x00;
1348         cmd.arg[1] = 0x00;
1349         cmd.arg[2] = 0x00;
1350
1351         if (cx24120_message_send(state, &cmd) != 0) {
1352                 err("Error tuner start! :(\n");
1353                 return -EREMOTEIO;
1354         }
1355
1356         /* Set VCO */
1357         ret = cx24120_set_vco(state);
1358         if (ret != 0) {
1359                 err("Error set VCO! :(\n");
1360                 return ret;
1361         }
1362
1363         /* set bandwidth */
1364         cmd.id = CMD_BANDWIDTH;
1365         cmd.len = 12;
1366         cmd.arg[0] = 0x00;
1367         cmd.arg[1] = 0x00;
1368         cmd.arg[2] = 0x00;
1369         cmd.arg[3] = 0x00;
1370         cmd.arg[4] = 0x05;
1371         cmd.arg[5] = 0x02;
1372         cmd.arg[6] = 0x02;
1373         cmd.arg[7] = 0x00;
1374         cmd.arg[8] = 0x05;
1375         cmd.arg[9] = 0x02;
1376         cmd.arg[10] = 0x02;
1377         cmd.arg[11] = 0x00;
1378
1379         if (cx24120_message_send(state, &cmd)) {
1380                 err("Error set bandwidth!\n");
1381                 return -EREMOTEIO;
1382         }
1383
1384         reg = cx24120_readreg(state, 0xba);
1385         if (reg > 3) {
1386                 dev_dbg(&state->i2c->dev, "Reset-readreg 0xba: %x\n", ret);
1387                 err("Error initialising tuner!\n");
1388                 return -EREMOTEIO;
1389         }
1390
1391         dev_dbg(&state->i2c->dev, "Tuner initialised correctly.\n");
1392
1393         /* Initialise mpeg outputs */
1394         cx24120_writereg(state, 0xeb, 0x0a);
1395         if (cx24120_msg_mpeg_output_global_config(state, 0) ||
1396             cx24120_msg_mpeg_output_config(state, 0) ||
1397             cx24120_msg_mpeg_output_config(state, 1) ||
1398             cx24120_msg_mpeg_output_config(state, 2)) {
1399                 err("Error initialising mpeg output. :(\n");
1400                 return -EREMOTEIO;
1401         }
1402
1403         /* Set size of BER window */
1404         cmd.id = CMD_BER_CTRL;
1405         cmd.len = 3;
1406         cmd.arg[0] = 0x00;
1407         cmd.arg[1] = CX24120_BER_WINDOW;
1408         cmd.arg[2] = CX24120_BER_WINDOW;
1409         if (cx24120_message_send(state, &cmd)) {
1410                 err("Error setting ber window\n");
1411                 return -EREMOTEIO;
1412         }
1413
1414         /* Firmware CMD 35: Get firmware version */
1415         cmd.id = CMD_FWVERSION;
1416         cmd.len = 1;
1417         for (i = 0; i < 4; i++) {
1418                 cmd.arg[0] = i;
1419                 ret = cx24120_message_send(state, &cmd);
1420                 if (ret != 0)
1421                         return ret;
1422                 vers[i] = cx24120_readreg(state, CX24120_REG_MAILBOX);
1423         }
1424         info("FW version %i.%i.%i.%i\n", vers[0], vers[1], vers[2], vers[3]);
1425
1426         /* init stats here in order signal app which stats are supported */
1427         c->strength.len = 1;
1428         c->strength.stat[0].scale = FE_SCALE_NOT_AVAILABLE;
1429         c->cnr.len = 1;
1430         c->cnr.stat[0].scale = FE_SCALE_NOT_AVAILABLE;
1431         c->post_bit_error.len = 1;
1432         c->post_bit_error.stat[0].scale = FE_SCALE_NOT_AVAILABLE;
1433         c->post_bit_count.len = 1;
1434         c->post_bit_count.stat[0].scale = FE_SCALE_NOT_AVAILABLE;
1435
1436         state->cold_init = 1;
1437         return 0;
1438 }
1439
1440 static int cx24120_tune(struct dvb_frontend *fe, bool re_tune,
1441                         unsigned int mode_flags, unsigned int *delay,
1442                         fe_status_t *status)
1443 {
1444         struct cx24120_state *state = fe->demodulator_priv;
1445         int ret;
1446
1447         dev_dbg(&state->i2c->dev, "(%d)\n", re_tune);
1448
1449         /* TODO: Do we need to set delay? */
1450
1451         if (re_tune) {
1452                 ret = cx24120_set_frontend(fe);
1453                 if (ret)
1454                         return ret;
1455         }
1456
1457         return cx24120_read_status(fe, status);
1458 }
1459
1460 static int cx24120_get_algo(struct dvb_frontend *fe)
1461 {
1462         return DVBFE_ALGO_HW;
1463 }
1464
1465 static int cx24120_sleep(struct dvb_frontend *fe)
1466 {
1467         return 0;
1468 }
1469
1470 static int cx24120_get_frontend(struct dvb_frontend *fe)
1471 {
1472         struct dtv_frontend_properties *c = &fe->dtv_property_cache;
1473         struct cx24120_state *state = fe->demodulator_priv;
1474         u8 freq1, freq2, freq3;
1475
1476         dev_dbg(&state->i2c->dev, "\n");
1477
1478         /* don't return empty data if we're not tuned in */
1479         if ((state->fe_status & FE_HAS_LOCK) == 0)
1480                 return 0;
1481
1482         /* Get frequency */
1483         freq1 = cx24120_readreg(state, CX24120_REG_FREQ1);
1484         freq2 = cx24120_readreg(state, CX24120_REG_FREQ2);
1485         freq3 = cx24120_readreg(state, CX24120_REG_FREQ3);
1486         c->frequency = (freq3 << 16) | (freq2 << 8) | freq1;
1487         dev_dbg(&state->i2c->dev, "frequency = %d\n", c->frequency);
1488
1489         /* Get modulation, fec, pilot */
1490         cx24120_get_fec(fe);
1491
1492         return 0;
1493 }
1494
1495 static void cx24120_release(struct dvb_frontend *fe)
1496 {
1497         struct cx24120_state *state = fe->demodulator_priv;
1498
1499         dev_dbg(&state->i2c->dev, "Clear state structure\n");
1500         kfree(state);
1501 }
1502
1503 static int cx24120_read_ucblocks(struct dvb_frontend *fe, u32 *ucblocks)
1504 {
1505         struct cx24120_state *state = fe->demodulator_priv;
1506
1507         *ucblocks = (cx24120_readreg(state, CX24120_REG_UCB_H) << 8) |
1508                      cx24120_readreg(state, CX24120_REG_UCB_L);
1509
1510         dev_dbg(&state->i2c->dev, "ucblocks = %d\n", *ucblocks);
1511         return 0;
1512 }
1513
1514 static struct dvb_frontend_ops cx24120_ops = {
1515         .delsys = { SYS_DVBS, SYS_DVBS2 },
1516         .info = {
1517                 .name = "Conexant CX24120/CX24118",
1518                 .frequency_min = 950000,
1519                 .frequency_max = 2150000,
1520                 .frequency_stepsize = 1011, /* kHz for QPSK frontends */
1521                 .frequency_tolerance = 5000,
1522                 .symbol_rate_min = 1000000,
1523                 .symbol_rate_max = 45000000,
1524                 .caps = FE_CAN_INVERSION_AUTO |
1525                         FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 |
1526                         FE_CAN_FEC_4_5 | FE_CAN_FEC_5_6 | FE_CAN_FEC_6_7 |
1527                         FE_CAN_FEC_7_8 | FE_CAN_FEC_AUTO |
1528                         FE_CAN_2G_MODULATION |
1529                         FE_CAN_QPSK | FE_CAN_RECOVER
1530         },
1531         .release =                      cx24120_release,
1532
1533         .init =                         cx24120_init,
1534         .sleep =                        cx24120_sleep,
1535
1536         .tune =                         cx24120_tune,
1537         .get_frontend_algo =            cx24120_get_algo,
1538         .set_frontend =                 cx24120_set_frontend,
1539
1540         .get_frontend =                 cx24120_get_frontend,
1541         .read_status =                  cx24120_read_status,
1542         .read_ber =                     cx24120_read_ber,
1543         .read_signal_strength =         cx24120_read_signal_strength,
1544         .read_snr =                     cx24120_read_snr,
1545         .read_ucblocks =                cx24120_read_ucblocks,
1546
1547         .diseqc_send_master_cmd =       cx24120_send_diseqc_msg,
1548
1549         .diseqc_send_burst =            cx24120_diseqc_send_burst,
1550         .set_tone =                     cx24120_set_tone,
1551         .set_voltage =                  cx24120_set_voltage,
1552 };
1553
1554 MODULE_DESCRIPTION("DVB Frontend module for Conexant CX24120/CX24118 hardware");
1555 MODULE_AUTHOR("Jemma Denson");
1556 MODULE_LICENSE("GPL");