Chinaunix首页 | 论坛 | 博客
  • 博客访问: 637269
  • 博文数量: 121
  • 博客积分: 8469
  • 博客等级: 中将
  • 技术积分: 1065
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-03 10:32
文章分类

全部博文(121)

文章存档

2013年(1)

2012年(15)

2010年(2)

2009年(8)

2008年(95)

我的朋友

分类: Android平台

2013-02-28 09:45:05

Usually, i2c devices are controlled by a kernel driver. But it is also
possible to access all devices on an adapter from userspace, through
the /dev interface. You need to load module i2c-dev for this.

Each registered i2c adapter gets a number, counting from 0. You can
examine /sys/class/i2c-dev/ to see what number corresponds to which adapter.
Alternatively, you can run "i2cdetect -l" to obtain a formated list of all
i2c adapters present on your system at a given time. i2cdetect is part of
the i2c-tools package.

I2C device files are character device files with major device number 89
and a minor device number corresponding to the number assigned as
explained above. They should be called "i2c-%d" (i2c-0, i2c-1, ...,
i2c-10, ...). All 256 minor device numbers are reserved for i2c.


C example
=========

So let's say you want to access an i2c adapter from a C program. The
first thing to do is "#include ". Please note that
there are two files named "i2c-dev.h" out there, one is distributed
with the Linux kernel and is meant to be included from kernel
driver code, the other one is distributed with i2c-tools and is
meant to be included from user-space programs. You obviously want
the second one here.

Now, you have to decide which adapter you want to access. You should
inspect /sys/class/i2c-dev/ or run "i2cdetect -l" to decide this.
Adapter numbers are assigned somewhat dynamically, so you can not
assume much about them. They can even change from one boot to the next.

Next thing, open the device file, as follows:

  int file;
  int adapter_nr = 2; /* probably dynamically determined */
  char filename[20];
 
  snprintf(filename, 19, "/dev/i2c-%d", adapter_nr);
  file = open(filename, O_RDWR);
  if (file < 0) {
    /* ERROR HANDLING; you can check errno to see what went wrong */
    exit(1);
  }

When you have opened the device, you must specify with what device
address you want to communicate:

  int addr = 0x40; /* The I2C address */

  if (ioctl(file, I2C_SLAVE, addr) < 0) {
    /* ERROR HANDLING; you can check errno to see what went wrong */
    exit(1);
  }

Well, you are all set up now. You can now use SMBus commands or plain
I2C to communicate with your device. SMBus commands are preferred if
the device supports them. Both are illustrated below.

  __u8 register = 0x10; /* Device register to access */
  __s32 res;
  char buf[10];

  /* Using SMBus commands */
  res = i2c_smbus_read_word_data(file, register);
  if (res < 0) {
    /* ERROR HANDLING: i2c transaction failed */
  } else {
    /* res contains the read word */
  }

  /* Using I2C Write, equivalent of
     i2c_smbus_write_word_data(file, register, 0x6543) */
  buf[0] = register;
  buf[1] = 0x43;
  buf[2] = 0x65;
  if (write(file, buf, 3) ! =3) {
    /* ERROR HANDLING: i2c transaction failed */
  }

  /* Using I2C Read, equivalent of i2c_smbus_read_byte(file) */
  if (read(file, buf, 1) != 1) {
    /* ERROR HANDLING: i2c transaction failed */
  } else {
    /* buf[0] contains the read byte */
  }

Note that only a subset of the I2C and SMBus protocols can be achieved by
the means of read() and write() calls. In particular, so-called combined
transactions (mixing read and write messages in the same transaction)
aren't supported. For this reason, this interface is almost never used by
user-space programs.

IMPORTANT: because of the use of inline functions, you *have* to use
'-O' or some variation when you compile your program!


Full interface description
==========================

The following IOCTLs are defined:

