linux/drivers/i2c/i2c-core.c
<<
>>
Prefs
   1/* i2c-core.c - a device driver for the iic-bus interface                    */
   2/* ------------------------------------------------------------------------- */
   3/*   Copyright (C) 1995-99 Simon G. Vogl
   4
   5    This program is free software; you can redistribute it and/or modify
   6    it under the terms of the GNU General Public License as published by
   7    the Free Software Foundation; either version 2 of the License, or
   8    (at your option) any later version.
   9
  10    This program is distributed in the hope that it will be useful,
  11    but WITHOUT ANY WARRANTY; without even the implied warranty of
  12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13    GNU General Public License for more details.                             */
  14/* ------------------------------------------------------------------------- */
  15
  16/* With some changes from Kyösti Mälkki <kmalkki@cc.hut.fi>.
  17   All SMBus-related things are written by Frodo Looijaard <frodol@dds.nl>
  18   SMBus 2.0 support by Mark Studebaker <mdsxyz123@yahoo.com> and
  19   Jean Delvare <khali@linux-fr.org>
  20   Mux support by Rodolfo Giometti <giometti@enneenne.com> and
  21   Michael Lawnick <michael.lawnick.ext@nsn.com>
  22   OF support is copyright (c) 2008 Jochen Friedrich <jochen@scram.de>
  23   (based on a previous patch from Jon Smirl <jonsmirl@gmail.com>) and
  24   (c) 2013  Wolfram Sang <wsa@the-dreams.de>
  25 */
  26
  27#include <linux/module.h>
  28#include <linux/kernel.h>
  29#include <linux/delay.h>
  30#include <linux/errno.h>
  31#include <linux/gpio.h>
  32#include <linux/slab.h>
  33#include <linux/i2c.h>
  34#include <linux/init.h>
  35#include <linux/idr.h>
  36#include <linux/mutex.h>
  37#include <linux/of.h>
  38#include <linux/of_device.h>
  39#include <linux/of_irq.h>
  40#include <linux/completion.h>
  41#include <linux/hardirq.h>
  42#include <linux/irqflags.h>
  43#include <linux/rwsem.h>
  44#include <linux/pm_runtime.h>
  45#include <linux/acpi.h>
  46#include <asm/uaccess.h>
  47
  48#include "i2c-core.h"
  49
  50
  51/* core_lock protects i2c_adapter_idr, and guarantees
  52   that device detection, deletion of detected devices, and attach_adapter
  53   calls are serialized */
  54static DEFINE_MUTEX(core_lock);
  55static DEFINE_IDR(i2c_adapter_idr);
  56
  57static struct device_type i2c_client_type;
  58static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
  59
  60/* ------------------------------------------------------------------------- */
  61
  62static const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
  63                                                const struct i2c_client *client)
  64{
  65        while (id->name[0]) {
  66                if (strcmp(client->name, id->name) == 0)
  67                        return id;
  68                id++;
  69        }
  70        return NULL;
  71}
  72
  73static int i2c_device_match(struct device *dev, struct device_driver *drv)
  74{
  75        struct i2c_client       *client = i2c_verify_client(dev);
  76        struct i2c_driver       *driver;
  77
  78        if (!client)
  79                return 0;
  80
  81        /* Attempt an OF style match */
  82        if (of_driver_match_device(dev, drv))
  83                return 1;
  84
  85        /* Then ACPI style match */
  86        if (acpi_driver_match_device(dev, drv))
  87                return 1;
  88
  89        driver = to_i2c_driver(drv);
  90        /* match on an id table if there is one */
  91        if (driver->id_table)
  92                return i2c_match_id(driver->id_table, client) != NULL;
  93
  94        return 0;
  95}
  96
  97
  98/* uevent helps with hotplug: modprobe -q $(MODALIAS) */
  99static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
 100{
 101        struct i2c_client       *client = to_i2c_client(dev);
 102
 103        if (add_uevent_var(env, "MODALIAS=%s%s",
 104                           I2C_MODULE_PREFIX, client->name))
 105                return -ENOMEM;
 106        dev_dbg(dev, "uevent\n");
 107        return 0;
 108}
 109
 110/* i2c bus recovery routines */
 111static int get_scl_gpio_value(struct i2c_adapter *adap)
 112{
 113        return gpio_get_value(adap->bus_recovery_info->scl_gpio);
 114}
 115
 116static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
 117{
 118        gpio_set_value(adap->bus_recovery_info->scl_gpio, val);
 119}
 120
 121static int get_sda_gpio_value(struct i2c_adapter *adap)
 122{
 123        return gpio_get_value(adap->bus_recovery_info->sda_gpio);
 124}
 125
 126static int i2c_get_gpios_for_recovery(struct i2c_adapter *adap)
 127{
 128        struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
 129        struct device *dev = &adap->dev;
 130        int ret = 0;
 131
 132        ret = gpio_request_one(bri->scl_gpio, GPIOF_OPEN_DRAIN |
 133                        GPIOF_OUT_INIT_HIGH, "i2c-scl");
 134        if (ret) {
 135                dev_warn(dev, "Can't get SCL gpio: %d\n", bri->scl_gpio);
 136                return ret;
 137        }
 138
 139        if (bri->get_sda) {
 140                if (gpio_request_one(bri->sda_gpio, GPIOF_IN, "i2c-sda")) {
 141                        /* work without SDA polling */
 142                        dev_warn(dev, "Can't get SDA gpio: %d. Not using SDA polling\n",
 143                                        bri->sda_gpio);
 144                        bri->get_sda = NULL;
 145                }
 146        }
 147
 148        return ret;
 149}
 150
 151static void i2c_put_gpios_for_recovery(struct i2c_adapter *adap)
 152{
 153        struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
 154
 155        if (bri->get_sda)
 156                gpio_free(bri->sda_gpio);
 157
 158        gpio_free(bri->scl_gpio);
 159}
 160
 161/*
 162 * We are generating clock pulses. ndelay() determines durating of clk pulses.
 163 * We will generate clock with rate 100 KHz and so duration of both clock levels
 164 * is: delay in ns = (10^6 / 100) / 2
 165 */
 166#define RECOVERY_NDELAY         5000
 167#define RECOVERY_CLK_CNT        9
 168
 169static int i2c_generic_recovery(struct i2c_adapter *adap)
 170{
 171        struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
 172        int i = 0, val = 1, ret = 0;
 173
 174        if (bri->prepare_recovery)
 175                bri->prepare_recovery(bri);
 176
 177        /*
 178         * By this time SCL is high, as we need to give 9 falling-rising edges
 179         */
 180        while (i++ < RECOVERY_CLK_CNT * 2) {
 181                if (val) {
 182                        /* Break if SDA is high */
 183                        if (bri->get_sda && bri->get_sda(adap))
 184                                        break;
 185                        /* SCL shouldn't be low here */
 186                        if (!bri->get_scl(adap)) {
 187                                dev_err(&adap->dev,
 188                                        "SCL is stuck low, exit recovery\n");
 189                                ret = -EBUSY;
 190                                break;
 191                        }
 192                }
 193
 194                val = !val;
 195                bri->set_scl(adap, val);
 196                ndelay(RECOVERY_NDELAY);
 197        }
 198
 199        if (bri->unprepare_recovery)
 200                bri->unprepare_recovery(bri);
 201
 202        return ret;
 203}
 204
 205int i2c_generic_scl_recovery(struct i2c_adapter *adap)
 206{
 207        adap->bus_recovery_info->set_scl(adap, 1);
 208        return i2c_generic_recovery(adap);
 209}
 210
 211int i2c_generic_gpio_recovery(struct i2c_adapter *adap)
 212{
 213        int ret;
 214
 215        ret = i2c_get_gpios_for_recovery(adap);
 216        if (ret)
 217                return ret;
 218
 219        ret = i2c_generic_recovery(adap);
 220        i2c_put_gpios_for_recovery(adap);
 221
 222        return ret;
 223}
 224
 225int i2c_recover_bus(struct i2c_adapter *adap)
 226{
 227        if (!adap->bus_recovery_info)
 228                return -EOPNOTSUPP;
 229
 230        dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
 231        return adap->bus_recovery_info->recover_bus(adap);
 232}
 233
 234static int i2c_device_probe(struct device *dev)
 235{
 236        struct i2c_client       *client = i2c_verify_client(dev);
 237        struct i2c_driver       *driver;
 238        int status;
 239
 240        if (!client)
 241                return 0;
 242
 243        if (!client->irq) {
 244                int irq = -ENOENT;
 245
 246                if (ACPI_COMPANION(dev))
 247                        irq = acpi_dev_gpio_irq_get(ACPI_COMPANION(dev), 0);
 248
 249                if (irq == -EPROBE_DEFER)
 250                        return irq;
 251                if (irq < 0)
 252                        irq = 0;
 253
 254                client->irq = irq;
 255        }
 256
 257        driver = to_i2c_driver(dev->driver);
 258        if (!driver->probe || !driver->id_table)
 259                return -ENODEV;
 260        client->driver = driver;
 261        if (!device_can_wakeup(&client->dev))
 262                device_init_wakeup(&client->dev,
 263                                        client->flags & I2C_CLIENT_WAKE);
 264        dev_dbg(dev, "probe\n");
 265
 266        status = driver->probe(client, i2c_match_id(driver->id_table, client));
 267        if (status) {
 268                client->driver = NULL;
 269                i2c_set_clientdata(client, NULL);
 270        }
 271        return status;
 272}
 273
 274static int i2c_device_remove(struct device *dev)
 275{
 276        struct i2c_client       *client = i2c_verify_client(dev);
 277        struct i2c_driver       *driver;
 278        int                     status;
 279
 280        if (!client || !dev->driver)
 281                return 0;
 282
 283        driver = to_i2c_driver(dev->driver);
 284        if (driver->remove) {
 285                dev_dbg(dev, "remove\n");
 286                status = driver->remove(client);
 287        } else {
 288                dev->driver = NULL;
 289                status = 0;
 290        }
 291        if (status == 0) {
 292                client->driver = NULL;
 293                i2c_set_clientdata(client, NULL);
 294        }
 295        return status;
 296}
 297
 298static void i2c_device_shutdown(struct device *dev)
 299{
 300        struct i2c_client *client = i2c_verify_client(dev);
 301        struct i2c_driver *driver;
 302
 303        if (!client || !dev->driver)
 304                return;
 305        driver = to_i2c_driver(dev->driver);
 306        if (driver->shutdown)
 307                driver->shutdown(client);
 308}
 309
 310#ifdef CONFIG_PM_SLEEP
 311static int i2c_legacy_suspend(struct device *dev, pm_message_t mesg)
 312{
 313        struct i2c_client *client = i2c_verify_client(dev);
 314        struct i2c_driver *driver;
 315
 316        if (!client || !dev->driver)
 317                return 0;
 318        driver = to_i2c_driver(dev->driver);
 319        if (!driver->suspend)
 320                return 0;
 321        return driver->suspend(client, mesg);
 322}
 323
 324static int i2c_legacy_resume(struct device *dev)
 325{
 326        struct i2c_client *client = i2c_verify_client(dev);
 327        struct i2c_driver *driver;
 328
 329        if (!client || !dev->driver)
 330                return 0;
 331        driver = to_i2c_driver(dev->driver);
 332        if (!driver->resume)
 333                return 0;
 334        return driver->resume(client);
 335}
 336
 337static int i2c_device_pm_suspend(struct device *dev)
 338{
 339        const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
 340
 341        if (pm)
 342                return pm_generic_suspend(dev);
 343        else
 344                return i2c_legacy_suspend(dev, PMSG_SUSPEND);
 345}
 346
 347static int i2c_device_pm_resume(struct device *dev)
 348{
 349        const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
 350
 351        if (pm)
 352                return pm_generic_resume(dev);
 353        else
 354                return i2c_legacy_resume(dev);
 355}
 356
 357static int i2c_device_pm_freeze(struct device *dev)
 358{
 359        const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
 360
 361        if (pm)
 362                return pm_generic_freeze(dev);
 363        else
 364                return i2c_legacy_suspend(dev, PMSG_FREEZE);
 365}
 366
 367static int i2c_device_pm_thaw(struct device *dev)
 368{
 369        const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
 370
 371        if (pm)
 372                return pm_generic_thaw(dev);
 373        else
 374                return i2c_legacy_resume(dev);
 375}
 376
 377static int i2c_device_pm_poweroff(struct device *dev)
 378{
 379        const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
 380
 381        if (pm)
 382                return pm_generic_poweroff(dev);
 383        else
 384                return i2c_legacy_suspend(dev, PMSG_HIBERNATE);
 385}
 386
 387static int i2c_device_pm_restore(struct device *dev)
 388{
 389        const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
 390
 391        if (pm)
 392                return pm_generic_restore(dev);
 393        else
 394                return i2c_legacy_resume(dev);
 395}
 396#else /* !CONFIG_PM_SLEEP */
 397#define i2c_device_pm_suspend   NULL
 398#define i2c_device_pm_resume    NULL
 399#define i2c_device_pm_freeze    NULL
 400#define i2c_device_pm_thaw      NULL
 401#define i2c_device_pm_poweroff  NULL
 402#define i2c_device_pm_restore   NULL
 403#endif /* !CONFIG_PM_SLEEP */
 404
 405static void i2c_client_dev_release(struct device *dev)
 406{
 407        kfree(to_i2c_client(dev));
 408}
 409
 410static ssize_t
 411show_name(struct device *dev, struct device_attribute *attr, char *buf)
 412{
 413        return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
 414                       to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
 415}
 416
 417static ssize_t
 418show_modalias(struct device *dev, struct device_attribute *attr, char *buf)
 419{
 420        struct i2c_client *client = to_i2c_client(dev);
 421        return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
 422}
 423
 424static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
 425static DEVICE_ATTR(modalias, S_IRUGO, show_modalias, NULL);
 426
 427static struct attribute *i2c_dev_attrs[] = {
 428        &dev_attr_name.attr,
 429        /* modalias helps coldplug:  modprobe $(cat .../modalias) */
 430        &dev_attr_modalias.attr,
 431        NULL
 432};
 433
 434static struct attribute_group i2c_dev_attr_group = {
 435        .attrs          = i2c_dev_attrs,
 436};
 437
 438static const struct attribute_group *i2c_dev_attr_groups[] = {
 439        &i2c_dev_attr_group,
 440        NULL
 441};
 442
 443static const struct dev_pm_ops i2c_device_pm_ops = {
 444        .suspend = i2c_device_pm_suspend,
 445        .resume = i2c_device_pm_resume,
 446        .freeze = i2c_device_pm_freeze,
 447        .thaw = i2c_device_pm_thaw,
 448        .poweroff = i2c_device_pm_poweroff,
 449        .restore = i2c_device_pm_restore,
 450        SET_RUNTIME_PM_OPS(
 451                pm_generic_runtime_suspend,
 452                pm_generic_runtime_resume,
 453                NULL
 454        )
 455};
 456
 457struct bus_type i2c_bus_type = {
 458        .name           = "i2c",
 459        .match          = i2c_device_match,
 460        .probe          = i2c_device_probe,
 461        .remove         = i2c_device_remove,
 462        .shutdown       = i2c_device_shutdown,
 463        .pm             = &i2c_device_pm_ops,
 464};
 465EXPORT_SYMBOL_GPL(i2c_bus_type);
 466
 467static struct device_type i2c_client_type = {
 468        .groups         = i2c_dev_attr_groups,
 469        .uevent         = i2c_device_uevent,
 470        .release        = i2c_client_dev_release,
 471};
 472
 473
 474/**
 475 * i2c_verify_client - return parameter as i2c_client, or NULL
 476 * @dev: device, probably from some driver model iterator
 477 *
 478 * When traversing the driver model tree, perhaps using driver model
 479 * iterators like @device_for_each_child(), you can't assume very much
 480 * about the nodes you find.  Use this function to avoid oopses caused
 481 * by wrongly treating some non-I2C device as an i2c_client.
 482 */
 483struct i2c_client *i2c_verify_client(struct device *dev)
 484{
 485        return (dev->type == &i2c_client_type)
 486                        ? to_i2c_client(dev)
 487                        : NULL;
 488}
 489EXPORT_SYMBOL(i2c_verify_client);
 490
 491
 492/* This is a permissive address validity check, I2C address map constraints
 493 * are purposely not enforced, except for the general call address. */
 494static int i2c_check_client_addr_validity(const struct i2c_client *client)
 495{
 496        if (client->flags & I2C_CLIENT_TEN) {
 497                /* 10-bit address, all values are valid */
 498                if (client->addr > 0x3ff)
 499                        return -EINVAL;
 500        } else {
 501                /* 7-bit address, reject the general call address */
 502                if (client->addr == 0x00 || client->addr > 0x7f)
 503                        return -EINVAL;
 504        }
 505        return 0;
 506}
 507
 508/* And this is a strict address validity check, used when probing. If a
 509 * device uses a reserved address, then it shouldn't be probed. 7-bit
 510 * addressing is assumed, 10-bit address devices are rare and should be
 511 * explicitly enumerated. */
 512static int i2c_check_addr_validity(unsigned short addr)
 513{
 514        /*
 515         * Reserved addresses per I2C specification:
 516         *  0x00       General call address / START byte
 517         *  0x01       CBUS address
 518         *  0x02       Reserved for different bus format
 519         *  0x03       Reserved for future purposes
 520         *  0x04-0x07  Hs-mode master code
 521         *  0x78-0x7b  10-bit slave addressing
 522         *  0x7c-0x7f  Reserved for future purposes
 523         */
 524        if (addr < 0x08 || addr > 0x77)
 525                return -EINVAL;
 526        return 0;
 527}
 528
 529static int __i2c_check_addr_busy(struct device *dev, void *addrp)
 530{
 531        struct i2c_client       *client = i2c_verify_client(dev);
 532        int                     addr = *(int *)addrp;
 533
 534        if (client && client->addr == addr)
 535                return -EBUSY;
 536        return 0;
 537}
 538
 539/* walk up mux tree */
 540static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
 541{
 542        struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
 543        int result;
 544
 545        result = device_for_each_child(&adapter->dev, &addr,
 546                                        __i2c_check_addr_busy);
 547
 548        if (!result && parent)
 549                result = i2c_check_mux_parents(parent, addr);
 550
 551        return result;
 552}
 553
 554/* recurse down mux tree */
 555static int i2c_check_mux_children(struct device *dev, void *addrp)
 556{
 557        int result;
 558
 559        if (dev->type == &i2c_adapter_type)
 560                result = device_for_each_child(dev, addrp,
 561                                                i2c_check_mux_children);
 562        else
 563                result = __i2c_check_addr_busy(dev, addrp);
 564
 565        return result;
 566}
 567
 568static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
 569{
 570        struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
 571        int result = 0;
 572
 573        if (parent)
 574                result = i2c_check_mux_parents(parent, addr);
 575
 576        if (!result)
 577                result = device_for_each_child(&adapter->dev, &addr,
 578                                                i2c_check_mux_children);
 579
 580        return result;
 581}
 582
 583/**
 584 * i2c_lock_adapter - Get exclusive access to an I2C bus segment
 585 * @adapter: Target I2C bus segment
 586 */
 587void i2c_lock_adapter(struct i2c_adapter *adapter)
 588{
 589        struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
 590
 591        if (parent)
 592                i2c_lock_adapter(parent);
 593        else
 594                rt_mutex_lock(&adapter->bus_lock);
 595}
 596EXPORT_SYMBOL_GPL(i2c_lock_adapter);
 597
 598/**
 599 * i2c_trylock_adapter - Try to get exclusive access to an I2C bus segment
 600 * @adapter: Target I2C bus segment
 601 */
 602static int i2c_trylock_adapter(struct i2c_adapter *adapter)
 603{
 604        struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
 605
 606        if (parent)
 607                return i2c_trylock_adapter(parent);
 608        else
 609                return rt_mutex_trylock(&adapter->bus_lock);
 610}
 611
 612/**
 613 * i2c_unlock_adapter - Release exclusive access to an I2C bus segment
 614 * @adapter: Target I2C bus segment
 615 */
 616void i2c_unlock_adapter(struct i2c_adapter *adapter)
 617{
 618        struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
 619
 620        if (parent)
 621                i2c_unlock_adapter(parent);
 622        else
 623                rt_mutex_unlock(&adapter->bus_lock);
 624}
 625EXPORT_SYMBOL_GPL(i2c_unlock_adapter);
 626
 627/**
 628 * i2c_new_device - instantiate an i2c device
 629 * @adap: the adapter managing the device
 630 * @info: describes one I2C device; bus_num is ignored
 631 * Context: can sleep
 632 *
 633 * Create an i2c device. Binding is handled through driver model
 634 * probe()/remove() methods.  A driver may be bound to this device when we
 635 * return from this function, or any later moment (e.g. maybe hotplugging will
 636 * load the driver module).  This call is not appropriate for use by mainboard
 637 * initialization logic, which usually runs during an arch_initcall() long
 638 * before any i2c_adapter could exist.
 639 *
 640 * This returns the new i2c client, which may be saved for later use with
 641 * i2c_unregister_device(); or NULL to indicate an error.
 642 */
 643struct i2c_client *
 644i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
 645{
 646        struct i2c_client       *client;
 647        int                     status;
 648
 649        client = kzalloc(sizeof *client, GFP_KERNEL);
 650        if (!client)
 651                return NULL;
 652
 653        client->adapter = adap;
 654
 655        client->dev.platform_data = info->platform_data;
 656
 657        if (info->archdata)
 658                client->dev.archdata = *info->archdata;
 659
 660        client->flags = info->flags;
 661        client->addr = info->addr;
 662        client->irq = info->irq;
 663
 664        strlcpy(client->name, info->type, sizeof(client->name));
 665
 666        /* Check for address validity */
 667        status = i2c_check_client_addr_validity(client);
 668        if (status) {
 669                dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
 670                        client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
 671                goto out_err_silent;
 672        }
 673
 674        /* Check for address business */
 675        status = i2c_check_addr_busy(adap, client->addr);
 676        if (status)
 677                goto out_err;
 678
 679        client->dev.parent = &client->adapter->dev;
 680        client->dev.bus = &i2c_bus_type;
 681        client->dev.type = &i2c_client_type;
 682        client->dev.of_node = info->of_node;
 683        device_rh_alloc(&client->dev);
 684        set_rh_dev_fwnode(&client->dev, info->fwnode);
 685
 686        /* For 10-bit clients, add an arbitrary offset to avoid collisions */
 687        dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
 688                     client->addr | ((client->flags & I2C_CLIENT_TEN)
 689                                     ? 0xa000 : 0));
 690        status = device_register(&client->dev);
 691        if (status)
 692                goto out_err;
 693
 694        dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
 695                client->name, dev_name(&client->dev));
 696
 697        return client;
 698
 699out_err:
 700        dev_err(&adap->dev, "Failed to register i2c client %s at 0x%02x "
 701                "(%d)\n", client->name, client->addr, status);
 702out_err_silent:
 703        kfree(client);
 704        return NULL;
 705}
 706EXPORT_SYMBOL_GPL(i2c_new_device);
 707
 708
 709/**
 710 * i2c_unregister_device - reverse effect of i2c_new_device()
 711 * @client: value returned from i2c_new_device()
 712 * Context: can sleep
 713 */
 714void i2c_unregister_device(struct i2c_client *client)
 715{
 716        device_unregister(&client->dev);
 717}
 718EXPORT_SYMBOL_GPL(i2c_unregister_device);
 719
 720
 721static const struct i2c_device_id dummy_id[] = {
 722        { "dummy", 0 },
 723        { },
 724};
 725
 726static int dummy_probe(struct i2c_client *client,
 727                       const struct i2c_device_id *id)
 728{
 729        return 0;
 730}
 731
 732static int dummy_remove(struct i2c_client *client)
 733{
 734        return 0;
 735}
 736
 737static struct i2c_driver dummy_driver = {
 738        .driver.name    = "dummy",
 739        .probe          = dummy_probe,
 740        .remove         = dummy_remove,
 741        .id_table       = dummy_id,
 742};
 743
 744/**
 745 * i2c_new_dummy - return a new i2c device bound to a dummy driver
 746 * @adapter: the adapter managing the device
 747 * @address: seven bit address to be used
 748 * Context: can sleep
 749 *
 750 * This returns an I2C client bound to the "dummy" driver, intended for use
 751 * with devices that consume multiple addresses.  Examples of such chips
 752 * include various EEPROMS (like 24c04 and 24c08 models).
 753 *
 754 * These dummy devices have two main uses.  First, most I2C and SMBus calls
 755 * except i2c_transfer() need a client handle; the dummy will be that handle.
 756 * And second, this prevents the specified address from being bound to a
 757 * different driver.
 758 *
 759 * This returns the new i2c client, which should be saved for later use with
 760 * i2c_unregister_device(); or NULL to indicate an error.
 761 */
 762struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
 763{
 764        struct i2c_board_info info = {
 765                I2C_BOARD_INFO("dummy", address),
 766        };
 767
 768        return i2c_new_device(adapter, &info);
 769}
 770EXPORT_SYMBOL_GPL(i2c_new_dummy);
 771
 772/* ------------------------------------------------------------------------- */
 773
 774/* I2C bus adapters -- one roots each I2C or SMBUS segment */
 775
 776static void i2c_adapter_dev_release(struct device *dev)
 777{
 778        struct i2c_adapter *adap = to_i2c_adapter(dev);
 779        complete(&adap->dev_released);
 780}
 781
 782/*
 783 * This function is only needed for mutex_lock_nested, so it is never
 784 * called unless locking correctness checking is enabled. Thus we
 785 * make it inline to avoid a compiler warning. That's what gcc ends up
 786 * doing anyway.
 787 */
 788static inline unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
 789{
 790        unsigned int depth = 0;
 791
 792        while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
 793                depth++;
 794
 795        return depth;
 796}
 797
 798/*
 799 * Let users instantiate I2C devices through sysfs. This can be used when
 800 * platform initialization code doesn't contain the proper data for
 801 * whatever reason. Also useful for drivers that do device detection and
 802 * detection fails, either because the device uses an unexpected address,
 803 * or this is a compatible device with different ID register values.
 804 *
 805 * Parameter checking may look overzealous, but we really don't want
 806 * the user to provide incorrect parameters.
 807 */
 808static ssize_t
 809i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
 810                     const char *buf, size_t count)
 811{
 812        struct i2c_adapter *adap = to_i2c_adapter(dev);
 813        struct i2c_board_info info;
 814        struct i2c_client *client;
 815        char *blank, end;
 816        int res;
 817
 818        memset(&info, 0, sizeof(struct i2c_board_info));
 819
 820        blank = strchr(buf, ' ');
 821        if (!blank) {
 822                dev_err(dev, "%s: Missing parameters\n", "new_device");
 823                return -EINVAL;
 824        }
 825        if (blank - buf > I2C_NAME_SIZE - 1) {
 826                dev_err(dev, "%s: Invalid device name\n", "new_device");
 827                return -EINVAL;
 828        }
 829        memcpy(info.type, buf, blank - buf);
 830
 831        /* Parse remaining parameters, reject extra parameters */
 832        res = sscanf(++blank, "%hi%c", &info.addr, &end);
 833        if (res < 1) {
 834                dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
 835                return -EINVAL;
 836        }
 837        if (res > 1  && end != '\n') {
 838                dev_err(dev, "%s: Extra parameters\n", "new_device");
 839                return -EINVAL;
 840        }
 841
 842        client = i2c_new_device(adap, &info);
 843        if (!client)
 844                return -EINVAL;
 845
 846        /* Keep track of the added device */
 847        mutex_lock(&adap->userspace_clients_lock);
 848        list_add_tail(&client->detected, &adap->userspace_clients);
 849        mutex_unlock(&adap->userspace_clients_lock);
 850        dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
 851                 info.type, info.addr);
 852
 853        return count;
 854}
 855
 856/*
 857 * And of course let the users delete the devices they instantiated, if
 858 * they got it wrong. This interface can only be used to delete devices
 859 * instantiated by i2c_sysfs_new_device above. This guarantees that we
 860 * don't delete devices to which some kernel code still has references.
 861 *
 862 * Parameter checking may look overzealous, but we really don't want
 863 * the user to delete the wrong device.
 864 */
 865static ssize_t
 866i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
 867                        const char *buf, size_t count)
 868{
 869        struct i2c_adapter *adap = to_i2c_adapter(dev);
 870        struct i2c_client *client, *next;
 871        unsigned short addr;
 872        char end;
 873        int res;
 874
 875        /* Parse parameters, reject extra parameters */
 876        res = sscanf(buf, "%hi%c", &addr, &end);
 877        if (res < 1) {
 878                dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
 879                return -EINVAL;
 880        }
 881        if (res > 1  && end != '\n') {
 882                dev_err(dev, "%s: Extra parameters\n", "delete_device");
 883                return -EINVAL;
 884        }
 885
 886        /* Make sure the device was added through sysfs */
 887        res = -ENOENT;
 888        mutex_lock_nested(&adap->userspace_clients_lock,
 889                          i2c_adapter_depth(adap));
 890        list_for_each_entry_safe(client, next, &adap->userspace_clients,
 891                                 detected) {
 892                if (client->addr == addr) {
 893                        dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
 894                                 "delete_device", client->name, client->addr);
 895
 896                        list_del(&client->detected);
 897                        i2c_unregister_device(client);
 898                        res = count;
 899                        break;
 900                }
 901        }
 902        mutex_unlock(&adap->userspace_clients_lock);
 903
 904        if (res < 0)
 905                dev_err(dev, "%s: Can't find device in list\n",
 906                        "delete_device");
 907        return res;
 908}
 909
 910static DEVICE_ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device);
 911static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
 912                                   i2c_sysfs_delete_device);
 913
 914static struct attribute *i2c_adapter_attrs[] = {
 915        &dev_attr_name.attr,
 916        &dev_attr_new_device.attr,
 917        &dev_attr_delete_device.attr,
 918        NULL
 919};
 920
 921static struct attribute_group i2c_adapter_attr_group = {
 922        .attrs          = i2c_adapter_attrs,
 923};
 924
 925static const struct attribute_group *i2c_adapter_attr_groups[] = {
 926        &i2c_adapter_attr_group,
 927        NULL
 928};
 929
 930struct device_type i2c_adapter_type = {
 931        .groups         = i2c_adapter_attr_groups,
 932        .release        = i2c_adapter_dev_release,
 933};
 934EXPORT_SYMBOL_GPL(i2c_adapter_type);
 935
 936/**
 937 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
 938 * @dev: device, probably from some driver model iterator
 939 *
 940 * When traversing the driver model tree, perhaps using driver model
 941 * iterators like @device_for_each_child(), you can't assume very much
 942 * about the nodes you find.  Use this function to avoid oopses caused
 943 * by wrongly treating some non-I2C device as an i2c_adapter.
 944 */
 945struct i2c_adapter *i2c_verify_adapter(struct device *dev)
 946{
 947        return (dev->type == &i2c_adapter_type)
 948                        ? to_i2c_adapter(dev)
 949                        : NULL;
 950}
 951EXPORT_SYMBOL(i2c_verify_adapter);
 952
 953#ifdef CONFIG_I2C_COMPAT
 954static struct class_compat *i2c_adapter_compat_class;
 955#endif
 956
 957static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
 958{
 959        struct i2c_devinfo      *devinfo;
 960
 961        down_read(&__i2c_board_lock);
 962        list_for_each_entry(devinfo, &__i2c_board_list, list) {
 963                if (devinfo->busnum == adapter->nr
 964                                && !i2c_new_device(adapter,
 965                                                &devinfo->board_info))
 966                        dev_err(&adapter->dev,
 967                                "Can't create device at 0x%02x\n",
 968                                devinfo->board_info.addr);
 969        }
 970        up_read(&__i2c_board_lock);
 971}
 972
 973/* ACPI support code */
 974
 975#if IS_ENABLED(CONFIG_ACPI)
 976static int acpi_i2c_add_resource(struct acpi_resource *ares, void *data)
 977{
 978        struct i2c_board_info *info = data;
 979
 980        if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
 981                struct acpi_resource_i2c_serialbus *sb;
 982
 983                sb = &ares->data.i2c_serial_bus;
 984                if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_I2C) {
 985                        info->addr = sb->slave_address;
 986                        if (sb->access_mode == ACPI_I2C_10BIT_MODE)
 987                                info->flags |= I2C_CLIENT_TEN;
 988                }
 989        } else if (!info->irq) {
 990                struct resource r;
 991
 992                if (acpi_dev_resource_interrupt(ares, 0, &r))
 993                        info->irq = r.start;
 994        }
 995
 996        /* Tell the ACPI core to skip this resource */
 997        return 1;
 998}
 999
