mv_cesa.c 29.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
/*
 * Support for Marvell's crypto engine which can be found on some Orion5X
 * boards.
 *
 * Author: Sebastian Andrzej Siewior < sebastian at breakpoint dot cc >
 * License: GPLv2
 *
 */
#include <crypto/aes.h>
#include <crypto/algapi.h>
#include <linux/crypto.h>
12
#include <linux/genalloc.h>
13 14 15 16 17
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/kthread.h>
#include <linux/platform_device.h>
#include <linux/scatterlist.h>
18
#include <linux/slab.h>
19
#include <linux/module.h>
20
#include <linux/clk.h>
21 22
#include <crypto/internal/hash.h>
#include <crypto/sha.h>
23 24 25
#include <linux/of.h>
#include <linux/of_platform.h>
#include <linux/of_irq.h>
26 27

#include "mv_cesa.h"
28 29 30

#define MV_CESA	"MV-CESA:"
#define MAX_HW_HASH_SIZE	0xFFFF
31
#define MV_CESA_EXPIRE		500 /* msec */
32

33 34
#define MV_CESA_DEFAULT_SRAM_SIZE	2048

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
/*
 * STM:
 *   /---------------------------------------\
 *   |					     | request complete
 *  \./					     |
 * IDLE -> new request -> BUSY -> done -> DEQUEUE
 *                         /°\               |
 *			    |		     | more scatter entries
 *			    \________________/
 */
enum engine_status {
	ENGINE_IDLE,
	ENGINE_BUSY,
	ENGINE_W_DEQUEUE,
};

/**
 * struct req_progress - used for every crypt request
 * @src_sg_it:		sg iterator for src
 * @dst_sg_it:		sg iterator for dst
 * @sg_src_left:	bytes left in src to process (scatter list)
 * @src_start:		offset to add to src start position (scatter list)
57
 * @crypt_len:		length of current hw crypt/hash process
58
 * @hw_nbytes:		total bytes to process in hw for this request
59
 * @copy_back:		whether to copy data back (crypt) or not (hash)
60 61
 * @sg_dst_left:	bytes left dst to process in this scatter list
 * @dst_start:		offset to add to dst start position (scatter list)
62
 * @hw_processed_bytes:	number of bytes processed by hw (request).
63 64 65 66 67 68 69 70
 *
 * sg helper are used to iterate over the scatterlist. Since the size of the
 * SRAM may be less than the scatter size, this struct struct is used to keep
 * track of progress within current scatterlist.
 */
struct req_progress {
	struct sg_mapping_iter src_sg_it;
	struct sg_mapping_iter dst_sg_it;
71 72
	void (*complete) (void);
	void (*process) (int is_first);
73 74 75 76 77

	/* src mostly */
	int sg_src_left;
	int src_start;
	int crypt_len;
78
	int hw_nbytes;
79
	/* dst mostly */
80
	int copy_back;
81 82
	int sg_dst_left;
	int dst_start;
83
	int hw_processed_bytes;
84 85 86 87 88
};

struct crypto_priv {
	void __iomem *reg;
	void __iomem *sram;
89 90
	struct gen_pool *sram_pool;
	dma_addr_t sram_dma;
91
	int irq;
92
	struct clk *clk;
93 94 95 96 97 98
	struct task_struct *queue_th;

	/* the lock protects queue and eng_st */
	spinlock_t lock;
	struct crypto_queue queue;
	enum engine_status eng_st;
99
	struct timer_list completion_timer;
100
	struct crypto_async_request *cur_req;
101 102 103
	struct req_progress p;
	int max_req_size;
	int sram_size;
104 105
	int has_sha1;
	int has_hmac_sha1;
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
};

static struct crypto_priv *cpg;

struct mv_ctx {
	u8 aes_enc_key[AES_KEY_LEN];
	u32 aes_dec_key[8];
	int key_len;
	u32 need_calc_aes_dkey;
};

enum crypto_op {
	COP_AES_ECB,
	COP_AES_CBC,
};

struct mv_req_ctx {
	enum crypto_op op;
	int decrypt;
};

127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
enum hash_op {
	COP_SHA1,
	COP_HMAC_SHA1
};

struct mv_tfm_hash_ctx {
	struct crypto_shash *fallback;
	struct crypto_shash *base_hash;
	u32 ivs[2 * SHA1_DIGEST_SIZE / 4];
	int count_add;
	enum hash_op op;
};

struct mv_req_hash_ctx {
	u64 count;
	u32 state[SHA1_DIGEST_SIZE / 4];
	u8 buffer[SHA1_BLOCK_SIZE];
	int first_hash;		/* marks that we don't have previous state */
	int last_chunk;		/* marks that this is the 'final' request */
	int extra_bytes;	/* unprocessed bytes in buffer */
	enum hash_op op;
	int count_add;
};

151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
static void mv_completion_timer_callback(unsigned long unused)
{
	int active = readl(cpg->reg + SEC_ACCEL_CMD) & SEC_CMD_EN_SEC_ACCL0;

	printk(KERN_ERR MV_CESA
	       "completion timer expired (CESA %sactive), cleaning up.\n",
	       active ? "" : "in");

	del_timer(&cpg->completion_timer);
	writel(SEC_CMD_DISABLE_SEC, cpg->reg + SEC_ACCEL_CMD);
	while(readl(cpg->reg + SEC_ACCEL_CMD) & SEC_CMD_DISABLE_SEC)
		printk(KERN_INFO MV_CESA "%s: waiting for engine finishing\n", __func__);
	cpg->eng_st = ENGINE_W_DEQUEUE;
	wake_up_process(cpg->queue_th);
}

