Merge branch 'v4l_for_linus' of git://git.kernel.org/pub/scm/linux/kernel/git/mchehab...
[linux-2.6.git] / drivers / media / common / tuners / tuner-xc2028.c
1 /* tuner-xc2028
2  *
3  * Copyright (c) 2007-2008 Mauro Carvalho Chehab (mchehab@infradead.org)
4  *
5  * Copyright (c) 2007 Michel Ludwig (michel.ludwig@gmail.com)
6  *       - frontend interface
7  *
8  * This code is placed under the terms of the GNU General Public License v2
9  */
10
11 #include <linux/i2c.h>
12 #include <asm/div64.h>
13 #include <linux/firmware.h>
14 #include <linux/videodev2.h>
15 #include <linux/delay.h>
16 #include <media/tuner.h>
17 #include <linux/mutex.h>
18 #include <linux/slab.h>
19 #include <asm/unaligned.h>
20 #include "tuner-i2c.h"
21 #include "tuner-xc2028.h"
22 #include "tuner-xc2028-types.h"
23
24 #include <linux/dvb/frontend.h>
25 #include "dvb_frontend.h"
26
27
28 static int debug;
29 module_param(debug, int, 0644);
30 MODULE_PARM_DESC(debug, "enable verbose debug messages");
31
32 static int no_poweroff;
33 module_param(no_poweroff, int, 0644);
34 MODULE_PARM_DESC(no_poweroff, "0 (default) powers device off when not used.\n"
35         "1 keep device energized and with tuner ready all the times.\n"
36         "  Faster, but consumes more power and keeps the device hotter\n");
37
38 static char audio_std[8];
39 module_param_string(audio_std, audio_std, sizeof(audio_std), 0);
40 MODULE_PARM_DESC(audio_std,
41         "Audio standard. XC3028 audio decoder explicitly "
42         "needs to know what audio\n"
43         "standard is needed for some video standards with audio A2 or NICAM.\n"
44         "The valid values are:\n"
45         "A2\n"
46         "A2/A\n"
47         "A2/B\n"
48         "NICAM\n"
49         "NICAM/A\n"
50         "NICAM/B\n");
51
52 static char firmware_name[30];
53 module_param_string(firmware_name, firmware_name, sizeof(firmware_name), 0);
54 MODULE_PARM_DESC(firmware_name, "Firmware file name. Allows overriding the "
55                                 "default firmware name\n");
56
57 static LIST_HEAD(hybrid_tuner_instance_list);
58 static DEFINE_MUTEX(xc2028_list_mutex);
59
60 /* struct for storing firmware table */
61 struct firmware_description {
62         unsigned int  type;
63         v4l2_std_id   id;
64         __u16         int_freq;
65         unsigned char *ptr;
66         unsigned int  size;
67 };
68
69 struct firmware_properties {
70         unsigned int    type;
71         v4l2_std_id     id;
72         v4l2_std_id     std_req;
73         __u16           int_freq;
74         unsigned int    scode_table;
75         int             scode_nr;
76 };
77
78 struct xc2028_data {
79         struct list_head        hybrid_tuner_instance_list;
80         struct tuner_i2c_props  i2c_props;
81         __u32                   frequency;
82
83         struct firmware_description *firm;
84         int                     firm_size;
85         __u16                   firm_version;
86
87         __u16                   hwmodel;
88         __u16                   hwvers;
89
90         struct xc2028_ctrl      ctrl;
91
92         struct firmware_properties cur_fw;
93
94         struct mutex lock;
95 };
96
97 #define i2c_send(priv, buf, size) ({                                    \
98         int _rc;                                                        \
99         _rc = tuner_i2c_xfer_send(&priv->i2c_props, buf, size);         \
100         if (size != _rc)                                                \
101                 tuner_info("i2c output error: rc = %d (should be %d)\n",\
102                            _rc, (int)size);                             \
103         if (priv->ctrl.msleep)                                          \
104                 msleep(priv->ctrl.msleep);                              \
105         _rc;                                                            \
106 })
107
108 #define i2c_rcv(priv, buf, size) ({                                     \
109         int _rc;                                                        \
110         _rc = tuner_i2c_xfer_recv(&priv->i2c_props, buf, size);         \
111         if (size != _rc)                                                \
112                 tuner_err("i2c input error: rc = %d (should be %d)\n",  \
113                            _rc, (int)size);                             \
114         _rc;                                                            \
115 })
116
117 #define i2c_send_recv(priv, obuf, osize, ibuf, isize) ({                \
118         int _rc;                                                        \
119         _rc = tuner_i2c_xfer_send_recv(&priv->i2c_props, obuf, osize,   \
120                                        ibuf, isize);                    \
121         if (isize != _rc)                                               \
122                 tuner_err("i2c input error: rc = %d (should be %d)\n",  \
123                            _rc, (int)isize);                            \
124         if (priv->ctrl.msleep)                                          \
125                 msleep(priv->ctrl.msleep);                              \
126         _rc;                                                            \
127 })
128
129 #define send_seq(priv, data...) ({                                      \
130         static u8 _val[] = data;                                        \
131         int _rc;                                                        \
132         if (sizeof(_val) !=                                             \
133                         (_rc = tuner_i2c_xfer_send(&priv->i2c_props,    \
134                                                 _val, sizeof(_val)))) { \
135                 tuner_err("Error on line %d: %d\n", __LINE__, _rc);     \
136         } else if (priv->ctrl.msleep)                                   \
137                 msleep(priv->ctrl.msleep);                              \
138         _rc;                                                            \
139 })
140
141 static int xc2028_get_reg(struct xc2028_data *priv, u16 reg, u16 *val)
142 {
143         unsigned char buf[2];
144         unsigned char ibuf[2];
145
146         tuner_dbg("%s %04x called\n", __func__, reg);
147
148         buf[0] = reg >> 8;
149         buf[1] = (unsigned char) reg;
150
151         if (i2c_send_recv(priv, buf, 2, ibuf, 2) != 2)
152                 return -EIO;
153
154         *val = (ibuf[1]) | (ibuf[0] << 8);
155         return 0;
156 }
157
158 #define dump_firm_type(t)       dump_firm_type_and_int_freq(t, 0)
159 static void dump_firm_type_and_int_freq(unsigned int type, u16 int_freq)
160 {
161          if (type & BASE)
162                 printk("BASE ");
163          if (type & INIT1)
164                 printk("INIT1 ");
165          if (type & F8MHZ)
166                 printk("F8MHZ ");
167          if (type & MTS)
168                 printk("MTS ");
169          if (type & D2620)
170                 printk("D2620 ");
171          if (type & D2633)
172                 printk("D2633 ");
173          if (type & DTV6)
174                 printk("DTV6 ");
175          if (type & QAM)
176                 printk("QAM ");
177          if (type & DTV7)
178                 printk("DTV7 ");
179          if (type & DTV78)
180                 printk("DTV78 ");
181          if (type & DTV8)
182                 printk("DTV8 ");
183          if (type & FM)
184                 printk("FM ");
185          if (type & INPUT1)
186                 printk("INPUT1 ");
187          if (type & LCD)
188                 printk("LCD ");
189          if (type & NOGD)
190                 printk("NOGD ");
191          if (type & MONO)
192                 printk("MONO ");
193          if (type & ATSC)
194                 printk("ATSC ");
195          if (type & IF)
196                 printk("IF ");
197          if (type & LG60)
198                 printk("LG60 ");
199          if (type & ATI638)
200                 printk("ATI638 ");
201          if (type & OREN538)
202                 printk("OREN538 ");
203          if (type & OREN36)
204                 printk("OREN36 ");
205          if (type & TOYOTA388)
206                 printk("TOYOTA388 ");
207          if (type & TOYOTA794)
208                 printk("TOYOTA794 ");
209          if (type & DIBCOM52)
210                 printk("DIBCOM52 ");
211          if (type & ZARLINK456)
212                 printk("ZARLINK456 ");
213          if (type & CHINA)
214                 printk("CHINA ");
215          if (type & F6MHZ)
216                 printk("F6MHZ ");
217          if (type & INPUT2)
218                 printk("INPUT2 ");
219          if (type & SCODE)
220                 printk("SCODE ");
221          if (type & HAS_IF)
222                 printk("HAS_IF_%d ", int_freq);
223 }
224
225 static  v4l2_std_id parse_audio_std_option(void)
226 {
227         if (strcasecmp(audio_std, "A2") == 0)
228                 return V4L2_STD_A2;
229         if (strcasecmp(audio_std, "A2/A") == 0)
230                 return V4L2_STD_A2_A;
231         if (strcasecmp(audio_std, "A2/B") == 0)
232                 return V4L2_STD_A2_B;
233         if (strcasecmp(audio_std, "NICAM") == 0)
234                 return V4L2_STD_NICAM;
235         if (strcasecmp(audio_std, "NICAM/A") == 0)
236                 return V4L2_STD_NICAM_A;
237         if (strcasecmp(audio_std, "NICAM/B") == 0)
238                 return V4L2_STD_NICAM_B;
239
240         return 0;
241 }
242
243 static void free_firmware(struct xc2028_data *priv)
244 {
245         int i;
246         tuner_dbg("%s called\n", __func__);
247
248         if (!priv->firm)
249                 return;
250
251         for (i = 0; i < priv->firm_size; i++)
252                 kfree(priv->firm[i].ptr);
253
254         kfree(priv->firm);
255
256         priv->firm = NULL;
257         priv->firm_size = 0;
258
259         memset(&priv->cur_fw, 0, sizeof(priv->cur_fw));
260 }
261
262 static int load_all_firmwares(struct dvb_frontend *fe)
263 {
264         struct xc2028_data    *priv = fe->tuner_priv;
265         const struct firmware *fw   = NULL;
266         const unsigned char   *p, *endp;
267         int                   rc = 0;
268         int                   n, n_array;
269         char                  name[33];
270         char                  *fname;
271
272         tuner_dbg("%s called\n", __func__);
273
274         if (!firmware_name[0])
275                 fname = priv->ctrl.fname;
276         else
277                 fname = firmware_name;
278
279         tuner_dbg("Reading firmware %s\n", fname);
280         rc = request_firmware(&fw, fname, priv->i2c_props.adap->dev.parent);
281         if (rc < 0) {
282                 if (rc == -ENOENT)
283                         tuner_err("Error: firmware %s not found.\n",
284                                    fname);
285                 else
286                         tuner_err("Error %d while requesting firmware %s \n",
287                                    rc, fname);
288
289                 return rc;
290         }
291         p = fw->data;
292         endp = p + fw->size;
293
294         if (fw->size < sizeof(name) - 1 + 2 + 2) {
295                 tuner_err("Error: firmware file %s has invalid size!\n",
296                           fname);
297                 goto corrupt;
298         }
299
300         memcpy(name, p, sizeof(name) - 1);
301         name[sizeof(name) - 1] = 0;
302         p += sizeof(name) - 1;
303
304         priv->firm_version = get_unaligned_le16(p);
305         p += 2;
306
307         n_array = get_unaligned_le16(p);
308         p += 2;
309
310         tuner_info("Loading %d firmware images from %s, type: %s, ver %d.%d\n",
311                    n_array, fname, name,
312                    priv->firm_version >> 8, priv->firm_version & 0xff);
313
314         priv->firm = kcalloc(n_array, sizeof(*priv->firm), GFP_KERNEL);
315         if (priv->firm == NULL) {
316                 tuner_err("Not enough memory to load firmware file.\n");
317                 rc = -ENOMEM;
318                 goto err;
319         }
320         priv->firm_size = n_array;
321
322         n = -1;
323         while (p < endp) {
324                 __u32 type, size;
325                 v4l2_std_id id;
326                 __u16 int_freq = 0;
327
328                 n++;
329                 if (n >= n_array) {
330                         tuner_err("More firmware images in file than "
331                                   "were expected!\n");
332                         goto corrupt;
333                 }
334
335                 /* Checks if there's enough bytes to read */
336                 if (endp - p < sizeof(type) + sizeof(id) + sizeof(size))
337                         goto header;
338
339                 type = get_unaligned_le32(p);
340                 p += sizeof(type);
341
342                 id = get_unaligned_le64(p);
343                 p += sizeof(id);
344
345                 if (type & HAS_IF) {
346                         int_freq = get_unaligned_le16(p);
347                         p += sizeof(int_freq);
348                         if (endp - p < sizeof(size))
349                                 goto header;
350                 }
351
352                 size = get_unaligned_le32(p);
353                 p += sizeof(size);
354
355                 if (!size || size > endp - p) {
356                         tuner_err("Firmware type ");
357                         dump_firm_type(type);
358                         printk("(%x), id %llx is corrupted "
359                                "(size=%d, expected %d)\n",
360                                type, (unsigned long long)id,
361                                (unsigned)(endp - p), size);
362                         goto corrupt;
363                 }
364
365                 priv->firm[n].ptr = kzalloc(size, GFP_KERNEL);
366                 if (priv->firm[n].ptr == NULL) {
367                         tuner_err("Not enough memory to load firmware file.\n");
368                         rc = -ENOMEM;
369                         goto err;
370                 }
371                 tuner_dbg("Reading firmware type ");
372                 if (debug) {
373                         dump_firm_type_and_int_freq(type, int_freq);
374                         printk("(%x), id %llx, size=%d.\n",
375                                type, (unsigned long long)id, size);
376                 }
377
378                 memcpy(priv->firm[n].ptr, p, size);
379                 priv->firm[n].type = type;
380                 priv->firm[n].id   = id;
381                 priv->firm[n].size = size;
382                 priv->firm[n].int_freq = int_freq;
383
384                 p += size;
385         }
386
387         if (n + 1 != priv->firm_size) {
388                 tuner_err("Firmware file is incomplete!\n");
389                 goto corrupt;
390         }
391
392         goto done;
393
394 header:
395         tuner_err("Firmware header is incomplete!\n");
396 corrupt:
397         rc = -EINVAL;
398         tuner_err("Error: firmware file is corrupted!\n");
399
400 err:
401         tuner_info("Releasing partially loaded firmware file.\n");
402         free_firmware(priv);
403
404 done:
405         release_firmware(fw);
406         if (rc == 0)
407                 tuner_dbg("Firmware files loaded.\n");
408
409         return rc;
410 }
411
412 static int seek_firmware(struct dvb_frontend *fe, unsigned int type,
413                          v4l2_std_id *id)
414 {
415         struct xc2028_data *priv = fe->tuner_priv;
416         int                 i, best_i = -1, best_nr_matches = 0;
417         unsigned int        type_mask = 0;
418
419         tuner_dbg("%s called, want type=", __func__);
420         if (debug) {
421                 dump_firm_type(type);
422                 printk("(%x), id %016llx.\n", type, (unsigned long long)*id);
423         }
424
425         if (!priv->firm) {
426                 tuner_err("Error! firmware not loaded\n");
427                 return -EINVAL;
428         }
429
430         if (((type & ~SCODE) == 0) && (*id == 0))
431                 *id = V4L2_STD_PAL;
432
433         if (type & BASE)
434                 type_mask = BASE_TYPES;
435         else if (type & SCODE) {
436                 type &= SCODE_TYPES;
437                 type_mask = SCODE_TYPES & ~HAS_IF;
438         } else if (type & DTV_TYPES)
439                 type_mask = DTV_TYPES;
440         else if (type & STD_SPECIFIC_TYPES)
441                 type_mask = STD_SPECIFIC_TYPES;
442
443         type &= type_mask;
444
445         if (!(type & SCODE))
446                 type_mask = ~0;
447
448         /* Seek for exact match */
449         for (i = 0; i < priv->firm_size; i++) {
450                 if ((type == (priv->firm[i].type & type_mask)) &&
451                     (*id == priv->firm[i].id))
452                         goto found;
453         }
454
455         /* Seek for generic video standard match */
456         for (i = 0; i < priv->firm_size; i++) {
457                 v4l2_std_id match_mask;
458                 int nr_matches;
459
460                 if (type != (priv->firm[i].type & type_mask))
461                         continue;
462
463                 match_mask = *id & priv->firm[i].id;
464                 if (!match_mask)
465                         continue;
466
467                 if ((*id & match_mask) == *id)
468                         goto found; /* Supports all the requested standards */
469
470                 nr_matches = hweight64(match_mask);
471                 if (nr_matches > best_nr_matches) {
472                         best_nr_matches = nr_matches;
473                         best_i = i;
474                 }
475         }
476
477         if (best_nr_matches > 0) {
478                 tuner_dbg("Selecting best matching firmware (%d bits) for "
479                           "type=", best_nr_matches);
480                 dump_firm_type(type);
481                 printk("(%x), id %016llx:\n", type, (unsigned long long)*id);
482                 i = best_i;
483                 goto found;
484         }
485
486         /*FIXME: Would make sense to seek for type "hint" match ? */
487
488         i = -ENOENT;
489         goto ret;
490
491 found:
492         *id = priv->firm[i].id;
493
494 ret:
495         tuner_dbg("%s firmware for type=", (i < 0) ? "Can't find" : "Found");
496         if (debug) {
497                 dump_firm_type(type);
498                 printk("(%x), id %016llx.\n", type, (unsigned long long)*id);
499         }
500         return i;
501 }
502
503 static inline int do_tuner_callback(struct dvb_frontend *fe, int cmd, int arg)
504 {
505         struct xc2028_data *priv = fe->tuner_priv;
506
507         /* analog side (tuner-core) uses i2c_adap->algo_data.
508          * digital side is not guaranteed to have algo_data defined.
509          *
510          * digital side will always have fe->dvb defined.
511          * analog side (tuner-core) doesn't (yet) define fe->dvb.
512          */
513
514         return (!fe->callback) ? -EINVAL :
515                 fe->callback(((fe->dvb) && (fe->dvb->priv)) ?
516                                 fe->dvb->priv : priv->i2c_props.adap->algo_data,
517                              DVB_FRONTEND_COMPONENT_TUNER, cmd, arg);
518 }
519
520 static int load_firmware(struct dvb_frontend *fe, unsigned int type,
521                          v4l2_std_id *id)
522 {
523         struct xc2028_data *priv = fe->tuner_priv;
524         int                pos, rc;
525         unsigned char      *p, *endp, buf[priv->ctrl.max_len];
526
527         tuner_dbg("%s called\n", __func__);
528
529         pos = seek_firmware(fe, type, id);
530         if (pos < 0)
531                 return pos;
532
533         tuner_info("Loading firmware for type=");
534         dump_firm_type(priv->firm[pos].type);
535         printk("(%x), id %016llx.\n", priv->firm[pos].type,
536                (unsigned long long)*id);
537
538         p = priv->firm[pos].ptr;
539         endp = p + priv->firm[pos].size;
540
541         while (p < endp) {
542                 __u16 size;
543
544                 /* Checks if there's enough bytes to read */
545                 if (p + sizeof(size) > endp) {
546                         tuner_err("Firmware chunk size is wrong\n");
547                         return -EINVAL;
548                 }
549
550                 size = le16_to_cpu(*(__u16 *) p);
551                 p += sizeof(size);
552
553                 if (size == 0xffff)
554                         return 0;
555
556                 if (!size) {
557                         /* Special callback command received */
558                         rc = do_tuner_callback(fe, XC2028_TUNER_RESET, 0);
559                         if (rc < 0) {
560                                 tuner_err("Error at RESET code %d\n",
561                                            (*p) & 0x7f);
562                                 return -EINVAL;
563                         }
564                         continue;
565                 }
566                 if (size >= 0xff00) {
567                         switch (size) {
568                         case 0xff00:
569                                 rc = do_tuner_callback(fe, XC2028_RESET_CLK, 0);
570                                 if (rc < 0) {
571                                         tuner_err("Error at RESET code %d\n",
572                                                   (*p) & 0x7f);
573                                         return -EINVAL;
574                                 }
575                                 break;
576                         default:
577                                 tuner_info("Invalid RESET code %d\n",
578                                            size & 0x7f);
579                                 return -EINVAL;
580
581                         }
582                         continue;
583                 }
584
585                 /* Checks for a sleep command */
586                 if (size & 0x8000) {
587                         msleep(size & 0x7fff);
588                         continue;
589                 }
590
591                 if ((size + p > endp)) {
592                         tuner_err("missing bytes: need %d, have %d\n",
593                                    size, (int)(endp - p));
594                         return -EINVAL;
595                 }
596
597                 buf[0] = *p;
598                 p++;
599                 size--;
600
601                 /* Sends message chunks */
602                 while (size > 0) {
603                         int len = (size < priv->ctrl.max_len - 1) ?
604                                    size : priv->ctrl.max_len - 1;
605
606                         memcpy(buf + 1, p, len);
607
608                         rc = i2c_send(priv, buf, len + 1);
609                         if (rc < 0) {
610                                 tuner_err("%d returned from send\n", rc);
611                                 return -EINVAL;
612                         }
613
614                         p += len;
615                         size -= len;
616                 }
617
618                 /* silently fail if the frontend doesn't support I2C flush */
619                 rc = do_tuner_callback(fe, XC2028_I2C_FLUSH, 0);
620                 if ((rc < 0) && (rc != -EINVAL)) {
621                         tuner_err("error executing flush: %d\n", rc);
622                         return rc;
623                 }
624         }
625         return 0;
626 }
627
628 static int load_scode(struct dvb_frontend *fe, unsigned int type,
629                          v4l2_std_id *id, __u16 int_freq, int scode)
630 {
631         struct xc2028_data *priv = fe->tuner_priv;
632         int                pos, rc;
633         unsigned char      *p;
634
635         tuner_dbg("%s called\n", __func__);
636
637         if (!int_freq) {
638                 pos = seek_firmware(fe, type, id);
639                 if (pos < 0)
640                         return pos;
641         } else {
642                 for (pos = 0; pos < priv->firm_size; pos++) {
643                         if ((priv->firm[pos].int_freq == int_freq) &&
644                             (priv->firm[pos].type & HAS_IF))
645                                 break;
646                 }
647                 if (pos == priv->firm_size)
648                         return -ENOENT;
649         }
650
651         p = priv->firm[pos].ptr;
652
653         if (priv->firm[pos].type & HAS_IF) {
654                 if (priv->firm[pos].size != 12 * 16 || scode >= 16)
655                         return -EINVAL;
656                 p += 12 * scode;
657         } else {
658                 /* 16 SCODE entries per file; each SCODE entry is 12 bytes and
659                  * has a 2-byte size header in the firmware format. */
660                 if (priv->firm[pos].size != 14 * 16 || scode >= 16 ||
661                     le16_to_cpu(*(__u16 *)(p + 14 * scode)) != 12)
662                         return -EINVAL;
663                 p += 14 * scode + 2;
664         }
665
666         tuner_info("Loading SCODE for type=");
667         dump_firm_type_and_int_freq(priv->firm[pos].type,
668                                     priv->firm[pos].int_freq);
669         printk("(%x), id %016llx.\n", priv->firm[pos].type,
670                (unsigned long long)*id);
671
672         if (priv->firm_version < 0x0202)
673                 rc = send_seq(priv, {0x20, 0x00, 0x00, 0x00});
674         else
675                 rc = send_seq(priv, {0xa0, 0x00, 0x00, 0x00});
676         if (rc < 0)
677                 return -EIO;
678
679         rc = i2c_send(priv, p, 12);
680         if (rc < 0)
681                 return -EIO;
682
683         rc = send_seq(priv, {0x00, 0x8c});
684         if (rc < 0)
685                 return -EIO;
686
687         return 0;
688 }
689
690 static int check_firmware(struct dvb_frontend *fe, unsigned int type,
691                           v4l2_std_id std, __u16 int_freq)
692 {
693         struct xc2028_data         *priv = fe->tuner_priv;
694         struct firmware_properties new_fw;
695         int                        rc = 0, retry_count = 0;
696         u16                        version, hwmodel;
697         v4l2_std_id                std0;
698
699         tuner_dbg("%s called\n", __func__);
700
701         if (!priv->firm) {
702                 if (!priv->ctrl.fname) {
703                         tuner_info("xc2028/3028 firmware name not set!\n");
704                         return -EINVAL;
705                 }
706
707                 rc = load_all_firmwares(fe);
708                 if (rc < 0)
709                         return rc;
710         }
711
712         if (priv->ctrl.mts && !(type & FM))
713                 type |= MTS;
714
715 retry:
716         new_fw.type = type;
717         new_fw.id = std;
718         new_fw.std_req = std;
719         new_fw.scode_table = SCODE | priv->ctrl.scode_table;
720         new_fw.scode_nr = 0;
721         new_fw.int_freq = int_freq;
722
723         tuner_dbg("checking firmware, user requested type=");
724         if (debug) {
725                 dump_firm_type(new_fw.type);
726                 printk("(%x), id %016llx, ", new_fw.type,
727                        (unsigned long long)new_fw.std_req);
728                 if (!int_freq) {
729                         printk("scode_tbl ");
730                         dump_firm_type(priv->ctrl.scode_table);
731                         printk("(%x), ", priv->ctrl.scode_table);
732                 } else
733                         printk("int_freq %d, ", new_fw.int_freq);
734                 printk("scode_nr %d\n", new_fw.scode_nr);
735         }
736
737         /* No need to reload base firmware if it matches */
738         if (((BASE | new_fw.type) & BASE_TYPES) ==
739             (priv->cur_fw.type & BASE_TYPES)) {
740                 tuner_dbg("BASE firmware not changed.\n");
741                 goto skip_base;
742         }
743
744         /* Updating BASE - forget about all currently loaded firmware */
745         memset(&priv->cur_fw, 0, sizeof(priv->cur_fw));
746
747         /* Reset is needed before loading firmware */
748         rc = do_tuner_callback(fe, XC2028_TUNER_RESET, 0);
749         if (rc < 0)
750                 goto fail;
751
752         /* BASE firmwares are all std0 */
753         std0 = 0;
754         rc = load_firmware(fe, BASE | new_fw.type, &std0);
755         if (rc < 0) {
756                 tuner_err("Error %d while loading base firmware\n",
757                           rc);
758                 goto fail;
759         }
760
761         /* Load INIT1, if needed */
762         tuner_dbg("Load init1 firmware, if exists\n");
763
764         rc = load_firmware(fe, BASE | INIT1 | new_fw.type, &std0);
765         if (rc == -ENOENT)
766                 rc = load_firmware(fe, (BASE | INIT1 | new_fw.type) & ~F8MHZ,
767                                    &std0);
768         if (rc < 0 && rc != -ENOENT) {
769                 tuner_err("Error %d while loading init1 firmware\n",
770                           rc);
771                 goto fail;
772         }
773
774 skip_base:
775         /*
776          * No need to reload standard specific firmware if base firmware
777          * was not reloaded and requested video standards have not changed.
778          */
779         if (priv->cur_fw.type == (BASE | new_fw.type) &&
780             priv->cur_fw.std_req == std) {
781                 tuner_dbg("Std-specific firmware already loaded.\n");
782                 goto skip_std_specific;
783         }
784
785         /* Reloading std-specific firmware forces a SCODE update */
786         priv->cur_fw.scode_table = 0;
787
788         rc = load_firmware(fe, new_fw.type, &new_fw.id);
789         if (rc == -ENOENT)
790                 rc = load_firmware(fe, new_fw.type & ~F8MHZ, &new_fw.id);
791
792         if (rc < 0)
793                 goto fail;
794
795 skip_std_specific:
796         if (priv->cur_fw.scode_table == new_fw.scode_table &&
797             priv->cur_fw.scode_nr == new_fw.scode_nr) {
798                 tuner_dbg("SCODE firmware already loaded.\n");
799                 goto check_device;
800         }
801
802         if (new_fw.type & FM)
803                 goto check_device;
804
805         /* Load SCODE firmware, if exists */
806         tuner_dbg("Trying to load scode %d\n", new_fw.scode_nr);
807
808         rc = load_scode(fe, new_fw.type | new_fw.scode_table, &new_fw.id,
809                         new_fw.int_freq, new_fw.scode_nr);
810
811 check_device:
812         if (xc2028_get_reg(priv, 0x0004, &version) < 0 ||
813             xc2028_get_reg(priv, 0x0008, &hwmodel) < 0) {
814                 tuner_err("Unable to read tuner registers.\n");
815                 goto fail;
816         }
817
818         tuner_dbg("Device is Xceive %d version %d.%d, "
819                   "firmware version %d.%d\n",
820                   hwmodel, (version & 0xf000) >> 12, (version & 0xf00) >> 8,
821                   (version & 0xf0) >> 4, version & 0xf);
822
823
824         if (priv->ctrl.read_not_reliable)
825                 goto read_not_reliable;
826
827         /* Check firmware version against what we downloaded. */
828         if (priv->firm_version != ((version & 0xf0) << 4 | (version & 0x0f))) {
829                 if (!priv->ctrl.read_not_reliable) {
830                         tuner_err("Incorrect readback of firmware version.\n");
831                         goto fail;
832                 } else {
833                         tuner_err("Returned an incorrect version. However, "
834                                   "read is not reliable enough. Ignoring it.\n");
835                         hwmodel = 3028;
836                 }
837         }
838
839         /* Check that the tuner hardware model remains consistent over time. */
840         if (priv->hwmodel == 0 && (hwmodel == 2028 || hwmodel == 3028)) {
841                 priv->hwmodel = hwmodel;
842                 priv->hwvers  = version & 0xff00;
843         } else if (priv->hwmodel == 0 || priv->hwmodel != hwmodel ||
844                    priv->hwvers != (version & 0xff00)) {
845                 tuner_err("Read invalid device hardware information - tuner "
846                           "hung?\n");
847                 goto fail;
848         }
849
850 read_not_reliable:
851         memcpy(&priv->cur_fw, &new_fw, sizeof(priv->cur_fw));
852
853         /*
854          * By setting BASE in cur_fw.type only after successfully loading all
855          * firmwares, we can:
856          * 1. Identify that BASE firmware with type=0 has been loaded;
857          * 2. Tell whether BASE firmware was just changed the next time through.
858          */
859         priv->cur_fw.type |= BASE;
860
861         return 0;
862
863 fail:
864         memset(&priv->cur_fw, 0, sizeof(priv->cur_fw));
865         if (retry_count < 8) {
866                 msleep(50);
867                 retry_count++;
868                 tuner_dbg("Retrying firmware load\n");
869                 goto retry;
870         }
871
872         if (rc == -ENOENT)
873                 rc = -EINVAL;
874         return rc;
875 }
876
877 static int xc2028_signal(struct dvb_frontend *fe, u16 *strength)
878 {
879         struct xc2028_data *priv = fe->tuner_priv;
880         u16                 frq_lock, signal = 0;
881         int                 rc;
882
883         tuner_dbg("%s called\n", __func__);
884
885         mutex_lock(&priv->lock);
886
887         /* Sync Lock Indicator */
888         rc = xc2028_get_reg(priv, 0x0002, &frq_lock);
889         if (rc < 0)
890                 goto ret;
891
892         /* Frequency is locked */
893         if (frq_lock == 1)
894                 signal = 1 << 11;
895
896         /* Get SNR of the video signal */
897         rc = xc2028_get_reg(priv, 0x0040, &signal);
898         if (rc < 0)
899                 goto ret;
900
901         /* Use both frq_lock and signal to generate the result */
902         signal = signal || ((signal & 0x07) << 12);
903
904 ret:
905         mutex_unlock(&priv->lock);
906
907         *strength = signal;
908
909         tuner_dbg("signal strength is %d\n", signal);
910
911         return rc;
912 }
913
914 #define DIV 15625
915
916 static int generic_set_freq(struct dvb_frontend *fe, u32 freq /* in HZ */,
917                             enum v4l2_tuner_type new_type,
918                             unsigned int type,
919                             v4l2_std_id std,
920                             u16 int_freq)
921 {
922         struct xc2028_data *priv = fe->tuner_priv;
923         int                rc = -EINVAL;
924         unsigned char      buf[4];
925         u32                div, offset = 0;
926
927         tuner_dbg("%s called\n", __func__);
928
929         mutex_lock(&priv->lock);
930
931         tuner_dbg("should set frequency %d kHz\n", freq / 1000);
932
933         if (check_firmware(fe, type, std, int_freq) < 0)
934                 goto ret;
935
936         /* On some cases xc2028 can disable video output, if
937          * very weak signals are received. By sending a soft
938          * reset, this is re-enabled. So, it is better to always
939          * send a soft reset before changing channels, to be sure
940          * that xc2028 will be in a safe state.
941          * Maybe this might also be needed for DTV.
942          */
943         switch (new_type) {
944         case V4L2_TUNER_ANALOG_TV:
945                 rc = send_seq(priv, {0x00, 0x00});
946
947                 /* Analog mode requires offset = 0 */
948                 break;
949         case V4L2_TUNER_RADIO:
950                 /* Radio mode requires offset = 0 */
951                 break;
952         case V4L2_TUNER_DIGITAL_TV:
953                 /*
954                  * Digital modes require an offset to adjust to the
955                  * proper frequency. The offset depends on what
956                  * firmware version is used.
957                  */
958
959                 /*
960                  * Adjust to the center frequency. This is calculated by the
961                  * formula: offset = 1.25MHz - BW/2
962                  * For DTV 7/8, the firmware uses BW = 8000, so it needs a
963                  * further adjustment to get the frequency center on VHF
964                  */
965
966                 /*
967                  * The firmware DTV78 used to work fine in UHF band (8 MHz
968                  * bandwidth) but not at all in VHF band (7 MHz bandwidth).
969                  * The real problem was connected to the formula used to
970                  * calculate the center frequency offset in VHF band.
971                  * In fact, removing the 500KHz adjustment fixed the problem.
972                  * This is coherent to what was implemented for the DTV7
973                  * firmware.
974                  * In the end, now the center frequency is the same for all 3
975                  * firmwares (DTV7, DTV8, DTV78) and doesn't depend on channel
976                  * bandwidth.
977                  */
978
979                 if (priv->cur_fw.type & DTV6)
980                         offset = 1750000;
981                 else    /* DTV7 or DTV8 or DTV78 */
982                         offset = 2750000;
983
984                 /*
985                  * xc3028 additional "magic"
986                  * Depending on the firmware version, it needs some adjustments
987                  * to properly centralize the frequency. This seems to be
988                  * needed to compensate the SCODE table adjustments made by
989                  * newer firmwares
990                  */
991
992                 /*
993                  * The proper adjustment would be to do it at s-code table.
994                  * However, this didn't work, as reported by
995                  * Robert Lowery <rglowery@exemail.com.au>
996                  */
997
998 #if 0
999                 /*
1000                  * Still need tests for XC3028L (firmware 3.2 or upper)
1001                  * So, for now, let's just comment the per-firmware
1002                  * version of this change. Reports with xc3028l working
1003                  * with and without the lines bellow are welcome
1004                  */
1005
1006                 if (priv->firm_version < 0x0302) {
1007                         if (priv->cur_fw.type & DTV7)
1008                                 offset += 500000;
1009                 } else {
1010                         if (priv->cur_fw.type & DTV7)
1011                                 offset -= 300000;
1012                         else if (type != ATSC) /* DVB @6MHz, DTV 8 and DTV 7/8 */
1013                                 offset += 200000;
1014                 }
1015 #endif
1016         }
1017
1018         div = (freq - offset + DIV / 2) / DIV;
1019
1020         /* CMD= Set frequency */
1021         if (priv->firm_version < 0x0202)
1022                 rc = send_seq(priv, {0x00, 0x02, 0x00, 0x00});
1023         else
1024                 rc = send_seq(priv, {0x80, 0x02, 0x00, 0x00});
1025         if (rc < 0)
1026                 goto ret;
1027
1028         /* Return code shouldn't be checked.
1029            The reset CLK is needed only with tm6000.
1030            Driver should work fine even if this fails.
1031          */
1032         if (priv->ctrl.msleep)
1033                 msleep(priv->ctrl.msleep);
1034         do_tuner_callback(fe, XC2028_RESET_CLK, 1);
1035
1036         msleep(10);
1037
1038         buf[0] = 0xff & (div >> 24);
1039         buf[1] = 0xff & (div >> 16);
1040         buf[2] = 0xff & (div >> 8);
1041         buf[3] = 0xff & (div);
1042
1043         rc = i2c_send(priv, buf, sizeof(buf));
1044         if (rc < 0)
1045                 goto ret;
1046         msleep(100);
1047
1048         priv->frequency = freq;
1049
1050         tuner_dbg("divisor= %02x %02x %02x %02x (freq=%d.%03d)\n",
1051                buf[0], buf[1], buf[2], buf[3],
1052                freq / 1000000, (freq % 1000000) / 1000);
1053
1054         rc = 0;
1055
1056 ret:
1057         mutex_unlock(&priv->lock);
1058
1059         return rc;
1060 }
1061
1062 static int xc2028_set_analog_freq(struct dvb_frontend *fe,
1063                               struct analog_parameters *p)
1064 {
1065         struct xc2028_data *priv = fe->tuner_priv;
1066         unsigned int       type=0;
1067
1068         tuner_dbg("%s called\n", __func__);
1069
1070         if (p->mode == V4L2_TUNER_RADIO) {
1071                 type |= FM;
1072                 if (priv->ctrl.input1)
1073                         type |= INPUT1;
1074                 return generic_set_freq(fe, (625l * p->frequency) / 10,
1075                                 V4L2_TUNER_RADIO, type, 0, 0);
1076         }
1077
1078         /* if std is not defined, choose one */
1079         if (!p->std)
1080                 p->std = V4L2_STD_MN;
1081
1082         /* PAL/M, PAL/N, PAL/Nc and NTSC variants should use 6MHz firmware */
1083         if (!(p->std & V4L2_STD_MN))
1084                 type |= F8MHZ;
1085
1086         /* Add audio hack to std mask */
1087         p->std |= parse_audio_std_option();
1088
1089         return generic_set_freq(fe, 62500l * p->frequency,
1090                                 V4L2_TUNER_ANALOG_TV, type, p->std, 0);
1091 }
1092
1093 static int xc2028_set_params(struct dvb_frontend *fe)
1094 {
1095         struct dtv_frontend_properties *c = &fe->dtv_property_cache;
1096         u32 delsys = c->delivery_system;
1097         u32 bw = c->bandwidth_hz;
1098         struct xc2028_data *priv = fe->tuner_priv;
1099         unsigned int       type=0;
1100         u16                demod = 0;
1101
1102         tuner_dbg("%s called\n", __func__);
1103
1104         switch (delsys) {
1105         case SYS_DVBT:
1106         case SYS_DVBT2:
1107                 /*
1108                  * The only countries with 6MHz seem to be Taiwan/Uruguay.
1109                  * Both seem to require QAM firmware for OFDM decoding
1110                  * Tested in Taiwan by Terry Wu <terrywu2009@gmail.com>
1111                  */
1112                 if (bw <= 6000000)
1113                         type |= QAM;
1114
1115                 switch (priv->ctrl.type) {
1116                 case XC2028_D2633:
1117                         type |= D2633;
1118                         break;
1119                 case XC2028_D2620:
1120                         type |= D2620;
1121                         break;
1122                 case XC2028_AUTO:
1123                 default:
1124                         /* Zarlink seems to need D2633 */
1125                         if (priv->ctrl.demod == XC3028_FE_ZARLINK456)
1126                                 type |= D2633;
1127                         else
1128                                 type |= D2620;
1129                 }
1130                 break;
1131         case SYS_ATSC:
1132                 /* The only ATSC firmware (at least on v2.7) is D2633 */
1133                 type |= ATSC | D2633;
1134                 break;
1135         /* DVB-S and pure QAM (FE_QAM) are not supported */
1136         default:
1137                 return -EINVAL;
1138         }
1139
1140         if (bw <= 6000000) {
1141                 type |= DTV6;
1142                 priv->ctrl.vhfbw7 = 0;
1143                 priv->ctrl.uhfbw8 = 0;
1144         } else if (bw <= 7000000) {
1145                 if (c->frequency < 470000000)
1146                         priv->ctrl.vhfbw7 = 1;
1147                 else
1148                         priv->ctrl.uhfbw8 = 0;
1149                 type |= (priv->ctrl.vhfbw7 && priv->ctrl.uhfbw8) ? DTV78 : DTV7;
1150                 type |= F8MHZ;
1151         } else {
1152                 if (c->frequency < 470000000)
1153                         priv->ctrl.vhfbw7 = 0;
1154                 else
1155                         priv->ctrl.uhfbw8 = 1;
1156                 type |= (priv->ctrl.vhfbw7 && priv->ctrl.uhfbw8) ? DTV78 : DTV8;
1157                 type |= F8MHZ;
1158         }
1159
1160         /* All S-code tables need a 200kHz shift */
1161         if (priv->ctrl.demod) {
1162                 demod = priv->ctrl.demod;
1163
1164                 /*
1165                  * Newer firmwares require a 200 kHz offset only for ATSC
1166                  */
1167                 if (type == ATSC || priv->firm_version < 0x0302)
1168                         demod += 200;
1169                 /*
1170                  * The DTV7 S-code table needs a 700 kHz shift.
1171                  *
1172                  * DTV7 is only used in Australia.  Germany or Italy may also
1173                  * use this firmware after initialization, but a tune to a UHF
1174                  * channel should then cause DTV78 to be used.
1175                  *
1176                  * Unfortunately, on real-field tests, the s-code offset
1177                  * didn't work as expected, as reported by
1178                  * Robert Lowery <rglowery@exemail.com.au>
1179                  */
1180         }
1181
1182         return generic_set_freq(fe, c->frequency,
1183                                 V4L2_TUNER_DIGITAL_TV, type, 0, demod);
1184 }
1185
1186 static int xc2028_sleep(struct dvb_frontend *fe)
1187 {
1188         struct xc2028_data *priv = fe->tuner_priv;
1189         int rc = 0;
1190
1191         /* Avoid firmware reload on slow devices or if PM disabled */
1192         if (no_poweroff || priv->ctrl.disable_power_mgmt)
1193                 return 0;
1194
1195         tuner_dbg("Putting xc2028/3028 into poweroff mode.\n");
1196         if (debug > 1) {
1197                 tuner_dbg("Printing sleep stack trace:\n");
1198                 dump_stack();
1199         }
1200
1201         mutex_lock(&priv->lock);
1202
1203         if (priv->firm_version < 0x0202)
1204                 rc = send_seq(priv, {0x00, 0x08, 0x00, 0x00});
1205         else
1206                 rc = send_seq(priv, {0x80, 0x08, 0x00, 0x00});
1207
1208         priv->cur_fw.type = 0;  /* need firmware reload */
1209
1210         mutex_unlock(&priv->lock);
1211
1212         return rc;
1213 }
1214
1215 static int xc2028_dvb_release(struct dvb_frontend *fe)
1216 {
1217         struct xc2028_data *priv = fe->tuner_priv;
1218
1219         tuner_dbg("%s called\n", __func__);
1220
1221         mutex_lock(&xc2028_list_mutex);
1222
1223         /* only perform final cleanup if this is the last instance */
1224         if (hybrid_tuner_report_instance_count(priv) == 1) {
1225                 kfree(priv->ctrl.fname);
1226                 free_firmware(priv);
1227         }
1228
1229         if (priv)
1230                 hybrid_tuner_release_state(priv);
1231
1232         mutex_unlock(&xc2028_list_mutex);
1233
1234         fe->tuner_priv = NULL;
1235
1236         return 0;
1237 }
1238
1239 static int xc2028_get_frequency(struct dvb_frontend *fe, u32 *frequency)
1240 {
1241         struct xc2028_data *priv = fe->tuner_priv;
1242
1243         tuner_dbg("%s called\n", __func__);
1244
1245         *frequency = priv->frequency;
1246
1247         return 0;
1248 }
1249
1250 static int xc2028_set_config(struct dvb_frontend *fe, void *priv_cfg)
1251 {
1252         struct xc2028_data *priv = fe->tuner_priv;
1253         struct xc2028_ctrl *p    = priv_cfg;
1254         int                 rc   = 0;
1255
1256         tuner_dbg("%s called\n", __func__);
1257
1258         mutex_lock(&priv->lock);
1259
1260         memcpy(&priv->ctrl, p, sizeof(priv->ctrl));
1261         if (priv->ctrl.max_len < 9)
1262                 priv->ctrl.max_len = 13;
1263
1264         if (p->fname) {
1265                 if (priv->ctrl.fname && strcmp(p->fname, priv->ctrl.fname)) {
1266                         kfree(priv->ctrl.fname);
1267                         free_firmware(priv);
1268                 }
1269
1270                 priv->ctrl.fname = kstrdup(p->fname, GFP_KERNEL);
1271                 if (priv->ctrl.fname == NULL)
1272                         rc = -ENOMEM;
1273         }
1274
1275         mutex_unlock(&priv->lock);
1276
1277         return rc;
1278 }
1279
1280 static const struct dvb_tuner_ops xc2028_dvb_tuner_ops = {
1281         .info = {
1282                  .name = "Xceive XC3028",
1283                  .frequency_min = 42000000,
1284                  .frequency_max = 864000000,
1285                  .frequency_step = 50000,
1286                  },
1287
1288         .set_config        = xc2028_set_config,
1289         .set_analog_params = xc2028_set_analog_freq,
1290         .release           = xc2028_dvb_release,
1291         .get_frequency     = xc2028_get_frequency,
1292         .get_rf_strength   = xc2028_signal,
1293         .set_params        = xc2028_set_params,
1294         .sleep             = xc2028_sleep,
1295 };
1296
1297 struct dvb_frontend *xc2028_attach(struct dvb_frontend *fe,
1298                                    struct xc2028_config *cfg)
1299 {
1300         struct xc2028_data *priv;
1301         int instance;
1302
1303         if (debug)
1304                 printk(KERN_DEBUG "xc2028: Xcv2028/3028 init called!\n");
1305
1306         if (NULL == cfg)
1307                 return NULL;
1308
1309         if (!fe) {
1310                 printk(KERN_ERR "xc2028: No frontend!\n");
1311                 return NULL;
1312         }
1313
1314         mutex_lock(&xc2028_list_mutex);
1315
1316         instance = hybrid_tuner_request_state(struct xc2028_data, priv,
1317                                               hybrid_tuner_instance_list,
1318                                               cfg->i2c_adap, cfg->i2c_addr,
1319                                               "xc2028");
1320         switch (instance) {
1321         case 0:
1322                 /* memory allocation failure */
1323                 goto fail;
1324                 break;
1325         case 1:
1326                 /* new tuner instance */
1327                 priv->ctrl.max_len = 13;
1328
1329                 mutex_init(&priv->lock);
1330
1331                 fe->tuner_priv = priv;
1332                 break;
1333         case 2:
1334                 /* existing tuner instance */
1335                 fe->tuner_priv = priv;
1336                 break;
1337         }
1338
1339         memcpy(&fe->ops.tuner_ops, &xc2028_dvb_tuner_ops,
1340                sizeof(xc2028_dvb_tuner_ops));
1341
1342         tuner_info("type set to %s\n", "XCeive xc2028/xc3028 tuner");
1343
1344         if (cfg->ctrl)
1345                 xc2028_set_config(fe, cfg->ctrl);
1346
1347         mutex_unlock(&xc2028_list_mutex);
1348
1349         return fe;
1350 fail:
1351         mutex_unlock(&xc2028_list_mutex);
1352
1353         xc2028_dvb_release(fe);
1354         return NULL;
1355 }
1356
1357 EXPORT_SYMBOL(xc2028_attach);
1358
1359 MODULE_DESCRIPTION("Xceive xc2028/xc3028 tuner driver");
1360 MODULE_AUTHOR("Michel Ludwig <michel.ludwig@gmail.com>");
1361 MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@infradead.org>");
1362 MODULE_LICENSE("GPL");