xref: /linux/drivers/crypto/atmel-i2c.c (revision 570f7e331f5febb30f1384817463c7e42b65ca7d)
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
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  */
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 
54 void atmel_i2c_init_read_config_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 = CONFIGURATION_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_config_cmd);
72 
73 int atmel_i2c_init_read_otp_cmd(struct atmel_i2c_cmd *cmd, u16 addr)
74 {
75 	if (addr >= OTP_ZONE_SIZE / 4)
76 		return -EINVAL;
77 
78 	cmd->word_addr = COMMAND;
79 	cmd->opcode = OPCODE_READ;
80 	/*
81 	 * Read the word from OTP zone that may contain e.g. serial
82 	 * numbers or similar if persistently pre-initialized and locked
83 	 */
84 	cmd->param1 = OTP_ZONE;
85 	cmd->param2 = cpu_to_le16(addr);
86 	cmd->count = READ_COUNT;
87 
88 	atmel_i2c_checksum(cmd);
89 
90 	cmd->msecs = MAX_EXEC_TIME_READ;
91 	cmd->rxsize = READ_RSP_SIZE;
92 
93 	return 0;
94 }
95 EXPORT_SYMBOL(atmel_i2c_init_read_otp_cmd);
96 
97 void atmel_i2c_init_random_cmd(struct atmel_i2c_cmd *cmd)
98 {
99 	cmd->word_addr = COMMAND;
100 	cmd->opcode = OPCODE_RANDOM;
101 	cmd->param1 = 0;
102 	cmd->param2 = 0;
103 	cmd->count = RANDOM_COUNT;
104 
105 	atmel_i2c_checksum(cmd);
106 
107 	cmd->msecs = MAX_EXEC_TIME_RANDOM;
108 	cmd->rxsize = RANDOM_RSP_SIZE;
109 }
110 EXPORT_SYMBOL(atmel_i2c_init_random_cmd);
111 
112 void atmel_i2c_init_genkey_cmd(struct atmel_i2c_cmd *cmd, u16 keyid)
113 {
114 	cmd->word_addr = COMMAND;
115 	cmd->count = GENKEY_COUNT;
116 	cmd->opcode = OPCODE_GENKEY;
117 	cmd->param1 = GENKEY_MODE_PRIVATE;
118 	/* a random private key will be generated and stored in slot keyID */
119 	cmd->param2 = cpu_to_le16(keyid);
120 
121 	atmel_i2c_checksum(cmd);
122 
123 	cmd->msecs = MAX_EXEC_TIME_GENKEY;
124 	cmd->rxsize = GENKEY_RSP_SIZE;
125 }
126 EXPORT_SYMBOL(atmel_i2c_init_genkey_cmd);
127 
128 int atmel_i2c_init_ecdh_cmd(struct atmel_i2c_cmd *cmd,
129 			    struct scatterlist *pubkey)
130 {
131 	size_t copied;
132 
133 	cmd->word_addr = COMMAND;
134 	cmd->count = ECDH_COUNT;
135 	cmd->opcode = OPCODE_ECDH;
136 	cmd->param1 = ECDH_PREFIX_MODE;
137 	/* private key slot */
138 	cmd->param2 = cpu_to_le16(DATA_SLOT_2);
139 
140 	/*
141 	 * The device only supports P-256. Its public key is encoded as
142 	 * two 32-byte coordinates.
143 	 */
144 	copied = sg_copy_to_buffer(pubkey,
145 				   sg_nents_for_len(pubkey,
146 						    ATMEL_ECC_PUBKEY_SIZE),
147 				   cmd->data, ATMEL_ECC_PUBKEY_SIZE);
148 	if (copied != ATMEL_ECC_PUBKEY_SIZE)
149 		return -EINVAL;
150 
151 	atmel_i2c_checksum(cmd);
152 
153 	cmd->msecs = MAX_EXEC_TIME_ECDH;
154 	cmd->rxsize = ECDH_RSP_SIZE;
155 
156 	return 0;
157 }
158 EXPORT_SYMBOL(atmel_i2c_init_ecdh_cmd);
159 
160 /*
161  * After wake and after execution of a command, there will be error, status, or
162  * result bytes in the device's output register that can be retrieved by the
163  * system. When the length of that group is four bytes, the codes returned are
164  * detailed in error_list.
165  */
166 static int atmel_i2c_status(struct device *dev, u8 *status)
167 {
168 	size_t err_list_len = ARRAY_SIZE(error_list);
169 	int i;
170 	u8 err_id = status[1];
171 
172 	if (*status != STATUS_SIZE)
173 		return 0;
174 
175 	if (err_id == STATUS_WAKE_SUCCESSFUL || err_id == STATUS_NOERR)
176 		return 0;
177 
178 	for (i = 0; i < err_list_len; i++)
179 		if (error_list[i].value == err_id)
180 			break;
181 
182 	/* if err_id is not in the error_list then ignore it */
183 	if (i != err_list_len) {
184 		dev_err(dev, "%02x: %s:\n", err_id, error_list[i].error_text);
185 		return err_id;
186 	}
187 
188 	return 0;
189 }
190 
191 static int atmel_i2c_wakeup(struct i2c_client *client)
192 {
193 	struct atmel_i2c_client_priv *i2c_priv = i2c_get_clientdata(client);
194 	u8 status[STATUS_RSP_SIZE];
195 	int ret;
196 
197 	/*
198 	 * The device ignores any levels or transitions on the SCL pin when the
199 	 * device is idle, asleep or during waking up. Don't check for error
200 	 * when waking up the device.
201 	 */
202 	i2c_transfer_buffer_flags(client, i2c_priv->wake_token,
203 				i2c_priv->wake_token_sz, I2C_M_IGNORE_NAK);
204 
205 	/*
206 	 * Wait to wake the device. Typical execution times for ecdh and genkey
207 	 * are around tens of milliseconds. Delta is chosen to 50 microseconds.
208 	 */
209 	usleep_range(TWHI_MIN, TWHI_MAX);
210 
211 	ret = i2c_master_recv(client, status, STATUS_SIZE);
212 	if (ret < 0)
213 		return ret;
214 
215 	return atmel_i2c_status(&client->dev, status);
216 }
217 
218 static int atmel_i2c_sleep(struct i2c_client *client)
219 {
220 	u8 sleep = SLEEP_TOKEN;
221 
222 	return i2c_master_send(client, &sleep, 1);
223 }
224 
225 /*
226  * atmel_i2c_send_receive() - send a command to the device and receive its
227  *                            response.
228  * @client: i2c client device
229  * @cmd   : structure used to communicate with the device
230  *
231  * After the device receives a Wake token, a watchdog counter starts within the
232  * device. After the watchdog timer expires, the device enters sleep mode
233  * regardless of whether some I/O transmission or command execution is in
234  * progress. If a command is attempted when insufficient time remains prior to
235  * watchdog timer execution, the device will return the watchdog timeout error
236  * code without attempting to execute the command. There is no way to reset the
237  * counter other than to put the device into sleep or idle mode and then
238  * wake it up again.
239  */
240 int atmel_i2c_send_receive(struct i2c_client *client, struct atmel_i2c_cmd *cmd)
241 {
242 	struct atmel_i2c_client_priv *i2c_priv = i2c_get_clientdata(client);
243 	int ret;
244 
245 	mutex_lock(&i2c_priv->lock);
246 
247 	ret = atmel_i2c_wakeup(client);
248 	if (ret)
249 		goto err;
250 
251 	/* send the command */
252 	ret = i2c_master_send(client, (u8 *)cmd, cmd->count + WORD_ADDR_SIZE);
253 	if (ret < 0)
254 		goto err;
255 
256 	/* delay the appropriate amount of time for command to execute */
257 	msleep(cmd->msecs);
258 
259 	/* receive the response */
260 	ret = i2c_master_recv(client, cmd->data, cmd->rxsize);
261 	if (ret < 0)
262 		goto err;
263 
264 	/* put the device into low-power mode */
265 	ret = atmel_i2c_sleep(client);
266 	if (ret < 0)
267 		goto err;
268 
269 	mutex_unlock(&i2c_priv->lock);
270 	return atmel_i2c_status(&client->dev, cmd->data);
271 err:
272 	mutex_unlock(&i2c_priv->lock);
273 	return ret;
274 }
275 EXPORT_SYMBOL(atmel_i2c_send_receive);
276 
277 static void atmel_i2c_work_handler(struct work_struct *work)
278 {
279 	struct atmel_i2c_work_data *work_data =
280 			container_of(work, struct atmel_i2c_work_data, work);
281 	struct atmel_i2c_cmd *cmd = &work_data->cmd;
282 	struct i2c_client *client = work_data->client;
283 	int status;
284 
285 	status = atmel_i2c_send_receive(client, cmd);
286 	work_data->cbk(work_data, work_data->areq, status);
287 }
288 
289 static struct workqueue_struct *atmel_wq;
290 
291 void atmel_i2c_enqueue(struct atmel_i2c_work_data *work_data,
292 		       void (*cbk)(struct atmel_i2c_work_data *work_data,
293 				   void *areq, int status),
294 		       void *areq)
295 {
296 	work_data->cbk = cbk;
297 	work_data->areq = areq;
298 
299 	INIT_WORK(&work_data->work, atmel_i2c_work_handler);
300 	queue_work(atmel_wq, &work_data->work);
301 }
302 EXPORT_SYMBOL(atmel_i2c_enqueue);
303 
304 void atmel_i2c_flush_queue(void)
305 {
306 	flush_workqueue(atmel_wq);
307 }
308 EXPORT_SYMBOL(atmel_i2c_flush_queue);
309 
310 static inline size_t atmel_i2c_wake_token_sz(u32 bus_clk_rate)
311 {
312 	u32 no_of_bits = DIV_ROUND_UP(TWLO_USEC * bus_clk_rate, USEC_PER_SEC);
313 
314 	/* return the size of the wake_token in bytes */
315 	return DIV_ROUND_UP(no_of_bits, 8);
316 }
317 
318 static int device_sanity_check(struct i2c_client *client)
319 {
320 	struct atmel_i2c_cmd *cmd;
321 	int ret;
322 
323 	cmd = kmalloc_obj(*cmd);
324 	if (!cmd)
325 		return -ENOMEM;
326 
327 	atmel_i2c_init_read_config_cmd(cmd);
328 
329 	ret = atmel_i2c_send_receive(client, cmd);
330 	if (ret)
331 		goto free_cmd;
332 
333 	/*
334 	 * It is vital that the Configuration, Data and OTP zones be locked
335 	 * prior to release into the field of the system containing the device.
336 	 * Failure to lock these zones may permit modification of any secret
337 	 * keys and may lead to other security problems.
338 	 */
339 	if (cmd->data[LOCK_CONFIG_IDX] || cmd->data[LOCK_VALUE_IDX]) {
340 		dev_err(&client->dev, "Configuration or Data and OTP zones are unlocked!\n");
341 		ret = -ENOTSUPP;
342 	}
343 
344 	/* fall through */
345 free_cmd:
346 	kfree(cmd);
347 	return ret;
348 }
349 
350 int atmel_i2c_probe(struct i2c_client *client)
351 {
352 	struct atmel_i2c_client_priv *i2c_priv;
353 	struct device *dev = &client->dev;
354 	int ret;
355 	u32 bus_clk_rate;
356 
357 	if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
358 		dev_err(dev, "I2C_FUNC_I2C not supported\n");
359 		return -ENODEV;
360 	}
361 
362 	bus_clk_rate = i2c_acpi_find_bus_speed(&client->adapter->dev);
363 	if (!bus_clk_rate) {
364 		ret = device_property_read_u32(&client->adapter->dev,
365 					       "clock-frequency", &bus_clk_rate);
366 		if (ret) {
367 			dev_err(dev, "failed to read clock-frequency property\n");
368 			return ret;
369 		}
370 	}
371 
372 	if (bus_clk_rate > I2C_MAX_FAST_MODE_PLUS_FREQ) {
373 		dev_err(dev, "%u exceeds maximum supported clock frequency (1MHz)\n",
374 			bus_clk_rate);
375 		return -EINVAL;
376 	}
377 
378 	i2c_priv = devm_kmalloc(dev, sizeof(*i2c_priv), GFP_KERNEL);
379 	if (!i2c_priv)
380 		return -ENOMEM;
381 
382 	i2c_priv->client = client;
383 	mutex_init(&i2c_priv->lock);
384 
385 	/*
386 	 * WAKE_TOKEN_MAX_SIZE was calculated for the maximum bus_clk_rate -
387 	 * 1MHz. The previous bus_clk_rate check ensures us that wake_token_sz
388 	 * will always be smaller than or equal to WAKE_TOKEN_MAX_SIZE.
389 	 */
390 	i2c_priv->wake_token_sz = atmel_i2c_wake_token_sz(bus_clk_rate);
391 
392 	memset(i2c_priv->wake_token, 0, sizeof(i2c_priv->wake_token));
393 
394 	atomic_set(&i2c_priv->tfm_count, 0);
395 
396 	i2c_set_clientdata(client, i2c_priv);
397 
398 	return device_sanity_check(client);
399 }
400 EXPORT_SYMBOL(atmel_i2c_probe);
401 
402 static int __init atmel_i2c_init(void)
403 {
404 	atmel_wq = alloc_workqueue("atmel_wq", WQ_PERCPU, 0);
405 	return atmel_wq ? 0 : -ENOMEM;
406 }
407 
408 static void __exit atmel_i2c_exit(void)
409 {
410 	destroy_workqueue(atmel_wq);
411 }
412 
413 module_init(atmel_i2c_init);
414 module_exit(atmel_i2c_exit);
415 
416 MODULE_AUTHOR("Tudor Ambarus");
417 MODULE_DESCRIPTION("Microchip / Atmel ECC (I2C) driver");
418 MODULE_LICENSE("GPL v2");
419