static void mv_setup_timer(void)
{
	setup_timer(&cpg->completion_timer, &mv_completion_timer_callback, 0);
	mod_timer(&cpg->completion_timer,
			jiffies + msecs_to_jiffies(MV_CESA_EXPIRE));
}

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
static void compute_aes_dec_key(struct mv_ctx *ctx)
{
	struct crypto_aes_ctx gen_aes_key;
	int key_pos;

	if (!ctx->need_calc_aes_dkey)
		return;

	crypto_aes_expand_key(&gen_aes_key, ctx->aes_enc_key, ctx->key_len);

	key_pos = ctx->key_len + 24;
	memcpy(ctx->aes_dec_key, &gen_aes_key.key_enc[key_pos], 4 * 4);
	switch (ctx->key_len) {
	case AES_KEYSIZE_256:
		key_pos -= 2;
		/* fall */
	case AES_KEYSIZE_192:
		key_pos -= 2;
		memcpy(&ctx->aes_dec_key[4], &gen_aes_key.key_enc[key_pos],
				4 * 4);
		break;
	}
	ctx->need_calc_aes_dkey = 0;
}

static int mv_setkey_aes(struct crypto_ablkcipher *cipher, const u8 *key,
		unsigned int len)
{
	struct crypto_tfm *tfm = crypto_ablkcipher_tfm(cipher);
	struct mv_ctx *ctx = crypto_tfm_ctx(tfm);

	switch (len) {
	case AES_KEYSIZE_128:
	case AES_KEYSIZE_192:
	case AES_KEYSIZE_256:
		break;
	default:
		crypto_ablkcipher_set_flags(cipher, CRYPTO_TFM_RES_BAD_KEY_LEN);
		return -EINVAL;
	}
	ctx->key_len = len;
	ctx->need_calc_aes_dkey = 1;

	memcpy(ctx->aes_enc_key, key, AES_KEY_LEN);
	return 0;
}

221
static void copy_src_to_buf(struct req_progress *p, char *dbuf, int len)
222 223
{
	int ret;
224
	void *sbuf;
225
	int copy_len;
226

227
	while (len) {
228 229 230 231 232 233
		if (!p->sg_src_left) {
			ret = sg_miter_next(&p->src_sg_it);
			BUG_ON(!ret);
			p->sg_src_left = p->src_sg_it.length;
			p->src_start = 0;
		}
234

235 236
		sbuf = p->src_sg_it.addr + p->src_start;

237 238 239 240 241 242 243 244
		copy_len = min(p->sg_src_left, len);
		memcpy(dbuf, sbuf, copy_len);

		p->src_start += copy_len;
		p->sg_src_left -= copy_len;

		len -= copy_len;
		dbuf += copy_len;
245 246
	}
}
247

248
static void setup_data_in(void)
249 250
{
	struct req_progress *p = &cpg->p;
251
	int data_in_sram =
252
	    min(p->hw_nbytes - p->hw_processed_bytes, cpg->max_req_size);
253 254 255
	copy_src_to_buf(p, cpg->sram + SRAM_DATA_IN_START + p->crypt_len,
			data_in_sram - p->crypt_len);
	p->crypt_len = data_in_sram;
256 257 258 259
}

static void mv_process_current_q(int first_block)
{
260
	struct ablkcipher_request *req = ablkcipher_request_cast(cpg->cur_req);
261 262 263 264 265 266 267 268 269
	struct mv_ctx *ctx = crypto_tfm_ctx(req->base.tfm);
	struct mv_req_ctx *req_ctx = ablkcipher_request_ctx(req);
	struct sec_accel_config op;

	switch (req_ctx->op) {
	case COP_AES_ECB:
		op.config = CFG_OP_CRYPT_ONLY | CFG_ENCM_AES | CFG_ENC_MODE_ECB;
		break;
	case COP_AES_CBC:
270
	default:
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
		op.config = CFG_OP_CRYPT_ONLY | CFG_ENCM_AES | CFG_ENC_MODE_CBC;
		op.enc_iv = ENC_IV_POINT(SRAM_DATA_IV) |
			ENC_IV_BUF_POINT(SRAM_DATA_IV_BUF);
		if (first_block)
			memcpy(cpg->sram + SRAM_DATA_IV, req->info, 16);
		break;
	}
	if (req_ctx->decrypt) {
		op.config |= CFG_DIR_DEC;
		memcpy(cpg->sram + SRAM_DATA_KEY_P, ctx->aes_dec_key,
				AES_KEY_LEN);
	} else {
		op.config |= CFG_DIR_ENC;
		memcpy(cpg->sram + SRAM_DATA_KEY_P, ctx->aes_enc_key,
				AES_KEY_LEN);
	}

	switch (ctx->key_len) {
	case AES_KEYSIZE_128:
		op.config |= CFG_AES_LEN_128;
		break;
	case AES_KEYSIZE_192:
		op.config |= CFG_AES_LEN_192;
		break;
	case AES_KEYSIZE_256:
		op.config |= CFG_AES_LEN_256;
		break;
	}
	op.enc_p = ENC_P_SRC(SRAM_DATA_IN_START) |
		ENC_P_DST(SRAM_DATA_OUT_START);
	op.enc_key_p = SRAM_DATA_KEY_P;

303
	setup_data_in();
304 305 306 307 308
	op.enc_len = cpg->p.crypt_len;
	memcpy(cpg->sram + SRAM_CONFIG, &op,
			sizeof(struct sec_accel_config));

	/* GO */
309
	mv_setup_timer();
310 311 312 313 314
	writel(SEC_CMD_EN_SEC_ACCL0, cpg->reg + SEC_ACCEL_CMD);
}

static void mv_crypto_algo_completion(void)
{
315
	struct ablkcipher_request *req = ablkcipher_request_cast(cpg->cur_req);
316 317
	struct mv_req_ctx *req_ctx = ablkcipher_request_ctx(req);

318 319 320
	sg_miter_stop(&cpg->p.src_sg_it);
	sg_miter_stop(&cpg->p.dst_sg_it);

321 322 323 324 325 326
	if (req_ctx->op != COP_AES_CBC)
		return ;

	memcpy(req->info, cpg->sram + SRAM_DATA_IV_BUF, 16);
}