ioctl(file, I2C_SLAVE, long addr)
  Change slave address. The address is passed in the 7 lower bits of the
  argument (except for 10 bit addresses, passed in the 10 lower bits in this
  case).

ioctl(file, I2C_TENBIT, long select)
  Selects ten bit addresses if select not equals 0, selects normal 7 bit
  addresses if select equals 0. Default 0.  This request is only valid
  if the adapter has I2C_FUNC_10BIT_ADDR.

ioctl(file, I2C_PEC, long select)
  Selects SMBus PEC (packet error checking) generation and verification
  if select not equals 0, disables if select equals 0. Default 0.
  Used only for SMBus transactions.  This request only has an effect if the
  the adapter has I2C_FUNC_SMBUS_PEC; it is still safe if not, it just
  doesn't have any effect.

ioctl(file, I2C_FUNCS, unsigned long *funcs)
  Gets the adapter functionality and puts it in *funcs.

ioctl(file, I2C_RDWR, struct i2c_rdwr_ioctl_data *msgset)
  Do combined read/write transaction without stop in between.
  Only valid if the adapter has I2C_FUNC_I2C.  The argument is
  a pointer to a

  struct i2c_rdwr_ioctl_data {
      struct i2c_msg *msgs;  /* ptr to array of simple messages */
      int nmsgs;             /* number of messages to exchange */
  }

  The msgs[] themselves contain further pointers into data buffers.
  The function will write or read data to or from that buffers depending
  on whether the I2C_M_RD flag is set in a particular message or not.
  The slave address and whether to use ten bit address mode has to be
  set in each message, overriding the values set with the above ioctl's.

ioctl(file, I2C_SMBUS, struct i2c_smbus_ioctl_data *args)
  Not meant to be called  directly; instead, use the access functions
  below.

You can do plain i2c transactions by using read(2) and write(2) calls.
You do not need to pass the address byte; instead, set it through
ioctl I2C_SLAVE before you try to access the device.

You can do SMBus level transactions (see documentation file smbus-protocol
for details) through the following functions:
  __s32 i2c_smbus_write_quick(int file, __u8 value);
  __s32 i2c_smbus_read_byte(int file);
  __s32 i2c_smbus_write_byte(int file, __u8 value);
  __s32 i2c_smbus_read_byte_data(int file, __u8 command);
  __s32 i2c_smbus_write_byte_data(int file, __u8 command, __u8 value);
  __s32 i2c_smbus_read_word_data(int file, __u8 command);
  __s32 i2c_smbus_write_word_data(int file, __u8 command, __u16 value);
  __s32 i2c_smbus_process_call(int file, __u8 command, __u16 value);
  __s32 i2c_smbus_read_block_data(int file, __u8 command, __u8 *values);
  __s32 i2c_smbus_write_block_data(int file, __u8 command, __u8 length,
                                   __u8 *values);
All these transactions return -1 on failure; you can read errno to see
what happened. The 'write' transactions return 0 on success; the
'read' transactions return the read value, except for read_block, which
returns the number of values read. The block buffers need not be longer
than 32 bytes.

The above functions are all inline functions, that resolve to calls to
the i2c_smbus_access function, that on its turn calls a specific ioctl
with the data in a specific format. Read the source code if you
want to know what happens behind the screens.


Implementation details
======================

For the interested, here's the code flow which happens inside the kernel
when you use the /dev interface to I2C:

1* Your program opens /dev/i2c-N and calls ioctl() on it, as described in
section "C example" above.

2* These open() and ioctl() calls are handled by the i2c-dev kernel
driver: see i2c-dev.c:i2cdev_open() and i2c-dev.c:i2cdev_ioctl(),
respectively. You can think of i2c-dev as a generic I2C chip driver
that can be programmed from user-space.

3* Some ioctl() calls are for administrative tasks and are handled by
i2c-dev directly. Examples include I2C_SLAVE (set the address of the
device you want to access) and I2C_PEC (enable or disable SMBus error
checking on future transactions.)

