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