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