4* Other ioctl() calls are converted to in-kernel function calls by
i2c-dev. Examples include I2C_FUNCS, which queries the I2C adapter
functionality using i2c.h:i2c_get_functionality(), and I2C_SMBUS, which
performs an SMBus transaction using i2c-core.c:i2c_smbus_xfer().

The i2c-dev driver is responsible for checking all the parameters that
come from user-space for validity. After this point, there is no
difference between these calls that came from user-space through i2c-dev
and calls that would have been performed by kernel I2C chip drivers
directly. This means that I2C bus drivers don't need to implement
anything special to support access from user-space.

5* These i2c-core.c/i2c.h functions are wrappers to the actual
implementation of your I2C bus driver. Each adapter must declare
callback functions implementing these standard calls.
i2c.h:i2c_get_functionality() calls i2c_adapter.algo->functionality(),
while i2c-core.c:i2c_smbus_xfer() calls either
adapter.algo->smbus_xfer() if it is implemented, or if not,
i2c-core.c:i2c_smbus_xfer_emulated() which in turn calls
i2c_adapter.algo->master_xfer().

After your I2C bus driver has processed these requests, execution runs
up the call chain, with almost no processing done, except by i2c-dev to
package the returned data, if any, in suitable format for the ioctl.

 

 

 

/*
    i2c-dev.c - i2c-bus driver, char device interface

    Copyright (C) 1995-97 Simon G. Vogl
    Copyright (C) 1998-99 Frodo Looijaard
    Copyright (C) 2003 Greg Kroah-Hartman

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

/* Note that this is a complete rewrite of Simon Vogl's i2c-dev module.
   But I have used so much of his original code and ideas that it seems
   only fair to recognize him as co-author -- Frodo */

/* The I2C_RDWR ioctl code is written by Kolja Waschk */

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include

static struct i2c_driver i2cdev_driver;

/*
 * An i2c_dev represents an i2c_adapter ... an I2C or SMBus master, not a
 * slave (i2c_client) with which messages will be exchanged.  It's coupled
 * with a character special file which is accessed by user mode drivers.
 *
 * The list of i2c_dev structures is parallel to the i2c_adapter lists
 * maintained by the driver model, and is updated using notifications
 * delivered to the i2cdev_driver.
 */
struct i2c_dev {
    struct list_head list;
    struct i2c_adapter *adap;
    struct device *dev;
};

#define I2C_MINORS    256
static LIST_HEAD(i2c_dev_list);
static DEFINE_SPINLOCK(i2c_dev_list_lock);

static struct i2c_dev *i2c_dev_get_by_minor(unsigned index)
{
    struct i2c_dev *i2c_dev;

    spin_lock(&i2c_dev_list_lock);
    list_for_each_entry(i2c_dev, &i2c_dev_list, list) {
        if (i2c_dev->adap->nr == index)
            goto found;
    }
    i2c_dev = NULL;
found:
    spin_unlock(&i2c_dev_list_lock);
    return i2c_dev;
}

static struct i2c_dev *get_free_i2c_dev(struct i2c_adapter *adap)
{
    struct i2c_dev *i2c_dev;

    if (adap->nr >= I2C_MINORS) {
        printk(KERN_ERR "i2c-dev: Out of device minors (%d)/n",
               adap->nr);
        return ERR_PTR(-ENODEV);
    }

    i2c_dev = kzalloc(sizeof(*i2c_dev), GFP_KERNEL);
    if (!i2c_dev)
        return ERR_PTR(-ENOMEM);
    i2c_dev->adap = adap;

    spin_lock(&i2c_dev_list_lock);
    list_add_tail(&i2c_dev->list, &i2c_dev_list);
    spin_unlock(&i2c_dev_list_lock);
    return i2c_dev;
}

