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