OSDN Git Service

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