327 328 329
static void mv_process_hash_current(int first_block)
{
	struct ahash_request *req = ahash_request_cast(cpg->cur_req);
330
	const struct mv_tfm_hash_ctx *tfm_ctx = crypto_tfm_ctx(req->base.tfm);
331 332 333 334 335 336 337 338 339 340 341 342
	struct mv_req_hash_ctx *req_ctx = ahash_request_ctx(req);
	struct req_progress *p = &cpg->p;
	struct sec_accel_config op = { 0 };
	int is_last;

	switch (req_ctx->op) {
	case COP_SHA1:
	default:
		op.config = CFG_OP_MAC_ONLY | CFG_MACM_SHA1;
		break;
	case COP_HMAC_SHA1:
		op.config = CFG_OP_MAC_ONLY | CFG_MACM_HMAC_SHA1;
343 344
		memcpy(cpg->sram + SRAM_HMAC_IV_IN,
				tfm_ctx->ivs, sizeof(tfm_ctx->ivs));
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
		break;
	}

	op.mac_src_p =
		MAC_SRC_DATA_P(SRAM_DATA_IN_START) | MAC_SRC_TOTAL_LEN((u32)
		req_ctx->
		count);

	setup_data_in();

	op.mac_digest =
		MAC_DIGEST_P(SRAM_DIGEST_BUF) | MAC_FRAG_LEN(p->crypt_len);
	op.mac_iv =
		MAC_INNER_IV_P(SRAM_HMAC_IV_IN) |
		MAC_OUTER_IV_P(SRAM_HMAC_IV_OUT);

	is_last = req_ctx->last_chunk
		&& (p->hw_processed_bytes + p->crypt_len >= p->hw_nbytes)
		&& (req_ctx->count <= MAX_HW_HASH_SIZE);
	if (req_ctx->first_hash) {
		if (is_last)
			op.config |= CFG_NOT_FRAG;
		else
			op.config |= CFG_FIRST_FRAG;

		req_ctx->first_hash = 0;
	} else {
		if (is_last)
			op.config |= CFG_LAST_FRAG;
		else
			op.config |= CFG_MID_FRAG;
376

377 378 379 380 381 382 383
		if (first_block) {
			writel(req_ctx->state[0], cpg->reg + DIGEST_INITIAL_VAL_A);
			writel(req_ctx->state[1], cpg->reg + DIGEST_INITIAL_VAL_B);
			writel(req_ctx->state[2], cpg->reg + DIGEST_INITIAL_VAL_C);
			writel(req_ctx->state[3], cpg->reg + DIGEST_INITIAL_VAL_D);
			writel(req_ctx->state[4], cpg->reg + DIGEST_INITIAL_VAL_E);
		}
384 385 386 387 388
	}

	memcpy(cpg->sram + SRAM_CONFIG, &op, sizeof(struct sec_accel_config));

	/* GO */
389
	mv_setup_timer();
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
	writel(SEC_CMD_EN_SEC_ACCL0, cpg->reg + SEC_ACCEL_CMD);
}

static inline int mv_hash_import_sha1_ctx(const struct mv_req_hash_ctx *ctx,
					  struct shash_desc *desc)
{
	int i;
	struct sha1_state shash_state;

	shash_state.count = ctx->count + ctx->count_add;
	for (i = 0; i < 5; i++)
		shash_state.state[i] = ctx->state[i];
	memcpy(shash_state.buffer, ctx->buffer, sizeof(shash_state.buffer));
	return crypto_shash_import(desc, &shash_state);
}

static int mv_hash_final_fallback(struct ahash_request *req)
{
	const struct mv_tfm_hash_ctx *tfm_ctx = crypto_tfm_ctx(req->base.tfm);
	struct mv_req_hash_ctx *req_ctx = ahash_request_ctx(req);
410
	SHASH_DESC_ON_STACK(shash, tfm_ctx->fallback);
411 412
	int rc;

413 414
	shash->tfm = tfm_ctx->fallback;
	shash->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
415
	if (unlikely(req_ctx->first_hash)) {
416 417
		crypto_shash_init(shash);
		crypto_shash_update(shash, req_ctx->buffer,
418 419 420 421
				    req_ctx->extra_bytes);
	} else {
		/* only SHA1 for now....
		 */
422
		rc = mv_hash_import_sha1_ctx(req_ctx, shash);
423 424 425
		if (rc)
			goto out;
	}
426
	rc = crypto_shash_final(shash, req->result);
427 428 429 430
out:
	return rc;
}

431 432 433 434 435 436 437 438 439
static void mv_save_digest_state(struct mv_req_hash_ctx *ctx)
{
	ctx->state[0] = readl(cpg->reg + DIGEST_INITIAL_VAL_A);
	ctx->state[1] = readl(cpg->reg + DIGEST_INITIAL_VAL_B);
	ctx->state[2] = readl(cpg->reg + DIGEST_INITIAL_VAL_C);
	ctx->state[3] = readl(cpg->reg + DIGEST_INITIAL_VAL_D);
	ctx->state[4] = readl(cpg->reg + DIGEST_INITIAL_VAL_E);
}

440 441 442 443 444 445 446 447 448 449 450 451 452 453
static void mv_hash_algo_completion(void)
{
	struct ahash_request *req = ahash_request_cast(cpg->cur_req);
	struct mv_req_hash_ctx *ctx = ahash_request_ctx(req);

	if (ctx->extra_bytes)
		copy_src_to_buf(&cpg->p, ctx->buffer, ctx->extra_bytes);
	sg_miter_stop(&cpg->p.src_sg_it);

	if (likely(ctx->last_chunk)) {
		if (likely(ctx->count <= MAX_HW_HASH_SIZE)) {
			memcpy(req->result, cpg->sram + SRAM_DIGEST_BUF,
			       crypto_ahash_digestsize(crypto_ahash_reqtfm
						       (req)));
454 455
		} else {
			mv_save_digest_state(ctx);
456
			mv_hash_final_fallback(req);
457
		}
458
	} else {
459
		mv_save_digest_state(ctx);
460 461 462
	}
}