static void return_i2c_dev(struct i2c_dev *i2c_dev)
{
    spin_lock(&i2c_dev_list_lock);
    list_del(&i2c_dev->list);
    spin_unlock(&i2c_dev_list_lock);
    kfree(i2c_dev);
}

static ssize_t show_adapter_name(struct device *dev,
                 struct device_attribute *attr, char *buf)
{
    struct i2c_dev *i2c_dev = i2c_dev_get_by_minor(MINOR(dev->devt));

    if (!i2c_dev)
        return -ENODEV;
    return sprintf(buf, "%s/n", i2c_dev->adap->name);
}
static DEVICE_ATTR(name, S_IRUGO, show_adapter_name, NULL);

/* ------------------------------------------------------------------------- */

/*
 * After opening an instance of this character special file, a file
 * descriptor starts out associated only with an i2c_adapter (and bus).
 *
 * Using the I2C_RDWR ioctl(), you can then *immediately* issue i2c_msg
 * traffic to any devices on the bus used by that adapter.  That's because
 * the i2c_msg vectors embed all the addressing information they need, and
 * are submitted directly to an i2c_adapter.  However, SMBus-only adapters
 * don't support that interface.
 *
 * To use read()/write() system calls on that file descriptor, or to use
 * SMBus interfaces (and work with SMBus-only hosts!), you must first issue
 * an I2C_SLAVE (or I2C_SLAVE_FORCE) ioctl.  That configures an anonymous
 * (never registered) i2c_client so it holds the addressing information
 * needed by those system calls and by this SMBus interface.
 */

static ssize_t i2cdev_read(struct file *file, char __user *buf, size_t count,
        loff_t *offset)
{
    char *tmp;
    int ret;

    struct i2c_client *client = file->private_data;

    if (count > 8192)
        count = 8192;

    tmp = kmalloc(count, GFP_KERNEL);
    if (tmp == NULL)
        return -ENOMEM;

    pr_debug("i2c-dev: i2c-%d reading %zu bytes./n",
        iminor(file->f_path.dentry->d_inode), count);

    ret = i2c_master_recv(client, tmp, count);
    if (ret >= 0)
        ret = copy_to_user(buf, tmp, count) ? -EFAULT : ret;
    kfree(tmp);
    return ret;
}

static ssize_t i2cdev_write(struct file *file, const char __user *buf,
        size_t count, loff_t *offset)
{
    int ret;
    char *tmp;
    struct i2c_client *client = file->private_data;

    if (count > 8192)
        count = 8192;

    tmp = memdup_user(buf, count);
    if (IS_ERR(tmp))
        return PTR_ERR(tmp);

    pr_debug("i2c-dev: i2c-%d writing %zu bytes./n",
        iminor(file->f_path.dentry->d_inode), count);

    ret = i2c_master_send(client, tmp, count);
    kfree(tmp);
    return ret;
}

static int i2cdev_check(struct device *dev, void *addrp)
{
    struct i2c_client *client = i2c_verify_client(dev);

    if (!client || client->addr != *(unsigned int *)addrp)
        return 0;

    return dev->driver ? -EBUSY : 0;
}

/* walk up mux tree */
static int i2cdev_check_mux_parents(struct i2c_adapter *adapter, int addr)
{
    int result;

    result = device_for_each_child(&adapter->dev, &addr, i2cdev_check);

    if (!result && i2c_parent_is_i2c_adapter(adapter))
        result = i2cdev_check_mux_parents(
                    to_i2c_adapter(adapter->dev.parent), addr);

    return result;
}

/* recurse down mux tree */
static int i2cdev_check_mux_children(struct device *dev, void *addrp)
{
    int result;

    if (dev->type == &i2c_adapter_type)
        result = device_for_each_child(dev, addrp,
                        i2cdev_check_mux_children);
    else
        result = i2cdev_check(dev, addrp);

    return result;
}

