xref: /openbmc/linux/drivers/crypto/caam/ctrl.c (revision f9834f18)
1 // SPDX-License-Identifier: GPL-2.0+
2 /* * CAAM control-plane driver backend
3  * Controller-level driver, kernel property detection, initialization
4  *
5  * Copyright 2008-2012 Freescale Semiconductor, Inc.
6  * Copyright 2018-2019 NXP
7  */
8 
9 #include <linux/device.h>
10 #include <linux/of_address.h>
11 #include <linux/of_irq.h>
12 #include <linux/sys_soc.h>
13 
14 #include "compat.h"
15 #include "regs.h"
16 #include "intern.h"
17 #include "jr.h"
18 #include "desc_constr.h"
19 #include "ctrl.h"
20 
21 bool caam_dpaa2;
22 EXPORT_SYMBOL(caam_dpaa2);
23 
24 #ifdef CONFIG_CAAM_QI
25 #include "qi.h"
26 #endif
27 
28 /*
29  * Descriptor to instantiate RNG State Handle 0 in normal mode and
30  * load the JDKEK, TDKEK and TDSK registers
31  */
32 static void build_instantiation_desc(u32 *desc, int handle, int do_sk)
33 {
34 	u32 *jump_cmd, op_flags;
35 
36 	init_job_desc(desc, 0);
37 
38 	op_flags = OP_TYPE_CLASS1_ALG | OP_ALG_ALGSEL_RNG |
39 			(handle << OP_ALG_AAI_SHIFT) | OP_ALG_AS_INIT;
40 
41 	/* INIT RNG in non-test mode */
42 	append_operation(desc, op_flags);
43 
44 	if (!handle && do_sk) {
45 		/*
46 		 * For SH0, Secure Keys must be generated as well
47 		 */
48 
49 		/* wait for done */
50 		jump_cmd = append_jump(desc, JUMP_CLASS_CLASS1);
51 		set_jump_tgt_here(desc, jump_cmd);
52 
53 		/*
54 		 * load 1 to clear written reg:
55 		 * resets the done interrrupt and returns the RNG to idle.
56 		 */
57 		append_load_imm_u32(desc, 1, LDST_SRCDST_WORD_CLRW);
58 
59 		/* Initialize State Handle  */
60 		append_operation(desc, OP_TYPE_CLASS1_ALG | OP_ALG_ALGSEL_RNG |
61 				 OP_ALG_AAI_RNG4_SK);
62 	}
63 
64 	append_jump(desc, JUMP_CLASS_CLASS1 | JUMP_TYPE_HALT);
65 }
66 
67 /* Descriptor for deinstantiation of State Handle 0 of the RNG block. */
68 static void build_deinstantiation_desc(u32 *desc, int handle)
69 {
70 	init_job_desc(desc, 0);
71 
72 	/* Uninstantiate State Handle 0 */
73 	append_operation(desc, OP_TYPE_CLASS1_ALG | OP_ALG_ALGSEL_RNG |
74 			 (handle << OP_ALG_AAI_SHIFT) | OP_ALG_AS_INITFINAL);
75 
76 	append_jump(desc, JUMP_CLASS_CLASS1 | JUMP_TYPE_HALT);
77 }
78 
79 /*
80  * run_descriptor_deco0 - runs a descriptor on DECO0, under direct control of
81  *			  the software (no JR/QI used).
82  * @ctrldev - pointer to device
83  * @status - descriptor status, after being run
84  *
85  * Return: - 0 if no error occurred
86  *	   - -ENODEV if the DECO couldn't be acquired
87  *	   - -EAGAIN if an error occurred while executing the descriptor
88  */
89 static inline int run_descriptor_deco0(struct device *ctrldev, u32 *desc,
90 					u32 *status)
91 {
92 	struct caam_drv_private *ctrlpriv = dev_get_drvdata(ctrldev);
93 	struct caam_ctrl __iomem *ctrl = ctrlpriv->ctrl;
94 	struct caam_deco __iomem *deco = ctrlpriv->deco;
95 	unsigned int timeout = 100000;
96 	u32 deco_dbg_reg, deco_state, flags;
97 	int i;
98 
99 
100 	if (ctrlpriv->virt_en == 1 ||
101 	    /*
102 	     * Apparently on i.MX8M{Q,M,N,P} it doesn't matter if virt_en == 1
103 	     * and the following steps should be performed regardless
104 	     */
105 	    of_machine_is_compatible("fsl,imx8mq") ||
106 	    of_machine_is_compatible("fsl,imx8mm") ||
107 	    of_machine_is_compatible("fsl,imx8mn") ||
108 	    of_machine_is_compatible("fsl,imx8mp")) {
109 		clrsetbits_32(&ctrl->deco_rsr, 0, DECORSR_JR0);
110 
111 		while (!(rd_reg32(&ctrl->deco_rsr) & DECORSR_VALID) &&
112 		       --timeout)
113 			cpu_relax();
114 
115 		timeout = 100000;
116 	}
117 
118 	clrsetbits_32(&ctrl->deco_rq, 0, DECORR_RQD0ENABLE);
119 
120 	while (!(rd_reg32(&ctrl->deco_rq) & DECORR_DEN0) &&
121 								 --timeout)
122 		cpu_relax();
123 
124 	if (!timeout) {
125 		dev_err(ctrldev, "failed to acquire DECO 0\n");
126 		clrsetbits_32(&ctrl->deco_rq, DECORR_RQD0ENABLE, 0);
127 		return -ENODEV;
128 	}
129 
130 	for (i = 0; i < desc_len(desc); i++)
131 		wr_reg32(&deco->descbuf[i], caam32_to_cpu(*(desc + i)));
132 
133 	flags = DECO_JQCR_WHL;
134 	/*
135 	 * If the descriptor length is longer than 4 words, then the
136 	 * FOUR bit in JRCTRL register must be set.
137 	 */
138 	if (desc_len(desc) >= 4)
139 		flags |= DECO_JQCR_FOUR;
140 
141 	/* Instruct the DECO to execute it */
142 	clrsetbits_32(&deco->jr_ctl_hi, 0, flags);
143 
144 	timeout = 10000000;
145 	do {
146 		deco_dbg_reg = rd_reg32(&deco->desc_dbg);
147 
148 		if (ctrlpriv->era < 10)
149 			deco_state = (deco_dbg_reg & DESC_DBG_DECO_STAT_MASK) >>
150 				     DESC_DBG_DECO_STAT_SHIFT;
151 		else
152 			deco_state = (rd_reg32(&deco->dbg_exec) &
153 				      DESC_DER_DECO_STAT_MASK) >>
154 				     DESC_DER_DECO_STAT_SHIFT;
155 
156 		/*
157 		 * If an error occured in the descriptor, then
158 		 * the DECO status field will be set to 0x0D
159 		 */
160 		if (deco_state == DECO_STAT_HOST_ERR)
161 			break;
162 
163 		cpu_relax();
164 	} while ((deco_dbg_reg & DESC_DBG_DECO_STAT_VALID) && --timeout);
165 
166 	*status = rd_reg32(&deco->op_status_hi) &
167 		  DECO_OP_STATUS_HI_ERR_MASK;
168 
169 	if (ctrlpriv->virt_en == 1)
170 		clrsetbits_32(&ctrl->deco_rsr, DECORSR_JR0, 0);
171 
172 	/* Mark the DECO as free */
173 	clrsetbits_32(&ctrl->deco_rq, DECORR_RQD0ENABLE, 0);
174 
175 	if (!timeout)
176 		return -EAGAIN;
177 
178 	return 0;
179 }
180 
181 /*
182  * deinstantiate_rng - builds and executes a descriptor on DECO0,
183  *		       which deinitializes the RNG block.
184  * @ctrldev - pointer to device
185  * @state_handle_mask - bitmask containing the instantiation status
186  *			for the RNG4 state handles which exist in
187  *			the RNG4 block: 1 if it's been instantiated
188  *
189  * Return: - 0 if no error occurred
190  *	   - -ENOMEM if there isn't enough memory to allocate the descriptor
191  *	   - -ENODEV if DECO0 couldn't be acquired
192  *	   - -EAGAIN if an error occurred when executing the descriptor
193  */
194 static int deinstantiate_rng(struct device *ctrldev, int state_handle_mask)
195 {
196 	u32 *desc, status;
197 	int sh_idx, ret = 0;
198 
199 	desc = kmalloc(CAAM_CMD_SZ * 3, GFP_KERNEL);
200 	if (!desc)
201 		return -ENOMEM;
202 
203 	for (sh_idx = 0; sh_idx < RNG4_MAX_HANDLES; sh_idx++) {
204 		/*
205 		 * If the corresponding bit is set, then it means the state
206 		 * handle was initialized by us, and thus it needs to be
207 		 * deinitialized as well
208 		 */
209 		if ((1 << sh_idx) & state_handle_mask) {
210 			/*
211 			 * Create the descriptor for deinstantating this state
212 			 * handle
213 			 */
214 			build_deinstantiation_desc(desc, sh_idx);
215 
216 			/* Try to run it through DECO0 */
217 			ret = run_descriptor_deco0(ctrldev, desc, &status);
218 
219 			if (ret ||
220 			    (status && status != JRSTA_SSRC_JUMP_HALT_CC)) {
221 				dev_err(ctrldev,
222 					"Failed to deinstantiate RNG4 SH%d\n",
223 					sh_idx);
224 				break;
225 			}
226 			dev_info(ctrldev, "Deinstantiated RNG4 SH%d\n", sh_idx);
227 		}
228 	}
229 
230 	kfree(desc);
231 
232 	return ret;
233 }
234 
235 static void devm_deinstantiate_rng(void *data)
236 {
237 	struct device *ctrldev = data;
238 	struct caam_drv_private *ctrlpriv = dev_get_drvdata(ctrldev);
239 
240 	/*
241 	 * De-initialize RNG state handles initialized by this driver.
242 	 * In case of SoCs with Management Complex, RNG is managed by MC f/w.
243 	 */
244 	if (ctrlpriv->rng4_sh_init)
245 		deinstantiate_rng(ctrldev, ctrlpriv->rng4_sh_init);
246 }
247 
248 /*
249  * instantiate_rng - builds and executes a descriptor on DECO0,
250  *		     which initializes the RNG block.
251  * @ctrldev - pointer to device
252  * @state_handle_mask - bitmask containing the instantiation status
253  *			for the RNG4 state handles which exist in
254  *			the RNG4 block: 1 if it's been instantiated
255  *			by an external entry, 0 otherwise.
256  * @gen_sk  - generate data to be loaded into the JDKEK, TDKEK and TDSK;
257  *	      Caution: this can be done only once; if the keys need to be
258  *	      regenerated, a POR is required
259  *
260  * Return: - 0 if no error occurred
261  *	   - -ENOMEM if there isn't enough memory to allocate the descriptor
262  *	   - -ENODEV if DECO0 couldn't be acquired
263  *	   - -EAGAIN if an error occurred when executing the descriptor
264  *	      f.i. there was a RNG hardware error due to not "good enough"
265  *	      entropy being aquired.
266  */
267 static int instantiate_rng(struct device *ctrldev, int state_handle_mask,
268 			   int gen_sk)
269 {
270 	struct caam_drv_private *ctrlpriv = dev_get_drvdata(ctrldev);
271 	struct caam_ctrl __iomem *ctrl;
272 	u32 *desc, status = 0, rdsta_val;
273 	int ret = 0, sh_idx;
274 
275 	ctrl = (struct caam_ctrl __iomem *)ctrlpriv->ctrl;
276 	desc = kmalloc(CAAM_CMD_SZ * 7, GFP_KERNEL);
277 	if (!desc)
278 		return -ENOMEM;
279 
280 	for (sh_idx = 0; sh_idx < RNG4_MAX_HANDLES; sh_idx++) {
281 		/*
282 		 * If the corresponding bit is set, this state handle
283 		 * was initialized by somebody else, so it's left alone.
284 		 */
285 		if ((1 << sh_idx) & state_handle_mask)
286 			continue;
287 
288 		/* Create the descriptor for instantiating RNG State Handle */
289 		build_instantiation_desc(desc, sh_idx, gen_sk);
290 
291 		/* Try to run it through DECO0 */
292 		ret = run_descriptor_deco0(ctrldev, desc, &status);
293 
294 		/*
295 		 * If ret is not 0, or descriptor status is not 0, then
296 		 * something went wrong. No need to try the next state
297 		 * handle (if available), bail out here.
298 		 * Also, if for some reason, the State Handle didn't get
299 		 * instantiated although the descriptor has finished
300 		 * without any error (HW optimizations for later
301 		 * CAAM eras), then try again.
302 		 */
303 		if (ret)
304 			break;
305 
306 		rdsta_val = rd_reg32(&ctrl->r4tst[0].rdsta) & RDSTA_IFMASK;
307 		if ((status && status != JRSTA_SSRC_JUMP_HALT_CC) ||
308 		    !(rdsta_val & (1 << sh_idx))) {
309 			ret = -EAGAIN;
310 			break;
311 		}
312 
313 		dev_info(ctrldev, "Instantiated RNG4 SH%d\n", sh_idx);
314 		/* Clear the contents before recreating the descriptor */
315 		memset(desc, 0x00, CAAM_CMD_SZ * 7);
316 	}
317 
318 	kfree(desc);
319 
320 	if (!ret)
321 		ret = devm_add_action_or_reset(ctrldev, devm_deinstantiate_rng,
322 					       ctrldev);
323 
324 	return ret;
325 }
326 
327 /*
328  * kick_trng - sets the various parameters for enabling the initialization
329  *	       of the RNG4 block in CAAM
330  * @pdev - pointer to the platform device
331  * @ent_delay - Defines the length (in system clocks) of each entropy sample.
332  */
333 static void kick_trng(struct platform_device *pdev, int ent_delay)
334 {
335 	struct device *ctrldev = &pdev->dev;
336 	struct caam_drv_private *ctrlpriv = dev_get_drvdata(ctrldev);
337 	struct caam_ctrl __iomem *ctrl;
338 	struct rng4tst __iomem *r4tst;
339 	u32 val;
340 
341 	ctrl = (struct caam_ctrl __iomem *)ctrlpriv->ctrl;
342 	r4tst = &ctrl->r4tst[0];
343 
344 	/* put RNG4 into program mode */
345 	clrsetbits_32(&r4tst->rtmctl, 0, RTMCTL_PRGM);
346 
347 	/*
348 	 * Performance-wise, it does not make sense to
349 	 * set the delay to a value that is lower
350 	 * than the last one that worked (i.e. the state handles
351 	 * were instantiated properly. Thus, instead of wasting
352 	 * time trying to set the values controlling the sample
353 	 * frequency, the function simply returns.
354 	 */
355 	val = (rd_reg32(&r4tst->rtsdctl) & RTSDCTL_ENT_DLY_MASK)
356 	      >> RTSDCTL_ENT_DLY_SHIFT;
357 	if (ent_delay <= val)
358 		goto start_rng;
359 
360 	val = rd_reg32(&r4tst->rtsdctl);
361 	val = (val & ~RTSDCTL_ENT_DLY_MASK) |
362 	      (ent_delay << RTSDCTL_ENT_DLY_SHIFT);
363 	wr_reg32(&r4tst->rtsdctl, val);
364 	/* min. freq. count, equal to 1/4 of the entropy sample length */
365 	wr_reg32(&r4tst->rtfrqmin, ent_delay >> 2);
366 	/* disable maximum frequency count */
367 	wr_reg32(&r4tst->rtfrqmax, RTFRQMAX_DISABLE);
368 	/* read the control register */
369 	val = rd_reg32(&r4tst->rtmctl);
370 start_rng:
371 	/*
372 	 * select raw sampling in both entropy shifter
373 	 * and statistical checker; ; put RNG4 into run mode
374 	 */
375 	clrsetbits_32(&r4tst->rtmctl, RTMCTL_PRGM, RTMCTL_SAMP_MODE_RAW_ES_SC);
376 }
377 
378 static int caam_get_era_from_hw(struct caam_ctrl __iomem *ctrl)
379 {
380 	static const struct {
381 		u16 ip_id;
382 		u8 maj_rev;
383 		u8 era;
384 	} id[] = {
385 		{0x0A10, 1, 1},
386 		{0x0A10, 2, 2},
387 		{0x0A12, 1, 3},
388 		{0x0A14, 1, 3},
389 		{0x0A14, 2, 4},
390 		{0x0A16, 1, 4},
391 		{0x0A10, 3, 4},
392 		{0x0A11, 1, 4},
393 		{0x0A18, 1, 4},
394 		{0x0A11, 2, 5},
395 		{0x0A12, 2, 5},
396 		{0x0A13, 1, 5},
397 		{0x0A1C, 1, 5}
398 	};
399 	u32 ccbvid, id_ms;
400 	u8 maj_rev, era;
401 	u16 ip_id;
402 	int i;
403 
404 	ccbvid = rd_reg32(&ctrl->perfmon.ccb_id);
405 	era = (ccbvid & CCBVID_ERA_MASK) >> CCBVID_ERA_SHIFT;
406 	if (era)	/* This is '0' prior to CAAM ERA-6 */
407 		return era;
408 
409 	id_ms = rd_reg32(&ctrl->perfmon.caam_id_ms);
410 	ip_id = (id_ms & SECVID_MS_IPID_MASK) >> SECVID_MS_IPID_SHIFT;
411 	maj_rev = (id_ms & SECVID_MS_MAJ_REV_MASK) >> SECVID_MS_MAJ_REV_SHIFT;
412 
413 	for (i = 0; i < ARRAY_SIZE(id); i++)
414 		if (id[i].ip_id == ip_id && id[i].maj_rev == maj_rev)
415 			return id[i].era;
416 
417 	return -ENOTSUPP;
418 }
419 
420 /**
421  * caam_get_era() - Return the ERA of the SEC on SoC, based
422  * on "sec-era" optional property in the DTS. This property is updated
423  * by u-boot.
424  * In case this property is not passed an attempt to retrieve the CAAM
425  * era via register reads will be made.
426  **/
427 static int caam_get_era(struct caam_ctrl __iomem *ctrl)
428 {
429 	struct device_node *caam_node;
430 	int ret;
431 	u32 prop;
432 
433 	caam_node = of_find_compatible_node(NULL, NULL, "fsl,sec-v4.0");
434 	ret = of_property_read_u32(caam_node, "fsl,sec-era", &prop);
435 	of_node_put(caam_node);
436 
437 	if (!ret)
438 		return prop;
439 	else
440 		return caam_get_era_from_hw(ctrl);
441 }
442 
443 /*
444  * ERRATA: imx6 devices (imx6D, imx6Q, imx6DL, imx6S, imx6DP and imx6QP)
445  * have an issue wherein AXI bus transactions may not occur in the correct
446  * order. This isn't a problem running single descriptors, but can be if
447  * running multiple concurrent descriptors. Reworking the driver to throttle
448  * to single requests is impractical, thus the workaround is to limit the AXI
449  * pipeline to a depth of 1 (from it's default of 4) to preclude this situation
450  * from occurring.
451  */
452 static void handle_imx6_err005766(u32 *mcr)
453 {
454 	if (of_machine_is_compatible("fsl,imx6q") ||
455 	    of_machine_is_compatible("fsl,imx6dl") ||
456 	    of_machine_is_compatible("fsl,imx6qp"))
457 		clrsetbits_32(mcr, MCFGR_AXIPIPE_MASK,
458 			      1 << MCFGR_AXIPIPE_SHIFT);
459 }
460 
461 static const struct of_device_id caam_match[] = {
462 	{
463 		.compatible = "fsl,sec-v4.0",
464 	},
465 	{
466 		.compatible = "fsl,sec4.0",
467 	},
468 	{},
469 };
470 MODULE_DEVICE_TABLE(of, caam_match);
471 
472 struct caam_imx_data {
473 	const struct clk_bulk_data *clks;
474 	int num_clks;
475 };
476 
477 static const struct clk_bulk_data caam_imx6_clks[] = {
478 	{ .id = "ipg" },
479 	{ .id = "mem" },
480 	{ .id = "aclk" },
481 	{ .id = "emi_slow" },
482 };
483 
484 static const struct caam_imx_data caam_imx6_data = {
485 	.clks = caam_imx6_clks,
486 	.num_clks = ARRAY_SIZE(caam_imx6_clks),
487 };
488 
489 static const struct clk_bulk_data caam_imx7_clks[] = {
490 	{ .id = "ipg" },
491 	{ .id = "aclk" },
492 };
493 
494 static const struct caam_imx_data caam_imx7_data = {
495 	.clks = caam_imx7_clks,
496 	.num_clks = ARRAY_SIZE(caam_imx7_clks),
497 };
498 
499 static const struct clk_bulk_data caam_imx6ul_clks[] = {
500 	{ .id = "ipg" },
501 	{ .id = "mem" },
502 	{ .id = "aclk" },
503 };
504 
505 static const struct caam_imx_data caam_imx6ul_data = {
506 	.clks = caam_imx6ul_clks,
507 	.num_clks = ARRAY_SIZE(caam_imx6ul_clks),
508 };
509 
510 static const struct soc_device_attribute caam_imx_soc_table[] = {
511 	{ .soc_id = "i.MX6UL", .data = &caam_imx6ul_data },
512 	{ .soc_id = "i.MX6*",  .data = &caam_imx6_data },
513 	{ .soc_id = "i.MX7*",  .data = &caam_imx7_data },
514 	{ .soc_id = "i.MX8M*", .data = &caam_imx7_data },
515 	{ .family = "Freescale i.MX" },
516 	{ /* sentinel */ }
517 };
518 
519 static void disable_clocks(void *data)
520 {
521 	struct caam_drv_private *ctrlpriv = data;
522 
523 	clk_bulk_disable_unprepare(ctrlpriv->num_clks, ctrlpriv->clks);
524 }
525 
526 static int init_clocks(struct device *dev, const struct caam_imx_data *data)
527 {
528 	struct caam_drv_private *ctrlpriv = dev_get_drvdata(dev);
529 	int ret;
530 
531 	ctrlpriv->num_clks = data->num_clks;
532 	ctrlpriv->clks = devm_kmemdup(dev, data->clks,
533 				      data->num_clks * sizeof(data->clks[0]),
534 				      GFP_KERNEL);
535 	if (!ctrlpriv->clks)
536 		return -ENOMEM;
537 
538 	ret = devm_clk_bulk_get(dev, ctrlpriv->num_clks, ctrlpriv->clks);
539 	if (ret) {
540 		dev_err(dev,
541 			"Failed to request all necessary clocks\n");
542 		return ret;
543 	}
544 
545 	ret = clk_bulk_prepare_enable(ctrlpriv->num_clks, ctrlpriv->clks);
546 	if (ret) {
547 		dev_err(dev,
548 			"Failed to prepare/enable all necessary clocks\n");
549 		return ret;
550 	}
551 
552 	return devm_add_action_or_reset(dev, disable_clocks, ctrlpriv);
553 }
554 
555 #ifdef CONFIG_DEBUG_FS
556 static void caam_remove_debugfs(void *root)
557 {
558 	debugfs_remove_recursive(root);
559 }
560 #endif
561 
562 /* Probe routine for CAAM top (controller) level */
563 static int caam_probe(struct platform_device *pdev)
564 {
565 	int ret, ring, gen_sk, ent_delay = RTSDCTL_ENT_DLY_MIN;
566 	u64 caam_id;
567 	const struct soc_device_attribute *imx_soc_match;
568 	struct device *dev;
569 	struct device_node *nprop, *np;
570 	struct caam_ctrl __iomem *ctrl;
571 	struct caam_drv_private *ctrlpriv;
572 #ifdef CONFIG_DEBUG_FS
573 	struct caam_perfmon *perfmon;
574 	struct dentry *dfs_root;
575 #endif
576 	u32 scfgr, comp_params;
577 	u8 rng_vid;
578 	int pg_size;
579 	int BLOCK_OFFSET = 0;
580 
581 	ctrlpriv = devm_kzalloc(&pdev->dev, sizeof(*ctrlpriv), GFP_KERNEL);
582 	if (!ctrlpriv)
583 		return -ENOMEM;
584 
585 	dev = &pdev->dev;
586 	dev_set_drvdata(dev, ctrlpriv);
587 	nprop = pdev->dev.of_node;
588 
589 	imx_soc_match = soc_device_match(caam_imx_soc_table);
590 	caam_imx = (bool)imx_soc_match;
591 
592 	if (imx_soc_match) {
593 		if (!imx_soc_match->data) {
594 			dev_err(dev, "No clock data provided for i.MX SoC");
595 			return -EINVAL;
596 		}
597 
598 		ret = init_clocks(dev, imx_soc_match->data);
599 		if (ret)
600 			return ret;
601 	}
602 
603 
604 	/* Get configuration properties from device tree */
605 	/* First, get register page */
606 	ctrl = devm_of_iomap(dev, nprop, 0, NULL);
607 	ret = PTR_ERR_OR_ZERO(ctrl);
608 	if (ret) {
609 		dev_err(dev, "caam: of_iomap() failed\n");
610 		return ret;
611 	}
612 
613 	caam_little_end = !(bool)(rd_reg32(&ctrl->perfmon.status) &
614 				  (CSTA_PLEND | CSTA_ALT_PLEND));
615 	comp_params = rd_reg32(&ctrl->perfmon.comp_parms_ms);
616 	if (comp_params & CTPR_MS_PS && rd_reg32(&ctrl->mcr) & MCFGR_LONG_PTR)
617 		caam_ptr_sz = sizeof(u64);
618 	else
619 		caam_ptr_sz = sizeof(u32);
620 	caam_dpaa2 = !!(comp_params & CTPR_MS_DPAA2);
621 	ctrlpriv->qi_present = !!(comp_params & CTPR_MS_QI_MASK);
622 
623 #ifdef CONFIG_CAAM_QI
624 	/* If (DPAA 1.x) QI present, check whether dependencies are available */
625 	if (ctrlpriv->qi_present && !caam_dpaa2) {
626 		ret = qman_is_probed();
627 		if (!ret) {
628 			return -EPROBE_DEFER;
629 		} else if (ret < 0) {
630 			dev_err(dev, "failing probe due to qman probe error\n");
631 			return -ENODEV;
632 		}
633 
634 		ret = qman_portals_probed();
635 		if (!ret) {
636 			return -EPROBE_DEFER;
637 		} else if (ret < 0) {
638 			dev_err(dev, "failing probe due to qman portals probe error\n");
639 			return -ENODEV;
640 		}
641 	}
642 #endif
643 
644 	/* Allocating the BLOCK_OFFSET based on the supported page size on
645 	 * the platform
646 	 */
647 	pg_size = (comp_params & CTPR_MS_PG_SZ_MASK) >> CTPR_MS_PG_SZ_SHIFT;
648 	if (pg_size == 0)
649 		BLOCK_OFFSET = PG_SIZE_4K;
650 	else
651 		BLOCK_OFFSET = PG_SIZE_64K;
652 
653 	ctrlpriv->ctrl = (struct caam_ctrl __iomem __force *)ctrl;
654 	ctrlpriv->assure = (struct caam_assurance __iomem __force *)
655 			   ((__force uint8_t *)ctrl +
656 			    BLOCK_OFFSET * ASSURE_BLOCK_NUMBER
657 			   );
658 	ctrlpriv->deco = (struct caam_deco __iomem __force *)
659 			 ((__force uint8_t *)ctrl +
660 			 BLOCK_OFFSET * DECO_BLOCK_NUMBER
661 			 );
662 
663 	/* Get the IRQ of the controller (for security violations only) */
664 	ctrlpriv->secvio_irq = irq_of_parse_and_map(nprop, 0);
665 
666 	/*
667 	 * Enable DECO watchdogs and, if this is a PHYS_ADDR_T_64BIT kernel,
668 	 * long pointers in master configuration register.
669 	 * In case of SoCs with Management Complex, MC f/w performs
670 	 * the configuration.
671 	 */
672 	np = of_find_compatible_node(NULL, NULL, "fsl,qoriq-mc");
673 	ctrlpriv->mc_en = !!np;
674 	of_node_put(np);
675 
676 	if (!ctrlpriv->mc_en)
677 		clrsetbits_32(&ctrl->mcr, MCFGR_AWCACHE_MASK,
678 			      MCFGR_AWCACHE_CACH | MCFGR_AWCACHE_BUFF |
679 			      MCFGR_WDENABLE | MCFGR_LARGE_BURST);
680 
681 	handle_imx6_err005766(&ctrl->mcr);
682 
683 	/*
684 	 *  Read the Compile Time paramters and SCFGR to determine
685 	 * if Virtualization is enabled for this platform
686 	 */
687 	scfgr = rd_reg32(&ctrl->scfgr);
688 
689 	ctrlpriv->virt_en = 0;
690 	if (comp_params & CTPR_MS_VIRT_EN_INCL) {
691 		/* VIRT_EN_INCL = 1 & VIRT_EN_POR = 1 or
692 		 * VIRT_EN_INCL = 1 & VIRT_EN_POR = 0 & SCFGR_VIRT_EN = 1
693 		 */
694 		if ((comp_params & CTPR_MS_VIRT_EN_POR) ||
695 		    (!(comp_params & CTPR_MS_VIRT_EN_POR) &&
696 		       (scfgr & SCFGR_VIRT_EN)))
697 				ctrlpriv->virt_en = 1;
698 	} else {
699 		/* VIRT_EN_INCL = 0 && VIRT_EN_POR_VALUE = 1 */
700 		if (comp_params & CTPR_MS_VIRT_EN_POR)
701 				ctrlpriv->virt_en = 1;
702 	}
703 
704 	if (ctrlpriv->virt_en == 1)
705 		clrsetbits_32(&ctrl->jrstart, 0, JRSTART_JR0_START |
706 			      JRSTART_JR1_START | JRSTART_JR2_START |
707 			      JRSTART_JR3_START);
708 
709 	ret = dma_set_mask_and_coherent(dev, caam_get_dma_mask(dev));
710 	if (ret) {
711 		dev_err(dev, "dma_set_mask_and_coherent failed (%d)\n", ret);
712 		return ret;
713 	}
714 
715 	ctrlpriv->era = caam_get_era(ctrl);
716 	ctrlpriv->domain = iommu_get_domain_for_dev(dev);
717 
718 #ifdef CONFIG_DEBUG_FS
719 	/*
720 	 * FIXME: needs better naming distinction, as some amalgamation of
721 	 * "caam" and nprop->full_name. The OF name isn't distinctive,
722 	 * but does separate instances
723 	 */
724 	perfmon = (struct caam_perfmon __force *)&ctrl->perfmon;
725 
726 	dfs_root = debugfs_create_dir(dev_name(dev), NULL);
727 	ret = devm_add_action_or_reset(dev, caam_remove_debugfs, dfs_root);
728 	if (ret)
729 		return ret;
730 
731 	ctrlpriv->ctl = debugfs_create_dir("ctl", dfs_root);
732 #endif
733 
734 	/* Check to see if (DPAA 1.x) QI present. If so, enable */
735 	if (ctrlpriv->qi_present && !caam_dpaa2) {
736 		ctrlpriv->qi = (struct caam_queue_if __iomem __force *)
737 			       ((__force uint8_t *)ctrl +
738 				 BLOCK_OFFSET * QI_BLOCK_NUMBER
739 			       );
740 		/* This is all that's required to physically enable QI */
741 		wr_reg32(&ctrlpriv->qi->qi_control_lo, QICTL_DQEN);
742 
743 		/* If QMAN driver is present, init CAAM-QI backend */
744 #ifdef CONFIG_CAAM_QI
745 		ret = caam_qi_init(pdev);
746 		if (ret)
747 			dev_err(dev, "caam qi i/f init failed: %d\n", ret);
748 #endif
749 	}
750 
751 	ring = 0;
752 	for_each_available_child_of_node(nprop, np)
753 		if (of_device_is_compatible(np, "fsl,sec-v4.0-job-ring") ||
754 		    of_device_is_compatible(np, "fsl,sec4.0-job-ring")) {
755 			ctrlpriv->jr[ring] = (struct caam_job_ring __iomem __force *)
756 					     ((__force uint8_t *)ctrl +
757 					     (ring + JR_BLOCK_NUMBER) *
758 					      BLOCK_OFFSET
759 					     );
760 			ctrlpriv->total_jobrs++;
761 			ring++;
762 		}
763 
764 	/* If no QI and no rings specified, quit and go home */
765 	if ((!ctrlpriv->qi_present) && (!ctrlpriv->total_jobrs)) {
766 		dev_err(dev, "no queues configured, terminating\n");
767 		return -ENOMEM;
768 	}
769 
770 	if (ctrlpriv->era < 10)
771 		rng_vid = (rd_reg32(&ctrl->perfmon.cha_id_ls) &
772 			   CHA_ID_LS_RNG_MASK) >> CHA_ID_LS_RNG_SHIFT;
773 	else
774 		rng_vid = (rd_reg32(&ctrl->vreg.rng) & CHA_VER_VID_MASK) >>
775 			   CHA_VER_VID_SHIFT;
776 
777 	/*
778 	 * If SEC has RNG version >= 4 and RNG state handle has not been
779 	 * already instantiated, do RNG instantiation
780 	 * In case of SoCs with Management Complex, RNG is managed by MC f/w.
781 	 */
782 	if (!ctrlpriv->mc_en && rng_vid >= 4) {
783 		ctrlpriv->rng4_sh_init =
784 			rd_reg32(&ctrl->r4tst[0].rdsta);
785 		/*
786 		 * If the secure keys (TDKEK, JDKEK, TDSK), were already
787 		 * generated, signal this to the function that is instantiating
788 		 * the state handles. An error would occur if RNG4 attempts
789 		 * to regenerate these keys before the next POR.
790 		 */
791 		gen_sk = ctrlpriv->rng4_sh_init & RDSTA_SKVN ? 0 : 1;
792 		ctrlpriv->rng4_sh_init &= RDSTA_IFMASK;
793 		do {
794 			int inst_handles =
795 				rd_reg32(&ctrl->r4tst[0].rdsta) &
796 								RDSTA_IFMASK;
797 			/*
798 			 * If either SH were instantiated by somebody else
799 			 * (e.g. u-boot) then it is assumed that the entropy
800 			 * parameters are properly set and thus the function
801 			 * setting these (kick_trng(...)) is skipped.
802 			 * Also, if a handle was instantiated, do not change
803 			 * the TRNG parameters.
804 			 */
805 			if (!(ctrlpriv->rng4_sh_init || inst_handles)) {
806 				dev_info(dev,
807 					 "Entropy delay = %u\n",
808 					 ent_delay);
809 				kick_trng(pdev, ent_delay);
810 				ent_delay += 400;
811 			}
812 			/*
813 			 * if instantiate_rng(...) fails, the loop will rerun
814 			 * and the kick_trng(...) function will modfiy the
815 			 * upper and lower limits of the entropy sampling
816 			 * interval, leading to a sucessful initialization of
817 			 * the RNG.
818 			 */
819 			ret = instantiate_rng(dev, inst_handles,
820 					      gen_sk);
821 			if (ret == -EAGAIN)
822 				/*
823 				 * if here, the loop will rerun,
824 				 * so don't hog the CPU
825 				 */
826 				cpu_relax();
827 		} while ((ret == -EAGAIN) && (ent_delay < RTSDCTL_ENT_DLY_MAX));
828 		if (ret) {
829 			dev_err(dev, "failed to instantiate RNG");
830 			return ret;
831 		}
832 		/*
833 		 * Set handles init'ed by this module as the complement of the
834 		 * already initialized ones
835 		 */
836 		ctrlpriv->rng4_sh_init = ~ctrlpriv->rng4_sh_init & RDSTA_IFMASK;
837 
838 		/* Enable RDB bit so that RNG works faster */
839 		clrsetbits_32(&ctrl->scfgr, 0, SCFGR_RDBENABLE);
840 	}
841 
842 	/* NOTE: RTIC detection ought to go here, around Si time */
843 
844 	caam_id = (u64)rd_reg32(&ctrl->perfmon.caam_id_ms) << 32 |
845 		  (u64)rd_reg32(&ctrl->perfmon.caam_id_ls);
846 
847 	/* Report "alive" for developer to see */
848 	dev_info(dev, "device ID = 0x%016llx (Era %d)\n", caam_id,
849 		 ctrlpriv->era);
850 	dev_info(dev, "job rings = %d, qi = %d\n",
851 		 ctrlpriv->total_jobrs, ctrlpriv->qi_present);
852 
853 #ifdef CONFIG_DEBUG_FS
854 	debugfs_create_file("rq_dequeued", S_IRUSR | S_IRGRP | S_IROTH,
855 			    ctrlpriv->ctl, &perfmon->req_dequeued,
856 			    &caam_fops_u64_ro);
857 	debugfs_create_file("ob_rq_encrypted", S_IRUSR | S_IRGRP | S_IROTH,
858 			    ctrlpriv->ctl, &perfmon->ob_enc_req,
859 			    &caam_fops_u64_ro);
860 	debugfs_create_file("ib_rq_decrypted", S_IRUSR | S_IRGRP | S_IROTH,
861 			    ctrlpriv->ctl, &perfmon->ib_dec_req,
862 			    &caam_fops_u64_ro);
863 	debugfs_create_file("ob_bytes_encrypted", S_IRUSR | S_IRGRP | S_IROTH,
864 			    ctrlpriv->ctl, &perfmon->ob_enc_bytes,
865 			    &caam_fops_u64_ro);
866 	debugfs_create_file("ob_bytes_protected", S_IRUSR | S_IRGRP | S_IROTH,
867 			    ctrlpriv->ctl, &perfmon->ob_prot_bytes,
868 			    &caam_fops_u64_ro);
869 	debugfs_create_file("ib_bytes_decrypted", S_IRUSR | S_IRGRP | S_IROTH,
870 			    ctrlpriv->ctl, &perfmon->ib_dec_bytes,
871 			    &caam_fops_u64_ro);
872 	debugfs_create_file("ib_bytes_validated", S_IRUSR | S_IRGRP | S_IROTH,
873 			    ctrlpriv->ctl, &perfmon->ib_valid_bytes,
874 			    &caam_fops_u64_ro);
875 
876 	/* Controller level - global status values */
877 	debugfs_create_file("fault_addr", S_IRUSR | S_IRGRP | S_IROTH,
878 			    ctrlpriv->ctl, &perfmon->faultaddr,
879 			    &caam_fops_u32_ro);
880 	debugfs_create_file("fault_detail", S_IRUSR | S_IRGRP | S_IROTH,
881 			    ctrlpriv->ctl, &perfmon->faultdetail,
882 			    &caam_fops_u32_ro);
883 	debugfs_create_file("fault_status", S_IRUSR | S_IRGRP | S_IROTH,
884 			    ctrlpriv->ctl, &perfmon->status,
885 			    &caam_fops_u32_ro);
886 
887 	/* Internal covering keys (useful in non-secure mode only) */
888 	ctrlpriv->ctl_kek_wrap.data = (__force void *)&ctrlpriv->ctrl->kek[0];
889 	ctrlpriv->ctl_kek_wrap.size = KEK_KEY_SIZE * sizeof(u32);
890 	debugfs_create_blob("kek", S_IRUSR | S_IRGRP | S_IROTH, ctrlpriv->ctl,
891 			    &ctrlpriv->ctl_kek_wrap);
892 
893 	ctrlpriv->ctl_tkek_wrap.data = (__force void *)&ctrlpriv->ctrl->tkek[0];
894 	ctrlpriv->ctl_tkek_wrap.size = KEK_KEY_SIZE * sizeof(u32);
895 	debugfs_create_blob("tkek", S_IRUSR | S_IRGRP | S_IROTH, ctrlpriv->ctl,
896 			    &ctrlpriv->ctl_tkek_wrap);
897 
898 	ctrlpriv->ctl_tdsk_wrap.data = (__force void *)&ctrlpriv->ctrl->tdsk[0];
899 	ctrlpriv->ctl_tdsk_wrap.size = KEK_KEY_SIZE * sizeof(u32);
900 	debugfs_create_blob("tdsk", S_IRUSR | S_IRGRP | S_IROTH, ctrlpriv->ctl,
901 			    &ctrlpriv->ctl_tdsk_wrap);
902 #endif
903 
904 	ret = devm_of_platform_populate(dev);
905 	if (ret)
906 		dev_err(dev, "JR platform devices creation error\n");
907 
908 	return ret;
909 }
910 
911 static struct platform_driver caam_driver = {
912 	.driver = {
913 		.name = "caam",
914 		.of_match_table = caam_match,
915 	},
916 	.probe       = caam_probe,
917 };
918 
919 module_platform_driver(caam_driver);
920 
921 MODULE_LICENSE("GPL");
922 MODULE_DESCRIPTION("FSL CAAM request backend");
923 MODULE_AUTHOR("Freescale Semiconductor - NMG/STC");
924