xref: /rk3399_ARM-atf/services/std_svc/spm/el3_spmc/spmc_main.c (revision 1a752245ecae6487844c57667e24b704e6df8079)
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 static uint64_t rxtx_map_handler(uint32_t smc_fid,
571 				 bool secure_origin,
572 				 uint64_t x1,
573 				 uint64_t x2,
574 				 uint64_t x3,
575 				 uint64_t x4,
576 				 void *cookie,
577 				 void *handle,
578 				 uint64_t flags)
579 {
580 	int ret;
581 	uint32_t error_code;
582 	uint32_t mem_atts = secure_origin ? MT_SECURE : MT_NS;
583 	struct mailbox *mbox;
584 	uintptr_t tx_address = x1;
585 	uintptr_t rx_address = x2;
586 	uint32_t page_count = x3 & FFA_RXTX_PAGE_COUNT_MASK; /* Bits [5:0] */
587 	uint32_t buf_size = page_count * FFA_PAGE_SIZE;
588 
589 	/*
590 	 * The SPMC does not support mapping of VM RX/TX pairs to facilitate
591 	 * indirect messaging with SPs. Check if the Hypervisor has invoked this
592 	 * ABI on behalf of a VM and reject it if this is the case.
593 	 */
594 	if (tx_address == 0 || rx_address == 0) {
595 		WARN("Mapping RX/TX Buffers on behalf of VM not supported.\n");
596 		return spmc_ffa_error_return(handle,
597 					     FFA_ERROR_INVALID_PARAMETER);
598 	}
599 
600 	/* Ensure the specified buffers are not the same. */
601 	if (tx_address == rx_address) {
602 		WARN("TX Buffer must not be the same as RX Buffer.\n");
603 		return spmc_ffa_error_return(handle,
604 					     FFA_ERROR_INVALID_PARAMETER);
605 	}
606 
607 	/* Ensure the buffer size is not 0. */
608 	if (buf_size == 0U) {
609 		WARN("Buffer size must not be 0\n");
610 		return spmc_ffa_error_return(handle,
611 					     FFA_ERROR_INVALID_PARAMETER);
612 	}
613 
614 	/*
615 	 * Ensure the buffer size is a multiple of the translation granule size
616 	 * in TF-A.
617 	 */
618 	if (buf_size % PAGE_SIZE != 0U) {
619 		WARN("Buffer size must be aligned to translation granule.\n");
620 		return spmc_ffa_error_return(handle,
621 					     FFA_ERROR_INVALID_PARAMETER);
622 	}
623 
624 	/* Obtain the RX/TX buffer pair descriptor. */
625 	mbox = spmc_get_mbox_desc(secure_origin);
626 
627 	spin_lock(&mbox->lock);
628 
629 	/* Check if buffers have already been mapped. */
630 	if (mbox->rx_buffer != 0 || mbox->tx_buffer != 0) {
631 		WARN("RX/TX Buffers already mapped (%p/%p)\n",
632 		     (void *) mbox->rx_buffer, (void *)mbox->tx_buffer);
633 		error_code = FFA_ERROR_DENIED;
634 		goto err;
635 	}
636 
637 	/* memmap the TX buffer as read only. */
638 	ret = mmap_add_dynamic_region(tx_address, /* PA */
639 			tx_address, /* VA */
640 			buf_size, /* size */
641 			mem_atts | MT_RO_DATA); /* attrs */
642 	if (ret != 0) {
643 		/* Return the correct error code. */
644 		error_code = (ret == -ENOMEM) ? FFA_ERROR_NO_MEMORY :
645 						FFA_ERROR_INVALID_PARAMETER;
646 		WARN("Unable to map TX buffer: %d\n", error_code);
647 		goto err;
648 	}
649 
650 	/* memmap the RX buffer as read write. */
651 	ret = mmap_add_dynamic_region(rx_address, /* PA */
652 			rx_address, /* VA */
653 			buf_size, /* size */
654 			mem_atts | MT_RW_DATA); /* attrs */
655 
656 	if (ret != 0) {
657 		error_code = (ret == -ENOMEM) ? FFA_ERROR_NO_MEMORY :
658 						FFA_ERROR_INVALID_PARAMETER;
659 		WARN("Unable to map RX buffer: %d\n", error_code);
660 		/* Unmap the TX buffer again. */
661 		mmap_remove_dynamic_region(tx_address, buf_size);
662 		goto err;
663 	}
664 
665 	mbox->tx_buffer = (void *) tx_address;
666 	mbox->rx_buffer = (void *) rx_address;
667 	mbox->rxtx_page_count = page_count;
668 	spin_unlock(&mbox->lock);
669 
670 	SMC_RET1(handle, FFA_SUCCESS_SMC32);
671 	/* Execution stops here. */
672 err:
673 	spin_unlock(&mbox->lock);
674 	return spmc_ffa_error_return(handle, error_code);
675 }
676 
677 static uint64_t rxtx_unmap_handler(uint32_t smc_fid,
678 				   bool secure_origin,
679 				   uint64_t x1,
680 				   uint64_t x2,
681 				   uint64_t x3,
682 				   uint64_t x4,
683 				   void *cookie,
684 				   void *handle,
685 				   uint64_t flags)
686 {
687 	struct mailbox *mbox = spmc_get_mbox_desc(secure_origin);
688 	uint32_t buf_size = mbox->rxtx_page_count * FFA_PAGE_SIZE;
689 
690 	/*
691 	 * The SPMC does not support mapping of VM RX/TX pairs to facilitate
692 	 * indirect messaging with SPs. Check if the Hypervisor has invoked this
693 	 * ABI on behalf of a VM and reject it if this is the case.
694 	 */
695 	if (x1 != 0UL) {
696 		return spmc_ffa_error_return(handle,
697 					     FFA_ERROR_INVALID_PARAMETER);
698 	}
699 
700 	spin_lock(&mbox->lock);
701 
702 	/* Check if buffers are currently mapped. */
703 	if (mbox->rx_buffer == 0 || mbox->tx_buffer == 0) {
704 		spin_unlock(&mbox->lock);
705 		return spmc_ffa_error_return(handle,
706 					     FFA_ERROR_INVALID_PARAMETER);
707 	}
708 
709 	/* Unmap RX Buffer */
710 	if (mmap_remove_dynamic_region((uintptr_t) mbox->rx_buffer,
711 				       buf_size) != 0) {
712 		WARN("Unable to unmap RX buffer!\n");
713 	}
714 
715 	mbox->rx_buffer = 0;
716 
717 	/* Unmap TX Buffer */
718 	if (mmap_remove_dynamic_region((uintptr_t) mbox->tx_buffer,
719 				       buf_size) != 0) {
720 		WARN("Unable to unmap TX buffer!\n");
721 	}
722 
723 	mbox->tx_buffer = 0;
724 	mbox->rxtx_page_count = 0;
725 
726 	spin_unlock(&mbox->lock);
727 	SMC_RET1(handle, FFA_SUCCESS_SMC32);
728 }
729 
730 /*******************************************************************************
731  * This function will parse the Secure Partition Manifest. From manifest, it
732  * will fetch details for preparing Secure partition image context and secure
733  * partition image boot arguments if any.
734  ******************************************************************************/
735 static int sp_manifest_parse(void *sp_manifest, int offset,
736 			     struct secure_partition_desc *sp,
737 			     entry_point_info_t *ep_info)
738 {
739 	int32_t ret, node;
740 	uint32_t config_32;
741 
742 	/*
743 	 * Look for the mandatory fields that are expected to be present in
744 	 * the SP manifests.
745 	 */
746 	node = fdt_path_offset(sp_manifest, "/");
747 	if (node < 0) {
748 		ERROR("Did not find root node.\n");
749 		return node;
750 	}
751 
752 	ret = fdt_read_uint32_array(sp_manifest, node, "uuid",
753 				    ARRAY_SIZE(sp->uuid), sp->uuid);
754 	if (ret != 0) {
755 		ERROR("Missing Secure Partition UUID.\n");
756 		return ret;
757 	}
758 
759 	ret = fdt_read_uint32(sp_manifest, node, "exception-level", &config_32);
760 	if (ret != 0) {
761 		ERROR("Missing SP Exception Level information.\n");
762 		return ret;
763 	}
764 
765 	sp->runtime_el = config_32;
766 
767 	ret = fdt_read_uint32(sp_manifest, node, "ffa-version", &config_32);
768 	if (ret != 0) {
769 		ERROR("Missing Secure Partition FF-A Version.\n");
770 		return ret;
771 	}
772 
773 	sp->ffa_version = config_32;
774 
775 	ret = fdt_read_uint32(sp_manifest, node, "execution-state", &config_32);
776 	if (ret != 0) {
777 		ERROR("Missing Secure Partition Execution State.\n");
778 		return ret;
779 	}
780 
781 	sp->execution_state = config_32;
782 
783 	ret = fdt_read_uint32(sp_manifest, node,
784 			      "messaging-method", &config_32);
785 	if (ret != 0) {
786 		ERROR("Missing Secure Partition messaging method.\n");
787 		return ret;
788 	}
789 
790 	/* Validate this entry, we currently only support direct messaging. */
791 	if ((config_32 & ~(FFA_PARTITION_DIRECT_REQ_RECV |
792 			  FFA_PARTITION_DIRECT_REQ_SEND)) != 0U) {
793 		WARN("Invalid Secure Partition messaging method (0x%x)\n",
794 		     config_32);
795 		return -EINVAL;
796 	}
797 
798 	sp->properties = config_32;
799 
800 	ret = fdt_read_uint32(sp_manifest, node,
801 			      "execution-ctx-count", &config_32);
802 
803 	if (ret != 0) {
804 		ERROR("Missing SP Execution Context Count.\n");
805 		return ret;
806 	}
807 
808 	/*
809 	 * Ensure this field is set correctly in the manifest however
810 	 * since this is currently a hardcoded value for S-EL1 partitions
811 	 * we don't need to save it here, just validate.
812 	 */
813 	if (config_32 != PLATFORM_CORE_COUNT) {
814 		ERROR("SP Execution Context Count (%u) must be %u.\n",
815 			config_32, PLATFORM_CORE_COUNT);
816 		return -EINVAL;
817 	}
818 
819 	/*
820 	 * Look for the optional fields that are expected to be present in
821 	 * an SP manifest.
822 	 */
823 	ret = fdt_read_uint32(sp_manifest, node, "id", &config_32);
824 	if (ret != 0) {
825 		WARN("Missing Secure Partition ID.\n");
826 	} else {
827 		if (!is_ffa_secure_id_valid(config_32)) {
828 			ERROR("Invalid Secure Partition ID (0x%x).\n",
829 			      config_32);
830 			return -EINVAL;
831 		}
832 		sp->sp_id = config_32;
833 	}
834 
835 	return 0;
836 }
837 
838 /*******************************************************************************
839  * This function gets the Secure Partition Manifest base and maps the manifest
840  * region.
841  * Currently only one Secure Partition manifest is considered which is used to
842  * prepare the context for the single Secure Partition.
843  ******************************************************************************/
844 static int find_and_prepare_sp_context(void)
845 {
846 	void *sp_manifest;
847 	uintptr_t manifest_base;
848 	uintptr_t manifest_base_align;
849 	entry_point_info_t *next_image_ep_info;
850 	int32_t ret;
851 	struct secure_partition_desc *sp;
852 
853 	next_image_ep_info = bl31_plat_get_next_image_ep_info(SECURE);
854 	if (next_image_ep_info == NULL) {
855 		WARN("No Secure Partition image provided by BL2.\n");
856 		return -ENOENT;
857 	}
858 
859 	sp_manifest = (void *)next_image_ep_info->args.arg0;
860 	if (sp_manifest == NULL) {
861 		WARN("Secure Partition manifest absent.\n");
862 		return -ENOENT;
863 	}
864 
865 	manifest_base = (uintptr_t)sp_manifest;
866 	manifest_base_align = page_align(manifest_base, DOWN);
867 
868 	/*
869 	 * Map the secure partition manifest region in the EL3 translation
870 	 * regime.
871 	 * Map an area equal to (2 * PAGE_SIZE) for now. During manifest base
872 	 * alignment the region of 1 PAGE_SIZE from manifest align base may
873 	 * not completely accommodate the secure partition manifest region.
874 	 */
875 	ret = mmap_add_dynamic_region((unsigned long long)manifest_base_align,
876 				      manifest_base_align,
877 				      PAGE_SIZE * 2,
878 				      MT_RO_DATA);
879 	if (ret != 0) {
880 		ERROR("Error while mapping SP manifest (%d).\n", ret);
881 		return ret;
882 	}
883 
884 	ret = fdt_node_offset_by_compatible(sp_manifest, -1,
885 					    "arm,ffa-manifest-1.0");
886 	if (ret < 0) {
887 		ERROR("Error happened in SP manifest reading.\n");
888 		return -EINVAL;
889 	}
890 
891 	/*
892 	 * Store the size of the manifest so that it can be used later to pass
893 	 * the manifest as boot information later.
894 	 */
895 	next_image_ep_info->args.arg1 = fdt_totalsize(sp_manifest);
896 	INFO("Manifest size = %lu bytes.\n", next_image_ep_info->args.arg1);
897 
898 	/*
899 	 * Select an SP descriptor for initialising the partition's execution
900 	 * context on the primary CPU.
901 	 */
902 	sp = spmc_get_current_sp_ctx();
903 
904 	/* Initialize entry point information for the SP */
905 	SET_PARAM_HEAD(next_image_ep_info, PARAM_EP, VERSION_1,
906 		       SECURE | EP_ST_ENABLE);
907 
908 	/* Parse the SP manifest. */
909 	ret = sp_manifest_parse(sp_manifest, ret, sp, next_image_ep_info);
910 	if (ret != 0) {
911 		ERROR("Error in Secure Partition manifest parsing.\n");
912 		return ret;
913 	}
914 
915 	/* Check that the runtime EL in the manifest was correct. */
916 	if (sp->runtime_el != S_EL1) {
917 		ERROR("Unexpected runtime EL: %d\n", sp->runtime_el);
918 		return -EINVAL;
919 	}
920 
921 	/* Perform any common initialisation. */
922 	spmc_sp_common_setup(sp, next_image_ep_info);
923 
924 	/* Perform any initialisation specific to S-EL1 SPs. */
925 	spmc_el1_sp_setup(sp, next_image_ep_info);
926 
927 	/* Initialize the SP context with the required ep info. */
928 	spmc_sp_common_ep_commit(sp, next_image_ep_info);
929 
930 	return 0;
931 }
932 
933 /*******************************************************************************
934  * This function takes an SP context pointer and performs a synchronous entry
935  * into it.
936  ******************************************************************************/
937 static int32_t logical_sp_init(void)
938 {
939 	int32_t rc = 0;
940 	struct el3_lp_desc *el3_lp_descs;
941 
942 	/* Perform initial validation of the Logical Partitions. */
943 	rc = el3_sp_desc_validate();
944 	if (rc != 0) {
945 		ERROR("Logical Partition validation failed!\n");
946 		return rc;
947 	}
948 
949 	el3_lp_descs = get_el3_lp_array();
950 
951 	INFO("Logical Secure Partition init start.\n");
952 	for (unsigned int i = 0U; i < EL3_LP_DESCS_COUNT; i++) {
953 		rc = el3_lp_descs[i].init();
954 		if (rc != 0) {
955 			ERROR("Logical SP (0x%x) Failed to Initialize\n",
956 			      el3_lp_descs[i].sp_id);
957 			return rc;
958 		}
959 		VERBOSE("Logical SP (0x%x) Initialized\n",
960 			      el3_lp_descs[i].sp_id);
961 	}
962 
963 	INFO("Logical Secure Partition init completed.\n");
964 
965 	return rc;
966 }
967 
968 uint64_t spmc_sp_synchronous_entry(struct sp_exec_ctx *ec)
969 {
970 	uint64_t rc;
971 
972 	assert(ec != NULL);
973 
974 	/* Assign the context of the SP to this CPU */
975 	cm_set_context(&(ec->cpu_ctx), SECURE);
976 
977 	/* Restore the context assigned above */
978 	cm_el1_sysregs_context_restore(SECURE);
979 	cm_set_next_eret_context(SECURE);
980 
981 	/* Invalidate TLBs at EL1. */
982 	tlbivmalle1();
983 	dsbish();
984 
985 	/* Enter Secure Partition */
986 	rc = spm_secure_partition_enter(&ec->c_rt_ctx);
987 
988 	/* Save secure state */
989 	cm_el1_sysregs_context_save(SECURE);
990 
991 	return rc;
992 }
993 
994 /*******************************************************************************
995  * SPMC Helper Functions.
996  ******************************************************************************/
997 static int32_t sp_init(void)
998 {
999 	uint64_t rc;
1000 	struct secure_partition_desc *sp;
1001 	struct sp_exec_ctx *ec;
1002 
1003 	sp = spmc_get_current_sp_ctx();
1004 	ec = spmc_get_sp_ec(sp);
1005 	ec->rt_model = RT_MODEL_INIT;
1006 	ec->rt_state = RT_STATE_RUNNING;
1007 
1008 	INFO("Secure Partition (0x%x) init start.\n", sp->sp_id);
1009 
1010 	rc = spmc_sp_synchronous_entry(ec);
1011 	if (rc != 0) {
1012 		/* Indicate SP init was not successful. */
1013 		ERROR("SP (0x%x) failed to initialize (%lu).\n",
1014 		      sp->sp_id, rc);
1015 		return 0;
1016 	}
1017 
1018 	ec->rt_state = RT_STATE_WAITING;
1019 	INFO("Secure Partition initialized.\n");
1020 
1021 	return 1;
1022 }
1023 
1024 static void initalize_sp_descs(void)
1025 {
1026 	struct secure_partition_desc *sp;
1027 
1028 	for (unsigned int i = 0U; i < SECURE_PARTITION_COUNT; i++) {
1029 		sp = &sp_desc[i];
1030 		sp->sp_id = INV_SP_ID;
1031 		sp->mailbox.rx_buffer = NULL;
1032 		sp->mailbox.tx_buffer = NULL;
1033 		sp->mailbox.state = MAILBOX_STATE_EMPTY;
1034 		sp->secondary_ep = 0;
1035 	}
1036 }
1037 
1038 static void initalize_ns_ep_descs(void)
1039 {
1040 	struct ns_endpoint_desc *ns_ep;
1041 
1042 	for (unsigned int i = 0U; i < NS_PARTITION_COUNT; i++) {
1043 		ns_ep = &ns_ep_desc[i];
1044 		/*
1045 		 * Clashes with the Hypervisor ID but will not be a
1046 		 * problem in practice.
1047 		 */
1048 		ns_ep->ns_ep_id = 0;
1049 		ns_ep->ffa_version = 0;
1050 		ns_ep->mailbox.rx_buffer = NULL;
1051 		ns_ep->mailbox.tx_buffer = NULL;
1052 		ns_ep->mailbox.state = MAILBOX_STATE_EMPTY;
1053 	}
1054 }
1055 
1056 /*******************************************************************************
1057  * Initialize SPMC attributes for the SPMD.
1058  ******************************************************************************/
1059 void spmc_populate_attrs(spmc_manifest_attribute_t *spmc_attrs)
1060 {
1061 	spmc_attrs->major_version = FFA_VERSION_MAJOR;
1062 	spmc_attrs->minor_version = FFA_VERSION_MINOR;
1063 	spmc_attrs->exec_state = MODE_RW_64;
1064 	spmc_attrs->spmc_id = FFA_SPMC_ID;
1065 }
1066 
1067 /*******************************************************************************
1068  * Initialize contexts of all Secure Partitions.
1069  ******************************************************************************/
1070 int32_t spmc_setup(void)
1071 {
1072 	int32_t ret;
1073 
1074 	/* Initialize endpoint descriptors */
1075 	initalize_sp_descs();
1076 	initalize_ns_ep_descs();
1077 
1078 	/* Setup logical SPs. */
1079 	ret = logical_sp_init();
1080 	if (ret != 0) {
1081 		ERROR("Failed to initialize Logical Partitions.\n");
1082 		return ret;
1083 	}
1084 
1085 	/* Perform physical SP setup. */
1086 
1087 	/* Disable MMU at EL1 (initialized by BL2) */
1088 	disable_mmu_icache_el1();
1089 
1090 	/* Initialize context of the SP */
1091 	INFO("Secure Partition context setup start.\n");
1092 
1093 	ret = find_and_prepare_sp_context();
1094 	if (ret != 0) {
1095 		ERROR("Error in SP finding and context preparation.\n");
1096 		return ret;
1097 	}
1098 
1099 	/* Register init function for deferred init.  */
1100 	bl31_register_bl32_init(&sp_init);
1101 
1102 	INFO("Secure Partition setup done.\n");
1103 
1104 	return 0;
1105 }
1106 
1107 /*******************************************************************************
1108  * Secure Partition Manager SMC handler.
1109  ******************************************************************************/
1110 uint64_t spmc_smc_handler(uint32_t smc_fid,
1111 			  bool secure_origin,
1112 			  uint64_t x1,
1113 			  uint64_t x2,
1114 			  uint64_t x3,
1115 			  uint64_t x4,
1116 			  void *cookie,
1117 			  void *handle,
1118 			  uint64_t flags)
1119 {
1120 	switch (smc_fid) {
1121 
1122 	case FFA_VERSION:
1123 		return ffa_version_handler(smc_fid, secure_origin, x1, x2, x3,
1124 					   x4, cookie, handle, flags);
1125 
1126 	case FFA_MSG_SEND_DIRECT_REQ_SMC32:
1127 	case FFA_MSG_SEND_DIRECT_REQ_SMC64:
1128 		return direct_req_smc_handler(smc_fid, secure_origin, x1, x2,
1129 					      x3, x4, cookie, handle, flags);
1130 
1131 	case FFA_MSG_SEND_DIRECT_RESP_SMC32:
1132 	case FFA_MSG_SEND_DIRECT_RESP_SMC64:
1133 		return direct_resp_smc_handler(smc_fid, secure_origin, x1, x2,
1134 					       x3, x4, cookie, handle, flags);
1135 
1136 	case FFA_RXTX_MAP_SMC32:
1137 	case FFA_RXTX_MAP_SMC64:
1138 		return rxtx_map_handler(smc_fid, secure_origin, x1, x2, x3, x4,
1139 					cookie, handle, flags);
1140 
1141 	case FFA_RXTX_UNMAP:
1142 		return rxtx_unmap_handler(smc_fid, secure_origin, x1, x2, x3,
1143 					  x4, cookie, handle, flags);
1144 
1145 	case FFA_MSG_WAIT:
1146 		return msg_wait_handler(smc_fid, secure_origin, x1, x2, x3, x4,
1147 					cookie, handle, flags);
1148 
1149 	case FFA_ERROR:
1150 		return ffa_error_handler(smc_fid, secure_origin, x1, x2, x3, x4,
1151 					cookie, handle, flags);
1152 
1153 	default:
1154 		WARN("Unsupported FF-A call 0x%08x.\n", smc_fid);
1155 		break;
1156 	}
1157 	return spmc_ffa_error_return(handle, FFA_ERROR_NOT_SUPPORTED);
1158 }
1159