]> git.karo-electronics.de Git - mv-sheeva.git/blob - drivers/staging/lirc/lirc_zilog.c
[media] lirc_zilog: Remove disable_tx module parameter
[mv-sheeva.git] / drivers / staging / lirc / lirc_zilog.c
1 /*
2  * i2c IR lirc driver for devices with zilog IR processors
3  *
4  * Copyright (c) 2000 Gerd Knorr <kraxel@goldbach.in-berlin.de>
5  * modified for PixelView (BT878P+W/FM) by
6  *      Michal Kochanowicz <mkochano@pld.org.pl>
7  *      Christoph Bartelmus <lirc@bartelmus.de>
8  * modified for KNC ONE TV Station/Anubis Typhoon TView Tuner by
9  *      Ulrich Mueller <ulrich.mueller42@web.de>
10  * modified for Asus TV-Box and Creative/VisionTek BreakOut-Box by
11  *      Stefan Jahn <stefan@lkcc.org>
12  * modified for inclusion into kernel sources by
13  *      Jerome Brock <jbrock@users.sourceforge.net>
14  * modified for Leadtek Winfast PVR2000 by
15  *      Thomas Reitmayr (treitmayr@yahoo.com)
16  * modified for Hauppauge PVR-150 IR TX device by
17  *      Mark Weaver <mark@npsl.co.uk>
18  * changed name from lirc_pvr150 to lirc_zilog, works on more than pvr-150
19  *      Jarod Wilson <jarod@redhat.com>
20  *
21  * parts are cut&pasted from the lirc_i2c.c driver
22  *
23  *  This program is free software; you can redistribute it and/or modify
24  *  it under the terms of the GNU General Public License as published by
25  *  the Free Software Foundation; either version 2 of the License, or
26  *  (at your option) any later version.
27  *
28  *  This program is distributed in the hope that it will be useful,
29  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
30  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
31  *  GNU General Public License for more details.
32  *
33  *  You should have received a copy of the GNU General Public License
34  *  along with this program; if not, write to the Free Software
35  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
36  *
37  */
38
39
40 #include <linux/version.h>
41 #include <linux/module.h>
42 #include <linux/kmod.h>
43 #include <linux/kernel.h>
44 #include <linux/sched.h>
45 #include <linux/fs.h>
46 #include <linux/poll.h>
47 #include <linux/string.h>
48 #include <linux/timer.h>
49 #include <linux/delay.h>
50 #include <linux/completion.h>
51 #include <linux/errno.h>
52 #include <linux/slab.h>
53 #include <linux/i2c.h>
54 #include <linux/firmware.h>
55 #include <linux/vmalloc.h>
56
57 #include <linux/mutex.h>
58 #include <linux/kthread.h>
59
60 #include <media/lirc_dev.h>
61 #include <media/lirc.h>
62
63 struct IR {
64         struct lirc_driver l;
65
66         /* Device info */
67         struct mutex ir_lock;
68         int open;
69         bool is_hdpvr;
70
71         /* RX device */
72         struct i2c_client c_rx;
73         int have_rx;
74
75         /* RX device buffer & lock */
76         struct lirc_buffer buf;
77         struct mutex buf_lock;
78
79         /* RX polling thread data */
80         struct completion *t_notify;
81         struct completion *t_notify2;
82         int shutdown;
83         struct task_struct *task;
84
85         /* RX read data */
86         unsigned char b[3];
87
88         /* TX device */
89         struct i2c_client c_tx;
90         int need_boot;
91         int have_tx;
92 };
93
94 /* Minor -> data mapping */
95 static struct IR *ir_devices[MAX_IRCTL_DEVICES];
96
97 /* Block size for IR transmitter */
98 #define TX_BLOCK_SIZE   99
99
100 /* Hauppauge IR transmitter data */
101 struct tx_data_struct {
102         /* Boot block */
103         unsigned char *boot_data;
104
105         /* Start of binary data block */
106         unsigned char *datap;
107
108         /* End of binary data block */
109         unsigned char *endp;
110
111         /* Number of installed codesets */
112         unsigned int num_code_sets;
113
114         /* Pointers to codesets */
115         unsigned char **code_sets;
116
117         /* Global fixed data template */
118         int fixed[TX_BLOCK_SIZE];
119 };
120
121 static struct tx_data_struct *tx_data;
122 static struct mutex tx_data_lock;
123
124 #define zilog_notify(s, args...) printk(KERN_NOTICE KBUILD_MODNAME ": " s, \
125                                         ## args)
126 #define zilog_error(s, args...) printk(KERN_ERR KBUILD_MODNAME ": " s, ## args)
127
128 #define ZILOG_HAUPPAUGE_IR_RX_NAME "Zilog/Hauppauge IR RX"
129 #define ZILOG_HAUPPAUGE_IR_TX_NAME "Zilog/Hauppauge IR TX"
130
131 /* module parameters */
132 static int debug;       /* debug output */
133 static int disable_rx;  /* disable RX device */
134 static int minor = -1;  /* minor number */
135
136 #define dprintk(fmt, args...)                                           \
137         do {                                                            \
138                 if (debug)                                              \
139                         printk(KERN_DEBUG KBUILD_MODNAME ": " fmt,      \
140                                  ## args);                              \
141         } while (0)
142
143 static int add_to_buf(struct IR *ir)
144 {
145         __u16 code;
146         unsigned char codes[2];
147         unsigned char keybuf[6];
148         int got_data = 0;
149         int ret;
150         int failures = 0;
151         unsigned char sendbuf[1] = { 0 };
152
153         if (lirc_buffer_full(&ir->buf)) {
154                 dprintk("buffer overflow\n");
155                 return -EOVERFLOW;
156         }
157
158         /*
159          * service the device as long as it is returning
160          * data and we have space
161          */
162         do {
163                 /*
164                  * Lock i2c bus for the duration.  RX/TX chips interfere so
165                  * this is worth it
166                  */
167                 mutex_lock(&ir->ir_lock);
168
169                 /*
170                  * Send random "poll command" (?)  Windows driver does this
171                  * and it is a good point to detect chip failure.
172                  */
173                 ret = i2c_master_send(&ir->c_rx, sendbuf, 1);
174                 if (ret != 1) {
175                         zilog_error("i2c_master_send failed with %d\n", ret);
176                         if (failures >= 3) {
177                                 mutex_unlock(&ir->ir_lock);
178                                 zilog_error("unable to read from the IR chip "
179                                             "after 3 resets, giving up\n");
180                                 return ret;
181                         }
182
183                         /* Looks like the chip crashed, reset it */
184                         zilog_error("polling the IR receiver chip failed, "
185                                     "trying reset\n");
186
187                         set_current_state(TASK_UNINTERRUPTIBLE);
188                         schedule_timeout((100 * HZ + 999) / 1000);
189                         ir->need_boot = 1;
190
191                         ++failures;
192                         mutex_unlock(&ir->ir_lock);
193                         continue;
194                 }
195
196                 ret = i2c_master_recv(&ir->c_rx, keybuf, sizeof(keybuf));
197                 mutex_unlock(&ir->ir_lock);
198                 if (ret != sizeof(keybuf)) {
199                         zilog_error("i2c_master_recv failed with %d -- "
200                                     "keeping last read buffer\n", ret);
201                 } else {
202                         ir->b[0] = keybuf[3];
203                         ir->b[1] = keybuf[4];
204                         ir->b[2] = keybuf[5];
205                         dprintk("key (0x%02x/0x%02x)\n", ir->b[0], ir->b[1]);
206                 }
207
208                 /* key pressed ? */
209                 if (ir->is_hdpvr) {
210                         if (got_data && (keybuf[0] == 0x80))
211                                 return 0;
212                         else if (got_data && (keybuf[0] == 0x00))
213                                 return -ENODATA;
214                 } else if ((ir->b[0] & 0x80) == 0)
215                         return got_data ? 0 : -ENODATA;
216
217                 /* look what we have */
218                 code = (((__u16)ir->b[0] & 0x7f) << 6) | (ir->b[1] >> 2);
219
220                 codes[0] = (code >> 8) & 0xff;
221                 codes[1] = code & 0xff;
222
223                 /* return it */
224                 lirc_buffer_write(&ir->buf, codes);
225                 ++got_data;
226         } while (!lirc_buffer_full(&ir->buf));
227
228         return 0;
229 }
230
231 /*
232  * Main function of the polling thread -- from lirc_dev.
233  * We don't fit the LIRC model at all anymore.  This is horrible, but
234  * basically we have a single RX/TX device with a nasty failure mode
235  * that needs to be accounted for across the pair.  lirc lets us provide
236  * fops, but prevents us from using the internal polling, etc. if we do
237  * so.  Hence the replication.  Might be neater to extend the LIRC model
238  * to account for this but I'd think it's a very special case of seriously
239  * messed up hardware.
240  */
241 static int lirc_thread(void *arg)
242 {
243         struct IR *ir = arg;
244
245         if (ir->t_notify != NULL)
246                 complete(ir->t_notify);
247
248         dprintk("poll thread started\n");
249
250         do {
251                 if (ir->open) {
252                         set_current_state(TASK_INTERRUPTIBLE);
253
254                         /*
255                          * This is ~113*2 + 24 + jitter (2*repeat gap +
256                          * code length).  We use this interval as the chip
257                          * resets every time you poll it (bad!).  This is
258                          * therefore just sufficient to catch all of the
259                          * button presses.  It makes the remote much more
260                          * responsive.  You can see the difference by
261                          * running irw and holding down a button.  With
262                          * 100ms, the old polling interval, you'll notice
263                          * breaks in the repeat sequence corresponding to
264                          * lost keypresses.
265                          */
266                         schedule_timeout((260 * HZ) / 1000);
267                         if (ir->shutdown)
268                                 break;
269                         if (!add_to_buf(ir))
270                                 wake_up_interruptible(&ir->buf.wait_poll);
271                 } else {
272                         /* if device not opened so we can sleep half a second */
273                         set_current_state(TASK_INTERRUPTIBLE);
274                         schedule_timeout(HZ/2);
275                 }
276         } while (!ir->shutdown);
277
278         if (ir->t_notify2 != NULL)
279                 wait_for_completion(ir->t_notify2);
280
281         ir->task = NULL;
282         if (ir->t_notify != NULL)
283                 complete(ir->t_notify);
284
285         dprintk("poll thread ended\n");
286         return 0;
287 }
288
289 static int set_use_inc(void *data)
290 {
291         struct IR *ir = data;
292
293         if (ir->l.owner == NULL || try_module_get(ir->l.owner) == 0)
294                 return -ENODEV;
295
296         /* lock bttv in memory while /dev/lirc is in use  */
297         /*
298          * this is completely broken code. lirc_unregister_driver()
299          * must be possible even when the device is open
300          */
301         if (ir->c_rx.addr)
302                 i2c_use_client(&ir->c_rx);
303         if (ir->c_tx.addr)
304                 i2c_use_client(&ir->c_tx);
305
306         return 0;
307 }
308
309 static void set_use_dec(void *data)
310 {
311         struct IR *ir = data;
312
313         if (ir->c_rx.addr)
314                 i2c_release_client(&ir->c_rx);
315         if (ir->c_tx.addr)
316                 i2c_release_client(&ir->c_tx);
317         if (ir->l.owner != NULL)
318                 module_put(ir->l.owner);
319 }
320
321 /* safe read of a uint32 (always network byte order) */
322 static int read_uint32(unsigned char **data,
323                                      unsigned char *endp, unsigned int *val)
324 {
325         if (*data + 4 > endp)
326                 return 0;
327         *val = ((*data)[0] << 24) | ((*data)[1] << 16) |
328                ((*data)[2] << 8) | (*data)[3];
329         *data += 4;
330         return 1;
331 }
332
333 /* safe read of a uint8 */
334 static int read_uint8(unsigned char **data,
335                                     unsigned char *endp, unsigned char *val)
336 {
337         if (*data + 1 > endp)
338                 return 0;
339         *val = *((*data)++);
340         return 1;
341 }
342
343 /* safe skipping of N bytes */
344 static int skip(unsigned char **data,
345                               unsigned char *endp, unsigned int distance)
346 {
347         if (*data + distance > endp)
348                 return 0;
349         *data += distance;
350         return 1;
351 }
352
353 /* decompress key data into the given buffer */
354 static int get_key_data(unsigned char *buf,
355                              unsigned int codeset, unsigned int key)
356 {
357         unsigned char *data, *endp, *diffs, *key_block;
358         unsigned char keys, ndiffs, id;
359         unsigned int base, lim, pos, i;
360
361         /* Binary search for the codeset */
362         for (base = 0, lim = tx_data->num_code_sets; lim; lim >>= 1) {
363                 pos = base + (lim >> 1);
364                 data = tx_data->code_sets[pos];
365
366                 if (!read_uint32(&data, tx_data->endp, &i))
367                         goto corrupt;
368
369                 if (i == codeset)
370                         break;
371                 else if (codeset > i) {
372                         base = pos + 1;
373                         --lim;
374                 }
375         }
376         /* Not found? */
377         if (!lim)
378                 return -EPROTO;
379
380         /* Set end of data block */
381         endp = pos < tx_data->num_code_sets - 1 ?
382                 tx_data->code_sets[pos + 1] : tx_data->endp;
383
384         /* Read the block header */
385         if (!read_uint8(&data, endp, &keys) ||
386             !read_uint8(&data, endp, &ndiffs) ||
387             ndiffs > TX_BLOCK_SIZE || keys == 0)
388                 goto corrupt;
389
390         /* Save diffs & skip */
391         diffs = data;
392         if (!skip(&data, endp, ndiffs))
393                 goto corrupt;
394
395         /* Read the id of the first key */
396         if (!read_uint8(&data, endp, &id))
397                 goto corrupt;
398
399         /* Unpack the first key's data */
400         for (i = 0; i < TX_BLOCK_SIZE; ++i) {
401                 if (tx_data->fixed[i] == -1) {
402                         if (!read_uint8(&data, endp, &buf[i]))
403                                 goto corrupt;
404                 } else {
405                         buf[i] = (unsigned char)tx_data->fixed[i];
406                 }
407         }
408
409         /* Early out key found/not found */
410         if (key == id)
411                 return 0;
412         if (keys == 1)
413                 return -EPROTO;
414
415         /* Sanity check */
416         key_block = data;
417         if (!skip(&data, endp, (keys - 1) * (ndiffs + 1)))
418                 goto corrupt;
419
420         /* Binary search for the key */
421         for (base = 0, lim = keys - 1; lim; lim >>= 1) {
422                 /* Seek to block */
423                 unsigned char *key_data;
424                 pos = base + (lim >> 1);
425                 key_data = key_block + (ndiffs + 1) * pos;
426
427                 if (*key_data == key) {
428                         /* skip key id */
429                         ++key_data;
430
431                         /* found, so unpack the diffs */
432                         for (i = 0; i < ndiffs; ++i) {
433                                 unsigned char val;
434                                 if (!read_uint8(&key_data, endp, &val) ||
435                                     diffs[i] >= TX_BLOCK_SIZE)
436                                         goto corrupt;
437                                 buf[diffs[i]] = val;
438                         }
439
440                         return 0;
441                 } else if (key > *key_data) {
442                         base = pos + 1;
443                         --lim;
444                 }
445         }
446         /* Key not found */
447         return -EPROTO;
448
449 corrupt:
450         zilog_error("firmware is corrupt\n");
451         return -EFAULT;
452 }
453
454 /* send a block of data to the IR TX device */
455 static int send_data_block(struct IR *ir, unsigned char *data_block)
456 {
457         int i, j, ret;
458         unsigned char buf[5];
459
460         for (i = 0; i < TX_BLOCK_SIZE;) {
461                 int tosend = TX_BLOCK_SIZE - i;
462                 if (tosend > 4)
463                         tosend = 4;
464                 buf[0] = (unsigned char)(i + 1);
465                 for (j = 0; j < tosend; ++j)
466                         buf[1 + j] = data_block[i + j];
467                 dprintk("%02x %02x %02x %02x %02x",
468                         buf[0], buf[1], buf[2], buf[3], buf[4]);
469                 ret = i2c_master_send(&ir->c_tx, buf, tosend + 1);
470                 if (ret != tosend + 1) {
471                         zilog_error("i2c_master_send failed with %d\n", ret);
472                         return ret < 0 ? ret : -EFAULT;
473                 }
474                 i += tosend;
475         }
476         return 0;
477 }
478
479 /* send boot data to the IR TX device */
480 static int send_boot_data(struct IR *ir)
481 {
482         int ret;
483         unsigned char buf[4];
484
485         /* send the boot block */
486         ret = send_data_block(ir, tx_data->boot_data);
487         if (ret != 0)
488                 return ret;
489
490         /* kick it off? */
491         buf[0] = 0x00;
492         buf[1] = 0x20;
493         ret = i2c_master_send(&ir->c_tx, buf, 2);
494         if (ret != 2) {
495                 zilog_error("i2c_master_send failed with %d\n", ret);
496                 return ret < 0 ? ret : -EFAULT;
497         }
498         ret = i2c_master_send(&ir->c_tx, buf, 1);
499         if (ret != 1) {
500                 zilog_error("i2c_master_send failed with %d\n", ret);
501                 return ret < 0 ? ret : -EFAULT;
502         }
503
504         /* Here comes the firmware version... (hopefully) */
505         ret = i2c_master_recv(&ir->c_tx, buf, 4);
506         if (ret != 4) {
507                 zilog_error("i2c_master_recv failed with %d\n", ret);
508                 return 0;
509         }
510         if (buf[0] != 0x80) {
511                 zilog_error("unexpected IR TX response: %02x\n", buf[0]);
512                 return 0;
513         }
514         zilog_notify("Zilog/Hauppauge IR blaster firmware version "
515                      "%d.%d.%d loaded\n", buf[1], buf[2], buf[3]);
516
517         return 0;
518 }
519
520 /* unload "firmware", lock held */
521 static void fw_unload_locked(void)
522 {
523         if (tx_data) {
524                 if (tx_data->code_sets)
525                         vfree(tx_data->code_sets);
526
527                 if (tx_data->datap)
528                         vfree(tx_data->datap);
529
530                 vfree(tx_data);
531                 tx_data = NULL;
532                 dprintk("successfully unloaded IR blaster firmware\n");
533         }
534 }
535
536 /* unload "firmware" for the IR TX device */
537 static void fw_unload(void)
538 {
539         mutex_lock(&tx_data_lock);
540         fw_unload_locked();
541         mutex_unlock(&tx_data_lock);
542 }
543
544 /* load "firmware" for the IR TX device */
545 static int fw_load(struct IR *ir)
546 {
547         int ret;
548         unsigned int i;
549         unsigned char *data, version, num_global_fixed;
550         const struct firmware *fw_entry;
551
552         /* Already loaded? */
553         mutex_lock(&tx_data_lock);
554         if (tx_data) {
555                 ret = 0;
556                 goto out;
557         }
558
559         /* Request codeset data file */
560         ret = request_firmware(&fw_entry, "haup-ir-blaster.bin", &ir->c_tx.dev);
561         if (ret != 0) {
562                 zilog_error("firmware haup-ir-blaster.bin not available "
563                             "(%d)\n", ret);
564                 ret = ret < 0 ? ret : -EFAULT;
565                 goto out;
566         }
567         dprintk("firmware of size %zu loaded\n", fw_entry->size);
568
569         /* Parse the file */
570         tx_data = vmalloc(sizeof(*tx_data));
571         if (tx_data == NULL) {
572                 zilog_error("out of memory\n");
573                 release_firmware(fw_entry);
574                 ret = -ENOMEM;
575                 goto out;
576         }
577         tx_data->code_sets = NULL;
578
579         /* Copy the data so hotplug doesn't get confused and timeout */
580         tx_data->datap = vmalloc(fw_entry->size);
581         if (tx_data->datap == NULL) {
582                 zilog_error("out of memory\n");
583                 release_firmware(fw_entry);
584                 vfree(tx_data);
585                 ret = -ENOMEM;
586                 goto out;
587         }
588         memcpy(tx_data->datap, fw_entry->data, fw_entry->size);
589         tx_data->endp = tx_data->datap + fw_entry->size;
590         release_firmware(fw_entry); fw_entry = NULL;
591
592         /* Check version */
593         data = tx_data->datap;
594         if (!read_uint8(&data, tx_data->endp, &version))
595                 goto corrupt;
596         if (version != 1) {
597                 zilog_error("unsupported code set file version (%u, expected"
598                             "1) -- please upgrade to a newer driver",
599                             version);
600                 fw_unload_locked();
601                 ret = -EFAULT;
602                 goto out;
603         }
604
605         /* Save boot block for later */
606         tx_data->boot_data = data;
607         if (!skip(&data, tx_data->endp, TX_BLOCK_SIZE))
608                 goto corrupt;
609
610         if (!read_uint32(&data, tx_data->endp,
611                               &tx_data->num_code_sets))
612                 goto corrupt;
613
614         dprintk("%u IR blaster codesets loaded\n", tx_data->num_code_sets);
615
616         tx_data->code_sets = vmalloc(
617                 tx_data->num_code_sets * sizeof(char *));
618         if (tx_data->code_sets == NULL) {
619                 fw_unload_locked();
620                 ret = -ENOMEM;
621                 goto out;
622         }
623
624         for (i = 0; i < TX_BLOCK_SIZE; ++i)
625                 tx_data->fixed[i] = -1;
626
627         /* Read global fixed data template */
628         if (!read_uint8(&data, tx_data->endp, &num_global_fixed) ||
629             num_global_fixed > TX_BLOCK_SIZE)
630                 goto corrupt;
631         for (i = 0; i < num_global_fixed; ++i) {
632                 unsigned char pos, val;
633                 if (!read_uint8(&data, tx_data->endp, &pos) ||
634                     !read_uint8(&data, tx_data->endp, &val) ||
635                     pos >= TX_BLOCK_SIZE)
636                         goto corrupt;
637                 tx_data->fixed[pos] = (int)val;
638         }
639
640         /* Filch out the position of each code set */
641         for (i = 0; i < tx_data->num_code_sets; ++i) {
642                 unsigned int id;
643                 unsigned char keys;
644                 unsigned char ndiffs;
645
646                 /* Save the codeset position */
647                 tx_data->code_sets[i] = data;
648
649                 /* Read header */
650                 if (!read_uint32(&data, tx_data->endp, &id) ||
651                     !read_uint8(&data, tx_data->endp, &keys) ||
652                     !read_uint8(&data, tx_data->endp, &ndiffs) ||
653                     ndiffs > TX_BLOCK_SIZE || keys == 0)
654                         goto corrupt;
655
656                 /* skip diff positions */
657                 if (!skip(&data, tx_data->endp, ndiffs))
658                         goto corrupt;
659
660                 /*
661                  * After the diffs we have the first key id + data -
662                  * global fixed
663                  */
664                 if (!skip(&data, tx_data->endp,
665                                1 + TX_BLOCK_SIZE - num_global_fixed))
666                         goto corrupt;
667
668                 /* Then we have keys-1 blocks of key id+diffs */
669                 if (!skip(&data, tx_data->endp,
670                                (ndiffs + 1) * (keys - 1)))
671                         goto corrupt;
672         }
673         ret = 0;
674         goto out;
675
676 corrupt:
677         zilog_error("firmware is corrupt\n");
678         fw_unload_locked();
679         ret = -EFAULT;
680
681 out:
682         mutex_unlock(&tx_data_lock);
683         return ret;
684 }
685
686 /* initialise the IR TX device */
687 static int tx_init(struct IR *ir)
688 {
689         int ret;
690
691         /* Load 'firmware' */
692         ret = fw_load(ir);
693         if (ret != 0)
694                 return ret;
695
696         /* Send boot block */
697         ret = send_boot_data(ir);
698         if (ret != 0)
699                 return ret;
700         ir->need_boot = 0;
701
702         /* Looks good */
703         return 0;
704 }
705
706 /* do nothing stub to make LIRC happy */
707 static loff_t lseek(struct file *filep, loff_t offset, int orig)
708 {
709         return -ESPIPE;
710 }
711
712 /* copied from lirc_dev */
713 static ssize_t read(struct file *filep, char *outbuf, size_t n, loff_t *ppos)
714 {
715         struct IR *ir = filep->private_data;
716         unsigned char buf[ir->buf.chunk_size];
717         int ret = 0, written = 0;
718         DECLARE_WAITQUEUE(wait, current);
719
720         dprintk("read called\n");
721         if (ir->c_rx.addr == 0)
722                 return -ENODEV;
723
724         if (mutex_lock_interruptible(&ir->buf_lock))
725                 return -ERESTARTSYS;
726
727         if (n % ir->buf.chunk_size) {
728                 dprintk("read result = -EINVAL\n");
729                 mutex_unlock(&ir->buf_lock);
730                 return -EINVAL;
731         }
732
733         /*
734          * we add ourselves to the task queue before buffer check
735          * to avoid losing scan code (in case when queue is awaken somewhere
736          * between while condition checking and scheduling)
737          */
738         add_wait_queue(&ir->buf.wait_poll, &wait);
739         set_current_state(TASK_INTERRUPTIBLE);
740
741         /*
742          * while we didn't provide 'length' bytes, device is opened in blocking
743          * mode and 'copy_to_user' is happy, wait for data.
744          */
745         while (written < n && ret == 0) {
746                 if (lirc_buffer_empty(&ir->buf)) {
747                         /*
748                          * According to the read(2) man page, 'written' can be
749                          * returned as less than 'n', instead of blocking
750                          * again, returning -EWOULDBLOCK, or returning
751                          * -ERESTARTSYS
752                          */
753                         if (written)
754                                 break;
755                         if (filep->f_flags & O_NONBLOCK) {
756                                 ret = -EWOULDBLOCK;
757                                 break;
758                         }
759                         if (signal_pending(current)) {
760                                 ret = -ERESTARTSYS;
761                                 break;
762                         }
763                         schedule();
764                         set_current_state(TASK_INTERRUPTIBLE);
765                 } else {
766                         lirc_buffer_read(&ir->buf, buf);
767                         ret = copy_to_user((void *)outbuf+written, buf,
768                                            ir->buf.chunk_size);
769                         written += ir->buf.chunk_size;
770                 }
771         }
772
773         remove_wait_queue(&ir->buf.wait_poll, &wait);
774         set_current_state(TASK_RUNNING);
775         mutex_unlock(&ir->buf_lock);
776
777         dprintk("read result = %s (%d)\n",
778                 ret ? "-EFAULT" : "OK", ret);
779
780         return ret ? ret : written;
781 }
782
783 /* send a keypress to the IR TX device */
784 static int send_code(struct IR *ir, unsigned int code, unsigned int key)
785 {
786         unsigned char data_block[TX_BLOCK_SIZE];
787         unsigned char buf[2];
788         int i, ret;
789
790         /* Get data for the codeset/key */
791         ret = get_key_data(data_block, code, key);
792
793         if (ret == -EPROTO) {
794                 zilog_error("failed to get data for code %u, key %u -- check "
795                             "lircd.conf entries\n", code, key);
796                 return ret;
797         } else if (ret != 0)
798                 return ret;
799
800         /* Send the data block */
801         ret = send_data_block(ir, data_block);
802         if (ret != 0)
803                 return ret;
804
805         /* Send data block length? */
806         buf[0] = 0x00;
807         buf[1] = 0x40;
808         ret = i2c_master_send(&ir->c_tx, buf, 2);
809         if (ret != 2) {
810                 zilog_error("i2c_master_send failed with %d\n", ret);
811                 return ret < 0 ? ret : -EFAULT;
812         }
813         ret = i2c_master_send(&ir->c_tx, buf, 1);
814         if (ret != 1) {
815                 zilog_error("i2c_master_send failed with %d\n", ret);
816                 return ret < 0 ? ret : -EFAULT;
817         }
818
819         /* Send finished download? */
820         ret = i2c_master_recv(&ir->c_tx, buf, 1);
821         if (ret != 1) {
822                 zilog_error("i2c_master_recv failed with %d\n", ret);
823                 return ret < 0 ? ret : -EFAULT;
824         }
825         if (buf[0] != 0xA0) {
826                 zilog_error("unexpected IR TX response #1: %02x\n",
827                         buf[0]);
828                 return -EFAULT;
829         }
830
831         /* Send prepare command? */
832         buf[0] = 0x00;
833         buf[1] = 0x80;
834         ret = i2c_master_send(&ir->c_tx, buf, 2);
835         if (ret != 2) {
836                 zilog_error("i2c_master_send failed with %d\n", ret);
837                 return ret < 0 ? ret : -EFAULT;
838         }
839
840         /*
841          * The sleep bits aren't necessary on the HD PVR, and in fact, the
842          * last i2c_master_recv always fails with a -5, so for now, we're
843          * going to skip this whole mess and say we're done on the HD PVR
844          */
845         if (ir->is_hdpvr) {
846                 dprintk("sent code %u, key %u\n", code, key);
847                 return 0;
848         }
849
850         /*
851          * This bit NAKs until the device is ready, so we retry it
852          * sleeping a bit each time.  This seems to be what the windows
853          * driver does, approximately.
854          * Try for up to 1s.
855          */
856         for (i = 0; i < 20; ++i) {
857                 set_current_state(TASK_UNINTERRUPTIBLE);
858                 schedule_timeout((50 * HZ + 999) / 1000);
859                 ret = i2c_master_send(&ir->c_tx, buf, 1);
860                 if (ret == 1)
861                         break;
862                 dprintk("NAK expected: i2c_master_send "
863                         "failed with %d (try %d)\n", ret, i+1);
864         }
865         if (ret != 1) {
866                 zilog_error("IR TX chip never got ready: last i2c_master_send "
867                             "failed with %d\n", ret);
868                 return ret < 0 ? ret : -EFAULT;
869         }
870
871         /* Seems to be an 'ok' response */
872         i = i2c_master_recv(&ir->c_tx, buf, 1);
873         if (i != 1) {
874                 zilog_error("i2c_master_recv failed with %d\n", ret);
875                 return -EFAULT;
876         }
877         if (buf[0] != 0x80) {
878                 zilog_error("unexpected IR TX response #2: %02x\n", buf[0]);
879                 return -EFAULT;
880         }
881
882         /* Oh good, it worked */
883         dprintk("sent code %u, key %u\n", code, key);
884         return 0;
885 }
886
887 /*
888  * Write a code to the device.  We take in a 32-bit number (an int) and then
889  * decode this to a codeset/key index.  The key data is then decompressed and
890  * sent to the device.  We have a spin lock as per i2c documentation to prevent
891  * multiple concurrent sends which would probably cause the device to explode.
892  */
893 static ssize_t write(struct file *filep, const char *buf, size_t n,
894                           loff_t *ppos)
895 {
896         struct IR *ir = filep->private_data;
897         size_t i;
898         int failures = 0;
899
900         if (ir->c_tx.addr == 0)
901                 return -ENODEV;
902
903         /* Validate user parameters */
904         if (n % sizeof(int))
905                 return -EINVAL;
906
907         /* Lock i2c bus for the duration */
908         mutex_lock(&ir->ir_lock);
909
910         /* Send each keypress */
911         for (i = 0; i < n;) {
912                 int ret = 0;
913                 int command;
914
915                 if (copy_from_user(&command, buf + i, sizeof(command))) {
916                         mutex_unlock(&ir->ir_lock);
917                         return -EFAULT;
918                 }
919
920                 /* Send boot data first if required */
921                 if (ir->need_boot == 1) {
922                         ret = send_boot_data(ir);
923                         if (ret == 0)
924                                 ir->need_boot = 0;
925                 }
926
927                 /* Send the code */
928                 if (ret == 0) {
929                         ret = send_code(ir, (unsigned)command >> 16,
930                                             (unsigned)command & 0xFFFF);
931                         if (ret == -EPROTO) {
932                                 mutex_unlock(&ir->ir_lock);
933                                 return ret;
934                         }
935                 }
936
937                 /*
938                  * Hmm, a failure.  If we've had a few then give up, otherwise
939                  * try a reset
940                  */
941                 if (ret != 0) {
942                         /* Looks like the chip crashed, reset it */
943                         zilog_error("sending to the IR transmitter chip "
944                                     "failed, trying reset\n");
945
946                         if (failures >= 3) {
947                                 zilog_error("unable to send to the IR chip "
948                                             "after 3 resets, giving up\n");
949                                 mutex_unlock(&ir->ir_lock);
950                                 return ret;
951                         }
952                         set_current_state(TASK_UNINTERRUPTIBLE);
953                         schedule_timeout((100 * HZ + 999) / 1000);
954                         ir->need_boot = 1;
955                         ++failures;
956                 } else
957                         i += sizeof(int);
958         }
959
960         /* Release i2c bus */
961         mutex_unlock(&ir->ir_lock);
962
963         /* All looks good */
964         return n;
965 }
966
967 /* copied from lirc_dev */
968 static unsigned int poll(struct file *filep, poll_table *wait)
969 {
970         struct IR *ir = filep->private_data;
971         unsigned int ret;
972
973         dprintk("poll called\n");
974         if (ir->c_rx.addr == 0)
975                 return -ENODEV;
976
977         mutex_lock(&ir->buf_lock);
978
979         poll_wait(filep, &ir->buf.wait_poll, wait);
980
981         dprintk("poll result = %s\n",
982                 lirc_buffer_empty(&ir->buf) ? "0" : "POLLIN|POLLRDNORM");
983
984         ret = lirc_buffer_empty(&ir->buf) ? 0 : (POLLIN|POLLRDNORM);
985
986         mutex_unlock(&ir->buf_lock);
987         return ret;
988 }
989
990 static long ioctl(struct file *filep, unsigned int cmd, unsigned long arg)
991 {
992         struct IR *ir = filep->private_data;
993         int result;
994         unsigned long mode, features = 0;
995
996         if (ir->c_rx.addr != 0)
997                 features |= LIRC_CAN_REC_LIRCCODE;
998         if (ir->c_tx.addr != 0)
999                 features |= LIRC_CAN_SEND_PULSE;
1000
1001         switch (cmd) {
1002         case LIRC_GET_LENGTH:
1003                 result = put_user((unsigned long)13,
1004                                   (unsigned long *)arg);
1005                 break;
1006         case LIRC_GET_FEATURES:
1007                 result = put_user(features, (unsigned long *) arg);
1008                 break;
1009         case LIRC_GET_REC_MODE:
1010                 if (!(features&LIRC_CAN_REC_MASK))
1011                         return -ENOSYS;
1012
1013                 result = put_user(LIRC_REC2MODE
1014                                   (features&LIRC_CAN_REC_MASK),
1015                                   (unsigned long *)arg);
1016                 break;
1017         case LIRC_SET_REC_MODE:
1018                 if (!(features&LIRC_CAN_REC_MASK))
1019                         return -ENOSYS;
1020
1021                 result = get_user(mode, (unsigned long *)arg);
1022                 if (!result && !(LIRC_MODE2REC(mode) & features))
1023                         result = -EINVAL;
1024                 break;
1025         case LIRC_GET_SEND_MODE:
1026                 if (!(features&LIRC_CAN_SEND_MASK))
1027                         return -ENOSYS;
1028
1029                 result = put_user(LIRC_MODE_PULSE, (unsigned long *) arg);
1030                 break;
1031         case LIRC_SET_SEND_MODE:
1032                 if (!(features&LIRC_CAN_SEND_MASK))
1033                         return -ENOSYS;
1034
1035                 result = get_user(mode, (unsigned long *) arg);
1036                 if (!result && mode != LIRC_MODE_PULSE)
1037                         return -EINVAL;
1038                 break;
1039         default:
1040                 return -EINVAL;
1041         }
1042         return result;
1043 }
1044
1045 /*
1046  * Open the IR device.  Get hold of our IR structure and
1047  * stash it in private_data for the file
1048  */
1049 static int open(struct inode *node, struct file *filep)
1050 {
1051         struct IR *ir;
1052         int ret;
1053
1054         /* find our IR struct */
1055         unsigned minor = MINOR(node->i_rdev);
1056         if (minor >= MAX_IRCTL_DEVICES) {
1057                 dprintk("minor %d: open result = -ENODEV\n",
1058                         minor);
1059                 return -ENODEV;
1060         }
1061         ir = ir_devices[minor];
1062
1063         /* increment in use count */
1064         mutex_lock(&ir->ir_lock);
1065         ++ir->open;
1066         ret = set_use_inc(ir);
1067         if (ret != 0) {
1068                 --ir->open;
1069                 mutex_unlock(&ir->ir_lock);
1070                 return ret;
1071         }
1072         mutex_unlock(&ir->ir_lock);
1073
1074         /* stash our IR struct */
1075         filep->private_data = ir;
1076
1077         return 0;
1078 }
1079
1080 /* Close the IR device */
1081 static int close(struct inode *node, struct file *filep)
1082 {
1083         /* find our IR struct */
1084         struct IR *ir = filep->private_data;
1085         if (ir == NULL) {
1086                 zilog_error("close: no private_data attached to the file!\n");
1087                 return -ENODEV;
1088         }
1089
1090         /* decrement in use count */
1091         mutex_lock(&ir->ir_lock);
1092         --ir->open;
1093         set_use_dec(ir);
1094         mutex_unlock(&ir->ir_lock);
1095
1096         return 0;
1097 }
1098
1099 static struct lirc_driver lirc_template = {
1100         .name           = "lirc_zilog",
1101         .set_use_inc    = set_use_inc,
1102         .set_use_dec    = set_use_dec,
1103         .owner          = THIS_MODULE
1104 };
1105
1106 static int ir_remove(struct i2c_client *client);
1107 static int ir_probe(struct i2c_client *client, const struct i2c_device_id *id);
1108 static int ir_command(struct i2c_client *client, unsigned int cmd, void *arg);
1109
1110 #define ID_FLAG_TX      0x01
1111 #define ID_FLAG_HDPVR   0x02
1112
1113 static const struct i2c_device_id ir_transceiver_id[] = {
1114         { "ir_tx_z8f0811_haup",  ID_FLAG_TX                 },
1115         { "ir_rx_z8f0811_haup",  0                          },
1116         { "ir_tx_z8f0811_hdpvr", ID_FLAG_HDPVR | ID_FLAG_TX },
1117         { "ir_rx_z8f0811_hdpvr", ID_FLAG_HDPVR              },
1118         { }
1119 };
1120
1121 static struct i2c_driver driver = {
1122         .driver = {
1123                 .owner  = THIS_MODULE,
1124                 .name   = "Zilog/Hauppauge i2c IR",
1125         },
1126         .probe          = ir_probe,
1127         .remove         = ir_remove,
1128         .command        = ir_command,
1129         .id_table       = ir_transceiver_id,
1130 };
1131
1132 static const struct file_operations lirc_fops = {
1133         .owner          = THIS_MODULE,
1134         .llseek         = lseek,
1135         .read           = read,
1136         .write          = write,
1137         .poll           = poll,
1138         .unlocked_ioctl = ioctl,
1139 #ifdef CONFIG_COMPAT
1140         .compat_ioctl   = ioctl,
1141 #endif
1142         .open           = open,
1143         .release        = close
1144 };
1145
1146 static int ir_remove(struct i2c_client *client)
1147 {
1148         struct IR *ir = i2c_get_clientdata(client);
1149
1150         mutex_lock(&ir->ir_lock);
1151
1152         if (ir->have_rx || ir->have_tx) {
1153                 DECLARE_COMPLETION(tn);
1154                 DECLARE_COMPLETION(tn2);
1155
1156                 /* end up polling thread */
1157                 if (ir->task && !IS_ERR(ir->task)) {
1158                         ir->t_notify = &tn;
1159                         ir->t_notify2 = &tn2;
1160                         ir->shutdown = 1;
1161                         wake_up_process(ir->task);
1162                         complete(&tn2);
1163                         wait_for_completion(&tn);
1164                         ir->t_notify = NULL;
1165                         ir->t_notify2 = NULL;
1166                 }
1167
1168         } else {
1169                 mutex_unlock(&ir->ir_lock);
1170                 zilog_error("%s: detached from something we didn't "
1171                             "attach to\n", __func__);
1172                 return -ENODEV;
1173         }
1174
1175         /* unregister lirc driver */
1176         if (ir->l.minor >= 0 && ir->l.minor < MAX_IRCTL_DEVICES) {
1177                 lirc_unregister_driver(ir->l.minor);
1178                 ir_devices[ir->l.minor] = NULL;
1179         }
1180
1181         /* free memory */
1182         lirc_buffer_free(&ir->buf);
1183         mutex_unlock(&ir->ir_lock);
1184         kfree(ir);
1185
1186         return 0;
1187 }
1188
1189 static int ir_probe(struct i2c_client *client, const struct i2c_device_id *id)
1190 {
1191         struct IR *ir = NULL;
1192         struct i2c_adapter *adap = client->adapter;
1193         char buf;
1194         int ret;
1195         int have_rx = 0, have_tx = 0;
1196
1197         dprintk("%s: %s on i2c-%d (%s), client addr=0x%02x\n",
1198                 __func__, id->name, adap->nr, adap->name, client->addr);
1199
1200         /*
1201          * FIXME - This probe function probes both the Tx and Rx
1202          * addresses of the IR microcontroller.
1203          *
1204          * However, the I2C subsystem is passing along one I2C client at a
1205          * time, based on matches to the ir_transceiver_id[] table above.
1206          * The expectation is that each i2c_client address will be probed
1207          * individually by drivers so the I2C subsystem can mark all client
1208          * addresses as claimed or not.
1209          *
1210          * This probe routine causes only one of the client addresses, TX or RX,
1211          * to be claimed.  This will cause a problem if the I2C subsystem is
1212          * subsequently triggered to probe unclaimed clients again.
1213          */
1214         /*
1215          * The external IR receiver is at i2c address 0x71.
1216          * The IR transmitter is at 0x70.
1217          */
1218         client->addr = 0x70;
1219
1220         if (i2c_master_recv(client, &buf, 1) == 1)
1221                 have_tx = 1;
1222         dprintk("probe 0x70 @ %s: %s\n",
1223                 adap->name, have_tx ? "success" : "failed");
1224
1225         if (!disable_rx) {
1226                 client->addr = 0x71;
1227                 if (i2c_master_recv(client, &buf, 1) == 1)
1228                         have_rx = 1;
1229                 dprintk("probe 0x71 @ %s: %s\n",
1230                         adap->name, have_rx ? "success" : "failed");
1231         }
1232
1233         if (!(have_rx || have_tx)) {
1234                 zilog_error("%s: no devices found\n", adap->name);
1235                 goto out_nodev;
1236         }
1237
1238         printk(KERN_INFO "lirc_zilog: chip found with %s\n",
1239                 have_rx && have_tx ? "RX and TX" :
1240                         have_rx ? "RX only" : "TX only");
1241
1242         ir = kzalloc(sizeof(struct IR), GFP_KERNEL);
1243
1244         if (!ir)
1245                 goto out_nomem;
1246
1247         ret = lirc_buffer_init(&ir->buf, 2, BUFLEN / 2);
1248         if (ret)
1249                 goto out_nomem;
1250
1251         mutex_init(&ir->ir_lock);
1252         mutex_init(&ir->buf_lock);
1253         ir->need_boot = 1;
1254         ir->is_hdpvr = (id->driver_data & ID_FLAG_HDPVR) ? true : false;
1255
1256         memcpy(&ir->l, &lirc_template, sizeof(struct lirc_driver));
1257         ir->l.minor = -1;
1258
1259         /* I2C attach to device */
1260         i2c_set_clientdata(client, ir);
1261
1262         /* initialise RX device */
1263         if (have_rx) {
1264                 DECLARE_COMPLETION(tn);
1265                 memcpy(&ir->c_rx, client, sizeof(struct i2c_client));
1266
1267                 ir->c_rx.addr = 0x71;
1268                 strlcpy(ir->c_rx.name, ZILOG_HAUPPAUGE_IR_RX_NAME,
1269                         I2C_NAME_SIZE);
1270
1271                 /* try to fire up polling thread */
1272                 ir->t_notify = &tn;
1273                 ir->task = kthread_run(lirc_thread, ir, "lirc_zilog");
1274                 if (IS_ERR(ir->task)) {
1275                         ret = PTR_ERR(ir->task);
1276                         zilog_error("lirc_register_driver: cannot run "
1277                                     "poll thread %d\n", ret);
1278                         goto err;
1279                 }
1280                 wait_for_completion(&tn);
1281                 ir->t_notify = NULL;
1282                 ir->have_rx = 1;
1283         }
1284
1285         /* initialise TX device */
1286         if (have_tx) {
1287                 memcpy(&ir->c_tx, client, sizeof(struct i2c_client));
1288                 ir->c_tx.addr = 0x70;
1289                 strlcpy(ir->c_tx.name, ZILOG_HAUPPAUGE_IR_TX_NAME,
1290                         I2C_NAME_SIZE);
1291                 ir->have_tx = 1;
1292         }
1293
1294         /* set lirc_dev stuff */
1295         ir->l.code_length = 13;
1296         ir->l.rbuf        = &ir->buf;
1297         ir->l.fops        = &lirc_fops;
1298         ir->l.data        = ir;
1299         ir->l.minor       = minor;
1300         ir->l.dev         = &adap->dev;
1301         ir->l.sample_rate = 0;
1302
1303         /* register with lirc */
1304         ir->l.minor = lirc_register_driver(&ir->l);
1305         if (ir->l.minor < 0 || ir->l.minor >= MAX_IRCTL_DEVICES) {
1306                 zilog_error("ir_attach: \"minor\" must be between 0 and %d "
1307                             "(%d)!\n", MAX_IRCTL_DEVICES-1, ir->l.minor);
1308                 ret = -EBADRQC;
1309                 goto err;
1310         }
1311
1312         /* store this for getting back in open() later on */
1313         ir_devices[ir->l.minor] = ir;
1314
1315         /*
1316          * if we have the tx device, load the 'firmware'.  We do this
1317          * after registering with lirc as otherwise hotplug seems to take
1318          * 10s to create the lirc device.
1319          */
1320         if (have_tx) {
1321                 /* Special TX init */
1322                 ret = tx_init(ir);
1323                 if (ret != 0)
1324                         goto err;
1325         }
1326
1327         return 0;
1328
1329 err:
1330         /* undo everything, hopefully... */
1331         if (ir->c_rx.addr)
1332                 ir_remove(&ir->c_rx);
1333         if (ir->c_tx.addr)
1334                 ir_remove(&ir->c_tx);
1335         return ret;
1336
1337 out_nodev:
1338         zilog_error("no device found\n");
1339         return -ENODEV;
1340
1341 out_nomem:
1342         zilog_error("memory allocation failure\n");
1343         kfree(ir);
1344         return -ENOMEM;
1345 }
1346
1347 static int ir_command(struct i2c_client *client, unsigned int cmd, void *arg)
1348 {
1349         /* nothing */
1350         return 0;
1351 }
1352
1353 static int __init zilog_init(void)
1354 {
1355         int ret;
1356
1357         zilog_notify("Zilog/Hauppauge IR driver initializing\n");
1358
1359         mutex_init(&tx_data_lock);
1360
1361         request_module("firmware_class");
1362
1363         ret = i2c_add_driver(&driver);
1364         if (ret)
1365                 zilog_error("initialization failed\n");
1366         else
1367                 zilog_notify("initialization complete\n");
1368
1369         return ret;
1370 }
1371
1372 static void __exit zilog_exit(void)
1373 {
1374         i2c_del_driver(&driver);
1375         /* if loaded */
1376         fw_unload();
1377         zilog_notify("Zilog/Hauppauge IR driver unloaded\n");
1378 }
1379
1380 module_init(zilog_init);
1381 module_exit(zilog_exit);
1382
1383 MODULE_DESCRIPTION("Zilog/Hauppauge infrared transmitter driver (i2c stack)");
1384 MODULE_AUTHOR("Gerd Knorr, Michal Kochanowicz, Christoph Bartelmus, "
1385               "Ulrich Mueller, Stefan Jahn, Jerome Brock, Mark Weaver");
1386 MODULE_LICENSE("GPL");
1387 /* for compat with old name, which isn't all that accurate anymore */
1388 MODULE_ALIAS("lirc_pvr150");
1389
1390 module_param(minor, int, 0444);
1391 MODULE_PARM_DESC(minor, "Preferred minor device number");
1392
1393 module_param(debug, bool, 0644);
1394 MODULE_PARM_DESC(debug, "Enable debugging messages");
1395
1396 module_param(disable_rx, bool, 0644);
1397 MODULE_PARM_DESC(disable_rx, "Disable the IR receiver device");