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