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