/* This address checking function differs from the one in i2c-core
   in that it considers an address with a registered device, but no
   driver bound to it, as NOT busy. */
static int i2cdev_check_addr(struct i2c_adapter *adapter, unsigned int addr)
{
    int result = 0;

    if (i2c_parent_is_i2c_adapter(adapter))
        result = i2cdev_check_mux_parents(
                    to_i2c_adapter(adapter->dev.parent), addr);

    if (!result)
        result = device_for_each_child(&adapter->dev, &addr,
                        i2cdev_check_mux_children);

    return result;
}

static noinline int i2cdev_ioctl_rdrw(struct i2c_client *client,
        unsigned long arg)
{
    struct i2c_rdwr_ioctl_data rdwr_arg;
    struct i2c_msg *rdwr_pa;
    u8 __user **data_ptrs;
    int i, res;

    if (copy_from_user(&rdwr_arg,
               (struct i2c_rdwr_ioctl_data __user *)arg,
               sizeof(rdwr_arg)))
        return -EFAULT;

    /* Put an arbitrary limit on the number of messages that can
     * be sent at once */
    if (rdwr_arg.nmsgs > I2C_RDRW_IOCTL_MAX_MSGS)
        return -EINVAL;

    rdwr_pa = kmalloc(rdwr_arg.nmsgs * sizeof(struct i2c_msg), GFP_KERNEL);
    if (!rdwr_pa)
        return -ENOMEM;

    if (copy_from_user(rdwr_pa, rdwr_arg.msgs,
               rdwr_arg.nmsgs * sizeof(struct i2c_msg))) {
        kfree(rdwr_pa);
        return -EFAULT;
    }

    data_ptrs = kmalloc(rdwr_arg.nmsgs * sizeof(u8 __user *), GFP_KERNEL);
    if (data_ptrs == NULL) {
        kfree(rdwr_pa);
        return -ENOMEM;
    }

    res = 0;
    for (i = 0; i < rdwr_arg.nmsgs; i++) {
        /* Limit the size of the message to a sane amount;
         * and don't let length change either. */
        if ((rdwr_pa[i].len > 8192) ||
            (rdwr_pa[i].flags & I2C_M_RECV_LEN)) {
            res = -EINVAL;
            break;
        }
        data_ptrs[i] = (u8 __user *)rdwr_pa[i].buf;
        rdwr_pa[i].buf = memdup_user(data_ptrs[i], rdwr_pa[i].len);
        if (IS_ERR(rdwr_pa[i].buf)) {
            res = PTR_ERR(rdwr_pa[i].buf);
            break;
        }
    }
    if (res < 0) {
        int j;
        for (j = 0; j < i; ++j)
            kfree(rdwr_pa[j].buf);
        kfree(data_ptrs);
        kfree(rdwr_pa);
        return res;
    }

    res = i2c_transfer(client->adapter, rdwr_pa, rdwr_arg.nmsgs);
    while (i-- > 0) {
        if (res >= 0 && (rdwr_pa[i].flags & I2C_M_RD)) {
            if (copy_to_user(data_ptrs[i], rdwr_pa[i].buf,
                     rdwr_pa[i].len))
                res = -EFAULT;
        }
        kfree(rdwr_pa[i].buf);
    }
    kfree(data_ptrs);
    kfree(rdwr_pa);
    return res;
}

