1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Microchip / Atmel ECC (I2C) driver.
4  *
5  * Copyright (c) 2017, Microchip Technology Inc.
6  * Author: Tudor Ambarus <tudor.ambarus@microchip.com>
7  */
8 
9 #include <linux/bitrev.h>
10 #include <linux/crc16.h>
11 #include <linux/delay.h>
12 #include <linux/device.h>
13 #include <linux/err.h>
14 #include <linux/errno.h>
15 #include <linux/i2c.h>
16 #include <linux/init.h>
17 #include <linux/kernel.h>
18 #include <linux/module.h>
19 #include <linux/scatterlist.h>
20 #include <linux/slab.h>
21 #include <linux/workqueue.h>
22 #include "atmel-i2c.h"
23 
24 static const struct {
25 	u8 value;
26 	const char *error_text;
27 } error_list[] = {
28 	{ 0x01, "CheckMac or Verify miscompare" },
29 	{ 0x03, "Parse Error" },
30 	{ 0x05, "ECC Fault" },
31 	{ 0x0F, "Execution Error" },
32 	{ 0xEE, "Watchdog about to expire" },
33 	{ 0xFF, "CRC or other communication error" },
34 };
35 
36 /**
37  * atmel_i2c_checksum() - Generate 16-bit CRC as required by ATMEL ECC.
38  * CRC16 verification of the count, opcode, param1, param2 and data bytes.
39  * The checksum is saved in little-endian format in the least significant
40  * two bytes of the command. CRC polynomial is 0x8005 and the initial register
41  * value should be zero.
42  *
43  * @cmd : structure used for communicating with the device.
44  */
atmel_i2c_checksum(struct atmel_i2c_cmd * cmd)45 static void atmel_i2c_checksum(struct atmel_i2c_cmd *cmd)
46 {
47 	u8 *data = &cmd->count;
48 	size_t len = cmd->count - CRC_SIZE;
49 	__le16 *__crc16 = (__le16 *)(data + len);
50 
51 	*__crc16 = cpu_to_le16(bitrev16(crc16(0, data, len)));
52 }
53 
atmel_i2c_init_read_cmd(struct atmel_i2c_cmd * cmd)54 void atmel_i2c_init_read_cmd(struct atmel_i2c_cmd *cmd)
55 {
56 	cmd->word_addr = COMMAND;
57 	cmd->opcode = OPCODE_READ;
58 	/*
59 	 * Read the word from Configuration zone that contains the lock bytes
60 	 * (UserExtra, Selector, LockValue, LockConfig).
61 	 */
62 	cmd->param1 = CONFIG_ZONE;
63 	cmd->param2 = cpu_to_le16(DEVICE_LOCK_ADDR);
64 	cmd->count = READ_COUNT;
65 
66 	atmel_i2c_checksum(cmd);
67 
68 	cmd->msecs = MAX_EXEC_TIME_READ;
69 	cmd->rxsize = READ_RSP_SIZE;
70 }
71 EXPORT_SYMBOL(atmel_i2c_init_read_cmd);
72 
atmel_i2c_init_random_cmd(struct atmel_i2c_cmd * cmd)73 void atmel_i2c_init_random_cmd(struct atmel_i2c_cmd *cmd)
74 {
75 	cmd->word_addr = COMMAND;
76 	cmd->opcode = OPCODE_RANDOM;
77 	cmd->param1 = 0;
78 	cmd->param2 = 0;
79 	cmd->count = RANDOM_COUNT;
80 
81 	atmel_i2c_checksum(cmd);
82 
83 	cmd->msecs = MAX_EXEC_TIME_RANDOM;
84 	cmd->rxsize = RANDOM_RSP_SIZE;
85 }
86 EXPORT_SYMBOL(atmel_i2c_init_random_cmd);
87 
atmel_i2c_init_genkey_cmd(struct atmel_i2c_cmd * cmd,u16 keyid)88 void atmel_i2c_init_genkey_cmd(struct atmel_i2c_cmd *cmd, u16 keyid)
89 {
90 	cmd->word_addr = COMMAND;
91 	cmd->count = GENKEY_COUNT;
92 	cmd->opcode = OPCODE_GENKEY;
93 	cmd->param1 = GENKEY_MODE_PRIVATE;
94 	/* a random private key will be generated and stored in slot keyID */
95 	cmd->param2 = cpu_to_le16(keyid);
96 
97 	atmel_i2c_checksum(cmd);
98 
99 	cmd->msecs = MAX_EXEC_TIME_GENKEY;
100 	cmd->rxsize = GENKEY_RSP_SIZE;
101 }
102 EXPORT_SYMBOL(atmel_i2c_init_genkey_cmd);
103 
atmel_i2c_init_ecdh_cmd(struct atmel_i2c_cmd * cmd,struct scatterlist * pubkey)104 int atmel_i2c_init_ecdh_cmd(struct atmel_i2c_cmd *cmd,
105 			    struct scatterlist *pubkey)
106 {
107 	size_t copied;
108 
109 	cmd->word_addr = COMMAND;
110 	cmd->count = ECDH_COUNT;
111 	cmd->opcode = OPCODE_ECDH;
112 	cmd->param1 = ECDH_PREFIX_MODE;
113 	/* private key slot */
114 	cmd->param2 = cpu_to_le16(DATA_SLOT_2);
115 
116 	/*
117 	 * The device only supports NIST P256 ECC keys. The public key size will
118 	 * always be the same. Use a macro for the key size to avoid unnecessary
119 	 * computations.
120 	 */
121 	copied = sg_copy_to_buffer(pubkey,
122 				   sg_nents_for_len(pubkey,
123 						    ATMEL_ECC_PUBKEY_SIZE),
124 				   cmd->data, ATMEL_ECC_PUBKEY_SIZE);
125 	if (copied != ATMEL_ECC_PUBKEY_SIZE)
126 		return -EINVAL;
127 
128 	atmel_i2c_checksum(cmd);
129 
130 	cmd->msecs = MAX_EXEC_TIME_ECDH;
131 	cmd->rxsize = ECDH_RSP_SIZE;
132 
133 	return 0;
134 }
135 EXPORT_SYMBOL(atmel_i2c_init_ecdh_cmd);
136 
137 /*
138  * After wake and after execution of a command, there will be error, status, or
139  * result bytes in the device's output register that can be retrieved by the
140  * system. When the length of that group is four bytes, the codes returned are
141  * detailed in error_list.
142  */
atmel_i2c_status(struct device * dev,u8 * status)143 static int atmel_i2c_status(struct device *dev, u8 *status)
144 {
145 	size_t err_list_len = ARRAY_SIZE(error_list);
146 	int i;
147 	u8 err_id = status[1];
148 
149 	if (*status != STATUS_SIZE)
150 		return 0;
151 
152 	if (err_id == STATUS_WAKE_SUCCESSFUL || err_id == STATUS_NOERR)
153 		return 0;
154 
155 	for (i = 0; i < err_list_len; i++)
156 		if (error_list[i].value == err_id)
157 			break;
158 
159 	/* if err_id is not in the error_list then ignore it */
160 	if (i != err_list_len) {
161 		dev_err(dev, "%02x: %s:\n", err_id, error_list[i].error_text);
162 		return err_id;
163 	}
164 
165 	return 0;
166 }
167 
atmel_i2c_wakeup(struct i2c_client * client)168 static int atmel_i2c_wakeup(struct i2c_client *client)
169 {
170 	struct atmel_i2c_client_priv *i2c_priv = i2c_get_clientdata(client);
171 	u8 status[STATUS_RSP_SIZE];
172 	int ret;
173 
174 	/*
175 	 * The device ignores any levels or transitions on the SCL pin when the
176 	 * device is idle, asleep or during waking up. Don't check for error
177 	 * when waking up the device.
178 	 */
179 	i2c_transfer_buffer_flags(client, i2c_priv->wake_token,
180 				i2c_priv->wake_token_sz, I2C_M_IGNORE_NAK);
181 
182 	/*
183 	 * Wait to wake the device. Typical execution times for ecdh and genkey
184 	 * are around tens of milliseconds. Delta is chosen to 50 microseconds.
185 	 */
186 	usleep_range(TWHI_MIN, TWHI_MAX);
187 
188 	ret = i2c_master_recv(client, status, STATUS_SIZE);
189 	if (ret < 0)
190 		return ret;
191 
192 	return atmel_i2c_status(&client->dev, status);
193 }
194 
atmel_i2c_sleep(struct i2c_client * client)195 static int atmel_i2c_sleep(struct i2c_client *client)
196 {
197 	u8 sleep = SLEEP_TOKEN;
198 
199 	return i2c_master_send(client, &sleep, 1);
200 }
201 
202 /*
203  * atmel_i2c_send_receive() - send a command to the device and receive its
204  *                            response.
205  * @client: i2c client device
206  * @cmd   : structure used to communicate with the device
207  *
208  * After the device receives a Wake token, a watchdog counter starts within the
209  * device. After the watchdog timer expires, the device enters sleep mode
210  * regardless of whether some I/O transmission or command execution is in
211  * progress. If a command is attempted when insufficient time remains prior to
212  * watchdog timer execution, the device will return the watchdog timeout error
213  * code without attempting to execute the command. There is no way to reset the
214  * counter other than to put the device into sleep or idle mode and then
215  * wake it up again.
216  */
atmel_i2c_send_receive(struct i2c_client * client,struct atmel_i2c_cmd * cmd)217 int atmel_i2c_send_receive(struct i2c_client *client, struct atmel_i2c_cmd *cmd)
218 {
219 	struct atmel_i2c_client_priv *i2c_priv = i2c_get_clientdata(client);
220 	int ret;
221 
222 	mutex_lock(&i2c_priv->lock);
223 
224 	ret = atmel_i2c_wakeup(client);
225 	if (ret)
226 		goto err;
227 
228 	/* send the command */
229 	ret = i2c_master_send(client, (u8 *)cmd, cmd->count + WORD_ADDR_SIZE);
230 	if (ret < 0)
231 		goto err;
232 
233 	/* delay the appropriate amount of time for command to execute */
234 	msleep(cmd->msecs);
235 
236 	/* receive the response */
237 	ret = i2c_master_recv(client, cmd->data, cmd->rxsize);
238 	if (ret < 0)
239 		goto err;
240 
241 	/* put the device into low-power mode */
242 	ret = atmel_i2c_sleep(client);
243 	if (ret < 0)
244 		goto err;
245 
246 	mutex_unlock(&i2c_priv->lock);
247 	return atmel_i2c_status(&client->dev, cmd->data);
248 err:
249 	mutex_unlock(&i2c_priv->lock);
250 	return ret;
251 }
252 EXPORT_SYMBOL(atmel_i2c_send_receive);
253 
atmel_i2c_work_handler(struct work_struct * work)254 static void atmel_i2c_work_handler(struct work_struct *work)
255 {
256 	struct atmel_i2c_work_data *work_data =
257 			container_of(work, struct atmel_i2c_work_data, work);
258 	struct atmel_i2c_cmd *cmd = &work_data->cmd;
259 	struct i2c_client *client = work_data->client;
260 	int status;
261 
262 	status = atmel_i2c_send_receive(client, cmd);
263 	work_data->cbk(work_data, work_data->areq, status);
264 }
265 
atmel_i2c_enqueue(struct atmel_i2c_work_data * work_data,void (* cbk)(struct atmel_i2c_work_data * work_data,void * areq,int status),void * areq)266 void atmel_i2c_enqueue(struct atmel_i2c_work_data *work_data,
267 		       void (*cbk)(struct atmel_i2c_work_data *work_data,
268 				   void *areq, int status),
269 		       void *areq)
270 {
271 	work_data->cbk = (void *)cbk;
272 	work_data->areq = areq;
273 
274 	INIT_WORK(&work_data->work, atmel_i2c_work_handler);
275 	schedule_work(&work_data->work);
276 }
277 EXPORT_SYMBOL(atmel_i2c_enqueue);
278 
atmel_i2c_wake_token_sz(u32 bus_clk_rate)279 static inline size_t atmel_i2c_wake_token_sz(u32 bus_clk_rate)
280 {
281 	u32 no_of_bits = DIV_ROUND_UP(TWLO_USEC * bus_clk_rate, USEC_PER_SEC);
282 
283 	/* return the size of the wake_token in bytes */
284 	return DIV_ROUND_UP(no_of_bits, 8);
285 }
286 
device_sanity_check(struct i2c_client * client)287 static int device_sanity_check(struct i2c_client *client)
288 {
289 	struct atmel_i2c_cmd *cmd;
290 	int ret;
291 
292 	cmd = kmalloc(sizeof(*cmd), GFP_KERNEL);
293 	if (!cmd)
294 		return -ENOMEM;
295 
296 	atmel_i2c_init_read_cmd(cmd);
297 
298 	ret = atmel_i2c_send_receive(client, cmd);
299 	if (ret)
300 		goto free_cmd;
301 
302 	/*
303 	 * It is vital that the Configuration, Data and OTP zones be locked
304 	 * prior to release into the field of the system containing the device.
305 	 * Failure to lock these zones may permit modification of any secret
306 	 * keys and may lead to other security problems.
307 	 */
308 	if (cmd->data[LOCK_CONFIG_IDX] || cmd->data[LOCK_VALUE_IDX]) {
309 		dev_err(&client->dev, "Configuration or Data and OTP zones are unlocked!\n");
310 		ret = -ENOTSUPP;
311 	}
312 
313 	/* fall through */
314 free_cmd:
315 	kfree(cmd);
316 	return ret;
317 }
318 
atmel_i2c_probe(struct i2c_client * client,const struct i2c_device_id * id)319 int atmel_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id)
320 {
321 	struct atmel_i2c_client_priv *i2c_priv;
322 	struct device *dev = &client->dev;
323 	int ret;
324 	u32 bus_clk_rate;
325 
326 	if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
327 		dev_err(dev, "I2C_FUNC_I2C not supported\n");
328 		return -ENODEV;
329 	}
330 
331 	bus_clk_rate = i2c_acpi_find_bus_speed(&client->adapter->dev);
332 	if (!bus_clk_rate) {
333 		ret = device_property_read_u32(&client->adapter->dev,
334 					       "clock-frequency", &bus_clk_rate);
335 		if (ret) {
336 			dev_err(dev, "failed to read clock-frequency property\n");
337 			return ret;
338 		}
339 	}
340 
341 	if (bus_clk_rate > 1000000L) {
342 		dev_err(dev, "%u exceeds maximum supported clock frequency (1MHz)\n",
343 			bus_clk_rate);
344 		return -EINVAL;
345 	}
346 
347 	i2c_priv = devm_kmalloc(dev, sizeof(*i2c_priv), GFP_KERNEL);
348 	if (!i2c_priv)
349 		return -ENOMEM;
350 
351 	i2c_priv->client = client;
352 	mutex_init(&i2c_priv->lock);
353 
354 	/*
355 	 * WAKE_TOKEN_MAX_SIZE was calculated for the maximum bus_clk_rate -
356 	 * 1MHz. The previous bus_clk_rate check ensures us that wake_token_sz
357 	 * will always be smaller than or equal to WAKE_TOKEN_MAX_SIZE.
358 	 */
359 	i2c_priv->wake_token_sz = atmel_i2c_wake_token_sz(bus_clk_rate);
360 
361 	memset(i2c_priv->wake_token, 0, sizeof(i2c_priv->wake_token));
362 
363 	atomic_set(&i2c_priv->tfm_count, 0);
364 
365 	i2c_set_clientdata(client, i2c_priv);
366 
367 	ret = device_sanity_check(client);
368 	if (ret)
369 		return ret;
370 
371 	return 0;
372 }
373 EXPORT_SYMBOL(atmel_i2c_probe);
374 
375 MODULE_AUTHOR("Tudor Ambarus <tudor.ambarus@microchip.com>");
376 MODULE_DESCRIPTION("Microchip / Atmel ECC (I2C) driver");
377 MODULE_LICENSE("GPL v2");
378