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