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