463 464
static void dequeue_complete_req(void)
{
465
	struct crypto_async_request *req = cpg->cur_req;
466 467
	void *buf;
	int ret;
468
	cpg->p.hw_processed_bytes += cpg->p.crypt_len;
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
	if (cpg->p.copy_back) {
		int need_copy_len = cpg->p.crypt_len;
		int sram_offset = 0;
		do {
			int dst_copy;

			if (!cpg->p.sg_dst_left) {
				ret = sg_miter_next(&cpg->p.dst_sg_it);
				BUG_ON(!ret);
				cpg->p.sg_dst_left = cpg->p.dst_sg_it.length;
				cpg->p.dst_start = 0;
			}

			buf = cpg->p.dst_sg_it.addr;
			buf += cpg->p.dst_start;

			dst_copy = min(need_copy_len, cpg->p.sg_dst_left);

			memcpy(buf,
			       cpg->sram + SRAM_DATA_OUT_START + sram_offset,
			       dst_copy);
			sram_offset += dst_copy;
			cpg->p.sg_dst_left -= dst_copy;
			need_copy_len -= dst_copy;
			cpg->p.dst_start += dst_copy;
		} while (need_copy_len > 0);
	}
496

497
	cpg->p.crypt_len = 0;
498 499

	BUG_ON(cpg->eng_st != ENGINE_W_DEQUEUE);
500
	if (cpg->p.hw_processed_bytes < cpg->p.hw_nbytes) {
501 502
		/* process next scatter list entry */
		cpg->eng_st = ENGINE_BUSY;
503
		cpg->p.process(0);
504
	} else {
505
		cpg->p.complete();
506
		cpg->eng_st = ENGINE_IDLE;
507
		local_bh_disable();
508
		req->complete(req, 0);
509
		local_bh_enable();
510 511 512 513 514 515
	}
}

static int count_sgs(struct scatterlist *sl, unsigned int total_bytes)
{
	int i = 0;
516 517
	size_t cur_len;

518
	while (sl) {
519 520 521 522 523 524 525
		cur_len = sl[i].length;
		++i;
		if (total_bytes > cur_len)
			total_bytes -= cur_len;
		else
			break;
	}
526 527 528 529

	return i;
}

530
static void mv_start_new_crypt_req(struct ablkcipher_request *req)
531
{
532
	struct req_progress *p = &cpg->p;
533 534
	int num_sgs;

535 536 537
	cpg->cur_req = &req->base;
	memset(p, 0, sizeof(struct req_progress));
	p->hw_nbytes = req->nbytes;
538 539
	p->complete = mv_crypto_algo_completion;
	p->process = mv_process_current_q;
540
	p->copy_back = 1;
541 542

	num_sgs = count_sgs(req->src, req->nbytes);
543
	sg_miter_start(&p->src_sg_it, req->src, num_sgs, SG_MITER_FROM_SG);
544 545

	num_sgs = count_sgs(req->dst, req->nbytes);
546 547
	sg_miter_start(&p->dst_sg_it, req->dst, num_sgs, SG_MITER_TO_SG);

548 549 550
	mv_process_current_q(1);
}

551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
static void mv_start_new_hash_req(struct ahash_request *req)
{
	struct req_progress *p = &cpg->p;
	struct mv_req_hash_ctx *ctx = ahash_request_ctx(req);
	int num_sgs, hw_bytes, old_extra_bytes, rc;
	cpg->cur_req = &req->base;
	memset(p, 0, sizeof(struct req_progress));
	hw_bytes = req->nbytes + ctx->extra_bytes;
	old_extra_bytes = ctx->extra_bytes;

	ctx->extra_bytes = hw_bytes % SHA1_BLOCK_SIZE;
	if (ctx->extra_bytes != 0
	    && (!ctx->last_chunk || ctx->count > MAX_HW_HASH_SIZE))
		hw_bytes -= ctx->extra_bytes;
	else
		ctx->extra_bytes = 0;

	num_sgs = count_sgs(req->src, req->nbytes);
	sg_miter_start(&p->src_sg_it, req->src, num_sgs, SG_MITER_FROM_SG);

	if (hw_bytes) {
		p->hw_nbytes = hw_bytes;
		p->complete = mv_hash_algo_completion;
		p->process = mv_process_hash_current;

576 577 578 579 580 581
		if (unlikely(old_extra_bytes)) {
			memcpy(cpg->sram + SRAM_DATA_IN_START, ctx->buffer,
			       old_extra_bytes);
			p->crypt_len = old_extra_bytes;
		}

582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
		mv_process_hash_current(1);
	} else {
		copy_src_to_buf(p, ctx->buffer + old_extra_bytes,
				ctx->extra_bytes - old_extra_bytes);
		sg_miter_stop(&p->src_sg_it);
		if (ctx->last_chunk)
			rc = mv_hash_final_fallback(req);
		else
			rc = 0;
		cpg->eng_st = ENGINE_IDLE;
		local_bh_disable();
		req->base.complete(&req->base, rc);
		local_bh_enable();
	}
}

