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