static noinline int i2cdev_ioctl_smbus(struct i2c_client *client,
        unsigned long arg)
{
    struct i2c_smbus_ioctl_data data_arg;
    union i2c_smbus_data temp;
    int datasize, res;

    if (copy_from_user(&data_arg,
               (struct i2c_smbus_ioctl_data __user *) arg,
               sizeof(struct i2c_smbus_ioctl_data)))
        return -EFAULT;
    if ((data_arg.size != I2C_SMBUS_BYTE) &&
        (data_arg.size != I2C_SMBUS_QUICK) &&
        (data_arg.size != I2C_SMBUS_BYTE_DATA) &&
        (data_arg.size != I2C_SMBUS_WORD_DATA) &&
        (data_arg.size != I2C_SMBUS_PROC_CALL) &&
        (data_arg.size != I2C_SMBUS_BLOCK_DATA) &&
        (data_arg.size != I2C_SMBUS_I2C_BLOCK_BROKEN) &&
        (data_arg.size != I2C_SMBUS_I2C_BLOCK_DATA) &&
        (data_arg.size != I2C_SMBUS_BLOCK_PROC_CALL)) {
        dev_dbg(&client->adapter->dev,
            "size out of range (%x) in ioctl I2C_SMBUS./n",
            data_arg.size);
        return -EINVAL;
    }
    /* Note that I2C_SMBUS_READ and I2C_SMBUS_WRITE are 0 and 1,
       so the check is valid if size==I2C_SMBUS_QUICK too. */
    if ((data_arg.read_write != I2C_SMBUS_READ) &&
        (data_arg.read_write != I2C_SMBUS_WRITE)) {
        dev_dbg(&client->adapter->dev,
            "read_write out of range (%x) in ioctl I2C_SMBUS./n",
            data_arg.read_write);
        return -EINVAL;
    }

    /* Note that command values are always valid! */

    if ((data_arg.size == I2C_SMBUS_QUICK) ||
        ((data_arg.size == I2C_SMBUS_BYTE) &&
        (data_arg.read_write == I2C_SMBUS_WRITE)))
        /* These are special: we do not use data */
        return i2c_smbus_xfer(client->adapter, client->addr,
                      client->flags, data_arg.read_write,
                      data_arg.command, data_arg.size, NULL);

    if (data_arg.data == NULL) {
        dev_dbg(&client->adapter->dev,
            "data is NULL pointer in ioctl I2C_SMBUS./n");
        return -EINVAL;
    }

    if ((data_arg.size == I2C_SMBUS_BYTE_DATA) ||
        (data_arg.size == I2C_SMBUS_BYTE))
        datasize = sizeof(data_arg.data->byte);
    else if ((data_arg.size == I2C_SMBUS_WORD_DATA) ||
         (data_arg.size == I2C_SMBUS_PROC_CALL))
        datasize = sizeof(data_arg.data->word);
    else /* size == smbus block, i2c block, or block proc. call */
        datasize = sizeof(data_arg.data->block);

    if ((data_arg.size == I2C_SMBUS_PROC_CALL) ||
        (data_arg.size == I2C_SMBUS_BLOCK_PROC_CALL) ||
        (data_arg.size == I2C_SMBUS_I2C_BLOCK_DATA) ||
        (data_arg.read_write == I2C_SMBUS_WRITE)) {
        if (copy_from_user(&temp, data_arg.data, datasize))
            return -EFAULT;
    }
    if (data_arg.size == I2C_SMBUS_I2C_BLOCK_BROKEN) {
        /* Convert old I2C block commands to the new
           convention. This preserves binary compatibility. */
        data_arg.size = I2C_SMBUS_I2C_BLOCK_DATA;
        if (data_arg.read_write == I2C_SMBUS_READ)
            temp.block[0] = I2C_SMBUS_BLOCK_MAX;
    }
    res = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
          data_arg.read_write, data_arg.command, data_arg.size, &temp);
    if (!res && ((data_arg.size == I2C_SMBUS_PROC_CALL) ||
             (data_arg.size == I2C_SMBUS_BLOCK_PROC_CALL) ||
             (data_arg.read_write == I2C_SMBUS_READ))) {
        if (copy_to_user(data_arg.data, &temp, datasize))
            return -EFAULT;
    }
    return res;
}