598 599 600 601 602
static int queue_manag(void *data)
{
	cpg->eng_st = ENGINE_IDLE;
	do {
		struct crypto_async_request *async_req = NULL;
603
		struct crypto_async_request *backlog = NULL;
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626

		__set_current_state(TASK_INTERRUPTIBLE);

		if (cpg->eng_st == ENGINE_W_DEQUEUE)
			dequeue_complete_req();

		spin_lock_irq(&cpg->lock);
		if (cpg->eng_st == ENGINE_IDLE) {
			backlog = crypto_get_backlog(&cpg->queue);
			async_req = crypto_dequeue_request(&cpg->queue);
			if (async_req) {
				BUG_ON(cpg->eng_st != ENGINE_IDLE);
				cpg->eng_st = ENGINE_BUSY;
			}
		}
		spin_unlock_irq(&cpg->lock);

		if (backlog) {
			backlog->complete(backlog, -EINPROGRESS);
			backlog = NULL;
		}

		if (async_req) {
627 628
			if (crypto_tfm_alg_type(async_req->tfm) !=
			    CRYPTO_ALG_TYPE_AHASH) {
629
				struct ablkcipher_request *req =
630
				    ablkcipher_request_cast(async_req);
631 632 633 634 635 636
				mv_start_new_crypt_req(req);
			} else {
				struct ahash_request *req =
				    ahash_request_cast(async_req);
				mv_start_new_hash_req(req);
			}
637 638 639 640 641 642 643 644 645
			async_req = NULL;
		}

		schedule();

	} while (!kthread_should_stop());
	return 0;
}

646
static int mv_handle_req(struct crypto_async_request *req)
647 648 649 650 651
{
	unsigned long flags;
	int ret;

	spin_lock_irqsave(&cpg->lock, flags);
652
	ret = crypto_enqueue_request(&cpg->queue, req);
653 654 655 656 657 658 659 660 661 662 663 664
	spin_unlock_irqrestore(&cpg->lock, flags);
	wake_up_process(cpg->queue_th);
	return ret;
}

static int mv_enc_aes_ecb(struct ablkcipher_request *req)
{
	struct mv_req_ctx *req_ctx = ablkcipher_request_ctx(req);

	req_ctx->op = COP_AES_ECB;
	req_ctx->decrypt = 0;

665
	return mv_handle_req(&req->base);
666 667 668 669 670 671 672 673 674 675 676
}

static int mv_dec_aes_ecb(struct ablkcipher_request *req)
{
	struct mv_ctx *ctx = crypto_tfm_ctx(req->base.tfm);
	struct mv_req_ctx *req_ctx = ablkcipher_request_ctx(req);

	req_ctx->op = COP_AES_ECB;
	req_ctx->decrypt = 1;

	compute_aes_dec_key(ctx);
677
	return mv_handle_req(&req->base);
678 679 680 681 682 683 684 685 686
}

static int mv_enc_aes_cbc(struct ablkcipher_request *req)
{
	struct mv_req_ctx *req_ctx = ablkcipher_request_ctx(req);

	req_ctx->op = COP_AES_CBC;
	req_ctx->decrypt = 0;

687
	return mv_handle_req(&req->base);
688 689 690 691 692 693 694 695 696 697 698
}

static int mv_dec_aes_cbc(struct ablkcipher_request *req)
{
	struct mv_ctx *ctx = crypto_tfm_ctx(req->base.tfm);
	struct mv_req_ctx *req_ctx = ablkcipher_request_ctx(req);

	req_ctx->op = COP_AES_CBC;
	req_ctx->decrypt = 1;

	compute_aes_dec_key(ctx);
699
	return mv_handle_req(&req->base);
700 701 702 703 704 705 706 707
}

static int mv_cra_init(struct crypto_tfm *tfm)
{
	tfm->crt_ablkcipher.reqsize = sizeof(struct mv_req_ctx);
	return 0;
}

708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
static void mv_init_hash_req_ctx(struct mv_req_hash_ctx *ctx, int op,
				 int is_last, unsigned int req_len,
				 int count_add)
{
	memset(ctx, 0, sizeof(*ctx));
	ctx->op = op;
	ctx->count = req_len;
	ctx->first_hash = 1;
	ctx->last_chunk = is_last;
	ctx->count_add = count_add;
}

static void mv_update_hash_req_ctx(struct mv_req_hash_ctx *ctx, int is_last,
				   unsigned req_len)
{
	ctx->last_chunk = is_last;
	ctx->count += req_len;
}

static int mv_hash_init(struct ahash_request *req)
{
	const struct mv_tfm_hash_ctx *tfm_ctx = crypto_tfm_ctx(req->base.tfm);
	mv_init_hash_req_ctx(ahash_request_ctx(req), tfm_ctx->op, 0, 0,
			     tfm_ctx->count_add);
	return 0;
}

static int mv_hash_update(struct ahash_request *req)
{
	if (!req->nbytes)
		return 0;

	mv_update_hash_req_ctx(ahash_request_ctx(req), 0, req->nbytes);
	return mv_handle_req(&req->base);
}

static int mv_hash_final(struct ahash_request *req)
{
	struct mv_req_hash_ctx *ctx = ahash_request_ctx(req);
747

748
	ahash_request_set_crypt(req, NULL, req->result, 0);
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
	mv_update_hash_req_ctx(ctx, 1, 0);
	return mv_handle_req(&req->base);
}

static int mv_hash_finup(struct ahash_request *req)
{
	mv_update_hash_req_ctx(ahash_request_ctx(req), 1, req->nbytes);
	return mv_handle_req(&req->base);
}

static int mv_hash_digest(struct ahash_request *req)
{
	const struct mv_tfm_hash_ctx *tfm_ctx = crypto_tfm_ctx(req->base.tfm);
	mv_init_hash_req_ctx(ahash_request_ctx(req), tfm_ctx->op, 1,
			     req->nbytes, tfm_ctx->count_add);
	return mv_handle_req(&req->base);
}

static void mv_hash_init_ivs(struct mv_tfm_hash_ctx *ctx, const void *istate,
			     const void *ostate)
{
	const struct sha1_state *isha1_state = istate, *osha1_state = ostate;
	int i;
	for (i = 0; i < 5; i++) {
		ctx->ivs[i] = cpu_to_be32(isha1_state->state[i]);
		ctx->ivs[i + 5] = cpu_to_be32(osha1_state->state[i]);
	}
}

