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