static long i2cdev_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
    struct i2c_client *client = file->private_data;
    unsigned long funcs;

    dev_dbg(&client->adapter->dev, "ioctl, cmd=0x%02x, arg=0x%02lx/n",
        cmd, arg);

    switch (cmd) {
    case I2C_SLAVE:
    case I2C_SLAVE_FORCE:
        /* NOTE:  devices set up to work with "new style" drivers
         * can't use I2C_SLAVE, even when the device node is not
         * bound to a driver.  Only I2C_SLAVE_FORCE will work.
         *
         * Setting the PEC flag here won't affect kernel drivers,
         * which will be using the i2c_client node registered with
         * the driver model core.  Likewise, when that client has
         * the PEC flag already set, the i2c-dev driver won't see
         * (or use) this setting.
         */
        if ((arg > 0x3ff) ||
            (((client->flags & I2C_M_TEN) == 0) && arg > 0x7f))
            return -EINVAL;
        if (cmd == I2C_SLAVE && i2cdev_check_addr(client->adapter, arg))
            return -EBUSY;
        /* REVISIT: address could become busy later */
        client->addr = arg;
        return 0;
    case I2C_TENBIT:
        if (arg)
            client->flags |= I2C_M_TEN;
        else
            client->flags &= ~I2C_M_TEN;
        return 0;
    case I2C_PEC:
        if (arg)
            client->flags |= I2C_CLIENT_PEC;
        else
            client->flags &= ~I2C_CLIENT_PEC;
        return 0;
    case I2C_FUNCS:
        funcs = i2c_get_functionality(client->adapter);
        return put_user(funcs, (unsigned long __user *)arg);

    case I2C_RDWR:
        return i2cdev_ioctl_rdrw(client, arg);

    case I2C_SMBUS:
        return i2cdev_ioctl_smbus(client, arg);

    case I2C_RETRIES:
        client->adapter->retries = arg;
        break;
    case I2C_TIMEOUT:
        /* For historical reasons, user-space sets the timeout
         * value in units of 10 ms.
         */
        client->adapter->timeout = msecs_to_jiffies(arg * 10);
        break;
    default:
        /* NOTE:  returning a fault code here could cause trouble
         * in buggy userspace code.  Some old kernel bugs returned
         * zero in this case, and userspace code might accidentally
         * have depended on that bug.
         */
        return -ENOTTY;
    }
    return 0;
}

static int i2cdev_open(struct inode *inode, struct file *file)
{
    unsigned int minor = iminor(inode);
    struct i2c_client *client;
    struct i2c_adapter *adap;
    struct i2c_dev *i2c_dev;

    i2c_dev = i2c_dev_get_by_minor(minor);
    if (!i2c_dev)
        return -ENODEV;

    adap = i2c_get_adapter(i2c_dev->adap->nr);
    if (!adap)
        return -ENODEV;

    /* This creates an anonymous i2c_client, which may later be
     * pointed to some address using I2C_SLAVE or I2C_SLAVE_FORCE.
     *
     * This client is ** NEVER REGISTERED ** with the driver model
     * or I2C core code!!  It just holds private copies of addressing
     * information and maybe a PEC flag.
     */
    client = kzalloc(sizeof(*client), GFP_KERNEL);
    if (!client) {
        i2c_put_adapter(adap);
        return -ENOMEM;
    }
    snprintf(client->name, I2C_NAME_SIZE, "i2c-dev %d", adap->nr);
    client->driver = &i2cdev_driver;

    client->adapter = adap;
    file->private_data = client;

    return 0;
}

static int i2cdev_release(struct inode *inode, struct file *file)
{
    struct i2c_client *client = file->private_data;

    i2c_put_adapter(client->adapter);
    kfree(client);
    file->private_data = NULL;

    return 0;
}

static const struct file_operations i2cdev_fops = {
    .owner        = THIS_MODULE,
    .llseek        = no_llseek,
    .read        = i2cdev_read,
    .write        = i2cdev_write,
    .unlocked_ioctl    = i2cdev_ioctl,
    .open        = i2cdev_open,
    .release    = i2cdev_release,
};

