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