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