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