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