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