static int mv_hash_setkey(struct crypto_ahash *tfm, const u8 * key,
			  unsigned int keylen)
{
	int rc;
	struct mv_tfm_hash_ctx *ctx = crypto_tfm_ctx(&tfm->base);
	int bs, ds, ss;

	if (!ctx->base_hash)
		return 0;

	rc = crypto_shash_setkey(ctx->fallback, key, keylen);
	if (rc)
		return rc;

	/* Can't see a way to extract the ipad/opad from the fallback tfm
	   so I'm basically copying code from the hmac module */
	bs = crypto_shash_blocksize(ctx->base_hash);
	ds = crypto_shash_digestsize(ctx->base_hash);
	ss = crypto_shash_statesize(ctx->base_hash);

	{
799 800
		SHASH_DESC_ON_STACK(shash, ctx->base_hash);

801 802 803 804
		unsigned int i;
		char ipad[ss];
		char opad[ss];

805 806
		shash->tfm = ctx->base_hash;
		shash->flags = crypto_shash_get_flags(ctx->base_hash) &
807 808 809 810 811 812
		    CRYPTO_TFM_REQ_MAY_SLEEP;

		if (keylen > bs) {
			int err;

			err =
813
			    crypto_shash_digest(shash, key, keylen, ipad);
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
			if (err)
				return err;

			keylen = ds;
		} else
			memcpy(ipad, key, keylen);

		memset(ipad + keylen, 0, bs - keylen);
		memcpy(opad, ipad, bs);

		for (i = 0; i < bs; i++) {
			ipad[i] ^= 0x36;
			opad[i] ^= 0x5c;
		}

829 830 831 832 833 834
		rc = crypto_shash_init(shash) ? :
		    crypto_shash_update(shash, ipad, bs) ? :
		    crypto_shash_export(shash, ipad) ? :
		    crypto_shash_init(shash) ? :
		    crypto_shash_update(shash, opad, bs) ? :
		    crypto_shash_export(shash, opad);
835 836 837 838 839 840 841 842 843 844 845

		if (rc == 0)
			mv_hash_init_ivs(ctx, ipad, opad);

		return rc;
	}
}

static int mv_cra_hash_init(struct crypto_tfm *tfm, const char *base_hash_name,
			    enum hash_op op, int count_add)
{
846
	const char *fallback_driver_name = crypto_tfm_alg_name(tfm);
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
	struct mv_tfm_hash_ctx *ctx = crypto_tfm_ctx(tfm);
	struct crypto_shash *fallback_tfm = NULL;
	struct crypto_shash *base_hash = NULL;
	int err = -ENOMEM;

	ctx->op = op;
	ctx->count_add = count_add;

	/* Allocate a fallback and abort if it failed. */
	fallback_tfm = crypto_alloc_shash(fallback_driver_name, 0,
					  CRYPTO_ALG_NEED_FALLBACK);
	if (IS_ERR(fallback_tfm)) {
		printk(KERN_WARNING MV_CESA
		       "Fallback driver '%s' could not be loaded!\n",
		       fallback_driver_name);
		err = PTR_ERR(fallback_tfm);
		goto out;
	}
	ctx->fallback = fallback_tfm;

	if (base_hash_name) {
		/* Allocate a hash to compute the ipad/opad of hmac. */
		base_hash = crypto_alloc_shash(base_hash_name, 0,
					       CRYPTO_ALG_NEED_FALLBACK);
		if (IS_ERR(base_hash)) {
			printk(KERN_WARNING MV_CESA
			       "Base driver '%s' could not be loaded!\n",
			       base_hash_name);
875
			err = PTR_ERR(base_hash);
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
			goto err_bad_base;
		}
	}
	ctx->base_hash = base_hash;

	crypto_ahash_set_reqsize(__crypto_ahash_cast(tfm),
				 sizeof(struct mv_req_hash_ctx) +
				 crypto_shash_descsize(ctx->fallback));
	return 0;
err_bad_base:
	crypto_free_shash(fallback_tfm);
out:
	return err;
}

static void mv_cra_hash_exit(struct crypto_tfm *tfm)
{
	struct mv_tfm_hash_ctx *ctx = crypto_tfm_ctx(tfm);

	crypto_free_shash(ctx->fallback);
	if (ctx->base_hash)
		crypto_free_shash(ctx->base_hash);
}

static int mv_cra_hash_sha1_init(struct crypto_tfm *tfm)
{
	return mv_cra_hash_init(tfm, NULL, COP_SHA1, 0);
}

static int mv_cra_hash_hmac_sha1_init(struct crypto_tfm *tfm)
{
	return mv_cra_hash_init(tfm, "sha1", COP_HMAC_SHA1, SHA1_BLOCK_SIZE);
}

910
static irqreturn_t crypto_int(int irq, void *priv)
911 912 913 914 915 916 917
{
	u32 val;

	val = readl(cpg->reg + SEC_ACCEL_INT_STATUS);
	if (!(val & SEC_INT_ACCEL0_DONE))
		return IRQ_NONE;

918 919 920 921
	if (!del_timer(&cpg->completion_timer)) {
		printk(KERN_WARNING MV_CESA
		       "got an interrupt but no pending timer?\n");
	}
922 923 924 925 926 927 928 929 930
	val &= ~SEC_INT_ACCEL0_DONE;
	writel(val, cpg->reg + FPGA_INT_STATUS);
	writel(val, cpg->reg + SEC_ACCEL_INT_STATUS);
	BUG_ON(cpg->eng_st != ENGINE_BUSY);
	cpg->eng_st = ENGINE_W_DEQUEUE;
	wake_up_process(cpg->queue_th);
	return IRQ_HANDLED;
}