1000static acpi_status acpi_i2c_add_device(acpi_handle handle, u32 level,
1001                                       void *data, void **return_value)
1002{
1003        struct i2c_adapter *adapter = data;
1004        struct list_head resource_list;
1005        struct i2c_board_info info;
1006        struct acpi_device *adev;
1007        int ret;
1008
1009        if (acpi_bus_get_device(handle, &adev))
1010                return AE_OK;
1011        if (acpi_bus_get_status(adev) || !adev->status.present)
1012                return AE_OK;
1013
1014        memset(&info, 0, sizeof(info));
1015        info.fwnode = acpi_fwnode_handle(adev);
1016
1017        INIT_LIST_HEAD(&resource_list);
1018        ret = acpi_dev_get_resources(adev, &resource_list,
1019                                     acpi_i2c_add_resource, &info);
1020        acpi_dev_free_resource_list(&resource_list);
1021
1022        if (ret < 0 || !info.addr)
1023                return AE_OK;
1024
1025        strlcpy(info.type, dev_name(&adev->dev), sizeof(info.type));
1026        if (!i2c_new_device(adapter, &info)) {
1027                dev_err(&adapter->dev,
1028                        "failed to add I2C device %s from ACPI\n",
1029                        dev_name(&adev->dev));
1030        }
1031
1032        return AE_OK;
1033}
1034
1035/**
1036 * acpi_i2c_register_devices - enumerate I2C slave devices behind adapter
1037 * @adap: pointer to adapter
1038 *
1039 * Enumerate all I2C slave devices behind this adapter by walking the ACPI
1040 * namespace. When a device is found it will be added to the Linux device
1041 * model and bound to the corresponding ACPI handle.
1042 */
1043static void acpi_i2c_register_devices(struct i2c_adapter *adap)
1044{
1045        acpi_handle handle;
1046        acpi_status status;
1047
1048        handle = ACPI_HANDLE(adap->dev.parent);
1049        if (!handle)
1050                return;
1051
1052        status = acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, 1,
1053                                     acpi_i2c_add_device, NULL,
1054                                     adap, NULL);
1055        if (ACPI_FAILURE(status))
1056                dev_warn(&adap->dev, "failed to enumerate I2C slaves\n");
1057}
1058#else
1059static inline void acpi_i2c_register_devices(struct i2c_adapter *adap) {}
1060#endif /* CONFIG_ACPI */
1061
1062/* OF support code */
1063
1064#if IS_ENABLED(CONFIG_OF)
1065static void of_i2c_register_devices(struct i2c_adapter *adap)
1066{
1067        void *result;
1068        struct device_node *node;
1069
1070        /* Only register child devices if the adapter has a node pointer set */
1071        if (!adap->dev.of_node)
1072                return;
1073
1074        dev_dbg(&adap->dev, "of_i2c: walking child nodes\n");
1075
1076        for_each_available_child_of_node(adap->dev.of_node, node) {
1077                struct i2c_board_info info = {};
1078                struct dev_archdata dev_ad = {};
1079                const __be32 *addr;
1080                int len;
1081
1082                dev_dbg(&adap->dev, "of_i2c: register %s\n", node->full_name);
1083
1084                if (of_modalias_node(node, info.type, sizeof(info.type)) < 0) {
1085                        dev_err(&adap->dev, "of_i2c: modalias failure on %s\n",
1086                                node->full_name);
1087                        continue;
1088                }
1089
1090                addr = of_get_property(node, "reg", &len);
1091                if (!addr || (len < sizeof(int))) {
1092                        dev_err(&adap->dev, "of_i2c: invalid reg on %s\n",
1093                                node->full_name);
1094                        continue;
1095                }
1096
1097                info.addr = be32_to_cpup(addr);
1098                if (info.addr > (1 << 10) - 1) {
1099                        dev_err(&adap->dev, "of_i2c: invalid addr=%x on %s\n",
1100                                info.addr, node->full_name);
1101                        continue;
1102                }
1103
1104                info.irq = irq_of_parse_and_map(node, 0);
1105                info.of_node = of_node_get(node);
1106                info.archdata = &dev_ad;
1107
1108                if (of_get_property(node, "wakeup-source", NULL))
1109                        info.flags |= I2C_CLIENT_WAKE;
1110
1111                request_module("%s%s", I2C_MODULE_PREFIX, info.type);
1112
1113                result = i2c_new_device(adap, &info);
1114                if (result == NULL) {
1115                        dev_err(&adap->dev, "of_i2c: Failure registering %s\n",
1116                                node->full_name);
1117                        of_node_put(node);
1118                        irq_dispose_mapping(info.irq);
1119                        continue;
1120                }
1121        }
1122}
1123
1124static int of_dev_node_match(struct device *dev, void *data)
1125{
1126        return dev->of_node == data;
1127}
1128
1129/* must call put_device() when done with returned i2c_client device */
1130struct i2c_client *of_find_i2c_device_by_node(struct device_node *node)
1131{
1132        struct device *dev;
1133
1134        dev = bus_find_device(&i2c_bus_type, NULL, node,
1135                                         of_dev_node_match);
1136        if (!dev)
1137                return NULL;
1138
1139        return i2c_verify_client(dev);
1140}
1141EXPORT_SYMBOL(of_find_i2c_device_by_node);
1142
1143/* must call put_device() when done with returned i2c_adapter device */
1144struct i2c_adapter *of_find_i2c_adapter_by_node(struct device_node *node)
1145{
1146        struct device *dev;
1147
1148        dev = bus_find_device(&i2c_bus_type, NULL, node,
1149                                         of_dev_node_match);
1150        if (!dev)
1151                return NULL;
1152
1153        return i2c_verify_adapter(dev);
1154}
1155EXPORT_SYMBOL(of_find_i2c_adapter_by_node);
1156#else
1157static void of_i2c_register_devices(struct i2c_adapter *adap) { }
1158#endif /* CONFIG_OF */
1159
1160static int i2c_do_add_adapter(struct i2c_driver *driver,
1161                              struct i2c_adapter *adap)
1162{
1163        /* Detect supported devices on that bus, and instantiate them */
1164        i2c_detect(adap, driver);
1165
1166        /* Let legacy drivers scan this bus for matching devices */
1167        if (driver->attach_adapter) {
1168                dev_warn(&adap->dev, "%s: attach_adapter method is deprecated\n",
1169                         driver->driver.name);
1170                dev_warn(&adap->dev, "Please use another way to instantiate "
1171                         "your i2c_client\n");
1172                /* We ignore the return code; if it fails, too bad */
1173                driver->attach_adapter(adap);
1174        }
1175        return 0;
1176}
1177
1178static int __process_new_adapter(struct device_driver *d, void *data)
1179{
1180        return i2c_do_add_adapter(to_i2c_driver(d), data);
1181}
1182
1183static int i2c_register_adapter(struct i2c_adapter *adap)
1184{
1185        int res = 0;
1186
1187        /* Can't register until after driver model init */
1188        if (unlikely(WARN_ON(!i2c_bus_type.p))) {
1189                res = -EAGAIN;
1190                goto out_list;
1191        }
1192
1193        /* Sanity checks */
1194        if (unlikely(adap->name[0] == '\0')) {
1195                pr_err("i2c-core: Attempt to register an adapter with "
1196                       "no name!\n");
1197                return -EINVAL;
1198        }
1199        if (unlikely(!adap->algo)) {
1200                pr_err("i2c-core: Attempt to register adapter '%s' with "
1201                       "no algo!\n", adap->name);
1202                return -EINVAL;
1203        }
1204
1205        rt_mutex_init(&adap->bus_lock);
1206        mutex_init(&adap->userspace_clients_lock);
1207        INIT_LIST_HEAD(&adap->userspace_clients);
1208
1209        /* Set default timeout to 1 second if not already set */
1210        if (adap->timeout == 0)
1211                adap->timeout = HZ;
1212
1213        dev_set_name(&adap->dev, "i2c-%d", adap->nr);
1214        adap->dev.bus = &i2c_bus_type;
1215        adap->dev.type = &i2c_adapter_type;
1216        res = device_register(&adap->dev);
1217        if (res)
1218                goto out_list;
1219
1220        dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
1221
1222#ifdef CONFIG_I2C_COMPAT
1223        res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
1224                                       adap->dev.parent);
1225        if (res)
1226                dev_warn(&adap->dev,
1227                         "Failed to create compatibility class link\n");
1228#endif
1229
1230        /* bus recovery specific initialization */
1231        if (adap->bus_recovery_info) {
1232                struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
1233
1234                if (!bri->recover_bus) {
1235                        dev_err(&adap->dev, "No recover_bus() found, not using recovery\n");
1236                        adap->bus_recovery_info = NULL;
1237                        goto exit_recovery;
1238                }
1239
1240                /* Generic GPIO recovery */
1241                if (bri->recover_bus == i2c_generic_gpio_recovery) {
1242                        if (!gpio_is_valid(bri->scl_gpio)) {
1243                                dev_err(&adap->dev, "Invalid SCL gpio, not using recovery\n");
1244                                adap->bus_recovery_info = NULL;
1245                                goto exit_recovery;
1246                        }
1247
1248                        if (gpio_is_valid(bri->sda_gpio))
1249                                bri->get_sda = get_sda_gpio_value;
1250                        else
1251                                bri->get_sda = NULL;
1252
1253                        bri->get_scl = get_scl_gpio_value;
1254                        bri->set_scl = set_scl_gpio_value;
1255                } else if (!bri->set_scl || !bri->get_scl) {
1256                        /* Generic SCL recovery */
1257                        dev_err(&adap->dev, "No {get|set}_gpio() found, not using recovery\n");
1258                        adap->bus_recovery_info = NULL;
1259                }
1260        }
1261
1262exit_recovery:
1263        /* create pre-declared device nodes */
1264        of_i2c_register_devices(adap);
1265        acpi_i2c_register_devices(adap);
1266
1267        if (adap->nr < __i2c_first_dynamic_bus_num)
1268                i2c_scan_static_board_info(adap);
1269
1270        /* Notify drivers */
1271        mutex_lock(&core_lock);
1272        bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
1273        mutex_unlock(&core_lock);
1274
1275        return 0;
1276
1277out_list:
1278        mutex_lock(&core_lock);
1279        idr_remove(&i2c_adapter_idr, adap->nr);
1280        mutex_unlock(&core_lock);
1281        return res;
1282}
1283
1284/**
1285 * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
1286 * @adap: the adapter to register (with adap->nr initialized)
1287 * Context: can sleep
1288 *
1289 * See i2c_add_numbered_adapter() for details.
1290 */
1291static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
1292{
1293        int     id;
1294
1295        mutex_lock(&core_lock);
1296        id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1,
1297                       GFP_KERNEL);
1298        mutex_unlock(&core_lock);
1299        if (id < 0)
1300                return id == -ENOSPC ? -EBUSY : id;
1301
1302        return i2c_register_adapter(adap);
1303}
1304
1305/**
1306 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
1307 * @adapter: the adapter to add
1308 * Context: can sleep
1309 *
1310 * This routine is used to declare an I2C adapter when its bus number
1311 * doesn't matter or when its bus number is specified by an dt alias.
1312 * Examples of bases when the bus number doesn't matter: I2C adapters
1313 * dynamically added by USB links or PCI plugin cards.
1314 *
1315 * When this returns zero, a new bus number was allocated and stored
1316 * in adap->nr, and the specified adapter became available for clients.
1317 * Otherwise, a negative errno value is returned.
1318 */
1319int i2c_add_adapter(struct i2c_adapter *adapter)
1320{
1321        struct device *dev = &adapter->dev;
1322        int id;
1323
1324        if (dev->of_node) {
1325                id = of_alias_get_id(dev->of_node, "i2c");
1326                if (id >= 0) {
1327                        adapter->nr = id;
1328                        return __i2c_add_numbered_adapter(adapter);
1329                }
1330        }
1331
1332        mutex_lock(&core_lock);
1333        id = idr_alloc(&i2c_adapter_idr, adapter,
1334                       __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
1335        mutex_unlock(&core_lock);
1336        if (id < 0)
1337                return id;
1338
1339        adapter->nr = id;
1340
1341        return i2c_register_adapter(adapter);
1342}
1343EXPORT_SYMBOL(i2c_add_adapter);
1344
1345/**
1346 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
1347 * @adap: the adapter to register (with adap->nr initialized)
1348 * Context: can sleep
1349 *
1350 * This routine is used to declare an I2C adapter when its bus number
1351 * matters.  For example, use it for I2C adapters from system-on-chip CPUs,
1352 * or otherwise built in to the system's mainboard, and where i2c_board_info
1353 * is used to properly configure I2C devices.
1354 *
1355 * If the requested bus number is set to -1, then this function will behave
1356 * identically to i2c_add_adapter, and will dynamically assign a bus number.
1357 *
1358 * If no devices have pre-been declared for this bus, then be sure to
1359 * register the adapter before any dynamically allocated ones.  Otherwise
1360 * the required bus ID may not be available.
1361 *
1362 * When this returns zero, the specified adapter became available for
1363 * clients using the bus number provided in adap->nr.  Also, the table
1364 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
1365 * and the appropriate driver model device nodes are created.  Otherwise, a
1366 * negative errno value is returned.
1367 */
1368int i2c_add_numbered_adapter(struct i2c_adapter *adap)
1369{
1370        if (adap->nr == -1) /* -1 means dynamically assign bus id */
1371                return i2c_add_adapter(adap);
1372
1373        return __i2c_add_numbered_adapter(adap);
1374}
1375EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
1376
1377static void i2c_do_del_adapter(struct i2c_driver *driver,
1378                              struct i2c_adapter *adapter)
1379{
1380        struct i2c_client *client, *_n;
1381
1382        /* Remove the devices we created ourselves as the result of hardware
1383         * probing (using a driver's detect method) */
1384        list_for_each_entry_safe(client, _n, &driver->clients, detected) {
1385                if (client->adapter == adapter) {
1386                        dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
1387                                client->name, client->addr);
1388                        list_del(&client->detected);
1389                        i2c_unregister_device(client);
1390                }
1391        }
1392}
1393
1394static int __unregister_client(struct device *dev, void *dummy)
1395{
1396        struct i2c_client *client = i2c_verify_client(dev);
1397        if (client && strcmp(client->name, "dummy"))
1398                i2c_unregister_device(client);
1399        return 0;
1400}
1401
1402static int __unregister_dummy(struct device *dev, void *dummy)
1403{
1404        struct i2c_client *client = i2c_verify_client(dev);
1405        if (client)
1406                i2c_unregister_device(client);
1407        return 0;
1408}
1409
1410static int __process_removed_adapter(struct device_driver *d, void *data)
1411{
1412        i2c_do_del_adapter(to_i2c_driver(d), data);
1413        return 0;
1414}
1415
1416/**
1417 * i2c_del_adapter - unregister I2C adapter
1418 * @adap: the adapter being unregistered
1419 * Context: can sleep
1420 *
1421 * This unregisters an I2C adapter which was previously registered
1422 * by @i2c_add_adapter or @i2c_add_numbered_adapter.
1423 */
1424void i2c_del_adapter(struct i2c_adapter *adap)
1425{
1426        struct i2c_adapter *found;
1427        struct i2c_client *client, *next;
1428
1429        /* First make sure that this adapter was ever added */
1430        mutex_lock(&core_lock);
1431        found = idr_find(&i2c_adapter_idr, adap->nr);
1432        mutex_unlock(&core_lock);
1433        if (found != adap) {
1434                pr_debug("i2c-core: attempting to delete unregistered "
1435                         "adapter [%s]\n", adap->name);
1436                return;
1437        }
1438
1439        /* Tell drivers about this removal */
1440        mutex_lock(&core_lock);
1441        bus_for_each_drv(&i2c_bus_type, NULL, adap,
1442                               __process_removed_adapter);
1443        mutex_unlock(&core_lock);
1444
1445        /* Remove devices instantiated from sysfs */
1446        mutex_lock_nested(&adap->userspace_clients_lock,
1447                          i2c_adapter_depth(adap));
1448        list_for_each_entry_safe(client, next, &adap->userspace_clients,
1449                                 detected) {
1450                dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
1451                        client->addr);
1452                list_del(&client->detected);
1453                i2c_unregister_device(client);
1454        }
1455        mutex_unlock(&adap->userspace_clients_lock);
1456
1457        /* Detach any active clients. This can't fail, thus we do not
1458         * check the returned value. This is a two-pass process, because
1459         * we can't remove the dummy devices during the first pass: they
1460         * could have been instantiated by real devices wishing to clean
1461         * them up properly, so we give them a chance to do that first. */
1462        device_for_each_child(&adap->dev, NULL, __unregister_client);
1463        device_for_each_child(&adap->dev, NULL, __unregister_dummy);
1464
1465#ifdef CONFIG_I2C_COMPAT
1466        class_compat_remove_link(i2c_adapter_compat_class, &adap->dev,
1467                                 adap->dev.parent);
1468#endif
1469
1470        /* device name is gone after device_unregister */
1471        dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
1472
1473        /* clean up the sysfs representation */
1474        init_completion(&adap->dev_released);
1475        device_unregister(&adap->dev);
1476
1477        /* wait for sysfs to drop all references */
1478        wait_for_completion(&adap->dev_released);
1479
1480        /* free bus id */
1481        mutex_lock(&core_lock);
1482        idr_remove(&i2c_adapter_idr, adap->nr);
1483        mutex_unlock(&core_lock);
1484
1485        /* Clear the device structure in case this adapter is ever going to be
1486           added again */
1487        memset(&adap->dev, 0, sizeof(adap->dev));
1488}
1489EXPORT_SYMBOL(i2c_del_adapter);
1490
1491/* ------------------------------------------------------------------------- */
1492
1493int i2c_for_each_dev(void *data, int (*fn)(struct device *, void *))
1494{
1495        int res;
1496
1497        mutex_lock(&core_lock);
1498        res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
1499        mutex_unlock(&core_lock);
1500
1501        return res;
1502}
1503EXPORT_SYMBOL_GPL(i2c_for_each_dev);
1504
1505static int __process_new_driver(struct device *dev, void *data)
1506{
1507        if (dev->type != &i2c_adapter_type)
1508                return 0;
1509        return i2c_do_add_adapter(data, to_i2c_adapter(dev));
1510}
1511
1512/*
1513 * An i2c_driver is used with one or more i2c_client (device) nodes to access
1514 * i2c slave chips, on a bus instance associated with some i2c_adapter.
1515 */
1516
1517int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
1518{
1519        int res;
1520
1521        /* Can't register until after driver model init */
1522        if (unlikely(WARN_ON(!i2c_bus_type.p)))
1523                return -EAGAIN;
1524
1525        /* add the driver to the list of i2c drivers in the driver core */
1526        driver->driver.owner = owner;
1527        driver->driver.bus = &i2c_bus_type;
1528
1529        /* When registration returns, the driver core
1530         * will have called probe() for all matching-but-unbound devices.
1531         */
1532        res = driver_register(&driver->driver);
1533        if (res)
1534                return res;
1535
1536        /* Drivers should switch to dev_pm_ops instead. */
1537        if (driver->suspend)
1538                pr_warn("i2c-core: driver [%s] using legacy suspend method\n",
1539                        driver->driver.name);
1540        if (driver->resume)
1541                pr_warn("i2c-core: driver [%s] using legacy resume method\n",
1542                        driver->driver.name);
1543
1544        pr_debug("i2c-core: driver [%s] registered\n", driver->driver.name);
1545
1546        INIT_LIST_HEAD(&driver->clients);
1547        /* Walk the adapters that are already present */
1548        i2c_for_each_dev(driver, __process_new_driver);
1549
1550        return 0;
1551}
1552EXPORT_SYMBOL(i2c_register_driver);
1553
1554static int __process_removed_driver(struct device *dev, void *data)
1555{
1556        if (dev->type == &i2c_adapter_type)
1557                i2c_do_del_adapter(data, to_i2c_adapter(dev));
1558        return 0;
1559}
1560
1561/**
1562 * i2c_del_driver - unregister I2C driver
1563 * @driver: the driver being unregistered
1564 * Context: can sleep
1565 */
1566void i2c_del_driver(struct i2c_driver *driver)
1567{
1568        i2c_for_each_dev(driver, __process_removed_driver);
1569
1570        driver_unregister(&driver->driver);
1571        pr_debug("i2c-core: driver [%s] unregistered\n", driver->driver.name);
1572}
1573EXPORT_SYMBOL(i2c_del_driver);
1574
1575/* ------------------------------------------------------------------------- */
1576
1577/**
1578 * i2c_use_client - increments the reference count of the i2c client structure
1579 * @client: the client being referenced
1580 *
1581 * Each live reference to a client should be refcounted. The driver model does
1582 * that automatically as part of driver binding, so that most drivers don't
1583 * need to do this explicitly: they hold a reference until they're unbound
1584 * from the device.
1585 *
1586 * A pointer to the client with the incremented reference counter is returned.
1587 */
1588struct i2c_client *i2c_use_client(struct i2c_client *client)
1589{
1590        if (client && get_device(&client->dev))
1591                return client;
1592        return NULL;
1593}
1594EXPORT_SYMBOL(i2c_use_client);
1595
1596/**
1597 * i2c_release_client - release a use of the i2c client structure
1598 * @client: the client being no longer referenced
1599 *
1600 * Must be called when a user of a client is finished with it.
1601 */
1602void i2c_release_client(struct i2c_client *client)
1603{
1604        if (client)
1605                put_device(&client->dev);
1606}
1607EXPORT_SYMBOL(i2c_release_client);
1608
1609struct i2c_cmd_arg {
1610        unsigned        cmd;
1611        void            *arg;
1612};
1613
1614static int i2c_cmd(struct device *dev, void *_arg)
1615{
1616        struct i2c_client       *client = i2c_verify_client(dev);
1617        struct i2c_cmd_arg      *arg = _arg;
1618
1619        if (client && client->driver && client->driver->command)
1620                client->driver->command(client, arg->cmd, arg->arg);
1621        return 0;
1622}
1623
1624void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
1625{
1626        struct i2c_cmd_arg      cmd_arg;
1627
1628        cmd_arg.cmd = cmd;
1629        cmd_arg.arg = arg;
1630        device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
1631}
1632EXPORT_SYMBOL(i2c_clients_command);
1633
1634static int __init i2c_init(void)
1635{
1636        int retval;
1637
1638        retval = bus_register(&i2c_bus_type);
1639        if (retval)
1640                return retval;
1641#ifdef CONFIG_I2C_COMPAT
1642        i2c_adapter_compat_class = class_compat_register("i2c-adapter");
1643        if (!i2c_adapter_compat_class) {
1644                retval = -ENOMEM;
1645                goto bus_err;
1646        }
1647#endif
1648        retval = i2c_add_driver(&dummy_driver);
1649        if (retval)
1650                goto class_err;
1651        return 0;
1652
1653class_err:
1654#ifdef CONFIG_I2C_COMPAT
1655        class_compat_unregister(i2c_adapter_compat_class);
1656bus_err:
1657#endif
1658        bus_unregister(&i2c_bus_type);
1659        return retval;
1660}
1661
1662static void __exit i2c_exit(void)
1663{
1664        i2c_del_driver(&dummy_driver);
1665#ifdef CONFIG_I2C_COMPAT
1666        class_compat_unregister(i2c_adapter_compat_class);
1667#endif
1668        bus_unregister(&i2c_bus_type);
1669}
1670
1671/* We must initialize early, because some subsystems register i2c drivers
1672 * in subsys_initcall() code, but are linked (and initialized) before i2c.
1673 */
1674postcore_initcall(i2c_init);
1675module_exit(i2c_exit);
1676
1677/* ----------------------------------------------------
1678 * the functional interface to the i2c busses.
1679 * ----------------------------------------------------
1680 */
1681
1682/* Check if val is exceeding the quirk IFF quirk is non 0 */
1683#define i2c_quirk_exceeded(val, quirk) ((quirk) && ((val) > (quirk)))
1684
1685static int i2c_quirk_error(struct i2c_adapter *adap, struct i2c_msg *msg, char *err_msg)
1686{
1687        dev_err_ratelimited(&adap->dev, "adapter quirk: %s (addr 0x%04x, size %u, %s)\n",
1688                            err_msg, msg->addr, msg->len,
1689                            msg->flags & I2C_M_RD ? "read" : "write");
1690        return -EOPNOTSUPP;
1691}
1692
1693static int i2c_check_for_quirks(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1694{
1695        const struct i2c_adapter_quirks *q = adap->quirks;
1696        int max_num = q->max_num_msgs, i;
1697        bool do_len_check = true;
1698
1699        if (q->flags & I2C_AQ_COMB) {
1700                max_num = 2;
1701
1702                /* special checks for combined messages */
1703                if (num == 2) {
1704                        if (q->flags & I2C_AQ_COMB_WRITE_FIRST && msgs[0].flags & I2C_M_RD)
1705                                return i2c_quirk_error(adap, &msgs[0], "1st comb msg must be write");
1706
1707                        if (q->flags & I2C_AQ_COMB_READ_SECOND && !(msgs[1].flags & I2C_M_RD))
1708                                return i2c_quirk_error(adap, &msgs[1], "2nd comb msg must be read");
1709
1710                        if (q->flags & I2C_AQ_COMB_SAME_ADDR && msgs[0].addr != msgs[1].addr)
1711                                return i2c_quirk_error(adap, &msgs[0], "comb msg only to same addr");
1712
1713                        if (i2c_quirk_exceeded(msgs[0].len, q->max_comb_1st_msg_len))
1714                                return i2c_quirk_error(adap, &msgs[0], "msg too long");
1715
1716                        if (i2c_quirk_exceeded(msgs[1].len, q->max_comb_2nd_msg_len))
1717                                return i2c_quirk_error(adap, &msgs[1], "msg too long");
1718
1719                        do_len_check = false;
1720                }
1721        }
1722
1723        if (i2c_quirk_exceeded(num, max_num))
1724                return i2c_quirk_error(adap, &msgs[0], "too many messages");
1725
1726        for (i = 0; i < num; i++) {
1727                u16 len = msgs[i].len;
1728
1729                if (msgs[i].flags & I2C_M_RD) {
1730                        if (do_len_check && i2c_quirk_exceeded(len, q->max_read_len))
1731                                return i2c_quirk_error(adap, &msgs[i], "msg too long");
1732                } else {
1733                        if (do_len_check && i2c_quirk_exceeded(len, q->max_write_len))
1734                                return i2c_quirk_error(adap, &msgs[i], "msg too long");
1735                }
1736        }
1737
1738        return 0;
1739}
1740
1741/**
1742 * __i2c_transfer - unlocked flavor of i2c_transfer
1743 * @adap: Handle to I2C bus
1744 * @msgs: One or more messages to execute before STOP is issued to
1745 *      terminate the operation; each message begins with a START.
1746 * @num: Number of messages to be executed.
1747 *
1748 * Returns negative errno, else the number of messages executed.
1749 *
1750 * Adapter lock must be held when calling this function. No debug logging
1751 * takes place. adap->algo->master_xfer existence isn't checked.
1752 */
1753int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1754{
1755        unsigned long orig_jiffies;
1756        int ret, try;
1757
1758        if (adap->quirks && i2c_check_for_quirks(adap, msgs, num))
1759                return -EOPNOTSUPP;
1760
1761        /* Retry automatically on arbitration loss */
1762        orig_jiffies = jiffies;
1763        for (ret = 0, try = 0; try <= adap->retries; try++) {
1764                ret = adap->algo->master_xfer(adap, msgs, num);
1765                if (ret != -EAGAIN)
1766                        break;
1767                if (time_after(jiffies, orig_jiffies + adap->timeout))
1768                        break;
1769        }
1770
1771        return ret;
1772}
1773EXPORT_SYMBOL(__i2c_transfer);
1774
1775/**
1776 * i2c_transfer - execute a single or combined I2C message
1777 * @adap: Handle to I2C bus
1778 * @msgs: One or more messages to execute before STOP is issued to
1779 *      terminate the operation; each message begins with a START.
1780 * @num: Number of messages to be executed.
1781 *
1782 * Returns negative errno, else the number of messages executed.
1783 *
1784 * Note that there is no requirement that each message be sent to
1785 * the same slave address, although that is the most common model.
1786 */
1787int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1788{
1789        int ret;
1790
1791        /* REVISIT the fault reporting model here is weak:
1792         *
1793         *  - When we get an error after receiving N bytes from a slave,
1794         *    there is no way to report "N".
1795         *
1796         *  - When we get a NAK after transmitting N bytes to a slave,
1797         *    there is no way to report "N" ... or to let the master
1798         *    continue executing the rest of this combined message, if
1799         *    that's the appropriate response.
1800         *
1801         *  - When for example "num" is two and we successfully complete
1802         *    the first message but get an error part way through the
1803         *    second, it's unclear whether that should be reported as
1804         *    one (discarding status on the second message) or errno
1805         *    (discarding status on the first one).
1806         */
1807
1808        if (adap->algo->master_xfer) {
1809#ifdef DEBUG
1810                for (ret = 0; ret < num; ret++) {
1811                        dev_dbg(&adap->dev, "master_xfer[%d] %c, addr=0x%02x, "
1812                                "len=%d%s\n", ret, (msgs[ret].flags & I2C_M_RD)
1813                                ? 'R' : 'W', msgs[ret].addr, msgs[ret].len,
1814                                (msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
1815                }
1816#endif
1817
1818                if (in_atomic() || irqs_disabled()) {
1819                        ret = i2c_trylock_adapter(adap);
1820                        if (!ret)
1821                                /* I2C activity is ongoing. */
1822                                return -EAGAIN;
1823                } else {
1824                        i2c_lock_adapter(adap);
1825                }
1826
1827                ret = __i2c_transfer(adap, msgs, num);
1828                i2c_unlock_adapter(adap);
1829
1830                return ret;
1831        } else {
1832                dev_dbg(&adap->dev, "I2C level transfers not supported\n");
1833                return -EOPNOTSUPP;
1834        }
1835}
1836EXPORT_SYMBOL(i2c_transfer);
1837
1838/**
1839 * i2c_master_send - issue a single I2C message in master transmit mode
1840 * @client: Handle to slave device
1841 * @buf: Data that will be written to the slave
1842 * @count: How many bytes to write, must be less than 64k since msg.len is u16
1843 *
1844 * Returns negative errno, or else the number of bytes written.
1845 */
1846int i2c_master_send(const struct i2c_client *client, const char *buf, int count)
1847{
1848        int ret;
1849        struct i2c_adapter *adap = client->adapter;
1850        struct i2c_msg msg;
1851
1852        msg.addr = client->addr;
1853        msg.flags = client->flags & I2C_M_TEN;
1854        msg.len = count;
1855        msg.buf = (char *)buf;
1856
1857        ret = i2c_transfer(adap, &msg, 1);
1858
1859        /*
1860         * If everything went ok (i.e. 1 msg transmitted), return #bytes
1861         * transmitted, else error code.
1862         */
1863        return (ret == 1) ? count : ret;
1864}
1865EXPORT_SYMBOL(i2c_master_send);
1866
1867/**
1868 * i2c_master_recv - issue a single I2C message in master receive mode
1869 * @client: Handle to slave device
1870 * @buf: Where to store data read from slave
1871 * @count: How many bytes to read, must be less than 64k since msg.len is u16
1872 *
1873 * Returns negative errno, or else the number of bytes read.
1874 */
1875int i2c_master_recv(const struct i2c_client *client, char *buf, int count)
1876{
1877        struct i2c_adapter *adap = client->adapter;
1878        struct i2c_msg msg;
1879        int ret;
1880
1881        msg.addr = client->addr;
1882        msg.flags = client->flags & I2C_M_TEN;
1883        msg.flags |= I2C_M_RD;
1884        msg.len = count;
1885        msg.buf = buf;
1886
1887        ret = i2c_transfer(adap, &msg, 1);
1888
1889        /*
1890         * If everything went ok (i.e. 1 msg received), return #bytes received,
1891         * else error code.
1892         */
1893        return (ret == 1) ? count : ret;
1894}
1895EXPORT_SYMBOL(i2c_master_recv);
1896
1897/* ----------------------------------------------------
1898 * the i2c address scanning function
1899 * Will not work for 10-bit addresses!
1900 * ----------------------------------------------------
1901 */
1902
1903/*
1904 * Legacy default probe function, mostly relevant for SMBus. The default
1905 * probe method is a quick write, but it is known to corrupt the 24RF08
1906 * EEPROMs due to a state machine bug, and could also irreversibly
1907 * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
1908 * we use a short byte read instead. Also, some bus drivers don't implement
1909 * quick write, so we fallback to a byte read in that case too.
1910 * On x86, there is another special case for FSC hardware monitoring chips,
1911 * which want regular byte reads (address 0x73.) Fortunately, these are the
1912 * only known chips using this I2C address on PC hardware.
1913 * Returns 1 if probe succeeded, 0 if not.
1914 */
1915static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
1916{
1917        int err;
1918        union i2c_smbus_data dummy;
1919
1920#ifdef CONFIG_X86
1921        if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
1922         && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
1923                err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
1924                                     I2C_SMBUS_BYTE_DATA, &dummy);
1925        else
1926#endif
1927        if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
1928         && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
1929                err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
1930                                     I2C_SMBUS_QUICK, NULL);
1931        else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
1932                err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
1933                                     I2C_SMBUS_BYTE, &dummy);
1934        else {
1935                dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n",
1936                         addr);
1937                err = -EOPNOTSUPP;
1938        }
1939
1940        return err >= 0;
1941}
1942
1943static int i2c_detect_address(struct i2c_client *temp_client,
1944                              struct i2c_driver *driver)
1945{
1946        struct i2c_board_info info;
1947        struct i2c_adapter *adapter = temp_client->adapter;
1948        int addr = temp_client->addr;
1949        int err;
1950
1951        /* Make sure the address is valid */
1952        err = i2c_check_addr_validity(addr);
1953        if (err) {
1954                dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
1955                         addr);
1956                return err;
1957        }
1958
1959        /* Skip if already in use */
1960        if (i2c_check_addr_busy(adapter, addr))
1961                return 0;
1962
1963        /* Make sure there is something at this address */
1964        if (!i2c_default_probe(adapter, addr))
1965                return 0;
1966
1967        /* Finally call the custom detection function */
1968        memset(&info, 0, sizeof(struct i2c_board_info));
1969        info.addr = addr;
1970        err = driver->detect(temp_client, &info);
1971        if (err) {
1972                /* -ENODEV is returned if the detection fails. We catch it
1973                   here as this isn't an error. */
1974                return err == -ENODEV ? 0 : err;
1975        }
1976
1977        /* Consistency check */
1978        if (info.type[0] == '\0') {
1979                dev_err(&adapter->dev, "%s detection function provided "
1980                        "no name for 0x%x\n", driver->driver.name,
1981                        addr);
1982        } else {
1983                struct i2c_client *client;
1984
1985                /* Detection succeeded, instantiate the device */
1986                dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
1987                        info.type, info.addr);
1988                client = i2c_new_device(adapter, &info);
1989                if (client)
1990                        list_add_tail(&client->detected, &driver->clients);
1991                else
1992                        dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
1993                                info.type, info.addr);
1994        }
1995        return 0;
1996}
1997
1998static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
1999{
2000        const unsigned short *address_list;
2001        struct i2c_client *temp_client;
2002        int i, err = 0;
2003        int adap_id = i2c_adapter_id(adapter);
2004
2005        address_list = driver->address_list;
2006        if (!driver->detect || !address_list)
2007                return 0;
2008
2009        /* Stop here if the classes do not match */
2010        if (!(adapter->class & driver->class))
2011                return 0;
2012
2013        /* Set up a temporary client to help detect callback */
2014        temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
2015        if (!temp_client)
2016                return -ENOMEM;
2017        temp_client->adapter = adapter;
2018
2019        for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
2020                dev_dbg(&adapter->dev, "found normal entry for adapter %d, "
2021                        "addr 0x%02x\n", adap_id, address_list[i]);
2022                temp_client->addr = address_list[i];
2023                err = i2c_detect_address(temp_client, driver);
2024                if (unlikely(err))
2025                        break;
2026        }
2027
2028        kfree(temp_client);
2029        return err;
2030}
2031
2032int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
2033{
2034        return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2035                              I2C_SMBUS_QUICK, NULL) >= 0;
2036}
2037EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
2038
2039struct i2c_client *
2040i2c_new_probed_device(struct i2c_adapter *adap,
2041                      struct i2c_board_info *info,
2042                      unsigned short const *addr_list,
2043                      int (*probe)(struct i2c_adapter *, unsigned short addr))
2044{
2045        int i;
2046
2047        if (!probe)
2048                probe = i2c_default_probe;
2049
2050        for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
2051                /* Check address validity */
2052                if (i2c_check_addr_validity(addr_list[i]) < 0) {
2053                        dev_warn(&adap->dev, "Invalid 7-bit address "
2054                                 "0x%02x\n", addr_list[i]);
2055                        continue;
2056                }
2057
2058                /* Check address availability */
2059                if (i2c_check_addr_busy(adap, addr_list[i])) {
2060                        dev_dbg(&adap->dev, "Address 0x%02x already in "
2061                                "use, not probing\n", addr_list[i]);
2062                        continue;
2063                }
2064
2065                /* Test address responsiveness */
2066                if (probe(adap, addr_list[i]))
2067                        break;
2068        }
2069
2070        if (addr_list[i] == I2C_CLIENT_END) {
2071                dev_dbg(&adap->dev, "Probing failed, no device found\n");
2072                return NULL;
2073        }
2074
2075        info->addr = addr_list[i];
2076        return i2c_new_device(adap, info);
2077}
2078EXPORT_SYMBOL_GPL(i2c_new_probed_device);
2079
2080struct i2c_adapter *i2c_get_adapter(int nr)
2081{
2082        struct i2c_adapter *adapter;
2083
2084        mutex_lock(&core_lock);
2085        adapter = idr_find(&i2c_adapter_idr, nr);
2086        if (adapter && !try_module_get(adapter->owner))
2087                adapter = NULL;
2088
2089        mutex_unlock(&core_lock);
2090        return adapter;
2091}
2092EXPORT_SYMBOL(i2c_get_adapter);
2093
2094void i2c_put_adapter(struct i2c_adapter *adap)
2095{
2096        if (adap)
2097                module_put(adap->owner);
2098}
2099EXPORT_SYMBOL(i2c_put_adapter);
2100
2101/* The SMBus parts */
2102
2103#define POLY    (0x1070U << 3)
2104static u8 crc8(u16 data)
2105{
2106        int i;
2107
2108        for (i = 0; i < 8; i++) {
2109                if (data & 0x8000)
2110                        data = data ^ POLY;
2111                data = data << 1;
2112        }
2113        return (u8)(data >> 8);
2114}
2115
2116/* Incremental CRC8 over count bytes in the array pointed to by p */
2117static u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
2118{
2119        int i;
2120
2121        for (i = 0; i < count; i++)
2122                crc = crc8((crc ^ p[i]) << 8);
2123        return crc;
2124}
2125
2126/* Assume a 7-bit address, which is reasonable for SMBus */
2127static u8 i2c_smbus_msg_pec(u8 pec, struct i2c_msg *msg)
2128{
2129        /* The address will be sent first */
2130        u8 addr = (msg->addr << 1) | !!(msg->flags & I2C_M_RD);
2131        pec = i2c_smbus_pec(pec, &addr, 1);
2132
2133        /* The data buffer follows */
2134        return i2c_smbus_pec(pec, msg->buf, msg->len);
2135}
2136
2137/* Used for write only transactions */
2138static inline void i2c_smbus_add_pec(struct i2c_msg *msg)
2139{
2140        msg->buf[msg->len] = i2c_smbus_msg_pec(0, msg);
2141        msg->len++;
2142}
2143
2144/* Return <0 on CRC error
2145   If there was a write before this read (most cases) we need to take the
2146   partial CRC from the write part into account.
2147   Note that this function does modify the message (we need to decrease the
2148   message length to hide the CRC byte from the caller). */
2149static int i2c_smbus_check_pec(u8 cpec, struct i2c_msg *msg)
2150{
2151        u8 rpec = msg->buf[--msg->len];
2152        cpec = i2c_smbus_msg_pec(cpec, msg);
2153
2154        if (rpec != cpec) {
2155                pr_debug("i2c-core: Bad PEC 0x%02x vs. 0x%02x\n",
2156                        rpec, cpec);
2157                return -EBADMSG;
2158        }
2159        return 0;
2160}
2161
2162/**
2163 * i2c_smbus_read_byte - SMBus "receive byte" protocol
2164 * @client: Handle to slave device
2165 *
2166 * This executes the SMBus "receive byte" protocol, returning negative errno
2167 * else the byte received from the device.
2168 */
2169s32 i2c_smbus_read_byte(const struct i2c_client *client)
2170{
2171        union i2c_smbus_data data;
2172        int status;
2173
2174        status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2175                                I2C_SMBUS_READ, 0,
2176                                I2C_SMBUS_BYTE, &data);
2177        return (status < 0) ? status : data.byte;
2178}
2179EXPORT_SYMBOL(i2c_smbus_read_byte);
2180
2181/**
2182 * i2c_smbus_write_byte - SMBus "send byte" protocol
2183 * @client: Handle to slave device
2184 * @value: Byte to be sent
2185 *
2186 * This executes the SMBus "send byte" protocol, returning negative errno
2187 * else zero on success.
2188 */
2189s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value)
2190{
2191        return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2192                              I2C_SMBUS_WRITE, value, I2C_SMBUS_BYTE, NULL);
2193}
2194EXPORT_SYMBOL(i2c_smbus_write_byte);
2195
2196/**
2197 * i2c_smbus_read_byte_data - SMBus "read byte" protocol
2198 * @client: Handle to slave device
2199 * @command: Byte interpreted by slave
2200 *
2201 * This executes the SMBus "read byte" protocol, returning negative errno
2202 * else a data byte received from the device.
2203 */
2204s32 i2c_smbus_read_byte_data(const struct i2c_client *client, u8 command)
2205{
2206        union i2c_smbus_data data;
2207        int status;
2208
2209        status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2210                                I2C_SMBUS_READ, command,
2211                                I2C_SMBUS_BYTE_DATA, &data);
2212        return (status < 0) ? status : data.byte;
2213}
2214EXPORT_SYMBOL(i2c_smbus_read_byte_data);
2215
2216/**
2217 * i2c_smbus_write_byte_data - SMBus "write byte" protocol
2218 * @client: Handle to slave device
2219 * @command: Byte interpreted by slave
2220 * @value: Byte being written
2221 *
2222 * This executes the SMBus "write byte" protocol, returning negative errno
2223 * else zero on success.
2224 */
2225s32 i2c_smbus_write_byte_data(const struct i2c_client *client, u8 command,
2226                              u8 value)
2227{
2228        union i2c_smbus_data data;
2229        data.byte = value;
2230        return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2231                              I2C_SMBUS_WRITE, command,
2232                              I2C_SMBUS_BYTE_DATA, &data);
2233}
2234EXPORT_SYMBOL(i2c_smbus_write_byte_data);
2235
2236/**
2237 * i2c_smbus_read_word_data - SMBus "read word" protocol
2238 * @client: Handle to slave device
2239 * @command: Byte interpreted by slave
2240 *
2241 * This executes the SMBus "read word" protocol, returning negative errno
2242 * else a 16-bit unsigned "word" received from the device.
2243 */
2244s32 i2c_smbus_read_word_data(const struct i2c_client *client, u8 command)
2245{
2246        union i2c_smbus_data data;
2247        int status;
2248
2249        status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2250                                I2C_SMBUS_READ, command,
2251                                I2C_SMBUS_WORD_DATA, &data);
2252        return (status < 0) ? status : data.word;
2253}
2254EXPORT_SYMBOL(i2c_smbus_read_word_data);
2255
2256/**
2257 * i2c_smbus_write_word_data - SMBus "write word" protocol
2258 * @client: Handle to slave device
2259 * @command: Byte interpreted by slave
2260 * @value: 16-bit "word" being written
2261 *
2262 * This executes the SMBus "write word" protocol, returning negative errno
2263 * else zero on success.
2264 */
2265s32 i2c_smbus_write_word_data(const struct i2c_client *client, u8 command,
2266                              u16 value)
2267{
2268        union i2c_smbus_data data;
2269        data.word = value;
2270        return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2271                              I2C_SMBUS_WRITE, command,
2272                              I2C_SMBUS_WORD_DATA, &data);
2273}
2274EXPORT_SYMBOL(i2c_smbus_write_word_data);
2275
2276/**
2277 * i2c_smbus_read_block_data - SMBus "block read" protocol
2278 * @client: Handle to slave device
2279 * @command: Byte interpreted by slave
2280 * @values: Byte array into which data will be read; big enough to hold
2281 *      the data returned by the slave.  SMBus allows at most 32 bytes.
2282 *
2283 * This executes the SMBus "block read" protocol, returning negative errno
2284 * else the number of data bytes in the slave's response.
2285 *
2286 * Note that using this function requires that the client's adapter support
2287 * the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality.  Not all adapter drivers
2288 * support this; its emulation through I2C messaging relies on a specific
2289 * mechanism (I2C_M_RECV_LEN) which may not be implemented.
2290 */
2291s32 i2c_smbus_read_block_data(const struct i2c_client *client, u8 command,
2292                              u8 *values)
2293{
2294        union i2c_smbus_data data;
2295        int status;
2296
2297        status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2298                                I2C_SMBUS_READ, command,
2299                                I2C_SMBUS_BLOCK_DATA, &data);
2300        if (status)
2301                return status;
2302
2303        memcpy(values, &data.block[1], data.block[0]);
2304        return data.block[0];
2305}
2306EXPORT_SYMBOL(i2c_smbus_read_block_data);
2307
2308/**
2309 * i2c_smbus_write_block_data - SMBus "block write" protocol
2310 * @client: Handle to slave device
2311 * @command: Byte interpreted by slave
2312 * @length: Size of data block; SMBus allows at most 32 bytes
2313 * @values: Byte array which will be written.
2314 *
2315 * This executes the SMBus "block write" protocol, returning negative errno
2316 * else zero on success.
2317 */
2318s32 i2c_smbus_write_block_data(const struct i2c_client *client, u8 command,
2319                               u8 length, const u8 *values)
2320{
2321        union i2c_smbus_data data;
2322
2323        if (length > I2C_SMBUS_BLOCK_MAX)
2324                length = I2C_SMBUS_BLOCK_MAX;
2325        data.block[0] = length;
2326        memcpy(&data.block[1], values, length);
2327        return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2328                              I2C_SMBUS_WRITE, command,
2329                              I2C_SMBUS_BLOCK_DATA, &data);
2330}
2331EXPORT_SYMBOL(i2c_smbus_write_block_data);
2332
2333/* Returns the number of read bytes */
2334s32 i2c_smbus_read_i2c_block_data(const struct i2c_client *client, u8 command,
2335                                  u8 length, u8 *values)
2336{
2337        union i2c_smbus_data data;
2338        int status;
2339
2340        if (length > I2C_SMBUS_BLOCK_MAX)
2341                length = I2C_SMBUS_BLOCK_MAX;
2342        data.block[0] = length;
2343        status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2344                                I2C_SMBUS_READ, command,
2345                                I2C_SMBUS_I2C_BLOCK_DATA, &data);
2346        if (status < 0)
2347                return status;
2348
2349        memcpy(values, &data.block[1], data.block[0]);
2350        return data.block[0];
2351}
2352EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data);
2353
2354s32 i2c_smbus_write_i2c_block_data(const struct i2c_client *client, u8 command,
2355                                   u8 length, const u8 *values)
2356{
2357        union i2c_smbus_data data;
2358
2359        if (length > I2C_SMBUS_BLOCK_MAX)
2360                length = I2C_SMBUS_BLOCK_MAX;
2361        data.block[0] = length;
2362        memcpy(data.block + 1, values, length);
2363        return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2364                              I2C_SMBUS_WRITE, command,
2365                              I2C_SMBUS_I2C_BLOCK_DATA, &data);
2366}
2367EXPORT_SYMBOL(i2c_smbus_write_i2c_block_data);
2368
2369/* Simulate a SMBus command using the i2c protocol
2370   No checking of parameters is done!  */
2371static s32 i2c_smbus_xfer_emulated(struct i2c_adapter *adapter, u16 addr,
2372                                   unsigned short flags,
2373                                   char read_write, u8 command, int size,
2374                                   union i2c_smbus_data *data)
2375{
2376        /* So we need to generate a series of msgs. In the case of writing, we
2377          need to use only one message; when reading, we need two. We initialize
2378          most things with sane defaults, to keep the code below somewhat
2379          simpler. */
2380        unsigned char msgbuf0[I2C_SMBUS_BLOCK_MAX+3];
2381        unsigned char msgbuf1[I2C_SMBUS_BLOCK_MAX+2];
2382        int num = read_write == I2C_SMBUS_READ ? 2 : 1;
2383        int i;
2384        u8 partial_pec = 0;
2385        int status;
2386        struct i2c_msg msg[2] = {
2387                {
2388                        .addr = addr,
2389                        .flags = flags,
2390                        .len = 1,
2391                        .buf = msgbuf0,
2392                }, {
2393                        .addr = addr,
2394                        .flags = flags | I2C_M_RD,
2395                        .len = 0,
2396                        .buf = msgbuf1,
2397                },
2398        };
2399
2400        msgbuf0[0] = command;
2401        switch (size) {
2402        case I2C_SMBUS_QUICK:
2403                msg[0].len = 0;
2404                /* Special case: The read/write field is used as data */
2405                msg[0].flags = flags | (read_write == I2C_SMBUS_READ ?
2406                                        I2C_M_RD : 0);
2407                num = 1;
2408                break;
2409        case I2C_SMBUS_BYTE:
2410                if (read_write == I2C_SMBUS_READ) {
2411                        /* Special case: only a read! */
2412                        msg[0].flags = I2C_M_RD | flags;
2413                        num = 1;
2414                }
2415                break;
2416        case I2C_SMBUS_BYTE_DATA:
2417                if (read_write == I2C_SMBUS_READ)
2418                        msg[1].len = 1;
2419                else {
2420                        msg[0].len = 2;
2421                        msgbuf0[1] = data->byte;
2422                }
2423                break;
2424        case I2C_SMBUS_WORD_DATA:
2425                if (read_write == I2C_SMBUS_READ)
2426                        msg[1].len = 2;
2427                else {
2428                        msg[0].len = 3;
2429                        msgbuf0[1] = data->word & 0xff;
2430                        msgbuf0[2] = data->word >> 8;
2431                }
2432                break;
2433        case I2C_SMBUS_PROC_CALL:
2434                num = 2; /* Special case */
2435                read_write = I2C_SMBUS_READ;
2436                msg[0].len = 3;
2437                msg[1].len = 2;
2438                msgbuf0[1] = data->word & 0xff;
2439                msgbuf0[2] = data->word >> 8;
2440                break;
2441        case I2C_SMBUS_BLOCK_DATA:
2442                if (read_write == I2C_SMBUS_READ) {
2443                        msg[1].flags |= I2C_M_RECV_LEN;
2444                        msg[1].len = 1; /* block length will be added by
2445                                           the underlying bus driver */
2446                } else {
2447                        msg[0].len = data->block[0] + 2;
2448                        if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) {
2449                                dev_err(&adapter->dev,
2450                                        "Invalid block write size %d\n",
2451                                        data->block[0]);
2452                                return -EINVAL;
2453                        }
2454                        for (i = 1; i < msg[0].len; i++)
2455                                msgbuf0[i] = data->block[i-1];
2456                }
2457                break;
2458        case I2C_SMBUS_BLOCK_PROC_CALL:
2459                num = 2; /* Another special case */
2460                read_write = I2C_SMBUS_READ;
2461                if (data->block[0] > I2C_SMBUS_BLOCK_MAX) {
2462                        dev_err(&adapter->dev,
2463                                "Invalid block write size %d\n",
2464                                data->block[0]);
2465                        return -EINVAL;
2466                }
2467                msg[0].len = data->block[0] + 2;
2468                for (i = 1; i < msg[0].len; i++)
2469                        msgbuf0[i] = data->block[i-1];
2470                msg[1].flags |= I2C_M_RECV_LEN;
2471                msg[1].len = 1; /* block length will be added by
2472                                   the underlying bus driver */
2473                break;
2474        case I2C_SMBUS_I2C_BLOCK_DATA:
2475                if (read_write == I2C_SMBUS_READ) {
2476                        msg[1].len = data->block[0];
2477                } else {
2478                        msg[0].len = data->block[0] + 1;
2479                        if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 1) {
2480                                dev_err(&adapter->dev,
2481                                        "Invalid block write size %d\n",
2482                                        data->block[0]);
2483                                return -EINVAL;
2484                        }
2485                        for (i = 1; i <= data->block[0]; i++)
2486                                msgbuf0[i] = data->block[i];
2487                }
2488                break;
2489        default:
2490                dev_err(&adapter->dev, "Unsupported transaction %d\n", size);
2491                return -EOPNOTSUPP;
2492        }
2493
2494        i = ((flags & I2C_CLIENT_PEC) && size != I2C_SMBUS_QUICK
2495                                      && size != I2C_SMBUS_I2C_BLOCK_DATA);
2496        if (i) {
2497                /* Compute PEC if first message is a write */
2498                if (!(msg[0].flags & I2C_M_RD)) {
2499                        if (num == 1) /* Write only */
2500                                i2c_smbus_add_pec(&msg[0]);
2501                        else /* Write followed by read */
2502                                partial_pec = i2c_smbus_msg_pec(0, &msg[0]);
2503                }
2504                /* Ask for PEC if last message is a read */
2505                if (msg[num-1].flags & I2C_M_RD)
2506                        msg[num-1].len++;
2507        }
2508
2509        status = i2c_transfer(adapter, msg, num);
2510        if (status < 0)
2511                return status;
2512
2513        /* Check PEC if last message is a read */
2514        if (i && (msg[num-1].flags & I2C_M_RD)) {
2515                status = i2c_smbus_check_pec(partial_pec, &msg[num-1]);
2516                if (status < 0)
2517                        return status;
2518        }
2519
2520        if (read_write == I2C_SMBUS_READ)
2521                switch (size) {
2522                case I2C_SMBUS_BYTE:
2523                        data->byte = msgbuf0[0];
2524                        break;
2525                case I2C_SMBUS_BYTE_DATA:
2526                        data->byte = msgbuf1[0];
2527                        break;
2528                case I2C_SMBUS_WORD_DATA:
2529                case I2C_SMBUS_PROC_CALL:
2530                        data->word = msgbuf1[0] | (msgbuf1[1] << 8);
2531                        break;
2532                case I2C_SMBUS_I2C_BLOCK_DATA:
2533                        for (i = 0; i < data->block[0]; i++)
2534                                data->block[i+1] = msgbuf1[i];
2535                        break;
2536                case I2C_SMBUS_BLOCK_DATA:
2537                case I2C_SMBUS_BLOCK_PROC_CALL:
2538                        for (i = 0; i < msgbuf1[0] + 1; i++)
2539                                data->block[i] = msgbuf1[i];
2540                        break;
2541                }
2542        return 0;
2543}
2544
2545/**
2546 * i2c_smbus_xfer - execute SMBus protocol operations
2547 * @adapter: Handle to I2C bus
2548 * @addr: Address of SMBus slave on that bus
2549 * @flags: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC)
2550 * @read_write: I2C_SMBUS_READ or I2C_SMBUS_WRITE
2551 * @command: Byte interpreted by slave, for protocols which use such bytes
2552 * @protocol: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL
2553 * @data: Data to be read or written
2554 *
2555 * This executes an SMBus protocol operation, and returns a negative
2556 * errno code else zero on success.
2557 */
2558s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags,
2559                   char read_write, u8 command, int protocol,
2560                   union i2c_smbus_data *data)
2561{
2562        unsigned long orig_jiffies;
2563        int try;
2564        s32 res;
2565
2566        flags &= I2C_M_TEN | I2C_CLIENT_PEC | I2C_CLIENT_SCCB;
2567
2568        if (adapter->algo->smbus_xfer) {
2569                i2c_lock_adapter(adapter);
2570
2571                /* Retry automatically on arbitration loss */
2572                orig_jiffies = jiffies;
2573                for (res = 0, try = 0; try <= adapter->retries; try++) {
2574                        res = adapter->algo->smbus_xfer(adapter, addr, flags,
2575                                                        read_write, command,
2576                                                        protocol, data);
2577                        if (res != -EAGAIN)
2578                                break;
2579                        if (time_after(jiffies,
2580                                       orig_jiffies + adapter->timeout))
2581                                break;
2582                }
2583                i2c_unlock_adapter(adapter);
2584
2585                if (res != -EOPNOTSUPP || !adapter->algo->master_xfer)
2586                        return res;
2587                /*
2588                 * Fall back to i2c_smbus_xfer_emulated if the adapter doesn't
2589                 * implement native support for the SMBus operation.
2590                 */
2591        }
2592
2593        return i2c_smbus_xfer_emulated(adapter, addr, flags, read_write,
2594                                       command, protocol, data);
2595}
2596EXPORT_SYMBOL(i2c_smbus_xfer);
2597
2598MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
2599MODULE_DESCRIPTION("I2C-Bus main module");
2600MODULE_LICENSE("GPL");
2601