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