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