xref: /rk3399_ARM-atf/services/std_svc/spm/el3_spmc/spmc_shared_mem.c (revision dd9fae1ce0e7b985c9fe8f8f8ae358b8c166c6a9)
1 /*
2  * Copyright (c) 2022-2023, ARM Limited and Contributors. All rights reserved.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 #include <assert.h>
7 #include <errno.h>
8 #include <inttypes.h>
9 
10 #include <common/debug.h>
11 #include <common/runtime_svc.h>
12 #include <lib/object_pool.h>
13 #include <lib/spinlock.h>
14 #include <lib/xlat_tables/xlat_tables_v2.h>
15 #include <services/ffa_svc.h>
16 #include "spmc.h"
17 #include "spmc_shared_mem.h"
18 
19 #include <platform_def.h>
20 
21 /**
22  * struct spmc_shmem_obj - Shared memory object.
23  * @desc_size:      Size of @desc.
24  * @desc_filled:    Size of @desc already received.
25  * @in_use:         Number of clients that have called ffa_mem_retrieve_req
26  *                  without a matching ffa_mem_relinquish call.
27  * @desc:           FF-A memory region descriptor passed in ffa_mem_share.
28  */
29 struct spmc_shmem_obj {
30 	size_t desc_size;
31 	size_t desc_filled;
32 	size_t in_use;
33 	struct ffa_mtd desc;
34 };
35 
36 /*
37  * Declare our data structure to store the metadata of memory share requests.
38  * The main datastore is allocated on a per platform basis to ensure enough
39  * storage can be made available.
40  * The address of the data store will be populated by the SPMC during its
41  * initialization.
42  */
43 
44 struct spmc_shmem_obj_state spmc_shmem_obj_state = {
45 	/* Set start value for handle so top 32 bits are needed quickly. */
46 	.next_handle = 0xffffffc0U,
47 };
48 
49 /**
50  * spmc_shmem_obj_size - Convert from descriptor size to object size.
51  * @desc_size:  Size of struct ffa_memory_region_descriptor object.
52  *
53  * Return: Size of struct spmc_shmem_obj object.
54  */
55 static size_t spmc_shmem_obj_size(size_t desc_size)
56 {
57 	return desc_size + offsetof(struct spmc_shmem_obj, desc);
58 }
59 
60 /**
61  * spmc_shmem_obj_alloc - Allocate struct spmc_shmem_obj.
62  * @state:      Global state.
63  * @desc_size:  Size of struct ffa_memory_region_descriptor object that
64  *              allocated object will hold.
65  *
66  * Return: Pointer to newly allocated object, or %NULL if there not enough space
67  *         left. The returned pointer is only valid while @state is locked, to
68  *         used it again after unlocking @state, spmc_shmem_obj_lookup must be
69  *         called.
70  */
71 static struct spmc_shmem_obj *
72 spmc_shmem_obj_alloc(struct spmc_shmem_obj_state *state, size_t desc_size)
73 {
74 	struct spmc_shmem_obj *obj;
75 	size_t free = state->data_size - state->allocated;
76 	size_t obj_size;
77 
78 	if (state->data == NULL) {
79 		ERROR("Missing shmem datastore!\n");
80 		return NULL;
81 	}
82 
83 	obj_size = spmc_shmem_obj_size(desc_size);
84 
85 	/* Ensure the obj size has not overflowed. */
86 	if (obj_size < desc_size) {
87 		WARN("%s(0x%zx) desc_size overflow\n",
88 		     __func__, desc_size);
89 		return NULL;
90 	}
91 
92 	if (obj_size > free) {
93 		WARN("%s(0x%zx) failed, free 0x%zx\n",
94 		     __func__, desc_size, free);
95 		return NULL;
96 	}
97 	obj = (struct spmc_shmem_obj *)(state->data + state->allocated);
98 	obj->desc = (struct ffa_mtd) {0};
99 	obj->desc_size = desc_size;
100 	obj->desc_filled = 0;
101 	obj->in_use = 0;
102 	state->allocated += obj_size;
103 	return obj;
104 }
105 
106 /**
107  * spmc_shmem_obj_free - Free struct spmc_shmem_obj.
108  * @state:      Global state.
109  * @obj:        Object to free.
110  *
111  * Release memory used by @obj. Other objects may move, so on return all
112  * pointers to struct spmc_shmem_obj object should be considered invalid, not
113  * just @obj.
114  *
115  * The current implementation always compacts the remaining objects to simplify
116  * the allocator and to avoid fragmentation.
117  */
118 
119 static void spmc_shmem_obj_free(struct spmc_shmem_obj_state *state,
120 				  struct spmc_shmem_obj *obj)
121 {
122 	size_t free_size = spmc_shmem_obj_size(obj->desc_size);
123 	uint8_t *shift_dest = (uint8_t *)obj;
124 	uint8_t *shift_src = shift_dest + free_size;
125 	size_t shift_size = state->allocated - (shift_src - state->data);
126 
127 	if (shift_size != 0U) {
128 		memmove(shift_dest, shift_src, shift_size);
129 	}
130 	state->allocated -= free_size;
131 }
132 
133 /**
134  * spmc_shmem_obj_lookup - Lookup struct spmc_shmem_obj by handle.
135  * @state:      Global state.
136  * @handle:     Unique handle of object to return.
137  *
138  * Return: struct spmc_shmem_obj_state object with handle matching @handle.
139  *         %NULL, if not object in @state->data has a matching handle.
140  */
141 static struct spmc_shmem_obj *
142 spmc_shmem_obj_lookup(struct spmc_shmem_obj_state *state, uint64_t handle)
143 {
144 	uint8_t *curr = state->data;
145 
146 	while (curr - state->data < state->allocated) {
147 		struct spmc_shmem_obj *obj = (struct spmc_shmem_obj *)curr;
148 
149 		if (obj->desc.handle == handle) {
150 			return obj;
151 		}
152 		curr += spmc_shmem_obj_size(obj->desc_size);
153 	}
154 	return NULL;
155 }
156 
157 /**
158  * spmc_shmem_obj_get_next - Get the next memory object from an offset.
159  * @offset:     Offset used to track which objects have previously been
160  *              returned.
161  *
162  * Return: the next struct spmc_shmem_obj_state object from the provided
163  *	   offset.
164  *	   %NULL, if there are no more objects.
165  */
166 static struct spmc_shmem_obj *
167 spmc_shmem_obj_get_next(struct spmc_shmem_obj_state *state, size_t *offset)
168 {
169 	uint8_t *curr = state->data + *offset;
170 
171 	if (curr - state->data < state->allocated) {
172 		struct spmc_shmem_obj *obj = (struct spmc_shmem_obj *)curr;
173 
174 		*offset += spmc_shmem_obj_size(obj->desc_size);
175 
176 		return obj;
177 	}
178 	return NULL;
179 }
180 
181 /*******************************************************************************
182  * FF-A memory descriptor helper functions.
183  ******************************************************************************/
184 /**
185  * spmc_shmem_obj_get_emad - Get the emad from a given index depending on the
186  *                           clients FF-A version.
187  * @desc:         The memory transaction descriptor.
188  * @index:        The index of the emad element to be accessed.
189  * @ffa_version:  FF-A version of the provided structure.
190  * @emad_size:    Will be populated with the size of the returned emad
191  *                descriptor.
192  * Return: A pointer to the requested emad structure.
193  */
194 static void *
195 spmc_shmem_obj_get_emad(const struct ffa_mtd *desc, uint32_t index,
196 			uint32_t ffa_version, size_t *emad_size)
197 {
198 	uint8_t *emad;
199 
200 	assert(index < desc->emad_count);
201 
202 	/*
203 	 * If the caller is using FF-A v1.0 interpret the descriptor as a v1.0
204 	 * format, otherwise assume it is a v1.1 format.
205 	 */
206 	if (ffa_version == MAKE_FFA_VERSION(1, 0)) {
207 		emad = (uint8_t *)desc + offsetof(struct ffa_mtd_v1_0, emad);
208 		*emad_size = sizeof(struct ffa_emad_v1_0);
209 	} else {
210 		assert(is_aligned(desc->emad_offset, 16));
211 		emad = ((uint8_t *) desc + desc->emad_offset);
212 		*emad_size = desc->emad_size;
213 	}
214 
215 	assert(((uint64_t)index * (uint64_t)*emad_size) <= UINT32_MAX);
216 	return (emad + (*emad_size * index));
217 }
218 
219 /**
220  * spmc_shmem_obj_get_comp_mrd - Get comp_mrd from a mtd struct based on the
221  *				 FF-A version of the descriptor.
222  * @obj:    Object containing ffa_memory_region_descriptor.
223  *
224  * Return: struct ffa_comp_mrd object corresponding to the composite memory
225  *	   region descriptor.
226  */
227 static struct ffa_comp_mrd *
228 spmc_shmem_obj_get_comp_mrd(struct spmc_shmem_obj *obj, uint32_t ffa_version)
229 {
230 	size_t emad_size;
231 	/*
232 	 * The comp_mrd_offset field of the emad descriptor remains consistent
233 	 * between FF-A versions therefore we can use the v1.0 descriptor here
234 	 * in all cases.
235 	 */
236 	struct ffa_emad_v1_0 *emad = spmc_shmem_obj_get_emad(&obj->desc, 0,
237 							     ffa_version,
238 							     &emad_size);
239 
240 	/* Ensure the composite descriptor offset is aligned. */
241 	if (!is_aligned(emad->comp_mrd_offset, 8)) {
242 		WARN("Unaligned composite memory region descriptor offset.\n");
243 		return NULL;
244 	}
245 
246 	return (struct ffa_comp_mrd *)
247 	       ((uint8_t *)(&obj->desc) + emad->comp_mrd_offset);
248 }
249 
250 /**
251  * spmc_shmem_obj_ffa_constituent_size - Calculate variable size part of obj.
252  * @obj:    Object containing ffa_memory_region_descriptor.
253  *
254  * Return: Size of ffa_constituent_memory_region_descriptors in @obj.
255  */
256 static size_t
257 spmc_shmem_obj_ffa_constituent_size(struct spmc_shmem_obj *obj,
258 				    uint32_t ffa_version)
259 {
260 	struct ffa_comp_mrd *comp_mrd;
261 
262 	comp_mrd = spmc_shmem_obj_get_comp_mrd(obj, ffa_version);
263 	if (comp_mrd == NULL) {
264 		return 0;
265 	}
266 	return comp_mrd->address_range_count * sizeof(struct ffa_cons_mrd);
267 }
268 
269 /**
270  * spmc_shmem_obj_validate_id - Validate a partition ID is participating in
271  *				a given memory transaction.
272  * @sp_id:      Partition ID to validate.
273  * @obj:        The shared memory object containing the descriptor
274  *              of the memory transaction.
275  * Return: true if ID is valid, else false.
276  */
277 bool spmc_shmem_obj_validate_id(struct spmc_shmem_obj *obj, uint16_t sp_id)
278 {
279 	bool found = false;
280 	struct ffa_mtd *desc = &obj->desc;
281 	size_t desc_size = obj->desc_size;
282 
283 	/* Validate the partition is a valid participant. */
284 	for (unsigned int i = 0U; i < desc->emad_count; i++) {
285 		size_t emad_size;
286 		struct ffa_emad_v1_0 *emad;
287 
288 		emad = spmc_shmem_obj_get_emad(desc, i,
289 					       MAKE_FFA_VERSION(1, 1),
290 					       &emad_size);
291 		/*
292 		 * Validate the calculated emad address resides within the
293 		 * descriptor.
294 		 */
295 		if ((emad == NULL) || (uintptr_t) emad >=
296 		    (uintptr_t)((uint8_t *) desc + desc_size)) {
297 			VERBOSE("Invalid emad.\n");
298 			break;
299 		}
300 		if (sp_id == emad->mapd.endpoint_id) {
301 			found = true;
302 			break;
303 		}
304 	}
305 	return found;
306 }
307 
308 /*
309  * Compare two memory regions to determine if any range overlaps with another
310  * ongoing memory transaction.
311  */
312 static bool
313 overlapping_memory_regions(struct ffa_comp_mrd *region1,
314 			   struct ffa_comp_mrd *region2)
315 {
316 	uint64_t region1_start;
317 	uint64_t region1_size;
318 	uint64_t region1_end;
319 	uint64_t region2_start;
320 	uint64_t region2_size;
321 	uint64_t region2_end;
322 
323 	assert(region1 != NULL);
324 	assert(region2 != NULL);
325 
326 	if (region1 == region2) {
327 		return true;
328 	}
329 
330 	/*
331 	 * Check each memory region in the request against existing
332 	 * transactions.
333 	 */
334 	for (size_t i = 0; i < region1->address_range_count; i++) {
335 
336 		region1_start = region1->address_range_array[i].address;
337 		region1_size =
338 			region1->address_range_array[i].page_count *
339 			PAGE_SIZE_4KB;
340 		region1_end = region1_start + region1_size;
341 
342 		for (size_t j = 0; j < region2->address_range_count; j++) {
343 
344 			region2_start = region2->address_range_array[j].address;
345 			region2_size =
346 				region2->address_range_array[j].page_count *
347 				PAGE_SIZE_4KB;
348 			region2_end = region2_start + region2_size;
349 
350 			/* Check if regions are not overlapping. */
351 			if (!((region2_end <= region1_start) ||
352 			      (region1_end <= region2_start))) {
353 				WARN("Overlapping mem regions 0x%lx-0x%lx & 0x%lx-0x%lx\n",
354 				     region1_start, region1_end,
355 				     region2_start, region2_end);
356 				return true;
357 			}
358 		}
359 	}
360 	return false;
361 }
362 
363 /*******************************************************************************
364  * FF-A v1.0 Memory Descriptor Conversion Helpers.
365  ******************************************************************************/
366 /**
367  * spmc_shm_get_v1_1_descriptor_size - Calculate the required size for a v1.1
368  *                                     converted descriptor.
369  * @orig:       The original v1.0 memory transaction descriptor.
370  * @desc_size:  The size of the original v1.0 memory transaction descriptor.
371  *
372  * Return: the size required to store the descriptor store in the v1.1 format.
373  */
374 static size_t
375 spmc_shm_get_v1_1_descriptor_size(struct ffa_mtd_v1_0 *orig, size_t desc_size)
376 {
377 	size_t size = 0;
378 	struct ffa_comp_mrd *mrd;
379 	struct ffa_emad_v1_0 *emad_array = orig->emad;
380 
381 	/* Get the size of the v1.1 descriptor. */
382 	size += sizeof(struct ffa_mtd);
383 
384 	/* Add the size of the emad descriptors. */
385 	size += orig->emad_count * sizeof(struct ffa_emad_v1_0);
386 
387 	/* Add the size of the composite mrds. */
388 	size += sizeof(struct ffa_comp_mrd);
389 
390 	/* Add the size of the constituent mrds. */
391 	mrd = (struct ffa_comp_mrd *) ((uint8_t *) orig +
392 	      emad_array[0].comp_mrd_offset);
393 
394 	/* Check the calculated address is within the memory descriptor. */
395 	if (((uintptr_t) mrd + sizeof(struct ffa_comp_mrd)) >
396 	    (uintptr_t)((uint8_t *) orig + desc_size)) {
397 		return 0;
398 	}
399 	size += mrd->address_range_count * sizeof(struct ffa_cons_mrd);
400 
401 	return size;
402 }
403 
404 /**
405  * spmc_shm_get_v1_0_descriptor_size - Calculate the required size for a v1.0
406  *                                     converted descriptor.
407  * @orig:       The original v1.1 memory transaction descriptor.
408  * @desc_size:  The size of the original v1.1 memory transaction descriptor.
409  *
410  * Return: the size required to store the descriptor store in the v1.0 format.
411  */
412 static size_t
413 spmc_shm_get_v1_0_descriptor_size(struct ffa_mtd *orig, size_t desc_size)
414 {
415 	size_t size = 0;
416 	struct ffa_comp_mrd *mrd;
417 	struct ffa_emad_v1_0 *emad_array = (struct ffa_emad_v1_0 *)
418 					   ((uint8_t *) orig +
419 					    orig->emad_offset);
420 
421 	/* Get the size of the v1.0 descriptor. */
422 	size += sizeof(struct ffa_mtd_v1_0);
423 
424 	/* Add the size of the v1.0 emad descriptors. */
425 	size += orig->emad_count * sizeof(struct ffa_emad_v1_0);
426 
427 	/* Add the size of the composite mrds. */
428 	size += sizeof(struct ffa_comp_mrd);
429 
430 	/* Add the size of the constituent mrds. */
431 	mrd = (struct ffa_comp_mrd *) ((uint8_t *) orig +
432 	      emad_array[0].comp_mrd_offset);
433 
434 	/* Check the calculated address is within the memory descriptor. */
435 	if (((uintptr_t) mrd + sizeof(struct ffa_comp_mrd)) >
436 	    (uintptr_t)((uint8_t *) orig + desc_size)) {
437 		return 0;
438 	}
439 	size += mrd->address_range_count * sizeof(struct ffa_cons_mrd);
440 
441 	return size;
442 }
443 
444 /**
445  * spmc_shm_convert_shmem_obj_from_v1_0 - Converts a given v1.0 memory object.
446  * @out_obj:	The shared memory object to populate the converted descriptor.
447  * @orig:	The shared memory object containing the v1.0 descriptor.
448  *
449  * Return: true if the conversion is successful else false.
450  */
451 static bool
452 spmc_shm_convert_shmem_obj_from_v1_0(struct spmc_shmem_obj *out_obj,
453 				     struct spmc_shmem_obj *orig)
454 {
455 	struct ffa_mtd_v1_0 *mtd_orig = (struct ffa_mtd_v1_0 *) &orig->desc;
456 	struct ffa_mtd *out = &out_obj->desc;
457 	struct ffa_emad_v1_0 *emad_array_in;
458 	struct ffa_emad_v1_0 *emad_array_out;
459 	struct ffa_comp_mrd *mrd_in;
460 	struct ffa_comp_mrd *mrd_out;
461 
462 	size_t mrd_in_offset;
463 	size_t mrd_out_offset;
464 	size_t mrd_size = 0;
465 
466 	/* Populate the new descriptor format from the v1.0 struct. */
467 	out->sender_id = mtd_orig->sender_id;
468 	out->memory_region_attributes = mtd_orig->memory_region_attributes;
469 	out->flags = mtd_orig->flags;
470 	out->handle = mtd_orig->handle;
471 	out->tag = mtd_orig->tag;
472 	out->emad_count = mtd_orig->emad_count;
473 	out->emad_size = sizeof(struct ffa_emad_v1_0);
474 
475 	/*
476 	 * We will locate the emad descriptors directly after the ffa_mtd
477 	 * struct. This will be 8-byte aligned.
478 	 */
479 	out->emad_offset = sizeof(struct ffa_mtd);
480 
481 	emad_array_in = mtd_orig->emad;
482 	emad_array_out = (struct ffa_emad_v1_0 *)
483 			 ((uint8_t *) out + out->emad_offset);
484 
485 	/* Copy across the emad structs. */
486 	for (unsigned int i = 0U; i < out->emad_count; i++) {
487 		/* Bound check for emad array. */
488 		if (((uint8_t *)emad_array_in + sizeof(struct ffa_emad_v1_0)) >
489 		    ((uint8_t *) mtd_orig + orig->desc_size)) {
490 			VERBOSE("%s: Invalid mtd structure.\n", __func__);
491 			return false;
492 		}
493 		memcpy(&emad_array_out[i], &emad_array_in[i],
494 		       sizeof(struct ffa_emad_v1_0));
495 	}
496 
497 	/* Place the mrd descriptors after the end of the emad descriptors.*/
498 	mrd_in_offset = emad_array_in->comp_mrd_offset;
499 	mrd_out_offset = out->emad_offset + (out->emad_size * out->emad_count);
500 	mrd_out = (struct ffa_comp_mrd *) ((uint8_t *) out + mrd_out_offset);
501 
502 	/* Add the size of the composite memory region descriptor. */
503 	mrd_size += sizeof(struct ffa_comp_mrd);
504 
505 	/* Find the mrd descriptor. */
506 	mrd_in = (struct ffa_comp_mrd *) ((uint8_t *) mtd_orig + mrd_in_offset);
507 
508 	/* Add the size of the constituent memory region descriptors. */
509 	mrd_size += mrd_in->address_range_count * sizeof(struct ffa_cons_mrd);
510 
511 	/*
512 	 * Update the offset in the emads by the delta between the input and
513 	 * output addresses.
514 	 */
515 	for (unsigned int i = 0U; i < out->emad_count; i++) {
516 		emad_array_out[i].comp_mrd_offset =
517 			emad_array_in[i].comp_mrd_offset +
518 			(mrd_out_offset - mrd_in_offset);
519 	}
520 
521 	/* Verify that we stay within bound of the memory descriptors. */
522 	if ((uintptr_t)((uint8_t *) mrd_in + mrd_size) >
523 	     (uintptr_t)((uint8_t *) mtd_orig + orig->desc_size) ||
524 	    ((uintptr_t)((uint8_t *) mrd_out + mrd_size) >
525 	     (uintptr_t)((uint8_t *) out + out_obj->desc_size))) {
526 		ERROR("%s: Invalid mrd structure.\n", __func__);
527 		return false;
528 	}
529 
530 	/* Copy the mrd descriptors directly. */
531 	memcpy(mrd_out, mrd_in, mrd_size);
532 
533 	return true;
534 }
535 
536 /**
537  * spmc_shm_convert_mtd_to_v1_0 - Converts a given v1.1 memory object to
538  *                                v1.0 memory object.
539  * @out_obj:    The shared memory object to populate the v1.0 descriptor.
540  * @orig:       The shared memory object containing the v1.1 descriptor.
541  *
542  * Return: true if the conversion is successful else false.
543  */
544 static bool
545 spmc_shm_convert_mtd_to_v1_0(struct spmc_shmem_obj *out_obj,
546 			     struct spmc_shmem_obj *orig)
547 {
548 	struct ffa_mtd *mtd_orig = &orig->desc;
549 	struct ffa_mtd_v1_0 *out = (struct ffa_mtd_v1_0 *) &out_obj->desc;
550 	struct ffa_emad_v1_0 *emad_in;
551 	struct ffa_emad_v1_0 *emad_array_in;
552 	struct ffa_emad_v1_0 *emad_array_out;
553 	struct ffa_comp_mrd *mrd_in;
554 	struct ffa_comp_mrd *mrd_out;
555 
556 	size_t mrd_in_offset;
557 	size_t mrd_out_offset;
558 	size_t emad_out_array_size;
559 	size_t mrd_size = 0;
560 	size_t orig_desc_size = orig->desc_size;
561 
562 	/* Populate the v1.0 descriptor format from the v1.1 struct. */
563 	out->sender_id = mtd_orig->sender_id;
564 	out->memory_region_attributes = mtd_orig->memory_region_attributes;
565 	out->flags = mtd_orig->flags;
566 	out->handle = mtd_orig->handle;
567 	out->tag = mtd_orig->tag;
568 	out->emad_count = mtd_orig->emad_count;
569 
570 	/* Determine the location of the emad array in both descriptors. */
571 	emad_array_in = (struct ffa_emad_v1_0 *)
572 			((uint8_t *) mtd_orig + mtd_orig->emad_offset);
573 	emad_array_out = out->emad;
574 
575 	/* Copy across the emad structs. */
576 	emad_in = emad_array_in;
577 	for (unsigned int i = 0U; i < out->emad_count; i++) {
578 		/* Bound check for emad array. */
579 		if (((uint8_t *)emad_in + sizeof(struct ffa_emad_v1_0)) >
580 				((uint8_t *) mtd_orig + orig_desc_size)) {
581 			VERBOSE("%s: Invalid mtd structure.\n", __func__);
582 			return false;
583 		}
584 		memcpy(&emad_array_out[i], emad_in,
585 		       sizeof(struct ffa_emad_v1_0));
586 
587 		emad_in +=  mtd_orig->emad_size;
588 	}
589 
590 	/* Place the mrd descriptors after the end of the emad descriptors. */
591 	emad_out_array_size = sizeof(struct ffa_emad_v1_0) * out->emad_count;
592 
593 	mrd_out_offset =  (uint8_t *) out->emad - (uint8_t *) out +
594 			  emad_out_array_size;
595 
596 	mrd_out = (struct ffa_comp_mrd *) ((uint8_t *) out + mrd_out_offset);
597 
598 	mrd_in_offset = mtd_orig->emad_offset +
599 			(mtd_orig->emad_size * mtd_orig->emad_count);
600 
601 	/* Add the size of the composite memory region descriptor. */
602 	mrd_size += sizeof(struct ffa_comp_mrd);
603 
604 	/* Find the mrd descriptor. */
605 	mrd_in = (struct ffa_comp_mrd *) ((uint8_t *) mtd_orig + mrd_in_offset);
606 
607 	/* Add the size of the constituent memory region descriptors. */
608 	mrd_size += mrd_in->address_range_count * sizeof(struct ffa_cons_mrd);
609 
610 	/*
611 	 * Update the offset in the emads by the delta between the input and
612 	 * output addresses.
613 	 */
614 	emad_in = emad_array_in;
615 
616 	for (unsigned int i = 0U; i < out->emad_count; i++) {
617 		emad_array_out[i].comp_mrd_offset = emad_in->comp_mrd_offset +
618 						    (mrd_out_offset -
619 						     mrd_in_offset);
620 		emad_in +=  mtd_orig->emad_size;
621 	}
622 
623 	/* Verify that we stay within bound of the memory descriptors. */
624 	if ((uintptr_t)((uint8_t *) mrd_in + mrd_size) >
625 	     (uintptr_t)((uint8_t *) mtd_orig + orig->desc_size) ||
626 	    ((uintptr_t)((uint8_t *) mrd_out + mrd_size) >
627 	     (uintptr_t)((uint8_t *) out + out_obj->desc_size))) {
628 		ERROR("%s: Invalid mrd structure.\n", __func__);
629 		return false;
630 	}
631 
632 	/* Copy the mrd descriptors directly. */
633 	memcpy(mrd_out, mrd_in, mrd_size);
634 
635 	return true;
636 }
637 
638 /**
639  * spmc_populate_ffa_v1_0_descriptor - Converts a given v1.1 memory object to
640  *                                     the v1.0 format and populates the
641  *                                     provided buffer.
642  * @dst:	    Buffer to populate v1.0 ffa_memory_region_descriptor.
643  * @orig_obj:	    Object containing v1.1 ffa_memory_region_descriptor.
644  * @buf_size:	    Size of the buffer to populate.
645  * @offset:	    The offset of the converted descriptor to copy.
646  * @copy_size:	    Will be populated with the number of bytes copied.
647  * @out_desc_size:  Will be populated with the total size of the v1.0
648  *                  descriptor.
649  *
650  * Return: 0 if conversion and population succeeded.
651  * Note: This function invalidates the reference to @orig therefore
652  * `spmc_shmem_obj_lookup` must be called if further usage is required.
653  */
654 static uint32_t
655 spmc_populate_ffa_v1_0_descriptor(void *dst, struct spmc_shmem_obj *orig_obj,
656 				 size_t buf_size, size_t offset,
657 				 size_t *copy_size, size_t *v1_0_desc_size)
658 {
659 		struct spmc_shmem_obj *v1_0_obj;
660 
661 		/* Calculate the size that the v1.0 descriptor will require. */
662 		*v1_0_desc_size = spmc_shm_get_v1_0_descriptor_size(
663 					&orig_obj->desc, orig_obj->desc_size);
664 
665 		if (*v1_0_desc_size == 0) {
666 			ERROR("%s: cannot determine size of descriptor.\n",
667 			      __func__);
668 			return FFA_ERROR_INVALID_PARAMETER;
669 		}
670 
671 		/* Get a new obj to store the v1.0 descriptor. */
672 		v1_0_obj = spmc_shmem_obj_alloc(&spmc_shmem_obj_state,
673 						*v1_0_desc_size);
674 
675 		if (!v1_0_obj) {
676 			return FFA_ERROR_NO_MEMORY;
677 		}
678 
679 		/* Perform the conversion from v1.1 to v1.0. */
680 		if (!spmc_shm_convert_mtd_to_v1_0(v1_0_obj, orig_obj)) {
681 			spmc_shmem_obj_free(&spmc_shmem_obj_state, v1_0_obj);
682 			return FFA_ERROR_INVALID_PARAMETER;
683 		}
684 
685 		*copy_size = MIN(v1_0_obj->desc_size - offset, buf_size);
686 		memcpy(dst, (uint8_t *) &v1_0_obj->desc + offset, *copy_size);
687 
688 		/*
689 		 * We're finished with the v1.0 descriptor for now so free it.
690 		 * Note that this will invalidate any references to the v1.1
691 		 * descriptor.
692 		 */
693 		spmc_shmem_obj_free(&spmc_shmem_obj_state, v1_0_obj);
694 
695 		return 0;
696 }
697 
698 static int
699 spmc_validate_mtd_start(struct ffa_mtd *desc, uint32_t ffa_version,
700 			size_t fragment_length, size_t total_length)
701 {
702 	unsigned long long emad_end;
703 	unsigned long long emad_size;
704 	unsigned long long emad_offset;
705 	unsigned int min_desc_size;
706 
707 	/* Determine the appropriate minimum descriptor size. */
708 	if (ffa_version == MAKE_FFA_VERSION(1, 0)) {
709 		min_desc_size = sizeof(struct ffa_mtd_v1_0);
710 	} else if (ffa_version == MAKE_FFA_VERSION(1, 1)) {
711 		min_desc_size = sizeof(struct ffa_mtd);
712 	} else {
713 		return FFA_ERROR_INVALID_PARAMETER;
714 	}
715 	if (fragment_length < min_desc_size) {
716 		WARN("%s: invalid length %zu < %u\n", __func__, fragment_length,
717 		     min_desc_size);
718 		return FFA_ERROR_INVALID_PARAMETER;
719 	}
720 
721 	if (desc->emad_count == 0U) {
722 		WARN("%s: unsupported attribute desc count %u.\n",
723 		     __func__, desc->emad_count);
724 		return FFA_ERROR_INVALID_PARAMETER;
725 	}
726 
727 	/*
728 	 * If the caller is using FF-A v1.0 interpret the descriptor as a v1.0
729 	 * format, otherwise assume it is a v1.1 format.
730 	 */
731 	if (ffa_version == MAKE_FFA_VERSION(1, 0)) {
732 		emad_offset = emad_size = sizeof(struct ffa_emad_v1_0);
733 	} else {
734 		if (!is_aligned(desc->emad_offset, 16)) {
735 			WARN("%s: Emad offset %" PRIx32 " is not 16-byte aligned.\n",
736 			     __func__, desc->emad_offset);
737 			return FFA_ERROR_INVALID_PARAMETER;
738 		}
739 		if (desc->emad_offset < sizeof(struct ffa_mtd)) {
740 			WARN("%s: Emad offset too small: 0x%" PRIx32 " < 0x%zx.\n",
741 			     __func__, desc->emad_offset,
742 			     sizeof(struct ffa_mtd));
743 			return FFA_ERROR_INVALID_PARAMETER;
744 		}
745 		emad_offset = desc->emad_offset;
746 		if (desc->emad_size < sizeof(struct ffa_emad_v1_0)) {
747 			WARN("%s: Bad emad size (%" PRIu32 " < %zu).\n", __func__,
748 			     desc->emad_size, sizeof(struct ffa_emad_v1_0));
749 			return FFA_ERROR_INVALID_PARAMETER;
750 		}
751 		if (!is_aligned(desc->emad_size, 16)) {
752 			WARN("%s: Emad size 0x%" PRIx32 " is not 16-byte aligned.\n",
753 			     __func__, desc->emad_size);
754 			return FFA_ERROR_INVALID_PARAMETER;
755 		}
756 		emad_size = desc->emad_size;
757 	}
758 
759 	/*
760 	 * Overflow is impossible: the arithmetic happens in at least 64-bit
761 	 * precision, but all of the operands are bounded by UINT32_MAX, and
762 	 * ((2^32 - 1)^2 + (2^32 - 1) + (2^32 - 1)) = ((2^32 - 1) * (2^32 + 1))
763 	 * = (2^64 - 1).
764 	 */
765 	CASSERT(sizeof(desc->emad_count == 4), assert_emad_count_max_too_large);
766 	emad_end = (desc->emad_count * (unsigned long long)emad_size) +
767 		   (unsigned long long)sizeof(struct ffa_comp_mrd) +
768 		   (unsigned long long)emad_offset;
769 
770 	if (emad_end > total_length) {
771 		WARN("%s: Composite memory region extends beyond descriptor: 0x%llx > 0x%zx\n",
772 		     __func__, emad_end, total_length);
773 		return FFA_ERROR_INVALID_PARAMETER;
774 	}
775 
776 	return 0;
777 }
778 
779 /**
780  * spmc_shmem_check_obj - Check that counts in descriptor match overall size.
781  * @obj:	  Object containing ffa_memory_region_descriptor.
782  * @ffa_version:  FF-A version of the provided descriptor.
783  *
784  * Return: 0 if object is valid, -EINVAL if constituent_memory_region_descriptor
785  * offset or count is invalid.
786  */
787 static int spmc_shmem_check_obj(struct spmc_shmem_obj *obj,
788 				uint32_t ffa_version)
789 {
790 	uint32_t comp_mrd_offset = 0;
791 
792 	if (obj->desc.emad_count == 0U) {
793 		WARN("%s: unsupported attribute desc count %u.\n",
794 		     __func__, obj->desc.emad_count);
795 		return -EINVAL;
796 	}
797 
798 	for (size_t emad_num = 0; emad_num < obj->desc.emad_count; emad_num++) {
799 		size_t size;
800 		size_t count;
801 		size_t expected_size;
802 		size_t total_page_count;
803 		size_t emad_size;
804 		size_t header_emad_size;
805 		uint32_t offset;
806 		struct ffa_comp_mrd *comp;
807 		struct ffa_emad_v1_0 *emad;
808 
809 		emad = spmc_shmem_obj_get_emad(&obj->desc, emad_num,
810 					       ffa_version, &emad_size);
811 
812 		/*
813 		 * Validate the calculated emad address resides within the
814 		 * descriptor.
815 		 */
816 		if ((uintptr_t) emad >=
817 		    (uintptr_t)((uint8_t *) &obj->desc + obj->desc_size)) {
818 			WARN("Invalid emad access.\n");
819 			return -EINVAL;
820 		}
821 
822 		offset = emad->comp_mrd_offset;
823 
824 		/*
825 		 * The offset provided to the composite memory region descriptor
826 		 * should be consistent across endpoint descriptors. Store the
827 		 * first entry and compare against subsequent entries.
828 		 */
829 		if (comp_mrd_offset == 0) {
830 			comp_mrd_offset = offset;
831 		} else {
832 			if (comp_mrd_offset != offset) {
833 				ERROR("%s: mismatching offsets provided, %u != %u\n",
834 				       __func__, offset, comp_mrd_offset);
835 				return -EINVAL;
836 			}
837 			continue; /* Remainder only executed on first iteration. */
838 		}
839 
840 		header_emad_size = (size_t)((uint8_t *)emad - (uint8_t *)&obj->desc) +
841 			(obj->desc.emad_count * emad_size);
842 
843 		if (offset < header_emad_size) {
844 			WARN("%s: invalid object, offset %u < header + emad %zu\n",
845 			     __func__, offset, header_emad_size);
846 			return -EINVAL;
847 		}
848 
849 		size = obj->desc_size;
850 
851 		if (offset > size) {
852 			WARN("%s: invalid object, offset %u > total size %zu\n",
853 			     __func__, offset, obj->desc_size);
854 			return -EINVAL;
855 		}
856 		size -= offset;
857 
858 		if (size < sizeof(struct ffa_comp_mrd)) {
859 			WARN("%s: invalid object, offset %u, total size %zu, no header space.\n",
860 			     __func__, offset, obj->desc_size);
861 			return -EINVAL;
862 		}
863 		size -= sizeof(struct ffa_comp_mrd);
864 
865 		count = size / sizeof(struct ffa_cons_mrd);
866 
867 		comp = spmc_shmem_obj_get_comp_mrd(obj, ffa_version);
868 
869 		if (comp == NULL) {
870 			WARN("%s: invalid comp_mrd offset\n", __func__);
871 			return -EINVAL;
872 		}
873 
874 		if (comp->address_range_count != count) {
875 			WARN("%s: invalid object, desc count %u != %zu\n",
876 			     __func__, comp->address_range_count, count);
877 			return -EINVAL;
878 		}
879 
880 		expected_size = offset + sizeof(*comp) +
881 				spmc_shmem_obj_ffa_constituent_size(obj,
882 								    ffa_version);
883 
884 		if (expected_size != obj->desc_size) {
885 			WARN("%s: invalid object, computed size %zu != size %zu\n",
886 			       __func__, expected_size, obj->desc_size);
887 			return -EINVAL;
888 		}
889 
890 		total_page_count = 0;
891 
892 		for (size_t i = 0; i < count; i++) {
893 			total_page_count +=
894 				comp->address_range_array[i].page_count;
895 		}
896 		if (comp->total_page_count != total_page_count) {
897 			WARN("%s: invalid object, desc total_page_count %u != %zu\n",
898 			     __func__, comp->total_page_count,
899 			total_page_count);
900 			return -EINVAL;
901 		}
902 	}
903 	return 0;
904 }
905 
906 /**
907  * spmc_shmem_check_state_obj - Check if the descriptor describes memory
908  *				regions that are currently involved with an
909  *				existing memory transactions. This implies that
910  *				the memory is not in a valid state for lending.
911  * @obj:    Object containing ffa_memory_region_descriptor.
912  *
913  * Return: 0 if object is valid, -EINVAL if invalid memory state.
914  */
915 static int spmc_shmem_check_state_obj(struct spmc_shmem_obj *obj,
916 				      uint32_t ffa_version)
917 {
918 	size_t obj_offset = 0;
919 	struct spmc_shmem_obj *inflight_obj;
920 
921 	struct ffa_comp_mrd *other_mrd;
922 	struct ffa_comp_mrd *requested_mrd = spmc_shmem_obj_get_comp_mrd(obj,
923 								  ffa_version);
924 
925 	if (requested_mrd == NULL) {
926 		return -EINVAL;
927 	}
928 
929 	inflight_obj = spmc_shmem_obj_get_next(&spmc_shmem_obj_state,
930 					       &obj_offset);
931 
932 	while (inflight_obj != NULL) {
933 		/*
934 		 * Don't compare the transaction to itself or to partially
935 		 * transmitted descriptors.
936 		 */
937 		if ((obj->desc.handle != inflight_obj->desc.handle) &&
938 		    (obj->desc_size == obj->desc_filled)) {
939 			other_mrd = spmc_shmem_obj_get_comp_mrd(inflight_obj,
940 							  FFA_VERSION_COMPILED);
941 			if (other_mrd == NULL) {
942 				return -EINVAL;
943 			}
944 			if (overlapping_memory_regions(requested_mrd,
945 						       other_mrd)) {
946 				return -EINVAL;
947 			}
948 		}
949 
950 		inflight_obj = spmc_shmem_obj_get_next(&spmc_shmem_obj_state,
951 						       &obj_offset);
952 	}
953 	return 0;
954 }
955 
956 static long spmc_ffa_fill_desc(struct mailbox *mbox,
957 			       struct spmc_shmem_obj *obj,
958 			       uint32_t fragment_length,
959 			       ffa_mtd_flag32_t mtd_flag,
960 			       uint32_t ffa_version,
961 			       void *smc_handle)
962 {
963 	int ret;
964 	size_t emad_size;
965 	uint32_t handle_low;
966 	uint32_t handle_high;
967 	struct ffa_emad_v1_0 *emad;
968 	struct ffa_emad_v1_0 *other_emad;
969 
970 	if (mbox->rxtx_page_count == 0U) {
971 		WARN("%s: buffer pair not registered.\n", __func__);
972 		ret = FFA_ERROR_INVALID_PARAMETER;
973 		goto err_arg;
974 	}
975 
976 	if (fragment_length > mbox->rxtx_page_count * PAGE_SIZE_4KB) {
977 		WARN("%s: bad fragment size %u > %u buffer size\n", __func__,
978 		     fragment_length, mbox->rxtx_page_count * PAGE_SIZE_4KB);
979 		ret = FFA_ERROR_INVALID_PARAMETER;
980 		goto err_arg;
981 	}
982 
983 	if (fragment_length > obj->desc_size - obj->desc_filled) {
984 		WARN("%s: bad fragment size %u > %zu remaining\n", __func__,
985 		     fragment_length, obj->desc_size - obj->desc_filled);
986 		ret = FFA_ERROR_INVALID_PARAMETER;
987 		goto err_arg;
988 	}
989 
990 	memcpy((uint8_t *)&obj->desc + obj->desc_filled,
991 	       (uint8_t *) mbox->tx_buffer, fragment_length);
992 
993 	/* Ensure that the sender ID resides in the normal world. */
994 	if (ffa_is_secure_world_id(obj->desc.sender_id)) {
995 		WARN("%s: Invalid sender ID 0x%x.\n",
996 		     __func__, obj->desc.sender_id);
997 		ret = FFA_ERROR_DENIED;
998 		goto err_arg;
999 	}
1000 
1001 	/* Ensure the NS bit is set to 0. */
1002 	if ((obj->desc.memory_region_attributes & FFA_MEM_ATTR_NS_BIT) != 0U) {
1003 		WARN("%s: NS mem attributes flags MBZ.\n", __func__);
1004 		ret = FFA_ERROR_INVALID_PARAMETER;
1005 		goto err_arg;
1006 	}
1007 
1008 	/*
1009 	 * We don't currently support any optional flags so ensure none are
1010 	 * requested.
1011 	 */
1012 	if (obj->desc.flags != 0U && mtd_flag != 0U &&
1013 	    (obj->desc.flags != mtd_flag)) {
1014 		WARN("%s: invalid memory transaction flags %u != %u\n",
1015 		     __func__, obj->desc.flags, mtd_flag);
1016 		ret = FFA_ERROR_INVALID_PARAMETER;
1017 		goto err_arg;
1018 	}
1019 
1020 	if (obj->desc_filled == 0U) {
1021 		/* First fragment, descriptor header has been copied */
1022 		ret = spmc_validate_mtd_start(&obj->desc, ffa_version,
1023 					      fragment_length, obj->desc_size);
1024 		if (ret != 0) {
1025 			goto err_bad_desc;
1026 		}
1027 
1028 		obj->desc.handle = spmc_shmem_obj_state.next_handle++;
1029 		obj->desc.flags |= mtd_flag;
1030 	}
1031 
1032 	obj->desc_filled += fragment_length;
1033 
1034 	handle_low = (uint32_t)obj->desc.handle;
1035 	handle_high = obj->desc.handle >> 32;
1036 
1037 	if (obj->desc_filled != obj->desc_size) {
1038 		SMC_RET8(smc_handle, FFA_MEM_FRAG_RX, handle_low,
1039 			 handle_high, obj->desc_filled,
1040 			 (uint32_t)obj->desc.sender_id << 16, 0, 0, 0);
1041 	}
1042 
1043 	/* The full descriptor has been received, perform any final checks. */
1044 
1045 	ret = spmc_shmem_check_obj(obj, ffa_version);
1046 	if (ret != 0) {
1047 		ret = FFA_ERROR_INVALID_PARAMETER;
1048 		goto err_bad_desc;
1049 	}
1050 
1051 	/*
1052 	 * If a partition ID resides in the secure world validate that the
1053 	 * partition ID is for a known partition. Ignore any partition ID
1054 	 * belonging to the normal world as it is assumed the Hypervisor will
1055 	 * have validated these.
1056 	 */
1057 	for (size_t i = 0; i < obj->desc.emad_count; i++) {
1058 		emad = spmc_shmem_obj_get_emad(&obj->desc, i, ffa_version,
1059 					       &emad_size);
1060 
1061 		ffa_endpoint_id16_t ep_id = emad->mapd.endpoint_id;
1062 
1063 		if (ffa_is_secure_world_id(ep_id)) {
1064 			if (spmc_get_sp_ctx(ep_id) == NULL) {
1065 				WARN("%s: Invalid receiver id 0x%x\n",
1066 				     __func__, ep_id);
1067 				ret = FFA_ERROR_INVALID_PARAMETER;
1068 				goto err_bad_desc;
1069 			}
1070 		}
1071 	}
1072 
1073 	/* Ensure partition IDs are not duplicated. */
1074 	for (size_t i = 0; i < obj->desc.emad_count; i++) {
1075 		emad = spmc_shmem_obj_get_emad(&obj->desc, i, ffa_version,
1076 					       &emad_size);
1077 
1078 		for (size_t j = i + 1; j < obj->desc.emad_count; j++) {
1079 			other_emad = spmc_shmem_obj_get_emad(&obj->desc, j,
1080 							     ffa_version,
1081 							     &emad_size);
1082 
1083 			if (emad->mapd.endpoint_id ==
1084 				other_emad->mapd.endpoint_id) {
1085 				WARN("%s: Duplicated endpoint id 0x%x\n",
1086 				     __func__, emad->mapd.endpoint_id);
1087 				ret = FFA_ERROR_INVALID_PARAMETER;
1088 				goto err_bad_desc;
1089 			}
1090 		}
1091 	}
1092 
1093 	ret = spmc_shmem_check_state_obj(obj, ffa_version);
1094 	if (ret) {
1095 		ERROR("%s: invalid memory region descriptor.\n", __func__);
1096 		ret = FFA_ERROR_INVALID_PARAMETER;
1097 		goto err_bad_desc;
1098 	}
1099 
1100 	/*
1101 	 * Everything checks out, if the sender was using FF-A v1.0, convert
1102 	 * the descriptor format to use the v1.1 structures.
1103 	 */
1104 	if (ffa_version == MAKE_FFA_VERSION(1, 0)) {
1105 		struct spmc_shmem_obj *v1_1_obj;
1106 		uint64_t mem_handle;
1107 
1108 		/* Calculate the size that the v1.1 descriptor will required. */
1109 		size_t v1_1_desc_size =
1110 		    spmc_shm_get_v1_1_descriptor_size((void *) &obj->desc,
1111 						      obj->desc_size);
1112 
1113 		if (v1_1_desc_size == 0U) {
1114 			ERROR("%s: cannot determine size of descriptor.\n",
1115 			      __func__);
1116 			goto err_arg;
1117 		}
1118 
1119 		/* Get a new obj to store the v1.1 descriptor. */
1120 		v1_1_obj =
1121 		    spmc_shmem_obj_alloc(&spmc_shmem_obj_state, v1_1_desc_size);
1122 
1123 		if (!v1_1_obj) {
1124 			ret = FFA_ERROR_NO_MEMORY;
1125 			goto err_arg;
1126 		}
1127 
1128 		/* Perform the conversion from v1.0 to v1.1. */
1129 		v1_1_obj->desc_size = v1_1_desc_size;
1130 		v1_1_obj->desc_filled = v1_1_desc_size;
1131 		if (!spmc_shm_convert_shmem_obj_from_v1_0(v1_1_obj, obj)) {
1132 			ERROR("%s: Could not convert mtd!\n", __func__);
1133 			spmc_shmem_obj_free(&spmc_shmem_obj_state, v1_1_obj);
1134 			goto err_arg;
1135 		}
1136 
1137 		/*
1138 		 * We're finished with the v1.0 descriptor so free it
1139 		 * and continue our checks with the new v1.1 descriptor.
1140 		 */
1141 		mem_handle = obj->desc.handle;
1142 		spmc_shmem_obj_free(&spmc_shmem_obj_state, obj);
1143 		obj = spmc_shmem_obj_lookup(&spmc_shmem_obj_state, mem_handle);
1144 		if (obj == NULL) {
1145 			ERROR("%s: Failed to find converted descriptor.\n",
1146 			     __func__);
1147 			ret = FFA_ERROR_INVALID_PARAMETER;
1148 			return spmc_ffa_error_return(smc_handle, ret);
1149 		}
1150 	}
1151 
1152 	/* Allow for platform specific operations to be performed. */
1153 	ret = plat_spmc_shmem_begin(&obj->desc);
1154 	if (ret != 0) {
1155 		goto err_arg;
1156 	}
1157 
1158 	SMC_RET8(smc_handle, FFA_SUCCESS_SMC32, 0, handle_low, handle_high, 0,
1159 		 0, 0, 0);
1160 
1161 err_bad_desc:
1162 err_arg:
1163 	spmc_shmem_obj_free(&spmc_shmem_obj_state, obj);
1164 	return spmc_ffa_error_return(smc_handle, ret);
1165 }
1166 
1167 /**
1168  * spmc_ffa_mem_send - FFA_MEM_SHARE/LEND implementation.
1169  * @client:             Client state.
1170  * @total_length:       Total length of shared memory descriptor.
1171  * @fragment_length:    Length of fragment of shared memory descriptor passed in
1172  *                      this call.
1173  * @address:            Not supported, must be 0.
1174  * @page_count:         Not supported, must be 0.
1175  * @smc_handle:         Handle passed to smc call. Used to return
1176  *                      FFA_MEM_FRAG_RX or SMC_FC_FFA_SUCCESS.
1177  *
1178  * Implements a subset of the FF-A FFA_MEM_SHARE and FFA_MEM_LEND calls needed
1179  * to share or lend memory from non-secure os to secure os (with no stream
1180  * endpoints).
1181  *
1182  * Return: 0 on success, error code on failure.
1183  */
1184 long spmc_ffa_mem_send(uint32_t smc_fid,
1185 			bool secure_origin,
1186 			uint64_t total_length,
1187 			uint32_t fragment_length,
1188 			uint64_t address,
1189 			uint32_t page_count,
1190 			void *cookie,
1191 			void *handle,
1192 			uint64_t flags)
1193 
1194 {
1195 	long ret;
1196 	struct spmc_shmem_obj *obj;
1197 	struct mailbox *mbox = spmc_get_mbox_desc(secure_origin);
1198 	ffa_mtd_flag32_t mtd_flag;
1199 	uint32_t ffa_version = get_partition_ffa_version(secure_origin);
1200 	size_t min_desc_size;
1201 
1202 	if (address != 0U || page_count != 0U) {
1203 		WARN("%s: custom memory region for message not supported.\n",
1204 		     __func__);
1205 		return spmc_ffa_error_return(handle,
1206 					     FFA_ERROR_INVALID_PARAMETER);
1207 	}
1208 
1209 	if (secure_origin) {
1210 		WARN("%s: unsupported share direction.\n", __func__);
1211 		return spmc_ffa_error_return(handle,
1212 					     FFA_ERROR_INVALID_PARAMETER);
1213 	}
1214 
1215 	if (ffa_version == MAKE_FFA_VERSION(1, 0)) {
1216 		min_desc_size = sizeof(struct ffa_mtd_v1_0);
1217 	} else if (ffa_version == MAKE_FFA_VERSION(1, 1)) {
1218 		min_desc_size = sizeof(struct ffa_mtd);
1219 	} else {
1220 		WARN("%s: bad FF-A version.\n", __func__);
1221 		return spmc_ffa_error_return(handle,
1222 					     FFA_ERROR_INVALID_PARAMETER);
1223 	}
1224 
1225 	/* Check if the descriptor is too small for the FF-A version. */
1226 	if (fragment_length < min_desc_size) {
1227 		WARN("%s: bad first fragment size %u < %zu\n",
1228 		     __func__, fragment_length, sizeof(struct ffa_mtd_v1_0));
1229 		return spmc_ffa_error_return(handle,
1230 					     FFA_ERROR_INVALID_PARAMETER);
1231 	}
1232 
1233 	if ((smc_fid & FUNCID_NUM_MASK) == FFA_FNUM_MEM_SHARE) {
1234 		mtd_flag = FFA_MTD_FLAG_TYPE_SHARE_MEMORY;
1235 	} else if ((smc_fid & FUNCID_NUM_MASK) == FFA_FNUM_MEM_LEND) {
1236 		mtd_flag = FFA_MTD_FLAG_TYPE_LEND_MEMORY;
1237 	} else {
1238 		WARN("%s: invalid memory management operation.\n", __func__);
1239 		return spmc_ffa_error_return(handle,
1240 					     FFA_ERROR_INVALID_PARAMETER);
1241 	}
1242 
1243 	spin_lock(&spmc_shmem_obj_state.lock);
1244 	obj = spmc_shmem_obj_alloc(&spmc_shmem_obj_state, total_length);
1245 	if (obj == NULL) {
1246 		ret = FFA_ERROR_NO_MEMORY;
1247 		goto err_unlock;
1248 	}
1249 
1250 	spin_lock(&mbox->lock);
1251 	ret = spmc_ffa_fill_desc(mbox, obj, fragment_length, mtd_flag,
1252 				 ffa_version, handle);
1253 	spin_unlock(&mbox->lock);
1254 
1255 	spin_unlock(&spmc_shmem_obj_state.lock);
1256 	return ret;
1257 
1258 err_unlock:
1259 	spin_unlock(&spmc_shmem_obj_state.lock);
1260 	return spmc_ffa_error_return(handle, ret);
1261 }
1262 
1263 /**
1264  * spmc_ffa_mem_frag_tx - FFA_MEM_FRAG_TX implementation.
1265  * @client:             Client state.
1266  * @handle_low:         Handle_low value returned from FFA_MEM_FRAG_RX.
1267  * @handle_high:        Handle_high value returned from FFA_MEM_FRAG_RX.
1268  * @fragment_length:    Length of fragments transmitted.
1269  * @sender_id:          Vmid of sender in bits [31:16]
1270  * @smc_handle:         Handle passed to smc call. Used to return
1271  *                      FFA_MEM_FRAG_RX or SMC_FC_FFA_SUCCESS.
1272  *
1273  * Return: @smc_handle on success, error code on failure.
1274  */
1275 long spmc_ffa_mem_frag_tx(uint32_t smc_fid,
1276 			  bool secure_origin,
1277 			  uint64_t handle_low,
1278 			  uint64_t handle_high,
1279 			  uint32_t fragment_length,
1280 			  uint32_t sender_id,
1281 			  void *cookie,
1282 			  void *handle,
1283 			  uint64_t flags)
1284 {
1285 	long ret;
1286 	uint32_t desc_sender_id;
1287 	uint32_t ffa_version = get_partition_ffa_version(secure_origin);
1288 	struct mailbox *mbox = spmc_get_mbox_desc(secure_origin);
1289 
1290 	struct spmc_shmem_obj *obj;
1291 	uint64_t mem_handle = handle_low | (((uint64_t)handle_high) << 32);
1292 
1293 	spin_lock(&spmc_shmem_obj_state.lock);
1294 
1295 	obj = spmc_shmem_obj_lookup(&spmc_shmem_obj_state, mem_handle);
1296 	if (obj == NULL) {
1297 		WARN("%s: invalid handle, 0x%lx, not a valid handle.\n",
1298 		     __func__, mem_handle);
1299 		ret = FFA_ERROR_INVALID_PARAMETER;
1300 		goto err_unlock;
1301 	}
1302 
1303 	desc_sender_id = (uint32_t)obj->desc.sender_id << 16;
1304 	if (sender_id != desc_sender_id) {
1305 		WARN("%s: invalid sender_id 0x%x != 0x%x\n", __func__,
1306 		     sender_id, desc_sender_id);
1307 		ret = FFA_ERROR_INVALID_PARAMETER;
1308 		goto err_unlock;
1309 	}
1310 
1311 	if (obj->desc_filled == obj->desc_size) {
1312 		WARN("%s: object desc already filled, %zu\n", __func__,
1313 		     obj->desc_filled);
1314 		ret = FFA_ERROR_INVALID_PARAMETER;
1315 		goto err_unlock;
1316 	}
1317 
1318 	spin_lock(&mbox->lock);
1319 	ret = spmc_ffa_fill_desc(mbox, obj, fragment_length, 0, ffa_version,
1320 				 handle);
1321 	spin_unlock(&mbox->lock);
1322 
1323 	spin_unlock(&spmc_shmem_obj_state.lock);
1324 	return ret;
1325 
1326 err_unlock:
1327 	spin_unlock(&spmc_shmem_obj_state.lock);
1328 	return spmc_ffa_error_return(handle, ret);
1329 }
1330 
1331 /**
1332  * spmc_ffa_mem_retrieve_set_ns_bit - Set the NS bit in the response descriptor
1333  *				      if the caller implements a version greater
1334  *				      than FF-A 1.0 or if they have requested
1335  *				      the functionality.
1336  *				      TODO: We are assuming that the caller is
1337  *				      an SP. To support retrieval from the
1338  *				      normal world this function will need to be
1339  *				      expanded accordingly.
1340  * @resp:       Descriptor populated in callers RX buffer.
1341  * @sp_ctx:     Context of the calling SP.
1342  */
1343 void spmc_ffa_mem_retrieve_set_ns_bit(struct ffa_mtd *resp,
1344 			 struct secure_partition_desc *sp_ctx)
1345 {
1346 	if (sp_ctx->ffa_version > MAKE_FFA_VERSION(1, 0) ||
1347 	    sp_ctx->ns_bit_requested) {
1348 		/*
1349 		 * Currently memory senders must reside in the normal
1350 		 * world, and we do not have the functionlaity to change
1351 		 * the state of memory dynamically. Therefore we can always set
1352 		 * the NS bit to 1.
1353 		 */
1354 		resp->memory_region_attributes |= FFA_MEM_ATTR_NS_BIT;
1355 	}
1356 }
1357 
1358 /**
1359  * spmc_ffa_mem_retrieve_req - FFA_MEM_RETRIEVE_REQ implementation.
1360  * @smc_fid:            FID of SMC
1361  * @total_length:       Total length of retrieve request descriptor if this is
1362  *                      the first call. Otherwise (unsupported) must be 0.
1363  * @fragment_length:    Length of fragment of retrieve request descriptor passed
1364  *                      in this call. Only @fragment_length == @length is
1365  *                      supported by this implementation.
1366  * @address:            Not supported, must be 0.
1367  * @page_count:         Not supported, must be 0.
1368  * @smc_handle:         Handle passed to smc call. Used to return
1369  *                      FFA_MEM_RETRIEVE_RESP.
1370  *
1371  * Implements a subset of the FF-A FFA_MEM_RETRIEVE_REQ call.
1372  * Used by secure os to retrieve memory already shared by non-secure os.
1373  * If the data does not fit in a single FFA_MEM_RETRIEVE_RESP message,
1374  * the client must call FFA_MEM_FRAG_RX until the full response has been
1375  * received.
1376  *
1377  * Return: @handle on success, error code on failure.
1378  */
1379 long
1380 spmc_ffa_mem_retrieve_req(uint32_t smc_fid,
1381 			  bool secure_origin,
1382 			  uint32_t total_length,
1383 			  uint32_t fragment_length,
1384 			  uint64_t address,
1385 			  uint32_t page_count,
1386 			  void *cookie,
1387 			  void *handle,
1388 			  uint64_t flags)
1389 {
1390 	int ret;
1391 	size_t buf_size;
1392 	size_t copy_size = 0;
1393 	size_t min_desc_size;
1394 	size_t out_desc_size = 0;
1395 
1396 	/*
1397 	 * Currently we are only accessing fields that are the same in both the
1398 	 * v1.0 and v1.1 mtd struct therefore we can use a v1.1 struct directly
1399 	 * here. We only need validate against the appropriate struct size.
1400 	 */
1401 	struct ffa_mtd *resp;
1402 	const struct ffa_mtd *req;
1403 	struct spmc_shmem_obj *obj = NULL;
1404 	struct mailbox *mbox = spmc_get_mbox_desc(secure_origin);
1405 	uint32_t ffa_version = get_partition_ffa_version(secure_origin);
1406 	struct secure_partition_desc *sp_ctx = spmc_get_current_sp_ctx();
1407 
1408 	if (!secure_origin) {
1409 		WARN("%s: unsupported retrieve req direction.\n", __func__);
1410 		return spmc_ffa_error_return(handle,
1411 					     FFA_ERROR_INVALID_PARAMETER);
1412 	}
1413 
1414 	if (address != 0U || page_count != 0U) {
1415 		WARN("%s: custom memory region not supported.\n", __func__);
1416 		return spmc_ffa_error_return(handle,
1417 					     FFA_ERROR_INVALID_PARAMETER);
1418 	}
1419 
1420 	spin_lock(&mbox->lock);
1421 
1422 	req = mbox->tx_buffer;
1423 	resp = mbox->rx_buffer;
1424 	buf_size = mbox->rxtx_page_count * FFA_PAGE_SIZE;
1425 
1426 	if (mbox->rxtx_page_count == 0U) {
1427 		WARN("%s: buffer pair not registered.\n", __func__);
1428 		ret = FFA_ERROR_INVALID_PARAMETER;
1429 		goto err_unlock_mailbox;
1430 	}
1431 
1432 	if (mbox->state != MAILBOX_STATE_EMPTY) {
1433 		WARN("%s: RX Buffer is full! %d\n", __func__, mbox->state);
1434 		ret = FFA_ERROR_DENIED;
1435 		goto err_unlock_mailbox;
1436 	}
1437 
1438 	if (fragment_length != total_length) {
1439 		WARN("%s: fragmented retrieve request not supported.\n",
1440 		     __func__);
1441 		ret = FFA_ERROR_INVALID_PARAMETER;
1442 		goto err_unlock_mailbox;
1443 	}
1444 
1445 	if (req->emad_count == 0U) {
1446 		WARN("%s: unsupported attribute desc count %u.\n",
1447 		     __func__, obj->desc.emad_count);
1448 		ret = FFA_ERROR_INVALID_PARAMETER;
1449 		goto err_unlock_mailbox;
1450 	}
1451 
1452 	/* Determine the appropriate minimum descriptor size. */
1453 	if (ffa_version == MAKE_FFA_VERSION(1, 0)) {
1454 		min_desc_size = sizeof(struct ffa_mtd_v1_0);
1455 	} else {
1456 		min_desc_size = sizeof(struct ffa_mtd);
1457 	}
1458 	if (total_length < min_desc_size) {
1459 		WARN("%s: invalid length %u < %zu\n", __func__, total_length,
1460 		     min_desc_size);
1461 		ret = FFA_ERROR_INVALID_PARAMETER;
1462 		goto err_unlock_mailbox;
1463 	}
1464 
1465 	spin_lock(&spmc_shmem_obj_state.lock);
1466 
1467 	obj = spmc_shmem_obj_lookup(&spmc_shmem_obj_state, req->handle);
1468 	if (obj == NULL) {
1469 		ret = FFA_ERROR_INVALID_PARAMETER;
1470 		goto err_unlock_all;
1471 	}
1472 
1473 	if (obj->desc_filled != obj->desc_size) {
1474 		WARN("%s: incomplete object desc filled %zu < size %zu\n",
1475 		     __func__, obj->desc_filled, obj->desc_size);
1476 		ret = FFA_ERROR_INVALID_PARAMETER;
1477 		goto err_unlock_all;
1478 	}
1479 
1480 	if (req->emad_count != 0U && req->sender_id != obj->desc.sender_id) {
1481 		WARN("%s: wrong sender id 0x%x != 0x%x\n",
1482 		     __func__, req->sender_id, obj->desc.sender_id);
1483 		ret = FFA_ERROR_INVALID_PARAMETER;
1484 		goto err_unlock_all;
1485 	}
1486 
1487 	if (req->emad_count != 0U && req->tag != obj->desc.tag) {
1488 		WARN("%s: wrong tag 0x%lx != 0x%lx\n",
1489 		     __func__, req->tag, obj->desc.tag);
1490 		ret = FFA_ERROR_INVALID_PARAMETER;
1491 		goto err_unlock_all;
1492 	}
1493 
1494 	if (req->emad_count != 0U && req->emad_count != obj->desc.emad_count) {
1495 		WARN("%s: mistmatch of endpoint counts %u != %u\n",
1496 		     __func__, req->emad_count, obj->desc.emad_count);
1497 		ret = FFA_ERROR_INVALID_PARAMETER;
1498 		goto err_unlock_all;
1499 	}
1500 
1501 	/* Ensure the NS bit is set to 0 in the request. */
1502 	if ((req->memory_region_attributes & FFA_MEM_ATTR_NS_BIT) != 0U) {
1503 		WARN("%s: NS mem attributes flags MBZ.\n", __func__);
1504 		ret = FFA_ERROR_INVALID_PARAMETER;
1505 		goto err_unlock_all;
1506 	}
1507 
1508 	if (req->flags != 0U) {
1509 		if ((req->flags & FFA_MTD_FLAG_TYPE_MASK) !=
1510 		    (obj->desc.flags & FFA_MTD_FLAG_TYPE_MASK)) {
1511 			/*
1512 			 * If the retrieve request specifies the memory
1513 			 * transaction ensure it matches what we expect.
1514 			 */
1515 			WARN("%s: wrong mem transaction flags %x != %x\n",
1516 			__func__, req->flags, obj->desc.flags);
1517 			ret = FFA_ERROR_INVALID_PARAMETER;
1518 			goto err_unlock_all;
1519 		}
1520 
1521 		if (req->flags != FFA_MTD_FLAG_TYPE_SHARE_MEMORY &&
1522 		    req->flags != FFA_MTD_FLAG_TYPE_LEND_MEMORY) {
1523 			/*
1524 			 * Current implementation does not support donate and
1525 			 * it supports no other flags.
1526 			 */
1527 			WARN("%s: invalid flags 0x%x\n", __func__, req->flags);
1528 			ret = FFA_ERROR_INVALID_PARAMETER;
1529 			goto err_unlock_all;
1530 		}
1531 	}
1532 
1533 	/* Validate the caller is a valid participant. */
1534 	if (!spmc_shmem_obj_validate_id(obj, sp_ctx->sp_id)) {
1535 		WARN("%s: Invalid endpoint ID (0x%x).\n",
1536 			__func__, sp_ctx->sp_id);
1537 		ret = FFA_ERROR_INVALID_PARAMETER;
1538 		goto err_unlock_all;
1539 	}
1540 
1541 	/* Validate that the provided emad offset and structure is valid.*/
1542 	for (size_t i = 0; i < req->emad_count; i++) {
1543 		size_t emad_size;
1544 		struct ffa_emad_v1_0 *emad;
1545 
1546 		emad = spmc_shmem_obj_get_emad(req, i, ffa_version,
1547 					       &emad_size);
1548 
1549 		if ((uintptr_t) emad >= (uintptr_t)
1550 					((uint8_t *) req + total_length)) {
1551 			WARN("Invalid emad access.\n");
1552 			ret = FFA_ERROR_INVALID_PARAMETER;
1553 			goto err_unlock_all;
1554 		}
1555 	}
1556 
1557 	/*
1558 	 * Validate all the endpoints match in the case of multiple
1559 	 * borrowers. We don't mandate that the order of the borrowers
1560 	 * must match in the descriptors therefore check to see if the
1561 	 * endpoints match in any order.
1562 	 */
1563 	for (size_t i = 0; i < req->emad_count; i++) {
1564 		bool found = false;
1565 		size_t emad_size;
1566 		struct ffa_emad_v1_0 *emad;
1567 		struct ffa_emad_v1_0 *other_emad;
1568 
1569 		emad = spmc_shmem_obj_get_emad(req, i, ffa_version,
1570 					       &emad_size);
1571 
1572 		for (size_t j = 0; j < obj->desc.emad_count; j++) {
1573 			other_emad = spmc_shmem_obj_get_emad(
1574 					&obj->desc, j, MAKE_FFA_VERSION(1, 1),
1575 					&emad_size);
1576 
1577 			if (req->emad_count &&
1578 			    emad->mapd.endpoint_id ==
1579 			    other_emad->mapd.endpoint_id) {
1580 				found = true;
1581 				break;
1582 			}
1583 		}
1584 
1585 		if (!found) {
1586 			WARN("%s: invalid receiver id (0x%x).\n",
1587 			     __func__, emad->mapd.endpoint_id);
1588 			ret = FFA_ERROR_INVALID_PARAMETER;
1589 			goto err_unlock_all;
1590 		}
1591 	}
1592 
1593 	mbox->state = MAILBOX_STATE_FULL;
1594 
1595 	if (req->emad_count != 0U) {
1596 		obj->in_use++;
1597 	}
1598 
1599 	/*
1600 	 * If the caller is v1.0 convert the descriptor, otherwise copy
1601 	 * directly.
1602 	 */
1603 	if (ffa_version == MAKE_FFA_VERSION(1, 0)) {
1604 		ret = spmc_populate_ffa_v1_0_descriptor(resp, obj, buf_size, 0,
1605 							&copy_size,
1606 							&out_desc_size);
1607 		if (ret != 0U) {
1608 			ERROR("%s: Failed to process descriptor.\n", __func__);
1609 			goto err_unlock_all;
1610 		}
1611 	} else {
1612 		copy_size = MIN(obj->desc_size, buf_size);
1613 		out_desc_size = obj->desc_size;
1614 
1615 		memcpy(resp, &obj->desc, copy_size);
1616 	}
1617 
1618 	/* Set the NS bit in the response if applicable. */
1619 	spmc_ffa_mem_retrieve_set_ns_bit(resp, sp_ctx);
1620 
1621 	spin_unlock(&spmc_shmem_obj_state.lock);
1622 	spin_unlock(&mbox->lock);
1623 
1624 	SMC_RET8(handle, FFA_MEM_RETRIEVE_RESP, out_desc_size,
1625 		 copy_size, 0, 0, 0, 0, 0);
1626 
1627 err_unlock_all:
1628 	spin_unlock(&spmc_shmem_obj_state.lock);
1629 err_unlock_mailbox:
1630 	spin_unlock(&mbox->lock);
1631 	return spmc_ffa_error_return(handle, ret);
1632 }
1633 
1634 /**
1635  * spmc_ffa_mem_frag_rx - FFA_MEM_FRAG_RX implementation.
1636  * @client:             Client state.
1637  * @handle_low:         Handle passed to &FFA_MEM_RETRIEVE_REQ. Bit[31:0].
1638  * @handle_high:        Handle passed to &FFA_MEM_RETRIEVE_REQ. Bit[63:32].
1639  * @fragment_offset:    Byte offset in descriptor to resume at.
1640  * @sender_id:          Bit[31:16]: Endpoint id of sender if client is a
1641  *                      hypervisor. 0 otherwise.
1642  * @smc_handle:         Handle passed to smc call. Used to return
1643  *                      FFA_MEM_FRAG_TX.
1644  *
1645  * Return: @smc_handle on success, error code on failure.
1646  */
1647 long spmc_ffa_mem_frag_rx(uint32_t smc_fid,
1648 			  bool secure_origin,
1649 			  uint32_t handle_low,
1650 			  uint32_t handle_high,
1651 			  uint32_t fragment_offset,
1652 			  uint32_t sender_id,
1653 			  void *cookie,
1654 			  void *handle,
1655 			  uint64_t flags)
1656 {
1657 	int ret;
1658 	void *src;
1659 	size_t buf_size;
1660 	size_t copy_size;
1661 	size_t full_copy_size;
1662 	uint32_t desc_sender_id;
1663 	struct mailbox *mbox = spmc_get_mbox_desc(secure_origin);
1664 	uint64_t mem_handle = handle_low | (((uint64_t)handle_high) << 32);
1665 	struct spmc_shmem_obj *obj;
1666 	uint32_t ffa_version = get_partition_ffa_version(secure_origin);
1667 
1668 	if (!secure_origin) {
1669 		WARN("%s: can only be called from swld.\n",
1670 		     __func__);
1671 		return spmc_ffa_error_return(handle,
1672 					     FFA_ERROR_INVALID_PARAMETER);
1673 	}
1674 
1675 	spin_lock(&spmc_shmem_obj_state.lock);
1676 
1677 	obj = spmc_shmem_obj_lookup(&spmc_shmem_obj_state, mem_handle);
1678 	if (obj == NULL) {
1679 		WARN("%s: invalid handle, 0x%lx, not a valid handle.\n",
1680 		     __func__, mem_handle);
1681 		ret = FFA_ERROR_INVALID_PARAMETER;
1682 		goto err_unlock_shmem;
1683 	}
1684 
1685 	desc_sender_id = (uint32_t)obj->desc.sender_id << 16;
1686 	if (sender_id != 0U && sender_id != desc_sender_id) {
1687 		WARN("%s: invalid sender_id 0x%x != 0x%x\n", __func__,
1688 		     sender_id, desc_sender_id);
1689 		ret = FFA_ERROR_INVALID_PARAMETER;
1690 		goto err_unlock_shmem;
1691 	}
1692 
1693 	if (fragment_offset >= obj->desc_size) {
1694 		WARN("%s: invalid fragment_offset 0x%x >= 0x%zx\n",
1695 		     __func__, fragment_offset, obj->desc_size);
1696 		ret = FFA_ERROR_INVALID_PARAMETER;
1697 		goto err_unlock_shmem;
1698 	}
1699 
1700 	spin_lock(&mbox->lock);
1701 
1702 	if (mbox->rxtx_page_count == 0U) {
1703 		WARN("%s: buffer pair not registered.\n", __func__);
1704 		ret = FFA_ERROR_INVALID_PARAMETER;
1705 		goto err_unlock_all;
1706 	}
1707 
1708 	if (mbox->state != MAILBOX_STATE_EMPTY) {
1709 		WARN("%s: RX Buffer is full!\n", __func__);
1710 		ret = FFA_ERROR_DENIED;
1711 		goto err_unlock_all;
1712 	}
1713 
1714 	buf_size = mbox->rxtx_page_count * FFA_PAGE_SIZE;
1715 
1716 	mbox->state = MAILBOX_STATE_FULL;
1717 
1718 	/*
1719 	 * If the caller is v1.0 convert the descriptor, otherwise copy
1720 	 * directly.
1721 	 */
1722 	if (ffa_version == MAKE_FFA_VERSION(1, 0)) {
1723 		size_t out_desc_size;
1724 
1725 		ret = spmc_populate_ffa_v1_0_descriptor(mbox->rx_buffer, obj,
1726 							buf_size,
1727 							fragment_offset,
1728 							&copy_size,
1729 							&out_desc_size);
1730 		if (ret != 0U) {
1731 			ERROR("%s: Failed to process descriptor.\n", __func__);
1732 			goto err_unlock_all;
1733 		}
1734 	} else {
1735 		full_copy_size = obj->desc_size - fragment_offset;
1736 		copy_size = MIN(full_copy_size, buf_size);
1737 
1738 		src = &obj->desc;
1739 
1740 		memcpy(mbox->rx_buffer, src + fragment_offset, copy_size);
1741 	}
1742 
1743 	spin_unlock(&mbox->lock);
1744 	spin_unlock(&spmc_shmem_obj_state.lock);
1745 
1746 	SMC_RET8(handle, FFA_MEM_FRAG_TX, handle_low, handle_high,
1747 		 copy_size, sender_id, 0, 0, 0);
1748 
1749 err_unlock_all:
1750 	spin_unlock(&mbox->lock);
1751 err_unlock_shmem:
1752 	spin_unlock(&spmc_shmem_obj_state.lock);
1753 	return spmc_ffa_error_return(handle, ret);
1754 }
1755 
1756 /**
1757  * spmc_ffa_mem_relinquish - FFA_MEM_RELINQUISH implementation.
1758  * @client:             Client state.
1759  *
1760  * Implements a subset of the FF-A FFA_MEM_RELINQUISH call.
1761  * Used by secure os release previously shared memory to non-secure os.
1762  *
1763  * The handle to release must be in the client's (secure os's) transmit buffer.
1764  *
1765  * Return: 0 on success, error code on failure.
1766  */
1767 int spmc_ffa_mem_relinquish(uint32_t smc_fid,
1768 			    bool secure_origin,
1769 			    uint32_t handle_low,
1770 			    uint32_t handle_high,
1771 			    uint32_t fragment_offset,
1772 			    uint32_t sender_id,
1773 			    void *cookie,
1774 			    void *handle,
1775 			    uint64_t flags)
1776 {
1777 	int ret;
1778 	struct mailbox *mbox = spmc_get_mbox_desc(secure_origin);
1779 	struct spmc_shmem_obj *obj;
1780 	const struct ffa_mem_relinquish_descriptor *req;
1781 	struct secure_partition_desc *sp_ctx = spmc_get_current_sp_ctx();
1782 
1783 	if (!secure_origin) {
1784 		WARN("%s: unsupported relinquish direction.\n", __func__);
1785 		return spmc_ffa_error_return(handle,
1786 					     FFA_ERROR_INVALID_PARAMETER);
1787 	}
1788 
1789 	spin_lock(&mbox->lock);
1790 
1791 	if (mbox->rxtx_page_count == 0U) {
1792 		WARN("%s: buffer pair not registered.\n", __func__);
1793 		ret = FFA_ERROR_INVALID_PARAMETER;
1794 		goto err_unlock_mailbox;
1795 	}
1796 
1797 	req = mbox->tx_buffer;
1798 
1799 	if (req->flags != 0U) {
1800 		WARN("%s: unsupported flags 0x%x\n", __func__, req->flags);
1801 		ret = FFA_ERROR_INVALID_PARAMETER;
1802 		goto err_unlock_mailbox;
1803 	}
1804 
1805 	if (req->endpoint_count == 0) {
1806 		WARN("%s: endpoint count cannot be 0.\n", __func__);
1807 		ret = FFA_ERROR_INVALID_PARAMETER;
1808 		goto err_unlock_mailbox;
1809 	}
1810 
1811 	spin_lock(&spmc_shmem_obj_state.lock);
1812 
1813 	obj = spmc_shmem_obj_lookup(&spmc_shmem_obj_state, req->handle);
1814 	if (obj == NULL) {
1815 		ret = FFA_ERROR_INVALID_PARAMETER;
1816 		goto err_unlock_all;
1817 	}
1818 
1819 	/*
1820 	 * Validate the endpoint ID was populated correctly. We don't currently
1821 	 * support proxy endpoints so the endpoint count should always be 1.
1822 	 */
1823 	if (req->endpoint_count != 1U) {
1824 		WARN("%s: unsupported endpoint count %u != 1\n", __func__,
1825 		     req->endpoint_count);
1826 		ret = FFA_ERROR_INVALID_PARAMETER;
1827 		goto err_unlock_all;
1828 	}
1829 
1830 	/* Validate provided endpoint ID matches the partition ID. */
1831 	if (req->endpoint_array[0] != sp_ctx->sp_id) {
1832 		WARN("%s: invalid endpoint ID %u != %u\n", __func__,
1833 		     req->endpoint_array[0], sp_ctx->sp_id);
1834 		ret = FFA_ERROR_INVALID_PARAMETER;
1835 		goto err_unlock_all;
1836 	}
1837 
1838 	/* Validate the caller is a valid participant. */
1839 	if (!spmc_shmem_obj_validate_id(obj, sp_ctx->sp_id)) {
1840 		WARN("%s: Invalid endpoint ID (0x%x).\n",
1841 			__func__, req->endpoint_array[0]);
1842 		ret = FFA_ERROR_INVALID_PARAMETER;
1843 		goto err_unlock_all;
1844 	}
1845 
1846 	if (obj->in_use == 0U) {
1847 		ret = FFA_ERROR_INVALID_PARAMETER;
1848 		goto err_unlock_all;
1849 	}
1850 	obj->in_use--;
1851 
1852 	spin_unlock(&spmc_shmem_obj_state.lock);
1853 	spin_unlock(&mbox->lock);
1854 
1855 	SMC_RET1(handle, FFA_SUCCESS_SMC32);
1856 
1857 err_unlock_all:
1858 	spin_unlock(&spmc_shmem_obj_state.lock);
1859 err_unlock_mailbox:
1860 	spin_unlock(&mbox->lock);
1861 	return spmc_ffa_error_return(handle, ret);
1862 }
1863 
1864 /**
1865  * spmc_ffa_mem_reclaim - FFA_MEM_RECLAIM implementation.
1866  * @client:         Client state.
1867  * @handle_low:     Unique handle of shared memory object to reclaim. Bit[31:0].
1868  * @handle_high:    Unique handle of shared memory object to reclaim.
1869  *                  Bit[63:32].
1870  * @flags:          Unsupported, ignored.
1871  *
1872  * Implements a subset of the FF-A FFA_MEM_RECLAIM call.
1873  * Used by non-secure os reclaim memory previously shared with secure os.
1874  *
1875  * Return: 0 on success, error code on failure.
1876  */
1877 int spmc_ffa_mem_reclaim(uint32_t smc_fid,
1878 			 bool secure_origin,
1879 			 uint32_t handle_low,
1880 			 uint32_t handle_high,
1881 			 uint32_t mem_flags,
1882 			 uint64_t x4,
1883 			 void *cookie,
1884 			 void *handle,
1885 			 uint64_t flags)
1886 {
1887 	int ret;
1888 	struct spmc_shmem_obj *obj;
1889 	uint64_t mem_handle = handle_low | (((uint64_t)handle_high) << 32);
1890 
1891 	if (secure_origin) {
1892 		WARN("%s: unsupported reclaim direction.\n", __func__);
1893 		return spmc_ffa_error_return(handle,
1894 					     FFA_ERROR_INVALID_PARAMETER);
1895 	}
1896 
1897 	if (mem_flags != 0U) {
1898 		WARN("%s: unsupported flags 0x%x\n", __func__, mem_flags);
1899 		return spmc_ffa_error_return(handle,
1900 					     FFA_ERROR_INVALID_PARAMETER);
1901 	}
1902 
1903 	spin_lock(&spmc_shmem_obj_state.lock);
1904 
1905 	obj = spmc_shmem_obj_lookup(&spmc_shmem_obj_state, mem_handle);
1906 	if (obj == NULL) {
1907 		ret = FFA_ERROR_INVALID_PARAMETER;
1908 		goto err_unlock;
1909 	}
1910 	if (obj->in_use != 0U) {
1911 		ret = FFA_ERROR_DENIED;
1912 		goto err_unlock;
1913 	}
1914 
1915 	if (obj->desc_filled != obj->desc_size) {
1916 		WARN("%s: incomplete object desc filled %zu < size %zu\n",
1917 		     __func__, obj->desc_filled, obj->desc_size);
1918 		ret = FFA_ERROR_INVALID_PARAMETER;
1919 		goto err_unlock;
1920 	}
1921 
1922 	/* Allow for platform specific operations to be performed. */
1923 	ret = plat_spmc_shmem_reclaim(&obj->desc);
1924 	if (ret != 0) {
1925 		goto err_unlock;
1926 	}
1927 
1928 	spmc_shmem_obj_free(&spmc_shmem_obj_state, obj);
1929 	spin_unlock(&spmc_shmem_obj_state.lock);
1930 
1931 	SMC_RET1(handle, FFA_SUCCESS_SMC32);
1932 
1933 err_unlock:
1934 	spin_unlock(&spmc_shmem_obj_state.lock);
1935 	return spmc_ffa_error_return(handle, ret);
1936 }
1937