931
static struct crypto_alg mv_aes_alg_ecb = {
932 933 934
	.cra_name		= "ecb(aes)",
	.cra_driver_name	= "mv-ecb-aes",
	.cra_priority	= 300,
935 936
	.cra_flags	= CRYPTO_ALG_TYPE_ABLKCIPHER |
			  CRYPTO_ALG_KERN_DRIVER_ONLY | CRYPTO_ALG_ASYNC,
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
	.cra_blocksize	= 16,
	.cra_ctxsize	= sizeof(struct mv_ctx),
	.cra_alignmask	= 0,
	.cra_type	= &crypto_ablkcipher_type,
	.cra_module	= THIS_MODULE,
	.cra_init	= mv_cra_init,
	.cra_u		= {
		.ablkcipher = {
			.min_keysize	=	AES_MIN_KEY_SIZE,
			.max_keysize	=	AES_MAX_KEY_SIZE,
			.setkey		=	mv_setkey_aes,
			.encrypt	=	mv_enc_aes_ecb,
			.decrypt	=	mv_dec_aes_ecb,
		},
	},
};

954
static struct crypto_alg mv_aes_alg_cbc = {
955 956 957
	.cra_name		= "cbc(aes)",
	.cra_driver_name	= "mv-cbc-aes",
	.cra_priority	= 300,
958 959
	.cra_flags	= CRYPTO_ALG_TYPE_ABLKCIPHER |
			  CRYPTO_ALG_KERN_DRIVER_ONLY | CRYPTO_ALG_ASYNC,
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
	.cra_blocksize	= AES_BLOCK_SIZE,
	.cra_ctxsize	= sizeof(struct mv_ctx),
	.cra_alignmask	= 0,
	.cra_type	= &crypto_ablkcipher_type,
	.cra_module	= THIS_MODULE,
	.cra_init	= mv_cra_init,
	.cra_u		= {
		.ablkcipher = {
			.ivsize		=	AES_BLOCK_SIZE,
			.min_keysize	=	AES_MIN_KEY_SIZE,
			.max_keysize	=	AES_MAX_KEY_SIZE,
			.setkey		=	mv_setkey_aes,
			.encrypt	=	mv_enc_aes_cbc,
			.decrypt	=	mv_dec_aes_cbc,
		},
	},
};

978
static struct ahash_alg mv_sha1_alg = {
979 980 981 982 983 984 985 986 987 988 989 990
	.init = mv_hash_init,
	.update = mv_hash_update,
	.final = mv_hash_final,
	.finup = mv_hash_finup,
	.digest = mv_hash_digest,
	.halg = {
		 .digestsize = SHA1_DIGEST_SIZE,
		 .base = {
			  .cra_name = "sha1",
			  .cra_driver_name = "mv-sha1",
			  .cra_priority = 300,
			  .cra_flags =
991 992
			  CRYPTO_ALG_ASYNC | CRYPTO_ALG_KERN_DRIVER_ONLY |
			  CRYPTO_ALG_NEED_FALLBACK,
993 994 995 996 997 998 999 1000 1001
			  .cra_blocksize = SHA1_BLOCK_SIZE,
			  .cra_ctxsize = sizeof(struct mv_tfm_hash_ctx),
			  .cra_init = mv_cra_hash_sha1_init,
			  .cra_exit = mv_cra_hash_exit,
			  .cra_module = THIS_MODULE,
			  }
		 }
};

1002
static struct ahash_alg mv_hmac_sha1_alg = {
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
	.init = mv_hash_init,
	.update = mv_hash_update,
	.final = mv_hash_final,
	.finup = mv_hash_finup,
	.digest = mv_hash_digest,
	.setkey = mv_hash_setkey,
	.halg = {
		 .digestsize = SHA1_DIGEST_SIZE,
		 .base = {
			  .cra_name = "hmac(sha1)",
			  .cra_driver_name = "mv-hmac-sha1",
			  .cra_priority = 300,
			  .cra_flags =
1016 1017
			  CRYPTO_ALG_ASYNC | CRYPTO_ALG_KERN_DRIVER_ONLY |
			  CRYPTO_ALG_NEED_FALLBACK,
1018 1019 1020 1021 1022 1023 1024 1025 1026
			  .cra_blocksize = SHA1_BLOCK_SIZE,
			  .cra_ctxsize = sizeof(struct mv_tfm_hash_ctx),
			  .cra_init = mv_cra_hash_hmac_sha1_init,
			  .cra_exit = mv_cra_hash_exit,
			  .cra_module = THIS_MODULE,
			  }
		 }
};

1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
static int mv_cesa_get_sram(struct platform_device *pdev,
			    struct crypto_priv *cp)
{
	struct resource *res;
	u32 sram_size = MV_CESA_DEFAULT_SRAM_SIZE;

	of_property_read_u32(pdev->dev.of_node, "marvell,crypto-sram-size",
			     &sram_size);

	cp->sram_size = sram_size;
1037
	cp->sram_pool = of_get_named_gen_pool(pdev->dev.of_node,
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
					      "marvell,crypto-srams", 0);
	if (cp->sram_pool) {
		cp->sram = gen_pool_dma_alloc(cp->sram_pool, sram_size,
					      &cp->sram_dma);
		if (cp->sram)
			return 0;

		return -ENOMEM;
	}

	res = platform_get_resource_byname(pdev, IORESOURCE_MEM,
					   "sram");
	if (!res || resource_size(res) < cp->sram_size)
		return -EINVAL;

	cp->sram = devm_ioremap_resource(&pdev->dev, res);
	if (IS_ERR(cp->sram))
		return PTR_ERR(cp->sram);

	return 0;
}

1060 1061 1062 1063 1064 1065 1066 1067
static int mv_probe(struct platform_device *pdev)
{
	struct crypto_priv *cp;
	struct resource *res;
	int irq;
	int ret;

	if (cpg) {
1068
		printk(KERN_ERR MV_CESA "Second crypto dev?\n");
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
		return -EEXIST;
	}

	res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "regs");
	if (!res)
		return -ENXIO;

	cp = kzalloc(sizeof(*cp), GFP_KERNEL);
	if (!cp)
		return -ENOMEM;

	spin_lock_init(&cp->lock);
	crypto_init_queue(&cp->queue, 50);
