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