GNU Linux-libre 4.14.251-gnu1
[releases.git] / drivers / staging / media / atomisp / i2c / imx / otp_brcc064_e2prom.c
1 /*
2  * Copyright (c) 2013 Intel Corporation. All Rights Reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License version
6  * 2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program; if not, write to the Free Software
15  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
16  * 02110-1301, USA.
17  *
18  */
19 #include <linux/bitops.h>
20 #include <linux/device.h>
21 #include <linux/errno.h>
22 #include <linux/fs.h>
23 #include <linux/init.h>
24 #include <linux/i2c.h>
25 #include <linux/io.h>
26 #include <linux/kernel.h>
27 #include <linux/mm.h>
28 #include <linux/slab.h>
29 #include <linux/string.h>
30 #include <linux/types.h>
31 #include <media/v4l2-device.h>
32 #include "common.h"
33
34 /*
35  * Read EEPROM data from brcc064 and store
36  * it into a kmalloced buffer. On error return NULL.
37  * @size: set to the size of the returned EEPROM data.
38  */
39 void *brcc064_otp_read(struct v4l2_subdev *sd, u8 dev_addr,
40         u32 start_addr, u32 size)
41 {
42         struct i2c_client *client = v4l2_get_subdevdata(sd);
43         unsigned int e2prom_i2c_addr = dev_addr >> 1;
44         static const unsigned int max_read_size = 30;
45         int addr;
46         u32 s_addr = start_addr & E2PROM_ADDR_MASK;
47         unsigned char *buffer;
48
49         buffer = devm_kzalloc(&client->dev, size, GFP_KERNEL);
50         if (!buffer)
51                 return NULL;
52
53         for (addr = s_addr; addr < size; addr += max_read_size) {
54                 struct i2c_msg msg[2];
55                 unsigned int i2c_addr = e2prom_i2c_addr;
56                 u16 addr_buf;
57                 int r;
58
59                 msg[0].flags = 0;
60                 msg[0].addr = i2c_addr;
61                 addr_buf = cpu_to_be16(addr & 0xFFFF);
62                 msg[0].len = 2;
63                 msg[0].buf = (u8 *)&addr_buf;
64
65                 msg[1].addr = i2c_addr;
66                 msg[1].flags = I2C_M_RD;
67                 msg[1].len = min(max_read_size, size - addr);
68                 msg[1].buf = &buffer[addr];
69
70                 r = i2c_transfer(client->adapter, msg, ARRAY_SIZE(msg));
71                 if (r != ARRAY_SIZE(msg)) {
72                         dev_err(&client->dev, "read failed at 0x%03x\n", addr);
73                         return NULL;
74                 }
75         }
76         return buffer;
77
78 }
79
80