1082 1083 1084
	cp->reg = devm_ioremap_resource(&pdev->dev, res);
	if (IS_ERR(cp->reg)) {
		ret = PTR_ERR(cp->reg);
1085 1086 1087
		goto err;
	}

1088 1089
	ret = mv_cesa_get_sram(pdev, cp);
	if (ret)
1090
		goto err;
1091

1092 1093
	cp->max_req_size = cp->sram_size - SRAM_CFG_SPACE;

1094 1095 1096 1097
	if (pdev->dev.of_node)
		irq = irq_of_parse_and_map(pdev->dev.of_node, 0);
	else
		irq = platform_get_irq(pdev, 0);
1098 1099
	if (irq < 0 || irq == NO_IRQ) {
		ret = irq;
1100
		goto err;
1101 1102 1103 1104 1105 1106 1107 1108 1109
	}
	cp->irq = irq;

	platform_set_drvdata(pdev, cp);
	cpg = cp;

	cp->queue_th = kthread_run(queue_manag, cp, "mv_crypto");
	if (IS_ERR(cp->queue_th)) {
		ret = PTR_ERR(cp->queue_th);
1110
		goto err;
1111 1112
	}

1113
	ret = request_irq(irq, crypto_int, 0, dev_name(&pdev->dev),
1114 1115
			cp);
	if (ret)
1116
		goto err_thread;
1117

1118 1119 1120 1121 1122 1123
	/* Not all platforms can gate the clock, so it is not
	   an error if the clock does not exists. */
	cp->clk = clk_get(&pdev->dev, NULL);
	if (!IS_ERR(cp->clk))
		clk_prepare_enable(cp->clk);

1124
	writel(0, cpg->reg + SEC_ACCEL_INT_STATUS);
1125 1126
	writel(SEC_INT_ACCEL0_DONE, cpg->reg + SEC_ACCEL_INT_MASK);
	writel(SEC_CFG_STOP_DIG_ERR, cpg->reg + SEC_ACCEL_CFG);
1127
	writel(SRAM_CONFIG, cpg->reg + SEC_ACCEL_DESC_P0);
1128 1129

	ret = crypto_register_alg(&mv_aes_alg_ecb);
1130 1131 1132
	if (ret) {
		printk(KERN_WARNING MV_CESA
		       "Could not register aes-ecb driver\n");
1133
		goto err_irq;
1134
	}
1135 1136

	ret = crypto_register_alg(&mv_aes_alg_cbc);
1137 1138 1139
	if (ret) {
		printk(KERN_WARNING MV_CESA
		       "Could not register aes-cbc driver\n");
1140
		goto err_unreg_ecb;
1141
	}
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156

	ret = crypto_register_ahash(&mv_sha1_alg);
	if (ret == 0)
		cpg->has_sha1 = 1;
	else
		printk(KERN_WARNING MV_CESA "Could not register sha1 driver\n");

	ret = crypto_register_ahash(&mv_hmac_sha1_alg);
	if (ret == 0) {
		cpg->has_hmac_sha1 = 1;
	} else {
		printk(KERN_WARNING MV_CESA
		       "Could not register hmac-sha1 driver\n");
	}

1157 1158 1159
	return 0;
err_unreg_ecb:
	crypto_unregister_alg(&mv_aes_alg_ecb);
1160
err_irq:
1161
	free_irq(irq, cp);
1162 1163 1164 1165
	if (!IS_ERR(cp->clk)) {
		clk_disable_unprepare(cp->clk);
		clk_put(cp->clk);
	}
1166
err_thread:
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
	kthread_stop(cp->queue_th);
err:
	kfree(cp);
	cpg = NULL;
	return ret;
}

static int mv_remove(struct platform_device *pdev)
{
	struct crypto_priv *cp = platform_get_drvdata(pdev);

	crypto_unregister_alg(&mv_aes_alg_ecb);
	crypto_unregister_alg(&mv_aes_alg_cbc);
1180 1181 1182 1183
	if (cp->has_sha1)
		crypto_unregister_ahash(&mv_sha1_alg);
	if (cp->has_hmac_sha1)
		crypto_unregister_ahash(&mv_hmac_sha1_alg);
1184 1185 1186
	kthread_stop(cp->queue_th);
	free_irq(cp->irq, cp);
	memset(cp->sram, 0, cp->sram_size);
1187 1188 1189 1190 1191 1192

	if (!IS_ERR(cp->clk)) {
		clk_disable_unprepare(cp->clk);
		clk_put(cp->clk);
	}

1193 1194 1195 1196 1197
	kfree(cp);
	cpg = NULL;
	return 0;
}

1198 1199
static const struct of_device_id mv_cesa_of_match_table[] = {
	{ .compatible = "marvell,orion-crypto", },
1200 1201
	{ .compatible = "marvell,kirkwood-crypto", },
	{ .compatible = "marvell,dove-crypto", },
1202 1203 1204 1205
	{}
};
MODULE_DEVICE_TABLE(of, mv_cesa_of_match_table);

1206 1207
static struct platform_driver marvell_crypto = {
	.probe		= mv_probe,
1208
	.remove		= mv_remove,
1209 1210
	.driver		= {
		.name	= "mv_crypto",
1211
		.of_match_table = mv_cesa_of_match_table,
1212 1213 1214 1215
	},
};
MODULE_ALIAS("platform:mv_crypto");

1216
module_platform_driver(marvell_crypto);
1217 1218 1219 1220

MODULE_AUTHOR("Sebastian Andrzej Siewior <sebastian@breakpoint.cc>");
MODULE_DESCRIPTION("Support for Marvell's cryptographic engine");
MODULE_LICENSE("GPL");