xref: /rk3399_ARM-atf/services/std_svc/spm/el3_spmc/spmc_main.c (revision 02d3ef333d4a0a07a3e40defb12a8cde3a7cba03)
1 /*
2  * Copyright (c) 2022, ARM Limited and Contributors. All rights reserved.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 #include <assert.h>
8 #include <errno.h>
9 
10 #include <arch_helpers.h>
11 #include <bl31/bl31.h>
12 #include <bl31/ehf.h>
13 #include <common/debug.h>
14 #include <common/fdt_wrappers.h>
15 #include <common/runtime_svc.h>
16 #include <lib/el3_runtime/context_mgmt.h>
17 #include <lib/smccc.h>
18 #include <lib/utils.h>
19 #include <lib/xlat_tables/xlat_tables_v2.h>
20 #include <libfdt.h>
21 #include <plat/common/platform.h>
22 #include <services/el3_spmc_logical_sp.h>
23 #include <services/ffa_svc.h>
24 #include <services/spmc_svc.h>
25 #include <services/spmd_svc.h>
26 #include "spmc.h"
27 
28 #include <platform_def.h>
29 
30 /*
31  * Allocate a secure partition descriptor to describe each SP in the system that
32  * does not reside at EL3.
33  */
34 static struct secure_partition_desc sp_desc[SECURE_PARTITION_COUNT];
35 
36 /*
37  * Allocate an NS endpoint descriptor to describe each VM and the Hypervisor in
38  * the system that interacts with a SP. It is used to track the Hypervisor
39  * buffer pair, version and ID for now. It could be extended to track VM
40  * properties when the SPMC supports indirect messaging.
41  */
42 static struct ns_endpoint_desc ns_ep_desc[NS_PARTITION_COUNT];
43 
44 /*
45  * Helper function to obtain the array storing the EL3
46  * Logical Partition descriptors.
47  */
48 struct el3_lp_desc *get_el3_lp_array(void)
49 {
50 	return (struct el3_lp_desc *) EL3_LP_DESCS_START;
51 }
52 
53 /*
54  * Helper function to obtain the descriptor of the last SP to whom control was
55  * handed to on this physical cpu. Currently, we assume there is only one SP.
56  * TODO: Expand to track multiple partitions when required.
57  */
58 struct secure_partition_desc *spmc_get_current_sp_ctx(void)
59 {
60 	return &(sp_desc[ACTIVE_SP_DESC_INDEX]);
61 }
62 
63 /*
64  * Helper function to obtain the execution context of an SP on the
65  * current physical cpu.
66  */
67 struct sp_exec_ctx *spmc_get_sp_ec(struct secure_partition_desc *sp)
68 {
69 	return &(sp->ec[get_ec_index(sp)]);
70 }
71 
72 /* Helper function to get pointer to SP context from its ID. */
73 struct secure_partition_desc *spmc_get_sp_ctx(uint16_t id)
74 {
75 	/* Check for Secure World Partitions. */
76 	for (unsigned int i = 0U; i < SECURE_PARTITION_COUNT; i++) {
77 		if (sp_desc[i].sp_id == id) {
78 			return &(sp_desc[i]);
79 		}
80 	}
81 	return NULL;
82 }
83 
84 /*
85  * Helper function to obtain the descriptor of the Hypervisor or OS kernel.
86  * We assume that the first descriptor is reserved for this entity.
87  */
88 struct ns_endpoint_desc *spmc_get_hyp_ctx(void)
89 {
90 	return &(ns_ep_desc[0]);
91 }
92 
93 /*
94  * Helper function to obtain the RX/TX buffer pair descriptor of the Hypervisor
95  * or OS kernel in the normal world or the last SP that was run.
96  */
97 struct mailbox *spmc_get_mbox_desc(bool secure_origin)
98 {
99 	/* Obtain the RX/TX buffer pair descriptor. */
100 	if (secure_origin) {
101 		return &(spmc_get_current_sp_ctx()->mailbox);
102 	} else {
103 		return &(spmc_get_hyp_ctx()->mailbox);
104 	}
105 }
106 
107 /******************************************************************************
108  * This function returns to the place where spmc_sp_synchronous_entry() was
109  * called originally.
110  ******************************************************************************/
111 __dead2 void spmc_sp_synchronous_exit(struct sp_exec_ctx *ec, uint64_t rc)
112 {
113 	/*
114 	 * The SPM must have initiated the original request through a
115 	 * synchronous entry into the secure partition. Jump back to the
116 	 * original C runtime context with the value of rc in x0;
117 	 */
118 	spm_secure_partition_exit(ec->c_rt_ctx, rc);
119 
120 	panic();
121 }
122 
123 /*******************************************************************************
124  * Return FFA_ERROR with specified error code.
125  ******************************************************************************/
126 uint64_t spmc_ffa_error_return(void *handle, int error_code)
127 {
128 	SMC_RET8(handle, FFA_ERROR,
129 		 FFA_TARGET_INFO_MBZ, error_code,
130 		 FFA_PARAM_MBZ, FFA_PARAM_MBZ, FFA_PARAM_MBZ,
131 		 FFA_PARAM_MBZ, FFA_PARAM_MBZ);
132 }
133 
134 /******************************************************************************
135  * Helper function to validate a secure partition ID to ensure it does not
136  * conflict with any other FF-A component and follows the convention to
137  * indicate it resides within the secure world.
138  ******************************************************************************/
139 bool is_ffa_secure_id_valid(uint16_t partition_id)
140 {
141 	struct el3_lp_desc *el3_lp_descs = get_el3_lp_array();
142 
143 	/* Ensure the ID is not the invalid partition ID. */
144 	if (partition_id == INV_SP_ID) {
145 		return false;
146 	}
147 
148 	/* Ensure the ID is not the SPMD ID. */
149 	if (partition_id == SPMD_DIRECT_MSG_ENDPOINT_ID) {
150 		return false;
151 	}
152 
153 	/*
154 	 * Ensure the ID follows the convention to indicate it resides
155 	 * in the secure world.
156 	 */
157 	if (!ffa_is_secure_world_id(partition_id)) {
158 		return false;
159 	}
160 
161 	/* Ensure we don't conflict with the SPMC partition ID. */
162 	if (partition_id == FFA_SPMC_ID) {
163 		return false;
164 	}
165 
166 	/* Ensure we do not already have an SP context with this ID. */
167 	if (spmc_get_sp_ctx(partition_id)) {
168 		return false;
169 	}
170 
171 	/* Ensure we don't clash with any Logical SP's. */
172 	for (unsigned int i = 0U; i < EL3_LP_DESCS_COUNT; i++) {
173 		if (el3_lp_descs[i].sp_id == partition_id) {
174 			return false;
175 		}
176 	}
177 
178 	return true;
179 }
180 
181 /*******************************************************************************
182  * This function either forwards the request to the other world or returns
183  * with an ERET depending on the source of the call.
184  * We can assume that the destination is for an entity at a lower exception
185  * level as any messages destined for a logical SP resident in EL3 will have
186  * already been taken care of by the SPMC before entering this function.
187  ******************************************************************************/
188 static uint64_t spmc_smc_return(uint32_t smc_fid,
189 				bool secure_origin,
190 				uint64_t x1,
191 				uint64_t x2,
192 				uint64_t x3,
193 				uint64_t x4,
194 				void *handle,
195 				void *cookie,
196 				uint64_t flags,
197 				uint16_t dst_id)
198 {
199 	/* If the destination is in the normal world always go via the SPMD. */
200 	if (ffa_is_normal_world_id(dst_id)) {
201 		return spmd_smc_handler(smc_fid, x1, x2, x3, x4,
202 					cookie, handle, flags);
203 	}
204 	/*
205 	 * If the caller is secure and we want to return to the secure world,
206 	 * ERET directly.
207 	 */
208 	else if (secure_origin && ffa_is_secure_world_id(dst_id)) {
209 		SMC_RET5(handle, smc_fid, x1, x2, x3, x4);
210 	}
211 	/* If we originated in the normal world then switch contexts. */
212 	else if (!secure_origin && ffa_is_secure_world_id(dst_id)) {
213 		return spmd_smc_switch_state(smc_fid, secure_origin, x1, x2,
214 					     x3, x4, handle);
215 	} else {
216 		/* Unknown State. */
217 		panic();
218 	}
219 
220 	/* Shouldn't be Reached. */
221 	return 0;
222 }
223 
224 /*******************************************************************************
225  * FF-A ABI Handlers.
226  ******************************************************************************/
227 
228 /*******************************************************************************
229  * Helper function to validate arg2 as part of a direct message.
230  ******************************************************************************/
231 static inline bool direct_msg_validate_arg2(uint64_t x2)
232 {
233 	/*
234 	 * We currently only support partition messages, therefore ensure x2 is
235 	 * not set.
236 	 */
237 	if (x2 != (uint64_t) 0) {
238 		VERBOSE("Arg2 MBZ for partition messages (0x%lx).\n", x2);
239 		return false;
240 	}
241 	return true;
242 }
243 
244 /*******************************************************************************
245  * Handle direct request messages and route to the appropriate destination.
246  ******************************************************************************/
247 static uint64_t direct_req_smc_handler(uint32_t smc_fid,
248 				       bool secure_origin,
249 				       uint64_t x1,
250 				       uint64_t x2,
251 				       uint64_t x3,
252 				       uint64_t x4,
253 				       void *cookie,
254 				       void *handle,
255 				       uint64_t flags)
256 {
257 	uint16_t dst_id = ffa_endpoint_destination(x1);
258 	struct el3_lp_desc *el3_lp_descs;
259 	struct secure_partition_desc *sp;
260 	unsigned int idx;
261 
262 	/* Check if arg2 has been populated correctly based on message type. */
263 	if (!direct_msg_validate_arg2(x2)) {
264 		return spmc_ffa_error_return(handle,
265 					     FFA_ERROR_INVALID_PARAMETER);
266 	}
267 
268 	el3_lp_descs = get_el3_lp_array();
269 
270 	/* Check if the request is destined for a Logical Partition. */
271 	for (unsigned int i = 0U; i < MAX_EL3_LP_DESCS_COUNT; i++) {
272 		if (el3_lp_descs[i].sp_id == dst_id) {
273 			return el3_lp_descs[i].direct_req(
274 					smc_fid, secure_origin, x1, x2, x3, x4,
275 					cookie, handle, flags);
276 		}
277 	}
278 
279 	/*
280 	 * If the request was not targeted to a LSP and from the secure world
281 	 * then it is invalid since a SP cannot call into the Normal world and
282 	 * there is no other SP to call into. If there are other SPs in future
283 	 * then the partition runtime model would need to be validated as well.
284 	 */
285 	if (secure_origin) {
286 		VERBOSE("Direct request not supported to the Normal World.\n");
287 		return spmc_ffa_error_return(handle,
288 					     FFA_ERROR_INVALID_PARAMETER);
289 	}
290 
291 	/* Check if the SP ID is valid. */
292 	sp = spmc_get_sp_ctx(dst_id);
293 	if (sp == NULL) {
294 		VERBOSE("Direct request to unknown partition ID (0x%x).\n",
295 			dst_id);
296 		return spmc_ffa_error_return(handle,
297 					     FFA_ERROR_INVALID_PARAMETER);
298 	}
299 
300 	/*
301 	 * Check that the target execution context is in a waiting state before
302 	 * forwarding the direct request to it.
303 	 */
304 	idx = get_ec_index(sp);
305 	if (sp->ec[idx].rt_state != RT_STATE_WAITING) {
306 		VERBOSE("SP context on core%u is not waiting (%u).\n",
307 			idx, sp->ec[idx].rt_model);
308 		return spmc_ffa_error_return(handle, FFA_ERROR_BUSY);
309 	}
310 
311 	/*
312 	 * Everything checks out so forward the request to the SP after updating
313 	 * its state and runtime model.
314 	 */
315 	sp->ec[idx].rt_state = RT_STATE_RUNNING;
316 	sp->ec[idx].rt_model = RT_MODEL_DIR_REQ;
317 	return spmc_smc_return(smc_fid, secure_origin, x1, x2, x3, x4,
318 			       handle, cookie, flags, dst_id);
319 }
320 
321 /*******************************************************************************
322  * Handle direct response messages and route to the appropriate destination.
323  ******************************************************************************/
324 static uint64_t direct_resp_smc_handler(uint32_t smc_fid,
325 					bool secure_origin,
326 					uint64_t x1,
327 					uint64_t x2,
328 					uint64_t x3,
329 					uint64_t x4,
330 					void *cookie,
331 					void *handle,
332 					uint64_t flags)
333 {
334 	uint16_t dst_id = ffa_endpoint_destination(x1);
335 	struct secure_partition_desc *sp;
336 	unsigned int idx;
337 
338 	/* Check if arg2 has been populated correctly based on message type. */
339 	if (!direct_msg_validate_arg2(x2)) {
340 		return spmc_ffa_error_return(handle,
341 					     FFA_ERROR_INVALID_PARAMETER);
342 	}
343 
344 	/* Check that the response did not originate from the Normal world. */
345 	if (!secure_origin) {
346 		VERBOSE("Direct Response not supported from Normal World.\n");
347 		return spmc_ffa_error_return(handle,
348 					     FFA_ERROR_INVALID_PARAMETER);
349 	}
350 
351 	/*
352 	 * Check that the response is either targeted to the Normal world or the
353 	 * SPMC e.g. a PM response.
354 	 */
355 	if ((dst_id != FFA_SPMC_ID) && ffa_is_secure_world_id(dst_id)) {
356 		VERBOSE("Direct response to invalid partition ID (0x%x).\n",
357 			dst_id);
358 		return spmc_ffa_error_return(handle,
359 					     FFA_ERROR_INVALID_PARAMETER);
360 	}
361 
362 	/* Obtain the SP descriptor and update its runtime state. */
363 	sp = spmc_get_sp_ctx(ffa_endpoint_source(x1));
364 	if (sp == NULL) {
365 		VERBOSE("Direct response to unknown partition ID (0x%x).\n",
366 			dst_id);
367 		return spmc_ffa_error_return(handle,
368 					     FFA_ERROR_INVALID_PARAMETER);
369 	}
370 
371 	/* Sanity check state is being tracked correctly in the SPMC. */
372 	idx = get_ec_index(sp);
373 	assert(sp->ec[idx].rt_state == RT_STATE_RUNNING);
374 
375 	/* Ensure SP execution context was in the right runtime model. */
376 	if (sp->ec[idx].rt_model != RT_MODEL_DIR_REQ) {
377 		VERBOSE("SP context on core%u not handling direct req (%u).\n",
378 			idx, sp->ec[idx].rt_model);
379 		return spmc_ffa_error_return(handle, FFA_ERROR_DENIED);
380 	}
381 
382 	/* Update the state of the SP execution context. */
383 	sp->ec[idx].rt_state = RT_STATE_WAITING;
384 
385 	/*
386 	 * If the receiver is not the SPMC then forward the response to the
387 	 * Normal world.
388 	 */
389 	if (dst_id == FFA_SPMC_ID) {
390 		spmc_sp_synchronous_exit(&sp->ec[idx], x4);
391 		/* Should not get here. */
392 		panic();
393 	}
394 
395 	return spmc_smc_return(smc_fid, secure_origin, x1, x2, x3, x4,
396 			       handle, cookie, flags, dst_id);
397 }
398 
399 /*******************************************************************************
400  * This function handles the FFA_MSG_WAIT SMC to allow an SP to relinquish its
401  * cycles.
402  ******************************************************************************/
403 static uint64_t msg_wait_handler(uint32_t smc_fid,
404 				 bool secure_origin,
405 				 uint64_t x1,
406 				 uint64_t x2,
407 				 uint64_t x3,
408 				 uint64_t x4,
409 				 void *cookie,
410 				 void *handle,
411 				 uint64_t flags)
412 {
413 	struct secure_partition_desc *sp;
414 	unsigned int idx;
415 
416 	/*
417 	 * Check that the response did not originate from the Normal world as
418 	 * only the secure world can call this ABI.
419 	 */
420 	if (!secure_origin) {
421 		VERBOSE("Normal world cannot call FFA_MSG_WAIT.\n");
422 		return spmc_ffa_error_return(handle, FFA_ERROR_NOT_SUPPORTED);
423 	}
424 
425 	/* Get the descriptor of the SP that invoked FFA_MSG_WAIT. */
426 	sp = spmc_get_current_sp_ctx();
427 	if (sp == NULL) {
428 		return spmc_ffa_error_return(handle,
429 					     FFA_ERROR_INVALID_PARAMETER);
430 	}
431 
432 	/*
433 	 * Get the execution context of the SP that invoked FFA_MSG_WAIT.
434 	 */
435 	idx = get_ec_index(sp);
436 
437 	/* Ensure SP execution context was in the right runtime model. */
438 	if (sp->ec[idx].rt_model == RT_MODEL_DIR_REQ) {
439 		return spmc_ffa_error_return(handle, FFA_ERROR_DENIED);
440 	}
441 
442 	/* Sanity check the state is being tracked correctly in the SPMC. */
443 	assert(sp->ec[idx].rt_state == RT_STATE_RUNNING);
444 
445 	/*
446 	 * Perform a synchronous exit if the partition was initialising. The
447 	 * state is updated after the exit.
448 	 */
449 	if (sp->ec[idx].rt_model == RT_MODEL_INIT) {
450 		spmc_sp_synchronous_exit(&sp->ec[idx], x4);
451 		/* Should not get here */
452 		panic();
453 	}
454 
455 	/* Update the state of the SP execution context. */
456 	sp->ec[idx].rt_state = RT_STATE_WAITING;
457 
458 	/* Resume normal world if a secure interrupt was handled. */
459 	if (sp->ec[idx].rt_model == RT_MODEL_INTR) {
460 		/* FFA_MSG_WAIT can only be called from the secure world. */
461 		unsigned int secure_state_in = SECURE;
462 		unsigned int secure_state_out = NON_SECURE;
463 
464 		cm_el1_sysregs_context_save(secure_state_in);
465 		cm_el1_sysregs_context_restore(secure_state_out);
466 		cm_set_next_eret_context(secure_state_out);
467 		SMC_RET0(cm_get_context(secure_state_out));
468 	}
469 
470 	/* Forward the response to the Normal world. */
471 	return spmc_smc_return(smc_fid, secure_origin, x1, x2, x3, x4,
472 			       handle, cookie, flags, FFA_NWD_ID);
473 }
474 
475 static uint64_t ffa_error_handler(uint32_t smc_fid,
476 				 bool secure_origin,
477 				 uint64_t x1,
478 				 uint64_t x2,
479 				 uint64_t x3,
480 				 uint64_t x4,
481 				 void *cookie,
482 				 void *handle,
483 				 uint64_t flags)
484 {
485 	struct secure_partition_desc *sp;
486 	unsigned int idx;
487 
488 	/* Check that the response did not originate from the Normal world. */
489 	if (!secure_origin) {
490 		return spmc_ffa_error_return(handle, FFA_ERROR_NOT_SUPPORTED);
491 	}
492 
493 	/* Get the descriptor of the SP that invoked FFA_ERROR. */
494 	sp = spmc_get_current_sp_ctx();
495 	if (sp == NULL) {
496 		return spmc_ffa_error_return(handle,
497 					     FFA_ERROR_INVALID_PARAMETER);
498 	}
499 
500 	/* Get the execution context of the SP that invoked FFA_ERROR. */
501 	idx = get_ec_index(sp);
502 
503 	/*
504 	 * We only expect FFA_ERROR to be received during SP initialisation
505 	 * otherwise this is an invalid call.
506 	 */
507 	if (sp->ec[idx].rt_model == RT_MODEL_INIT) {
508 		ERROR("SP 0x%x failed to initialize.\n", sp->sp_id);
509 		spmc_sp_synchronous_exit(&sp->ec[idx], x2);
510 		/* Should not get here. */
511 		panic();
512 	}
513 
514 	return spmc_ffa_error_return(handle, FFA_ERROR_NOT_SUPPORTED);
515 }
516 
517 static uint64_t ffa_version_handler(uint32_t smc_fid,
518 				    bool secure_origin,
519 				    uint64_t x1,
520 				    uint64_t x2,
521 				    uint64_t x3,
522 				    uint64_t x4,
523 				    void *cookie,
524 				    void *handle,
525 				    uint64_t flags)
526 {
527 	uint32_t requested_version = x1 & FFA_VERSION_MASK;
528 
529 	if (requested_version & FFA_VERSION_BIT31_MASK) {
530 		/* Invalid encoding, return an error. */
531 		SMC_RET1(handle, FFA_ERROR_NOT_SUPPORTED);
532 		/* Execution stops here. */
533 	}
534 
535 	/* Determine the caller to store the requested version. */
536 	if (secure_origin) {
537 		/*
538 		 * Ensure that the SP is reporting the same version as
539 		 * specified in its manifest. If these do not match there is
540 		 * something wrong with the SP.
541 		 * TODO: Should we abort the SP? For now assert this is not
542 		 *       case.
543 		 */
544 		assert(requested_version ==
545 		       spmc_get_current_sp_ctx()->ffa_version);
546 	} else {
547 		/*
548 		 * If this is called by the normal world, record this
549 		 * information in its descriptor.
550 		 */
551 		spmc_get_hyp_ctx()->ffa_version = requested_version;
552 	}
553 
554 	SMC_RET1(handle, MAKE_FFA_VERSION(FFA_VERSION_MAJOR,
555 					  FFA_VERSION_MINOR));
556 }
557 
558 /*******************************************************************************
559  * Helper function to obtain the FF-A version of the calling partition.
560  ******************************************************************************/
561 uint32_t get_partition_ffa_version(bool secure_origin)
562 {
563 	if (secure_origin) {
564 		return spmc_get_current_sp_ctx()->ffa_version;
565 	} else {
566 		return spmc_get_hyp_ctx()->ffa_version;
567 	}
568 }
569 
570 /*******************************************************************************
571  * This function will parse the Secure Partition Manifest. From manifest, it
572  * will fetch details for preparing Secure partition image context and secure
573  * partition image boot arguments if any.
574  ******************************************************************************/
575 static int sp_manifest_parse(void *sp_manifest, int offset,
576 			     struct secure_partition_desc *sp,
577 			     entry_point_info_t *ep_info)
578 {
579 	int32_t ret, node;
580 	uint32_t config_32;
581 
582 	/*
583 	 * Look for the mandatory fields that are expected to be present in
584 	 * the SP manifests.
585 	 */
586 	node = fdt_path_offset(sp_manifest, "/");
587 	if (node < 0) {
588 		ERROR("Did not find root node.\n");
589 		return node;
590 	}
591 
592 	ret = fdt_read_uint32_array(sp_manifest, node, "uuid",
593 				    ARRAY_SIZE(sp->uuid), sp->uuid);
594 	if (ret != 0) {
595 		ERROR("Missing Secure Partition UUID.\n");
596 		return ret;
597 	}
598 
599 	ret = fdt_read_uint32(sp_manifest, node, "exception-level", &config_32);
600 	if (ret != 0) {
601 		ERROR("Missing SP Exception Level information.\n");
602 		return ret;
603 	}
604 
605 	sp->runtime_el = config_32;
606 
607 	ret = fdt_read_uint32(sp_manifest, node, "ffa-version", &config_32);
608 	if (ret != 0) {
609 		ERROR("Missing Secure Partition FF-A Version.\n");
610 		return ret;
611 	}
612 
613 	sp->ffa_version = config_32;
614 
615 	ret = fdt_read_uint32(sp_manifest, node, "execution-state", &config_32);
616 	if (ret != 0) {
617 		ERROR("Missing Secure Partition Execution State.\n");
618 		return ret;
619 	}
620 
621 	sp->execution_state = config_32;
622 
623 	ret = fdt_read_uint32(sp_manifest, node,
624 			      "messaging-method", &config_32);
625 	if (ret != 0) {
626 		ERROR("Missing Secure Partition messaging method.\n");
627 		return ret;
628 	}
629 
630 	/* Validate this entry, we currently only support direct messaging. */
631 	if ((config_32 & ~(FFA_PARTITION_DIRECT_REQ_RECV |
632 			  FFA_PARTITION_DIRECT_REQ_SEND)) != 0U) {
633 		WARN("Invalid Secure Partition messaging method (0x%x)\n",
634 		     config_32);
635 		return -EINVAL;
636 	}
637 
638 	sp->properties = config_32;
639 
640 	ret = fdt_read_uint32(sp_manifest, node,
641 			      "execution-ctx-count", &config_32);
642 
643 	if (ret != 0) {
644 		ERROR("Missing SP Execution Context Count.\n");
645 		return ret;
646 	}
647 
648 	/*
649 	 * Ensure this field is set correctly in the manifest however
650 	 * since this is currently a hardcoded value for S-EL1 partitions
651 	 * we don't need to save it here, just validate.
652 	 */
653 	if (config_32 != PLATFORM_CORE_COUNT) {
654 		ERROR("SP Execution Context Count (%u) must be %u.\n",
655 			config_32, PLATFORM_CORE_COUNT);
656 		return -EINVAL;
657 	}
658 
659 	/*
660 	 * Look for the optional fields that are expected to be present in
661 	 * an SP manifest.
662 	 */
663 	ret = fdt_read_uint32(sp_manifest, node, "id", &config_32);
664 	if (ret != 0) {
665 		WARN("Missing Secure Partition ID.\n");
666 	} else {
667 		if (!is_ffa_secure_id_valid(config_32)) {
668 			ERROR("Invalid Secure Partition ID (0x%x).\n",
669 			      config_32);
670 			return -EINVAL;
671 		}
672 		sp->sp_id = config_32;
673 	}
674 
675 	return 0;
676 }
677 
678 /*******************************************************************************
679  * This function gets the Secure Partition Manifest base and maps the manifest
680  * region.
681  * Currently only one Secure Partition manifest is considered which is used to
682  * prepare the context for the single Secure Partition.
683  ******************************************************************************/
684 static int find_and_prepare_sp_context(void)
685 {
686 	void *sp_manifest;
687 	uintptr_t manifest_base;
688 	uintptr_t manifest_base_align;
689 	entry_point_info_t *next_image_ep_info;
690 	int32_t ret;
691 	struct secure_partition_desc *sp;
692 
693 	next_image_ep_info = bl31_plat_get_next_image_ep_info(SECURE);
694 	if (next_image_ep_info == NULL) {
695 		WARN("No Secure Partition image provided by BL2.\n");
696 		return -ENOENT;
697 	}
698 
699 	sp_manifest = (void *)next_image_ep_info->args.arg0;
700 	if (sp_manifest == NULL) {
701 		WARN("Secure Partition manifest absent.\n");
702 		return -ENOENT;
703 	}
704 
705 	manifest_base = (uintptr_t)sp_manifest;
706 	manifest_base_align = page_align(manifest_base, DOWN);
707 
708 	/*
709 	 * Map the secure partition manifest region in the EL3 translation
710 	 * regime.
711 	 * Map an area equal to (2 * PAGE_SIZE) for now. During manifest base
712 	 * alignment the region of 1 PAGE_SIZE from manifest align base may
713 	 * not completely accommodate the secure partition manifest region.
714 	 */
715 	ret = mmap_add_dynamic_region((unsigned long long)manifest_base_align,
716 				      manifest_base_align,
717 				      PAGE_SIZE * 2,
718 				      MT_RO_DATA);
719 	if (ret != 0) {
720 		ERROR("Error while mapping SP manifest (%d).\n", ret);
721 		return ret;
722 	}
723 
724 	ret = fdt_node_offset_by_compatible(sp_manifest, -1,
725 					    "arm,ffa-manifest-1.0");
726 	if (ret < 0) {
727 		ERROR("Error happened in SP manifest reading.\n");
728 		return -EINVAL;
729 	}
730 
731 	/*
732 	 * Store the size of the manifest so that it can be used later to pass
733 	 * the manifest as boot information later.
734 	 */
735 	next_image_ep_info->args.arg1 = fdt_totalsize(sp_manifest);
736 	INFO("Manifest size = %lu bytes.\n", next_image_ep_info->args.arg1);
737 
738 	/*
739 	 * Select an SP descriptor for initialising the partition's execution
740 	 * context on the primary CPU.
741 	 */
742 	sp = spmc_get_current_sp_ctx();
743 
744 	/* Initialize entry point information for the SP */
745 	SET_PARAM_HEAD(next_image_ep_info, PARAM_EP, VERSION_1,
746 		       SECURE | EP_ST_ENABLE);
747 
748 	/* Parse the SP manifest. */
749 	ret = sp_manifest_parse(sp_manifest, ret, sp, next_image_ep_info);
750 	if (ret != 0) {
751 		ERROR("Error in Secure Partition manifest parsing.\n");
752 		return ret;
753 	}
754 
755 	/* Check that the runtime EL in the manifest was correct. */
756 	if (sp->runtime_el != S_EL1) {
757 		ERROR("Unexpected runtime EL: %d\n", sp->runtime_el);
758 		return -EINVAL;
759 	}
760 
761 	/* Perform any common initialisation. */
762 	spmc_sp_common_setup(sp, next_image_ep_info);
763 
764 	/* Perform any initialisation specific to S-EL1 SPs. */
765 	spmc_el1_sp_setup(sp, next_image_ep_info);
766 
767 	/* Initialize the SP context with the required ep info. */
768 	spmc_sp_common_ep_commit(sp, next_image_ep_info);
769 
770 	return 0;
771 }
772 
773 /*******************************************************************************
774  * This function takes an SP context pointer and performs a synchronous entry
775  * into it.
776  ******************************************************************************/
777 static int32_t logical_sp_init(void)
778 {
779 	int32_t rc = 0;
780 	struct el3_lp_desc *el3_lp_descs;
781 
782 	/* Perform initial validation of the Logical Partitions. */
783 	rc = el3_sp_desc_validate();
784 	if (rc != 0) {
785 		ERROR("Logical Partition validation failed!\n");
786 		return rc;
787 	}
788 
789 	el3_lp_descs = get_el3_lp_array();
790 
791 	INFO("Logical Secure Partition init start.\n");
792 	for (unsigned int i = 0U; i < EL3_LP_DESCS_COUNT; i++) {
793 		rc = el3_lp_descs[i].init();
794 		if (rc != 0) {
795 			ERROR("Logical SP (0x%x) Failed to Initialize\n",
796 			      el3_lp_descs[i].sp_id);
797 			return rc;
798 		}
799 		VERBOSE("Logical SP (0x%x) Initialized\n",
800 			      el3_lp_descs[i].sp_id);
801 	}
802 
803 	INFO("Logical Secure Partition init completed.\n");
804 
805 	return rc;
806 }
807 
808 uint64_t spmc_sp_synchronous_entry(struct sp_exec_ctx *ec)
809 {
810 	uint64_t rc;
811 
812 	assert(ec != NULL);
813 
814 	/* Assign the context of the SP to this CPU */
815 	cm_set_context(&(ec->cpu_ctx), SECURE);
816 
817 	/* Restore the context assigned above */
818 	cm_el1_sysregs_context_restore(SECURE);
819 	cm_set_next_eret_context(SECURE);
820 
821 	/* Invalidate TLBs at EL1. */
822 	tlbivmalle1();
823 	dsbish();
824 
825 	/* Enter Secure Partition */
826 	rc = spm_secure_partition_enter(&ec->c_rt_ctx);
827 
828 	/* Save secure state */
829 	cm_el1_sysregs_context_save(SECURE);
830 
831 	return rc;
832 }
833 
834 /*******************************************************************************
835  * SPMC Helper Functions.
836  ******************************************************************************/
837 static int32_t sp_init(void)
838 {
839 	uint64_t rc;
840 	struct secure_partition_desc *sp;
841 	struct sp_exec_ctx *ec;
842 
843 	sp = spmc_get_current_sp_ctx();
844 	ec = spmc_get_sp_ec(sp);
845 	ec->rt_model = RT_MODEL_INIT;
846 	ec->rt_state = RT_STATE_RUNNING;
847 
848 	INFO("Secure Partition (0x%x) init start.\n", sp->sp_id);
849 
850 	rc = spmc_sp_synchronous_entry(ec);
851 	if (rc != 0) {
852 		/* Indicate SP init was not successful. */
853 		ERROR("SP (0x%x) failed to initialize (%lu).\n",
854 		      sp->sp_id, rc);
855 		return 0;
856 	}
857 
858 	ec->rt_state = RT_STATE_WAITING;
859 	INFO("Secure Partition initialized.\n");
860 
861 	return 1;
862 }
863 
864 static void initalize_sp_descs(void)
865 {
866 	struct secure_partition_desc *sp;
867 
868 	for (unsigned int i = 0U; i < SECURE_PARTITION_COUNT; i++) {
869 		sp = &sp_desc[i];
870 		sp->sp_id = INV_SP_ID;
871 		sp->mailbox.rx_buffer = NULL;
872 		sp->mailbox.tx_buffer = NULL;
873 		sp->mailbox.state = MAILBOX_STATE_EMPTY;
874 		sp->secondary_ep = 0;
875 	}
876 }
877 
878 static void initalize_ns_ep_descs(void)
879 {
880 	struct ns_endpoint_desc *ns_ep;
881 
882 	for (unsigned int i = 0U; i < NS_PARTITION_COUNT; i++) {
883 		ns_ep = &ns_ep_desc[i];
884 		/*
885 		 * Clashes with the Hypervisor ID but will not be a
886 		 * problem in practice.
887 		 */
888 		ns_ep->ns_ep_id = 0;
889 		ns_ep->ffa_version = 0;
890 		ns_ep->mailbox.rx_buffer = NULL;
891 		ns_ep->mailbox.tx_buffer = NULL;
892 		ns_ep->mailbox.state = MAILBOX_STATE_EMPTY;
893 	}
894 }
895 
896 /*******************************************************************************
897  * Initialize SPMC attributes for the SPMD.
898  ******************************************************************************/
899 void spmc_populate_attrs(spmc_manifest_attribute_t *spmc_attrs)
900 {
901 	spmc_attrs->major_version = FFA_VERSION_MAJOR;
902 	spmc_attrs->minor_version = FFA_VERSION_MINOR;
903 	spmc_attrs->exec_state = MODE_RW_64;
904 	spmc_attrs->spmc_id = FFA_SPMC_ID;
905 }
906 
907 /*******************************************************************************
908  * Initialize contexts of all Secure Partitions.
909  ******************************************************************************/
910 int32_t spmc_setup(void)
911 {
912 	int32_t ret;
913 
914 	/* Initialize endpoint descriptors */
915 	initalize_sp_descs();
916 	initalize_ns_ep_descs();
917 
918 	/* Setup logical SPs. */
919 	ret = logical_sp_init();
920 	if (ret != 0) {
921 		ERROR("Failed to initialize Logical Partitions.\n");
922 		return ret;
923 	}
924 
925 	/* Perform physical SP setup. */
926 
927 	/* Disable MMU at EL1 (initialized by BL2) */
928 	disable_mmu_icache_el1();
929 
930 	/* Initialize context of the SP */
931 	INFO("Secure Partition context setup start.\n");
932 
933 	ret = find_and_prepare_sp_context();
934 	if (ret != 0) {
935 		ERROR("Error in SP finding and context preparation.\n");
936 		return ret;
937 	}
938 
939 	/* Register init function for deferred init.  */
940 	bl31_register_bl32_init(&sp_init);
941 
942 	INFO("Secure Partition setup done.\n");
943 
944 	return 0;
945 }
946 
947 /*******************************************************************************
948  * Secure Partition Manager SMC handler.
949  ******************************************************************************/
950 uint64_t spmc_smc_handler(uint32_t smc_fid,
951 			  bool secure_origin,
952 			  uint64_t x1,
953 			  uint64_t x2,
954 			  uint64_t x3,
955 			  uint64_t x4,
956 			  void *cookie,
957 			  void *handle,
958 			  uint64_t flags)
959 {
960 	switch (smc_fid) {
961 
962 	case FFA_VERSION:
963 		return ffa_version_handler(smc_fid, secure_origin, x1, x2, x3,
964 					   x4, cookie, handle, flags);
965 
966 	case FFA_MSG_SEND_DIRECT_REQ_SMC32:
967 	case FFA_MSG_SEND_DIRECT_REQ_SMC64:
968 		return direct_req_smc_handler(smc_fid, secure_origin, x1, x2,
969 					      x3, x4, cookie, handle, flags);
970 
971 	case FFA_MSG_SEND_DIRECT_RESP_SMC32:
972 	case FFA_MSG_SEND_DIRECT_RESP_SMC64:
973 		return direct_resp_smc_handler(smc_fid, secure_origin, x1, x2,
974 					       x3, x4, cookie, handle, flags);
975 
976 	case FFA_MSG_WAIT:
977 		return msg_wait_handler(smc_fid, secure_origin, x1, x2, x3, x4,
978 					cookie, handle, flags);
979 
980 	case FFA_ERROR:
981 		return ffa_error_handler(smc_fid, secure_origin, x1, x2, x3, x4,
982 					cookie, handle, flags);
983 
984 	default:
985 		WARN("Unsupported FF-A call 0x%08x.\n", smc_fid);
986 		break;
987 	}
988 	return spmc_ffa_error_return(handle, FFA_ERROR_NOT_SUPPORTED);
989 }
990