Linux Audio

Check our new training course

Loading...
v5.9
  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/delay.h>
 10#include <linux/device.h>
 11#include <linux/err.h>
 12#include <linux/errno.h>
 13#include <linux/i2c.h>
 14#include <linux/init.h>
 15#include <linux/kernel.h>
 16#include <linux/module.h>
 17#include <linux/of_device.h>
 18#include <linux/scatterlist.h>
 19#include <linux/slab.h>
 20#include <linux/workqueue.h>
 21#include <crypto/internal/kpp.h>
 22#include <crypto/ecdh.h>
 23#include <crypto/kpp.h>
 24#include "atmel-i2c.h"
 
 
 
 
 
 
 25
 26static struct atmel_ecc_driver_data driver_data;
 27
 28/**
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 29 * atmel_ecdh_ctx - transformation context
 30 * @client     : pointer to i2c client device
 31 * @fallback   : used for unsupported curves or when user wants to use its own
 32 *               private key.
 33 * @public_key : generated when calling set_secret(). It's the responsibility
 34 *               of the user to not call set_secret() while
 35 *               generate_public_key() or compute_shared_secret() are in flight.
 36 * @curve_id   : elliptic curve id
 37 * @n_sz       : size in bytes of the n prime
 38 * @do_fallback: true when the device doesn't support the curve or when the user
 39 *               wants to use its own private key.
 40 */
 41struct atmel_ecdh_ctx {
 42	struct i2c_client *client;
 43	struct crypto_kpp *fallback;
 44	const u8 *public_key;
 45	unsigned int curve_id;
 46	size_t n_sz;
 47	bool do_fallback;
 48};
 49
 50static void atmel_ecdh_done(struct atmel_i2c_work_data *work_data, void *areq,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 51			    int status)
 52{
 53	struct kpp_request *req = areq;
 54	struct atmel_ecdh_ctx *ctx = work_data->ctx;
 55	struct atmel_i2c_cmd *cmd = &work_data->cmd;
 56	size_t copied, n_sz;
 
 57
 58	if (status)
 59		goto free_work_data;
 60
 61	/* might want less than we've got */
 62	n_sz = min_t(size_t, ctx->n_sz, req->dst_len);
 63
 64	/* copy the shared secret */
 65	copied = sg_copy_from_buffer(req->dst, sg_nents_for_len(req->dst, n_sz),
 66				     &cmd->data[RSP_DATA_IDX], n_sz);
 67	if (copied != n_sz)
 68		status = -EINVAL;
 69
 70	/* fall through */
 71free_work_data:
 72	kfree_sensitive(work_data);
 73	kpp_request_complete(req, status);
 74}
 75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 76static unsigned int atmel_ecdh_supported_curve(unsigned int curve_id)
 77{
 78	if (curve_id == ECC_CURVE_NIST_P256)
 79		return ATMEL_ECC_NIST_P256_N_SIZE;
 80
 81	return 0;
 82}
 83
 84/*
 85 * A random private key is generated and stored in the device. The device
 86 * returns the pair public key.
 87 */
 88static int atmel_ecdh_set_secret(struct crypto_kpp *tfm, const void *buf,
 89				 unsigned int len)
 90{
 91	struct atmel_ecdh_ctx *ctx = kpp_tfm_ctx(tfm);
 92	struct atmel_i2c_cmd *cmd;
 93	void *public_key;
 94	struct ecdh params;
 95	int ret = -ENOMEM;
 96
 97	/* free the old public key, if any */
 98	kfree(ctx->public_key);
 99	/* make sure you don't free the old public key twice */
100	ctx->public_key = NULL;
101
102	if (crypto_ecdh_decode_key(buf, len, &params) < 0) {
103		dev_err(&ctx->client->dev, "crypto_ecdh_decode_key failed\n");
104		return -EINVAL;
105	}
106
107	ctx->n_sz = atmel_ecdh_supported_curve(params.curve_id);
108	if (!ctx->n_sz || params.key_size) {
109		/* fallback to ecdh software implementation */
110		ctx->do_fallback = true;
111		return crypto_kpp_set_secret(ctx->fallback, buf, len);
112	}
113
114	cmd = kmalloc(sizeof(*cmd), GFP_KERNEL);
115	if (!cmd)
116		return -ENOMEM;
117
118	/*
119	 * The device only supports NIST P256 ECC keys. The public key size will
120	 * always be the same. Use a macro for the key size to avoid unnecessary
121	 * computations.
122	 */
123	public_key = kmalloc(ATMEL_ECC_PUBKEY_SIZE, GFP_KERNEL);
124	if (!public_key)
125		goto free_cmd;
126
127	ctx->do_fallback = false;
128	ctx->curve_id = params.curve_id;
129
130	atmel_i2c_init_genkey_cmd(cmd, DATA_SLOT_2);
131
132	ret = atmel_i2c_send_receive(ctx->client, cmd);
133	if (ret)
134		goto free_public_key;
135
136	/* save the public key */
137	memcpy(public_key, &cmd->data[RSP_DATA_IDX], ATMEL_ECC_PUBKEY_SIZE);
138	ctx->public_key = public_key;
139
140	kfree(cmd);
141	return 0;
142
143free_public_key:
144	kfree(public_key);
145free_cmd:
146	kfree(cmd);
147	return ret;
148}
149
150static int atmel_ecdh_generate_public_key(struct kpp_request *req)
151{
152	struct crypto_kpp *tfm = crypto_kpp_reqtfm(req);
153	struct atmel_ecdh_ctx *ctx = kpp_tfm_ctx(tfm);
154	size_t copied, nbytes;
155	int ret = 0;
156
157	if (ctx->do_fallback) {
158		kpp_request_set_tfm(req, ctx->fallback);
159		return crypto_kpp_generate_public_key(req);
160	}
161
162	if (!ctx->public_key)
163		return -EINVAL;
164
165	/* might want less than we've got */
166	nbytes = min_t(size_t, ATMEL_ECC_PUBKEY_SIZE, req->dst_len);
167
168	/* public key was saved at private key generation */
169	copied = sg_copy_from_buffer(req->dst,
170				     sg_nents_for_len(req->dst, nbytes),
171				     ctx->public_key, nbytes);
172	if (copied != nbytes)
173		ret = -EINVAL;
174
175	return ret;
176}
177
178static int atmel_ecdh_compute_shared_secret(struct kpp_request *req)
179{
180	struct crypto_kpp *tfm = crypto_kpp_reqtfm(req);
181	struct atmel_ecdh_ctx *ctx = kpp_tfm_ctx(tfm);
182	struct atmel_i2c_work_data *work_data;
183	gfp_t gfp;
184	int ret;
185
186	if (ctx->do_fallback) {
187		kpp_request_set_tfm(req, ctx->fallback);
188		return crypto_kpp_compute_shared_secret(req);
189	}
190
191	/* must have exactly two points to be on the curve */
192	if (req->src_len != ATMEL_ECC_PUBKEY_SIZE)
193		return -EINVAL;
194
195	gfp = (req->base.flags & CRYPTO_TFM_REQ_MAY_SLEEP) ? GFP_KERNEL :
196							     GFP_ATOMIC;
197
198	work_data = kmalloc(sizeof(*work_data), gfp);
199	if (!work_data)
200		return -ENOMEM;
201
202	work_data->ctx = ctx;
203	work_data->client = ctx->client;
204
205	ret = atmel_i2c_init_ecdh_cmd(&work_data->cmd, req->src);
206	if (ret)
207		goto free_work_data;
208
209	atmel_i2c_enqueue(work_data, atmel_ecdh_done, req);
210
211	return -EINPROGRESS;
212
213free_work_data:
214	kfree(work_data);
215	return ret;
216}
217
218static struct i2c_client *atmel_ecc_i2c_client_alloc(void)
219{
220	struct atmel_i2c_client_priv *i2c_priv, *min_i2c_priv = NULL;
221	struct i2c_client *client = ERR_PTR(-ENODEV);
222	int min_tfm_cnt = INT_MAX;
223	int tfm_cnt;
224
225	spin_lock(&driver_data.i2c_list_lock);
226
227	if (list_empty(&driver_data.i2c_client_list)) {
228		spin_unlock(&driver_data.i2c_list_lock);
229		return ERR_PTR(-ENODEV);
230	}
231
232	list_for_each_entry(i2c_priv, &driver_data.i2c_client_list,
233			    i2c_client_list_node) {
234		tfm_cnt = atomic_read(&i2c_priv->tfm_count);
235		if (tfm_cnt < min_tfm_cnt) {
236			min_tfm_cnt = tfm_cnt;
237			min_i2c_priv = i2c_priv;
238		}
239		if (!min_tfm_cnt)
240			break;
241	}
242
243	if (min_i2c_priv) {
244		atomic_inc(&min_i2c_priv->tfm_count);
245		client = min_i2c_priv->client;
246	}
247
248	spin_unlock(&driver_data.i2c_list_lock);
249
250	return client;
251}
252
253static void atmel_ecc_i2c_client_free(struct i2c_client *client)
254{
255	struct atmel_i2c_client_priv *i2c_priv = i2c_get_clientdata(client);
256
257	atomic_dec(&i2c_priv->tfm_count);
258}
259
260static int atmel_ecdh_init_tfm(struct crypto_kpp *tfm)
261{
262	const char *alg = kpp_alg_name(tfm);
263	struct crypto_kpp *fallback;
264	struct atmel_ecdh_ctx *ctx = kpp_tfm_ctx(tfm);
265
266	ctx->client = atmel_ecc_i2c_client_alloc();
267	if (IS_ERR(ctx->client)) {
268		pr_err("tfm - i2c_client binding failed\n");
269		return PTR_ERR(ctx->client);
270	}
271
272	fallback = crypto_alloc_kpp(alg, 0, CRYPTO_ALG_NEED_FALLBACK);
273	if (IS_ERR(fallback)) {
274		dev_err(&ctx->client->dev, "Failed to allocate transformation for '%s': %ld\n",
275			alg, PTR_ERR(fallback));
276		return PTR_ERR(fallback);
277	}
278
279	crypto_kpp_set_flags(fallback, crypto_kpp_get_flags(tfm));
 
 
 
 
280	ctx->fallback = fallback;
281
282	return 0;
283}
284
285static void atmel_ecdh_exit_tfm(struct crypto_kpp *tfm)
286{
287	struct atmel_ecdh_ctx *ctx = kpp_tfm_ctx(tfm);
288
289	kfree(ctx->public_key);
290	crypto_free_kpp(ctx->fallback);
291	atmel_ecc_i2c_client_free(ctx->client);
292}
293
294static unsigned int atmel_ecdh_max_size(struct crypto_kpp *tfm)
295{
296	struct atmel_ecdh_ctx *ctx = kpp_tfm_ctx(tfm);
297
298	if (ctx->fallback)
299		return crypto_kpp_maxsize(ctx->fallback);
300
301	/*
302	 * The device only supports NIST P256 ECC keys. The public key size will
303	 * always be the same. Use a macro for the key size to avoid unnecessary
304	 * computations.
305	 */
306	return ATMEL_ECC_PUBKEY_SIZE;
307}
308
309static struct kpp_alg atmel_ecdh = {
310	.set_secret = atmel_ecdh_set_secret,
311	.generate_public_key = atmel_ecdh_generate_public_key,
312	.compute_shared_secret = atmel_ecdh_compute_shared_secret,
313	.init = atmel_ecdh_init_tfm,
314	.exit = atmel_ecdh_exit_tfm,
315	.max_size = atmel_ecdh_max_size,
316	.base = {
317		.cra_flags = CRYPTO_ALG_NEED_FALLBACK,
318		.cra_name = "ecdh",
319		.cra_driver_name = "atmel-ecdh",
320		.cra_priority = ATMEL_ECC_PRIORITY,
321		.cra_module = THIS_MODULE,
322		.cra_ctxsize = sizeof(struct atmel_ecdh_ctx),
323	},
324};
325
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326static int atmel_ecc_probe(struct i2c_client *client,
327			   const struct i2c_device_id *id)
328{
329	struct atmel_i2c_client_priv *i2c_priv;
 
330	int ret;
 
331
332	ret = atmel_i2c_probe(client, id);
333	if (ret)
 
 
 
 
 
 
 
334		return ret;
 
 
 
 
 
 
 
 
 
 
 
335
336	i2c_priv = i2c_get_clientdata(client);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337
338	spin_lock(&driver_data.i2c_list_lock);
339	list_add_tail(&i2c_priv->i2c_client_list_node,
340		      &driver_data.i2c_client_list);
341	spin_unlock(&driver_data.i2c_list_lock);
342
343	ret = crypto_register_kpp(&atmel_ecdh);
344	if (ret) {
345		spin_lock(&driver_data.i2c_list_lock);
346		list_del(&i2c_priv->i2c_client_list_node);
347		spin_unlock(&driver_data.i2c_list_lock);
348
349		dev_err(&client->dev, "%s alg registration failed\n",
350			atmel_ecdh.base.cra_driver_name);
351	} else {
352		dev_info(&client->dev, "atmel ecc algorithms registered in /proc/crypto\n");
353	}
354
355	return ret;
356}
357
358static int atmel_ecc_remove(struct i2c_client *client)
359{
360	struct atmel_i2c_client_priv *i2c_priv = i2c_get_clientdata(client);
361
362	/* Return EBUSY if i2c client already allocated. */
363	if (atomic_read(&i2c_priv->tfm_count)) {
364		dev_err(&client->dev, "Device is busy\n");
365		return -EBUSY;
366	}
367
368	crypto_unregister_kpp(&atmel_ecdh);
369
370	spin_lock(&driver_data.i2c_list_lock);
371	list_del(&i2c_priv->i2c_client_list_node);
372	spin_unlock(&driver_data.i2c_list_lock);
373
374	return 0;
375}
376
377#ifdef CONFIG_OF
378static const struct of_device_id atmel_ecc_dt_ids[] = {
379	{
380		.compatible = "atmel,atecc508a",
381	}, {
382		/* sentinel */
383	}
384};
385MODULE_DEVICE_TABLE(of, atmel_ecc_dt_ids);
386#endif
387
388static const struct i2c_device_id atmel_ecc_id[] = {
389	{ "atecc508a", 0 },
390	{ }
391};
392MODULE_DEVICE_TABLE(i2c, atmel_ecc_id);
393
394static struct i2c_driver atmel_ecc_driver = {
395	.driver = {
396		.name	= "atmel-ecc",
397		.of_match_table = of_match_ptr(atmel_ecc_dt_ids),
398	},
399	.probe		= atmel_ecc_probe,
400	.remove		= atmel_ecc_remove,
401	.id_table	= atmel_ecc_id,
402};
403
404static int __init atmel_ecc_init(void)
405{
406	spin_lock_init(&driver_data.i2c_list_lock);
407	INIT_LIST_HEAD(&driver_data.i2c_client_list);
408	return i2c_add_driver(&atmel_ecc_driver);
409}
410
411static void __exit atmel_ecc_exit(void)
412{
413	flush_scheduled_work();
414	i2c_del_driver(&atmel_ecc_driver);
415}
416
417module_init(atmel_ecc_init);
418module_exit(atmel_ecc_exit);
419
420MODULE_AUTHOR("Tudor Ambarus <tudor.ambarus@microchip.com>");
421MODULE_DESCRIPTION("Microchip / Atmel ECC (I2C) driver");
422MODULE_LICENSE("GPL v2");
v4.17
 
  1/*
  2 * Microchip / Atmel ECC (I2C) driver.
  3 *
  4 * Copyright (c) 2017, Microchip Technology Inc.
  5 * Author: Tudor Ambarus <tudor.ambarus@microchip.com>
  6 *
  7 * This software is licensed under the terms of the GNU General Public
  8 * License version 2, as published by the Free Software Foundation, and
  9 * may be copied, distributed, and modified under those terms.
 10 *
 11 * This program is distributed in the hope that it will be useful,
 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 14 * GNU General Public License for more details.
 15 *
 16 */
 17
 18#include <linux/bitrev.h>
 19#include <linux/crc16.h>
 20#include <linux/delay.h>
 21#include <linux/device.h>
 22#include <linux/err.h>
 23#include <linux/errno.h>
 24#include <linux/i2c.h>
 25#include <linux/init.h>
 26#include <linux/kernel.h>
 27#include <linux/module.h>
 28#include <linux/of_device.h>
 29#include <linux/scatterlist.h>
 30#include <linux/slab.h>
 31#include <linux/workqueue.h>
 32#include <crypto/internal/kpp.h>
 33#include <crypto/ecdh.h>
 34#include <crypto/kpp.h>
 35#include "atmel-ecc.h"
 36
 37/* Used for binding tfm objects to i2c clients. */
 38struct atmel_ecc_driver_data {
 39	struct list_head i2c_client_list;
 40	spinlock_t i2c_list_lock;
 41} ____cacheline_aligned;
 42
 43static struct atmel_ecc_driver_data driver_data;
 44
 45/**
 46 * atmel_ecc_i2c_client_priv - i2c_client private data
 47 * @client              : pointer to i2c client device
 48 * @i2c_client_list_node: part of i2c_client_list
 49 * @lock                : lock for sending i2c commands
 50 * @wake_token          : wake token array of zeros
 51 * @wake_token_sz       : size in bytes of the wake_token
 52 * @tfm_count           : number of active crypto transformations on i2c client
 53 *
 54 * Reads and writes from/to the i2c client are sequential. The first byte
 55 * transmitted to the device is treated as the byte size. Any attempt to send
 56 * more than this number of bytes will cause the device to not ACK those bytes.
 57 * After the host writes a single command byte to the input buffer, reads are
 58 * prohibited until after the device completes command execution. Use a mutex
 59 * when sending i2c commands.
 60 */
 61struct atmel_ecc_i2c_client_priv {
 62	struct i2c_client *client;
 63	struct list_head i2c_client_list_node;
 64	struct mutex lock;
 65	u8 wake_token[WAKE_TOKEN_MAX_SIZE];
 66	size_t wake_token_sz;
 67	atomic_t tfm_count ____cacheline_aligned;
 68};
 69
 70/**
 71 * atmel_ecdh_ctx - transformation context
 72 * @client     : pointer to i2c client device
 73 * @fallback   : used for unsupported curves or when user wants to use its own
 74 *               private key.
 75 * @public_key : generated when calling set_secret(). It's the responsibility
 76 *               of the user to not call set_secret() while
 77 *               generate_public_key() or compute_shared_secret() are in flight.
 78 * @curve_id   : elliptic curve id
 79 * @n_sz       : size in bytes of the n prime
 80 * @do_fallback: true when the device doesn't support the curve or when the user
 81 *               wants to use its own private key.
 82 */
 83struct atmel_ecdh_ctx {
 84	struct i2c_client *client;
 85	struct crypto_kpp *fallback;
 86	const u8 *public_key;
 87	unsigned int curve_id;
 88	size_t n_sz;
 89	bool do_fallback;
 90};
 91
 92/**
 93 * atmel_ecc_work_data - data structure representing the work
 94 * @ctx : transformation context.
 95 * @cbk : pointer to a callback function to be invoked upon completion of this
 96 *        request. This has the form:
 97 *        callback(struct atmel_ecc_work_data *work_data, void *areq, u8 status)
 98 *        where:
 99 *        @work_data: data structure representing the work
100 *        @areq     : optional pointer to an argument passed with the original
101 *                    request.
102 *        @status   : status returned from the i2c client device or i2c error.
103 * @areq: optional pointer to a user argument for use at callback time.
104 * @work: describes the task to be executed.
105 * @cmd : structure used for communicating with the device.
106 */
107struct atmel_ecc_work_data {
108	struct atmel_ecdh_ctx *ctx;
109	void (*cbk)(struct atmel_ecc_work_data *work_data, void *areq,
110		    int status);
111	void *areq;
112	struct work_struct work;
113	struct atmel_ecc_cmd cmd;
114};
115
116static u16 atmel_ecc_crc16(u16 crc, const u8 *buffer, size_t len)
117{
118	return cpu_to_le16(bitrev16(crc16(crc, buffer, len)));
119}
120
121/**
122 * atmel_ecc_checksum() - Generate 16-bit CRC as required by ATMEL ECC.
123 * CRC16 verification of the count, opcode, param1, param2 and data bytes.
124 * The checksum is saved in little-endian format in the least significant
125 * two bytes of the command. CRC polynomial is 0x8005 and the initial register
126 * value should be zero.
127 *
128 * @cmd : structure used for communicating with the device.
129 */
130static void atmel_ecc_checksum(struct atmel_ecc_cmd *cmd)
131{
132	u8 *data = &cmd->count;
133	size_t len = cmd->count - CRC_SIZE;
134	u16 *crc16 = (u16 *)(data + len);
135
136	*crc16 = atmel_ecc_crc16(0, data, len);
137}
138
139static void atmel_ecc_init_read_cmd(struct atmel_ecc_cmd *cmd)
140{
141	cmd->word_addr = COMMAND;
142	cmd->opcode = OPCODE_READ;
143	/*
144	 * Read the word from Configuration zone that contains the lock bytes
145	 * (UserExtra, Selector, LockValue, LockConfig).
146	 */
147	cmd->param1 = CONFIG_ZONE;
148	cmd->param2 = DEVICE_LOCK_ADDR;
149	cmd->count = READ_COUNT;
150
151	atmel_ecc_checksum(cmd);
152
153	cmd->msecs = MAX_EXEC_TIME_READ;
154	cmd->rxsize = READ_RSP_SIZE;
155}
156
157static void atmel_ecc_init_genkey_cmd(struct atmel_ecc_cmd *cmd, u16 keyid)
158{
159	cmd->word_addr = COMMAND;
160	cmd->count = GENKEY_COUNT;
161	cmd->opcode = OPCODE_GENKEY;
162	cmd->param1 = GENKEY_MODE_PRIVATE;
163	/* a random private key will be generated and stored in slot keyID */
164	cmd->param2 = cpu_to_le16(keyid);
165
166	atmel_ecc_checksum(cmd);
167
168	cmd->msecs = MAX_EXEC_TIME_GENKEY;
169	cmd->rxsize = GENKEY_RSP_SIZE;
170}
171
172static int atmel_ecc_init_ecdh_cmd(struct atmel_ecc_cmd *cmd,
173				   struct scatterlist *pubkey)
174{
175	size_t copied;
176
177	cmd->word_addr = COMMAND;
178	cmd->count = ECDH_COUNT;
179	cmd->opcode = OPCODE_ECDH;
180	cmd->param1 = ECDH_PREFIX_MODE;
181	/* private key slot */
182	cmd->param2 = cpu_to_le16(DATA_SLOT_2);
183
184	/*
185	 * The device only supports NIST P256 ECC keys. The public key size will
186	 * always be the same. Use a macro for the key size to avoid unnecessary
187	 * computations.
188	 */
189	copied = sg_copy_to_buffer(pubkey, 1, cmd->data, ATMEL_ECC_PUBKEY_SIZE);
190	if (copied != ATMEL_ECC_PUBKEY_SIZE)
191		return -EINVAL;
192
193	atmel_ecc_checksum(cmd);
194
195	cmd->msecs = MAX_EXEC_TIME_ECDH;
196	cmd->rxsize = ECDH_RSP_SIZE;
197
198	return 0;
199}
200
201/*
202 * After wake and after execution of a command, there will be error, status, or
203 * result bytes in the device's output register that can be retrieved by the
204 * system. When the length of that group is four bytes, the codes returned are
205 * detailed in error_list.
206 */
207static int atmel_ecc_status(struct device *dev, u8 *status)
208{
209	size_t err_list_len = ARRAY_SIZE(error_list);
210	int i;
211	u8 err_id = status[1];
212
213	if (*status != STATUS_SIZE)
214		return 0;
215
216	if (err_id == STATUS_WAKE_SUCCESSFUL || err_id == STATUS_NOERR)
217		return 0;
218
219	for (i = 0; i < err_list_len; i++)
220		if (error_list[i].value == err_id)
221			break;
222
223	/* if err_id is not in the error_list then ignore it */
224	if (i != err_list_len) {
225		dev_err(dev, "%02x: %s:\n", err_id, error_list[i].error_text);
226		return err_id;
227	}
228
229	return 0;
230}
231
232static int atmel_ecc_wakeup(struct i2c_client *client)
233{
234	struct atmel_ecc_i2c_client_priv *i2c_priv = i2c_get_clientdata(client);
235	u8 status[STATUS_RSP_SIZE];
236	int ret;
237
238	/*
239	 * The device ignores any levels or transitions on the SCL pin when the
240	 * device is idle, asleep or during waking up. Don't check for error
241	 * when waking up the device.
242	 */
243	i2c_master_send(client, i2c_priv->wake_token, i2c_priv->wake_token_sz);
244
245	/*
246	 * Wait to wake the device. Typical execution times for ecdh and genkey
247	 * are around tens of milliseconds. Delta is chosen to 50 microseconds.
248	 */
249	usleep_range(TWHI_MIN, TWHI_MAX);
250
251	ret = i2c_master_recv(client, status, STATUS_SIZE);
252	if (ret < 0)
253		return ret;
254
255	return atmel_ecc_status(&client->dev, status);
256}
257
258static int atmel_ecc_sleep(struct i2c_client *client)
259{
260	u8 sleep = SLEEP_TOKEN;
261
262	return i2c_master_send(client, &sleep, 1);
263}
264
265static void atmel_ecdh_done(struct atmel_ecc_work_data *work_data, void *areq,
266			    int status)
267{
268	struct kpp_request *req = areq;
269	struct atmel_ecdh_ctx *ctx = work_data->ctx;
270	struct atmel_ecc_cmd *cmd = &work_data->cmd;
271	size_t copied;
272	size_t n_sz = ctx->n_sz;
273
274	if (status)
275		goto free_work_data;
276
 
 
 
277	/* copy the shared secret */
278	copied = sg_copy_from_buffer(req->dst, 1, &cmd->data[RSP_DATA_IDX],
279				     n_sz);
280	if (copied != n_sz)
281		status = -EINVAL;
282
283	/* fall through */
284free_work_data:
285	kzfree(work_data);
286	kpp_request_complete(req, status);
287}
288
289/*
290 * atmel_ecc_send_receive() - send a command to the device and receive its
291 *                            response.
292 * @client: i2c client device
293 * @cmd   : structure used to communicate with the device
294 *
295 * After the device receives a Wake token, a watchdog counter starts within the
296 * device. After the watchdog timer expires, the device enters sleep mode
297 * regardless of whether some I/O transmission or command execution is in
298 * progress. If a command is attempted when insufficient time remains prior to
299 * watchdog timer execution, the device will return the watchdog timeout error
300 * code without attempting to execute the command. There is no way to reset the
301 * counter other than to put the device into sleep or idle mode and then
302 * wake it up again.
303 */
304static int atmel_ecc_send_receive(struct i2c_client *client,
305				  struct atmel_ecc_cmd *cmd)
306{
307	struct atmel_ecc_i2c_client_priv *i2c_priv = i2c_get_clientdata(client);
308	int ret;
309
310	mutex_lock(&i2c_priv->lock);
311
312	ret = atmel_ecc_wakeup(client);
313	if (ret)
314		goto err;
315
316	/* send the command */
317	ret = i2c_master_send(client, (u8 *)cmd, cmd->count + WORD_ADDR_SIZE);
318	if (ret < 0)
319		goto err;
320
321	/* delay the appropriate amount of time for command to execute */
322	msleep(cmd->msecs);
323
324	/* receive the response */
325	ret = i2c_master_recv(client, cmd->data, cmd->rxsize);
326	if (ret < 0)
327		goto err;
328
329	/* put the device into low-power mode */
330	ret = atmel_ecc_sleep(client);
331	if (ret < 0)
332		goto err;
333
334	mutex_unlock(&i2c_priv->lock);
335	return atmel_ecc_status(&client->dev, cmd->data);
336err:
337	mutex_unlock(&i2c_priv->lock);
338	return ret;
339}
340
341static void atmel_ecc_work_handler(struct work_struct *work)
342{
343	struct atmel_ecc_work_data *work_data =
344			container_of(work, struct atmel_ecc_work_data, work);
345	struct atmel_ecc_cmd *cmd = &work_data->cmd;
346	struct i2c_client *client = work_data->ctx->client;
347	int status;
348
349	status = atmel_ecc_send_receive(client, cmd);
350	work_data->cbk(work_data, work_data->areq, status);
351}
352
353static void atmel_ecc_enqueue(struct atmel_ecc_work_data *work_data,
354			      void (*cbk)(struct atmel_ecc_work_data *work_data,
355					  void *areq, int status),
356			      void *areq)
357{
358	work_data->cbk = (void *)cbk;
359	work_data->areq = areq;
360
361	INIT_WORK(&work_data->work, atmel_ecc_work_handler);
362	schedule_work(&work_data->work);
363}
364
365static unsigned int atmel_ecdh_supported_curve(unsigned int curve_id)
366{
367	if (curve_id == ECC_CURVE_NIST_P256)
368		return ATMEL_ECC_NIST_P256_N_SIZE;
369
370	return 0;
371}
372
373/*
374 * A random private key is generated and stored in the device. The device
375 * returns the pair public key.
376 */
377static int atmel_ecdh_set_secret(struct crypto_kpp *tfm, const void *buf,
378				 unsigned int len)
379{
380	struct atmel_ecdh_ctx *ctx = kpp_tfm_ctx(tfm);
381	struct atmel_ecc_cmd *cmd;
382	void *public_key;
383	struct ecdh params;
384	int ret = -ENOMEM;
385
386	/* free the old public key, if any */
387	kfree(ctx->public_key);
388	/* make sure you don't free the old public key twice */
389	ctx->public_key = NULL;
390
391	if (crypto_ecdh_decode_key(buf, len, &params) < 0) {
392		dev_err(&ctx->client->dev, "crypto_ecdh_decode_key failed\n");
393		return -EINVAL;
394	}
395
396	ctx->n_sz = atmel_ecdh_supported_curve(params.curve_id);
397	if (!ctx->n_sz || params.key_size) {
398		/* fallback to ecdh software implementation */
399		ctx->do_fallback = true;
400		return crypto_kpp_set_secret(ctx->fallback, buf, len);
401	}
402
403	cmd = kmalloc(sizeof(*cmd), GFP_KERNEL);
404	if (!cmd)
405		return -ENOMEM;
406
407	/*
408	 * The device only supports NIST P256 ECC keys. The public key size will
409	 * always be the same. Use a macro for the key size to avoid unnecessary
410	 * computations.
411	 */
412	public_key = kmalloc(ATMEL_ECC_PUBKEY_SIZE, GFP_KERNEL);
413	if (!public_key)
414		goto free_cmd;
415
416	ctx->do_fallback = false;
417	ctx->curve_id = params.curve_id;
418
419	atmel_ecc_init_genkey_cmd(cmd, DATA_SLOT_2);
420
421	ret = atmel_ecc_send_receive(ctx->client, cmd);
422	if (ret)
423		goto free_public_key;
424
425	/* save the public key */
426	memcpy(public_key, &cmd->data[RSP_DATA_IDX], ATMEL_ECC_PUBKEY_SIZE);
427	ctx->public_key = public_key;
428
429	kfree(cmd);
430	return 0;
431
432free_public_key:
433	kfree(public_key);
434free_cmd:
435	kfree(cmd);
436	return ret;
437}
438
439static int atmel_ecdh_generate_public_key(struct kpp_request *req)
440{
441	struct crypto_kpp *tfm = crypto_kpp_reqtfm(req);
442	struct atmel_ecdh_ctx *ctx = kpp_tfm_ctx(tfm);
443	size_t copied;
444	int ret = 0;
445
446	if (ctx->do_fallback) {
447		kpp_request_set_tfm(req, ctx->fallback);
448		return crypto_kpp_generate_public_key(req);
449	}
450
 
 
 
 
 
 
451	/* public key was saved at private key generation */
452	copied = sg_copy_from_buffer(req->dst, 1, ctx->public_key,
453				     ATMEL_ECC_PUBKEY_SIZE);
454	if (copied != ATMEL_ECC_PUBKEY_SIZE)
 
455		ret = -EINVAL;
456
457	return ret;
458}
459
460static int atmel_ecdh_compute_shared_secret(struct kpp_request *req)
461{
462	struct crypto_kpp *tfm = crypto_kpp_reqtfm(req);
463	struct atmel_ecdh_ctx *ctx = kpp_tfm_ctx(tfm);
464	struct atmel_ecc_work_data *work_data;
465	gfp_t gfp;
466	int ret;
467
468	if (ctx->do_fallback) {
469		kpp_request_set_tfm(req, ctx->fallback);
470		return crypto_kpp_compute_shared_secret(req);
471	}
472
 
 
 
 
473	gfp = (req->base.flags & CRYPTO_TFM_REQ_MAY_SLEEP) ? GFP_KERNEL :
474							     GFP_ATOMIC;
475
476	work_data = kmalloc(sizeof(*work_data), gfp);
477	if (!work_data)
478		return -ENOMEM;
479
480	work_data->ctx = ctx;
 
481
482	ret = atmel_ecc_init_ecdh_cmd(&work_data->cmd, req->src);
483	if (ret)
484		goto free_work_data;
485
486	atmel_ecc_enqueue(work_data, atmel_ecdh_done, req);
487
488	return -EINPROGRESS;
489
490free_work_data:
491	kfree(work_data);
492	return ret;
493}
494
495static struct i2c_client *atmel_ecc_i2c_client_alloc(void)
496{
497	struct atmel_ecc_i2c_client_priv *i2c_priv, *min_i2c_priv = NULL;
498	struct i2c_client *client = ERR_PTR(-ENODEV);
499	int min_tfm_cnt = INT_MAX;
500	int tfm_cnt;
501
502	spin_lock(&driver_data.i2c_list_lock);
503
504	if (list_empty(&driver_data.i2c_client_list)) {
505		spin_unlock(&driver_data.i2c_list_lock);
506		return ERR_PTR(-ENODEV);
507	}
508
509	list_for_each_entry(i2c_priv, &driver_data.i2c_client_list,
510			    i2c_client_list_node) {
511		tfm_cnt = atomic_read(&i2c_priv->tfm_count);
512		if (tfm_cnt < min_tfm_cnt) {
513			min_tfm_cnt = tfm_cnt;
514			min_i2c_priv = i2c_priv;
515		}
516		if (!min_tfm_cnt)
517			break;
518	}
519
520	if (min_i2c_priv) {
521		atomic_inc(&min_i2c_priv->tfm_count);
522		client = min_i2c_priv->client;
523	}
524
525	spin_unlock(&driver_data.i2c_list_lock);
526
527	return client;
528}
529
530static void atmel_ecc_i2c_client_free(struct i2c_client *client)
531{
532	struct atmel_ecc_i2c_client_priv *i2c_priv = i2c_get_clientdata(client);
533
534	atomic_dec(&i2c_priv->tfm_count);
535}
536
537static int atmel_ecdh_init_tfm(struct crypto_kpp *tfm)
538{
539	const char *alg = kpp_alg_name(tfm);
540	struct crypto_kpp *fallback;
541	struct atmel_ecdh_ctx *ctx = kpp_tfm_ctx(tfm);
542
543	ctx->client = atmel_ecc_i2c_client_alloc();
544	if (IS_ERR(ctx->client)) {
545		pr_err("tfm - i2c_client binding failed\n");
546		return PTR_ERR(ctx->client);
547	}
548
549	fallback = crypto_alloc_kpp(alg, 0, CRYPTO_ALG_NEED_FALLBACK);
550	if (IS_ERR(fallback)) {
551		dev_err(&ctx->client->dev, "Failed to allocate transformation for '%s': %ld\n",
552			alg, PTR_ERR(fallback));
553		return PTR_ERR(fallback);
554	}
555
556	crypto_kpp_set_flags(fallback, crypto_kpp_get_flags(tfm));
557
558	dev_info(&ctx->client->dev, "Using '%s' as fallback implementation.\n",
559		 crypto_tfm_alg_driver_name(crypto_kpp_tfm(fallback)));
560
561	ctx->fallback = fallback;
562
563	return 0;
564}
565
566static void atmel_ecdh_exit_tfm(struct crypto_kpp *tfm)
567{
568	struct atmel_ecdh_ctx *ctx = kpp_tfm_ctx(tfm);
569
570	kfree(ctx->public_key);
571	crypto_free_kpp(ctx->fallback);
572	atmel_ecc_i2c_client_free(ctx->client);
573}
574
575static unsigned int atmel_ecdh_max_size(struct crypto_kpp *tfm)
576{
577	struct atmel_ecdh_ctx *ctx = kpp_tfm_ctx(tfm);
578
579	if (ctx->fallback)
580		return crypto_kpp_maxsize(ctx->fallback);
581
582	/*
583	 * The device only supports NIST P256 ECC keys. The public key size will
584	 * always be the same. Use a macro for the key size to avoid unnecessary
585	 * computations.
586	 */
587	return ATMEL_ECC_PUBKEY_SIZE;
588}
589
590static struct kpp_alg atmel_ecdh = {
591	.set_secret = atmel_ecdh_set_secret,
592	.generate_public_key = atmel_ecdh_generate_public_key,
593	.compute_shared_secret = atmel_ecdh_compute_shared_secret,
594	.init = atmel_ecdh_init_tfm,
595	.exit = atmel_ecdh_exit_tfm,
596	.max_size = atmel_ecdh_max_size,
597	.base = {
598		.cra_flags = CRYPTO_ALG_NEED_FALLBACK,
599		.cra_name = "ecdh",
600		.cra_driver_name = "atmel-ecdh",
601		.cra_priority = ATMEL_ECC_PRIORITY,
602		.cra_module = THIS_MODULE,
603		.cra_ctxsize = sizeof(struct atmel_ecdh_ctx),
604	},
605};
606
607static inline size_t atmel_ecc_wake_token_sz(u32 bus_clk_rate)
608{
609	u32 no_of_bits = DIV_ROUND_UP(TWLO_USEC * bus_clk_rate, USEC_PER_SEC);
610
611	/* return the size of the wake_token in bytes */
612	return DIV_ROUND_UP(no_of_bits, 8);
613}
614
615static int device_sanity_check(struct i2c_client *client)
616{
617	struct atmel_ecc_cmd *cmd;
618	int ret;
619
620	cmd = kmalloc(sizeof(*cmd), GFP_KERNEL);
621	if (!cmd)
622		return -ENOMEM;
623
624	atmel_ecc_init_read_cmd(cmd);
625
626	ret = atmel_ecc_send_receive(client, cmd);
627	if (ret)
628		goto free_cmd;
629
630	/*
631	 * It is vital that the Configuration, Data and OTP zones be locked
632	 * prior to release into the field of the system containing the device.
633	 * Failure to lock these zones may permit modification of any secret
634	 * keys and may lead to other security problems.
635	 */
636	if (cmd->data[LOCK_CONFIG_IDX] || cmd->data[LOCK_VALUE_IDX]) {
637		dev_err(&client->dev, "Configuration or Data and OTP zones are unlocked!\n");
638		ret = -ENOTSUPP;
639	}
640
641	/* fall through */
642free_cmd:
643	kfree(cmd);
644	return ret;
645}
646
647static int atmel_ecc_probe(struct i2c_client *client,
648			   const struct i2c_device_id *id)
649{
650	struct atmel_ecc_i2c_client_priv *i2c_priv;
651	struct device *dev = &client->dev;
652	int ret;
653	u32 bus_clk_rate;
654
655	if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
656		dev_err(dev, "I2C_FUNC_I2C not supported\n");
657		return -ENODEV;
658	}
659
660	ret = of_property_read_u32(client->adapter->dev.of_node,
661				   "clock-frequency", &bus_clk_rate);
662	if (ret) {
663		dev_err(dev, "of: failed to read clock-frequency property\n");
664		return ret;
665	}
666
667	if (bus_clk_rate > 1000000L) {
668		dev_err(dev, "%d exceeds maximum supported clock frequency (1MHz)\n",
669			bus_clk_rate);
670		return -EINVAL;
671	}
672
673	i2c_priv = devm_kmalloc(dev, sizeof(*i2c_priv), GFP_KERNEL);
674	if (!i2c_priv)
675		return -ENOMEM;
676
677	i2c_priv->client = client;
678	mutex_init(&i2c_priv->lock);
679
680	/*
681	 * WAKE_TOKEN_MAX_SIZE was calculated for the maximum bus_clk_rate -
682	 * 1MHz. The previous bus_clk_rate check ensures us that wake_token_sz
683	 * will always be smaller than or equal to WAKE_TOKEN_MAX_SIZE.
684	 */
685	i2c_priv->wake_token_sz = atmel_ecc_wake_token_sz(bus_clk_rate);
686
687	memset(i2c_priv->wake_token, 0, sizeof(i2c_priv->wake_token));
688
689	atomic_set(&i2c_priv->tfm_count, 0);
690
691	i2c_set_clientdata(client, i2c_priv);
692
693	ret = device_sanity_check(client);
694	if (ret)
695		return ret;
696
697	spin_lock(&driver_data.i2c_list_lock);
698	list_add_tail(&i2c_priv->i2c_client_list_node,
699		      &driver_data.i2c_client_list);
700	spin_unlock(&driver_data.i2c_list_lock);
701
702	ret = crypto_register_kpp(&atmel_ecdh);
703	if (ret) {
704		spin_lock(&driver_data.i2c_list_lock);
705		list_del(&i2c_priv->i2c_client_list_node);
706		spin_unlock(&driver_data.i2c_list_lock);
707
708		dev_err(dev, "%s alg registration failed\n",
709			atmel_ecdh.base.cra_driver_name);
710	} else {
711		dev_info(dev, "atmel ecc algorithms registered in /proc/crypto\n");
712	}
713
714	return ret;
715}
716
717static int atmel_ecc_remove(struct i2c_client *client)
718{
719	struct atmel_ecc_i2c_client_priv *i2c_priv = i2c_get_clientdata(client);
720
721	/* Return EBUSY if i2c client already allocated. */
722	if (atomic_read(&i2c_priv->tfm_count)) {
723		dev_err(&client->dev, "Device is busy\n");
724		return -EBUSY;
725	}
726
727	crypto_unregister_kpp(&atmel_ecdh);
728
729	spin_lock(&driver_data.i2c_list_lock);
730	list_del(&i2c_priv->i2c_client_list_node);
731	spin_unlock(&driver_data.i2c_list_lock);
732
733	return 0;
734}
735
736#ifdef CONFIG_OF
737static const struct of_device_id atmel_ecc_dt_ids[] = {
738	{
739		.compatible = "atmel,atecc508a",
740	}, {
741		/* sentinel */
742	}
743};
744MODULE_DEVICE_TABLE(of, atmel_ecc_dt_ids);
745#endif
746
747static const struct i2c_device_id atmel_ecc_id[] = {
748	{ "atecc508a", 0 },
749	{ }
750};
751MODULE_DEVICE_TABLE(i2c, atmel_ecc_id);
752
753static struct i2c_driver atmel_ecc_driver = {
754	.driver = {
755		.name	= "atmel-ecc",
756		.of_match_table = of_match_ptr(atmel_ecc_dt_ids),
757	},
758	.probe		= atmel_ecc_probe,
759	.remove		= atmel_ecc_remove,
760	.id_table	= atmel_ecc_id,
761};
762
763static int __init atmel_ecc_init(void)
764{
765	spin_lock_init(&driver_data.i2c_list_lock);
766	INIT_LIST_HEAD(&driver_data.i2c_client_list);
767	return i2c_add_driver(&atmel_ecc_driver);
768}
769
770static void __exit atmel_ecc_exit(void)
771{
772	flush_scheduled_work();
773	i2c_del_driver(&atmel_ecc_driver);
774}
775
776module_init(atmel_ecc_init);
777module_exit(atmel_ecc_exit);
778
779MODULE_AUTHOR("Tudor Ambarus <tudor.ambarus@microchip.com>");
780MODULE_DESCRIPTION("Microchip / Atmel ECC (I2C) driver");
781MODULE_LICENSE("GPL v2");