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