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