GNU Linux-libre 4.14.259-gnu1
[releases.git] / drivers / media / dvb-frontends / or51132.c
1 /*
2  *    Support for OR51132 (pcHDTV HD-3000) - VSB/QAM
3  *
4  *
5  *    Copyright (C) 2007 Trent Piepho <xyzzy@speakeasy.org>
6  *
7  *    Copyright (C) 2005 Kirk Lapray <kirk_lapray@bigfoot.com>
8  *
9  *    Based on code from Jack Kelliher (kelliher@xmission.com)
10  *                           Copyright (C) 2002 & pcHDTV, inc.
11  *
12  *    This program is free software; you can redistribute it and/or modify
13  *    it under the terms of the GNU General Public License as published by
14  *    the Free Software Foundation; either version 2 of the License, or
15  *    (at your option) any later version.
16  *
17  *    This program is distributed in the hope that it will be useful,
18  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
19  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  *    GNU General Public License for more details.
21  *
22 */
23
24 /*(DEBLOBBED)*/
25 #define OR51132_VSB_FIRMWARE "/*(DEBLOBBED)*/"
26 #define OR51132_QAM_FIRMWARE "/*(DEBLOBBED)*/"
27
28 #include <linux/kernel.h>
29 #include <linux/module.h>
30 #include <linux/init.h>
31 #include <linux/delay.h>
32 #include <linux/string.h>
33 #include <linux/slab.h>
34 #include <asm/byteorder.h>
35
36 #include "dvb_math.h"
37 #include "dvb_frontend.h"
38 #include "or51132.h"
39
40 static int debug;
41 #define dprintk(args...) \
42         do { \
43                 if (debug) printk(KERN_DEBUG "or51132: " args); \
44         } while (0)
45
46
47 struct or51132_state
48 {
49         struct i2c_adapter* i2c;
50
51         /* Configuration settings */
52         const struct or51132_config* config;
53
54         struct dvb_frontend frontend;
55
56         /* Demodulator private data */
57         enum fe_modulation current_modulation;
58         u32 snr; /* Result of last SNR calculation */
59
60         /* Tuner private data */
61         u32 current_frequency;
62 };
63
64
65 /* Write buffer to demod */
66 static int or51132_writebuf(struct or51132_state *state, const u8 *buf, int len)
67 {
68         int err;
69         struct i2c_msg msg = { .addr = state->config->demod_address,
70                                .flags = 0, .buf = (u8*)buf, .len = len };
71
72         /* msleep(20); */ /* doesn't appear to be necessary */
73         if ((err = i2c_transfer(state->i2c, &msg, 1)) != 1) {
74                 printk(KERN_WARNING "or51132: I2C write (addr 0x%02x len %d) error: %d\n",
75                        msg.addr, msg.len, err);
76                 return -EREMOTEIO;
77         }
78         return 0;
79 }
80
81 /* Write constant bytes, e.g. or51132_writebytes(state, 0x04, 0x42, 0x00);
82    Less code and more efficient that loading a buffer on the stack with
83    the bytes to send and then calling or51132_writebuf() on that. */
84 #define or51132_writebytes(state, data...)  \
85         ({ static const u8 _data[] = {data}; \
86         or51132_writebuf(state, _data, sizeof(_data)); })
87
88 /* Read data from demod into buffer.  Returns 0 on success. */
89 static int or51132_readbuf(struct or51132_state *state, u8 *buf, int len)
90 {
91         int err;
92         struct i2c_msg msg = { .addr = state->config->demod_address,
93                                .flags = I2C_M_RD, .buf = buf, .len = len };
94
95         /* msleep(20); */ /* doesn't appear to be necessary */
96         if ((err = i2c_transfer(state->i2c, &msg, 1)) != 1) {
97                 printk(KERN_WARNING "or51132: I2C read (addr 0x%02x len %d) error: %d\n",
98                        msg.addr, msg.len, err);
99                 return -EREMOTEIO;
100         }
101         return 0;
102 }
103
104 /* Reads a 16-bit demod register.  Returns <0 on error. */
105 static int or51132_readreg(struct or51132_state *state, u8 reg)
106 {
107         u8 buf[2] = { 0x04, reg };
108         struct i2c_msg msg[2] = {
109                 {.addr = state->config->demod_address, .flags = 0,
110                  .buf = buf, .len = 2 },
111                 {.addr = state->config->demod_address, .flags = I2C_M_RD,
112                  .buf = buf, .len = 2 }};
113         int err;
114
115         if ((err = i2c_transfer(state->i2c, msg, 2)) != 2) {
116                 printk(KERN_WARNING "or51132: I2C error reading register %d: %d\n",
117                        reg, err);
118                 return -EREMOTEIO;
119         }
120         return buf[0] | (buf[1] << 8);
121 }
122
123 static int or51132_load_firmware (struct dvb_frontend* fe, const struct firmware *fw)
124 {
125         struct or51132_state* state = fe->demodulator_priv;
126         static const u8 run_buf[] = {0x7F,0x01};
127         u8 rec_buf[8];
128         u32 firmwareAsize, firmwareBsize;
129         int i,ret;
130
131         dprintk("Firmware is %zd bytes\n",fw->size);
132
133         /* Get size of firmware A and B */
134         firmwareAsize = le32_to_cpu(*((__le32*)fw->data));
135         dprintk("FirmwareA is %i bytes\n",firmwareAsize);
136         firmwareBsize = le32_to_cpu(*((__le32*)(fw->data+4)));
137         dprintk("FirmwareB is %i bytes\n",firmwareBsize);
138
139         /* Upload firmware */
140         if ((ret = or51132_writebuf(state, &fw->data[8], firmwareAsize))) {
141                 printk(KERN_WARNING "or51132: load_firmware error 1\n");
142                 return ret;
143         }
144         if ((ret = or51132_writebuf(state, &fw->data[8+firmwareAsize],
145                                     firmwareBsize))) {
146                 printk(KERN_WARNING "or51132: load_firmware error 2\n");
147                 return ret;
148         }
149
150         if ((ret = or51132_writebuf(state, run_buf, 2))) {
151                 printk(KERN_WARNING "or51132: load_firmware error 3\n");
152                 return ret;
153         }
154         if ((ret = or51132_writebuf(state, run_buf, 2))) {
155                 printk(KERN_WARNING "or51132: load_firmware error 4\n");
156                 return ret;
157         }
158
159         /* 50ms for operation to begin */
160         msleep(50);
161
162         /* Read back ucode version to besure we loaded correctly and are really up and running */
163         /* Get uCode version */
164         if ((ret = or51132_writebytes(state, 0x10, 0x10, 0x00))) {
165                 printk(KERN_WARNING "or51132: load_firmware error a\n");
166                 return ret;
167         }
168         if ((ret = or51132_writebytes(state, 0x04, 0x17))) {
169                 printk(KERN_WARNING "or51132: load_firmware error b\n");
170                 return ret;
171         }
172         if ((ret = or51132_writebytes(state, 0x00, 0x00))) {
173                 printk(KERN_WARNING "or51132: load_firmware error c\n");
174                 return ret;
175         }
176         for (i=0;i<4;i++) {
177                 /* Once upon a time, this command might have had something
178                    to do with getting the firmware version, but it's
179                    not used anymore:
180                    {0x04,0x00,0x30,0x00,i+1} */
181                 /* Read 8 bytes, two bytes at a time */
182                 if ((ret = or51132_readbuf(state, &rec_buf[i*2], 2))) {
183                         printk(KERN_WARNING
184                                "or51132: load_firmware error d - %d\n",i);
185                         return ret;
186                 }
187         }
188
189         printk(KERN_WARNING
190                "or51132: Version: %02X%02X%02X%02X-%02X%02X%02X%02X (%02X%01X-%01X-%02X%01X-%01X)\n",
191                rec_buf[1],rec_buf[0],rec_buf[3],rec_buf[2],
192                rec_buf[5],rec_buf[4],rec_buf[7],rec_buf[6],
193                rec_buf[3],rec_buf[2]>>4,rec_buf[2]&0x0f,
194                rec_buf[5],rec_buf[4]>>4,rec_buf[4]&0x0f);
195
196         if ((ret = or51132_writebytes(state, 0x10, 0x00, 0x00))) {
197                 printk(KERN_WARNING "or51132: load_firmware error e\n");
198                 return ret;
199         }
200         return 0;
201 };
202
203 static int or51132_init(struct dvb_frontend* fe)
204 {
205         return 0;
206 }
207
208 static int or51132_read_ber(struct dvb_frontend* fe, u32* ber)
209 {
210         *ber = 0;
211         return 0;
212 }
213
214 static int or51132_read_ucblocks(struct dvb_frontend* fe, u32* ucblocks)
215 {
216         *ucblocks = 0;
217         return 0;
218 }
219
220 static int or51132_sleep(struct dvb_frontend* fe)
221 {
222         return 0;
223 }
224
225 static int or51132_setmode(struct dvb_frontend* fe)
226 {
227         struct or51132_state* state = fe->demodulator_priv;
228         u8 cmd_buf1[3] = {0x04, 0x01, 0x5f};
229         u8 cmd_buf2[3] = {0x1c, 0x00, 0 };
230
231         dprintk("setmode %d\n",(int)state->current_modulation);
232
233         switch (state->current_modulation) {
234         case VSB_8:
235                 /* Auto CH, Auto NTSC rej, MPEGser, MPEG2tr, phase noise-high */
236                 cmd_buf1[2] = 0x50;
237                 /* REC MODE inv IF spectrum, Normal */
238                 cmd_buf2[1] = 0x03;
239                 /* Channel MODE ATSC/VSB8 */
240                 cmd_buf2[2] = 0x06;
241                 break;
242         /* All QAM modes are:
243            Auto-deinterleave; MPEGser, MPEG2tr, phase noise-high
244            REC MODE Normal Carrier Lock */
245         case QAM_AUTO:
246                 /* Channel MODE Auto QAM64/256 */
247                 cmd_buf2[2] = 0x4f;
248                 break;
249         case QAM_256:
250                 /* Channel MODE QAM256 */
251                 cmd_buf2[2] = 0x45;
252                 break;
253         case QAM_64:
254                 /* Channel MODE QAM64 */
255                 cmd_buf2[2] = 0x43;
256                 break;
257         default:
258                 printk(KERN_WARNING
259                        "or51132: setmode: Modulation set to unsupported value (%d)\n",
260                        state->current_modulation);
261                 return -EINVAL;
262         }
263
264         /* Set Receiver 1 register */
265         if (or51132_writebuf(state, cmd_buf1, 3)) {
266                 printk(KERN_WARNING "or51132: set_mode error 1\n");
267                 return -EREMOTEIO;
268         }
269         dprintk("set #1 to %02x\n", cmd_buf1[2]);
270
271         /* Set operation mode in Receiver 6 register */
272         if (or51132_writebuf(state, cmd_buf2, 3)) {
273                 printk(KERN_WARNING "or51132: set_mode error 2\n");
274                 return -EREMOTEIO;
275         }
276         dprintk("set #6 to 0x%02x%02x\n", cmd_buf2[1], cmd_buf2[2]);
277
278         return 0;
279 }
280
281 /* Some modulations use the same firmware.  This classifies modulations
282    by the firmware they use. */
283 #define MOD_FWCLASS_UNKNOWN     0
284 #define MOD_FWCLASS_VSB         1
285 #define MOD_FWCLASS_QAM         2
286 static int modulation_fw_class(enum fe_modulation modulation)
287 {
288         switch(modulation) {
289         case VSB_8:
290                 return MOD_FWCLASS_VSB;
291         case QAM_AUTO:
292         case QAM_64:
293         case QAM_256:
294                 return MOD_FWCLASS_QAM;
295         default:
296                 return MOD_FWCLASS_UNKNOWN;
297         }
298 }
299
300 static int or51132_set_parameters(struct dvb_frontend *fe)
301 {
302         struct dtv_frontend_properties *p = &fe->dtv_property_cache;
303         int ret;
304         struct or51132_state* state = fe->demodulator_priv;
305         const struct firmware *fw;
306         const char *fwname;
307         int clock_mode;
308
309         /* Upload new firmware only if we need a different one */
310         if (modulation_fw_class(state->current_modulation) !=
311             modulation_fw_class(p->modulation)) {
312                 switch (modulation_fw_class(p->modulation)) {
313                 case MOD_FWCLASS_VSB:
314                         dprintk("set_parameters VSB MODE\n");
315                         fwname = OR51132_VSB_FIRMWARE;
316
317                         /* Set non-punctured clock for VSB */
318                         clock_mode = 0;
319                         break;
320                 case MOD_FWCLASS_QAM:
321                         dprintk("set_parameters QAM MODE\n");
322                         fwname = OR51132_QAM_FIRMWARE;
323
324                         /* Set punctured clock for QAM */
325                         clock_mode = 1;
326                         break;
327                 default:
328                         printk("or51132: Modulation type(%d) UNSUPPORTED\n",
329                                p->modulation);
330                         return -1;
331                 }
332                 printk("or51132: Waiting for firmware upload(%s)...\n",
333                        fwname);
334                 ret = reject_firmware(&fw, fwname, state->i2c->dev.parent);
335                 if (ret) {
336                         printk(KERN_WARNING "or51132: No firmware uploaded(timeout or file not found?)\n");
337                         return ret;
338                 }
339                 ret = or51132_load_firmware(fe, fw);
340                 release_firmware(fw);
341                 if (ret) {
342                         printk(KERN_WARNING "or51132: Writing firmware to device failed!\n");
343                         return ret;
344                 }
345                 printk("or51132: Firmware upload complete.\n");
346                 state->config->set_ts_params(fe, clock_mode);
347         }
348         /* Change only if we are actually changing the modulation */
349         if (state->current_modulation != p->modulation) {
350                 state->current_modulation = p->modulation;
351                 or51132_setmode(fe);
352         }
353
354         if (fe->ops.tuner_ops.set_params) {
355                 fe->ops.tuner_ops.set_params(fe);
356                 if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0);
357         }
358
359         /* Set to current mode */
360         or51132_setmode(fe);
361
362         /* Update current frequency */
363         state->current_frequency = p->frequency;
364         return 0;
365 }
366
367 static int or51132_get_parameters(struct dvb_frontend* fe,
368                                   struct dtv_frontend_properties *p)
369 {
370         struct or51132_state* state = fe->demodulator_priv;
371         int status;
372         int retry = 1;
373
374 start:
375         /* Receiver Status */
376         if ((status = or51132_readreg(state, 0x00)) < 0) {
377                 printk(KERN_WARNING "or51132: get_parameters: error reading receiver status\n");
378                 return -EREMOTEIO;
379         }
380         switch(status&0xff) {
381         case 0x06:
382                 p->modulation = VSB_8;
383                 break;
384         case 0x43:
385                 p->modulation = QAM_64;
386                 break;
387         case 0x45:
388                 p->modulation = QAM_256;
389                 break;
390         default:
391                 if (retry--)
392                         goto start;
393                 printk(KERN_WARNING "or51132: unknown status 0x%02x\n",
394                        status&0xff);
395                 return -EREMOTEIO;
396         }
397
398         /* FIXME: Read frequency from frontend, take AFC into account */
399         p->frequency = state->current_frequency;
400
401         /* FIXME: How to read inversion setting? Receiver 6 register? */
402         p->inversion = INVERSION_AUTO;
403
404         return 0;
405 }
406
407 static int or51132_read_status(struct dvb_frontend *fe, enum fe_status *status)
408 {
409         struct or51132_state* state = fe->demodulator_priv;
410         int reg;
411
412         /* Receiver Status */
413         if ((reg = or51132_readreg(state, 0x00)) < 0) {
414                 printk(KERN_WARNING "or51132: read_status: error reading receiver status: %d\n", reg);
415                 *status = 0;
416                 return -EREMOTEIO;
417         }
418         dprintk("%s: read_status %04x\n", __func__, reg);
419
420         if (reg & 0x0100) /* Receiver Lock */
421                 *status = FE_HAS_SIGNAL|FE_HAS_CARRIER|FE_HAS_VITERBI|
422                           FE_HAS_SYNC|FE_HAS_LOCK;
423         else
424                 *status = 0;
425         return 0;
426 }
427
428 /* Calculate SNR estimation (scaled by 2^24)
429
430    8-VSB SNR and QAM equations from Oren datasheets
431
432    For 8-VSB:
433      SNR[dB] = 10 * log10(897152044.8282 / MSE^2 ) - K
434
435      Where K = 0 if NTSC rejection filter is OFF; and
436            K = 3 if NTSC rejection filter is ON
437
438    For QAM64:
439      SNR[dB] = 10 * log10(897152044.8282 / MSE^2 )
440
441    For QAM256:
442      SNR[dB] = 10 * log10(907832426.314266  / MSE^2 )
443
444    We re-write the snr equation as:
445      SNR * 2^24 = 10*(c - 2*intlog10(MSE))
446    Where for QAM256, c = log10(907832426.314266) * 2^24
447    and for 8-VSB and QAM64, c = log10(897152044.8282) * 2^24 */
448
449 static u32 calculate_snr(u32 mse, u32 c)
450 {
451         if (mse == 0) /* No signal */
452                 return 0;
453
454         mse = 2*intlog10(mse);
455         if (mse > c) {
456                 /* Negative SNR, which is possible, but realisticly the
457                 demod will lose lock before the signal gets this bad.  The
458                 API only allows for unsigned values, so just return 0 */
459                 return 0;
460         }
461         return 10*(c - mse);
462 }
463
464 static int or51132_read_snr(struct dvb_frontend* fe, u16* snr)
465 {
466         struct or51132_state* state = fe->demodulator_priv;
467         int noise, reg;
468         u32 c, usK = 0;
469         int retry = 1;
470
471 start:
472         /* SNR after Equalizer */
473         noise = or51132_readreg(state, 0x02);
474         if (noise < 0) {
475                 printk(KERN_WARNING "or51132: read_snr: error reading equalizer\n");
476                 return -EREMOTEIO;
477         }
478         dprintk("read_snr noise (%d)\n", noise);
479
480         /* Read status, contains modulation type for QAM_AUTO and
481            NTSC filter for VSB */
482         reg = or51132_readreg(state, 0x00);
483         if (reg < 0) {
484                 printk(KERN_WARNING "or51132: read_snr: error reading receiver status\n");
485                 return -EREMOTEIO;
486         }
487
488         switch (reg&0xff) {
489         case 0x06:
490                 if (reg & 0x1000) usK = 3 << 24;
491                 /* fall through */
492         case 0x43: /* QAM64 */
493                 c = 150204167;
494                 break;
495         case 0x45:
496                 c = 150290396;
497                 break;
498         default:
499                 printk(KERN_WARNING "or51132: unknown status 0x%02x\n", reg&0xff);
500                 if (retry--) goto start;
501                 return -EREMOTEIO;
502         }
503         dprintk("%s: modulation %02x, NTSC rej O%s\n", __func__,
504                 reg&0xff, reg&0x1000?"n":"ff");
505
506         /* Calculate SNR using noise, c, and NTSC rejection correction */
507         state->snr = calculate_snr(noise, c) - usK;
508         *snr = (state->snr) >> 16;
509
510         dprintk("%s: noise = 0x%08x, snr = %d.%02d dB\n", __func__, noise,
511                 state->snr >> 24, (((state->snr>>8) & 0xffff) * 100) >> 16);
512
513         return 0;
514 }
515
516 static int or51132_read_signal_strength(struct dvb_frontend* fe, u16* strength)
517 {
518         /* Calculate Strength from SNR up to 35dB */
519         /* Even though the SNR can go higher than 35dB, there is some comfort */
520         /* factor in having a range of strong signals that can show at 100%   */
521         struct or51132_state* state = (struct or51132_state*) fe->demodulator_priv;
522         u16 snr;
523         int ret;
524
525         ret = fe->ops.read_snr(fe, &snr);
526         if (ret != 0)
527                 return ret;
528         /* Rather than use the 8.8 value snr, use state->snr which is 8.24 */
529         /* scale the range 0 - 35*2^24 into 0 - 65535 */
530         if (state->snr >= 8960 * 0x10000)
531                 *strength = 0xffff;
532         else
533                 *strength = state->snr / 8960;
534
535         return 0;
536 }
537
538 static int or51132_get_tune_settings(struct dvb_frontend* fe, struct dvb_frontend_tune_settings* fe_tune_settings)
539 {
540         fe_tune_settings->min_delay_ms = 500;
541         fe_tune_settings->step_size = 0;
542         fe_tune_settings->max_drift = 0;
543
544         return 0;
545 }
546
547 static void or51132_release(struct dvb_frontend* fe)
548 {
549         struct or51132_state* state = fe->demodulator_priv;
550         kfree(state);
551 }
552
553 static const struct dvb_frontend_ops or51132_ops;
554
555 struct dvb_frontend* or51132_attach(const struct or51132_config* config,
556                                     struct i2c_adapter* i2c)
557 {
558         struct or51132_state* state = NULL;
559
560         /* Allocate memory for the internal state */
561         state = kzalloc(sizeof(struct or51132_state), GFP_KERNEL);
562         if (state == NULL)
563                 return NULL;
564
565         /* Setup the state */
566         state->config = config;
567         state->i2c = i2c;
568         state->current_frequency = -1;
569         state->current_modulation = -1;
570
571         /* Create dvb_frontend */
572         memcpy(&state->frontend.ops, &or51132_ops, sizeof(struct dvb_frontend_ops));
573         state->frontend.demodulator_priv = state;
574         return &state->frontend;
575 }
576
577 static const struct dvb_frontend_ops or51132_ops = {
578         .delsys = { SYS_ATSC, SYS_DVBC_ANNEX_B },
579         .info = {
580                 .name                   = "Oren OR51132 VSB/QAM Frontend",
581                 .frequency_min          = 44000000,
582                 .frequency_max          = 958000000,
583                 .frequency_stepsize     = 166666,
584                 .caps = FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 |
585                         FE_CAN_FEC_5_6 | FE_CAN_FEC_7_8 | FE_CAN_FEC_AUTO |
586                         FE_CAN_QAM_64 | FE_CAN_QAM_256 | FE_CAN_QAM_AUTO |
587                         FE_CAN_8VSB
588         },
589
590         .release = or51132_release,
591
592         .init = or51132_init,
593         .sleep = or51132_sleep,
594
595         .set_frontend = or51132_set_parameters,
596         .get_frontend = or51132_get_parameters,
597         .get_tune_settings = or51132_get_tune_settings,
598
599         .read_status = or51132_read_status,
600         .read_ber = or51132_read_ber,
601         .read_signal_strength = or51132_read_signal_strength,
602         .read_snr = or51132_read_snr,
603         .read_ucblocks = or51132_read_ucblocks,
604 };
605
606 module_param(debug, int, 0644);
607 MODULE_PARM_DESC(debug, "Turn on/off frontend debugging (default:off).");
608
609 MODULE_DESCRIPTION("OR51132 ATSC [pcHDTV HD-3000] (8VSB & ITU J83 AnnexB FEC QAM64/256) Demodulator Driver");
610 MODULE_AUTHOR("Kirk Lapray");
611 MODULE_AUTHOR("Trent Piepho");
612 MODULE_LICENSE("GPL");
613
614 EXPORT_SYMBOL(or51132_attach);