Merge branch 'gpio/merge' of git://git.secretlab.ca/git/linux-2.6
[pandora-kernel.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  * Numerous changes updating lirc_zilog.c in kernel 2.6.38 and later are
24  * Copyright (C) 2011 Andy Walls <awalls@md.metrocast.net>
25  *
26  *  This program is free software; you can redistribute it and/or modify
27  *  it under the terms of the GNU General Public License as published by
28  *  the Free Software Foundation; either version 2 of the License, or
29  *  (at your option) any later version.
30  *
31  *  This program is distributed in the hope that it will be useful,
32  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
33  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
34  *  GNU General Public License for more details.
35  *
36  *  You should have received a copy of the GNU General Public License
37  *  along with this program; if not, write to the Free Software
38  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
39  *
40  */
41
42
43 #include <linux/version.h>
44 #include <linux/module.h>
45 #include <linux/kmod.h>
46 #include <linux/kernel.h>
47 #include <linux/sched.h>
48 #include <linux/fs.h>
49 #include <linux/poll.h>
50 #include <linux/string.h>
51 #include <linux/timer.h>
52 #include <linux/delay.h>
53 #include <linux/completion.h>
54 #include <linux/errno.h>
55 #include <linux/slab.h>
56 #include <linux/i2c.h>
57 #include <linux/firmware.h>
58 #include <linux/vmalloc.h>
59
60 #include <linux/mutex.h>
61 #include <linux/kthread.h>
62
63 #include <media/lirc_dev.h>
64 #include <media/lirc.h>
65
66 struct IR;
67
68 struct IR_rx {
69         struct kref ref;
70         struct IR *ir;
71
72         /* RX device */
73         struct mutex client_lock;
74         struct i2c_client *c;
75
76         /* RX polling thread data */
77         struct task_struct *task;
78
79         /* RX read data */
80         unsigned char b[3];
81         bool hdpvr_data_fmt;
82 };
83
84 struct IR_tx {
85         struct kref ref;
86         struct IR *ir;
87
88         /* TX device */
89         struct mutex client_lock;
90         struct i2c_client *c;
91
92         /* TX additional actions needed */
93         int need_boot;
94         bool post_tx_ready_poll;
95 };
96
97 struct IR {
98         struct kref ref;
99         struct list_head list;
100
101         /* FIXME spinlock access to l.features */
102         struct lirc_driver l;
103         struct lirc_buffer rbuf;
104
105         struct mutex ir_lock;
106         atomic_t open_count;
107
108         struct i2c_adapter *adapter;
109
110         spinlock_t rx_ref_lock; /* struct IR_rx kref get()/put() */
111         struct IR_rx *rx;
112
113         spinlock_t tx_ref_lock; /* struct IR_tx kref get()/put() */
114         struct IR_tx *tx;
115 };
116
117 /* IR transceiver instance object list */
118 /*
119  * This lock is used for the following:
120  * a. ir_devices_list access, insertions, deletions
121  * b. struct IR kref get()s and put()s
122  * c. serialization of ir_probe() for the two i2c_clients for a Z8
123  */
124 static DEFINE_MUTEX(ir_devices_lock);
125 static LIST_HEAD(ir_devices_list);
126
127 /* Block size for IR transmitter */
128 #define TX_BLOCK_SIZE   99
129
130 /* Hauppauge IR transmitter data */
131 struct tx_data_struct {
132         /* Boot block */
133         unsigned char *boot_data;
134
135         /* Start of binary data block */
136         unsigned char *datap;
137
138         /* End of binary data block */
139         unsigned char *endp;
140
141         /* Number of installed codesets */
142         unsigned int num_code_sets;
143
144         /* Pointers to codesets */
145         unsigned char **code_sets;
146
147         /* Global fixed data template */
148         int fixed[TX_BLOCK_SIZE];
149 };
150
151 static struct tx_data_struct *tx_data;
152 static struct mutex tx_data_lock;
153
154 #define zilog_notify(s, args...) printk(KERN_NOTICE KBUILD_MODNAME ": " s, \
155                                         ## args)
156 #define zilog_error(s, args...) printk(KERN_ERR KBUILD_MODNAME ": " s, ## args)
157 #define zilog_info(s, args...) printk(KERN_INFO KBUILD_MODNAME ": " s, ## args)
158
159 /* module parameters */
160 static int debug;       /* debug output */
161 static int tx_only;     /* only handle the IR Tx function */
162 static int minor = -1;  /* minor number */
163
164 #define dprintk(fmt, args...)                                           \
165         do {                                                            \
166                 if (debug)                                              \
167                         printk(KERN_DEBUG KBUILD_MODNAME ": " fmt,      \
168                                  ## args);                              \
169         } while (0)
170
171
172 /* struct IR reference counting */
173 static struct IR *get_ir_device(struct IR *ir, bool ir_devices_lock_held)
174 {
175         if (ir_devices_lock_held) {
176                 kref_get(&ir->ref);
177         } else {
178                 mutex_lock(&ir_devices_lock);
179                 kref_get(&ir->ref);
180                 mutex_unlock(&ir_devices_lock);
181         }
182         return ir;
183 }
184
185 static void release_ir_device(struct kref *ref)
186 {
187         struct IR *ir = container_of(ref, struct IR, ref);
188
189         /*
190          * Things should be in this state by now:
191          * ir->rx set to NULL and deallocated - happens before ir->rx->ir put()
192          * ir->rx->task kthread stopped - happens before ir->rx->ir put()
193          * ir->tx set to NULL and deallocated - happens before ir->tx->ir put()
194          * ir->open_count ==  0 - happens on final close()
195          * ir_lock, tx_ref_lock, rx_ref_lock, all released
196          */
197         if (ir->l.minor >= 0 && ir->l.minor < MAX_IRCTL_DEVICES) {
198                 lirc_unregister_driver(ir->l.minor);
199                 ir->l.minor = MAX_IRCTL_DEVICES;
200         }
201         if (ir->rbuf.fifo_initialized)
202                 lirc_buffer_free(&ir->rbuf);
203         list_del(&ir->list);
204         kfree(ir);
205 }
206
207 static int put_ir_device(struct IR *ir, bool ir_devices_lock_held)
208 {
209         int released;
210
211         if (ir_devices_lock_held)
212                 return kref_put(&ir->ref, release_ir_device);
213
214         mutex_lock(&ir_devices_lock);
215         released = kref_put(&ir->ref, release_ir_device);
216         mutex_unlock(&ir_devices_lock);
217
218         return released;
219 }
220
221 /* struct IR_rx reference counting */
222 static struct IR_rx *get_ir_rx(struct IR *ir)
223 {
224         struct IR_rx *rx;
225
226         spin_lock(&ir->rx_ref_lock);
227         rx = ir->rx;
228         if (rx != NULL)
229                 kref_get(&rx->ref);
230         spin_unlock(&ir->rx_ref_lock);
231         return rx;
232 }
233
234 static void destroy_rx_kthread(struct IR_rx *rx, bool ir_devices_lock_held)
235 {
236         /* end up polling thread */
237         if (!IS_ERR_OR_NULL(rx->task)) {
238                 kthread_stop(rx->task);
239                 rx->task = NULL;
240                 /* Put the ir ptr that ir_probe() gave to the rx poll thread */
241                 put_ir_device(rx->ir, ir_devices_lock_held);
242         }
243 }
244
245 static void release_ir_rx(struct kref *ref)
246 {
247         struct IR_rx *rx = container_of(ref, struct IR_rx, ref);
248         struct IR *ir = rx->ir;
249
250         /*
251          * This release function can't do all the work, as we want
252          * to keep the rx_ref_lock a spinlock, and killing the poll thread
253          * and releasing the ir reference can cause a sleep.  That work is
254          * performed by put_ir_rx()
255          */
256         ir->l.features &= ~LIRC_CAN_REC_LIRCCODE;
257         /* Don't put_ir_device(rx->ir) here; lock can't be freed yet */
258         ir->rx = NULL;
259         /* Don't do the kfree(rx) here; we still need to kill the poll thread */
260         return;
261 }
262
263 static int put_ir_rx(struct IR_rx *rx, bool ir_devices_lock_held)
264 {
265         int released;
266         struct IR *ir = rx->ir;
267
268         spin_lock(&ir->rx_ref_lock);
269         released = kref_put(&rx->ref, release_ir_rx);
270         spin_unlock(&ir->rx_ref_lock);
271         /* Destroy the rx kthread while not holding the spinlock */
272         if (released) {
273                 destroy_rx_kthread(rx, ir_devices_lock_held);
274                 kfree(rx);
275                 /* Make sure we're not still in a poll_table somewhere */
276                 wake_up_interruptible(&ir->rbuf.wait_poll);
277         }
278         /* Do a reference put() for the rx->ir reference, if we released rx */
279         if (released)
280                 put_ir_device(ir, ir_devices_lock_held);
281         return released;
282 }
283
284 /* struct IR_tx reference counting */
285 static struct IR_tx *get_ir_tx(struct IR *ir)
286 {
287         struct IR_tx *tx;
288
289         spin_lock(&ir->tx_ref_lock);
290         tx = ir->tx;
291         if (tx != NULL)
292                 kref_get(&tx->ref);
293         spin_unlock(&ir->tx_ref_lock);
294         return tx;
295 }
296
297 static void release_ir_tx(struct kref *ref)
298 {
299         struct IR_tx *tx = container_of(ref, struct IR_tx, ref);
300         struct IR *ir = tx->ir;
301
302         ir->l.features &= ~LIRC_CAN_SEND_PULSE;
303         /* Don't put_ir_device(tx->ir) here, so our lock doesn't get freed */
304         ir->tx = NULL;
305         kfree(tx);
306 }
307
308 static int put_ir_tx(struct IR_tx *tx, bool ir_devices_lock_held)
309 {
310         int released;
311         struct IR *ir = tx->ir;
312
313         spin_lock(&ir->tx_ref_lock);
314         released = kref_put(&tx->ref, release_ir_tx);
315         spin_unlock(&ir->tx_ref_lock);
316         /* Do a reference put() for the tx->ir reference, if we released tx */
317         if (released)
318                 put_ir_device(ir, ir_devices_lock_held);
319         return released;
320 }
321
322 static int add_to_buf(struct IR *ir)
323 {
324         __u16 code;
325         unsigned char codes[2];
326         unsigned char keybuf[6];
327         int got_data = 0;
328         int ret;
329         int failures = 0;
330         unsigned char sendbuf[1] = { 0 };
331         struct lirc_buffer *rbuf = ir->l.rbuf;
332         struct IR_rx *rx;
333         struct IR_tx *tx;
334
335         if (lirc_buffer_full(rbuf)) {
336                 dprintk("buffer overflow\n");
337                 return -EOVERFLOW;
338         }
339
340         rx = get_ir_rx(ir);
341         if (rx == NULL)
342                 return -ENXIO;
343
344         /* Ensure our rx->c i2c_client remains valid for the duration */
345         mutex_lock(&rx->client_lock);
346         if (rx->c == NULL) {
347                 mutex_unlock(&rx->client_lock);
348                 put_ir_rx(rx, false);
349                 return -ENXIO;
350         }
351
352         tx = get_ir_tx(ir);
353
354         /*
355          * service the device as long as it is returning
356          * data and we have space
357          */
358         do {
359                 if (kthread_should_stop()) {
360                         ret = -ENODATA;
361                         break;
362                 }
363
364                 /*
365                  * Lock i2c bus for the duration.  RX/TX chips interfere so
366                  * this is worth it
367                  */
368                 mutex_lock(&ir->ir_lock);
369
370                 if (kthread_should_stop()) {
371                         mutex_unlock(&ir->ir_lock);
372                         ret = -ENODATA;
373                         break;
374                 }
375
376                 /*
377                  * Send random "poll command" (?)  Windows driver does this
378                  * and it is a good point to detect chip failure.
379                  */
380                 ret = i2c_master_send(rx->c, sendbuf, 1);
381                 if (ret != 1) {
382                         zilog_error("i2c_master_send failed with %d\n", ret);
383                         if (failures >= 3) {
384                                 mutex_unlock(&ir->ir_lock);
385                                 zilog_error("unable to read from the IR chip "
386                                             "after 3 resets, giving up\n");
387                                 break;
388                         }
389
390                         /* Looks like the chip crashed, reset it */
391                         zilog_error("polling the IR receiver chip failed, "
392                                     "trying reset\n");
393
394                         set_current_state(TASK_UNINTERRUPTIBLE);
395                         if (kthread_should_stop()) {
396                                 mutex_unlock(&ir->ir_lock);
397                                 ret = -ENODATA;
398                                 break;
399                         }
400                         schedule_timeout((100 * HZ + 999) / 1000);
401                         if (tx != NULL)
402                                 tx->need_boot = 1;
403
404                         ++failures;
405                         mutex_unlock(&ir->ir_lock);
406                         ret = 0;
407                         continue;
408                 }
409
410                 if (kthread_should_stop()) {
411                         mutex_unlock(&ir->ir_lock);
412                         ret = -ENODATA;
413                         break;
414                 }
415                 ret = i2c_master_recv(rx->c, keybuf, sizeof(keybuf));
416                 mutex_unlock(&ir->ir_lock);
417                 if (ret != sizeof(keybuf)) {
418                         zilog_error("i2c_master_recv failed with %d -- "
419                                     "keeping last read buffer\n", ret);
420                 } else {
421                         rx->b[0] = keybuf[3];
422                         rx->b[1] = keybuf[4];
423                         rx->b[2] = keybuf[5];
424                         dprintk("key (0x%02x/0x%02x)\n", rx->b[0], rx->b[1]);
425                 }
426
427                 /* key pressed ? */
428                 if (rx->hdpvr_data_fmt) {
429                         if (got_data && (keybuf[0] == 0x80)) {
430                                 ret = 0;
431                                 break;
432                         } else if (got_data && (keybuf[0] == 0x00)) {
433                                 ret = -ENODATA;
434                                 break;
435                         }
436                 } else if ((rx->b[0] & 0x80) == 0) {
437                         ret = got_data ? 0 : -ENODATA;
438                         break;
439                 }
440
441                 /* look what we have */
442                 code = (((__u16)rx->b[0] & 0x7f) << 6) | (rx->b[1] >> 2);
443
444                 codes[0] = (code >> 8) & 0xff;
445                 codes[1] = code & 0xff;
446
447                 /* return it */
448                 lirc_buffer_write(rbuf, codes);
449                 ++got_data;
450                 ret = 0;
451         } while (!lirc_buffer_full(rbuf));
452
453         mutex_unlock(&rx->client_lock);
454         if (tx != NULL)
455                 put_ir_tx(tx, false);
456         put_ir_rx(rx, false);
457         return ret;
458 }
459
460 /*
461  * Main function of the polling thread -- from lirc_dev.
462  * We don't fit the LIRC model at all anymore.  This is horrible, but
463  * basically we have a single RX/TX device with a nasty failure mode
464  * that needs to be accounted for across the pair.  lirc lets us provide
465  * fops, but prevents us from using the internal polling, etc. if we do
466  * so.  Hence the replication.  Might be neater to extend the LIRC model
467  * to account for this but I'd think it's a very special case of seriously
468  * messed up hardware.
469  */
470 static int lirc_thread(void *arg)
471 {
472         struct IR *ir = arg;
473         struct lirc_buffer *rbuf = ir->l.rbuf;
474
475         dprintk("poll thread started\n");
476
477         while (!kthread_should_stop()) {
478                 set_current_state(TASK_INTERRUPTIBLE);
479
480                 /* if device not opened, we can sleep half a second */
481                 if (atomic_read(&ir->open_count) == 0) {
482                         schedule_timeout(HZ/2);
483                         continue;
484                 }
485
486                 /*
487                  * This is ~113*2 + 24 + jitter (2*repeat gap + code length).
488                  * We use this interval as the chip resets every time you poll
489                  * it (bad!).  This is therefore just sufficient to catch all
490                  * of the button presses.  It makes the remote much more
491                  * responsive.  You can see the difference by running irw and
492                  * holding down a button.  With 100ms, the old polling
493                  * interval, you'll notice breaks in the repeat sequence
494                  * corresponding to lost keypresses.
495                  */
496                 schedule_timeout((260 * HZ) / 1000);
497                 if (kthread_should_stop())
498                         break;
499                 if (!add_to_buf(ir))
500                         wake_up_interruptible(&rbuf->wait_poll);
501         }
502
503         dprintk("poll thread ended\n");
504         return 0;
505 }
506
507 static int set_use_inc(void *data)
508 {
509         return 0;
510 }
511
512 static void set_use_dec(void *data)
513 {
514         return;
515 }
516
517 /* safe read of a uint32 (always network byte order) */
518 static int read_uint32(unsigned char **data,
519                                      unsigned char *endp, unsigned int *val)
520 {
521         if (*data + 4 > endp)
522                 return 0;
523         *val = ((*data)[0] << 24) | ((*data)[1] << 16) |
524                ((*data)[2] << 8) | (*data)[3];
525         *data += 4;
526         return 1;
527 }
528
529 /* safe read of a uint8 */
530 static int read_uint8(unsigned char **data,
531                                     unsigned char *endp, unsigned char *val)
532 {
533         if (*data + 1 > endp)
534                 return 0;
535         *val = *((*data)++);
536         return 1;
537 }
538
539 /* safe skipping of N bytes */
540 static int skip(unsigned char **data,
541                               unsigned char *endp, unsigned int distance)
542 {
543         if (*data + distance > endp)
544                 return 0;
545         *data += distance;
546         return 1;
547 }
548
549 /* decompress key data into the given buffer */
550 static int get_key_data(unsigned char *buf,
551                              unsigned int codeset, unsigned int key)
552 {
553         unsigned char *data, *endp, *diffs, *key_block;
554         unsigned char keys, ndiffs, id;
555         unsigned int base, lim, pos, i;
556
557         /* Binary search for the codeset */
558         for (base = 0, lim = tx_data->num_code_sets; lim; lim >>= 1) {
559                 pos = base + (lim >> 1);
560                 data = tx_data->code_sets[pos];
561
562                 if (!read_uint32(&data, tx_data->endp, &i))
563                         goto corrupt;
564
565                 if (i == codeset)
566                         break;
567                 else if (codeset > i) {
568                         base = pos + 1;
569                         --lim;
570                 }
571         }
572         /* Not found? */
573         if (!lim)
574                 return -EPROTO;
575
576         /* Set end of data block */
577         endp = pos < tx_data->num_code_sets - 1 ?
578                 tx_data->code_sets[pos + 1] : tx_data->endp;
579
580         /* Read the block header */
581         if (!read_uint8(&data, endp, &keys) ||
582             !read_uint8(&data, endp, &ndiffs) ||
583             ndiffs > TX_BLOCK_SIZE || keys == 0)
584                 goto corrupt;
585
586         /* Save diffs & skip */
587         diffs = data;
588         if (!skip(&data, endp, ndiffs))
589                 goto corrupt;
590
591         /* Read the id of the first key */
592         if (!read_uint8(&data, endp, &id))
593                 goto corrupt;
594
595         /* Unpack the first key's data */
596         for (i = 0; i < TX_BLOCK_SIZE; ++i) {
597                 if (tx_data->fixed[i] == -1) {
598                         if (!read_uint8(&data, endp, &buf[i]))
599                                 goto corrupt;
600                 } else {
601                         buf[i] = (unsigned char)tx_data->fixed[i];
602                 }
603         }
604
605         /* Early out key found/not found */
606         if (key == id)
607                 return 0;
608         if (keys == 1)
609                 return -EPROTO;
610
611         /* Sanity check */
612         key_block = data;
613         if (!skip(&data, endp, (keys - 1) * (ndiffs + 1)))
614                 goto corrupt;
615
616         /* Binary search for the key */
617         for (base = 0, lim = keys - 1; lim; lim >>= 1) {
618                 /* Seek to block */
619                 unsigned char *key_data;
620                 pos = base + (lim >> 1);
621                 key_data = key_block + (ndiffs + 1) * pos;
622
623                 if (*key_data == key) {
624                         /* skip key id */
625                         ++key_data;
626
627                         /* found, so unpack the diffs */
628                         for (i = 0; i < ndiffs; ++i) {
629                                 unsigned char val;
630                                 if (!read_uint8(&key_data, endp, &val) ||
631                                     diffs[i] >= TX_BLOCK_SIZE)
632                                         goto corrupt;
633                                 buf[diffs[i]] = val;
634                         }
635
636                         return 0;
637                 } else if (key > *key_data) {
638                         base = pos + 1;
639                         --lim;
640                 }
641         }
642         /* Key not found */
643         return -EPROTO;
644
645 corrupt:
646         zilog_error("firmware is corrupt\n");
647         return -EFAULT;
648 }
649
650 /* send a block of data to the IR TX device */
651 static int send_data_block(struct IR_tx *tx, unsigned char *data_block)
652 {
653         int i, j, ret;
654         unsigned char buf[5];
655
656         for (i = 0; i < TX_BLOCK_SIZE;) {
657                 int tosend = TX_BLOCK_SIZE - i;
658                 if (tosend > 4)
659                         tosend = 4;
660                 buf[0] = (unsigned char)(i + 1);
661                 for (j = 0; j < tosend; ++j)
662                         buf[1 + j] = data_block[i + j];
663                 dprintk("%02x %02x %02x %02x %02x",
664                         buf[0], buf[1], buf[2], buf[3], buf[4]);
665                 ret = i2c_master_send(tx->c, buf, tosend + 1);
666                 if (ret != tosend + 1) {
667                         zilog_error("i2c_master_send failed with %d\n", ret);
668                         return ret < 0 ? ret : -EFAULT;
669                 }
670                 i += tosend;
671         }
672         return 0;
673 }
674
675 /* send boot data to the IR TX device */
676 static int send_boot_data(struct IR_tx *tx)
677 {
678         int ret, i;
679         unsigned char buf[4];
680
681         /* send the boot block */
682         ret = send_data_block(tx, tx_data->boot_data);
683         if (ret != 0)
684                 return ret;
685
686         /* Hit the go button to activate the new boot data */
687         buf[0] = 0x00;
688         buf[1] = 0x20;
689         ret = i2c_master_send(tx->c, buf, 2);
690         if (ret != 2) {
691                 zilog_error("i2c_master_send failed with %d\n", ret);
692                 return ret < 0 ? ret : -EFAULT;
693         }
694
695         /*
696          * Wait for zilog to settle after hitting go post boot block upload.
697          * Without this delay, the HD-PVR and HVR-1950 both return an -EIO
698          * upon attempting to get firmware revision, and tx probe thus fails.
699          */
700         for (i = 0; i < 10; i++) {
701                 ret = i2c_master_send(tx->c, buf, 1);
702                 if (ret == 1)
703                         break;
704                 udelay(100);
705         }
706
707         if (ret != 1) {
708                 zilog_error("i2c_master_send failed with %d\n", ret);
709                 return ret < 0 ? ret : -EFAULT;
710         }
711
712         /* Here comes the firmware version... (hopefully) */
713         ret = i2c_master_recv(tx->c, buf, 4);
714         if (ret != 4) {
715                 zilog_error("i2c_master_recv failed with %d\n", ret);
716                 return 0;
717         }
718         if ((buf[0] != 0x80) && (buf[0] != 0xa0)) {
719                 zilog_error("unexpected IR TX init response: %02x\n", buf[0]);
720                 return 0;
721         }
722         zilog_notify("Zilog/Hauppauge IR blaster firmware version "
723                      "%d.%d.%d loaded\n", buf[1], buf[2], buf[3]);
724
725         return 0;
726 }
727
728 /* unload "firmware", lock held */
729 static void fw_unload_locked(void)
730 {
731         if (tx_data) {
732                 if (tx_data->code_sets)
733                         vfree(tx_data->code_sets);
734
735                 if (tx_data->datap)
736                         vfree(tx_data->datap);
737
738                 vfree(tx_data);
739                 tx_data = NULL;
740                 dprintk("successfully unloaded IR blaster firmware\n");
741         }
742 }
743
744 /* unload "firmware" for the IR TX device */
745 static void fw_unload(void)
746 {
747         mutex_lock(&tx_data_lock);
748         fw_unload_locked();
749         mutex_unlock(&tx_data_lock);
750 }
751
752 /* load "firmware" for the IR TX device */
753 static int fw_load(struct IR_tx *tx)
754 {
755         int ret;
756         unsigned int i;
757         unsigned char *data, version, num_global_fixed;
758         const struct firmware *fw_entry;
759
760         /* Already loaded? */
761         mutex_lock(&tx_data_lock);
762         if (tx_data) {
763                 ret = 0;
764                 goto out;
765         }
766
767         /* Request codeset data file */
768         ret = request_firmware(&fw_entry, "haup-ir-blaster.bin", tx->ir->l.dev);
769         if (ret != 0) {
770                 zilog_error("firmware haup-ir-blaster.bin not available "
771                             "(%d)\n", ret);
772                 ret = ret < 0 ? ret : -EFAULT;
773                 goto out;
774         }
775         dprintk("firmware of size %zu loaded\n", fw_entry->size);
776
777         /* Parse the file */
778         tx_data = vmalloc(sizeof(*tx_data));
779         if (tx_data == NULL) {
780                 zilog_error("out of memory\n");
781                 release_firmware(fw_entry);
782                 ret = -ENOMEM;
783                 goto out;
784         }
785         tx_data->code_sets = NULL;
786
787         /* Copy the data so hotplug doesn't get confused and timeout */
788         tx_data->datap = vmalloc(fw_entry->size);
789         if (tx_data->datap == NULL) {
790                 zilog_error("out of memory\n");
791                 release_firmware(fw_entry);
792                 vfree(tx_data);
793                 ret = -ENOMEM;
794                 goto out;
795         }
796         memcpy(tx_data->datap, fw_entry->data, fw_entry->size);
797         tx_data->endp = tx_data->datap + fw_entry->size;
798         release_firmware(fw_entry); fw_entry = NULL;
799
800         /* Check version */
801         data = tx_data->datap;
802         if (!read_uint8(&data, tx_data->endp, &version))
803                 goto corrupt;
804         if (version != 1) {
805                 zilog_error("unsupported code set file version (%u, expected"
806                             "1) -- please upgrade to a newer driver",
807                             version);
808                 fw_unload_locked();
809                 ret = -EFAULT;
810                 goto out;
811         }
812
813         /* Save boot block for later */
814         tx_data->boot_data = data;
815         if (!skip(&data, tx_data->endp, TX_BLOCK_SIZE))
816                 goto corrupt;
817
818         if (!read_uint32(&data, tx_data->endp,
819                               &tx_data->num_code_sets))
820                 goto corrupt;
821
822         dprintk("%u IR blaster codesets loaded\n", tx_data->num_code_sets);
823
824         tx_data->code_sets = vmalloc(
825                 tx_data->num_code_sets * sizeof(char *));
826         if (tx_data->code_sets == NULL) {
827                 fw_unload_locked();
828                 ret = -ENOMEM;
829                 goto out;
830         }
831
832         for (i = 0; i < TX_BLOCK_SIZE; ++i)
833                 tx_data->fixed[i] = -1;
834
835         /* Read global fixed data template */
836         if (!read_uint8(&data, tx_data->endp, &num_global_fixed) ||
837             num_global_fixed > TX_BLOCK_SIZE)
838                 goto corrupt;
839         for (i = 0; i < num_global_fixed; ++i) {
840                 unsigned char pos, val;
841                 if (!read_uint8(&data, tx_data->endp, &pos) ||
842                     !read_uint8(&data, tx_data->endp, &val) ||
843                     pos >= TX_BLOCK_SIZE)
844                         goto corrupt;
845                 tx_data->fixed[pos] = (int)val;
846         }
847
848         /* Filch out the position of each code set */
849         for (i = 0; i < tx_data->num_code_sets; ++i) {
850                 unsigned int id;
851                 unsigned char keys;
852                 unsigned char ndiffs;
853
854                 /* Save the codeset position */
855                 tx_data->code_sets[i] = data;
856
857                 /* Read header */
858                 if (!read_uint32(&data, tx_data->endp, &id) ||
859                     !read_uint8(&data, tx_data->endp, &keys) ||
860                     !read_uint8(&data, tx_data->endp, &ndiffs) ||
861                     ndiffs > TX_BLOCK_SIZE || keys == 0)
862                         goto corrupt;
863
864                 /* skip diff positions */
865                 if (!skip(&data, tx_data->endp, ndiffs))
866                         goto corrupt;
867
868                 /*
869                  * After the diffs we have the first key id + data -
870                  * global fixed
871                  */
872                 if (!skip(&data, tx_data->endp,
873                                1 + TX_BLOCK_SIZE - num_global_fixed))
874                         goto corrupt;
875
876                 /* Then we have keys-1 blocks of key id+diffs */
877                 if (!skip(&data, tx_data->endp,
878                                (ndiffs + 1) * (keys - 1)))
879                         goto corrupt;
880         }
881         ret = 0;
882         goto out;
883
884 corrupt:
885         zilog_error("firmware is corrupt\n");
886         fw_unload_locked();
887         ret = -EFAULT;
888
889 out:
890         mutex_unlock(&tx_data_lock);
891         return ret;
892 }
893
894 /* copied from lirc_dev */
895 static ssize_t read(struct file *filep, char *outbuf, size_t n, loff_t *ppos)
896 {
897         struct IR *ir = filep->private_data;
898         struct IR_rx *rx;
899         struct lirc_buffer *rbuf = ir->l.rbuf;
900         int ret = 0, written = 0, retries = 0;
901         unsigned int m;
902         DECLARE_WAITQUEUE(wait, current);
903
904         dprintk("read called\n");
905         if (n % rbuf->chunk_size) {
906                 dprintk("read result = -EINVAL\n");
907                 return -EINVAL;
908         }
909
910         rx = get_ir_rx(ir);
911         if (rx == NULL)
912                 return -ENXIO;
913
914         /*
915          * we add ourselves to the task queue before buffer check
916          * to avoid losing scan code (in case when queue is awaken somewhere
917          * between while condition checking and scheduling)
918          */
919         add_wait_queue(&rbuf->wait_poll, &wait);
920         set_current_state(TASK_INTERRUPTIBLE);
921
922         /*
923          * while we didn't provide 'length' bytes, device is opened in blocking
924          * mode and 'copy_to_user' is happy, wait for data.
925          */
926         while (written < n && ret == 0) {
927                 if (lirc_buffer_empty(rbuf)) {
928                         /*
929                          * According to the read(2) man page, 'written' can be
930                          * returned as less than 'n', instead of blocking
931                          * again, returning -EWOULDBLOCK, or returning
932                          * -ERESTARTSYS
933                          */
934                         if (written)
935                                 break;
936                         if (filep->f_flags & O_NONBLOCK) {
937                                 ret = -EWOULDBLOCK;
938                                 break;
939                         }
940                         if (signal_pending(current)) {
941                                 ret = -ERESTARTSYS;
942                                 break;
943                         }
944                         schedule();
945                         set_current_state(TASK_INTERRUPTIBLE);
946                 } else {
947                         unsigned char buf[rbuf->chunk_size];
948                         m = lirc_buffer_read(rbuf, buf);
949                         if (m == rbuf->chunk_size) {
950                                 ret = copy_to_user((void *)outbuf+written, buf,
951                                                    rbuf->chunk_size);
952                                 written += rbuf->chunk_size;
953                         } else {
954                                 retries++;
955                         }
956                         if (retries >= 5) {
957                                 zilog_error("Buffer read failed!\n");
958                                 ret = -EIO;
959                         }
960                 }
961         }
962
963         remove_wait_queue(&rbuf->wait_poll, &wait);
964         put_ir_rx(rx, false);
965         set_current_state(TASK_RUNNING);
966
967         dprintk("read result = %d (%s)\n", ret, ret ? "Error" : "OK");
968
969         return ret ? ret : written;
970 }
971
972 /* send a keypress to the IR TX device */
973 static int send_code(struct IR_tx *tx, unsigned int code, unsigned int key)
974 {
975         unsigned char data_block[TX_BLOCK_SIZE];
976         unsigned char buf[2];
977         int i, ret;
978
979         /* Get data for the codeset/key */
980         ret = get_key_data(data_block, code, key);
981
982         if (ret == -EPROTO) {
983                 zilog_error("failed to get data for code %u, key %u -- check "
984                             "lircd.conf entries\n", code, key);
985                 return ret;
986         } else if (ret != 0)
987                 return ret;
988
989         /* Send the data block */
990         ret = send_data_block(tx, data_block);
991         if (ret != 0)
992                 return ret;
993
994         /* Send data block length? */
995         buf[0] = 0x00;
996         buf[1] = 0x40;
997         ret = i2c_master_send(tx->c, buf, 2);
998         if (ret != 2) {
999                 zilog_error("i2c_master_send failed with %d\n", ret);
1000                 return ret < 0 ? ret : -EFAULT;
1001         }
1002
1003         /* Give the z8 a moment to process data block */
1004         for (i = 0; i < 10; i++) {
1005                 ret = i2c_master_send(tx->c, buf, 1);
1006                 if (ret == 1)
1007                         break;
1008                 udelay(100);
1009         }
1010
1011         if (ret != 1) {
1012                 zilog_error("i2c_master_send failed with %d\n", ret);
1013                 return ret < 0 ? ret : -EFAULT;
1014         }
1015
1016         /* Send finished download? */
1017         ret = i2c_master_recv(tx->c, buf, 1);
1018         if (ret != 1) {
1019                 zilog_error("i2c_master_recv failed with %d\n", ret);
1020                 return ret < 0 ? ret : -EFAULT;
1021         }
1022         if (buf[0] != 0xA0) {
1023                 zilog_error("unexpected IR TX response #1: %02x\n",
1024                         buf[0]);
1025                 return -EFAULT;
1026         }
1027
1028         /* Send prepare command? */
1029         buf[0] = 0x00;
1030         buf[1] = 0x80;
1031         ret = i2c_master_send(tx->c, buf, 2);
1032         if (ret != 2) {
1033                 zilog_error("i2c_master_send failed with %d\n", ret);
1034                 return ret < 0 ? ret : -EFAULT;
1035         }
1036
1037         /*
1038          * The sleep bits aren't necessary on the HD PVR, and in fact, the
1039          * last i2c_master_recv always fails with a -5, so for now, we're
1040          * going to skip this whole mess and say we're done on the HD PVR
1041          */
1042         if (!tx->post_tx_ready_poll) {
1043                 dprintk("sent code %u, key %u\n", code, key);
1044                 return 0;
1045         }
1046
1047         /*
1048          * This bit NAKs until the device is ready, so we retry it
1049          * sleeping a bit each time.  This seems to be what the windows
1050          * driver does, approximately.
1051          * Try for up to 1s.
1052          */
1053         for (i = 0; i < 20; ++i) {
1054                 set_current_state(TASK_UNINTERRUPTIBLE);
1055                 schedule_timeout((50 * HZ + 999) / 1000);
1056                 ret = i2c_master_send(tx->c, buf, 1);
1057                 if (ret == 1)
1058                         break;
1059                 dprintk("NAK expected: i2c_master_send "
1060                         "failed with %d (try %d)\n", ret, i+1);
1061         }
1062         if (ret != 1) {
1063                 zilog_error("IR TX chip never got ready: last i2c_master_send "
1064                             "failed with %d\n", ret);
1065                 return ret < 0 ? ret : -EFAULT;
1066         }
1067
1068         /* Seems to be an 'ok' response */
1069         i = i2c_master_recv(tx->c, buf, 1);
1070         if (i != 1) {
1071                 zilog_error("i2c_master_recv failed with %d\n", ret);
1072                 return -EFAULT;
1073         }
1074         if (buf[0] != 0x80) {
1075                 zilog_error("unexpected IR TX response #2: %02x\n", buf[0]);
1076                 return -EFAULT;
1077         }
1078
1079         /* Oh good, it worked */
1080         dprintk("sent code %u, key %u\n", code, key);
1081         return 0;
1082 }
1083
1084 /*
1085  * Write a code to the device.  We take in a 32-bit number (an int) and then
1086  * decode this to a codeset/key index.  The key data is then decompressed and
1087  * sent to the device.  We have a spin lock as per i2c documentation to prevent
1088  * multiple concurrent sends which would probably cause the device to explode.
1089  */
1090 static ssize_t write(struct file *filep, const char *buf, size_t n,
1091                           loff_t *ppos)
1092 {
1093         struct IR *ir = filep->private_data;
1094         struct IR_tx *tx;
1095         size_t i;
1096         int failures = 0;
1097
1098         /* Validate user parameters */
1099         if (n % sizeof(int))
1100                 return -EINVAL;
1101
1102         /* Get a struct IR_tx reference */
1103         tx = get_ir_tx(ir);
1104         if (tx == NULL)
1105                 return -ENXIO;
1106
1107         /* Ensure our tx->c i2c_client remains valid for the duration */
1108         mutex_lock(&tx->client_lock);
1109         if (tx->c == NULL) {
1110                 mutex_unlock(&tx->client_lock);
1111                 put_ir_tx(tx, false);
1112                 return -ENXIO;
1113         }
1114
1115         /* Lock i2c bus for the duration */
1116         mutex_lock(&ir->ir_lock);
1117
1118         /* Send each keypress */
1119         for (i = 0; i < n;) {
1120                 int ret = 0;
1121                 int command;
1122
1123                 if (copy_from_user(&command, buf + i, sizeof(command))) {
1124                         mutex_unlock(&ir->ir_lock);
1125                         mutex_unlock(&tx->client_lock);
1126                         put_ir_tx(tx, false);
1127                         return -EFAULT;
1128                 }
1129
1130                 /* Send boot data first if required */
1131                 if (tx->need_boot == 1) {
1132                         /* Make sure we have the 'firmware' loaded, first */
1133                         ret = fw_load(tx);
1134                         if (ret != 0) {
1135                                 mutex_unlock(&ir->ir_lock);
1136                                 mutex_unlock(&tx->client_lock);
1137                                 put_ir_tx(tx, false);
1138                                 if (ret != -ENOMEM)
1139                                         ret = -EIO;
1140                                 return ret;
1141                         }
1142                         /* Prep the chip for transmitting codes */
1143                         ret = send_boot_data(tx);
1144                         if (ret == 0)
1145                                 tx->need_boot = 0;
1146                 }
1147
1148                 /* Send the code */
1149                 if (ret == 0) {
1150                         ret = send_code(tx, (unsigned)command >> 16,
1151                                             (unsigned)command & 0xFFFF);
1152                         if (ret == -EPROTO) {
1153                                 mutex_unlock(&ir->ir_lock);
1154                                 mutex_unlock(&tx->client_lock);
1155                                 put_ir_tx(tx, false);
1156                                 return ret;
1157                         }
1158                 }
1159
1160                 /*
1161                  * Hmm, a failure.  If we've had a few then give up, otherwise
1162                  * try a reset
1163                  */
1164                 if (ret != 0) {
1165                         /* Looks like the chip crashed, reset it */
1166                         zilog_error("sending to the IR transmitter chip "
1167                                     "failed, trying reset\n");
1168
1169                         if (failures >= 3) {
1170                                 zilog_error("unable to send to the IR chip "
1171                                             "after 3 resets, giving up\n");
1172                                 mutex_unlock(&ir->ir_lock);
1173                                 mutex_unlock(&tx->client_lock);
1174                                 put_ir_tx(tx, false);
1175                                 return ret;
1176                         }
1177                         set_current_state(TASK_UNINTERRUPTIBLE);
1178                         schedule_timeout((100 * HZ + 999) / 1000);
1179                         tx->need_boot = 1;
1180                         ++failures;
1181                 } else
1182                         i += sizeof(int);
1183         }
1184
1185         /* Release i2c bus */
1186         mutex_unlock(&ir->ir_lock);
1187
1188         mutex_unlock(&tx->client_lock);
1189
1190         /* Give back our struct IR_tx reference */
1191         put_ir_tx(tx, false);
1192
1193         /* All looks good */
1194         return n;
1195 }
1196
1197 /* copied from lirc_dev */
1198 static unsigned int poll(struct file *filep, poll_table *wait)
1199 {
1200         struct IR *ir = filep->private_data;
1201         struct IR_rx *rx;
1202         struct lirc_buffer *rbuf = ir->l.rbuf;
1203         unsigned int ret;
1204
1205         dprintk("poll called\n");
1206
1207         rx = get_ir_rx(ir);
1208         if (rx == NULL) {
1209                 /*
1210                  * Revisit this, if our poll function ever reports writeable
1211                  * status for Tx
1212                  */
1213                 dprintk("poll result = POLLERR\n");
1214                 return POLLERR;
1215         }
1216
1217         /*
1218          * Add our lirc_buffer's wait_queue to the poll_table. A wake up on
1219          * that buffer's wait queue indicates we may have a new poll status.
1220          */
1221         poll_wait(filep, &rbuf->wait_poll, wait);
1222
1223         /* Indicate what ops could happen immediately without blocking */
1224         ret = lirc_buffer_empty(rbuf) ? 0 : (POLLIN|POLLRDNORM);
1225
1226         dprintk("poll result = %s\n", ret ? "POLLIN|POLLRDNORM" : "none");
1227         return ret;
1228 }
1229
1230 static long ioctl(struct file *filep, unsigned int cmd, unsigned long arg)
1231 {
1232         struct IR *ir = filep->private_data;
1233         int result;
1234         unsigned long mode, features;
1235
1236         features = ir->l.features;
1237
1238         switch (cmd) {
1239         case LIRC_GET_LENGTH:
1240                 result = put_user((unsigned long)13,
1241                                   (unsigned long *)arg);
1242                 break;
1243         case LIRC_GET_FEATURES:
1244                 result = put_user(features, (unsigned long *) arg);
1245                 break;
1246         case LIRC_GET_REC_MODE:
1247                 if (!(features&LIRC_CAN_REC_MASK))
1248                         return -ENOSYS;
1249
1250                 result = put_user(LIRC_REC2MODE
1251                                   (features&LIRC_CAN_REC_MASK),
1252                                   (unsigned long *)arg);
1253                 break;
1254         case LIRC_SET_REC_MODE:
1255                 if (!(features&LIRC_CAN_REC_MASK))
1256                         return -ENOSYS;
1257
1258                 result = get_user(mode, (unsigned long *)arg);
1259                 if (!result && !(LIRC_MODE2REC(mode) & features))
1260                         result = -EINVAL;
1261                 break;
1262         case LIRC_GET_SEND_MODE:
1263                 if (!(features&LIRC_CAN_SEND_MASK))
1264                         return -ENOSYS;
1265
1266                 result = put_user(LIRC_MODE_PULSE, (unsigned long *) arg);
1267                 break;
1268         case LIRC_SET_SEND_MODE:
1269                 if (!(features&LIRC_CAN_SEND_MASK))
1270                         return -ENOSYS;
1271
1272                 result = get_user(mode, (unsigned long *) arg);
1273                 if (!result && mode != LIRC_MODE_PULSE)
1274                         return -EINVAL;
1275                 break;
1276         default:
1277                 return -EINVAL;
1278         }
1279         return result;
1280 }
1281
1282 static struct IR *get_ir_device_by_minor(unsigned int minor)
1283 {
1284         struct IR *ir;
1285         struct IR *ret = NULL;
1286
1287         mutex_lock(&ir_devices_lock);
1288
1289         if (!list_empty(&ir_devices_list)) {
1290                 list_for_each_entry(ir, &ir_devices_list, list) {
1291                         if (ir->l.minor == minor) {
1292                                 ret = get_ir_device(ir, true);
1293                                 break;
1294                         }
1295                 }
1296         }
1297
1298         mutex_unlock(&ir_devices_lock);
1299         return ret;
1300 }
1301
1302 /*
1303  * Open the IR device.  Get hold of our IR structure and
1304  * stash it in private_data for the file
1305  */
1306 static int open(struct inode *node, struct file *filep)
1307 {
1308         struct IR *ir;
1309         unsigned int minor = MINOR(node->i_rdev);
1310
1311         /* find our IR struct */
1312         ir = get_ir_device_by_minor(minor);
1313
1314         if (ir == NULL)
1315                 return -ENODEV;
1316
1317         atomic_inc(&ir->open_count);
1318
1319         /* stash our IR struct */
1320         filep->private_data = ir;
1321
1322         nonseekable_open(node, filep);
1323         return 0;
1324 }
1325
1326 /* Close the IR device */
1327 static int close(struct inode *node, struct file *filep)
1328 {
1329         /* find our IR struct */
1330         struct IR *ir = filep->private_data;
1331         if (ir == NULL) {
1332                 zilog_error("close: no private_data attached to the file!\n");
1333                 return -ENODEV;
1334         }
1335
1336         atomic_dec(&ir->open_count);
1337
1338         put_ir_device(ir, false);
1339         return 0;
1340 }
1341
1342 static int ir_remove(struct i2c_client *client);
1343 static int ir_probe(struct i2c_client *client, const struct i2c_device_id *id);
1344
1345 #define ID_FLAG_TX      0x01
1346 #define ID_FLAG_HDPVR   0x02
1347
1348 static const struct i2c_device_id ir_transceiver_id[] = {
1349         { "ir_tx_z8f0811_haup",  ID_FLAG_TX                 },
1350         { "ir_rx_z8f0811_haup",  0                          },
1351         { "ir_tx_z8f0811_hdpvr", ID_FLAG_HDPVR | ID_FLAG_TX },
1352         { "ir_rx_z8f0811_hdpvr", ID_FLAG_HDPVR              },
1353         { }
1354 };
1355
1356 static struct i2c_driver driver = {
1357         .driver = {
1358                 .owner  = THIS_MODULE,
1359                 .name   = "Zilog/Hauppauge i2c IR",
1360         },
1361         .probe          = ir_probe,
1362         .remove         = ir_remove,
1363         .id_table       = ir_transceiver_id,
1364 };
1365
1366 static const struct file_operations lirc_fops = {
1367         .owner          = THIS_MODULE,
1368         .llseek         = no_llseek,
1369         .read           = read,
1370         .write          = write,
1371         .poll           = poll,
1372         .unlocked_ioctl = ioctl,
1373 #ifdef CONFIG_COMPAT
1374         .compat_ioctl   = ioctl,
1375 #endif
1376         .open           = open,
1377         .release        = close
1378 };
1379
1380 static struct lirc_driver lirc_template = {
1381         .name           = "lirc_zilog",
1382         .minor          = -1,
1383         .code_length    = 13,
1384         .buffer_size    = BUFLEN / 2,
1385         .sample_rate    = 0, /* tell lirc_dev to not start its own kthread */
1386         .chunk_size     = 2,
1387         .set_use_inc    = set_use_inc,
1388         .set_use_dec    = set_use_dec,
1389         .fops           = &lirc_fops,
1390         .owner          = THIS_MODULE,
1391 };
1392
1393 static int ir_remove(struct i2c_client *client)
1394 {
1395         if (strncmp("ir_tx_z8", client->name, 8) == 0) {
1396                 struct IR_tx *tx = i2c_get_clientdata(client);
1397                 if (tx != NULL) {
1398                         mutex_lock(&tx->client_lock);
1399                         tx->c = NULL;
1400                         mutex_unlock(&tx->client_lock);
1401                         put_ir_tx(tx, false);
1402                 }
1403         } else if (strncmp("ir_rx_z8", client->name, 8) == 0) {
1404                 struct IR_rx *rx = i2c_get_clientdata(client);
1405                 if (rx != NULL) {
1406                         mutex_lock(&rx->client_lock);
1407                         rx->c = NULL;
1408                         mutex_unlock(&rx->client_lock);
1409                         put_ir_rx(rx, false);
1410                 }
1411         }
1412         return 0;
1413 }
1414
1415
1416 /* ir_devices_lock must be held */
1417 static struct IR *get_ir_device_by_adapter(struct i2c_adapter *adapter)
1418 {
1419         struct IR *ir;
1420
1421         if (list_empty(&ir_devices_list))
1422                 return NULL;
1423
1424         list_for_each_entry(ir, &ir_devices_list, list)
1425                 if (ir->adapter == adapter) {
1426                         get_ir_device(ir, true);
1427                         return ir;
1428                 }
1429
1430         return NULL;
1431 }
1432
1433 static int ir_probe(struct i2c_client *client, const struct i2c_device_id *id)
1434 {
1435         struct IR *ir;
1436         struct IR_tx *tx;
1437         struct IR_rx *rx;
1438         struct i2c_adapter *adap = client->adapter;
1439         int ret;
1440         bool tx_probe = false;
1441
1442         dprintk("%s: %s on i2c-%d (%s), client addr=0x%02x\n",
1443                 __func__, id->name, adap->nr, adap->name, client->addr);
1444
1445         /*
1446          * The IR receiver    is at i2c address 0x71.
1447          * The IR transmitter is at i2c address 0x70.
1448          */
1449
1450         if (id->driver_data & ID_FLAG_TX)
1451                 tx_probe = true;
1452         else if (tx_only) /* module option */
1453                 return -ENXIO;
1454
1455         zilog_info("probing IR %s on %s (i2c-%d)\n",
1456                    tx_probe ? "Tx" : "Rx", adap->name, adap->nr);
1457
1458         mutex_lock(&ir_devices_lock);
1459
1460         /* Use a single struct IR instance for both the Rx and Tx functions */
1461         ir = get_ir_device_by_adapter(adap);
1462         if (ir == NULL) {
1463                 ir = kzalloc(sizeof(struct IR), GFP_KERNEL);
1464                 if (ir == NULL) {
1465                         ret = -ENOMEM;
1466                         goto out_no_ir;
1467                 }
1468                 kref_init(&ir->ref);
1469
1470                 /* store for use in ir_probe() again, and open() later on */
1471                 INIT_LIST_HEAD(&ir->list);
1472                 list_add_tail(&ir->list, &ir_devices_list);
1473
1474                 ir->adapter = adap;
1475                 mutex_init(&ir->ir_lock);
1476                 atomic_set(&ir->open_count, 0);
1477                 spin_lock_init(&ir->tx_ref_lock);
1478                 spin_lock_init(&ir->rx_ref_lock);
1479
1480                 /* set lirc_dev stuff */
1481                 memcpy(&ir->l, &lirc_template, sizeof(struct lirc_driver));
1482                 /*
1483                  * FIXME this is a pointer reference to us, but no refcount.
1484                  *
1485                  * This OK for now, since lirc_dev currently won't touch this
1486                  * buffer as we provide our own lirc_fops.
1487                  *
1488                  * Currently our own lirc_fops rely on this ir->l.rbuf pointer
1489                  */
1490                 ir->l.rbuf = &ir->rbuf;
1491                 ir->l.dev  = &adap->dev;
1492                 ret = lirc_buffer_init(ir->l.rbuf,
1493                                        ir->l.chunk_size, ir->l.buffer_size);
1494                 if (ret)
1495                         goto out_put_ir;
1496         }
1497
1498         if (tx_probe) {
1499                 /* Get the IR_rx instance for later, if already allocated */
1500                 rx = get_ir_rx(ir);
1501
1502                 /* Set up a struct IR_tx instance */
1503                 tx = kzalloc(sizeof(struct IR_tx), GFP_KERNEL);
1504                 if (tx == NULL) {
1505                         ret = -ENOMEM;
1506                         goto out_put_xx;
1507                 }
1508                 kref_init(&tx->ref);
1509                 ir->tx = tx;
1510
1511                 ir->l.features |= LIRC_CAN_SEND_PULSE;
1512                 mutex_init(&tx->client_lock);
1513                 tx->c = client;
1514                 tx->need_boot = 1;
1515                 tx->post_tx_ready_poll =
1516                                (id->driver_data & ID_FLAG_HDPVR) ? false : true;
1517
1518                 /* An ir ref goes to the struct IR_tx instance */
1519                 tx->ir = get_ir_device(ir, true);
1520
1521                 /* A tx ref goes to the i2c_client */
1522                 i2c_set_clientdata(client, get_ir_tx(ir));
1523
1524                 /*
1525                  * Load the 'firmware'.  We do this before registering with
1526                  * lirc_dev, so the first firmware load attempt does not happen
1527                  * after a open() or write() call on the device.
1528                  *
1529                  * Failure here is not deemed catastrophic, so the receiver will
1530                  * still be usable.  Firmware load will be retried in write(),
1531                  * if it is needed.
1532                  */
1533                 fw_load(tx);
1534
1535                 /* Proceed only if the Rx client is also ready or not needed */
1536                 if (rx == NULL && !tx_only) {
1537                         zilog_info("probe of IR Tx on %s (i2c-%d) done. Waiting"
1538                                    " on IR Rx.\n", adap->name, adap->nr);
1539                         goto out_ok;
1540                 }
1541         } else {
1542                 /* Get the IR_tx instance for later, if already allocated */
1543                 tx = get_ir_tx(ir);
1544
1545                 /* Set up a struct IR_rx instance */
1546                 rx = kzalloc(sizeof(struct IR_rx), GFP_KERNEL);
1547                 if (rx == NULL) {
1548                         ret = -ENOMEM;
1549                         goto out_put_xx;
1550                 }
1551                 kref_init(&rx->ref);
1552                 ir->rx = rx;
1553
1554                 ir->l.features |= LIRC_CAN_REC_LIRCCODE;
1555                 mutex_init(&rx->client_lock);
1556                 rx->c = client;
1557                 rx->hdpvr_data_fmt =
1558                                (id->driver_data & ID_FLAG_HDPVR) ? true : false;
1559
1560                 /* An ir ref goes to the struct IR_rx instance */
1561                 rx->ir = get_ir_device(ir, true);
1562
1563                 /* An rx ref goes to the i2c_client */
1564                 i2c_set_clientdata(client, get_ir_rx(ir));
1565
1566                 /*
1567                  * Start the polling thread.
1568                  * It will only perform an empty loop around schedule_timeout()
1569                  * until we register with lirc_dev and the first user open()
1570                  */
1571                 /* An ir ref goes to the new rx polling kthread */
1572                 rx->task = kthread_run(lirc_thread, get_ir_device(ir, true),
1573                                        "zilog-rx-i2c-%d", adap->nr);
1574                 if (IS_ERR(rx->task)) {
1575                         ret = PTR_ERR(rx->task);
1576                         zilog_error("%s: could not start IR Rx polling thread"
1577                                     "\n", __func__);
1578                         /* Failed kthread, so put back the ir ref */
1579                         put_ir_device(ir, true);
1580                         /* Failure exit, so put back rx ref from i2c_client */
1581                         i2c_set_clientdata(client, NULL);
1582                         put_ir_rx(rx, true);
1583                         ir->l.features &= ~LIRC_CAN_REC_LIRCCODE;
1584                         goto out_put_xx;
1585                 }
1586
1587                 /* Proceed only if the Tx client is also ready */
1588                 if (tx == NULL) {
1589                         zilog_info("probe of IR Rx on %s (i2c-%d) done. Waiting"
1590                                    " on IR Tx.\n", adap->name, adap->nr);
1591                         goto out_ok;
1592                 }
1593         }
1594
1595         /* register with lirc */
1596         ir->l.minor = minor; /* module option: user requested minor number */
1597         ir->l.minor = lirc_register_driver(&ir->l);
1598         if (ir->l.minor < 0 || ir->l.minor >= MAX_IRCTL_DEVICES) {
1599                 zilog_error("%s: \"minor\" must be between 0 and %d (%d)!\n",
1600                             __func__, MAX_IRCTL_DEVICES-1, ir->l.minor);
1601                 ret = -EBADRQC;
1602                 goto out_put_xx;
1603         }
1604         zilog_info("IR unit on %s (i2c-%d) registered as lirc%d and ready\n",
1605                    adap->name, adap->nr, ir->l.minor);
1606
1607 out_ok:
1608         if (rx != NULL)
1609                 put_ir_rx(rx, true);
1610         if (tx != NULL)
1611                 put_ir_tx(tx, true);
1612         put_ir_device(ir, true);
1613         zilog_info("probe of IR %s on %s (i2c-%d) done\n",
1614                    tx_probe ? "Tx" : "Rx", adap->name, adap->nr);
1615         mutex_unlock(&ir_devices_lock);
1616         return 0;
1617
1618 out_put_xx:
1619         if (rx != NULL)
1620                 put_ir_rx(rx, true);
1621         if (tx != NULL)
1622                 put_ir_tx(tx, true);
1623 out_put_ir:
1624         put_ir_device(ir, true);
1625 out_no_ir:
1626         zilog_error("%s: probing IR %s on %s (i2c-%d) failed with %d\n",
1627                     __func__, tx_probe ? "Tx" : "Rx", adap->name, adap->nr,
1628                    ret);
1629         mutex_unlock(&ir_devices_lock);
1630         return ret;
1631 }
1632
1633 static int __init zilog_init(void)
1634 {
1635         int ret;
1636
1637         zilog_notify("Zilog/Hauppauge IR driver initializing\n");
1638
1639         mutex_init(&tx_data_lock);
1640
1641         request_module("firmware_class");
1642
1643         ret = i2c_add_driver(&driver);
1644         if (ret)
1645                 zilog_error("initialization failed\n");
1646         else
1647                 zilog_notify("initialization complete\n");
1648
1649         return ret;
1650 }
1651
1652 static void __exit zilog_exit(void)
1653 {
1654         i2c_del_driver(&driver);
1655         /* if loaded */
1656         fw_unload();
1657         zilog_notify("Zilog/Hauppauge IR driver unloaded\n");
1658 }
1659
1660 module_init(zilog_init);
1661 module_exit(zilog_exit);
1662
1663 MODULE_DESCRIPTION("Zilog/Hauppauge infrared transmitter driver (i2c stack)");
1664 MODULE_AUTHOR("Gerd Knorr, Michal Kochanowicz, Christoph Bartelmus, "
1665               "Ulrich Mueller, Stefan Jahn, Jerome Brock, Mark Weaver, "
1666               "Andy Walls");
1667 MODULE_LICENSE("GPL");
1668 /* for compat with old name, which isn't all that accurate anymore */
1669 MODULE_ALIAS("lirc_pvr150");
1670
1671 module_param(minor, int, 0444);
1672 MODULE_PARM_DESC(minor, "Preferred minor device number");
1673
1674 module_param(debug, bool, 0644);
1675 MODULE_PARM_DESC(debug, "Enable debugging messages");
1676
1677 module_param(tx_only, bool, 0644);
1678 MODULE_PARM_DESC(tx_only, "Only handle the IR transmit function");