1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2016-2017 Hisilicon Limited. */
3 #include <linux/crypto.h>
4 #include <linux/dma-mapping.h>
5 #include <linux/dmapool.h>
6 #include <linux/module.h>
7 #include <linux/mutex.h>
8 #include <linux/slab.h>
9 
10 #include <crypto/aes.h>
11 #include <crypto/algapi.h>
12 #include <crypto/des.h>
13 #include <crypto/skcipher.h>
14 #include <crypto/xts.h>
15 #include <crypto/internal/skcipher.h>
16 
17 #include "sec_drv.h"
18 
19 #define SEC_MAX_CIPHER_KEY		64
20 #define SEC_REQ_LIMIT SZ_32M
21 
22 struct sec_c_alg_cfg {
23 	unsigned c_alg		: 3;
24 	unsigned c_mode		: 3;
25 	unsigned key_len	: 2;
26 	unsigned c_width	: 2;
27 };
28 
29 static const struct sec_c_alg_cfg sec_c_alg_cfgs[] =  {
30 	[SEC_C_DES_ECB_64] = {
31 		.c_alg = SEC_C_ALG_DES,
32 		.c_mode = SEC_C_MODE_ECB,
33 		.key_len = SEC_KEY_LEN_DES,
34 	},
35 	[SEC_C_DES_CBC_64] = {
36 		.c_alg = SEC_C_ALG_DES,
37 		.c_mode = SEC_C_MODE_CBC,
38 		.key_len = SEC_KEY_LEN_DES,
39 	},
40 	[SEC_C_3DES_ECB_192_3KEY] = {
41 		.c_alg = SEC_C_ALG_3DES,
42 		.c_mode = SEC_C_MODE_ECB,
43 		.key_len = SEC_KEY_LEN_3DES_3_KEY,
44 	},
45 	[SEC_C_3DES_ECB_192_2KEY] = {
46 		.c_alg = SEC_C_ALG_3DES,
47 		.c_mode = SEC_C_MODE_ECB,
48 		.key_len = SEC_KEY_LEN_3DES_2_KEY,
49 	},
50 	[SEC_C_3DES_CBC_192_3KEY] = {
51 		.c_alg = SEC_C_ALG_3DES,
52 		.c_mode = SEC_C_MODE_CBC,
53 		.key_len = SEC_KEY_LEN_3DES_3_KEY,
54 	},
55 	[SEC_C_3DES_CBC_192_2KEY] = {
56 		.c_alg = SEC_C_ALG_3DES,
57 		.c_mode = SEC_C_MODE_CBC,
58 		.key_len = SEC_KEY_LEN_3DES_2_KEY,
59 	},
60 	[SEC_C_AES_ECB_128] = {
61 		.c_alg = SEC_C_ALG_AES,
62 		.c_mode = SEC_C_MODE_ECB,
63 		.key_len = SEC_KEY_LEN_AES_128,
64 	},
65 	[SEC_C_AES_ECB_192] = {
66 		.c_alg = SEC_C_ALG_AES,
67 		.c_mode = SEC_C_MODE_ECB,
68 		.key_len = SEC_KEY_LEN_AES_192,
69 	},
70 	[SEC_C_AES_ECB_256] = {
71 		.c_alg = SEC_C_ALG_AES,
72 		.c_mode = SEC_C_MODE_ECB,
73 		.key_len = SEC_KEY_LEN_AES_256,
74 	},
75 	[SEC_C_AES_CBC_128] = {
76 		.c_alg = SEC_C_ALG_AES,
77 		.c_mode = SEC_C_MODE_CBC,
78 		.key_len = SEC_KEY_LEN_AES_128,
79 	},
80 	[SEC_C_AES_CBC_192] = {
81 		.c_alg = SEC_C_ALG_AES,
82 		.c_mode = SEC_C_MODE_CBC,
83 		.key_len = SEC_KEY_LEN_AES_192,
84 	},
85 	[SEC_C_AES_CBC_256] = {
86 		.c_alg = SEC_C_ALG_AES,
87 		.c_mode = SEC_C_MODE_CBC,
88 		.key_len = SEC_KEY_LEN_AES_256,
89 	},
90 	[SEC_C_AES_CTR_128] = {
91 		.c_alg = SEC_C_ALG_AES,
92 		.c_mode = SEC_C_MODE_CTR,
93 		.key_len = SEC_KEY_LEN_AES_128,
94 	},
95 	[SEC_C_AES_CTR_192] = {
96 		.c_alg = SEC_C_ALG_AES,
97 		.c_mode = SEC_C_MODE_CTR,
98 		.key_len = SEC_KEY_LEN_AES_192,
99 	},
100 	[SEC_C_AES_CTR_256] = {
101 		.c_alg = SEC_C_ALG_AES,
102 		.c_mode = SEC_C_MODE_CTR,
103 		.key_len = SEC_KEY_LEN_AES_256,
104 	},
105 	[SEC_C_AES_XTS_128] = {
106 		.c_alg = SEC_C_ALG_AES,
107 		.c_mode = SEC_C_MODE_XTS,
108 		.key_len = SEC_KEY_LEN_AES_128,
109 	},
110 	[SEC_C_AES_XTS_256] = {
111 		.c_alg = SEC_C_ALG_AES,
112 		.c_mode = SEC_C_MODE_XTS,
113 		.key_len = SEC_KEY_LEN_AES_256,
114 	},
115 	[SEC_C_NULL] = {
116 	},
117 };
118 
119 /*
120  * Mutex used to ensure safe operation of reference count of
121  * alg providers
122  */
123 static DEFINE_MUTEX(algs_lock);
124 static unsigned int active_devs;
125 
126 static void sec_alg_skcipher_init_template(struct sec_alg_tfm_ctx *ctx,
127 					   struct sec_bd_info *req,
128 					   enum sec_cipher_alg alg)
129 {
130 	const struct sec_c_alg_cfg *cfg = &sec_c_alg_cfgs[alg];
131 
132 	memset(req, 0, sizeof(*req));
133 	req->w0 |= cfg->c_mode << SEC_BD_W0_C_MODE_S;
134 	req->w1 |= cfg->c_alg << SEC_BD_W1_C_ALG_S;
135 	req->w3 |= cfg->key_len << SEC_BD_W3_C_KEY_LEN_S;
136 	req->w0 |= cfg->c_width << SEC_BD_W0_C_WIDTH_S;
137 
138 	req->cipher_key_addr_lo = lower_32_bits(ctx->pkey);
139 	req->cipher_key_addr_hi = upper_32_bits(ctx->pkey);
140 }
141 
142 static void sec_alg_skcipher_init_context(struct crypto_skcipher *atfm,
143 					  const u8 *key,
144 					  unsigned int keylen,
145 					  enum sec_cipher_alg alg)
146 {
147 	struct crypto_tfm *tfm = crypto_skcipher_tfm(atfm);
148 	struct sec_alg_tfm_ctx *ctx = crypto_tfm_ctx(tfm);
149 
150 	ctx->cipher_alg = alg;
151 	memcpy(ctx->key, key, keylen);
152 	sec_alg_skcipher_init_template(ctx, &ctx->req_template,
153 				       ctx->cipher_alg);
154 }
155 
156 static int sec_alloc_and_fill_hw_sgl(struct sec_hw_sgl **sec_sgl,
157 				     dma_addr_t *psec_sgl,
158 				     struct scatterlist *sgl,
159 				     int count,
160 				     struct sec_dev_info *info)
161 {
162 	struct sec_hw_sgl *sgl_current = NULL;
163 	struct sec_hw_sgl *sgl_next;
164 	dma_addr_t sgl_next_dma;
165 	struct scatterlist *sg;
166 	int ret, sge_index, i;
167 
168 	if (!count)
169 		return -EINVAL;
170 
171 	for_each_sg(sgl, sg, count, i) {
172 		sge_index = i % SEC_MAX_SGE_NUM;
173 		if (sge_index == 0) {
174 			sgl_next = dma_pool_zalloc(info->hw_sgl_pool,
175 						   GFP_KERNEL, &sgl_next_dma);
176 			if (!sgl_next) {
177 				ret = -ENOMEM;
178 				goto err_free_hw_sgls;
179 			}
180 
181 			if (!sgl_current) { /* First one */
182 				*psec_sgl = sgl_next_dma;
183 				*sec_sgl = sgl_next;
184 			} else { /* Chained */
185 				sgl_current->entry_sum_in_sgl = SEC_MAX_SGE_NUM;
186 				sgl_current->next_sgl = sgl_next_dma;
187 				sgl_current->next = sgl_next;
188 			}
189 			sgl_current = sgl_next;
190 		}
191 		sgl_current->sge_entries[sge_index].buf = sg_dma_address(sg);
192 		sgl_current->sge_entries[sge_index].len = sg_dma_len(sg);
193 		sgl_current->data_bytes_in_sgl += sg_dma_len(sg);
194 	}
195 	sgl_current->entry_sum_in_sgl = count % SEC_MAX_SGE_NUM;
196 	sgl_current->next_sgl = 0;
197 	(*sec_sgl)->entry_sum_in_chain = count;
198 
199 	return 0;
200 
201 err_free_hw_sgls:
202 	sgl_current = *sec_sgl;
203 	while (sgl_current) {
204 		sgl_next = sgl_current->next;
205 		dma_pool_free(info->hw_sgl_pool, sgl_current,
206 			      sgl_current->next_sgl);
207 		sgl_current = sgl_next;
208 	}
209 	*psec_sgl = 0;
210 
211 	return ret;
212 }
213 
214 static void sec_free_hw_sgl(struct sec_hw_sgl *hw_sgl,
215 			    dma_addr_t psec_sgl, struct sec_dev_info *info)
216 {
217 	struct sec_hw_sgl *sgl_current, *sgl_next;
218 
219 	if (!hw_sgl)
220 		return;
221 	sgl_current = hw_sgl;
222 	while (sgl_current->next) {
223 		sgl_next = sgl_current->next;
224 		dma_pool_free(info->hw_sgl_pool, sgl_current,
225 			      sgl_current->next_sgl);
226 		sgl_current = sgl_next;
227 	}
228 	dma_pool_free(info->hw_sgl_pool, hw_sgl, psec_sgl);
229 }
230 
231 static int sec_alg_skcipher_setkey(struct crypto_skcipher *tfm,
232 				   const u8 *key, unsigned int keylen,
233 				   enum sec_cipher_alg alg)
234 {
235 	struct sec_alg_tfm_ctx *ctx = crypto_skcipher_ctx(tfm);
236 	struct device *dev = ctx->queue->dev_info->dev;
237 
238 	mutex_lock(&ctx->lock);
239 	if (ctx->key) {
240 		/* rekeying */
241 		memset(ctx->key, 0, SEC_MAX_CIPHER_KEY);
242 	} else {
243 		/* new key */
244 		ctx->key = dma_alloc_coherent(dev, SEC_MAX_CIPHER_KEY,
245 					      &ctx->pkey, GFP_KERNEL);
246 		if (!ctx->key) {
247 			mutex_unlock(&ctx->lock);
248 			return -ENOMEM;
249 		}
250 	}
251 	mutex_unlock(&ctx->lock);
252 	sec_alg_skcipher_init_context(tfm, key, keylen, alg);
253 
254 	return 0;
255 }
256 
257 static int sec_alg_skcipher_setkey_aes_ecb(struct crypto_skcipher *tfm,
258 					   const u8 *key, unsigned int keylen)
259 {
260 	enum sec_cipher_alg alg;
261 
262 	switch (keylen) {
263 	case AES_KEYSIZE_128:
264 		alg = SEC_C_AES_ECB_128;
265 		break;
266 	case AES_KEYSIZE_192:
267 		alg = SEC_C_AES_ECB_192;
268 		break;
269 	case AES_KEYSIZE_256:
270 		alg = SEC_C_AES_ECB_256;
271 		break;
272 	default:
273 		return -EINVAL;
274 	}
275 
276 	return sec_alg_skcipher_setkey(tfm, key, keylen, alg);
277 }
278 
279 static int sec_alg_skcipher_setkey_aes_cbc(struct crypto_skcipher *tfm,
280 					   const u8 *key, unsigned int keylen)
281 {
282 	enum sec_cipher_alg alg;
283 
284 	switch (keylen) {
285 	case AES_KEYSIZE_128:
286 		alg = SEC_C_AES_CBC_128;
287 		break;
288 	case AES_KEYSIZE_192:
289 		alg = SEC_C_AES_CBC_192;
290 		break;
291 	case AES_KEYSIZE_256:
292 		alg = SEC_C_AES_CBC_256;
293 		break;
294 	default:
295 		return -EINVAL;
296 	}
297 
298 	return sec_alg_skcipher_setkey(tfm, key, keylen, alg);
299 }
300 
301 static int sec_alg_skcipher_setkey_aes_ctr(struct crypto_skcipher *tfm,
302 					   const u8 *key, unsigned int keylen)
303 {
304 	enum sec_cipher_alg alg;
305 
306 	switch (keylen) {
307 	case AES_KEYSIZE_128:
308 		alg = SEC_C_AES_CTR_128;
309 		break;
310 	case AES_KEYSIZE_192:
311 		alg = SEC_C_AES_CTR_192;
312 		break;
313 	case AES_KEYSIZE_256:
314 		alg = SEC_C_AES_CTR_256;
315 		break;
316 	default:
317 		return -EINVAL;
318 	}
319 
320 	return sec_alg_skcipher_setkey(tfm, key, keylen, alg);
321 }
322 
323 static int sec_alg_skcipher_setkey_aes_xts(struct crypto_skcipher *tfm,
324 					   const u8 *key, unsigned int keylen)
325 {
326 	enum sec_cipher_alg alg;
327 	int ret;
328 
329 	ret = xts_verify_key(tfm, key, keylen);
330 	if (ret)
331 		return ret;
332 
333 	switch (keylen) {
334 	case AES_KEYSIZE_128 * 2:
335 		alg = SEC_C_AES_XTS_128;
336 		break;
337 	case AES_KEYSIZE_256 * 2:
338 		alg = SEC_C_AES_XTS_256;
339 		break;
340 	default:
341 		return -EINVAL;
342 	}
343 
344 	return sec_alg_skcipher_setkey(tfm, key, keylen, alg);
345 }
346 
347 static int sec_alg_skcipher_setkey_des_ecb(struct crypto_skcipher *tfm,
348 					   const u8 *key, unsigned int keylen)
349 {
350 	if (keylen != DES_KEY_SIZE)
351 		return -EINVAL;
352 
353 	return sec_alg_skcipher_setkey(tfm, key, keylen, SEC_C_DES_ECB_64);
354 }
355 
356 static int sec_alg_skcipher_setkey_des_cbc(struct crypto_skcipher *tfm,
357 					   const u8 *key, unsigned int keylen)
358 {
359 	if (keylen != DES_KEY_SIZE)
360 		return -EINVAL;
361 
362 	return sec_alg_skcipher_setkey(tfm, key, keylen, SEC_C_DES_CBC_64);
363 }
364 
365 static int sec_alg_skcipher_setkey_3des_ecb(struct crypto_skcipher *tfm,
366 					    const u8 *key, unsigned int keylen)
367 {
368 	return unlikely(des3_verify_key(tfm, key)) ?:
369 	       sec_alg_skcipher_setkey(tfm, key, keylen,
370 				       SEC_C_3DES_ECB_192_3KEY);
371 }
372 
373 static int sec_alg_skcipher_setkey_3des_cbc(struct crypto_skcipher *tfm,
374 					    const u8 *key, unsigned int keylen)
375 {
376 	return unlikely(des3_verify_key(tfm, key)) ?:
377 	       sec_alg_skcipher_setkey(tfm, key, keylen,
378 				       SEC_C_3DES_CBC_192_3KEY);
379 }
380 
381 static void sec_alg_free_el(struct sec_request_el *el,
382 			    struct sec_dev_info *info)
383 {
384 	sec_free_hw_sgl(el->out, el->dma_out, info);
385 	sec_free_hw_sgl(el->in, el->dma_in, info);
386 	kfree(el->sgl_in);
387 	kfree(el->sgl_out);
388 	kfree(el);
389 }
390 
391 /* queuelock must be held */
392 static int sec_send_request(struct sec_request *sec_req, struct sec_queue *queue)
393 {
394 	struct sec_request_el *el, *temp;
395 	int ret = 0;
396 
397 	mutex_lock(&sec_req->lock);
398 	list_for_each_entry_safe(el, temp, &sec_req->elements, head) {
399 		/*
400 		 * Add to hardware queue only under following circumstances
401 		 * 1) Software and hardware queue empty so no chain dependencies
402 		 * 2) No dependencies as new IV - (check software queue empty
403 		 *    to maintain order)
404 		 * 3) No dependencies because the mode does no chaining.
405 		 *
406 		 * In other cases first insert onto the software queue which
407 		 * is then emptied as requests complete
408 		 */
409 		if (!queue->havesoftqueue ||
410 		    (kfifo_is_empty(&queue->softqueue) &&
411 		     sec_queue_empty(queue))) {
412 			ret = sec_queue_send(queue, &el->req, sec_req);
413 			if (ret == -EAGAIN) {
414 				/* Wait unti we can send then try again */
415 				/* DEAD if here - should not happen */
416 				ret = -EBUSY;
417 				goto err_unlock;
418 			}
419 		} else {
420 			kfifo_put(&queue->softqueue, el);
421 		}
422 	}
423 err_unlock:
424 	mutex_unlock(&sec_req->lock);
425 
426 	return ret;
427 }
428 
429 static void sec_skcipher_alg_callback(struct sec_bd_info *sec_resp,
430 				      struct crypto_async_request *req_base)
431 {
432 	struct skcipher_request *skreq = container_of(req_base,
433 						      struct skcipher_request,
434 						      base);
435 	struct sec_request *sec_req = skcipher_request_ctx(skreq);
436 	struct sec_request *backlog_req;
437 	struct sec_request_el *sec_req_el, *nextrequest;
438 	struct sec_alg_tfm_ctx *ctx = sec_req->tfm_ctx;
439 	struct crypto_skcipher *atfm = crypto_skcipher_reqtfm(skreq);
440 	struct device *dev = ctx->queue->dev_info->dev;
441 	int icv_or_skey_en, ret;
442 	bool done;
443 
444 	sec_req_el = list_first_entry(&sec_req->elements, struct sec_request_el,
445 				      head);
446 	icv_or_skey_en = (sec_resp->w0 & SEC_BD_W0_ICV_OR_SKEY_EN_M) >>
447 		SEC_BD_W0_ICV_OR_SKEY_EN_S;
448 	if (sec_resp->w1 & SEC_BD_W1_BD_INVALID || icv_or_skey_en == 3) {
449 		dev_err(dev, "Got an invalid answer %lu %d\n",
450 			sec_resp->w1 & SEC_BD_W1_BD_INVALID,
451 			icv_or_skey_en);
452 		sec_req->err = -EINVAL;
453 		/*
454 		 * We need to muddle on to avoid getting stuck with elements
455 		 * on the queue. Error will be reported so requester so
456 		 * it should be able to handle appropriately.
457 		 */
458 	}
459 
460 	mutex_lock(&ctx->queue->queuelock);
461 	/* Put the IV in place for chained cases */
462 	switch (ctx->cipher_alg) {
463 	case SEC_C_AES_CBC_128:
464 	case SEC_C_AES_CBC_192:
465 	case SEC_C_AES_CBC_256:
466 		if (sec_req_el->req.w0 & SEC_BD_W0_DE)
467 			sg_pcopy_to_buffer(sec_req_el->sgl_out,
468 					   sg_nents(sec_req_el->sgl_out),
469 					   skreq->iv,
470 					   crypto_skcipher_ivsize(atfm),
471 					   sec_req_el->el_length -
472 					   crypto_skcipher_ivsize(atfm));
473 		else
474 			sg_pcopy_to_buffer(sec_req_el->sgl_in,
475 					   sg_nents(sec_req_el->sgl_in),
476 					   skreq->iv,
477 					   crypto_skcipher_ivsize(atfm),
478 					   sec_req_el->el_length -
479 					   crypto_skcipher_ivsize(atfm));
480 		/* No need to sync to the device as coherent DMA */
481 		break;
482 	case SEC_C_AES_CTR_128:
483 	case SEC_C_AES_CTR_192:
484 	case SEC_C_AES_CTR_256:
485 		crypto_inc(skreq->iv, 16);
486 		break;
487 	default:
488 		/* Do not update */
489 		break;
490 	}
491 
492 	if (ctx->queue->havesoftqueue &&
493 	    !kfifo_is_empty(&ctx->queue->softqueue) &&
494 	    sec_queue_empty(ctx->queue)) {
495 		ret = kfifo_get(&ctx->queue->softqueue, &nextrequest);
496 		if (ret <= 0)
497 			dev_err(dev,
498 				"Error getting next element from kfifo %d\n",
499 				ret);
500 		else
501 			/* We know there is space so this cannot fail */
502 			sec_queue_send(ctx->queue, &nextrequest->req,
503 				       nextrequest->sec_req);
504 	} else if (!list_empty(&ctx->backlog)) {
505 		/* Need to verify there is room first */
506 		backlog_req = list_first_entry(&ctx->backlog,
507 					       typeof(*backlog_req),
508 					       backlog_head);
509 		if (sec_queue_can_enqueue(ctx->queue,
510 		    backlog_req->num_elements) ||
511 		    (ctx->queue->havesoftqueue &&
512 		     kfifo_avail(&ctx->queue->softqueue) >
513 		     backlog_req->num_elements)) {
514 			sec_send_request(backlog_req, ctx->queue);
515 			backlog_req->req_base->complete(backlog_req->req_base,
516 							-EINPROGRESS);
517 			list_del(&backlog_req->backlog_head);
518 		}
519 	}
520 	mutex_unlock(&ctx->queue->queuelock);
521 
522 	mutex_lock(&sec_req->lock);
523 	list_del(&sec_req_el->head);
524 	mutex_unlock(&sec_req->lock);
525 	sec_alg_free_el(sec_req_el, ctx->queue->dev_info);
526 
527 	/*
528 	 * Request is done.
529 	 * The dance is needed as the lock is freed in the completion
530 	 */
531 	mutex_lock(&sec_req->lock);
532 	done = list_empty(&sec_req->elements);
533 	mutex_unlock(&sec_req->lock);
534 	if (done) {
535 		if (crypto_skcipher_ivsize(atfm)) {
536 			dma_unmap_single(dev, sec_req->dma_iv,
537 					 crypto_skcipher_ivsize(atfm),
538 					 DMA_TO_DEVICE);
539 		}
540 		dma_unmap_sg(dev, skreq->src, sec_req->len_in,
541 			     DMA_BIDIRECTIONAL);
542 		if (skreq->src != skreq->dst)
543 			dma_unmap_sg(dev, skreq->dst, sec_req->len_out,
544 				     DMA_BIDIRECTIONAL);
545 		skreq->base.complete(&skreq->base, sec_req->err);
546 	}
547 }
548 
549 void sec_alg_callback(struct sec_bd_info *resp, void *shadow)
550 {
551 	struct sec_request *sec_req = shadow;
552 
553 	sec_req->cb(resp, sec_req->req_base);
554 }
555 
556 static int sec_alg_alloc_and_calc_split_sizes(int length, size_t **split_sizes,
557 					      int *steps)
558 {
559 	size_t *sizes;
560 	int i;
561 
562 	/* Split into suitable sized blocks */
563 	*steps = roundup(length, SEC_REQ_LIMIT) / SEC_REQ_LIMIT;
564 	sizes = kcalloc(*steps, sizeof(*sizes), GFP_KERNEL);
565 	if (!sizes)
566 		return -ENOMEM;
567 
568 	for (i = 0; i < *steps - 1; i++)
569 		sizes[i] = SEC_REQ_LIMIT;
570 	sizes[*steps - 1] = length - SEC_REQ_LIMIT * (*steps - 1);
571 	*split_sizes = sizes;
572 
573 	return 0;
574 }
575 
576 static int sec_map_and_split_sg(struct scatterlist *sgl, size_t *split_sizes,
577 				int steps, struct scatterlist ***splits,
578 				int **splits_nents,
579 				int sgl_len_in,
580 				struct device *dev)
581 {
582 	int ret, count;
583 
584 	count = dma_map_sg(dev, sgl, sgl_len_in, DMA_BIDIRECTIONAL);
585 	if (!count)
586 		return -EINVAL;
587 
588 	*splits = kcalloc(steps, sizeof(struct scatterlist *), GFP_KERNEL);
589 	if (!*splits) {
590 		ret = -ENOMEM;
591 		goto err_unmap_sg;
592 	}
593 	*splits_nents = kcalloc(steps, sizeof(int), GFP_KERNEL);
594 	if (!*splits_nents) {
595 		ret = -ENOMEM;
596 		goto err_free_splits;
597 	}
598 
599 	/* output the scatter list before and after this */
600 	ret = sg_split(sgl, count, 0, steps, split_sizes,
601 		       *splits, *splits_nents, GFP_KERNEL);
602 	if (ret) {
603 		ret = -ENOMEM;
604 		goto err_free_splits_nents;
605 	}
606 
607 	return 0;
608 
609 err_free_splits_nents:
610 	kfree(*splits_nents);
611 err_free_splits:
612 	kfree(*splits);
613 err_unmap_sg:
614 	dma_unmap_sg(dev, sgl, sgl_len_in, DMA_BIDIRECTIONAL);
615 
616 	return ret;
617 }
618 
619 /*
620  * Reverses the sec_map_and_split_sg call for messages not yet added to
621  * the queues.
622  */
623 static void sec_unmap_sg_on_err(struct scatterlist *sgl, int steps,
624 				struct scatterlist **splits, int *splits_nents,
625 				int sgl_len_in, struct device *dev)
626 {
627 	int i;
628 
629 	for (i = 0; i < steps; i++)
630 		kfree(splits[i]);
631 	kfree(splits_nents);
632 	kfree(splits);
633 
634 	dma_unmap_sg(dev, sgl, sgl_len_in, DMA_BIDIRECTIONAL);
635 }
636 
637 static struct sec_request_el
638 *sec_alg_alloc_and_fill_el(struct sec_bd_info *template, int encrypt,
639 			   int el_size, bool different_dest,
640 			   struct scatterlist *sgl_in, int n_ents_in,
641 			   struct scatterlist *sgl_out, int n_ents_out,
642 			   struct sec_dev_info *info)
643 {
644 	struct sec_request_el *el;
645 	struct sec_bd_info *req;
646 	int ret;
647 
648 	el = kzalloc(sizeof(*el), GFP_KERNEL);
649 	if (!el)
650 		return ERR_PTR(-ENOMEM);
651 	el->el_length = el_size;
652 	req = &el->req;
653 	memcpy(req, template, sizeof(*req));
654 
655 	req->w0 &= ~SEC_BD_W0_CIPHER_M;
656 	if (encrypt)
657 		req->w0 |= SEC_CIPHER_ENCRYPT << SEC_BD_W0_CIPHER_S;
658 	else
659 		req->w0 |= SEC_CIPHER_DECRYPT << SEC_BD_W0_CIPHER_S;
660 
661 	req->w0 &= ~SEC_BD_W0_C_GRAN_SIZE_19_16_M;
662 	req->w0 |= ((el_size >> 16) << SEC_BD_W0_C_GRAN_SIZE_19_16_S) &
663 		SEC_BD_W0_C_GRAN_SIZE_19_16_M;
664 
665 	req->w0 &= ~SEC_BD_W0_C_GRAN_SIZE_21_20_M;
666 	req->w0 |= ((el_size >> 20) << SEC_BD_W0_C_GRAN_SIZE_21_20_S) &
667 		SEC_BD_W0_C_GRAN_SIZE_21_20_M;
668 
669 	/* Writing whole u32 so no need to take care of masking */
670 	req->w2 = ((1 << SEC_BD_W2_GRAN_NUM_S) & SEC_BD_W2_GRAN_NUM_M) |
671 		((el_size << SEC_BD_W2_C_GRAN_SIZE_15_0_S) &
672 		 SEC_BD_W2_C_GRAN_SIZE_15_0_M);
673 
674 	req->w3 &= ~SEC_BD_W3_CIPHER_LEN_OFFSET_M;
675 	req->w1 |= SEC_BD_W1_ADDR_TYPE;
676 
677 	el->sgl_in = sgl_in;
678 
679 	ret = sec_alloc_and_fill_hw_sgl(&el->in, &el->dma_in, el->sgl_in,
680 					n_ents_in, info);
681 	if (ret)
682 		goto err_free_el;
683 
684 	req->data_addr_lo = lower_32_bits(el->dma_in);
685 	req->data_addr_hi = upper_32_bits(el->dma_in);
686 
687 	if (different_dest) {
688 		el->sgl_out = sgl_out;
689 		ret = sec_alloc_and_fill_hw_sgl(&el->out, &el->dma_out,
690 						el->sgl_out,
691 						n_ents_out, info);
692 		if (ret)
693 			goto err_free_hw_sgl_in;
694 
695 		req->w0 |= SEC_BD_W0_DE;
696 		req->cipher_destin_addr_lo = lower_32_bits(el->dma_out);
697 		req->cipher_destin_addr_hi = upper_32_bits(el->dma_out);
698 
699 	} else {
700 		req->w0 &= ~SEC_BD_W0_DE;
701 		req->cipher_destin_addr_lo = lower_32_bits(el->dma_in);
702 		req->cipher_destin_addr_hi = upper_32_bits(el->dma_in);
703 	}
704 
705 	return el;
706 
707 err_free_hw_sgl_in:
708 	sec_free_hw_sgl(el->in, el->dma_in, info);
709 err_free_el:
710 	kfree(el);
711 
712 	return ERR_PTR(ret);
713 }
714 
715 static int sec_alg_skcipher_crypto(struct skcipher_request *skreq,
716 				   bool encrypt)
717 {
718 	struct crypto_skcipher *atfm = crypto_skcipher_reqtfm(skreq);
719 	struct crypto_tfm *tfm = crypto_skcipher_tfm(atfm);
720 	struct sec_alg_tfm_ctx *ctx = crypto_tfm_ctx(tfm);
721 	struct sec_queue *queue = ctx->queue;
722 	struct sec_request *sec_req = skcipher_request_ctx(skreq);
723 	struct sec_dev_info *info = queue->dev_info;
724 	int i, ret, steps;
725 	size_t *split_sizes;
726 	struct scatterlist **splits_in;
727 	struct scatterlist **splits_out = NULL;
728 	int *splits_in_nents;
729 	int *splits_out_nents = NULL;
730 	struct sec_request_el *el, *temp;
731 	bool split = skreq->src != skreq->dst;
732 
733 	mutex_init(&sec_req->lock);
734 	sec_req->req_base = &skreq->base;
735 	sec_req->err = 0;
736 	/* SGL mapping out here to allow us to break it up as necessary */
737 	sec_req->len_in = sg_nents(skreq->src);
738 
739 	ret = sec_alg_alloc_and_calc_split_sizes(skreq->cryptlen, &split_sizes,
740 						 &steps);
741 	if (ret)
742 		return ret;
743 	sec_req->num_elements = steps;
744 	ret = sec_map_and_split_sg(skreq->src, split_sizes, steps, &splits_in,
745 				   &splits_in_nents, sec_req->len_in,
746 				   info->dev);
747 	if (ret)
748 		goto err_free_split_sizes;
749 
750 	if (split) {
751 		sec_req->len_out = sg_nents(skreq->dst);
752 		ret = sec_map_and_split_sg(skreq->dst, split_sizes, steps,
753 					   &splits_out, &splits_out_nents,
754 					   sec_req->len_out, info->dev);
755 		if (ret)
756 			goto err_unmap_in_sg;
757 	}
758 	/* Shared info stored in seq_req - applies to all BDs */
759 	sec_req->tfm_ctx = ctx;
760 	sec_req->cb = sec_skcipher_alg_callback;
761 	INIT_LIST_HEAD(&sec_req->elements);
762 
763 	/*
764 	 * Future optimization.
765 	 * In the chaining case we can't use a dma pool bounce buffer
766 	 * but in the case where we know there is no chaining we can
767 	 */
768 	if (crypto_skcipher_ivsize(atfm)) {
769 		sec_req->dma_iv = dma_map_single(info->dev, skreq->iv,
770 						 crypto_skcipher_ivsize(atfm),
771 						 DMA_TO_DEVICE);
772 		if (dma_mapping_error(info->dev, sec_req->dma_iv)) {
773 			ret = -ENOMEM;
774 			goto err_unmap_out_sg;
775 		}
776 	}
777 
778 	/* Set them all up then queue - cleaner error handling. */
779 	for (i = 0; i < steps; i++) {
780 		el = sec_alg_alloc_and_fill_el(&ctx->req_template,
781 					       encrypt ? 1 : 0,
782 					       split_sizes[i],
783 					       skreq->src != skreq->dst,
784 					       splits_in[i], splits_in_nents[i],
785 					       split ? splits_out[i] : NULL,
786 					       split ? splits_out_nents[i] : 0,
787 					       info);
788 		if (IS_ERR(el)) {
789 			ret = PTR_ERR(el);
790 			goto err_free_elements;
791 		}
792 		el->req.cipher_iv_addr_lo = lower_32_bits(sec_req->dma_iv);
793 		el->req.cipher_iv_addr_hi = upper_32_bits(sec_req->dma_iv);
794 		el->sec_req = sec_req;
795 		list_add_tail(&el->head, &sec_req->elements);
796 	}
797 
798 	/*
799 	 * Only attempt to queue if the whole lot can fit in the queue -
800 	 * we can't successfully cleanup after a partial queing so this
801 	 * must succeed or fail atomically.
802 	 *
803 	 * Big hammer test of both software and hardware queues - could be
804 	 * more refined but this is unlikely to happen so no need.
805 	 */
806 
807 	/* Grab a big lock for a long time to avoid concurrency issues */
808 	mutex_lock(&queue->queuelock);
809 
810 	/*
811 	 * Can go on to queue if we have space in either:
812 	 * 1) The hardware queue and no software queue
813 	 * 2) The software queue
814 	 * AND there is nothing in the backlog.  If there is backlog we
815 	 * have to only queue to the backlog queue and return busy.
816 	 */
817 	if ((!sec_queue_can_enqueue(queue, steps) &&
818 	     (!queue->havesoftqueue ||
819 	      kfifo_avail(&queue->softqueue) > steps)) ||
820 	    !list_empty(&ctx->backlog)) {
821 		ret = -EBUSY;
822 		if ((skreq->base.flags & CRYPTO_TFM_REQ_MAY_BACKLOG)) {
823 			list_add_tail(&sec_req->backlog_head, &ctx->backlog);
824 			mutex_unlock(&queue->queuelock);
825 			goto out;
826 		}
827 
828 		mutex_unlock(&queue->queuelock);
829 		goto err_free_elements;
830 	}
831 	ret = sec_send_request(sec_req, queue);
832 	mutex_unlock(&queue->queuelock);
833 	if (ret)
834 		goto err_free_elements;
835 
836 	ret = -EINPROGRESS;
837 out:
838 	/* Cleanup - all elements in pointer arrays have been copied */
839 	kfree(splits_in_nents);
840 	kfree(splits_in);
841 	kfree(splits_out_nents);
842 	kfree(splits_out);
843 	kfree(split_sizes);
844 	return ret;
845 
846 err_free_elements:
847 	list_for_each_entry_safe(el, temp, &sec_req->elements, head) {
848 		list_del(&el->head);
849 		sec_alg_free_el(el, info);
850 	}
851 	if (crypto_skcipher_ivsize(atfm))
852 		dma_unmap_single(info->dev, sec_req->dma_iv,
853 				 crypto_skcipher_ivsize(atfm),
854 				 DMA_BIDIRECTIONAL);
855 err_unmap_out_sg:
856 	if (split)
857 		sec_unmap_sg_on_err(skreq->dst, steps, splits_out,
858 				    splits_out_nents, sec_req->len_out,
859 				    info->dev);
860 err_unmap_in_sg:
861 	sec_unmap_sg_on_err(skreq->src, steps, splits_in, splits_in_nents,
862 			    sec_req->len_in, info->dev);
863 err_free_split_sizes:
864 	kfree(split_sizes);
865 
866 	return ret;
867 }
868 
869 static int sec_alg_skcipher_encrypt(struct skcipher_request *req)
870 {
871 	return sec_alg_skcipher_crypto(req, true);
872 }
873 
874 static int sec_alg_skcipher_decrypt(struct skcipher_request *req)
875 {
876 	return sec_alg_skcipher_crypto(req, false);
877 }
878 
879 static int sec_alg_skcipher_init(struct crypto_skcipher *tfm)
880 {
881 	struct sec_alg_tfm_ctx *ctx = crypto_skcipher_ctx(tfm);
882 
883 	mutex_init(&ctx->lock);
884 	INIT_LIST_HEAD(&ctx->backlog);
885 	crypto_skcipher_set_reqsize(tfm, sizeof(struct sec_request));
886 
887 	ctx->queue = sec_queue_alloc_start_safe();
888 	if (IS_ERR(ctx->queue))
889 		return PTR_ERR(ctx->queue);
890 
891 	mutex_init(&ctx->queue->queuelock);
892 	ctx->queue->havesoftqueue = false;
893 
894 	return 0;
895 }
896 
897 static void sec_alg_skcipher_exit(struct crypto_skcipher *tfm)
898 {
899 	struct sec_alg_tfm_ctx *ctx = crypto_skcipher_ctx(tfm);
900 	struct device *dev = ctx->queue->dev_info->dev;
901 
902 	if (ctx->key) {
903 		memzero_explicit(ctx->key, SEC_MAX_CIPHER_KEY);
904 		dma_free_coherent(dev, SEC_MAX_CIPHER_KEY, ctx->key,
905 				  ctx->pkey);
906 	}
907 	sec_queue_stop_release(ctx->queue);
908 }
909 
910 static int sec_alg_skcipher_init_with_queue(struct crypto_skcipher *tfm)
911 {
912 	struct sec_alg_tfm_ctx *ctx = crypto_skcipher_ctx(tfm);
913 	int ret;
914 
915 	ret = sec_alg_skcipher_init(tfm);
916 	if (ret)
917 		return ret;
918 
919 	INIT_KFIFO(ctx->queue->softqueue);
920 	ret = kfifo_alloc(&ctx->queue->softqueue, 512, GFP_KERNEL);
921 	if (ret) {
922 		sec_alg_skcipher_exit(tfm);
923 		return ret;
924 	}
925 	ctx->queue->havesoftqueue = true;
926 
927 	return 0;
928 }
929 
930 static void sec_alg_skcipher_exit_with_queue(struct crypto_skcipher *tfm)
931 {
932 	struct sec_alg_tfm_ctx *ctx = crypto_skcipher_ctx(tfm);
933 
934 	kfifo_free(&ctx->queue->softqueue);
935 	sec_alg_skcipher_exit(tfm);
936 }
937 
938 static struct skcipher_alg sec_algs[] = {
939 	{
940 		.base = {
941 			.cra_name = "ecb(aes)",
942 			.cra_driver_name = "hisi_sec_aes_ecb",
943 			.cra_priority = 4001,
944 			.cra_flags = CRYPTO_ALG_ASYNC,
945 			.cra_blocksize = AES_BLOCK_SIZE,
946 			.cra_ctxsize = sizeof(struct sec_alg_tfm_ctx),
947 			.cra_alignmask = 0,
948 			.cra_module = THIS_MODULE,
949 		},
950 		.init = sec_alg_skcipher_init,
951 		.exit = sec_alg_skcipher_exit,
952 		.setkey = sec_alg_skcipher_setkey_aes_ecb,
953 		.decrypt = sec_alg_skcipher_decrypt,
954 		.encrypt = sec_alg_skcipher_encrypt,
955 		.min_keysize = AES_MIN_KEY_SIZE,
956 		.max_keysize = AES_MAX_KEY_SIZE,
957 		.ivsize = 0,
958 	}, {
959 		.base = {
960 			.cra_name = "cbc(aes)",
961 			.cra_driver_name = "hisi_sec_aes_cbc",
962 			.cra_priority = 4001,
963 			.cra_flags = CRYPTO_ALG_ASYNC,
964 			.cra_blocksize = AES_BLOCK_SIZE,
965 			.cra_ctxsize = sizeof(struct sec_alg_tfm_ctx),
966 			.cra_alignmask = 0,
967 			.cra_module = THIS_MODULE,
968 		},
969 		.init = sec_alg_skcipher_init_with_queue,
970 		.exit = sec_alg_skcipher_exit_with_queue,
971 		.setkey = sec_alg_skcipher_setkey_aes_cbc,
972 		.decrypt = sec_alg_skcipher_decrypt,
973 		.encrypt = sec_alg_skcipher_encrypt,
974 		.min_keysize = AES_MIN_KEY_SIZE,
975 		.max_keysize = AES_MAX_KEY_SIZE,
976 		.ivsize = AES_BLOCK_SIZE,
977 	}, {
978 		.base = {
979 			.cra_name = "ctr(aes)",
980 			.cra_driver_name = "hisi_sec_aes_ctr",
981 			.cra_priority = 4001,
982 			.cra_flags = CRYPTO_ALG_ASYNC,
983 			.cra_blocksize = AES_BLOCK_SIZE,
984 			.cra_ctxsize = sizeof(struct sec_alg_tfm_ctx),
985 			.cra_alignmask = 0,
986 			.cra_module = THIS_MODULE,
987 		},
988 		.init = sec_alg_skcipher_init_with_queue,
989 		.exit = sec_alg_skcipher_exit_with_queue,
990 		.setkey = sec_alg_skcipher_setkey_aes_ctr,
991 		.decrypt = sec_alg_skcipher_decrypt,
992 		.encrypt = sec_alg_skcipher_encrypt,
993 		.min_keysize = AES_MIN_KEY_SIZE,
994 		.max_keysize = AES_MAX_KEY_SIZE,
995 		.ivsize = AES_BLOCK_SIZE,
996 	}, {
997 		.base = {
998 			.cra_name = "xts(aes)",
999 			.cra_driver_name = "hisi_sec_aes_xts",
1000 			.cra_priority = 4001,
1001 			.cra_flags = CRYPTO_ALG_ASYNC,
1002 			.cra_blocksize = AES_BLOCK_SIZE,
1003 			.cra_ctxsize = sizeof(struct sec_alg_tfm_ctx),
1004 			.cra_alignmask = 0,
1005 			.cra_module = THIS_MODULE,
1006 		},
1007 		.init = sec_alg_skcipher_init,
1008 		.exit = sec_alg_skcipher_exit,
1009 		.setkey = sec_alg_skcipher_setkey_aes_xts,
1010 		.decrypt = sec_alg_skcipher_decrypt,
1011 		.encrypt = sec_alg_skcipher_encrypt,
1012 		.min_keysize = 2 * AES_MIN_KEY_SIZE,
1013 		.max_keysize = 2 * AES_MAX_KEY_SIZE,
1014 		.ivsize = AES_BLOCK_SIZE,
1015 	}, {
1016 	/* Unable to find any test vectors so untested */
1017 		.base = {
1018 			.cra_name = "ecb(des)",
1019 			.cra_driver_name = "hisi_sec_des_ecb",
1020 			.cra_priority = 4001,
1021 			.cra_flags = CRYPTO_ALG_ASYNC,
1022 			.cra_blocksize = DES_BLOCK_SIZE,
1023 			.cra_ctxsize = sizeof(struct sec_alg_tfm_ctx),
1024 			.cra_alignmask = 0,
1025 			.cra_module = THIS_MODULE,
1026 		},
1027 		.init = sec_alg_skcipher_init,
1028 		.exit = sec_alg_skcipher_exit,
1029 		.setkey = sec_alg_skcipher_setkey_des_ecb,
1030 		.decrypt = sec_alg_skcipher_decrypt,
1031 		.encrypt = sec_alg_skcipher_encrypt,
1032 		.min_keysize = DES_KEY_SIZE,
1033 		.max_keysize = DES_KEY_SIZE,
1034 		.ivsize = 0,
1035 	}, {
1036 		.base = {
1037 			.cra_name = "cbc(des)",
1038 			.cra_driver_name = "hisi_sec_des_cbc",
1039 			.cra_priority = 4001,
1040 			.cra_flags = CRYPTO_ALG_ASYNC,
1041 			.cra_blocksize = DES_BLOCK_SIZE,
1042 			.cra_ctxsize = sizeof(struct sec_alg_tfm_ctx),
1043 			.cra_alignmask = 0,
1044 			.cra_module = THIS_MODULE,
1045 		},
1046 		.init = sec_alg_skcipher_init_with_queue,
1047 		.exit = sec_alg_skcipher_exit_with_queue,
1048 		.setkey = sec_alg_skcipher_setkey_des_cbc,
1049 		.decrypt = sec_alg_skcipher_decrypt,
1050 		.encrypt = sec_alg_skcipher_encrypt,
1051 		.min_keysize = DES_KEY_SIZE,
1052 		.max_keysize = DES_KEY_SIZE,
1053 		.ivsize = DES_BLOCK_SIZE,
1054 	}, {
1055 		.base = {
1056 			.cra_name = "cbc(des3_ede)",
1057 			.cra_driver_name = "hisi_sec_3des_cbc",
1058 			.cra_priority = 4001,
1059 			.cra_flags = CRYPTO_ALG_ASYNC,
1060 			.cra_blocksize = DES3_EDE_BLOCK_SIZE,
1061 			.cra_ctxsize = sizeof(struct sec_alg_tfm_ctx),
1062 			.cra_alignmask = 0,
1063 			.cra_module = THIS_MODULE,
1064 		},
1065 		.init = sec_alg_skcipher_init_with_queue,
1066 		.exit = sec_alg_skcipher_exit_with_queue,
1067 		.setkey = sec_alg_skcipher_setkey_3des_cbc,
1068 		.decrypt = sec_alg_skcipher_decrypt,
1069 		.encrypt = sec_alg_skcipher_encrypt,
1070 		.min_keysize = DES3_EDE_KEY_SIZE,
1071 		.max_keysize = DES3_EDE_KEY_SIZE,
1072 		.ivsize = DES3_EDE_BLOCK_SIZE,
1073 	}, {
1074 		.base = {
1075 			.cra_name = "ecb(des3_ede)",
1076 			.cra_driver_name = "hisi_sec_3des_ecb",
1077 			.cra_priority = 4001,
1078 			.cra_flags = CRYPTO_ALG_ASYNC,
1079 			.cra_blocksize = DES3_EDE_BLOCK_SIZE,
1080 			.cra_ctxsize = sizeof(struct sec_alg_tfm_ctx),
1081 			.cra_alignmask = 0,
1082 			.cra_module = THIS_MODULE,
1083 		},
1084 		.init = sec_alg_skcipher_init,
1085 		.exit = sec_alg_skcipher_exit,
1086 		.setkey = sec_alg_skcipher_setkey_3des_ecb,
1087 		.decrypt = sec_alg_skcipher_decrypt,
1088 		.encrypt = sec_alg_skcipher_encrypt,
1089 		.min_keysize = DES3_EDE_KEY_SIZE,
1090 		.max_keysize = DES3_EDE_KEY_SIZE,
1091 		.ivsize = 0,
1092 	}
1093 };
1094 
1095 int sec_algs_register(void)
1096 {
1097 	int ret = 0;
1098 
1099 	mutex_lock(&algs_lock);
1100 	if (++active_devs != 1)
1101 		goto unlock;
1102 
1103 	ret = crypto_register_skciphers(sec_algs, ARRAY_SIZE(sec_algs));
1104 	if (ret)
1105 		--active_devs;
1106 unlock:
1107 	mutex_unlock(&algs_lock);
1108 
1109 	return ret;
1110 }
1111 
1112 void sec_algs_unregister(void)
1113 {
1114 	mutex_lock(&algs_lock);
1115 	if (--active_devs != 0)
1116 		goto unlock;
1117 	crypto_unregister_skciphers(sec_algs, ARRAY_SIZE(sec_algs));
1118 
1119 unlock:
1120 	mutex_unlock(&algs_lock);
1121 }
1122