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