1 /*
2  * STMicroelectronics hts221 i2c driver
3  *
4  * Copyright 2016 STMicroelectronics Inc.
5  *
6  * Lorenzo Bianconi <lorenzo.bianconi@st.com>
7  *
8  * Licensed under the GPL-2.
9  */
10 
11 #include <linux/kernel.h>
12 #include <linux/module.h>
13 #include <linux/i2c.h>
14 #include <linux/slab.h>
15 #include "hts221.h"
16 
17 #define I2C_AUTO_INCREMENT	0x80
18 
19 static int hts221_i2c_read(struct device *dev, u8 addr, int len, u8 *data)
20 {
21 	struct i2c_msg msg[2];
22 	struct i2c_client *client = to_i2c_client(dev);
23 
24 	if (len > 1)
25 		addr |= I2C_AUTO_INCREMENT;
26 
27 	msg[0].addr = client->addr;
28 	msg[0].flags = client->flags;
29 	msg[0].len = 1;
30 	msg[0].buf = &addr;
31 
32 	msg[1].addr = client->addr;
33 	msg[1].flags = client->flags | I2C_M_RD;
34 	msg[1].len = len;
35 	msg[1].buf = data;
36 
37 	return i2c_transfer(client->adapter, msg, 2);
38 }
39 
40 static int hts221_i2c_write(struct device *dev, u8 addr, int len, u8 *data)
41 {
42 	u8 send[len + 1];
43 	struct i2c_msg msg;
44 	struct i2c_client *client = to_i2c_client(dev);
45 
46 	if (len > 1)
47 		addr |= I2C_AUTO_INCREMENT;
48 
49 	send[0] = addr;
50 	memcpy(&send[1], data, len * sizeof(u8));
51 
52 	msg.addr = client->addr;
53 	msg.flags = client->flags;
54 	msg.len = len + 1;
55 	msg.buf = send;
56 
57 	return i2c_transfer(client->adapter, &msg, 1);
58 }
59 
60 static const struct hts221_transfer_function hts221_transfer_fn = {
61 	.read = hts221_i2c_read,
62 	.write = hts221_i2c_write,
63 };
64 
65 static int hts221_i2c_probe(struct i2c_client *client,
66 			    const struct i2c_device_id *id)
67 {
68 	struct hts221_hw *hw;
69 	struct iio_dev *iio_dev;
70 
71 	iio_dev = devm_iio_device_alloc(&client->dev, sizeof(*hw));
72 	if (!iio_dev)
73 		return -ENOMEM;
74 
75 	i2c_set_clientdata(client, iio_dev);
76 
77 	hw = iio_priv(iio_dev);
78 	hw->name = client->name;
79 	hw->dev = &client->dev;
80 	hw->irq = client->irq;
81 	hw->tf = &hts221_transfer_fn;
82 
83 	return hts221_probe(iio_dev);
84 }
85 
86 static const struct of_device_id hts221_i2c_of_match[] = {
87 	{ .compatible = "st,hts221", },
88 	{},
89 };
90 MODULE_DEVICE_TABLE(of, hts221_i2c_of_match);
91 
92 static const struct i2c_device_id hts221_i2c_id_table[] = {
93 	{ HTS221_DEV_NAME },
94 	{},
95 };
96 MODULE_DEVICE_TABLE(i2c, hts221_i2c_id_table);
97 
98 static struct i2c_driver hts221_driver = {
99 	.driver = {
100 		.name = "hts221_i2c",
101 		.of_match_table = of_match_ptr(hts221_i2c_of_match),
102 	},
103 	.probe = hts221_i2c_probe,
104 	.id_table = hts221_i2c_id_table,
105 };
106 module_i2c_driver(hts221_driver);
107 
108 MODULE_AUTHOR("Lorenzo Bianconi <lorenzo.bianconi@st.com>");
109 MODULE_DESCRIPTION("STMicroelectronics hts221 i2c driver");
110 MODULE_LICENSE("GPL v2");
111