linux/drivers/i2c/i2c-core.c
<<
>>
Prefs
   1/* i2c-core.c - a device driver for the iic-bus interface                    */
   2/* ------------------------------------------------------------------------- */
   3/*   Copyright (C) 1995-99 Simon G. Vogl
   4
   5    This program is free software; you can redistribute it and/or modify
   6    it under the terms of the GNU General Public License as published by
   7    the Free Software Foundation; either version 2 of the License, or
   8    (at your option) any later version.
   9
  10    This program is distributed in the hope that it will be useful,
  11    but WITHOUT ANY WARRANTY; without even the implied warranty of
  12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13    GNU General Public License for more details.                             */
  14/* ------------------------------------------------------------------------- */
  15
  16/* With some changes from Kyösti Mälkki <kmalkki@cc.hut.fi>.
  17   All SMBus-related things are written by Frodo Looijaard <frodol@dds.nl>
  18   SMBus 2.0 support by Mark Studebaker <mdsxyz123@yahoo.com> and
  19   Jean Delvare <khali@linux-fr.org>
  20   Mux support by Rodolfo Giometti <giometti@enneenne.com> and
  21   Michael Lawnick <michael.lawnick.ext@nsn.com>
  22   OF support is copyright (c) 2008 Jochen Friedrich <jochen@scram.de>
  23   (based on a previous patch from Jon Smirl <jonsmirl@gmail.com>) and
  24   (c) 2013  Wolfram Sang <wsa@the-dreams.de>
  25   I2C ACPI code Copyright (C) 2014 Intel Corp
  26   Author: Lan Tianyu <tianyu.lan@intel.com>
  27   I2C slave support (c) 2014 by Wolfram Sang <wsa@sang-engineering.com>
  28 */
  29
  30#define pr_fmt(fmt) "i2c-core: " fmt
  31
  32#include <linux/module.h>
  33#include <linux/kernel.h>
  34#include <linux/delay.h>
  35#include <linux/errno.h>
  36#include <linux/gpio.h>
  37#include <linux/slab.h>
  38#include <linux/i2c.h>
  39#include <linux/init.h>
  40#include <linux/idr.h>
  41#include <linux/mutex.h>
  42#include <linux/of.h>
  43#include <linux/of_device.h>
  44#include <linux/of_irq.h>
  45#include <linux/completion.h>
  46#include <linux/hardirq.h>
  47#include <linux/irqflags.h>
  48#include <linux/rwsem.h>
  49#include <linux/pm_runtime.h>
  50#include <linux/acpi.h>
  51#include <linux/jump_label.h>
  52#include <asm/uaccess.h>
  53
  54#include "i2c-core.h"
  55
  56#define CREATE_TRACE_POINTS
  57#include <trace/events/i2c.h>
  58
  59#define I2C_ADDR_OFFSET_TEN_BIT 0xa000
  60#define I2C_ADDR_OFFSET_SLAVE   0x1000
  61
  62/* core_lock protects i2c_adapter_idr, and guarantees
  63   that device detection, deletion of detected devices, and attach_adapter
  64   calls are serialized */
  65static DEFINE_MUTEX(core_lock);
  66static DEFINE_IDR(i2c_adapter_idr);
  67
  68static struct device_type i2c_client_type;
  69static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
  70
  71static struct static_key i2c_trace_msg = STATIC_KEY_INIT_FALSE;
  72static bool is_registered;
  73
  74void i2c_transfer_trace_reg(void)
  75{
  76        static_key_slow_inc(&i2c_trace_msg);
  77}
  78
  79void i2c_transfer_trace_unreg(void)
  80{
  81        static_key_slow_dec(&i2c_trace_msg);
  82}
  83
  84#if defined(CONFIG_ACPI)
  85struct i2c_acpi_handler_data {
  86        struct acpi_connection_info info;
  87        struct i2c_adapter *adapter;
  88};
  89
  90struct gsb_buffer {
  91        u8      status;
  92        u8      len;
  93        union {
  94                u16     wdata;
  95                u8      bdata;
  96                u8      data[0];
  97        };
  98} __packed;
  99
 100struct i2c_acpi_lookup {
 101        struct i2c_board_info *info;
 102        acpi_handle adapter_handle;
 103        acpi_handle device_handle;
 104        acpi_handle search_handle;
 105        u32 speed;
 106        u32 min_speed;
 107};
 108
 109static int i2c_acpi_fill_info(struct acpi_resource *ares, void *data)
 110{
 111        struct i2c_acpi_lookup *lookup = data;
 112        struct i2c_board_info *info = lookup->info;
 113        struct acpi_resource_i2c_serialbus *sb;
 114        acpi_status status;
 115
 116        if (info->addr || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
 117                return 1;
 118
 119        sb = &ares->data.i2c_serial_bus;
 120        if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C)
 121                return 1;
 122
 123        status = acpi_get_handle(lookup->device_handle,
 124                                 sb->resource_source.string_ptr,
 125                                 &lookup->adapter_handle);
 126        if (!ACPI_SUCCESS(status))
 127                return 1;
 128
 129        info->addr = sb->slave_address;
 130        lookup->speed = sb->connection_speed;
 131        if (sb->access_mode == ACPI_I2C_10BIT_MODE)
 132                info->flags |= I2C_CLIENT_TEN;
 133        return 1;
 134}
 135
 136static int i2c_acpi_do_lookup(struct acpi_device *adev,
 137                              struct i2c_acpi_lookup *lookup)
 138{
 139        struct i2c_board_info *info = lookup->info;
 140        struct list_head resource_list;
 141        int ret;
 142
 143        if (acpi_bus_get_status(adev) || !adev->status.present ||
 144            acpi_device_enumerated(adev))
 145                return -EINVAL;
 146
 147        memset(info, 0, sizeof(*info));
 148        lookup->device_handle = acpi_device_handle(adev);
 149
 150        /* Look up for I2cSerialBus resource */
 151        INIT_LIST_HEAD(&resource_list);
 152        ret = acpi_dev_get_resources(adev, &resource_list,
 153                                     i2c_acpi_fill_info, lookup);
 154        acpi_dev_free_resource_list(&resource_list);
 155
 156        if (ret < 0 || !info->addr)
 157                return -EINVAL;
 158
 159        return 0;
 160}
 161
 162static int i2c_acpi_get_info(struct acpi_device *adev,
 163                             struct i2c_board_info *info,
 164                             acpi_handle *adapter_handle)
 165{
 166        struct list_head resource_list;
 167        struct resource_entry *entry;
 168        struct i2c_acpi_lookup lookup;
 169        int ret;
 170
 171        memset(&lookup, 0, sizeof(lookup));
 172        lookup.info = info;
 173
 174        ret = i2c_acpi_do_lookup(adev, &lookup);
 175        if (ret)
 176                return ret;
 177
 178        info->fwnode = acpi_fwnode_handle(adev);
 179        *adapter_handle = lookup.adapter_handle;
 180
 181        /* Then fill IRQ number if any */
 182        INIT_LIST_HEAD(&resource_list);
 183        ret = acpi_dev_get_resources(adev, &resource_list, NULL, NULL);
 184        if (ret < 0)
 185                return -EINVAL;
 186
 187        resource_list_for_each_entry(entry, &resource_list) {
 188                if (resource_type(entry->res) == IORESOURCE_IRQ) {
 189                        info->irq = entry->res->start;
 190                        break;
 191                }
 192        }
 193
 194        acpi_dev_free_resource_list(&resource_list);
 195
 196        strlcpy(info->type, dev_name(&adev->dev), sizeof(info->type));
 197
 198        return 0;
 199}
 200
 201static void i2c_acpi_register_device(struct i2c_adapter *adapter,
 202                                     struct acpi_device *adev,
 203                                     struct i2c_board_info *info)
 204{
 205        adev->power.flags.ignore_parent = true;
 206        acpi_device_set_enumerated(adev);
 207
 208        if (!i2c_new_device(adapter, info)) {
 209                adev->power.flags.ignore_parent = false;
 210                dev_err(&adapter->dev,
 211                        "failed to add I2C device %s from ACPI\n",
 212                        dev_name(&adev->dev));
 213        }
 214}
 215
 216static acpi_status i2c_acpi_add_device(acpi_handle handle, u32 level,
 217                                       void *data, void **return_value)
 218{
 219        struct i2c_adapter *adapter = data;
 220        struct acpi_device *adev;
 221        acpi_handle adapter_handle;
 222        struct i2c_board_info info;
 223
 224        if (acpi_bus_get_device(handle, &adev))
 225                return AE_OK;
 226
 227        if (i2c_acpi_get_info(adev, &info, &adapter_handle))
 228                return AE_OK;
 229
 230        if (adapter_handle != ACPI_HANDLE(&adapter->dev))
 231                return AE_OK;
 232
 233        i2c_acpi_register_device(adapter, adev, &info);
 234
 235        return AE_OK;
 236}
 237
 238#define I2C_ACPI_MAX_SCAN_DEPTH 32
 239
 240/**
 241 * i2c_acpi_register_devices - enumerate I2C slave devices behind adapter
 242 * @adap: pointer to adapter
 243 *
 244 * Enumerate all I2C slave devices behind this adapter by walking the ACPI
 245 * namespace. When a device is found it will be added to the Linux device
 246 * model and bound to the corresponding ACPI handle.
 247 */
 248static void i2c_acpi_register_devices(struct i2c_adapter *adap)
 249{
 250        acpi_status status;
 251
 252        if (!adap->dev.parent || !has_acpi_companion(adap->dev.parent))
 253                return;
 254
 255        status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
 256                                     I2C_ACPI_MAX_SCAN_DEPTH,
 257                                     i2c_acpi_add_device, NULL,
 258                                     adap, NULL);
 259        if (ACPI_FAILURE(status))
 260                dev_warn(&adap->dev, "failed to enumerate I2C slaves\n");
 261}
 262
 263static acpi_status i2c_acpi_lookup_speed(acpi_handle handle, u32 level,
 264                                           void *data, void **return_value)
 265{
 266        struct i2c_acpi_lookup *lookup = data;
 267        struct acpi_device *adev;
 268
 269        if (acpi_bus_get_device(handle, &adev))
 270                return AE_OK;
 271
 272        if (i2c_acpi_do_lookup(adev, lookup))
 273                return AE_OK;
 274
 275        if (lookup->search_handle != lookup->adapter_handle)
 276                return AE_OK;
 277
 278        if (lookup->speed <= lookup->min_speed)
 279                lookup->min_speed = lookup->speed;
 280
 281        return AE_OK;
 282}
 283
 284/**
 285 * i2c_acpi_find_bus_speed - find I2C bus speed from ACPI
 286 * @dev: The device owning the bus
 287 *
 288 * Find the I2C bus speed by walking the ACPI namespace for all I2C slaves
 289 * devices connected to this bus and use the speed of slowest device.
 290 *
 291 * Returns the speed in Hz or zero
 292 */
 293u32 i2c_acpi_find_bus_speed(struct device *dev)
 294{
 295        struct i2c_acpi_lookup lookup;
 296        struct i2c_board_info dummy;
 297        acpi_status status;
 298
 299        if (!has_acpi_companion(dev))
 300                return 0;
 301
 302        memset(&lookup, 0, sizeof(lookup));
 303        lookup.search_handle = ACPI_HANDLE(dev);
 304        lookup.min_speed = UINT_MAX;
 305        lookup.info = &dummy;
 306
 307        status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
 308                                     I2C_ACPI_MAX_SCAN_DEPTH,
 309                                     i2c_acpi_lookup_speed, NULL,
 310                                     &lookup, NULL);
 311
 312        if (ACPI_FAILURE(status)) {
 313                dev_warn(dev, "unable to find I2C bus speed from ACPI\n");
 314                return 0;
 315        }
 316
 317        return lookup.min_speed != UINT_MAX ? lookup.min_speed : 0;
 318}
 319EXPORT_SYMBOL_GPL(i2c_acpi_find_bus_speed);
 320
 321static int i2c_acpi_match_adapter(struct device *dev, void *data)
 322{
 323        struct i2c_adapter *adapter = i2c_verify_adapter(dev);
 324
 325        if (!adapter)
 326                return 0;
 327
 328        return ACPI_HANDLE(dev) == (acpi_handle)data;
 329}
 330
 331static int i2c_acpi_match_device(struct device *dev, void *data)
 332{
 333        return ACPI_COMPANION(dev) == data;
 334}
 335
 336static struct i2c_adapter *i2c_acpi_find_adapter_by_handle(acpi_handle handle)
 337{
 338        struct device *dev;
 339
 340        dev = bus_find_device(&i2c_bus_type, NULL, handle,
 341                              i2c_acpi_match_adapter);
 342        return dev ? i2c_verify_adapter(dev) : NULL;
 343}
 344
 345static struct i2c_client *i2c_acpi_find_client_by_adev(struct acpi_device *adev)
 346{
 347        struct device *dev;
 348
 349        dev = bus_find_device(&i2c_bus_type, NULL, adev, i2c_acpi_match_device);
 350        return dev ? i2c_verify_client(dev) : NULL;
 351}
 352
 353static int i2c_acpi_notify(struct notifier_block *nb, unsigned long value,
 354                           void *arg)
 355{
 356        struct acpi_device *adev = arg;
 357        struct i2c_board_info info;
 358        acpi_handle adapter_handle;
 359        struct i2c_adapter *adapter;
 360        struct i2c_client *client;
 361
 362        switch (value) {
 363        case ACPI_RECONFIG_DEVICE_ADD:
 364                if (i2c_acpi_get_info(adev, &info, &adapter_handle))
 365                        break;
 366
 367                adapter = i2c_acpi_find_adapter_by_handle(adapter_handle);
 368                if (!adapter)
 369                        break;
 370
 371                i2c_acpi_register_device(adapter, adev, &info);
 372                break;
 373        case ACPI_RECONFIG_DEVICE_REMOVE:
 374                if (!acpi_device_enumerated(adev))
 375                        break;
 376
 377                client = i2c_acpi_find_client_by_adev(adev);
 378                if (!client)
 379                        break;
 380
 381                i2c_unregister_device(client);
 382                put_device(&client->dev);
 383                break;
 384        }
 385
 386        return NOTIFY_OK;
 387}
 388
 389static struct notifier_block i2c_acpi_notifier = {
 390        .notifier_call = i2c_acpi_notify,
 391};
 392#else /* CONFIG_ACPI */
 393static inline void i2c_acpi_register_devices(struct i2c_adapter *adap) { }
 394extern struct notifier_block i2c_acpi_notifier;
 395#endif /* CONFIG_ACPI */
 396
 397#ifdef CONFIG_ACPI_I2C_OPREGION
 398static int acpi_gsb_i2c_read_bytes(struct i2c_client *client,
 399                u8 cmd, u8 *data, u8 data_len)
 400{
 401
 402        struct i2c_msg msgs[2];
 403        int ret;
 404        u8 *buffer;
 405
 406        buffer = kzalloc(data_len, GFP_KERNEL);
 407        if (!buffer)
 408                return AE_NO_MEMORY;
 409
 410        msgs[0].addr = client->addr;
 411        msgs[0].flags = client->flags;
 412        msgs[0].len = 1;
 413        msgs[0].buf = &cmd;
 414
 415        msgs[1].addr = client->addr;
 416        msgs[1].flags = client->flags | I2C_M_RD;
 417        msgs[1].len = data_len;
 418        msgs[1].buf = buffer;
 419
 420        ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
 421        if (ret < 0)
 422                dev_err(&client->adapter->dev, "i2c read failed\n");
 423        else
 424                memcpy(data, buffer, data_len);
 425
 426        kfree(buffer);
 427        return ret;
 428}
 429
 430static int acpi_gsb_i2c_write_bytes(struct i2c_client *client,
 431                u8 cmd, u8 *data, u8 data_len)
 432{
 433
 434        struct i2c_msg msgs[1];
 435        u8 *buffer;
 436        int ret = AE_OK;
 437
 438        buffer = kzalloc(data_len + 1, GFP_KERNEL);
 439        if (!buffer)
 440                return AE_NO_MEMORY;
 441
 442        buffer[0] = cmd;
 443        memcpy(buffer + 1, data, data_len);
 444
 445        msgs[0].addr = client->addr;
 446        msgs[0].flags = client->flags;
 447        msgs[0].len = data_len + 1;
 448        msgs[0].buf = buffer;
 449
 450        ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
 451        if (ret < 0)
 452                dev_err(&client->adapter->dev, "i2c write failed\n");
 453
 454        kfree(buffer);
 455        return ret;
 456}
 457
 458static acpi_status
 459i2c_acpi_space_handler(u32 function, acpi_physical_address command,
 460                        u32 bits, u64 *value64,
 461                        void *handler_context, void *region_context)
 462{
 463        struct gsb_buffer *gsb = (struct gsb_buffer *)value64;
 464        struct i2c_acpi_handler_data *data = handler_context;
 465        struct acpi_connection_info *info = &data->info;
 466        struct acpi_resource_i2c_serialbus *sb;
 467        struct i2c_adapter *adapter = data->adapter;
 468        struct i2c_client *client;
 469        struct acpi_resource *ares;
 470        u32 accessor_type = function >> 16;
 471        u8 action = function & ACPI_IO_MASK;
 472        acpi_status ret;
 473        int status;
 474
 475        ret = acpi_buffer_to_resource(info->connection, info->length, &ares);
 476        if (ACPI_FAILURE(ret))
 477                return ret;
 478
 479        client = kzalloc(sizeof(*client), GFP_KERNEL);
 480        if (!client) {
 481                ret = AE_NO_MEMORY;
 482                goto err;
 483        }
 484
 485        if (!value64 || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS) {
 486                ret = AE_BAD_PARAMETER;
 487                goto err;
 488        }
 489
 490        sb = &ares->data.i2c_serial_bus;
 491        if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C) {
 492                ret = AE_BAD_PARAMETER;
 493                goto err;
 494        }
 495
 496        client->adapter = adapter;
 497        client->addr = sb->slave_address;
 498
 499        if (sb->access_mode == ACPI_I2C_10BIT_MODE)
 500                client->flags |= I2C_CLIENT_TEN;
 501
 502        switch (accessor_type) {
 503        case ACPI_GSB_ACCESS_ATTRIB_SEND_RCV:
 504                if (action == ACPI_READ) {
 505                        status = i2c_smbus_read_byte(client);
 506                        if (status >= 0) {
 507                                gsb->bdata = status;
 508                                status = 0;
 509                        }
 510                } else {
 511                        status = i2c_smbus_write_byte(client, gsb->bdata);
 512                }
 513                break;
 514
 515        case ACPI_GSB_ACCESS_ATTRIB_BYTE:
 516                if (action == ACPI_READ) {
 517                        status = i2c_smbus_read_byte_data(client, command);
 518                        if (status >= 0) {
 519                                gsb->bdata = status;
 520                                status = 0;
 521                        }
 522                } else {
 523                        status = i2c_smbus_write_byte_data(client, command,
 524                                        gsb->bdata);
 525                }
 526                break;
 527
 528        case ACPI_GSB_ACCESS_ATTRIB_WORD:
 529                if (action == ACPI_READ) {
 530                        status = i2c_smbus_read_word_data(client, command);
 531                        if (status >= 0) {
 532                                gsb->wdata = status;
 533                                status = 0;
 534                        }
 535                } else {
 536                        status = i2c_smbus_write_word_data(client, command,
 537                                        gsb->wdata);
 538                }
 539                break;
 540
 541        case ACPI_GSB_ACCESS_ATTRIB_BLOCK:
 542                if (action == ACPI_READ) {
 543                        status = i2c_smbus_read_block_data(client, command,
 544                                        gsb->data);
 545                        if (status >= 0) {
 546                                gsb->len = status;
 547                                status = 0;
 548                        }
 549                } else {
 550                        status = i2c_smbus_write_block_data(client, command,
 551                                        gsb->len, gsb->data);
 552                }
 553                break;
 554
 555        case ACPI_GSB_ACCESS_ATTRIB_MULTIBYTE:
 556                if (action == ACPI_READ) {
 557                        status = acpi_gsb_i2c_read_bytes(client, command,
 558                                        gsb->data, info->access_length);
 559                        if (status > 0)
 560                                status = 0;
 561                } else {
 562                        status = acpi_gsb_i2c_write_bytes(client, command,
 563                                        gsb->data, info->access_length);
 564                }
 565                break;
 566
 567        default:
 568                dev_warn(&adapter->dev, "protocol 0x%02x not supported for client 0x%02x\n",
 569                         accessor_type, client->addr);
 570                ret = AE_BAD_PARAMETER;
 571                goto err;
 572        }
 573
 574        gsb->status = status;
 575
 576 err:
 577        kfree(client);
 578        ACPI_FREE(ares);
 579        return ret;
 580}
 581
 582
 583static int i2c_acpi_install_space_handler(struct i2c_adapter *adapter)
 584{
 585        acpi_handle handle;
 586        struct i2c_acpi_handler_data *data;
 587        acpi_status status;
 588
 589        if (!adapter->dev.parent)
 590                return -ENODEV;
 591
 592        handle = ACPI_HANDLE(adapter->dev.parent);
 593
 594        if (!handle)
 595                return -ENODEV;
 596
 597        data = kzalloc(sizeof(struct i2c_acpi_handler_data),
 598                            GFP_KERNEL);
 599        if (!data)
 600                return -ENOMEM;
 601
 602        data->adapter = adapter;
 603        status = acpi_bus_attach_private_data(handle, (void *)data);
 604        if (ACPI_FAILURE(status)) {
 605                kfree(data);
 606                return -ENOMEM;
 607        }
 608
 609        status = acpi_install_address_space_handler(handle,
 610                                ACPI_ADR_SPACE_GSBUS,
 611                                &i2c_acpi_space_handler,
 612                                NULL,
 613                                data);
 614        if (ACPI_FAILURE(status)) {
 615                dev_err(&adapter->dev, "Error installing i2c space handler\n");
 616                acpi_bus_detach_private_data(handle);
 617                kfree(data);
 618                return -ENOMEM;
 619        }
 620
 621        return 0;
 622}
 623
 624static void i2c_acpi_remove_space_handler(struct i2c_adapter *adapter)
 625{
 626        acpi_handle handle;
 627        struct i2c_acpi_handler_data *data;
 628        acpi_status status;
 629
 630        if (!adapter->dev.parent)
 631                return;
 632
 633        handle = ACPI_HANDLE(adapter->dev.parent);
 634
 635        if (!handle)
 636                return;
 637
 638        acpi_remove_address_space_handler(handle,
 639                                ACPI_ADR_SPACE_GSBUS,
 640                                &i2c_acpi_space_handler);
 641
 642        status = acpi_bus_get_private_data(handle, (void **)&data);
 643        if (ACPI_SUCCESS(status))
 644                kfree(data);
 645
 646        acpi_bus_detach_private_data(handle);
 647}
 648#else /* CONFIG_ACPI_I2C_OPREGION */
 649static inline void i2c_acpi_remove_space_handler(struct i2c_adapter *adapter)
 650{ }
 651
 652static inline int i2c_acpi_install_space_handler(struct i2c_adapter *adapter)
 653{ return 0; }
 654#endif /* CONFIG_ACPI_I2C_OPREGION */
 655
 656/* ------------------------------------------------------------------------- */
 657
 658static const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
 659                                                const struct i2c_client *client)
 660{
 661        while (id->name[0]) {
 662                if (strcmp(client->name, id->name) == 0)
 663                        return id;
 664                id++;
 665        }
 666        return NULL;
 667}
 668
 669static int i2c_device_match(struct device *dev, struct device_driver *drv)
 670{
 671        struct i2c_client       *client = i2c_verify_client(dev);
 672        struct i2c_driver       *driver;
 673
 674        if (!client)
 675                return 0;
 676
 677        /* Attempt an OF style match */
 678        if (of_driver_match_device(dev, drv))
 679                return 1;
 680
 681        /* Then ACPI style match */
 682        if (acpi_driver_match_device(dev, drv))
 683                return 1;
 684
 685        driver = to_i2c_driver(drv);
 686        /* match on an id table if there is one */
 687        if (driver->id_table)
 688                return i2c_match_id(driver->id_table, client) != NULL;
 689
 690        return 0;
 691}
 692
 693
 694/* uevent helps with hotplug: modprobe -q $(MODALIAS) */
 695static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
 696{
 697        struct i2c_client       *client = to_i2c_client(dev);
 698
 699        if (add_uevent_var(env, "MODALIAS=%s%s",
 700                           I2C_MODULE_PREFIX, client->name))
 701                return -ENOMEM;
 702        dev_dbg(dev, "uevent\n");
 703        return 0;
 704}
 705
 706/* i2c bus recovery routines */
 707static int get_scl_gpio_value(struct i2c_adapter *adap)
 708{
 709        return gpio_get_value(adap->bus_recovery_info->scl_gpio);
 710}
 711
 712static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
 713{
 714        gpio_set_value(adap->bus_recovery_info->scl_gpio, val);
 715}
 716
 717static int get_sda_gpio_value(struct i2c_adapter *adap)
 718{
 719        return gpio_get_value(adap->bus_recovery_info->sda_gpio);
 720}
 721
 722static int i2c_get_gpios_for_recovery(struct i2c_adapter *adap)
 723{
 724        struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
 725        struct device *dev = &adap->dev;
 726        int ret = 0;
 727
 728        ret = gpio_request_one(bri->scl_gpio, GPIOF_OPEN_DRAIN |
 729                        GPIOF_OUT_INIT_HIGH, "i2c-scl");
 730        if (ret) {
 731                dev_warn(dev, "Can't get SCL gpio: %d\n", bri->scl_gpio);
 732                return ret;
 733        }
 734
 735        if (bri->get_sda) {
 736                if (gpio_request_one(bri->sda_gpio, GPIOF_IN, "i2c-sda")) {
 737                        /* work without SDA polling */
 738                        dev_warn(dev, "Can't get SDA gpio: %d. Not using SDA polling\n",
 739                                        bri->sda_gpio);
 740                        bri->get_sda = NULL;
 741                }
 742        }
 743
 744        return ret;
 745}
 746
 747static void i2c_put_gpios_for_recovery(struct i2c_adapter *adap)
 748{
 749        struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
 750
 751        if (bri->get_sda)
 752                gpio_free(bri->sda_gpio);
 753
 754        gpio_free(bri->scl_gpio);
 755}
 756
 757/*
 758 * We are generating clock pulses. ndelay() determines durating of clk pulses.
 759 * We will generate clock with rate 100 KHz and so duration of both clock levels
 760 * is: delay in ns = (10^6 / 100) / 2
 761 */
 762#define RECOVERY_NDELAY         5000
 763#define RECOVERY_CLK_CNT        9
 764
 765static int i2c_generic_recovery(struct i2c_adapter *adap)
 766{
 767        struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
 768        int i = 0, val = 1, ret = 0;
 769
 770        if (bri->prepare_recovery)
 771                bri->prepare_recovery(adap);
 772
 773        bri->set_scl(adap, val);
 774        ndelay(RECOVERY_NDELAY);
 775
 776        /*
 777         * By this time SCL is high, as we need to give 9 falling-rising edges
 778         */
 779        while (i++ < RECOVERY_CLK_CNT * 2) {
 780                if (val) {
 781                        /* Break if SDA is high */
 782                        if (bri->get_sda && bri->get_sda(adap))
 783                                        break;
 784                        /* SCL shouldn't be low here */
 785                        if (!bri->get_scl(adap)) {
 786                                dev_err(&adap->dev,
 787                                        "SCL is stuck low, exit recovery\n");
 788                                ret = -EBUSY;
 789                                break;
 790                        }
 791                }
 792
 793                val = !val;
 794                bri->set_scl(adap, val);
 795                ndelay(RECOVERY_NDELAY);
 796        }
 797
 798        if (bri->unprepare_recovery)
 799                bri->unprepare_recovery(adap);
 800
 801        return ret;
 802}
 803
 804int i2c_generic_scl_recovery(struct i2c_adapter *adap)
 805{
 806        return i2c_generic_recovery(adap);
 807}
 808EXPORT_SYMBOL_GPL(i2c_generic_scl_recovery);
 809
 810int i2c_generic_gpio_recovery(struct i2c_adapter *adap)
 811{
 812        int ret;
 813
 814        ret = i2c_get_gpios_for_recovery(adap);
 815        if (ret)
 816                return ret;
 817
 818        ret = i2c_generic_recovery(adap);
 819        i2c_put_gpios_for_recovery(adap);
 820
 821        return ret;
 822}
 823EXPORT_SYMBOL_GPL(i2c_generic_gpio_recovery);
 824
 825int i2c_recover_bus(struct i2c_adapter *adap)
 826{
 827        if (!adap->bus_recovery_info)
 828                return -EOPNOTSUPP;
 829
 830        dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
 831        return adap->bus_recovery_info->recover_bus(adap);
 832}
 833EXPORT_SYMBOL_GPL(i2c_recover_bus);
 834
 835static void i2c_init_recovery(struct i2c_adapter *adap)
 836{
 837        struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
 838        char *err_str;
 839
 840        if (!bri)
 841                return;
 842
 843        if (!bri->recover_bus) {
 844                err_str = "no recover_bus() found";
 845                goto err;
 846        }
 847
 848        /* Generic GPIO recovery */
 849        if (bri->recover_bus == i2c_generic_gpio_recovery) {
 850                if (!gpio_is_valid(bri->scl_gpio)) {
 851                        err_str = "invalid SCL gpio";
 852                        goto err;
 853                }
 854
 855                if (gpio_is_valid(bri->sda_gpio))
 856                        bri->get_sda = get_sda_gpio_value;
 857                else
 858                        bri->get_sda = NULL;
 859
 860                bri->get_scl = get_scl_gpio_value;
 861                bri->set_scl = set_scl_gpio_value;
 862        } else if (bri->recover_bus == i2c_generic_scl_recovery) {
 863                /* Generic SCL recovery */
 864                if (!bri->set_scl || !bri->get_scl) {
 865                        err_str = "no {get|set}_scl() found";
 866                        goto err;
 867                }
 868        }
 869
 870        return;
 871 err:
 872        dev_err(&adap->dev, "Not using recovery: %s\n", err_str);
 873        adap->bus_recovery_info = NULL;
 874}
 875
 876static int i2c_device_probe(struct device *dev)
 877{
 878        struct i2c_client       *client = i2c_verify_client(dev);
 879        struct i2c_driver       *driver;
 880        int status;
 881
 882        if (!client)
 883                return 0;
 884
 885        if (!client->irq) {
 886                int irq = -ENOENT;
 887
 888                if (ACPI_COMPANION(dev))
 889                        irq = acpi_dev_gpio_irq_get(ACPI_COMPANION(dev), 0);
 890
 891                if (irq == -EPROBE_DEFER)
 892                        return irq;
 893                if (irq < 0)
 894                        irq = 0;
 895
 896                client->irq = irq;
 897        }
 898
 899        driver = to_i2c_driver(dev->driver);
 900        if (!driver->probe || !driver->id_table)
 901                return -ENODEV;
 902
 903        if (!device_can_wakeup(&client->dev))
 904                device_init_wakeup(&client->dev,
 905                                        client->flags & I2C_CLIENT_WAKE);
 906        dev_dbg(dev, "probe\n");
 907
 908        acpi_dev_pm_attach(&client->dev, true);
 909
 910        status = driver->probe(client, i2c_match_id(driver->id_table, client));
 911        if (status) {
 912                i2c_set_clientdata(client, NULL);
 913                acpi_dev_pm_detach(&client->dev, true);
 914        }
 915
 916        return status;
 917}
 918
 919static int i2c_device_remove(struct device *dev)
 920{
 921        struct i2c_client       *client = i2c_verify_client(dev);
 922        struct i2c_driver       *driver;
 923        int                     status;
 924
 925        if (!client || !dev->driver)
 926                return 0;
 927
 928        driver = to_i2c_driver(dev->driver);
 929        if (driver->remove) {
 930                dev_dbg(dev, "remove\n");
 931                status = driver->remove(client);
 932        } else {
 933                dev->driver = NULL;
 934                status = 0;
 935        }
 936        if (status == 0)
 937                i2c_set_clientdata(client, NULL);
 938        acpi_dev_pm_detach(&client->dev, true);
 939        return status;
 940}
 941
 942static void i2c_device_shutdown(struct device *dev)
 943{
 944        struct i2c_client *client = i2c_verify_client(dev);
 945        struct i2c_driver *driver;
 946
 947        if (!client || !dev->driver)
 948                return;
 949        driver = to_i2c_driver(dev->driver);
 950        if (driver->shutdown)
 951                driver->shutdown(client);
 952}
 953
 954static void i2c_client_dev_release(struct device *dev)
 955{
 956        kfree(to_i2c_client(dev));
 957}
 958
 959static ssize_t
 960show_name(struct device *dev, struct device_attribute *attr, char *buf)
 961{
 962        return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
 963                       to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
 964}
 965static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
 966
 967static ssize_t
 968show_modalias(struct device *dev, struct device_attribute *attr, char *buf)
 969{
 970        struct i2c_client *client = to_i2c_client(dev);
 971        return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
 972}
 973static DEVICE_ATTR(modalias, S_IRUGO, show_modalias, NULL);
 974
 975static struct attribute *i2c_dev_attrs[] = {
 976        &dev_attr_name.attr,
 977        /* modalias helps coldplug:  modprobe $(cat .../modalias) */
 978        &dev_attr_modalias.attr,
 979        NULL
 980};
 981ATTRIBUTE_GROUPS(i2c_dev);
 982
 983struct bus_type i2c_bus_type = {
 984        .name           = "i2c",
 985        .match          = i2c_device_match,
 986        .probe          = i2c_device_probe,
 987        .remove         = i2c_device_remove,
 988        .shutdown       = i2c_device_shutdown,
 989};
 990EXPORT_SYMBOL_GPL(i2c_bus_type);
 991
 992static struct device_type i2c_client_type = {
 993        .groups         = i2c_dev_groups,
 994        .uevent         = i2c_device_uevent,
 995        .release        = i2c_client_dev_release,
 996};
 997
 998
 999/**
1000 * i2c_verify_client - return parameter as i2c_client, or NULL
1001 * @dev: device, probably from some driver model iterator
1002 *
1003 * When traversing the driver model tree, perhaps using driver model
1004 * iterators like @device_for_each_child(), you can't assume very much
1005 * about the nodes you find.  Use this function to avoid oopses caused
1006 * by wrongly treating some non-I2C device as an i2c_client.
1007 */
1008struct i2c_client *i2c_verify_client(struct device *dev)
1009{
1010        return (dev->type == &i2c_client_type)
1011                        ? to_i2c_client(dev)
1012                        : NULL;
1013}
1014EXPORT_SYMBOL(i2c_verify_client);
1015
1016
1017/* Return a unique address which takes the flags of the client into account */
1018static unsigned short i2c_encode_flags_to_addr(struct i2c_client *client)
1019{
1020        unsigned short addr = client->addr;
1021
1022        /* For some client flags, add an arbitrary offset to avoid collisions */
1023        if (client->flags & I2C_CLIENT_TEN)
1024                addr |= I2C_ADDR_OFFSET_TEN_BIT;
1025
1026        if (client->flags & I2C_CLIENT_SLAVE)
1027                addr |= I2C_ADDR_OFFSET_SLAVE;
1028
1029        return addr;
1030}
1031
1032/* This is a permissive address validity check, I2C address map constraints
1033 * are purposely not enforced, except for the general call address. */
1034static int i2c_check_addr_validity(unsigned addr, unsigned short flags)
1035{
1036        if (flags & I2C_CLIENT_TEN) {
1037                /* 10-bit address, all values are valid */
1038                if (addr > 0x3ff)
1039                        return -EINVAL;
1040        } else {
1041                /* 7-bit address, reject the general call address */
1042                if (addr == 0x00 || addr > 0x7f)
1043                        return -EINVAL;
1044        }
1045        return 0;
1046}
1047
1048/* And this is a strict address validity check, used when probing. If a
1049 * device uses a reserved address, then it shouldn't be probed. 7-bit
1050 * addressing is assumed, 10-bit address devices are rare and should be
1051 * explicitly enumerated. */
1052static int i2c_check_7bit_addr_validity_strict(unsigned short addr)
1053{
1054        /*
1055         * Reserved addresses per I2C specification:
1056         *  0x00       General call address / START byte
1057         *  0x01       CBUS address
1058         *  0x02       Reserved for different bus format
1059         *  0x03       Reserved for future purposes
1060         *  0x04-0x07  Hs-mode master code
1061         *  0x78-0x7b  10-bit slave addressing
1062         *  0x7c-0x7f  Reserved for future purposes
1063         */
1064        if (addr < 0x08 || addr > 0x77)
1065                return -EINVAL;
1066        return 0;
1067}
1068
1069static int __i2c_check_addr_busy(struct device *dev, void *addrp)
1070{
1071        struct i2c_client       *client = i2c_verify_client(dev);
1072        int                     addr = *(int *)addrp;
1073
1074        if (client && i2c_encode_flags_to_addr(client) == addr)
1075                return -EBUSY;
1076        return 0;
1077}
1078
1079/* walk up mux tree */
1080static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
1081{
1082        struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
1083        int result;
1084
1085        result = device_for_each_child(&adapter->dev, &addr,
1086                                        __i2c_check_addr_busy);
1087
1088        if (!result && parent)
1089                result = i2c_check_mux_parents(parent, addr);
1090
1091        return result;
1092}
1093
1094/* recurse down mux tree */
1095static int i2c_check_mux_children(struct device *dev, void *addrp)
1096{
1097        int result;
1098
1099        if (dev->type == &i2c_adapter_type)
1100                result = device_for_each_child(dev, addrp,
1101                                                i2c_check_mux_children);
1102        else
1103                result = __i2c_check_addr_busy(dev, addrp);
1104
1105        return result;
1106}
1107
1108static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
1109{
1110        struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
1111        int result = 0;
1112
1113        if (parent)
1114                result = i2c_check_mux_parents(parent, addr);
1115
1116        if (!result)
1117                result = device_for_each_child(&adapter->dev, &addr,
1118                                                i2c_check_mux_children);
1119
1120        return result;
1121}
1122
1123/**
1124 * i2c_lock_adapter - Get exclusive access to an I2C bus segment
1125 * @adapter: Target I2C bus segment
1126 */
1127void i2c_lock_adapter(struct i2c_adapter *adapter)
1128{
1129        struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
1130
1131        if (parent)
1132                i2c_lock_adapter(parent);
1133        else
1134                rt_mutex_lock(&adapter->bus_lock);
1135}
1136EXPORT_SYMBOL_GPL(i2c_lock_adapter);
1137
1138/**
1139 * i2c_trylock_adapter - Try to get exclusive access to an I2C bus segment
1140 * @adapter: Target I2C bus segment
1141 */
1142static int i2c_trylock_adapter(struct i2c_adapter *adapter)
1143{
1144        struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
1145
1146        if (parent)
1147                return i2c_trylock_adapter(parent);
1148        else
1149                return rt_mutex_trylock(&adapter->bus_lock);
1150}
1151
1152/**
1153 * i2c_unlock_adapter - Release exclusive access to an I2C bus segment
1154 * @adapter: Target I2C bus segment
1155 */
1156void i2c_unlock_adapter(struct i2c_adapter *adapter)
1157{
1158        struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
1159
1160        if (parent)
1161                i2c_unlock_adapter(parent);
1162        else
1163                rt_mutex_unlock(&adapter->bus_lock);
1164}
1165EXPORT_SYMBOL_GPL(i2c_unlock_adapter);
1166
1167static void i2c_dev_set_name(struct i2c_adapter *adap,
1168                             struct i2c_client *client)
1169{
1170        struct acpi_device *adev = ACPI_COMPANION(&client->dev);
1171
1172        if (adev) {
1173                dev_set_name(&client->dev, "i2c-%s", acpi_dev_name(adev));
1174                return;
1175        }
1176
1177        dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
1178                     i2c_encode_flags_to_addr(client));
1179}
1180
1181/**
1182 * i2c_new_device - instantiate an i2c device
1183 * @adap: the adapter managing the device
1184 * @info: describes one I2C device; bus_num is ignored
1185 * Context: can sleep
1186 *
1187 * Create an i2c device. Binding is handled through driver model
1188 * probe()/remove() methods.  A driver may be bound to this device when we
1189 * return from this function, or any later moment (e.g. maybe hotplugging will
1190 * load the driver module).  This call is not appropriate for use by mainboard
1191 * initialization logic, which usually runs during an arch_initcall() long
1192 * before any i2c_adapter could exist.
1193 *
1194 * This returns the new i2c client, which may be saved for later use with
1195 * i2c_unregister_device(); or NULL to indicate an error.
1196 */
1197struct i2c_client *
1198i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
1199{
1200        struct i2c_client       *client;
1201        int                     status;
1202
1203        client = kzalloc(sizeof *client, GFP_KERNEL);
1204        if (!client)
1205                return NULL;
1206
1207        client->adapter = adap;
1208
1209        client->dev.platform_data = info->platform_data;
1210
1211        if (info->archdata)
1212                client->dev.archdata = *info->archdata;
1213
1214        client->flags = info->flags;
1215        client->addr = info->addr;
1216        client->irq = info->irq;
1217
1218        strlcpy(client->name, info->type, sizeof(client->name));
1219
1220        status = i2c_check_addr_validity(client->addr, client->flags);
1221        if (status) {
1222                dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
1223                        client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
1224                goto out_err_silent;
1225        }
1226
1227        /* Check for address business */
1228        status = i2c_check_addr_busy(adap, i2c_encode_flags_to_addr(client));
1229        if (status)
1230                goto out_err;
1231
1232        client->dev.parent = &client->adapter->dev;
1233        client->dev.bus = &i2c_bus_type;
1234        client->dev.type = &i2c_client_type;
1235        client->dev.of_node = info->of_node;
1236        device_rh_alloc(&client->dev);
1237        set_rh_dev_fwnode(&client->dev, info->fwnode);
1238
1239        i2c_dev_set_name(adap, client);
1240        status = device_register(&client->dev);
1241        if (status)
1242                goto out_err;
1243
1244        dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
1245                client->name, dev_name(&client->dev));
1246
1247        return client;
1248
1249out_err:
1250        dev_err(&adap->dev, "Failed to register i2c client %s at 0x%02x "
1251                "(%d)\n", client->name, client->addr, status);
1252out_err_silent:
1253        kfree(client);
1254        return NULL;
1255}
1256EXPORT_SYMBOL_GPL(i2c_new_device);
1257
1258
1259/**
1260 * i2c_unregister_device - reverse effect of i2c_new_device()
1261 * @client: value returned from i2c_new_device()
1262 * Context: can sleep
1263 */
1264void i2c_unregister_device(struct i2c_client *client)
1265{
1266        if (ACPI_COMPANION(&client->dev))
1267                acpi_device_clear_enumerated(ACPI_COMPANION(&client->dev));
1268        device_unregister(&client->dev);
1269}
1270EXPORT_SYMBOL_GPL(i2c_unregister_device);
1271
1272
1273static const struct i2c_device_id dummy_id[] = {
1274        { "dummy", 0 },
1275        { },
1276};
1277
1278static int dummy_probe(struct i2c_client *client,
1279                       const struct i2c_device_id *id)
1280{
1281        return 0;
1282}
1283
1284static int dummy_remove(struct i2c_client *client)
1285{
1286        return 0;
1287}
1288
1289static struct i2c_driver dummy_driver = {
1290        .driver.name    = "dummy",
1291        .probe          = dummy_probe,
1292        .remove         = dummy_remove,
1293        .id_table       = dummy_id,
1294};
1295
1296/**
1297 * i2c_new_dummy - return a new i2c device bound to a dummy driver
1298 * @adapter: the adapter managing the device
1299 * @address: seven bit address to be used
1300 * Context: can sleep
1301 *
1302 * This returns an I2C client bound to the "dummy" driver, intended for use
1303 * with devices that consume multiple addresses.  Examples of such chips
1304 * include various EEPROMS (like 24c04 and 24c08 models).
1305 *
1306 * These dummy devices have two main uses.  First, most I2C and SMBus calls
1307 * except i2c_transfer() need a client handle; the dummy will be that handle.
1308 * And second, this prevents the specified address from being bound to a
1309 * different driver.
1310 *
1311 * This returns the new i2c client, which should be saved for later use with
1312 * i2c_unregister_device(); or NULL to indicate an error.
1313 */
1314struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
1315{
1316        struct i2c_board_info info = {
1317                I2C_BOARD_INFO("dummy", address),
1318        };
1319
1320        return i2c_new_device(adapter, &info);
1321}
1322EXPORT_SYMBOL_GPL(i2c_new_dummy);
1323
1324/**
1325 * i2c_new_secondary_device - Helper to get the instantiated secondary address
1326 * and create the associated device
1327 * @client: Handle to the primary client
1328 * @name: Handle to specify which secondary address to get
1329 * @default_addr: Used as a fallback if no secondary address was specified
1330 * Context: can sleep
1331 *
1332 * I2C clients can be composed of multiple I2C slaves bound together in a single
1333 * component. The I2C client driver then binds to the master I2C slave and needs
1334 * to create I2C dummy clients to communicate with all the other slaves.
1335 *
1336 * This function creates and returns an I2C dummy client whose I2C address is
1337 * retrieved from the platform firmware based on the given slave name. If no
1338 * address is specified by the firmware default_addr is used.
1339 *
1340 * On DT-based platforms the address is retrieved from the "reg" property entry
1341 * cell whose "reg-names" value matches the slave name.
1342 *
1343 * This returns the new i2c client, which should be saved for later use with
1344 * i2c_unregister_device(); or NULL to indicate an error.
1345 */
1346struct i2c_client *i2c_new_secondary_device(struct i2c_client *client,
1347                                                const char *name,
1348                                                u16 default_addr)
1349{
1350        struct device_node *np = client->dev.of_node;
1351        u32 addr = default_addr;
1352        int i;
1353
1354        if (np) {
1355                i = of_property_match_string(np, "reg-names", name);
1356                if (i >= 0)
1357                        of_property_read_u32_index(np, "reg", i, &addr);
1358        }
1359
1360        dev_dbg(&client->adapter->dev, "Address for %s : 0x%x\n", name, addr);
1361        return i2c_new_dummy(client->adapter, addr);
1362}
1363EXPORT_SYMBOL_GPL(i2c_new_secondary_device);
1364
1365/* ------------------------------------------------------------------------- */
1366
1367/* I2C bus adapters -- one roots each I2C or SMBUS segment */
1368
1369static void i2c_adapter_dev_release(struct device *dev)
1370{
1371        struct i2c_adapter *adap = to_i2c_adapter(dev);
1372        complete(&adap->dev_released);
1373}
1374
1375/*
1376 * This function is only needed for mutex_lock_nested, so it is never
1377 * called unless locking correctness checking is enabled. Thus we
1378 * make it inline to avoid a compiler warning. That's what gcc ends up
1379 * doing anyway.
1380 */
1381static inline unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
1382{
1383        unsigned int depth = 0;
1384
1385        while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
1386                depth++;
1387
1388        return depth;
1389}
1390
1391/*
1392 * Let users instantiate I2C devices through sysfs. This can be used when
1393 * platform initialization code doesn't contain the proper data for
1394 * whatever reason. Also useful for drivers that do device detection and
1395 * detection fails, either because the device uses an unexpected address,
1396 * or this is a compatible device with different ID register values.
1397 *
1398 * Parameter checking may look overzealous, but we really don't want
1399 * the user to provide incorrect parameters.
1400 */
1401static ssize_t
1402i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
1403                     const char *buf, size_t count)
1404{
1405        struct i2c_adapter *adap = to_i2c_adapter(dev);
1406        struct i2c_board_info info;
1407        struct i2c_client *client;
1408        char *blank, end;
1409        int res;
1410
1411        memset(&info, 0, sizeof(struct i2c_board_info));
1412
1413        blank = strchr(buf, ' ');
1414        if (!blank) {
1415                dev_err(dev, "%s: Missing parameters\n", "new_device");
1416                return -EINVAL;
1417        }
1418        if (blank - buf > I2C_NAME_SIZE - 1) {
1419                dev_err(dev, "%s: Invalid device name\n", "new_device");
1420                return -EINVAL;
1421        }
1422        memcpy(info.type, buf, blank - buf);
1423
1424        /* Parse remaining parameters, reject extra parameters */
1425        res = sscanf(++blank, "%hi%c", &info.addr, &end);
1426        if (res < 1) {
1427                dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
1428                return -EINVAL;
1429        }
1430        if (res > 1  && end != '\n') {
1431                dev_err(dev, "%s: Extra parameters\n", "new_device");
1432                return -EINVAL;
1433        }
1434
1435        if ((info.addr & I2C_ADDR_OFFSET_TEN_BIT) == I2C_ADDR_OFFSET_TEN_BIT) {
1436                info.addr &= ~I2C_ADDR_OFFSET_TEN_BIT;
1437                info.flags |= I2C_CLIENT_TEN;
1438        }
1439
1440        if (info.addr & I2C_ADDR_OFFSET_SLAVE) {
1441                info.addr &= ~I2C_ADDR_OFFSET_SLAVE;
1442                info.flags |= I2C_CLIENT_SLAVE;
1443        }
1444
1445        client = i2c_new_device(adap, &info);
1446        if (!client)
1447                return -EINVAL;
1448
1449        /* Keep track of the added device */
1450        mutex_lock(&adap->userspace_clients_lock);
1451        list_add_tail(&client->detected, &adap->userspace_clients);
1452        mutex_unlock(&adap->userspace_clients_lock);
1453        dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
1454                 info.type, info.addr);
1455
1456        return count;
1457}
1458static DEVICE_ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device);
1459
1460/*
1461 * And of course let the users delete the devices they instantiated, if
1462 * they got it wrong. This interface can only be used to delete devices
1463 * instantiated by i2c_sysfs_new_device above. This guarantees that we
1464 * don't delete devices to which some kernel code still has references.
1465 *
1466 * Parameter checking may look overzealous, but we really don't want
1467 * the user to delete the wrong device.
1468 */
1469static ssize_t
1470i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
1471                        const char *buf, size_t count)
1472{
1473        struct i2c_adapter *adap = to_i2c_adapter(dev);
1474        struct i2c_client *client, *next;
1475        unsigned short addr;
1476        char end;
1477        int res;
1478
1479        /* Parse parameters, reject extra parameters */
1480        res = sscanf(buf, "%hi%c", &addr, &end);
1481        if (res < 1) {
1482                dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
1483                return -EINVAL;
1484        }
1485        if (res > 1  && end != '\n') {
1486                dev_err(dev, "%s: Extra parameters\n", "delete_device");
1487                return -EINVAL;
1488        }
1489
1490        /* Make sure the device was added through sysfs */
1491        res = -ENOENT;
1492        mutex_lock_nested(&adap->userspace_clients_lock,
1493                          i2c_adapter_depth(adap));
1494        list_for_each_entry_safe(client, next, &adap->userspace_clients,
1495                                 detected) {
1496                if (i2c_encode_flags_to_addr(client) == addr) {
1497                        dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
1498                                 "delete_device", client->name, client->addr);
1499
1500                        list_del(&client->detected);
1501                        i2c_unregister_device(client);
1502                        res = count;
1503                        break;
1504                }
1505        }
1506        mutex_unlock(&adap->userspace_clients_lock);
1507
1508        if (res < 0)
1509                dev_err(dev, "%s: Can't find device in list\n",
1510                        "delete_device");
1511        return res;
1512}
1513static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
1514                                   i2c_sysfs_delete_device);
1515
1516static struct attribute *i2c_adapter_attrs[] = {
1517        &dev_attr_name.attr,
1518        &dev_attr_new_device.attr,
1519        &dev_attr_delete_device.attr,
1520        NULL
1521};
1522ATTRIBUTE_GROUPS(i2c_adapter);
1523
1524struct device_type i2c_adapter_type = {
1525        .groups         = i2c_adapter_groups,
1526        .release        = i2c_adapter_dev_release,
1527};
1528EXPORT_SYMBOL_GPL(i2c_adapter_type);
1529
1530/**
1531 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
1532 * @dev: device, probably from some driver model iterator
1533 *
1534 * When traversing the driver model tree, perhaps using driver model
1535 * iterators like @device_for_each_child(), you can't assume very much
1536 * about the nodes you find.  Use this function to avoid oopses caused
1537 * by wrongly treating some non-I2C device as an i2c_adapter.
1538 */
1539struct i2c_adapter *i2c_verify_adapter(struct device *dev)
1540{
1541        return (dev->type == &i2c_adapter_type)
1542                        ? to_i2c_adapter(dev)
1543                        : NULL;
1544}
1545EXPORT_SYMBOL(i2c_verify_adapter);
1546
1547#ifdef CONFIG_I2C_COMPAT
1548static struct class_compat *i2c_adapter_compat_class;
1549#endif
1550
1551static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
1552{
1553        struct i2c_devinfo      *devinfo;
1554
1555        down_read(&__i2c_board_lock);
1556        list_for_each_entry(devinfo, &__i2c_board_list, list) {
1557                if (devinfo->busnum == adapter->nr
1558                                && !i2c_new_device(adapter,
1559                                                &devinfo->board_info))
1560                        dev_err(&adapter->dev,
1561                                "Can't create device at 0x%02x\n",
1562                                devinfo->board_info.addr);
1563        }
1564        up_read(&__i2c_board_lock);
1565}
1566
1567/* OF support code */
1568
1569#if IS_ENABLED(CONFIG_OF)
1570static void of_i2c_register_devices(struct i2c_adapter *adap)
1571{
1572        void *result;
1573        struct device_node *node;
1574
1575        /* Only register child devices if the adapter has a node pointer set */
1576        if (!adap->dev.of_node)
1577                return;
1578
1579        dev_dbg(&adap->dev, "of_i2c: walking child nodes\n");
1580
1581        for_each_available_child_of_node(adap->dev.of_node, node) {
1582                struct i2c_board_info info = {};
1583                struct dev_archdata dev_ad = {};
1584                const __be32 *addr;
1585                int len;
1586
1587                dev_dbg(&adap->dev, "of_i2c: register %s\n", node->full_name);
1588
1589                if (of_modalias_node(node, info.type, sizeof(info.type)) < 0) {
1590                        dev_err(&adap->dev, "of_i2c: modalias failure on %s\n",
1591                                node->full_name);
1592                        continue;
1593                }
1594
1595                addr = of_get_property(node, "reg", &len);
1596                if (!addr || (len < sizeof(*addr))) {
1597                        dev_err(&adap->dev, "of_i2c: invalid reg on %s\n",
1598                                node->full_name);
1599                        continue;
1600                }
1601
1602                info.addr = be32_to_cpup(addr);
1603                if (info.addr > (1 << 10) - 1) {
1604                        dev_err(&adap->dev, "of_i2c: invalid addr=%x on %s\n",
1605                                info.addr, node->full_name);
1606                        continue;
1607                }
1608
1609                info.irq = irq_of_parse_and_map(node, 0);
1610                info.of_node = of_node_get(node);
1611                info.archdata = &dev_ad;
1612
1613                if (of_get_property(node, "wakeup-source", NULL))
1614                        info.flags |= I2C_CLIENT_WAKE;
1615
1616                result = i2c_new_device(adap, &info);
1617                if (result == NULL) {
1618                        dev_err(&adap->dev, "of_i2c: Failure registering %s\n",
1619                                node->full_name);
1620                        of_node_put(node);
1621                        irq_dispose_mapping(info.irq);
1622                        continue;
1623                }
1624        }
1625}
1626
1627static int of_dev_node_match(struct device *dev, void *data)
1628{
1629        return dev->of_node == data;
1630}
1631
1632/* must call put_device() when done with returned i2c_client device */
1633struct i2c_client *of_find_i2c_device_by_node(struct device_node *node)
1634{
1635        struct device *dev;
1636        struct i2c_client *client;
1637
1638        dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match);
1639        if (!dev)
1640                return NULL;
1641
1642        client = i2c_verify_client(dev);
1643        if (!client)
1644                put_device(dev);
1645
1646        return client;
1647}
1648EXPORT_SYMBOL(of_find_i2c_device_by_node);
1649
1650/* must call put_device() when done with returned i2c_adapter device */
1651struct i2c_adapter *of_find_i2c_adapter_by_node(struct device_node *node)
1652{
1653        struct device *dev;
1654        struct i2c_adapter *adapter;
1655
1656        dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match);
1657        if (!dev)
1658                return NULL;
1659
1660        adapter = i2c_verify_adapter(dev);
1661        if (!adapter)
1662                put_device(dev);
1663
1664        return adapter;
1665}
1666EXPORT_SYMBOL(of_find_i2c_adapter_by_node);
1667
1668/* must call i2c_put_adapter() when done with returned i2c_adapter device */
1669struct i2c_adapter *of_get_i2c_adapter_by_node(struct device_node *node)
1670{
1671        struct i2c_adapter *adapter;
1672
1673        adapter = of_find_i2c_adapter_by_node(node);
1674        if (!adapter)
1675                return NULL;
1676
1677        if (!try_module_get(adapter->owner)) {
1678                put_device(&adapter->dev);
1679                adapter = NULL;
1680        }
1681
1682        return adapter;
1683}
1684EXPORT_SYMBOL(of_get_i2c_adapter_by_node);
1685#else
1686static void of_i2c_register_devices(struct i2c_adapter *adap) { }
1687#endif /* CONFIG_OF */
1688
1689static int i2c_do_add_adapter(struct i2c_driver *driver,
1690                              struct i2c_adapter *adap)
1691{
1692        /* Detect supported devices on that bus, and instantiate them */
1693        i2c_detect(adap, driver);
1694
1695        /* Let legacy drivers scan this bus for matching devices */
1696        if (driver->attach_adapter) {
1697                dev_warn(&adap->dev, "%s: attach_adapter method is deprecated\n",
1698                         driver->driver.name);
1699                dev_warn(&adap->dev, "Please use another way to instantiate "
1700                         "your i2c_client\n");
1701                /* We ignore the return code; if it fails, too bad */
1702                driver->attach_adapter(adap);
1703        }
1704        return 0;
1705}
1706
1707static int __process_new_adapter(struct device_driver *d, void *data)
1708{
1709        return i2c_do_add_adapter(to_i2c_driver(d), data);
1710}
1711
1712static int i2c_register_adapter(struct i2c_adapter *adap)
1713{
1714        int res = -EINVAL;
1715
1716        /* Can't register until after driver model init */
1717        if (WARN_ON(!is_registered)) {
1718                res = -EAGAIN;
1719                goto out_list;
1720        }
1721
1722        /* Sanity checks */
1723        if (WARN(!adap->name[0], "i2c adapter has no name"))
1724                goto out_list;
1725
1726        if (!adap->algo) {
1727                pr_err("adapter '%s': no algo supplied!\n", adap->name);
1728                goto out_list;
1729        }
1730
1731        rt_mutex_init(&adap->bus_lock);
1732        mutex_init(&adap->userspace_clients_lock);
1733        INIT_LIST_HEAD(&adap->userspace_clients);
1734
1735        /* Set default timeout to 1 second if not already set */
1736        if (adap->timeout == 0)
1737                adap->timeout = HZ;
1738
1739        dev_set_name(&adap->dev, "i2c-%d", adap->nr);
1740        adap->dev.bus = &i2c_bus_type;
1741        adap->dev.type = &i2c_adapter_type;
1742        res = device_register(&adap->dev);
1743        if (res) {
1744                pr_err("adapter '%s': can't register device (%d)\n", adap->name, res);
1745                goto out_list;
1746        }
1747
1748        dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
1749
1750        pm_runtime_no_callbacks(&adap->dev);
1751        pm_suspend_ignore_children(&adap->dev, true);
1752        pm_runtime_enable(&adap->dev);
1753
1754#ifdef CONFIG_I2C_COMPAT
1755        res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
1756                                       adap->dev.parent);
1757        if (res)
1758                dev_warn(&adap->dev,
1759                         "Failed to create compatibility class link\n");
1760#endif
1761
1762        i2c_init_recovery(adap);
1763
1764        /* create pre-declared device nodes */
1765        of_i2c_register_devices(adap);
1766        i2c_acpi_register_devices(adap);
1767        i2c_acpi_install_space_handler(adap);
1768
1769        if (adap->nr < __i2c_first_dynamic_bus_num)
1770                i2c_scan_static_board_info(adap);
1771
1772        /* Notify drivers */
1773        mutex_lock(&core_lock);
1774        bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
1775        mutex_unlock(&core_lock);
1776
1777        return 0;
1778
1779out_list:
1780        mutex_lock(&core_lock);
1781        idr_remove(&i2c_adapter_idr, adap->nr);
1782        mutex_unlock(&core_lock);
1783        return res;
1784}
1785
1786/**
1787 * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
1788 * @adap: the adapter to register (with adap->nr initialized)
1789 * Context: can sleep
1790 *
1791 * See i2c_add_numbered_adapter() for details.
1792 */
1793static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
1794{
1795        int id;
1796
1797        mutex_lock(&core_lock);
1798        id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1, GFP_KERNEL);
1799        mutex_unlock(&core_lock);
1800        if (WARN(id < 0, "couldn't get idr"))
1801                return id == -ENOSPC ? -EBUSY : id;
1802
1803        return i2c_register_adapter(adap);
1804}
1805
1806/**
1807 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
1808 * @adapter: the adapter to add
1809 * Context: can sleep
1810 *
1811 * This routine is used to declare an I2C adapter when its bus number
1812 * doesn't matter or when its bus number is specified by an dt alias.
1813 * Examples of bases when the bus number doesn't matter: I2C adapters
1814 * dynamically added by USB links or PCI plugin cards.
1815 *
1816 * When this returns zero, a new bus number was allocated and stored
1817 * in adap->nr, and the specified adapter became available for clients.
1818 * Otherwise, a negative errno value is returned.
1819 */
1820int i2c_add_adapter(struct i2c_adapter *adapter)
1821{
1822        struct device *dev = &adapter->dev;
1823        int id;
1824
1825        if (dev->of_node) {
1826                id = of_alias_get_id(dev->of_node, "i2c");
1827                if (id >= 0) {
1828                        adapter->nr = id;
1829                        return __i2c_add_numbered_adapter(adapter);
1830                }
1831        }
1832
1833        mutex_lock(&core_lock);
1834        id = idr_alloc(&i2c_adapter_idr, adapter,
1835                       __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
1836        mutex_unlock(&core_lock);
1837        if (WARN(id < 0, "couldn't get idr"))
1838                return id;
1839
1840        adapter->nr = id;
1841
1842        return i2c_register_adapter(adapter);
1843}
1844EXPORT_SYMBOL(i2c_add_adapter);
1845
1846/**
1847 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
1848 * @adap: the adapter to register (with adap->nr initialized)
1849 * Context: can sleep
1850 *
1851 * This routine is used to declare an I2C adapter when its bus number
1852 * matters.  For example, use it for I2C adapters from system-on-chip CPUs,
1853 * or otherwise built in to the system's mainboard, and where i2c_board_info
1854 * is used to properly configure I2C devices.
1855 *
1856 * If the requested bus number is set to -1, then this function will behave
1857 * identically to i2c_add_adapter, and will dynamically assign a bus number.
1858 *
1859 * If no devices have pre-been declared for this bus, then be sure to
1860 * register the adapter before any dynamically allocated ones.  Otherwise
1861 * the required bus ID may not be available.
1862 *
1863 * When this returns zero, the specified adapter became available for
1864 * clients using the bus number provided in adap->nr.  Also, the table
1865 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
1866 * and the appropriate driver model device nodes are created.  Otherwise, a
1867 * negative errno value is returned.
1868 */
1869int i2c_add_numbered_adapter(struct i2c_adapter *adap)
1870{
1871        if (adap->nr == -1) /* -1 means dynamically assign bus id */
1872                return i2c_add_adapter(adap);
1873
1874        return __i2c_add_numbered_adapter(adap);
1875}
1876EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
1877
1878static void i2c_do_del_adapter(struct i2c_driver *driver,
1879                              struct i2c_adapter *adapter)
1880{
1881        struct i2c_client *client, *_n;
1882
1883        /* Remove the devices we created ourselves as the result of hardware
1884         * probing (using a driver's detect method) */
1885        list_for_each_entry_safe(client, _n, &driver->clients, detected) {
1886                if (client->adapter == adapter) {
1887                        dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
1888                                client->name, client->addr);
1889                        list_del(&client->detected);
1890                        i2c_unregister_device(client);
1891                }
1892        }
1893}
1894
1895static int __unregister_client(struct device *dev, void *dummy)
1896{
1897        struct i2c_client *client = i2c_verify_client(dev);
1898        if (client && strcmp(client->name, "dummy"))
1899                i2c_unregister_device(client);
1900        return 0;
1901}
1902
1903static int __unregister_dummy(struct device *dev, void *dummy)
1904{
1905        struct i2c_client *client = i2c_verify_client(dev);
1906        if (client)
1907                i2c_unregister_device(client);
1908        return 0;
1909}
1910
1911static int __process_removed_adapter(struct device_driver *d, void *data)
1912{
1913        i2c_do_del_adapter(to_i2c_driver(d), data);
1914        return 0;
1915}
1916
1917/**
1918 * i2c_del_adapter - unregister I2C adapter
1919 * @adap: the adapter being unregistered
1920 * Context: can sleep
1921 *
1922 * This unregisters an I2C adapter which was previously registered
1923 * by @i2c_add_adapter or @i2c_add_numbered_adapter.
1924 */
1925void i2c_del_adapter(struct i2c_adapter *adap)
1926{
1927        struct i2c_adapter *found;
1928        struct i2c_client *client, *next;
1929
1930        /* First make sure that this adapter was ever added */
1931        mutex_lock(&core_lock);
1932        found = idr_find(&i2c_adapter_idr, adap->nr);
1933        mutex_unlock(&core_lock);
1934        if (found != adap) {
1935                pr_debug("attempting to delete unregistered adapter [%s]\n", adap->name);
1936                return;
1937        }
1938
1939        i2c_acpi_remove_space_handler(adap);
1940        /* Tell drivers about this removal */
1941        mutex_lock(&core_lock);
1942        bus_for_each_drv(&i2c_bus_type, NULL, adap,
1943                               __process_removed_adapter);
1944        mutex_unlock(&core_lock);
1945
1946        /* Remove devices instantiated from sysfs */
1947        mutex_lock_nested(&adap->userspace_clients_lock,
1948                          i2c_adapter_depth(adap));
1949        list_for_each_entry_safe(client, next, &adap->userspace_clients,
1950                                 detected) {
1951                dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
1952                        client->addr);
1953                list_del(&client->detected);
1954                i2c_unregister_device(client);
1955        }
1956        mutex_unlock(&adap->userspace_clients_lock);
1957
1958        /* Detach any active clients. This can't fail, thus we do not
1959         * check the returned value. This is a two-pass process, because
1960         * we can't remove the dummy devices during the first pass: they
1961         * could have been instantiated by real devices wishing to clean
1962         * them up properly, so we give them a chance to do that first. */
1963        device_for_each_child(&adap->dev, NULL, __unregister_client);
1964        device_for_each_child(&adap->dev, NULL, __unregister_dummy);
1965
1966#ifdef CONFIG_I2C_COMPAT
1967        class_compat_remove_link(i2c_adapter_compat_class, &adap->dev,
1968                                 adap->dev.parent);
1969#endif
1970
1971        /* device name is gone after device_unregister */
1972        dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
1973
1974        pm_runtime_disable(&adap->dev);
1975
1976        /* wait until all references to the device are gone
1977         *
1978         * FIXME: This is old code and should ideally be replaced by an
1979         * alternative which results in decoupling the lifetime of the struct
1980         * device from the i2c_adapter, like spi or netdev do. Any solution
1981         * should be thoroughly tested with DEBUG_KOBJECT_RELEASE enabled!
1982         */
1983        init_completion(&adap->dev_released);
1984        device_unregister(&adap->dev);
1985        wait_for_completion(&adap->dev_released);
1986
1987        /* free bus id */
1988        mutex_lock(&core_lock);
1989        idr_remove(&i2c_adapter_idr, adap->nr);
1990        mutex_unlock(&core_lock);
1991
1992        /* Clear the device structure in case this adapter is ever going to be
1993           added again */
1994        memset(&adap->dev, 0, sizeof(adap->dev));
1995}
1996EXPORT_SYMBOL(i2c_del_adapter);
1997
1998/* ------------------------------------------------------------------------- */
1999
2000int i2c_for_each_dev(void *data, int (*fn)(struct device *, void *))
2001{
2002        int res;
2003
2004        mutex_lock(&core_lock);
2005        res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
2006        mutex_unlock(&core_lock);
2007
2008        return res;
2009}
2010EXPORT_SYMBOL_GPL(i2c_for_each_dev);
2011
2012static int __process_new_driver(struct device *dev, void *data)
2013{
2014        if (dev->type != &i2c_adapter_type)
2015                return 0;
2016        return i2c_do_add_adapter(data, to_i2c_adapter(dev));
2017}
2018
2019/*
2020 * An i2c_driver is used with one or more i2c_client (device) nodes to access
2021 * i2c slave chips, on a bus instance associated with some i2c_adapter.
2022 */
2023
2024int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
2025{
2026        int res;
2027
2028        /* Can't register until after driver model init */
2029        if (WARN_ON(!is_registered))
2030                return -EAGAIN;
2031
2032        /* add the driver to the list of i2c drivers in the driver core */
2033        driver->driver.owner = owner;
2034        driver->driver.bus = &i2c_bus_type;
2035
2036        /* When registration returns, the driver core
2037         * will have called probe() for all matching-but-unbound devices.
2038         */
2039        res = driver_register(&driver->driver);
2040        if (res)
2041                return res;
2042
2043        pr_debug("driver [%s] registered\n", driver->driver.name);
2044
2045        INIT_LIST_HEAD(&driver->clients);
2046        /* Walk the adapters that are already present */
2047        i2c_for_each_dev(driver, __process_new_driver);
2048
2049        return 0;
2050}
2051EXPORT_SYMBOL(i2c_register_driver);
2052
2053static int __process_removed_driver(struct device *dev, void *data)
2054{
2055        if (dev->type == &i2c_adapter_type)
2056                i2c_do_del_adapter(data, to_i2c_adapter(dev));
2057        return 0;
2058}
2059
2060/**
2061 * i2c_del_driver - unregister I2C driver
2062 * @driver: the driver being unregistered
2063 * Context: can sleep
2064 */
2065void i2c_del_driver(struct i2c_driver *driver)
2066{
2067        i2c_for_each_dev(driver, __process_removed_driver);
2068
2069        driver_unregister(&driver->driver);
2070        pr_debug("driver [%s] unregistered\n", driver->driver.name);
2071}
2072EXPORT_SYMBOL(i2c_del_driver);
2073
2074/* ------------------------------------------------------------------------- */
2075
2076/**
2077 * i2c_use_client - increments the reference count of the i2c client structure
2078 * @client: the client being referenced
2079 *
2080 * Each live reference to a client should be refcounted. The driver model does
2081 * that automatically as part of driver binding, so that most drivers don't
2082 * need to do this explicitly: they hold a reference until they're unbound
2083 * from the device.
2084 *
2085 * A pointer to the client with the incremented reference counter is returned.
2086 */
2087struct i2c_client *i2c_use_client(struct i2c_client *client)
2088{
2089        if (client && get_device(&client->dev))
2090                return client;
2091        return NULL;
2092}
2093EXPORT_SYMBOL(i2c_use_client);
2094
2095/**
2096 * i2c_release_client - release a use of the i2c client structure
2097 * @client: the client being no longer referenced
2098 *
2099 * Must be called when a user of a client is finished with it.
2100 */
2101void i2c_release_client(struct i2c_client *client)
2102{
2103        if (client)
2104                put_device(&client->dev);
2105}
2106EXPORT_SYMBOL(i2c_release_client);
2107
2108struct i2c_cmd_arg {
2109        unsigned        cmd;
2110        void            *arg;
2111};
2112
2113static int i2c_cmd(struct device *dev, void *_arg)
2114{
2115        struct i2c_client       *client = i2c_verify_client(dev);
2116        struct i2c_cmd_arg      *arg = _arg;
2117        struct i2c_driver       *driver;
2118
2119        if (!client || !client->dev.driver)
2120                return 0;
2121
2122        driver = to_i2c_driver(client->dev.driver);
2123        if (driver->command)
2124                driver->command(client, arg->cmd, arg->arg);
2125        return 0;
2126}
2127
2128void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
2129{
2130        struct i2c_cmd_arg      cmd_arg;
2131
2132        cmd_arg.cmd = cmd;
2133        cmd_arg.arg = arg;
2134        device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
2135}
2136EXPORT_SYMBOL(i2c_clients_command);
2137
2138static int __init i2c_init(void)
2139{
2140        int retval;
2141
2142        retval = bus_register(&i2c_bus_type);
2143        if (retval)
2144                return retval;
2145
2146        is_registered = true;
2147
2148#ifdef CONFIG_I2C_COMPAT
2149        i2c_adapter_compat_class = class_compat_register("i2c-adapter");
2150        if (!i2c_adapter_compat_class) {
2151                retval = -ENOMEM;
2152                goto bus_err;
2153        }
2154#endif
2155        retval = i2c_add_driver(&dummy_driver);
2156        if (retval)
2157                goto class_err;
2158
2159        if (IS_ENABLED(CONFIG_ACPI))
2160                WARN_ON(acpi_reconfig_notifier_register(&i2c_acpi_notifier));
2161
2162        return 0;
2163
2164class_err:
2165#ifdef CONFIG_I2C_COMPAT
2166        class_compat_unregister(i2c_adapter_compat_class);
2167bus_err:
2168#endif
2169        is_registered = false;
2170        bus_unregister(&i2c_bus_type);
2171        return retval;
2172}
2173
2174static void __exit i2c_exit(void)
2175{
2176        if (IS_ENABLED(CONFIG_ACPI))
2177                WARN_ON(acpi_reconfig_notifier_unregister(&i2c_acpi_notifier));
2178        i2c_del_driver(&dummy_driver);
2179#ifdef CONFIG_I2C_COMPAT
2180        class_compat_unregister(i2c_adapter_compat_class);
2181#endif
2182        bus_unregister(&i2c_bus_type);
2183        tracepoint_synchronize_unregister();
2184}
2185
2186/* We must initialize early, because some subsystems register i2c drivers
2187 * in subsys_initcall() code, but are linked (and initialized) before i2c.
2188 */
2189postcore_initcall(i2c_init);
2190module_exit(i2c_exit);
2191
2192/* ----------------------------------------------------
2193 * the functional interface to the i2c busses.
2194 * ----------------------------------------------------
2195 */
2196
2197/* Check if val is exceeding the quirk IFF quirk is non 0 */
2198#define i2c_quirk_exceeded(val, quirk) ((quirk) && ((val) > (quirk)))
2199
2200static int i2c_quirk_error(struct i2c_adapter *adap, struct i2c_msg *msg, char *err_msg)
2201{
2202        dev_err_ratelimited(&adap->dev, "adapter quirk: %s (addr 0x%04x, size %u, %s)\n",
2203                            err_msg, msg->addr, msg->len,
2204                            msg->flags & I2C_M_RD ? "read" : "write");
2205        return -EOPNOTSUPP;
2206}
2207
2208static int i2c_check_for_quirks(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2209{
2210        const struct i2c_adapter_quirks *q = adap->quirks;
2211        int max_num = q->max_num_msgs, i;
2212        bool do_len_check = true;
2213
2214        if (q->flags & I2C_AQ_COMB) {
2215                max_num = 2;
2216
2217                /* special checks for combined messages */
2218                if (num == 2) {
2219                        if (q->flags & I2C_AQ_COMB_WRITE_FIRST && msgs[0].flags & I2C_M_RD)
2220                                return i2c_quirk_error(adap, &msgs[0], "1st comb msg must be write");
2221
2222                        if (q->flags & I2C_AQ_COMB_READ_SECOND && !(msgs[1].flags & I2C_M_RD))
2223                                return i2c_quirk_error(adap, &msgs[1], "2nd comb msg must be read");
2224
2225                        if (q->flags & I2C_AQ_COMB_SAME_ADDR && msgs[0].addr != msgs[1].addr)
2226                                return i2c_quirk_error(adap, &msgs[0], "comb msg only to same addr");
2227
2228                        if (i2c_quirk_exceeded(msgs[0].len, q->max_comb_1st_msg_len))
2229                                return i2c_quirk_error(adap, &msgs[0], "msg too long");
2230
2231                        if (i2c_quirk_exceeded(msgs[1].len, q->max_comb_2nd_msg_len))
2232                                return i2c_quirk_error(adap, &msgs[1], "msg too long");
2233
2234                        do_len_check = false;
2235                }
2236        }
2237
2238        if (i2c_quirk_exceeded(num, max_num))
2239                return i2c_quirk_error(adap, &msgs[0], "too many messages");
2240
2241        for (i = 0; i < num; i++) {
2242                u16 len = msgs[i].len;
2243
2244                if (msgs[i].flags & I2C_M_RD) {
2245                        if (do_len_check && i2c_quirk_exceeded(len, q->max_read_len))
2246                                return i2c_quirk_error(adap, &msgs[i], "msg too long");
2247                } else {
2248                        if (do_len_check && i2c_quirk_exceeded(len, q->max_write_len))
2249                                return i2c_quirk_error(adap, &msgs[i], "msg too long");
2250                }
2251        }
2252
2253        return 0;
2254}
2255
2256/**
2257 * __i2c_transfer - unlocked flavor of i2c_transfer
2258 * @adap: Handle to I2C bus
2259 * @msgs: One or more messages to execute before STOP is issued to
2260 *      terminate the operation; each message begins with a START.
2261 * @num: Number of messages to be executed.
2262 *
2263 * Returns negative errno, else the number of messages executed.
2264 *
2265 * Adapter lock must be held when calling this function. No debug logging
2266 * takes place. adap->algo->master_xfer existence isn't checked.
2267 */
2268int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2269{
2270        unsigned long orig_jiffies;
2271        int ret, try;
2272
2273        if (adap->quirks && i2c_check_for_quirks(adap, msgs, num))
2274                return -EOPNOTSUPP;
2275
2276        /* i2c_trace_msg gets enabled when tracepoint i2c_transfer gets
2277         * enabled.  This is an efficient way of keeping the for-loop from
2278         * being executed when not needed.
2279         */
2280        if (static_key_false(&i2c_trace_msg)) {
2281                int i;
2282                for (i = 0; i < num; i++)
2283                        if (msgs[i].flags & I2C_M_RD)
2284                                trace_i2c_read(adap, &msgs[i], i);
2285                        else
2286                                trace_i2c_write(adap, &msgs[i], i);
2287        }
2288
2289        /* Retry automatically on arbitration loss */
2290        orig_jiffies = jiffies;
2291        for (ret = 0, try = 0; try <= adap->retries; try++) {
2292                ret = adap->algo->master_xfer(adap, msgs, num);
2293                if (ret != -EAGAIN)
2294                        break;
2295                if (time_after(jiffies, orig_jiffies + adap->timeout))
2296                        break;
2297        }
2298
2299        if (static_key_false(&i2c_trace_msg)) {
2300                int i;
2301                for (i = 0; i < ret; i++)
2302                        if (msgs[i].flags & I2C_M_RD)
2303                                trace_i2c_reply(adap, &msgs[i], i);
2304                trace_i2c_result(adap, i, ret);
2305        }
2306
2307        return ret;
2308}
2309EXPORT_SYMBOL(__i2c_transfer);
2310
2311/**
2312 * i2c_transfer - execute a single or combined I2C message
2313 * @adap: Handle to I2C bus
2314 * @msgs: One or more messages to execute before STOP is issued to
2315 *      terminate the operation; each message begins with a START.
2316 * @num: Number of messages to be executed.
2317 *
2318 * Returns negative errno, else the number of messages executed.
2319 *
2320 * Note that there is no requirement that each message be sent to
2321 * the same slave address, although that is the most common model.
2322 */
2323int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2324{
2325        int ret;
2326
2327        /* REVISIT the fault reporting model here is weak:
2328         *
2329         *  - When we get an error after receiving N bytes from a slave,
2330         *    there is no way to report "N".
2331         *
2332         *  - When we get a NAK after transmitting N bytes to a slave,
2333         *    there is no way to report "N" ... or to let the master
2334         *    continue executing the rest of this combined message, if
2335         *    that's the appropriate response.
2336         *
2337         *  - When for example "num" is two and we successfully complete
2338         *    the first message but get an error part way through the
2339         *    second, it's unclear whether that should be reported as
2340         *    one (discarding status on the second message) or errno
2341         *    (discarding status on the first one).
2342         */
2343
2344        if (adap->algo->master_xfer) {
2345#ifdef DEBUG
2346                for (ret = 0; ret < num; ret++) {
2347                        dev_dbg(&adap->dev, "master_xfer[%d] %c, addr=0x%02x, "
2348                                "len=%d%s\n", ret, (msgs[ret].flags & I2C_M_RD)
2349                                ? 'R' : 'W', msgs[ret].addr, msgs[ret].len,
2350                                (msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
2351                }
2352#endif
2353
2354                if (in_atomic() || irqs_disabled()) {
2355                        ret = i2c_trylock_adapter(adap);
2356                        if (!ret)
2357                                /* I2C activity is ongoing. */
2358                                return -EAGAIN;
2359                } else {
2360                        i2c_lock_adapter(adap);
2361                }
2362
2363                ret = __i2c_transfer(adap, msgs, num);
2364                i2c_unlock_adapter(adap);
2365
2366                return ret;
2367        } else {
2368                dev_dbg(&adap->dev, "I2C level transfers not supported\n");
2369                return -EOPNOTSUPP;
2370        }
2371}
2372EXPORT_SYMBOL(i2c_transfer);
2373
2374/**
2375 * i2c_master_send - issue a single I2C message in master transmit mode
2376 * @client: Handle to slave device
2377 * @buf: Data that will be written to the slave
2378 * @count: How many bytes to write, must be less than 64k since msg.len is u16
2379 *
2380 * Returns negative errno, or else the number of bytes written.
2381 */
2382int i2c_master_send(const struct i2c_client *client, const char *buf, int count)
2383{
2384        int ret;
2385        struct i2c_adapter *adap = client->adapter;
2386        struct i2c_msg msg;
2387
2388        msg.addr = client->addr;
2389        msg.flags = client->flags & I2C_M_TEN;
2390        msg.len = count;
2391        msg.buf = (char *)buf;
2392
2393        ret = i2c_transfer(adap, &msg, 1);
2394
2395        /*
2396         * If everything went ok (i.e. 1 msg transmitted), return #bytes
2397         * transmitted, else error code.
2398         */
2399        return (ret == 1) ? count : ret;
2400}
2401EXPORT_SYMBOL(i2c_master_send);
2402
2403/**
2404 * i2c_master_recv - issue a single I2C message in master receive mode
2405 * @client: Handle to slave device
2406 * @buf: Where to store data read from slave
2407 * @count: How many bytes to read, must be less than 64k since msg.len is u16
2408 *
2409 * Returns negative errno, or else the number of bytes read.
2410 */
2411int i2c_master_recv(const struct i2c_client *client, char *buf, int count)
2412{
2413        struct i2c_adapter *adap = client->adapter;
2414        struct i2c_msg msg;
2415        int ret;
2416
2417        msg.addr = client->addr;
2418        msg.flags = client->flags & I2C_M_TEN;
2419        msg.flags |= I2C_M_RD;
2420        msg.len = count;
2421        msg.buf = buf;
2422
2423        ret = i2c_transfer(adap, &msg, 1);
2424
2425        /*
2426         * If everything went ok (i.e. 1 msg received), return #bytes received,
2427         * else error code.
2428         */
2429        return (ret == 1) ? count : ret;
2430}
2431EXPORT_SYMBOL(i2c_master_recv);
2432
2433/* ----------------------------------------------------
2434 * the i2c address scanning function
2435 * Will not work for 10-bit addresses!
2436 * ----------------------------------------------------
2437 */
2438
2439/*
2440 * Legacy default probe function, mostly relevant for SMBus. The default
2441 * probe method is a quick write, but it is known to corrupt the 24RF08
2442 * EEPROMs due to a state machine bug, and could also irreversibly
2443 * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
2444 * we use a short byte read instead. Also, some bus drivers don't implement
2445 * quick write, so we fallback to a byte read in that case too.
2446 * On x86, there is another special case for FSC hardware monitoring chips,
2447 * which want regular byte reads (address 0x73.) Fortunately, these are the
2448 * only known chips using this I2C address on PC hardware.
2449 * Returns 1 if probe succeeded, 0 if not.
2450 */
2451static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
2452{
2453        int err;
2454        union i2c_smbus_data dummy;
2455
2456#ifdef CONFIG_X86
2457        if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
2458         && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
2459                err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2460                                     I2C_SMBUS_BYTE_DATA, &dummy);
2461        else
2462#endif
2463        if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
2464         && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
2465                err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
2466                                     I2C_SMBUS_QUICK, NULL);
2467        else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
2468                err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2469                                     I2C_SMBUS_BYTE, &dummy);
2470        else {
2471                dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n",
2472                         addr);
2473                err = -EOPNOTSUPP;
2474        }
2475
2476        return err >= 0;
2477}
2478
2479static int i2c_detect_address(struct i2c_client *temp_client,
2480                              struct i2c_driver *driver)
2481{
2482        struct i2c_board_info info;
2483        struct i2c_adapter *adapter = temp_client->adapter;
2484        int addr = temp_client->addr;
2485        int err;
2486
2487        /* Make sure the address is valid */
2488        err = i2c_check_7bit_addr_validity_strict(addr);
2489        if (err) {
2490                dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
2491                         addr);
2492                return err;
2493        }
2494
2495        /* Skip if already in use (7 bit, no need to encode flags) */
2496        if (i2c_check_addr_busy(adapter, addr))
2497                return 0;
2498
2499        /* Make sure there is something at this address */
2500        if (!i2c_default_probe(adapter, addr))
2501                return 0;
2502
2503        /* Finally call the custom detection function */
2504        memset(&info, 0, sizeof(struct i2c_board_info));
2505        info.addr = addr;
2506        err = driver->detect(temp_client, &info);
2507        if (err) {
2508                /* -ENODEV is returned if the detection fails. We catch it
2509                   here as this isn't an error. */
2510                return err == -ENODEV ? 0 : err;
2511        }
2512
2513        /* Consistency check */
2514        if (info.type[0] == '\0') {
2515                dev_err(&adapter->dev, "%s detection function provided "
2516                        "no name for 0x%x\n", driver->driver.name,
2517                        addr);
2518        } else {
2519                struct i2c_client *client;
2520
2521                /* Detection succeeded, instantiate the device */
2522                if (adapter->class & I2C_CLASS_DEPRECATED)
2523                        dev_warn(&adapter->dev,
2524                                "This adapter will soon drop class based instantiation of devices. "
2525                                "Please make sure client 0x%02x gets instantiated by other means. "
2526                                "Check 'Documentation/i2c/instantiating-devices' for details.\n",
2527                                info.addr);
2528
2529                dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
2530                        info.type, info.addr);
2531                client = i2c_new_device(adapter, &info);
2532                if (client)
2533                        list_add_tail(&client->detected, &driver->clients);
2534                else
2535                        dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
2536                                info.type, info.addr);
2537        }
2538        return 0;
2539}
2540
2541static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
2542{
2543        const unsigned short *address_list;
2544        struct i2c_client *temp_client;
2545        int i, err = 0;
2546        int adap_id = i2c_adapter_id(adapter);
2547
2548        address_list = driver->address_list;
2549        if (!driver->detect || !address_list)
2550                return 0;
2551
2552        /* Warn that the adapter lost class based instantiation */
2553        if (adapter->class == I2C_CLASS_DEPRECATED) {
2554                dev_dbg(&adapter->dev,
2555                        "This adapter dropped support for I2C classes and "
2556                        "won't auto-detect %s devices anymore. If you need it, check "
2557                        "'Documentation/i2c/instantiating-devices' for alternatives.\n",
2558                        driver->driver.name);
2559                return 0;
2560        }
2561
2562        /* Stop here if the classes do not match */
2563        if (!(adapter->class & driver->class))
2564                return 0;
2565
2566        /* Set up a temporary client to help detect callback */
2567        temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
2568        if (!temp_client)
2569                return -ENOMEM;
2570        temp_client->adapter = adapter;
2571
2572        for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
2573                dev_dbg(&adapter->dev, "found normal entry for adapter %d, "
2574                        "addr 0x%02x\n", adap_id, address_list[i]);
2575                temp_client->addr = address_list[i];
2576                err = i2c_detect_address(temp_client, driver);
2577                if (unlikely(err))
2578                        break;
2579        }
2580
2581        kfree(temp_client);
2582        return err;
2583}
2584
2585int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
2586{
2587        return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2588                              I2C_SMBUS_QUICK, NULL) >= 0;
2589}
2590EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
2591
2592struct i2c_client *
2593i2c_new_probed_device(struct i2c_adapter *adap,
2594                      struct i2c_board_info *info,
2595                      unsigned short const *addr_list,
2596                      int (*probe)(struct i2c_adapter *, unsigned short addr))
2597{
2598        int i;
2599
2600        if (!probe)
2601                probe = i2c_default_probe;
2602
2603        for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
2604                /* Check address validity */
2605                if (i2c_check_7bit_addr_validity_strict(addr_list[i]) < 0) {
2606                        dev_warn(&adap->dev, "Invalid 7-bit address "
2607                                 "0x%02x\n", addr_list[i]);
2608                        continue;
2609                }
2610
2611                /* Check address availability (7 bit, no need to encode flags) */
2612                if (i2c_check_addr_busy(adap, addr_list[i])) {
2613                        dev_dbg(&adap->dev, "Address 0x%02x already in "
2614                                "use, not probing\n", addr_list[i]);
2615                        continue;
2616                }
2617
2618                /* Test address responsiveness */
2619                if (probe(adap, addr_list[i]))
2620                        break;
2621        }
2622
2623        if (addr_list[i] == I2C_CLIENT_END) {
2624                dev_dbg(&adap->dev, "Probing failed, no device found\n");
2625                return NULL;
2626        }
2627
2628        info->addr = addr_list[i];
2629        return i2c_new_device(adap, info);
2630}
2631EXPORT_SYMBOL_GPL(i2c_new_probed_device);
2632
2633struct i2c_adapter *i2c_get_adapter(int nr)
2634{
2635        struct i2c_adapter *adapter;
2636
2637        mutex_lock(&core_lock);
2638        adapter = idr_find(&i2c_adapter_idr, nr);
2639        if (!adapter)
2640                goto exit;
2641
2642        if (try_module_get(adapter->owner))
2643                get_device(&adapter->dev);
2644        else
2645                adapter = NULL;
2646
2647 exit:
2648        mutex_unlock(&core_lock);
2649        return adapter;
2650}
2651EXPORT_SYMBOL(i2c_get_adapter);
2652
2653void i2c_put_adapter(struct i2c_adapter *adap)
2654{
2655        if (!adap)
2656                return;
2657
2658        put_device(&adap->dev);
2659        module_put(adap->owner);
2660}
2661EXPORT_SYMBOL(i2c_put_adapter);
2662
2663/* The SMBus parts */
2664
2665#define POLY    (0x1070U << 3)
2666static u8 crc8(u16 data)
2667{
2668        int i;
2669
2670        for (i = 0; i < 8; i++) {
2671                if (data & 0x8000)
2672                        data = data ^ POLY;
2673                data = data << 1;
2674        }
2675        return (u8)(data >> 8);
2676}
2677
2678/* Incremental CRC8 over count bytes in the array pointed to by p */
2679static u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
2680{
2681        int i;
2682
2683        for (i = 0; i < count; i++)
2684                crc = crc8((crc ^ p[i]) << 8);
2685        return crc;
2686}
2687
2688/* Assume a 7-bit address, which is reasonable for SMBus */
2689static u8 i2c_smbus_msg_pec(u8 pec, struct i2c_msg *msg)
2690{
2691        /* The address will be sent first */
2692        u8 addr = i2c_8bit_addr_from_msg(msg);
2693        pec = i2c_smbus_pec(pec, &addr, 1);
2694
2695        /* The data buffer follows */
2696        return i2c_smbus_pec(pec, msg->buf, msg->len);
2697}
2698
2699/* Used for write only transactions */
2700static inline void i2c_smbus_add_pec(struct i2c_msg *msg)
2701{
2702        msg->buf[msg->len] = i2c_smbus_msg_pec(0, msg);
2703        msg->len++;
2704}
2705
2706/* Return <0 on CRC error
2707   If there was a write before this read (most cases) we need to take the
2708   partial CRC from the write part into account.
2709   Note that this function does modify the message (we need to decrease the
2710   message length to hide the CRC byte from the caller). */
2711static int i2c_smbus_check_pec(u8 cpec, struct i2c_msg *msg)
2712{
2713        u8 rpec = msg->buf[--msg->len];
2714        cpec = i2c_smbus_msg_pec(cpec, msg);
2715
2716        if (rpec != cpec) {
2717                pr_debug("Bad PEC 0x%02x vs. 0x%02x\n",
2718                        rpec, cpec);
2719                return -EBADMSG;
2720        }
2721        return 0;
2722}
2723
2724/**
2725 * i2c_smbus_read_byte - SMBus "receive byte" protocol
2726 * @client: Handle to slave device
2727 *
2728 * This executes the SMBus "receive byte" protocol, returning negative errno
2729 * else the byte received from the device.
2730 */
2731s32 i2c_smbus_read_byte(const struct i2c_client *client)
2732{
2733        union i2c_smbus_data data;
2734        int status;
2735
2736        status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2737                                I2C_SMBUS_READ, 0,
2738                                I2C_SMBUS_BYTE, &data);
2739        return (status < 0) ? status : data.byte;
2740}
2741EXPORT_SYMBOL(i2c_smbus_read_byte);
2742
2743/**
2744 * i2c_smbus_write_byte - SMBus "send byte" protocol
2745 * @client: Handle to slave device
2746 * @value: Byte to be sent
2747 *
2748 * This executes the SMBus "send byte" protocol, returning negative errno
2749 * else zero on success.
2750 */
2751s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value)
2752{
2753        return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2754                              I2C_SMBUS_WRITE, value, I2C_SMBUS_BYTE, NULL);
2755}
2756EXPORT_SYMBOL(i2c_smbus_write_byte);
2757
2758/**
2759 * i2c_smbus_read_byte_data - SMBus "read byte" protocol
2760 * @client: Handle to slave device
2761 * @command: Byte interpreted by slave
2762 *
2763 * This executes the SMBus "read byte" protocol, returning negative errno
2764 * else a data byte received from the device.
2765 */
2766s32 i2c_smbus_read_byte_data(const struct i2c_client *client, u8 command)
2767{
2768        union i2c_smbus_data data;
2769        int status;
2770
2771        status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2772                                I2C_SMBUS_READ, command,
2773                                I2C_SMBUS_BYTE_DATA, &data);
2774        return (status < 0) ? status : data.byte;
2775}
2776EXPORT_SYMBOL(i2c_smbus_read_byte_data);
2777
2778/**
2779 * i2c_smbus_write_byte_data - SMBus "write byte" protocol
2780 * @client: Handle to slave device
2781 * @command: Byte interpreted by slave
2782 * @value: Byte being written
2783 *
2784 * This executes the SMBus "write byte" protocol, returning negative errno
2785 * else zero on success.
2786 */
2787s32 i2c_smbus_write_byte_data(const struct i2c_client *client, u8 command,
2788                              u8 value)
2789{
2790        union i2c_smbus_data data;
2791        data.byte = value;
2792        return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2793                              I2C_SMBUS_WRITE, command,
2794                              I2C_SMBUS_BYTE_DATA, &data);
2795}
2796EXPORT_SYMBOL(i2c_smbus_write_byte_data);
2797
2798/**
2799 * i2c_smbus_read_word_data - SMBus "read word" protocol
2800 * @client: Handle to slave device
2801 * @command: Byte interpreted by slave
2802 *
2803 * This executes the SMBus "read word" protocol, returning negative errno
2804 * else a 16-bit unsigned "word" received from the device.
2805 */
2806s32 i2c_smbus_read_word_data(const struct i2c_client *client, u8 command)
2807{
2808        union i2c_smbus_data data;
2809        int status;
2810
2811        status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2812                                I2C_SMBUS_READ, command,
2813                                I2C_SMBUS_WORD_DATA, &data);
2814        return (status < 0) ? status : data.word;
2815}
2816EXPORT_SYMBOL(i2c_smbus_read_word_data);
2817
2818/**
2819 * i2c_smbus_write_word_data - SMBus "write word" protocol
2820 * @client: Handle to slave device
2821 * @command: Byte interpreted by slave
2822 * @value: 16-bit "word" being written
2823 *
2824 * This executes the SMBus "write word" protocol, returning negative errno
2825 * else zero on success.
2826 */
2827s32 i2c_smbus_write_word_data(const struct i2c_client *client, u8 command,
2828                              u16 value)
2829{
2830        union i2c_smbus_data data;
2831        data.word = value;
2832        return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2833                              I2C_SMBUS_WRITE, command,
2834                              I2C_SMBUS_WORD_DATA, &data);
2835}
2836EXPORT_SYMBOL(i2c_smbus_write_word_data);
2837
2838/**
2839 * i2c_smbus_read_block_data - SMBus "block read" protocol
2840 * @client: Handle to slave device
2841 * @command: Byte interpreted by slave
2842 * @values: Byte array into which data will be read; big enough to hold
2843 *      the data returned by the slave.  SMBus allows at most 32 bytes.
2844 *
2845 * This executes the SMBus "block read" protocol, returning negative errno
2846 * else the number of data bytes in the slave's response.
2847 *
2848 * Note that using this function requires that the client's adapter support
2849 * the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality.  Not all adapter drivers
2850 * support this; its emulation through I2C messaging relies on a specific
2851 * mechanism (I2C_M_RECV_LEN) which may not be implemented.
2852 */
2853s32 i2c_smbus_read_block_data(const struct i2c_client *client, u8 command,
2854                              u8 *values)
2855{
2856        union i2c_smbus_data data;
2857        int status;
2858
2859        status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2860                                I2C_SMBUS_READ, command,
2861                                I2C_SMBUS_BLOCK_DATA, &data);
2862        if (status)
2863                return status;
2864
2865        memcpy(values, &data.block[1], data.block[0]);
2866        return data.block[0];
2867}
2868EXPORT_SYMBOL(i2c_smbus_read_block_data);
2869
2870/**
2871 * i2c_smbus_write_block_data - SMBus "block write" protocol
2872 * @client: Handle to slave device
2873 * @command: Byte interpreted by slave
2874 * @length: Size of data block; SMBus allows at most 32 bytes
2875 * @values: Byte array which will be written.
2876 *
2877 * This executes the SMBus "block write" protocol, returning negative errno
2878 * else zero on success.
2879 */
2880s32 i2c_smbus_write_block_data(const struct i2c_client *client, u8 command,
2881                               u8 length, const u8 *values)
2882{
2883        union i2c_smbus_data data;
2884
2885        if (length > I2C_SMBUS_BLOCK_MAX)
2886                length = I2C_SMBUS_BLOCK_MAX;
2887        data.block[0] = length;
2888        memcpy(&data.block[1], values, length);
2889        return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2890                              I2C_SMBUS_WRITE, command,
2891                              I2C_SMBUS_BLOCK_DATA, &data);
2892}
2893EXPORT_SYMBOL(i2c_smbus_write_block_data);
2894
2895/* Returns the number of read bytes */
2896s32 i2c_smbus_read_i2c_block_data(const struct i2c_client *client, u8 command,
2897                                  u8 length, u8 *values)
2898{
2899        union i2c_smbus_data data;
2900        int status;
2901
2902        if (length > I2C_SMBUS_BLOCK_MAX)
2903                length = I2C_SMBUS_BLOCK_MAX;
2904        data.block[0] = length;
2905        status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2906                                I2C_SMBUS_READ, command,
2907                                I2C_SMBUS_I2C_BLOCK_DATA, &data);
2908        if (status < 0)
2909                return status;
2910
2911        memcpy(values, &data.block[1], data.block[0]);
2912        return data.block[0];
2913}
2914EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data);
2915
2916s32 i2c_smbus_write_i2c_block_data(const struct i2c_client *client, u8 command,
2917                                   u8 length, const u8 *values)
2918{
2919        union i2c_smbus_data data;
2920
2921        if (length > I2C_SMBUS_BLOCK_MAX)
2922                length = I2C_SMBUS_BLOCK_MAX;
2923        data.block[0] = length;
2924        memcpy(data.block + 1, values, length);
2925        return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2926                              I2C_SMBUS_WRITE, command,
2927                              I2C_SMBUS_I2C_BLOCK_DATA, &data);
2928}
2929EXPORT_SYMBOL(i2c_smbus_write_i2c_block_data);
2930
2931/* Simulate a SMBus command using the i2c protocol
2932   No checking of parameters is done!  */
2933static s32 i2c_smbus_xfer_emulated(struct i2c_adapter *adapter, u16 addr,
2934                                   unsigned short flags,
2935                                   char read_write, u8 command, int size,
2936                                   union i2c_smbus_data *data)
2937{
2938        /* So we need to generate a series of msgs. In the case of writing, we
2939          need to use only one message; when reading, we need two. We initialize
2940          most things with sane defaults, to keep the code below somewhat
2941          simpler. */
2942        unsigned char msgbuf0[I2C_SMBUS_BLOCK_MAX+3];
2943        unsigned char msgbuf1[I2C_SMBUS_BLOCK_MAX+2];
2944        int num = read_write == I2C_SMBUS_READ ? 2 : 1;
2945        int i;
2946        u8 partial_pec = 0;
2947        int status;
2948        struct i2c_msg msg[2] = {
2949                {
2950                        .addr = addr,
2951                        .flags = flags,
2952                        .len = 1,
2953                        .buf = msgbuf0,
2954                }, {
2955                        .addr = addr,
2956                        .flags = flags | I2C_M_RD,
2957                        .len = 0,
2958                        .buf = msgbuf1,
2959                },
2960        };
2961
2962        msgbuf0[0] = command;
2963        switch (size) {
2964        case I2C_SMBUS_QUICK:
2965                msg[0].len = 0;
2966                /* Special case: The read/write field is used as data */
2967                msg[0].flags = flags | (read_write == I2C_SMBUS_READ ?
2968                                        I2C_M_RD : 0);
2969                num = 1;
2970                break;
2971        case I2C_SMBUS_BYTE:
2972                if (read_write == I2C_SMBUS_READ) {
2973                        /* Special case: only a read! */
2974                        msg[0].flags = I2C_M_RD | flags;
2975                        num = 1;
2976                }
2977                break;
2978        case I2C_SMBUS_BYTE_DATA:
2979                if (read_write == I2C_SMBUS_READ)
2980                        msg[1].len = 1;
2981                else {
2982                        msg[0].len = 2;
2983                        msgbuf0[1] = data->byte;
2984                }
2985                break;
2986        case I2C_SMBUS_WORD_DATA:
2987                if (read_write == I2C_SMBUS_READ)
2988                        msg[1].len = 2;
2989                else {
2990                        msg[0].len = 3;
2991                        msgbuf0[1] = data->word & 0xff;
2992                        msgbuf0[2] = data->word >> 8;
2993                }
2994                break;
2995        case I2C_SMBUS_PROC_CALL:
2996                num = 2; /* Special case */
2997                read_write = I2C_SMBUS_READ;
2998                msg[0].len = 3;
2999                msg[1].len = 2;
3000                msgbuf0[1] = data->word & 0xff;
3001                msgbuf0[2] = data->word >> 8;
3002                break;
3003        case I2C_SMBUS_BLOCK_DATA:
3004                if (read_write == I2C_SMBUS_READ) {
3005                        msg[1].flags |= I2C_M_RECV_LEN;
3006                        msg[1].len = 1; /* block length will be added by
3007                                           the underlying bus driver */
3008                } else {
3009                        msg[0].len = data->block[0] + 2;
3010                        if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) {
3011                                dev_err(&adapter->dev,
3012                                        "Invalid block write size %d\n",
3013                                        data->block[0]);
3014                                return -EINVAL;
3015                        }
3016                        for (i = 1; i < msg[0].len; i++)
3017                                msgbuf0[i] = data->block[i-1];
3018                }
3019                break;
3020        case I2C_SMBUS_BLOCK_PROC_CALL:
3021                num = 2; /* Another special case */
3022                read_write = I2C_SMBUS_READ;
3023                if (data->block[0] > I2C_SMBUS_BLOCK_MAX) {
3024                        dev_err(&adapter->dev,
3025                                "Invalid block write size %d\n",
3026                                data->block[0]);
3027                        return -EINVAL;
3028                }
3029                msg[0].len = data->block[0] + 2;
3030                for (i = 1; i < msg[0].len; i++)
3031                        msgbuf0[i] = data->block[i-1];
3032                msg[1].flags |= I2C_M_RECV_LEN;
3033                msg[1].len = 1; /* block length will be added by
3034                                   the underlying bus driver */
3035                break;
3036        case I2C_SMBUS_I2C_BLOCK_DATA:
3037                if (read_write == I2C_SMBUS_READ) {
3038                        msg[1].len = data->block[0];
3039                } else {
3040                        msg[0].len = data->block[0] + 1;
3041                        if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 1) {
3042                                dev_err(&adapter->dev,
3043                                        "Invalid block write size %d\n",
3044                                        data->block[0]);
3045                                return -EINVAL;
3046                        }
3047                        for (i = 1; i <= data->block[0]; i++)
3048                                msgbuf0[i] = data->block[i];
3049                }
3050                break;
3051        default:
3052                dev_err(&adapter->dev, "Unsupported transaction %d\n", size);
3053                return -EOPNOTSUPP;
3054        }
3055
3056        i = ((flags & I2C_CLIENT_PEC) && size != I2C_SMBUS_QUICK
3057                                      && size != I2C_SMBUS_I2C_BLOCK_DATA);
3058        if (i) {
3059                /* Compute PEC if first message is a write */
3060                if (!(msg[0].flags & I2C_M_RD)) {
3061                        if (num == 1) /* Write only */
3062                                i2c_smbus_add_pec(&msg[0]);
3063                        else /* Write followed by read */
3064                                partial_pec = i2c_smbus_msg_pec(0, &msg[0]);
3065                }
3066                /* Ask for PEC if last message is a read */
3067                if (msg[num-1].flags & I2C_M_RD)
3068                        msg[num-1].len++;
3069        }
3070
3071        status = i2c_transfer(adapter, msg, num);
3072        if (status < 0)
3073                return status;
3074
3075        /* Check PEC if last message is a read */
3076        if (i && (msg[num-1].flags & I2C_M_RD)) {
3077                status = i2c_smbus_check_pec(partial_pec, &msg[num-1]);
3078                if (status < 0)
3079                        return status;
3080        }
3081
3082        if (read_write == I2C_SMBUS_READ)
3083                switch (size) {
3084                case I2C_SMBUS_BYTE:
3085                        data->byte = msgbuf0[0];
3086                        break;
3087                case I2C_SMBUS_BYTE_DATA:
3088                        data->byte = msgbuf1[0];
3089                        break;
3090                case I2C_SMBUS_WORD_DATA:
3091                case I2C_SMBUS_PROC_CALL:
3092                        data->word = msgbuf1[0] | (msgbuf1[1] << 8);
3093                        break;
3094                case I2C_SMBUS_I2C_BLOCK_DATA:
3095                        for (i = 0; i < data->block[0]; i++)
3096                                data->block[i+1] = msgbuf1[i];
3097                        break;
3098                case I2C_SMBUS_BLOCK_DATA:
3099                case I2C_SMBUS_BLOCK_PROC_CALL:
3100                        for (i = 0; i < msgbuf1[0] + 1; i++)
3101                                data->block[i] = msgbuf1[i];
3102                        break;
3103                }
3104        return 0;
3105}
3106
3107/**
3108 * i2c_smbus_xfer - execute SMBus protocol operations
3109 * @adapter: Handle to I2C bus
3110 * @addr: Address of SMBus slave on that bus
3111 * @flags: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC)
3112 * @read_write: I2C_SMBUS_READ or I2C_SMBUS_WRITE
3113 * @command: Byte interpreted by slave, for protocols which use such bytes
3114 * @protocol: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL
3115 * @data: Data to be read or written
3116 *
3117 * This executes an SMBus protocol operation, and returns a negative
3118 * errno code else zero on success.
3119 */
3120s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags,
3121                   char read_write, u8 command, int protocol,
3122                   union i2c_smbus_data *data)
3123{
3124        unsigned long orig_jiffies;
3125        int try;
3126        s32 res;
3127
3128        /* If enabled, the following two tracepoints are conditional on
3129         * read_write and protocol.
3130         */
3131        trace_smbus_write(adapter, addr, flags, read_write,
3132                          command, protocol, data);
3133        trace_smbus_read(adapter, addr, flags, read_write,
3134                         command, protocol);
3135
3136        flags &= I2C_M_TEN | I2C_CLIENT_PEC | I2C_CLIENT_SCCB;
3137
3138        if (adapter->algo->smbus_xfer) {
3139                i2c_lock_adapter(adapter);
3140
3141                /* Retry automatically on arbitration loss */
3142                orig_jiffies = jiffies;
3143                for (res = 0, try = 0; try <= adapter->retries; try++) {
3144                        res = adapter->algo->smbus_xfer(adapter, addr, flags,
3145                                                        read_write, command,
3146                                                        protocol, data);
3147                        if (res != -EAGAIN)
3148                                break;
3149                        if (time_after(jiffies,
3150                                       orig_jiffies + adapter->timeout))
3151                                break;
3152                }
3153                i2c_unlock_adapter(adapter);
3154
3155                if (res != -EOPNOTSUPP || !adapter->algo->master_xfer)
3156                        goto trace;
3157                /*
3158                 * Fall back to i2c_smbus_xfer_emulated if the adapter doesn't
3159                 * implement native support for the SMBus operation.
3160                 */
3161        }
3162
3163        res = i2c_smbus_xfer_emulated(adapter, addr, flags, read_write,
3164                                      command, protocol, data);
3165
3166trace:
3167        /* If enabled, the reply tracepoint is conditional on read_write. */
3168        trace_smbus_reply(adapter, addr, flags, read_write,
3169                          command, protocol, data);
3170        trace_smbus_result(adapter, addr, flags, read_write,
3171                           command, protocol, res);
3172
3173        return res;
3174}
3175EXPORT_SYMBOL(i2c_smbus_xfer);
3176
3177/**
3178 * i2c_smbus_read_i2c_block_data_or_emulated - read block or emulate
3179 * @client: Handle to slave device
3180 * @command: Byte interpreted by slave
3181 * @length: Size of data block; SMBus allows at most I2C_SMBUS_BLOCK_MAX bytes
3182 * @values: Byte array into which data will be read; big enough to hold
3183 *      the data returned by the slave.  SMBus allows at most
3184 *      I2C_SMBUS_BLOCK_MAX bytes.
3185 *
3186 * This executes the SMBus "block read" protocol if supported by the adapter.
3187 * If block read is not supported, it emulates it using either word or byte
3188 * read protocols depending on availability.
3189 *
3190 * The addresses of the I2C slave device that are accessed with this function
3191 * must be mapped to a linear region, so that a block read will have the same
3192 * effect as a byte read. Before using this function you must double-check
3193 * if the I2C slave does support exchanging a block transfer with a byte
3194 * transfer.
3195 */
3196s32 i2c_smbus_read_i2c_block_data_or_emulated(const struct i2c_client *client,
3197                                              u8 command, u8 length, u8 *values)
3198{
3199        u8 i = 0;
3200        int status;
3201
3202        if (length > I2C_SMBUS_BLOCK_MAX)
3203                length = I2C_SMBUS_BLOCK_MAX;
3204
3205        if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_I2C_BLOCK))
3206                return i2c_smbus_read_i2c_block_data(client, command, length, values);
3207
3208        if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_BYTE_DATA))
3209                return -EOPNOTSUPP;
3210
3211        if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_WORD_DATA)) {
3212                while ((i + 2) <= length) {
3213                        status = i2c_smbus_read_word_data(client, command + i);
3214                        if (status < 0)
3215                                return status;
3216                        values[i] = status & 0xff;
3217                        values[i + 1] = status >> 8;
3218                        i += 2;
3219                }
3220        }
3221
3222        while (i < length) {
3223                status = i2c_smbus_read_byte_data(client, command + i);
3224                if (status < 0)
3225                        return status;
3226                values[i] = status;
3227                i++;
3228        }
3229
3230        return i;
3231}
3232EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data_or_emulated);
3233
3234#if IS_ENABLED(CONFIG_I2C_SLAVE)
3235int i2c_slave_register(struct i2c_client *client, i2c_slave_cb_t slave_cb)
3236{
3237        int ret;
3238
3239        if (!client || !slave_cb) {
3240                WARN(1, "insufficent data\n");
3241                return -EINVAL;
3242        }
3243
3244        if (!(client->flags & I2C_CLIENT_SLAVE))
3245                dev_warn(&client->dev, "%s: client slave flag not set. You might see address collisions\n",
3246                         __func__);
3247
3248        if (!(client->flags & I2C_CLIENT_TEN)) {
3249                /* Enforce stricter address checking */
3250                ret = i2c_check_7bit_addr_validity_strict(client->addr);
3251                if (ret) {
3252                        dev_err(&client->dev, "%s: invalid address\n", __func__);
3253                        return ret;
3254                }
3255        }
3256
3257        if (!client->adapter->algo->reg_slave) {
3258                dev_err(&client->dev, "%s: not supported by adapter\n", __func__);
3259                return -EOPNOTSUPP;
3260        }
3261
3262        client->slave_cb = slave_cb;
3263
3264        i2c_lock_adapter(client->adapter);
3265        ret = client->adapter->algo->reg_slave(client);
3266        i2c_unlock_adapter(client->adapter);
3267
3268        if (ret) {
3269                client->slave_cb = NULL;
3270                dev_err(&client->dev, "%s: adapter returned error %d\n", __func__, ret);
3271        }
3272
3273        return ret;
3274}
3275EXPORT_SYMBOL_GPL(i2c_slave_register);
3276
3277int i2c_slave_unregister(struct i2c_client *client)
3278{
3279        int ret;
3280
3281        if (!client->adapter->algo->unreg_slave) {
3282                dev_err(&client->dev, "%s: not supported by adapter\n", __func__);
3283                return -EOPNOTSUPP;
3284        }
3285
3286        i2c_lock_adapter(client->adapter);
3287        ret = client->adapter->algo->unreg_slave(client);
3288        i2c_unlock_adapter(client->adapter);
3289
3290        if (ret == 0)
3291                client->slave_cb = NULL;
3292        else
3293                dev_err(&client->dev, "%s: adapter returned error %d\n", __func__, ret);
3294
3295        return ret;
3296}
3297EXPORT_SYMBOL_GPL(i2c_slave_unregister);
3298#endif
3299
3300MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
3301MODULE_DESCRIPTION("I2C-Bus main module");
3302MODULE_LICENSE("GPL");
3303