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