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