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