1 /*
2  * Copyright 2021 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  *
22  */
23 
24 #include "amdgpu_eeprom.h"
25 #include "amdgpu.h"
26 
27 #define EEPROM_OFFSET_LENGTH 2
28 
29 int amdgpu_eeprom_xfer(struct i2c_adapter *i2c_adap,
30 		       u16 slave_addr, u16 eeprom_addr,
31 		       u8 *eeprom_buf, u16 bytes, bool read)
32 {
33 	u8 eeprom_offset_buf[2];
34 	u16 bytes_transferred;
35 	struct i2c_msg msgs[] = {
36 		{
37 			.addr = slave_addr,
38 			.flags = 0,
39 			.len = EEPROM_OFFSET_LENGTH,
40 			.buf = eeprom_offset_buf,
41 		},
42 		{
43 			.addr = slave_addr,
44 			.flags = read ? I2C_M_RD : 0,
45 			.len = bytes,
46 			.buf = eeprom_buf,
47 		},
48 	};
49 	int r;
50 
51 	msgs[0].buf[0] = ((eeprom_addr >> 8) & 0xff);
52 	msgs[0].buf[1] = (eeprom_addr & 0xff);
53 
54 	while (msgs[1].len) {
55 		r = i2c_transfer(i2c_adap, msgs, ARRAY_SIZE(msgs));
56 		if (r <= 0)
57 			return r;
58 
59 		/* Only for write data */
60 		if (!msgs[1].flags)
61 			/*
62 			 * According to EEPROM spec there is a MAX of 10 ms required for
63 			 * EEPROM to flush internal RX buffer after STOP was issued at the
64 			 * end of write transaction. During this time the EEPROM will not be
65 			 * responsive to any more commands - so wait a bit more.
66 			 *
67 			 * TODO Improve to wait for first ACK for slave address after
68 			 * internal write cycle done.
69 			 */
70 			msleep(10);
71 
72 
73 		bytes_transferred = r - EEPROM_OFFSET_LENGTH;
74 		eeprom_addr += bytes_transferred;
75 		msgs[0].buf[0] = ((eeprom_addr >> 8) & 0xff);
76 		msgs[0].buf[1] = (eeprom_addr & 0xff);
77 		msgs[1].buf += bytes_transferred;
78 		msgs[1].len -= bytes_transferred;
79 	}
80 
81 	return 0;
82 }
83