linux/drivers/i2c/i2c-core-base.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0-or-later
   2/*
   3 * Linux I2C core
   4 *
   5 * Copyright (C) 1995-99 Simon G. Vogl
   6 *   With some changes from Kyösti Mälkki <kmalkki@cc.hut.fi>
   7 *   Mux support by Rodolfo Giometti <giometti@enneenne.com> and
   8 *   Michael Lawnick <michael.lawnick.ext@nsn.com>
   9 *
  10 * Copyright (C) 2013-2017 Wolfram Sang <wsa@the-dreams.de>
  11 */
  12
  13#define pr_fmt(fmt) "i2c-core: " fmt
  14
  15#include <dt-bindings/i2c/i2c.h>
  16#include <linux/acpi.h>
  17#include <linux/clk/clk-conf.h>
  18#include <linux/completion.h>
  19#include <linux/delay.h>
  20#include <linux/err.h>
  21#include <linux/errno.h>
  22#include <linux/gpio/consumer.h>
  23#include <linux/i2c.h>
  24#include <linux/i2c-smbus.h>
  25#include <linux/idr.h>
  26#include <linux/init.h>
  27#include <linux/irqflags.h>
  28#include <linux/jump_label.h>
  29#include <linux/kernel.h>
  30#include <linux/module.h>
  31#include <linux/mutex.h>
  32#include <linux/of_device.h>
  33#include <linux/of.h>
  34#include <linux/of_irq.h>
  35#include <linux/pm_domain.h>
  36#include <linux/pm_runtime.h>
  37#include <linux/pm_wakeirq.h>
  38#include <linux/property.h>
  39#include <linux/rwsem.h>
  40#include <linux/slab.h>
  41
  42#include "i2c-core.h"
  43
  44#define CREATE_TRACE_POINTS
  45#include <trace/events/i2c.h>
  46
  47#define I2C_ADDR_OFFSET_TEN_BIT 0xa000
  48#define I2C_ADDR_OFFSET_SLAVE   0x1000
  49
  50#define I2C_ADDR_7BITS_MAX      0x77
  51#define I2C_ADDR_7BITS_COUNT    (I2C_ADDR_7BITS_MAX + 1)
  52
  53#define I2C_ADDR_DEVICE_ID      0x7c
  54
  55/*
  56 * core_lock protects i2c_adapter_idr, and guarantees that device detection,
  57 * deletion of detected devices are serialized
  58 */
  59static DEFINE_MUTEX(core_lock);
  60static DEFINE_IDR(i2c_adapter_idr);
  61
  62static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
  63
  64static DEFINE_STATIC_KEY_FALSE(i2c_trace_msg_key);
  65static bool is_registered;
  66
  67int i2c_transfer_trace_reg(void)
  68{
  69        static_branch_inc(&i2c_trace_msg_key);
  70        return 0;
  71}
  72
  73void i2c_transfer_trace_unreg(void)
  74{
  75        static_branch_dec(&i2c_trace_msg_key);
  76}
  77
  78const char *i2c_freq_mode_string(u32 bus_freq_hz)
  79{
  80        switch (bus_freq_hz) {
  81        case I2C_MAX_STANDARD_MODE_FREQ:
  82                return "Standard Mode (100 kHz)";
  83        case I2C_MAX_FAST_MODE_FREQ:
  84                return "Fast Mode (400 kHz)";
  85        case I2C_MAX_FAST_MODE_PLUS_FREQ:
  86                return "Fast Mode Plus (1.0 MHz)";
  87        case I2C_MAX_TURBO_MODE_FREQ:
  88                return "Turbo Mode (1.4 MHz)";
  89        case I2C_MAX_HIGH_SPEED_MODE_FREQ:
  90                return "High Speed Mode (3.4 MHz)";
  91        case I2C_MAX_ULTRA_FAST_MODE_FREQ:
  92                return "Ultra Fast Mode (5.0 MHz)";
  93        default:
  94                return "Unknown Mode";
  95        }
  96}
  97EXPORT_SYMBOL_GPL(i2c_freq_mode_string);
  98
  99const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
 100                                                const struct i2c_client *client)
 101{
 102        if (!(id && client))
 103                return NULL;
 104
 105        while (id->name[0]) {
 106                if (strcmp(client->name, id->name) == 0)
 107                        return id;
 108                id++;
 109        }
 110        return NULL;
 111}
 112EXPORT_SYMBOL_GPL(i2c_match_id);
 113
 114static int i2c_device_match(struct device *dev, struct device_driver *drv)
 115{
 116        struct i2c_client       *client = i2c_verify_client(dev);
 117        struct i2c_driver       *driver;
 118
 119
 120        /* Attempt an OF style match */
 121        if (i2c_of_match_device(drv->of_match_table, client))
 122                return 1;
 123
 124        /* Then ACPI style match */
 125        if (acpi_driver_match_device(dev, drv))
 126                return 1;
 127
 128        driver = to_i2c_driver(drv);
 129
 130        /* Finally an I2C match */
 131        if (i2c_match_id(driver->id_table, client))
 132                return 1;
 133
 134        return 0;
 135}
 136
 137static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
 138{
 139        struct i2c_client *client = to_i2c_client(dev);
 140        int rc;
 141
 142        rc = of_device_uevent_modalias(dev, env);
 143        if (rc != -ENODEV)
 144                return rc;
 145
 146        rc = acpi_device_uevent_modalias(dev, env);
 147        if (rc != -ENODEV)
 148                return rc;
 149
 150        return add_uevent_var(env, "MODALIAS=%s%s", I2C_MODULE_PREFIX, client->name);
 151}
 152
 153/* i2c bus recovery routines */
 154static int get_scl_gpio_value(struct i2c_adapter *adap)
 155{
 156        return gpiod_get_value_cansleep(adap->bus_recovery_info->scl_gpiod);
 157}
 158
 159static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
 160{
 161        gpiod_set_value_cansleep(adap->bus_recovery_info->scl_gpiod, val);
 162}
 163
 164static int get_sda_gpio_value(struct i2c_adapter *adap)
 165{
 166        return gpiod_get_value_cansleep(adap->bus_recovery_info->sda_gpiod);
 167}
 168
 169static void set_sda_gpio_value(struct i2c_adapter *adap, int val)
 170{
 171        gpiod_set_value_cansleep(adap->bus_recovery_info->sda_gpiod, val);
 172}
 173
 174static int i2c_generic_bus_free(struct i2c_adapter *adap)
 175{
 176        struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
 177        int ret = -EOPNOTSUPP;
 178
 179        if (bri->get_bus_free)
 180                ret = bri->get_bus_free(adap);
 181        else if (bri->get_sda)
 182                ret = bri->get_sda(adap);
 183
 184        if (ret < 0)
 185                return ret;
 186
 187        return ret ? 0 : -EBUSY;
 188}
 189
 190/*
 191 * We are generating clock pulses. ndelay() determines durating of clk pulses.
 192 * We will generate clock with rate 100 KHz and so duration of both clock levels
 193 * is: delay in ns = (10^6 / 100) / 2
 194 */
 195#define RECOVERY_NDELAY         5000
 196#define RECOVERY_CLK_CNT        9
 197
 198int i2c_generic_scl_recovery(struct i2c_adapter *adap)
 199{
 200        struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
 201        int i = 0, scl = 1, ret = 0;
 202
 203        if (bri->prepare_recovery)
 204                bri->prepare_recovery(adap);
 205
 206        /*
 207         * If we can set SDA, we will always create a STOP to ensure additional
 208         * pulses will do no harm. This is achieved by letting SDA follow SCL
 209         * half a cycle later. Check the 'incomplete_write_byte' fault injector
 210         * for details. Note that we must honour tsu:sto, 4us, but lets use 5us
 211         * here for simplicity.
 212         */
 213        bri->set_scl(adap, scl);
 214        ndelay(RECOVERY_NDELAY);
 215        if (bri->set_sda)
 216                bri->set_sda(adap, scl);
 217        ndelay(RECOVERY_NDELAY / 2);
 218
 219        /*
 220         * By this time SCL is high, as we need to give 9 falling-rising edges
 221         */
 222        while (i++ < RECOVERY_CLK_CNT * 2) {
 223                if (scl) {
 224                        /* SCL shouldn't be low here */
 225                        if (!bri->get_scl(adap)) {
 226                                dev_err(&adap->dev,
 227                                        "SCL is stuck low, exit recovery\n");
 228                                ret = -EBUSY;
 229                                break;
 230                        }
 231                }
 232
 233                scl = !scl;
 234                bri->set_scl(adap, scl);
 235                /* Creating STOP again, see above */
 236                if (scl)  {
 237                        /* Honour minimum tsu:sto */
 238                        ndelay(RECOVERY_NDELAY);
 239                } else {
 240                        /* Honour minimum tf and thd:dat */
 241                        ndelay(RECOVERY_NDELAY / 2);
 242                }
 243                if (bri->set_sda)
 244                        bri->set_sda(adap, scl);
 245                ndelay(RECOVERY_NDELAY / 2);
 246
 247                if (scl) {
 248                        ret = i2c_generic_bus_free(adap);
 249                        if (ret == 0)
 250                                break;
 251                }
 252        }
 253
 254        /* If we can't check bus status, assume recovery worked */
 255        if (ret == -EOPNOTSUPP)
 256                ret = 0;
 257
 258        if (bri->unprepare_recovery)
 259                bri->unprepare_recovery(adap);
 260
 261        return ret;
 262}
 263EXPORT_SYMBOL_GPL(i2c_generic_scl_recovery);
 264
 265int i2c_recover_bus(struct i2c_adapter *adap)
 266{
 267        if (!adap->bus_recovery_info)
 268                return -EOPNOTSUPP;
 269
 270        dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
 271        return adap->bus_recovery_info->recover_bus(adap);
 272}
 273EXPORT_SYMBOL_GPL(i2c_recover_bus);
 274
 275static void i2c_init_recovery(struct i2c_adapter *adap)
 276{
 277        struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
 278        char *err_str;
 279
 280        if (!bri)
 281                return;
 282
 283        if (!bri->recover_bus) {
 284                err_str = "no recover_bus() found";
 285                goto err;
 286        }
 287
 288        if (bri->scl_gpiod && bri->recover_bus == i2c_generic_scl_recovery) {
 289                bri->get_scl = get_scl_gpio_value;
 290                bri->set_scl = set_scl_gpio_value;
 291                if (bri->sda_gpiod) {
 292                        bri->get_sda = get_sda_gpio_value;
 293                        /* FIXME: add proper flag instead of '0' once available */
 294                        if (gpiod_get_direction(bri->sda_gpiod) == 0)
 295                                bri->set_sda = set_sda_gpio_value;
 296                }
 297                return;
 298        }
 299
 300        if (bri->recover_bus == i2c_generic_scl_recovery) {
 301                /* Generic SCL recovery */
 302                if (!bri->set_scl || !bri->get_scl) {
 303                        err_str = "no {get|set}_scl() found";
 304                        goto err;
 305                }
 306                if (!bri->set_sda && !bri->get_sda) {
 307                        err_str = "either get_sda() or set_sda() needed";
 308                        goto err;
 309                }
 310        }
 311
 312        return;
 313 err:
 314        dev_err(&adap->dev, "Not using recovery: %s\n", err_str);
 315        adap->bus_recovery_info = NULL;
 316}
 317
 318static int i2c_smbus_host_notify_to_irq(const struct i2c_client *client)
 319{
 320        struct i2c_adapter *adap = client->adapter;
 321        unsigned int irq;
 322
 323        if (!adap->host_notify_domain)
 324                return -ENXIO;
 325
 326        if (client->flags & I2C_CLIENT_TEN)
 327                return -EINVAL;
 328
 329        irq = irq_create_mapping(adap->host_notify_domain, client->addr);
 330
 331        return irq > 0 ? irq : -ENXIO;
 332}
 333
 334static int i2c_device_probe(struct device *dev)
 335{
 336        struct i2c_client       *client = i2c_verify_client(dev);
 337        struct i2c_driver       *driver;
 338        int status;
 339
 340        if (!client)
 341                return 0;
 342
 343        driver = to_i2c_driver(dev->driver);
 344
 345        client->irq = client->init_irq;
 346
 347        if (!client->irq && !driver->disable_i2c_core_irq_mapping) {
 348                int irq = -ENOENT;
 349
 350                if (client->flags & I2C_CLIENT_HOST_NOTIFY) {
 351                        dev_dbg(dev, "Using Host Notify IRQ\n");
 352                        /* Keep adapter active when Host Notify is required */
 353                        pm_runtime_get_sync(&client->adapter->dev);
 354                        irq = i2c_smbus_host_notify_to_irq(client);
 355                } else if (dev->of_node) {
 356                        irq = of_irq_get_byname(dev->of_node, "irq");
 357                        if (irq == -EINVAL || irq == -ENODATA)
 358                                irq = of_irq_get(dev->of_node, 0);
 359                } else if (ACPI_COMPANION(dev)) {
 360                        irq = i2c_acpi_get_irq(client);
 361                }
 362                if (irq == -EPROBE_DEFER)
 363                        return irq;
 364
 365                if (irq < 0)
 366                        irq = 0;
 367
 368                client->irq = irq;
 369        }
 370
 371        /*
 372         * An I2C ID table is not mandatory, if and only if, a suitable OF
 373         * or ACPI ID table is supplied for the probing device.
 374         */
 375        if (!driver->id_table &&
 376            !i2c_acpi_match_device(dev->driver->acpi_match_table, client) &&
 377            !i2c_of_match_device(dev->driver->of_match_table, client))
 378                return -ENODEV;
 379
 380        if (client->flags & I2C_CLIENT_WAKE) {
 381                int wakeirq;
 382
 383                wakeirq = of_irq_get_byname(dev->of_node, "wakeup");
 384                if (wakeirq == -EPROBE_DEFER)
 385                        return wakeirq;
 386
 387                device_init_wakeup(&client->dev, true);
 388
 389                if (wakeirq > 0 && wakeirq != client->irq)
 390                        status = dev_pm_set_dedicated_wake_irq(dev, wakeirq);
 391                else if (client->irq > 0)
 392                        status = dev_pm_set_wake_irq(dev, client->irq);
 393                else
 394                        status = 0;
 395
 396                if (status)
 397                        dev_warn(&client->dev, "failed to set up wakeup irq\n");
 398        }
 399
 400        dev_dbg(dev, "probe\n");
 401
 402        status = of_clk_set_defaults(dev->of_node, false);
 403        if (status < 0)
 404                goto err_clear_wakeup_irq;
 405
 406        status = dev_pm_domain_attach(&client->dev, true);
 407        if (status)
 408                goto err_clear_wakeup_irq;
 409
 410        /*
 411         * When there are no more users of probe(),
 412         * rename probe_new to probe.
 413         */
 414        if (driver->probe_new)
 415                status = driver->probe_new(client);
 416        else if (driver->probe)
 417                status = driver->probe(client,
 418                                       i2c_match_id(driver->id_table, client));
 419        else
 420                status = -EINVAL;
 421
 422        if (status)
 423                goto err_detach_pm_domain;
 424
 425        return 0;
 426
 427err_detach_pm_domain:
 428        dev_pm_domain_detach(&client->dev, true);
 429err_clear_wakeup_irq:
 430        dev_pm_clear_wake_irq(&client->dev);
 431        device_init_wakeup(&client->dev, false);
 432        return status;
 433}
 434
 435static int i2c_device_remove(struct device *dev)
 436{
 437        struct i2c_client       *client = i2c_verify_client(dev);
 438        struct i2c_driver       *driver;
 439        int status = 0;
 440
 441        if (!client || !dev->driver)
 442                return 0;
 443
 444        driver = to_i2c_driver(dev->driver);
 445        if (driver->remove) {
 446                dev_dbg(dev, "remove\n");
 447                status = driver->remove(client);
 448        }
 449
 450        dev_pm_domain_detach(&client->dev, true);
 451
 452        dev_pm_clear_wake_irq(&client->dev);
 453        device_init_wakeup(&client->dev, false);
 454
 455        client->irq = 0;
 456        if (client->flags & I2C_CLIENT_HOST_NOTIFY)
 457                pm_runtime_put(&client->adapter->dev);
 458
 459        return status;
 460}
 461
 462static void i2c_device_shutdown(struct device *dev)
 463{
 464        struct i2c_client *client = i2c_verify_client(dev);
 465        struct i2c_driver *driver;
 466
 467        if (!client || !dev->driver)
 468                return;
 469        driver = to_i2c_driver(dev->driver);
 470        if (driver->shutdown)
 471                driver->shutdown(client);
 472}
 473
 474static void i2c_client_dev_release(struct device *dev)
 475{
 476        kfree(to_i2c_client(dev));
 477}
 478
 479static ssize_t
 480name_show(struct device *dev, struct device_attribute *attr, char *buf)
 481{
 482        return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
 483                       to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
 484}
 485static DEVICE_ATTR_RO(name);
 486
 487static ssize_t
 488modalias_show(struct device *dev, struct device_attribute *attr, char *buf)
 489{
 490        struct i2c_client *client = to_i2c_client(dev);
 491        int len;
 492
 493        len = of_device_modalias(dev, buf, PAGE_SIZE);
 494        if (len != -ENODEV)
 495                return len;
 496
 497        len = acpi_device_modalias(dev, buf, PAGE_SIZE -1);
 498        if (len != -ENODEV)
 499                return len;
 500
 501        return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
 502}
 503static DEVICE_ATTR_RO(modalias);
 504
 505static struct attribute *i2c_dev_attrs[] = {
 506        &dev_attr_name.attr,
 507        /* modalias helps coldplug:  modprobe $(cat .../modalias) */
 508        &dev_attr_modalias.attr,
 509        NULL
 510};
 511ATTRIBUTE_GROUPS(i2c_dev);
 512
 513struct bus_type i2c_bus_type = {
 514        .name           = "i2c",
 515        .match          = i2c_device_match,
 516        .probe          = i2c_device_probe,
 517        .remove         = i2c_device_remove,
 518        .shutdown       = i2c_device_shutdown,
 519};
 520EXPORT_SYMBOL_GPL(i2c_bus_type);
 521
 522struct device_type i2c_client_type = {
 523        .groups         = i2c_dev_groups,
 524        .uevent         = i2c_device_uevent,
 525        .release        = i2c_client_dev_release,
 526};
 527EXPORT_SYMBOL_GPL(i2c_client_type);
 528
 529
 530/**
 531 * i2c_verify_client - return parameter as i2c_client, or NULL
 532 * @dev: device, probably from some driver model iterator
 533 *
 534 * When traversing the driver model tree, perhaps using driver model
 535 * iterators like @device_for_each_child(), you can't assume very much
 536 * about the nodes you find.  Use this function to avoid oopses caused
 537 * by wrongly treating some non-I2C device as an i2c_client.
 538 */
 539struct i2c_client *i2c_verify_client(struct device *dev)
 540{
 541        return (dev->type == &i2c_client_type)
 542                        ? to_i2c_client(dev)
 543                        : NULL;
 544}
 545EXPORT_SYMBOL(i2c_verify_client);
 546
 547
 548/* Return a unique address which takes the flags of the client into account */
 549static unsigned short i2c_encode_flags_to_addr(struct i2c_client *client)
 550{
 551        unsigned short addr = client->addr;
 552
 553        /* For some client flags, add an arbitrary offset to avoid collisions */
 554        if (client->flags & I2C_CLIENT_TEN)
 555                addr |= I2C_ADDR_OFFSET_TEN_BIT;
 556
 557        if (client->flags & I2C_CLIENT_SLAVE)
 558                addr |= I2C_ADDR_OFFSET_SLAVE;
 559
 560        return addr;
 561}
 562
 563/* This is a permissive address validity check, I2C address map constraints
 564 * are purposely not enforced, except for the general call address. */
 565static int i2c_check_addr_validity(unsigned int addr, unsigned short flags)
 566{
 567        if (flags & I2C_CLIENT_TEN) {
 568                /* 10-bit address, all values are valid */
 569                if (addr > 0x3ff)
 570                        return -EINVAL;
 571        } else {
 572                /* 7-bit address, reject the general call address */
 573                if (addr == 0x00 || addr > 0x7f)
 574                        return -EINVAL;
 575        }
 576        return 0;
 577}
 578
 579/* And this is a strict address validity check, used when probing. If a
 580 * device uses a reserved address, then it shouldn't be probed. 7-bit
 581 * addressing is assumed, 10-bit address devices are rare and should be
 582 * explicitly enumerated. */
 583int i2c_check_7bit_addr_validity_strict(unsigned short addr)
 584{
 585        /*
 586         * Reserved addresses per I2C specification:
 587         *  0x00       General call address / START byte
 588         *  0x01       CBUS address
 589         *  0x02       Reserved for different bus format
 590         *  0x03       Reserved for future purposes
 591         *  0x04-0x07  Hs-mode master code
 592         *  0x78-0x7b  10-bit slave addressing
 593         *  0x7c-0x7f  Reserved for future purposes
 594         */
 595        if (addr < 0x08 || addr > 0x77)
 596                return -EINVAL;
 597        return 0;
 598}
 599
 600static int __i2c_check_addr_busy(struct device *dev, void *addrp)
 601{
 602        struct i2c_client       *client = i2c_verify_client(dev);
 603        int                     addr = *(int *)addrp;
 604
 605        if (client && i2c_encode_flags_to_addr(client) == addr)
 606                return -EBUSY;
 607        return 0;
 608}
 609
 610/* walk up mux tree */
 611static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
 612{
 613        struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
 614        int result;
 615
 616        result = device_for_each_child(&adapter->dev, &addr,
 617                                        __i2c_check_addr_busy);
 618
 619        if (!result && parent)
 620                result = i2c_check_mux_parents(parent, addr);
 621
 622        return result;
 623}
 624
 625/* recurse down mux tree */
 626static int i2c_check_mux_children(struct device *dev, void *addrp)
 627{
 628        int result;
 629
 630        if (dev->type == &i2c_adapter_type)
 631                result = device_for_each_child(dev, addrp,
 632                                                i2c_check_mux_children);
 633        else
 634                result = __i2c_check_addr_busy(dev, addrp);
 635
 636        return result;
 637}
 638
 639static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
 640{
 641        struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
 642        int result = 0;
 643
 644        if (parent)
 645                result = i2c_check_mux_parents(parent, addr);
 646
 647        if (!result)
 648                result = device_for_each_child(&adapter->dev, &addr,
 649                                                i2c_check_mux_children);
 650
 651        return result;
 652}
 653
 654/**
 655 * i2c_adapter_lock_bus - Get exclusive access to an I2C bus segment
 656 * @adapter: Target I2C bus segment
 657 * @flags: I2C_LOCK_ROOT_ADAPTER locks the root i2c adapter, I2C_LOCK_SEGMENT
 658 *      locks only this branch in the adapter tree
 659 */
 660static void i2c_adapter_lock_bus(struct i2c_adapter *adapter,
 661                                 unsigned int flags)
 662{
 663        rt_mutex_lock_nested(&adapter->bus_lock, i2c_adapter_depth(adapter));
 664}
 665
 666/**
 667 * i2c_adapter_trylock_bus - Try to get exclusive access to an I2C bus segment
 668 * @adapter: Target I2C bus segment
 669 * @flags: I2C_LOCK_ROOT_ADAPTER trylocks the root i2c adapter, I2C_LOCK_SEGMENT
 670 *      trylocks only this branch in the adapter tree
 671 */
 672static int i2c_adapter_trylock_bus(struct i2c_adapter *adapter,
 673                                   unsigned int flags)
 674{
 675        return rt_mutex_trylock(&adapter->bus_lock);
 676}
 677
 678/**
 679 * i2c_adapter_unlock_bus - Release exclusive access to an I2C bus segment
 680 * @adapter: Target I2C bus segment
 681 * @flags: I2C_LOCK_ROOT_ADAPTER unlocks the root i2c adapter, I2C_LOCK_SEGMENT
 682 *      unlocks only this branch in the adapter tree
 683 */
 684static void i2c_adapter_unlock_bus(struct i2c_adapter *adapter,
 685                                   unsigned int flags)
 686{
 687        rt_mutex_unlock(&adapter->bus_lock);
 688}
 689
 690static void i2c_dev_set_name(struct i2c_adapter *adap,
 691                             struct i2c_client *client,
 692                             struct i2c_board_info const *info)
 693{
 694        struct acpi_device *adev = ACPI_COMPANION(&client->dev);
 695
 696        if (info && info->dev_name) {
 697                dev_set_name(&client->dev, "i2c-%s", info->dev_name);
 698                return;
 699        }
 700
 701        if (adev) {
 702                dev_set_name(&client->dev, "i2c-%s", acpi_dev_name(adev));
 703                return;
 704        }
 705
 706        dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
 707                     i2c_encode_flags_to_addr(client));
 708}
 709
 710int i2c_dev_irq_from_resources(const struct resource *resources,
 711                               unsigned int num_resources)
 712{
 713        struct irq_data *irqd;
 714        int i;
 715
 716        for (i = 0; i < num_resources; i++) {
 717                const struct resource *r = &resources[i];
 718
 719                if (resource_type(r) != IORESOURCE_IRQ)
 720                        continue;
 721
 722                if (r->flags & IORESOURCE_BITS) {
 723                        irqd = irq_get_irq_data(r->start);
 724                        if (!irqd)
 725                                break;
 726
 727                        irqd_set_trigger_type(irqd, r->flags & IORESOURCE_BITS);
 728                }
 729
 730                return r->start;
 731        }
 732
 733        return 0;
 734}
 735
 736/**
 737 * i2c_new_client_device - instantiate an i2c device
 738 * @adap: the adapter managing the device
 739 * @info: describes one I2C device; bus_num is ignored
 740 * Context: can sleep
 741 *
 742 * Create an i2c device. Binding is handled through driver model
 743 * probe()/remove() methods.  A driver may be bound to this device when we
 744 * return from this function, or any later moment (e.g. maybe hotplugging will
 745 * load the driver module).  This call is not appropriate for use by mainboard
 746 * initialization logic, which usually runs during an arch_initcall() long
 747 * before any i2c_adapter could exist.
 748 *
 749 * This returns the new i2c client, which may be saved for later use with
 750 * i2c_unregister_device(); or an ERR_PTR to describe the error.
 751 */
 752struct i2c_client *
 753i2c_new_client_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
 754{
 755        struct i2c_client       *client;
 756        int                     status;
 757
 758        client = kzalloc(sizeof *client, GFP_KERNEL);
 759        if (!client)
 760                return ERR_PTR(-ENOMEM);
 761
 762        client->adapter = adap;
 763
 764        client->dev.platform_data = info->platform_data;
 765        client->flags = info->flags;
 766        client->addr = info->addr;
 767
 768        client->init_irq = info->irq;
 769        if (!client->init_irq)
 770                client->init_irq = i2c_dev_irq_from_resources(info->resources,
 771                                                         info->num_resources);
 772
 773        strlcpy(client->name, info->type, sizeof(client->name));
 774
 775        status = i2c_check_addr_validity(client->addr, client->flags);
 776        if (status) {
 777                dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
 778                        client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
 779                goto out_err_silent;
 780        }
 781
 782        /* Check for address business */
 783        status = i2c_check_addr_busy(adap, i2c_encode_flags_to_addr(client));
 784        if (status)
 785                goto out_err;
 786
 787        client->dev.parent = &client->adapter->dev;
 788        client->dev.bus = &i2c_bus_type;
 789        client->dev.type = &i2c_client_type;
 790        client->dev.of_node = of_node_get(info->of_node);
 791        client->dev.fwnode = info->fwnode;
 792
 793        i2c_dev_set_name(adap, client, info);
 794
 795        if (info->properties) {
 796                status = device_add_properties(&client->dev, info->properties);
 797                if (status) {
 798                        dev_err(&adap->dev,
 799                                "Failed to add properties to client %s: %d\n",
 800                                client->name, status);
 801                        goto out_err_put_of_node;
 802                }
 803        }
 804
 805        status = device_register(&client->dev);
 806        if (status)
 807                goto out_free_props;
 808
 809        dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
 810                client->name, dev_name(&client->dev));
 811
 812        return client;
 813
 814out_free_props:
 815        if (info->properties)
 816                device_remove_properties(&client->dev);
 817out_err_put_of_node:
 818        of_node_put(info->of_node);
 819out_err:
 820        dev_err(&adap->dev,
 821                "Failed to register i2c client %s at 0x%02x (%d)\n",
 822                client->name, client->addr, status);
 823out_err_silent:
 824        kfree(client);
 825        return ERR_PTR(status);
 826}
 827EXPORT_SYMBOL_GPL(i2c_new_client_device);
 828
 829/**
 830 * i2c_new_device - instantiate an i2c device
 831 * @adap: the adapter managing the device
 832 * @info: describes one I2C device; bus_num is ignored
 833 * Context: can sleep
 834 *
 835 * This deprecated function has the same functionality as
 836 * @i2c_new_client_device, it just returns NULL instead of an ERR_PTR in case of
 837 * an error for compatibility with current I2C API. It will be removed once all
 838 * users are converted.
 839 *
 840 * This returns the new i2c client, which may be saved for later use with
 841 * i2c_unregister_device(); or NULL to indicate an error.
 842 */
 843struct i2c_client *
 844i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
 845{
 846        struct i2c_client *ret;
 847
 848        ret = i2c_new_client_device(adap, info);
 849        return IS_ERR(ret) ? NULL : ret;
 850}
 851EXPORT_SYMBOL_GPL(i2c_new_device);
 852
 853
 854/**
 855 * i2c_unregister_device - reverse effect of i2c_new_*_device()
 856 * @client: value returned from i2c_new_*_device()
 857 * Context: can sleep
 858 */
 859void i2c_unregister_device(struct i2c_client *client)
 860{
 861        if (IS_ERR_OR_NULL(client))
 862                return;
 863
 864        if (client->dev.of_node) {
 865                of_node_clear_flag(client->dev.of_node, OF_POPULATED);
 866                of_node_put(client->dev.of_node);
 867        }
 868
 869        if (ACPI_COMPANION(&client->dev))
 870                acpi_device_clear_enumerated(ACPI_COMPANION(&client->dev));
 871        device_unregister(&client->dev);
 872}
 873EXPORT_SYMBOL_GPL(i2c_unregister_device);
 874
 875
 876static const struct i2c_device_id dummy_id[] = {
 877        { "dummy", 0 },
 878        { },
 879};
 880
 881static int dummy_probe(struct i2c_client *client,
 882                       const struct i2c_device_id *id)
 883{
 884        return 0;
 885}
 886
 887static int dummy_remove(struct i2c_client *client)
 888{
 889        return 0;
 890}
 891
 892static struct i2c_driver dummy_driver = {
 893        .driver.name    = "dummy",
 894        .probe          = dummy_probe,
 895        .remove         = dummy_remove,
 896        .id_table       = dummy_id,
 897};
 898
 899/**
 900 * i2c_new_dummy_device - return a new i2c device bound to a dummy driver
 901 * @adapter: the adapter managing the device
 902 * @address: seven bit address to be used
 903 * Context: can sleep
 904 *
 905 * This returns an I2C client bound to the "dummy" driver, intended for use
 906 * with devices that consume multiple addresses.  Examples of such chips
 907 * include various EEPROMS (like 24c04 and 24c08 models).
 908 *
 909 * These dummy devices have two main uses.  First, most I2C and SMBus calls
 910 * except i2c_transfer() need a client handle; the dummy will be that handle.
 911 * And second, this prevents the specified address from being bound to a
 912 * different driver.
 913 *
 914 * This returns the new i2c client, which should be saved for later use with
 915 * i2c_unregister_device(); or an ERR_PTR to describe the error.
 916 */
 917struct i2c_client *i2c_new_dummy_device(struct i2c_adapter *adapter, u16 address)
 918{
 919        struct i2c_board_info info = {
 920                I2C_BOARD_INFO("dummy", address),
 921        };
 922
 923        return i2c_new_client_device(adapter, &info);
 924}
 925EXPORT_SYMBOL_GPL(i2c_new_dummy_device);
 926
 927struct i2c_dummy_devres {
 928        struct i2c_client *client;
 929};
 930
 931static void devm_i2c_release_dummy(struct device *dev, void *res)
 932{
 933        struct i2c_dummy_devres *this = res;
 934
 935        i2c_unregister_device(this->client);
 936}
 937
 938/**
 939 * devm_i2c_new_dummy_device - return a new i2c device bound to a dummy driver
 940 * @dev: device the managed resource is bound to
 941 * @adapter: the adapter managing the device
 942 * @address: seven bit address to be used
 943 * Context: can sleep
 944 *
 945 * This is the device-managed version of @i2c_new_dummy_device. It returns the
 946 * new i2c client or an ERR_PTR in case of an error.
 947 */
 948struct i2c_client *devm_i2c_new_dummy_device(struct device *dev,
 949                                             struct i2c_adapter *adapter,
 950                                             u16 address)
 951{
 952        struct i2c_dummy_devres *dr;
 953        struct i2c_client *client;
 954
 955        dr = devres_alloc(devm_i2c_release_dummy, sizeof(*dr), GFP_KERNEL);
 956        if (!dr)
 957                return ERR_PTR(-ENOMEM);
 958
 959        client = i2c_new_dummy_device(adapter, address);
 960        if (IS_ERR(client)) {
 961                devres_free(dr);
 962        } else {
 963                dr->client = client;
 964                devres_add(dev, dr);
 965        }
 966
 967        return client;
 968}
 969EXPORT_SYMBOL_GPL(devm_i2c_new_dummy_device);
 970
 971/**
 972 * i2c_new_ancillary_device - Helper to get the instantiated secondary address
 973 * and create the associated device
 974 * @client: Handle to the primary client
 975 * @name: Handle to specify which secondary address to get
 976 * @default_addr: Used as a fallback if no secondary address was specified
 977 * Context: can sleep
 978 *
 979 * I2C clients can be composed of multiple I2C slaves bound together in a single
 980 * component. The I2C client driver then binds to the master I2C slave and needs
 981 * to create I2C dummy clients to communicate with all the other slaves.
 982 *
 983 * This function creates and returns an I2C dummy client whose I2C address is
 984 * retrieved from the platform firmware based on the given slave name. If no
 985 * address is specified by the firmware default_addr is used.
 986 *
 987 * On DT-based platforms the address is retrieved from the "reg" property entry
 988 * cell whose "reg-names" value matches the slave name.
 989 *
 990 * This returns the new i2c client, which should be saved for later use with
 991 * i2c_unregister_device(); or an ERR_PTR to describe the error.
 992 */
 993struct i2c_client *i2c_new_ancillary_device(struct i2c_client *client,
 994                                                const char *name,
 995                                                u16 default_addr)
 996{
 997        struct device_node *np = client->dev.of_node;
 998        u32 addr = default_addr;
 999        int i;
1000
1001        if (np) {
1002                i = of_property_match_string(np, "reg-names", name);
1003                if (i >= 0)
1004                        of_property_read_u32_index(np, "reg", i, &addr);
1005        }
1006
1007        dev_dbg(&client->adapter->dev, "Address for %s : 0x%x\n", name, addr);
1008        return i2c_new_dummy_device(client->adapter, addr);
1009}
1010EXPORT_SYMBOL_GPL(i2c_new_ancillary_device);
1011
1012/* ------------------------------------------------------------------------- */
1013
1014/* I2C bus adapters -- one roots each I2C or SMBUS segment */
1015
1016static void i2c_adapter_dev_release(struct device *dev)
1017{
1018        struct i2c_adapter *adap = to_i2c_adapter(dev);
1019        complete(&adap->dev_released);
1020}
1021
1022unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
1023{
1024        unsigned int depth = 0;
1025
1026        while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
1027                depth++;
1028
1029        WARN_ONCE(depth >= MAX_LOCKDEP_SUBCLASSES,
1030                  "adapter depth exceeds lockdep subclass limit\n");
1031
1032        return depth;
1033}
1034EXPORT_SYMBOL_GPL(i2c_adapter_depth);
1035
1036/*
1037 * Let users instantiate I2C devices through sysfs. This can be used when
1038 * platform initialization code doesn't contain the proper data for
1039 * whatever reason. Also useful for drivers that do device detection and
1040 * detection fails, either because the device uses an unexpected address,
1041 * or this is a compatible device with different ID register values.
1042 *
1043 * Parameter checking may look overzealous, but we really don't want
1044 * the user to provide incorrect parameters.
1045 */
1046static ssize_t
1047new_device_store(struct device *dev, struct device_attribute *attr,
1048                 const char *buf, size_t count)
1049{
1050        struct i2c_adapter *adap = to_i2c_adapter(dev);
1051        struct i2c_board_info info;
1052        struct i2c_client *client;
1053        char *blank, end;
1054        int res;
1055
1056        memset(&info, 0, sizeof(struct i2c_board_info));
1057
1058        blank = strchr(buf, ' ');
1059        if (!blank) {
1060                dev_err(dev, "%s: Missing parameters\n", "new_device");
1061                return -EINVAL;
1062        }
1063        if (blank - buf > I2C_NAME_SIZE - 1) {
1064                dev_err(dev, "%s: Invalid device name\n", "new_device");
1065                return -EINVAL;
1066        }
1067        memcpy(info.type, buf, blank - buf);
1068
1069        /* Parse remaining parameters, reject extra parameters */
1070        res = sscanf(++blank, "%hi%c", &info.addr, &end);
1071        if (res < 1) {
1072                dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
1073                return -EINVAL;
1074        }
1075        if (res > 1  && end != '\n') {
1076                dev_err(dev, "%s: Extra parameters\n", "new_device");
1077                return -EINVAL;
1078        }
1079
1080        if ((info.addr & I2C_ADDR_OFFSET_TEN_BIT) == I2C_ADDR_OFFSET_TEN_BIT) {
1081                info.addr &= ~I2C_ADDR_OFFSET_TEN_BIT;
1082                info.flags |= I2C_CLIENT_TEN;
1083        }
1084
1085        if (info.addr & I2C_ADDR_OFFSET_SLAVE) {
1086                info.addr &= ~I2C_ADDR_OFFSET_SLAVE;
1087                info.flags |= I2C_CLIENT_SLAVE;
1088        }
1089
1090        client = i2c_new_client_device(adap, &info);
1091        if (IS_ERR(client))
1092                return PTR_ERR(client);
1093
1094        /* Keep track of the added device */
1095        mutex_lock(&adap->userspace_clients_lock);
1096        list_add_tail(&client->detected, &adap->userspace_clients);
1097        mutex_unlock(&adap->userspace_clients_lock);
1098        dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
1099                 info.type, info.addr);
1100
1101        return count;
1102}
1103static DEVICE_ATTR_WO(new_device);
1104
1105/*
1106 * And of course let the users delete the devices they instantiated, if
1107 * they got it wrong. This interface can only be used to delete devices
1108 * instantiated by i2c_sysfs_new_device above. This guarantees that we
1109 * don't delete devices to which some kernel code still has references.
1110 *
1111 * Parameter checking may look overzealous, but we really don't want
1112 * the user to delete the wrong device.
1113 */
1114static ssize_t
1115delete_device_store(struct device *dev, struct device_attribute *attr,
1116                    const char *buf, size_t count)
1117{
1118        struct i2c_adapter *adap = to_i2c_adapter(dev);
1119        struct i2c_client *client, *next;
1120        unsigned short addr;
1121        char end;
1122        int res;
1123
1124        /* Parse parameters, reject extra parameters */
1125        res = sscanf(buf, "%hi%c", &addr, &end);
1126        if (res < 1) {
1127                dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
1128                return -EINVAL;
1129        }
1130        if (res > 1  && end != '\n') {
1131                dev_err(dev, "%s: Extra parameters\n", "delete_device");
1132                return -EINVAL;
1133        }
1134
1135        /* Make sure the device was added through sysfs */
1136        res = -ENOENT;
1137        mutex_lock_nested(&adap->userspace_clients_lock,
1138                          i2c_adapter_depth(adap));
1139        list_for_each_entry_safe(client, next, &adap->userspace_clients,
1140                                 detected) {
1141                if (i2c_encode_flags_to_addr(client) == addr) {
1142                        dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
1143                                 "delete_device", client->name, client->addr);
1144
1145                        list_del(&client->detected);
1146                        i2c_unregister_device(client);
1147                        res = count;
1148                        break;
1149                }
1150        }
1151        mutex_unlock(&adap->userspace_clients_lock);
1152
1153        if (res < 0)
1154                dev_err(dev, "%s: Can't find device in list\n",
1155                        "delete_device");
1156        return res;
1157}
1158static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
1159                                  delete_device_store);
1160
1161static struct attribute *i2c_adapter_attrs[] = {
1162        &dev_attr_name.attr,
1163        &dev_attr_new_device.attr,
1164        &dev_attr_delete_device.attr,
1165        NULL
1166};
1167ATTRIBUTE_GROUPS(i2c_adapter);
1168
1169struct device_type i2c_adapter_type = {
1170        .groups         = i2c_adapter_groups,
1171        .release        = i2c_adapter_dev_release,
1172};
1173EXPORT_SYMBOL_GPL(i2c_adapter_type);
1174
1175/**
1176 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
1177 * @dev: device, probably from some driver model iterator
1178 *
1179 * When traversing the driver model tree, perhaps using driver model
1180 * iterators like @device_for_each_child(), you can't assume very much
1181 * about the nodes you find.  Use this function to avoid oopses caused
1182 * by wrongly treating some non-I2C device as an i2c_adapter.
1183 */
1184struct i2c_adapter *i2c_verify_adapter(struct device *dev)
1185{
1186        return (dev->type == &i2c_adapter_type)
1187                        ? to_i2c_adapter(dev)
1188                        : NULL;
1189}
1190EXPORT_SYMBOL(i2c_verify_adapter);
1191
1192#ifdef CONFIG_I2C_COMPAT
1193static struct class_compat *i2c_adapter_compat_class;
1194#endif
1195
1196static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
1197{
1198        struct i2c_devinfo      *devinfo;
1199
1200        down_read(&__i2c_board_lock);
1201        list_for_each_entry(devinfo, &__i2c_board_list, list) {
1202                if (devinfo->busnum == adapter->nr &&
1203                    IS_ERR(i2c_new_client_device(adapter, &devinfo->board_info)))
1204                        dev_err(&adapter->dev,
1205                                "Can't create device at 0x%02x\n",
1206                                devinfo->board_info.addr);
1207        }
1208        up_read(&__i2c_board_lock);
1209}
1210
1211static int i2c_do_add_adapter(struct i2c_driver *driver,
1212                              struct i2c_adapter *adap)
1213{
1214        /* Detect supported devices on that bus, and instantiate them */
1215        i2c_detect(adap, driver);
1216
1217        return 0;
1218}
1219
1220static int __process_new_adapter(struct device_driver *d, void *data)
1221{
1222        return i2c_do_add_adapter(to_i2c_driver(d), data);
1223}
1224
1225static const struct i2c_lock_operations i2c_adapter_lock_ops = {
1226        .lock_bus =    i2c_adapter_lock_bus,
1227        .trylock_bus = i2c_adapter_trylock_bus,
1228        .unlock_bus =  i2c_adapter_unlock_bus,
1229};
1230
1231static void i2c_host_notify_irq_teardown(struct i2c_adapter *adap)
1232{
1233        struct irq_domain *domain = adap->host_notify_domain;
1234        irq_hw_number_t hwirq;
1235
1236        if (!domain)
1237                return;
1238
1239        for (hwirq = 0 ; hwirq < I2C_ADDR_7BITS_COUNT ; hwirq++)
1240                irq_dispose_mapping(irq_find_mapping(domain, hwirq));
1241
1242        irq_domain_remove(domain);
1243        adap->host_notify_domain = NULL;
1244}
1245
1246static int i2c_host_notify_irq_map(struct irq_domain *h,
1247                                          unsigned int virq,
1248                                          irq_hw_number_t hw_irq_num)
1249{
1250        irq_set_chip_and_handler(virq, &dummy_irq_chip, handle_simple_irq);
1251
1252        return 0;
1253}
1254
1255static const struct irq_domain_ops i2c_host_notify_irq_ops = {
1256        .map = i2c_host_notify_irq_map,
1257};
1258
1259static int i2c_setup_host_notify_irq_domain(struct i2c_adapter *adap)
1260{
1261        struct irq_domain *domain;
1262
1263        if (!i2c_check_functionality(adap, I2C_FUNC_SMBUS_HOST_NOTIFY))
1264                return 0;
1265
1266        domain = irq_domain_create_linear(adap->dev.fwnode,
1267                                          I2C_ADDR_7BITS_COUNT,
1268                                          &i2c_host_notify_irq_ops, adap);
1269        if (!domain)
1270                return -ENOMEM;
1271
1272        adap->host_notify_domain = domain;
1273
1274        return 0;
1275}
1276
1277/**
1278 * i2c_handle_smbus_host_notify - Forward a Host Notify event to the correct
1279 * I2C client.
1280 * @adap: the adapter
1281 * @addr: the I2C address of the notifying device
1282 * Context: can't sleep
1283 *
1284 * Helper function to be called from an I2C bus driver's interrupt
1285 * handler. It will schedule the Host Notify IRQ.
1286 */
1287int i2c_handle_smbus_host_notify(struct i2c_adapter *adap, unsigned short addr)
1288{
1289        int irq;
1290
1291        if (!adap)
1292                return -EINVAL;
1293
1294        irq = irq_find_mapping(adap->host_notify_domain, addr);
1295        if (irq <= 0)
1296                return -ENXIO;
1297
1298        generic_handle_irq(irq);
1299
1300        return 0;
1301}
1302EXPORT_SYMBOL_GPL(i2c_handle_smbus_host_notify);
1303
1304static int i2c_register_adapter(struct i2c_adapter *adap)
1305{
1306        int res = -EINVAL;
1307
1308        /* Can't register until after driver model init */
1309        if (WARN_ON(!is_registered)) {
1310                res = -EAGAIN;
1311                goto out_list;
1312        }
1313
1314        /* Sanity checks */
1315        if (WARN(!adap->name[0], "i2c adapter has no name"))
1316                goto out_list;
1317
1318        if (!adap->algo) {
1319                pr_err("adapter '%s': no algo supplied!\n", adap->name);
1320                goto out_list;
1321        }
1322
1323        if (!adap->lock_ops)
1324                adap->lock_ops = &i2c_adapter_lock_ops;
1325
1326        adap->locked_flags = 0;
1327        rt_mutex_init(&adap->bus_lock);
1328        rt_mutex_init(&adap->mux_lock);
1329        mutex_init(&adap->userspace_clients_lock);
1330        INIT_LIST_HEAD(&adap->userspace_clients);
1331
1332        /* Set default timeout to 1 second if not already set */
1333        if (adap->timeout == 0)
1334                adap->timeout = HZ;
1335
1336        /* register soft irqs for Host Notify */
1337        res = i2c_setup_host_notify_irq_domain(adap);
1338        if (res) {
1339                pr_err("adapter '%s': can't create Host Notify IRQs (%d)\n",
1340                       adap->name, res);
1341                goto out_list;
1342        }
1343
1344        dev_set_name(&adap->dev, "i2c-%d", adap->nr);
1345        adap->dev.bus = &i2c_bus_type;
1346        adap->dev.type = &i2c_adapter_type;
1347        res = device_register(&adap->dev);
1348        if (res) {
1349                pr_err("adapter '%s': can't register device (%d)\n", adap->name, res);
1350                goto out_list;
1351        }
1352
1353        res = of_i2c_setup_smbus_alert(adap);
1354        if (res)
1355                goto out_reg;
1356
1357        dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
1358
1359        pm_runtime_no_callbacks(&adap->dev);
1360        pm_suspend_ignore_children(&adap->dev, true);
1361        pm_runtime_enable(&adap->dev);
1362
1363#ifdef CONFIG_I2C_COMPAT
1364        res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
1365                                       adap->dev.parent);
1366        if (res)
1367                dev_warn(&adap->dev,
1368                         "Failed to create compatibility class link\n");
1369#endif
1370
1371        i2c_init_recovery(adap);
1372
1373        /* create pre-declared device nodes */
1374        of_i2c_register_devices(adap);
1375        i2c_acpi_register_devices(adap);
1376        i2c_acpi_install_space_handler(adap);
1377
1378        if (adap->nr < __i2c_first_dynamic_bus_num)
1379                i2c_scan_static_board_info(adap);
1380
1381        /* Notify drivers */
1382        mutex_lock(&core_lock);
1383        bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
1384        mutex_unlock(&core_lock);
1385
1386        return 0;
1387
1388out_reg:
1389        init_completion(&adap->dev_released);
1390        device_unregister(&adap->dev);
1391        wait_for_completion(&adap->dev_released);
1392out_list:
1393        mutex_lock(&core_lock);
1394        idr_remove(&i2c_adapter_idr, adap->nr);
1395        mutex_unlock(&core_lock);
1396        return res;
1397}
1398
1399/**
1400 * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
1401 * @adap: the adapter to register (with adap->nr initialized)
1402 * Context: can sleep
1403 *
1404 * See i2c_add_numbered_adapter() for details.
1405 */
1406static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
1407{
1408        int id;
1409
1410        mutex_lock(&core_lock);
1411        id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1, GFP_KERNEL);
1412        mutex_unlock(&core_lock);
1413        if (WARN(id < 0, "couldn't get idr"))
1414                return id == -ENOSPC ? -EBUSY : id;
1415
1416        return i2c_register_adapter(adap);
1417}
1418
1419/**
1420 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
1421 * @adapter: the adapter to add
1422 * Context: can sleep
1423 *
1424 * This routine is used to declare an I2C adapter when its bus number
1425 * doesn't matter or when its bus number is specified by an dt alias.
1426 * Examples of bases when the bus number doesn't matter: I2C adapters
1427 * dynamically added by USB links or PCI plugin cards.
1428 *
1429 * When this returns zero, a new bus number was allocated and stored
1430 * in adap->nr, and the specified adapter became available for clients.
1431 * Otherwise, a negative errno value is returned.
1432 */
1433int i2c_add_adapter(struct i2c_adapter *adapter)
1434{
1435        struct device *dev = &adapter->dev;
1436        int id;
1437
1438        if (dev->of_node) {
1439                id = of_alias_get_id(dev->of_node, "i2c");
1440                if (id >= 0) {
1441                        adapter->nr = id;
1442                        return __i2c_add_numbered_adapter(adapter);
1443                }
1444        }
1445
1446        mutex_lock(&core_lock);
1447        id = idr_alloc(&i2c_adapter_idr, adapter,
1448                       __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
1449        mutex_unlock(&core_lock);
1450        if (WARN(id < 0, "couldn't get idr"))
1451                return id;
1452
1453        adapter->nr = id;
1454
1455        return i2c_register_adapter(adapter);
1456}
1457EXPORT_SYMBOL(i2c_add_adapter);
1458
1459/**
1460 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
1461 * @adap: the adapter to register (with adap->nr initialized)
1462 * Context: can sleep
1463 *
1464 * This routine is used to declare an I2C adapter when its bus number
1465 * matters.  For example, use it for I2C adapters from system-on-chip CPUs,
1466 * or otherwise built in to the system's mainboard, and where i2c_board_info
1467 * is used to properly configure I2C devices.
1468 *
1469 * If the requested bus number is set to -1, then this function will behave
1470 * identically to i2c_add_adapter, and will dynamically assign a bus number.
1471 *
1472 * If no devices have pre-been declared for this bus, then be sure to
1473 * register the adapter before any dynamically allocated ones.  Otherwise
1474 * the required bus ID may not be available.
1475 *
1476 * When this returns zero, the specified adapter became available for
1477 * clients using the bus number provided in adap->nr.  Also, the table
1478 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
1479 * and the appropriate driver model device nodes are created.  Otherwise, a
1480 * negative errno value is returned.
1481 */
1482int i2c_add_numbered_adapter(struct i2c_adapter *adap)
1483{
1484        if (adap->nr == -1) /* -1 means dynamically assign bus id */
1485                return i2c_add_adapter(adap);
1486
1487        return __i2c_add_numbered_adapter(adap);
1488}
1489EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
1490
1491static void i2c_do_del_adapter(struct i2c_driver *driver,
1492                              struct i2c_adapter *adapter)
1493{
1494        struct i2c_client *client, *_n;
1495
1496        /* Remove the devices we created ourselves as the result of hardware
1497         * probing (using a driver's detect method) */
1498        list_for_each_entry_safe(client, _n, &driver->clients, detected) {
1499                if (client->adapter == adapter) {
1500                        dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
1501                                client->name, client->addr);
1502                        list_del(&client->detected);
1503                        i2c_unregister_device(client);
1504                }
1505        }
1506}
1507
1508static int __unregister_client(struct device *dev, void *dummy)
1509{
1510        struct i2c_client *client = i2c_verify_client(dev);
1511        if (client && strcmp(client->name, "dummy"))
1512                i2c_unregister_device(client);
1513        return 0;
1514}
1515
1516static int __unregister_dummy(struct device *dev, void *dummy)
1517{
1518        struct i2c_client *client = i2c_verify_client(dev);
1519        i2c_unregister_device(client);
1520        return 0;
1521}
1522
1523static int __process_removed_adapter(struct device_driver *d, void *data)
1524{
1525        i2c_do_del_adapter(to_i2c_driver(d), data);
1526        return 0;
1527}
1528
1529/**
1530 * i2c_del_adapter - unregister I2C adapter
1531 * @adap: the adapter being unregistered
1532 * Context: can sleep
1533 *
1534 * This unregisters an I2C adapter which was previously registered
1535 * by @i2c_add_adapter or @i2c_add_numbered_adapter.
1536 */
1537void i2c_del_adapter(struct i2c_adapter *adap)
1538{
1539        struct i2c_adapter *found;
1540        struct i2c_client *client, *next;
1541
1542        /* First make sure that this adapter was ever added */
1543        mutex_lock(&core_lock);
1544        found = idr_find(&i2c_adapter_idr, adap->nr);
1545        mutex_unlock(&core_lock);
1546        if (found != adap) {
1547                pr_debug("attempting to delete unregistered adapter [%s]\n", adap->name);
1548                return;
1549        }
1550
1551        i2c_acpi_remove_space_handler(adap);
1552        /* Tell drivers about this removal */
1553        mutex_lock(&core_lock);
1554        bus_for_each_drv(&i2c_bus_type, NULL, adap,
1555                               __process_removed_adapter);
1556        mutex_unlock(&core_lock);
1557
1558        /* Remove devices instantiated from sysfs */
1559        mutex_lock_nested(&adap->userspace_clients_lock,
1560                          i2c_adapter_depth(adap));
1561        list_for_each_entry_safe(client, next, &adap->userspace_clients,
1562                                 detected) {
1563                dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
1564                        client->addr);
1565                list_del(&client->detected);
1566                i2c_unregister_device(client);
1567        }
1568        mutex_unlock(&adap->userspace_clients_lock);
1569
1570        /* Detach any active clients. This can't fail, thus we do not
1571         * check the returned value. This is a two-pass process, because
1572         * we can't remove the dummy devices during the first pass: they
1573         * could have been instantiated by real devices wishing to clean
1574         * them up properly, so we give them a chance to do that first. */
1575        device_for_each_child(&adap->dev, NULL, __unregister_client);
1576        device_for_each_child(&adap->dev, NULL, __unregister_dummy);
1577
1578#ifdef CONFIG_I2C_COMPAT
1579        class_compat_remove_link(i2c_adapter_compat_class, &adap->dev,
1580                                 adap->dev.parent);
1581#endif
1582
1583        /* device name is gone after device_unregister */
1584        dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
1585
1586        pm_runtime_disable(&adap->dev);
1587
1588        i2c_host_notify_irq_teardown(adap);
1589
1590        /* wait until all references to the device are gone
1591         *
1592         * FIXME: This is old code and should ideally be replaced by an
1593         * alternative which results in decoupling the lifetime of the struct
1594         * device from the i2c_adapter, like spi or netdev do. Any solution
1595         * should be thoroughly tested with DEBUG_KOBJECT_RELEASE enabled!
1596         */
1597        init_completion(&adap->dev_released);
1598        device_unregister(&adap->dev);
1599        wait_for_completion(&adap->dev_released);
1600
1601        /* free bus id */
1602        mutex_lock(&core_lock);
1603        idr_remove(&i2c_adapter_idr, adap->nr);
1604        mutex_unlock(&core_lock);
1605
1606        /* Clear the device structure in case this adapter is ever going to be
1607           added again */
1608        memset(&adap->dev, 0, sizeof(adap->dev));
1609}
1610EXPORT_SYMBOL(i2c_del_adapter);
1611
1612/**
1613 * i2c_parse_fw_timings - get I2C related timing parameters from firmware
1614 * @dev: The device to scan for I2C timing properties
1615 * @t: the i2c_timings struct to be filled with values
1616 * @use_defaults: bool to use sane defaults derived from the I2C specification
1617 *                when properties are not found, otherwise use 0
1618 *
1619 * Scan the device for the generic I2C properties describing timing parameters
1620 * for the signal and fill the given struct with the results. If a property was
1621 * not found and use_defaults was true, then maximum timings are assumed which
1622 * are derived from the I2C specification. If use_defaults is not used, the
1623 * results will be 0, so drivers can apply their own defaults later. The latter
1624 * is mainly intended for avoiding regressions of existing drivers which want
1625 * to switch to this function. New drivers almost always should use the defaults.
1626 */
1627
1628void i2c_parse_fw_timings(struct device *dev, struct i2c_timings *t, bool use_defaults)
1629{
1630        int ret;
1631
1632        memset(t, 0, sizeof(*t));
1633
1634        ret = device_property_read_u32(dev, "clock-frequency", &t->bus_freq_hz);
1635        if (ret && use_defaults)
1636                t->bus_freq_hz = I2C_MAX_STANDARD_MODE_FREQ;
1637
1638        ret = device_property_read_u32(dev, "i2c-scl-rising-time-ns", &t->scl_rise_ns);
1639        if (ret && use_defaults) {
1640                if (t->bus_freq_hz <= I2C_MAX_STANDARD_MODE_FREQ)
1641                        t->scl_rise_ns = 1000;
1642                else if (t->bus_freq_hz <= I2C_MAX_FAST_MODE_FREQ)
1643                        t->scl_rise_ns = 300;
1644                else
1645                        t->scl_rise_ns = 120;
1646        }
1647
1648        ret = device_property_read_u32(dev, "i2c-scl-falling-time-ns", &t->scl_fall_ns);
1649        if (ret && use_defaults) {
1650                if (t->bus_freq_hz <= I2C_MAX_FAST_MODE_FREQ)
1651                        t->scl_fall_ns = 300;
1652                else
1653                        t->scl_fall_ns = 120;
1654        }
1655
1656        device_property_read_u32(dev, "i2c-scl-internal-delay-ns", &t->scl_int_delay_ns);
1657
1658        ret = device_property_read_u32(dev, "i2c-sda-falling-time-ns", &t->sda_fall_ns);
1659        if (ret && use_defaults)
1660                t->sda_fall_ns = t->scl_fall_ns;
1661
1662        device_property_read_u32(dev, "i2c-sda-hold-time-ns", &t->sda_hold_ns);
1663
1664        device_property_read_u32(dev, "i2c-digital-filter-width-ns",
1665                                 &t->digital_filter_width_ns);
1666
1667        device_property_read_u32(dev, "i2c-analog-filter-cutoff-frequency",
1668                                 &t->analog_filter_cutoff_freq_hz);
1669}
1670EXPORT_SYMBOL_GPL(i2c_parse_fw_timings);
1671
1672/* ------------------------------------------------------------------------- */
1673
1674int i2c_for_each_dev(void *data, int (*fn)(struct device *dev, void *data))
1675{
1676        int res;
1677
1678        mutex_lock(&core_lock);
1679        res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
1680        mutex_unlock(&core_lock);
1681
1682        return res;
1683}
1684EXPORT_SYMBOL_GPL(i2c_for_each_dev);
1685
1686static int __process_new_driver(struct device *dev, void *data)
1687{
1688        if (dev->type != &i2c_adapter_type)
1689                return 0;
1690        return i2c_do_add_adapter(data, to_i2c_adapter(dev));
1691}
1692
1693/*
1694 * An i2c_driver is used with one or more i2c_client (device) nodes to access
1695 * i2c slave chips, on a bus instance associated with some i2c_adapter.
1696 */
1697
1698int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
1699{
1700        int res;
1701
1702        /* Can't register until after driver model init */
1703        if (WARN_ON(!is_registered))
1704                return -EAGAIN;
1705
1706        /* add the driver to the list of i2c drivers in the driver core */
1707        driver->driver.owner = owner;
1708        driver->driver.bus = &i2c_bus_type;
1709        INIT_LIST_HEAD(&driver->clients);
1710
1711        /* When registration returns, the driver core
1712         * will have called probe() for all matching-but-unbound devices.
1713         */
1714        res = driver_register(&driver->driver);
1715        if (res)
1716                return res;
1717
1718        pr_debug("driver [%s] registered\n", driver->driver.name);
1719
1720        /* Walk the adapters that are already present */
1721        i2c_for_each_dev(driver, __process_new_driver);
1722
1723        return 0;
1724}
1725EXPORT_SYMBOL(i2c_register_driver);
1726
1727static int __process_removed_driver(struct device *dev, void *data)
1728{
1729        if (dev->type == &i2c_adapter_type)
1730                i2c_do_del_adapter(data, to_i2c_adapter(dev));
1731        return 0;
1732}
1733
1734/**
1735 * i2c_del_driver - unregister I2C driver
1736 * @driver: the driver being unregistered
1737 * Context: can sleep
1738 */
1739void i2c_del_driver(struct i2c_driver *driver)
1740{
1741        i2c_for_each_dev(driver, __process_removed_driver);
1742
1743        driver_unregister(&driver->driver);
1744        pr_debug("driver [%s] unregistered\n", driver->driver.name);
1745}
1746EXPORT_SYMBOL(i2c_del_driver);
1747
1748/* ------------------------------------------------------------------------- */
1749
1750struct i2c_cmd_arg {
1751        unsigned        cmd;
1752        void            *arg;
1753};
1754
1755static int i2c_cmd(struct device *dev, void *_arg)
1756{
1757        struct i2c_client       *client = i2c_verify_client(dev);
1758        struct i2c_cmd_arg      *arg = _arg;
1759        struct i2c_driver       *driver;
1760
1761        if (!client || !client->dev.driver)
1762                return 0;
1763
1764        driver = to_i2c_driver(client->dev.driver);
1765        if (driver->command)
1766                driver->command(client, arg->cmd, arg->arg);
1767        return 0;
1768}
1769
1770void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
1771{
1772        struct i2c_cmd_arg      cmd_arg;
1773
1774        cmd_arg.cmd = cmd;
1775        cmd_arg.arg = arg;
1776        device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
1777}
1778EXPORT_SYMBOL(i2c_clients_command);
1779
1780static int __init i2c_init(void)
1781{
1782        int retval;
1783
1784        retval = of_alias_get_highest_id("i2c");
1785
1786        down_write(&__i2c_board_lock);
1787        if (retval >= __i2c_first_dynamic_bus_num)
1788                __i2c_first_dynamic_bus_num = retval + 1;
1789        up_write(&__i2c_board_lock);
1790
1791        retval = bus_register(&i2c_bus_type);
1792        if (retval)
1793                return retval;
1794
1795        is_registered = true;
1796
1797#ifdef CONFIG_I2C_COMPAT
1798        i2c_adapter_compat_class = class_compat_register("i2c-adapter");
1799        if (!i2c_adapter_compat_class) {
1800                retval = -ENOMEM;
1801                goto bus_err;
1802        }
1803#endif
1804        retval = i2c_add_driver(&dummy_driver);
1805        if (retval)
1806                goto class_err;
1807
1808        if (IS_ENABLED(CONFIG_OF_DYNAMIC))
1809                WARN_ON(of_reconfig_notifier_register(&i2c_of_notifier));
1810        if (IS_ENABLED(CONFIG_ACPI))
1811                WARN_ON(acpi_reconfig_notifier_register(&i2c_acpi_notifier));
1812
1813        return 0;
1814
1815class_err:
1816#ifdef CONFIG_I2C_COMPAT
1817        class_compat_unregister(i2c_adapter_compat_class);
1818bus_err:
1819#endif
1820        is_registered = false;
1821        bus_unregister(&i2c_bus_type);
1822        return retval;
1823}
1824
1825static void __exit i2c_exit(void)
1826{
1827        if (IS_ENABLED(CONFIG_ACPI))
1828                WARN_ON(acpi_reconfig_notifier_unregister(&i2c_acpi_notifier));
1829        if (IS_ENABLED(CONFIG_OF_DYNAMIC))
1830                WARN_ON(of_reconfig_notifier_unregister(&i2c_of_notifier));
1831        i2c_del_driver(&dummy_driver);
1832#ifdef CONFIG_I2C_COMPAT
1833        class_compat_unregister(i2c_adapter_compat_class);
1834#endif
1835        bus_unregister(&i2c_bus_type);
1836        tracepoint_synchronize_unregister();
1837}
1838
1839/* We must initialize early, because some subsystems register i2c drivers
1840 * in subsys_initcall() code, but are linked (and initialized) before i2c.
1841 */
1842postcore_initcall(i2c_init);
1843module_exit(i2c_exit);
1844
1845/* ----------------------------------------------------
1846 * the functional interface to the i2c busses.
1847 * ----------------------------------------------------
1848 */
1849
1850/* Check if val is exceeding the quirk IFF quirk is non 0 */
1851#define i2c_quirk_exceeded(val, quirk) ((quirk) && ((val) > (quirk)))
1852
1853static int i2c_quirk_error(struct i2c_adapter *adap, struct i2c_msg *msg, char *err_msg)
1854{
1855        dev_err_ratelimited(&adap->dev, "adapter quirk: %s (addr 0x%04x, size %u, %s)\n",
1856                            err_msg, msg->addr, msg->len,
1857                            msg->flags & I2C_M_RD ? "read" : "write");
1858        return -EOPNOTSUPP;
1859}
1860
1861static int i2c_check_for_quirks(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1862{
1863        const struct i2c_adapter_quirks *q = adap->quirks;
1864        int max_num = q->max_num_msgs, i;
1865        bool do_len_check = true;
1866
1867        if (q->flags & I2C_AQ_COMB) {
1868                max_num = 2;
1869
1870                /* special checks for combined messages */
1871                if (num == 2) {
1872                        if (q->flags & I2C_AQ_COMB_WRITE_FIRST && msgs[0].flags & I2C_M_RD)
1873                                return i2c_quirk_error(adap, &msgs[0], "1st comb msg must be write");
1874
1875                        if (q->flags & I2C_AQ_COMB_READ_SECOND && !(msgs[1].flags & I2C_M_RD))
1876                                return i2c_quirk_error(adap, &msgs[1], "2nd comb msg must be read");
1877
1878                        if (q->flags & I2C_AQ_COMB_SAME_ADDR && msgs[0].addr != msgs[1].addr)
1879                                return i2c_quirk_error(adap, &msgs[0], "comb msg only to same addr");
1880
1881                        if (i2c_quirk_exceeded(msgs[0].len, q->max_comb_1st_msg_len))
1882                                return i2c_quirk_error(adap, &msgs[0], "msg too long");
1883
1884                        if (i2c_quirk_exceeded(msgs[1].len, q->max_comb_2nd_msg_len))
1885                                return i2c_quirk_error(adap, &msgs[1], "msg too long");
1886
1887                        do_len_check = false;
1888                }
1889        }
1890
1891        if (i2c_quirk_exceeded(num, max_num))
1892                return i2c_quirk_error(adap, &msgs[0], "too many messages");
1893
1894        for (i = 0; i < num; i++) {
1895                u16 len = msgs[i].len;
1896
1897                if (msgs[i].flags & I2C_M_RD) {
1898                        if (do_len_check && i2c_quirk_exceeded(len, q->max_read_len))
1899                                return i2c_quirk_error(adap, &msgs[i], "msg too long");
1900
1901                        if (q->flags & I2C_AQ_NO_ZERO_LEN_READ && len == 0)
1902                                return i2c_quirk_error(adap, &msgs[i], "no zero length");
1903                } else {
1904                        if (do_len_check && i2c_quirk_exceeded(len, q->max_write_len))
1905                                return i2c_quirk_error(adap, &msgs[i], "msg too long");
1906
1907                        if (q->flags & I2C_AQ_NO_ZERO_LEN_WRITE && len == 0)
1908                                return i2c_quirk_error(adap, &msgs[i], "no zero length");
1909                }
1910        }
1911
1912        return 0;
1913}
1914
1915/**
1916 * __i2c_transfer - unlocked flavor of i2c_transfer
1917 * @adap: Handle to I2C bus
1918 * @msgs: One or more messages to execute before STOP is issued to
1919 *      terminate the operation; each message begins with a START.
1920 * @num: Number of messages to be executed.
1921 *
1922 * Returns negative errno, else the number of messages executed.
1923 *
1924 * Adapter lock must be held when calling this function. No debug logging
1925 * takes place. adap->algo->master_xfer existence isn't checked.
1926 */
1927int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1928{
1929        unsigned long orig_jiffies;
1930        int ret, try;
1931
1932        if (WARN_ON(!msgs || num < 1))
1933                return -EINVAL;
1934
1935        ret = __i2c_check_suspended(adap);
1936        if (ret)
1937                return ret;
1938
1939        if (adap->quirks && i2c_check_for_quirks(adap, msgs, num))
1940                return -EOPNOTSUPP;
1941
1942        /*
1943         * i2c_trace_msg_key gets enabled when tracepoint i2c_transfer gets
1944         * enabled.  This is an efficient way of keeping the for-loop from
1945         * being executed when not needed.
1946         */
1947        if (static_branch_unlikely(&i2c_trace_msg_key)) {
1948                int i;
1949                for (i = 0; i < num; i++)
1950                        if (msgs[i].flags & I2C_M_RD)
1951                                trace_i2c_read(adap, &msgs[i], i);
1952                        else
1953                                trace_i2c_write(adap, &msgs[i], i);
1954        }
1955
1956        /* Retry automatically on arbitration loss */
1957        orig_jiffies = jiffies;
1958        for (ret = 0, try = 0; try <= adap->retries; try++) {
1959                if (i2c_in_atomic_xfer_mode() && adap->algo->master_xfer_atomic)
1960                        ret = adap->algo->master_xfer_atomic(adap, msgs, num);
1961                else
1962                        ret = adap->algo->master_xfer(adap, msgs, num);
1963
1964                if (ret != -EAGAIN)
1965                        break;
1966                if (time_after(jiffies, orig_jiffies + adap->timeout))
1967                        break;
1968        }
1969
1970        if (static_branch_unlikely(&i2c_trace_msg_key)) {
1971                int i;
1972                for (i = 0; i < ret; i++)
1973                        if (msgs[i].flags & I2C_M_RD)
1974                                trace_i2c_reply(adap, &msgs[i], i);
1975                trace_i2c_result(adap, num, ret);
1976        }
1977
1978        return ret;
1979}
1980EXPORT_SYMBOL(__i2c_transfer);
1981
1982/**
1983 * i2c_transfer - execute a single or combined I2C message
1984 * @adap: Handle to I2C bus
1985 * @msgs: One or more messages to execute before STOP is issued to
1986 *      terminate the operation; each message begins with a START.
1987 * @num: Number of messages to be executed.
1988 *
1989 * Returns negative errno, else the number of messages executed.
1990 *
1991 * Note that there is no requirement that each message be sent to
1992 * the same slave address, although that is the most common model.
1993 */
1994int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1995{
1996        int ret;
1997
1998        if (!adap->algo->master_xfer) {
1999                dev_dbg(&adap->dev, "I2C level transfers not supported\n");
2000                return -EOPNOTSUPP;
2001        }
2002
2003        /* REVISIT the fault reporting model here is weak:
2004         *
2005         *  - When we get an error after receiving N bytes from a slave,
2006         *    there is no way to report "N".
2007         *
2008         *  - When we get a NAK after transmitting N bytes to a slave,
2009         *    there is no way to report "N" ... or to let the master
2010         *    continue executing the rest of this combined message, if
2011         *    that's the appropriate response.
2012         *
2013         *  - When for example "num" is two and we successfully complete
2014         *    the first message but get an error part way through the
2015         *    second, it's unclear whether that should be reported as
2016         *    one (discarding status on the second message) or errno
2017         *    (discarding status on the first one).
2018         */
2019        ret = __i2c_lock_bus_helper(adap);
2020        if (ret)
2021                return ret;
2022
2023        ret = __i2c_transfer(adap, msgs, num);
2024        i2c_unlock_bus(adap, I2C_LOCK_SEGMENT);
2025
2026        return ret;
2027}
2028EXPORT_SYMBOL(i2c_transfer);
2029
2030/**
2031 * i2c_transfer_buffer_flags - issue a single I2C message transferring data
2032 *                             to/from a buffer
2033 * @client: Handle to slave device
2034 * @buf: Where the data is stored
2035 * @count: How many bytes to transfer, must be less than 64k since msg.len is u16
2036 * @flags: The flags to be used for the message, e.g. I2C_M_RD for reads
2037 *
2038 * Returns negative errno, or else the number of bytes transferred.
2039 */
2040int i2c_transfer_buffer_flags(const struct i2c_client *client, char *buf,
2041                              int count, u16 flags)
2042{
2043        int ret;
2044        struct i2c_msg msg = {
2045                .addr = client->addr,
2046                .flags = flags | (client->flags & I2C_M_TEN),
2047                .len = count,
2048                .buf = buf,
2049        };
2050
2051        ret = i2c_transfer(client->adapter, &msg, 1);
2052
2053        /*
2054         * If everything went ok (i.e. 1 msg transferred), return #bytes
2055         * transferred, else error code.
2056         */
2057        return (ret == 1) ? count : ret;
2058}
2059EXPORT_SYMBOL(i2c_transfer_buffer_flags);
2060
2061/**
2062 * i2c_get_device_id - get manufacturer, part id and die revision of a device
2063 * @client: The device to query
2064 * @id: The queried information
2065 *
2066 * Returns negative errno on error, zero on success.
2067 */
2068int i2c_get_device_id(const struct i2c_client *client,
2069                      struct i2c_device_identity *id)
2070{
2071        struct i2c_adapter *adap = client->adapter;
2072        union i2c_smbus_data raw_id;
2073        int ret;
2074
2075        if (!i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_I2C_BLOCK))
2076                return -EOPNOTSUPP;
2077
2078        raw_id.block[0] = 3;
2079        ret = i2c_smbus_xfer(adap, I2C_ADDR_DEVICE_ID, 0,
2080                             I2C_SMBUS_READ, client->addr << 1,
2081                             I2C_SMBUS_I2C_BLOCK_DATA, &raw_id);
2082        if (ret)
2083                return ret;
2084
2085        id->manufacturer_id = (raw_id.block[1] << 4) | (raw_id.block[2] >> 4);
2086        id->part_id = ((raw_id.block[2] & 0xf) << 5) | (raw_id.block[3] >> 3);
2087        id->die_revision = raw_id.block[3] & 0x7;
2088        return 0;
2089}
2090EXPORT_SYMBOL_GPL(i2c_get_device_id);
2091
2092/* ----------------------------------------------------
2093 * the i2c address scanning function
2094 * Will not work for 10-bit addresses!
2095 * ----------------------------------------------------
2096 */
2097
2098/*
2099 * Legacy default probe function, mostly relevant for SMBus. The default
2100 * probe method is a quick write, but it is known to corrupt the 24RF08
2101 * EEPROMs due to a state machine bug, and could also irreversibly
2102 * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
2103 * we use a short byte read instead. Also, some bus drivers don't implement
2104 * quick write, so we fallback to a byte read in that case too.
2105 * On x86, there is another special case for FSC hardware monitoring chips,
2106 * which want regular byte reads (address 0x73.) Fortunately, these are the
2107 * only known chips using this I2C address on PC hardware.
2108 * Returns 1 if probe succeeded, 0 if not.
2109 */
2110static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
2111{
2112        int err;
2113        union i2c_smbus_data dummy;
2114
2115#ifdef CONFIG_X86
2116        if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
2117         && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
2118                err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2119                                     I2C_SMBUS_BYTE_DATA, &dummy);
2120        else
2121#endif
2122        if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
2123         && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
2124                err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
2125                                     I2C_SMBUS_QUICK, NULL);
2126        else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
2127                err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2128                                     I2C_SMBUS_BYTE, &dummy);
2129        else {
2130                dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n",
2131                         addr);
2132                err = -EOPNOTSUPP;
2133        }
2134
2135        return err >= 0;
2136}
2137
2138static int i2c_detect_address(struct i2c_client *temp_client,
2139                              struct i2c_driver *driver)
2140{
2141        struct i2c_board_info info;
2142        struct i2c_adapter *adapter = temp_client->adapter;
2143        int addr = temp_client->addr;
2144        int err;
2145
2146        /* Make sure the address is valid */
2147        err = i2c_check_7bit_addr_validity_strict(addr);
2148        if (err) {
2149                dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
2150                         addr);
2151                return err;
2152        }
2153
2154        /* Skip if already in use (7 bit, no need to encode flags) */
2155        if (i2c_check_addr_busy(adapter, addr))
2156                return 0;
2157
2158        /* Make sure there is something at this address */
2159        if (!i2c_default_probe(adapter, addr))
2160                return 0;
2161
2162        /* Finally call the custom detection function */
2163        memset(&info, 0, sizeof(struct i2c_board_info));
2164        info.addr = addr;
2165        err = driver->detect(temp_client, &info);
2166        if (err) {
2167                /* -ENODEV is returned if the detection fails. We catch it
2168                   here as this isn't an error. */
2169                return err == -ENODEV ? 0 : err;
2170        }
2171
2172        /* Consistency check */
2173        if (info.type[0] == '\0') {
2174                dev_err(&adapter->dev,
2175                        "%s detection function provided no name for 0x%x\n",
2176                        driver->driver.name, addr);
2177        } else {
2178                struct i2c_client *client;
2179
2180                /* Detection succeeded, instantiate the device */
2181                if (adapter->class & I2C_CLASS_DEPRECATED)
2182                        dev_warn(&adapter->dev,
2183                                "This adapter will soon drop class based instantiation of devices. "
2184                                "Please make sure client 0x%02x gets instantiated by other means. "
2185                                "Check 'Documentation/i2c/instantiating-devices' for details.\n",
2186                                info.addr);
2187
2188                dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
2189                        info.type, info.addr);
2190                client = i2c_new_client_device(adapter, &info);
2191                if (!IS_ERR(client))
2192                        list_add_tail(&client->detected, &driver->clients);
2193                else
2194                        dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
2195                                info.type, info.addr);
2196        }
2197        return 0;
2198}
2199
2200static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
2201{
2202        const unsigned short *address_list;
2203        struct i2c_client *temp_client;
2204        int i, err = 0;
2205        int adap_id = i2c_adapter_id(adapter);
2206
2207        address_list = driver->address_list;
2208        if (!driver->detect || !address_list)
2209                return 0;
2210
2211        /* Warn that the adapter lost class based instantiation */
2212        if (adapter->class == I2C_CLASS_DEPRECATED) {
2213                dev_dbg(&adapter->dev,
2214                        "This adapter dropped support for I2C classes and won't auto-detect %s devices anymore. "
2215                        "If you need it, check 'Documentation/i2c/instantiating-devices' for alternatives.\n",
2216                        driver->driver.name);
2217                return 0;
2218        }
2219
2220        /* Stop here if the classes do not match */
2221        if (!(adapter->class & driver->class))
2222                return 0;
2223
2224        /* Set up a temporary client to help detect callback */
2225        temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
2226        if (!temp_client)
2227                return -ENOMEM;
2228        temp_client->adapter = adapter;
2229
2230        for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
2231                dev_dbg(&adapter->dev,
2232                        "found normal entry for adapter %d, addr 0x%02x\n",
2233                        adap_id, address_list[i]);
2234                temp_client->addr = address_list[i];
2235                err = i2c_detect_address(temp_client, driver);
2236                if (unlikely(err))
2237                        break;
2238        }
2239
2240        kfree(temp_client);
2241        return err;
2242}
2243
2244int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
2245{
2246        return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2247                              I2C_SMBUS_QUICK, NULL) >= 0;
2248}
2249EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
2250
2251struct i2c_client *
2252i2c_new_scanned_device(struct i2c_adapter *adap,
2253                       struct i2c_board_info *info,
2254                       unsigned short const *addr_list,
2255                       int (*probe)(struct i2c_adapter *adap, unsigned short addr))
2256{
2257        int i;
2258
2259        if (!probe)
2260                probe = i2c_default_probe;
2261
2262        for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
2263                /* Check address validity */
2264                if (i2c_check_7bit_addr_validity_strict(addr_list[i]) < 0) {
2265                        dev_warn(&adap->dev, "Invalid 7-bit address 0x%02x\n",
2266                                 addr_list[i]);
2267                        continue;
2268                }
2269
2270                /* Check address availability (7 bit, no need to encode flags) */
2271                if (i2c_check_addr_busy(adap, addr_list[i])) {
2272                        dev_dbg(&adap->dev,
2273                                "Address 0x%02x already in use, not probing\n",
2274                                addr_list[i]);
2275                        continue;
2276                }
2277
2278                /* Test address responsiveness */
2279                if (probe(adap, addr_list[i]))
2280                        break;
2281        }
2282
2283        if (addr_list[i] == I2C_CLIENT_END) {
2284                dev_dbg(&adap->dev, "Probing failed, no device found\n");
2285                return ERR_PTR(-ENODEV);
2286        }
2287
2288        info->addr = addr_list[i];
2289        return i2c_new_client_device(adap, info);
2290}
2291EXPORT_SYMBOL_GPL(i2c_new_scanned_device);
2292
2293struct i2c_client *
2294i2c_new_probed_device(struct i2c_adapter *adap,
2295                      struct i2c_board_info *info,
2296                      unsigned short const *addr_list,
2297                      int (*probe)(struct i2c_adapter *adap, unsigned short addr))
2298{
2299        struct i2c_client *client;
2300
2301        client = i2c_new_scanned_device(adap, info, addr_list, probe);
2302        return IS_ERR(client) ? NULL : client;
2303}
2304EXPORT_SYMBOL_GPL(i2c_new_probed_device);
2305
2306struct i2c_adapter *i2c_get_adapter(int nr)
2307{
2308        struct i2c_adapter *adapter;
2309
2310        mutex_lock(&core_lock);
2311        adapter = idr_find(&i2c_adapter_idr, nr);
2312        if (!adapter)
2313                goto exit;
2314
2315        if (try_module_get(adapter->owner))
2316                get_device(&adapter->dev);
2317        else
2318                adapter = NULL;
2319
2320 exit:
2321        mutex_unlock(&core_lock);
2322        return adapter;
2323}
2324EXPORT_SYMBOL(i2c_get_adapter);
2325
2326void i2c_put_adapter(struct i2c_adapter *adap)
2327{
2328        if (!adap)
2329                return;
2330
2331        put_device(&adap->dev);
2332        module_put(adap->owner);
2333}
2334EXPORT_SYMBOL(i2c_put_adapter);
2335
2336/**
2337 * i2c_get_dma_safe_msg_buf() - get a DMA safe buffer for the given i2c_msg
2338 * @msg: the message to be checked
2339 * @threshold: the minimum number of bytes for which using DMA makes sense.
2340 *             Should at least be 1.
2341 *
2342 * Return: NULL if a DMA safe buffer was not obtained. Use msg->buf with PIO.
2343 *         Or a valid pointer to be used with DMA. After use, release it by
2344 *         calling i2c_put_dma_safe_msg_buf().
2345 *
2346 * This function must only be called from process context!
2347 */
2348u8 *i2c_get_dma_safe_msg_buf(struct i2c_msg *msg, unsigned int threshold)
2349{
2350        /* also skip 0-length msgs for bogus thresholds of 0 */
2351        if (!threshold)
2352                pr_debug("DMA buffer for addr=0x%02x with length 0 is bogus\n",
2353                         msg->addr);
2354        if (msg->len < threshold || msg->len == 0)
2355                return NULL;
2356
2357        if (msg->flags & I2C_M_DMA_SAFE)
2358                return msg->buf;
2359
2360        pr_debug("using bounce buffer for addr=0x%02x, len=%d\n",
2361                 msg->addr, msg->len);
2362
2363        if (msg->flags & I2C_M_RD)
2364                return kzalloc(msg->len, GFP_KERNEL);
2365        else
2366                return kmemdup(msg->buf, msg->len, GFP_KERNEL);
2367}
2368EXPORT_SYMBOL_GPL(i2c_get_dma_safe_msg_buf);
2369
2370/**
2371 * i2c_put_dma_safe_msg_buf - release DMA safe buffer and sync with i2c_msg
2372 * @buf: the buffer obtained from i2c_get_dma_safe_msg_buf(). May be NULL.
2373 * @msg: the message which the buffer corresponds to
2374 * @xferred: bool saying if the message was transferred
2375 */
2376void i2c_put_dma_safe_msg_buf(u8 *buf, struct i2c_msg *msg, bool xferred)
2377{
2378        if (!buf || buf == msg->buf)
2379                return;
2380
2381        if (xferred && msg->flags & I2C_M_RD)
2382                memcpy(msg->buf, buf, msg->len);
2383
2384        kfree(buf);
2385}
2386EXPORT_SYMBOL_GPL(i2c_put_dma_safe_msg_buf);
2387
2388MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
2389MODULE_DESCRIPTION("I2C-Bus main module");
2390MODULE_LICENSE("GPL");
2391