/* ------------------------------------------------------------------------- */

/*
 * The legacy "i2cdev_driver" is used primarily to get notifications when
 * I2C adapters are added or removed, so that each one gets an i2c_dev
 * and is thus made available to userspace driver code.
 */

static struct class *i2c_dev_class;

static int i2cdev_attach_adapter(struct i2c_adapter *adap)
{
    struct i2c_dev *i2c_dev;
    int res;

    i2c_dev = get_free_i2c_dev(adap);
    if (IS_ERR(i2c_dev))
        return PTR_ERR(i2c_dev);

    /* register this i2c device with the driver core */
    i2c_dev->dev = device_create(i2c_dev_class, &adap->dev,
                     MKDEV(I2C_MAJOR, adap->nr), NULL,
                     "i2c-%d", adap->nr);
    if (IS_ERR(i2c_dev->dev)) {
        res = PTR_ERR(i2c_dev->dev);
        goto error;
    }
    res = device_create_file(i2c_dev->dev, &dev_attr_name);
    if (res)
        goto error_destroy;

    pr_debug("i2c-dev: adapter [%s] registered as minor %d/n",
         adap->name, adap->nr);
    return 0;
error_destroy:
    device_destroy(i2c_dev_class, MKDEV(I2C_MAJOR, adap->nr));
error:
    return_i2c_dev(i2c_dev);
    return res;
}

static int i2cdev_detach_adapter(struct i2c_adapter *adap)
{
    struct i2c_dev *i2c_dev;

    i2c_dev = i2c_dev_get_by_minor(adap->nr);
    if (!i2c_dev) /* attach_adapter must have failed */
        return 0;

    device_remove_file(i2c_dev->dev, &dev_attr_name);
    return_i2c_dev(i2c_dev);
    device_destroy(i2c_dev_class, MKDEV(I2C_MAJOR, adap->nr));

    pr_debug("i2c-dev: adapter [%s] unregistered/n", adap->name);
    return 0;
}

static struct i2c_driver i2cdev_driver = {
    .driver = {
        .name    = "dev_driver",
    },
    .attach_adapter    = i2cdev_attach_adapter,
    .detach_adapter    = i2cdev_detach_adapter,
};

/* ------------------------------------------------------------------------- */

/*
 * module load/unload record keeping
 */

static int __init i2c_dev_init(void)
{
    int res;

    printk(KERN_INFO "i2c /dev entries driver/n");

    res = register_chrdev(I2C_MAJOR, "i2c", &i2cdev_fops);
    if (res)
        goto out;

    i2c_dev_class = class_create(THIS_MODULE, "i2c-dev");
    if (IS_ERR(i2c_dev_class)) {
        res = PTR_ERR(i2c_dev_class);
        goto out_unreg_chrdev;
    }

    res = i2c_add_driver(&i2cdev_driver);
    if (res)
        goto out_unreg_class;

    return 0;

out_unreg_class:
    class_destroy(i2c_dev_class);
out_unreg_chrdev:
    unregister_chrdev(I2C_MAJOR, "i2c");
out:
    printk(KERN_ERR "%s: Driver Initialisation failed/n", __FILE__);
    return res;
}

static void __exit i2c_dev_exit(void)
{
    i2c_del_driver(&i2cdev_driver);
    class_destroy(i2c_dev_class);
    unregister_chrdev(I2C_MAJOR, "i2c");
}

MODULE_AUTHOR("Frodo Looijaard and "
        "Simon G. Vogl ");
MODULE_DESCRIPTION("I2C /dev entries driver");
MODULE_LICENSE("GPL");

module_init(i2c_dev_init);
module_exit(i2c_dev_exit);

阅读(1992) | 评论(0) | 转发(0) |
0

上一篇:linux系统ds2786驱动程序分析

下一篇:没有了

给主人留下些什么吧!~~