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